Build an AI Fashion Assistant in Django – Full Tutorial (w/ Videos)
The fashion industry is constantly evolving, and staying ahead of the curve requires innovative solutions. Artificial intelligence (AI) offers incredible opportunities to revolutionize how we shop, style outfits, and manage our wardrobes. In this comprehensive tutorial, we’ll guide you through building an AI-powered fashion assistant using Django, a powerful Python web framework. This assistant will leverage AI to provide personalized recommendations, style advice, and more. We’ll break down the process into manageable steps, complete with code examples and video demonstrations.
Table of Contents
- Introduction: The Future of Fashion and AI
- Prerequisites: Setting Up Your Development Environment
- Project Setup: Creating a Django Project
- Model Creation: Designing the Database Schema
- Data Ingestion: Populating the Database with Fashion Data
- AI Integration: Choosing and Implementing an AI Model
- Building the Recommendation Engine
- User Interface: Designing the Frontend with HTML, CSS, and JavaScript
- Deployment: Making Your Fashion Assistant Live
- Advanced Features: Enhancing Your AI Assistant
- Conclusion: The Power of AI in Fashion
1. Introduction: The Future of Fashion and AI
The intersection of fashion and AI is creating exciting new possibilities. Imagine a world where:
- AI analyzes your existing wardrobe and suggests outfits you haven’t thought of.
- A virtual stylist provides personalized recommendations based on your body type and preferences.
- You can virtually try on clothes before buying them online, ensuring a perfect fit.
This tutorial aims to give you the foundational knowledge to build such an AI-powered fashion assistant. We’ll focus on:
- Personalized Recommendations: Suggesting clothing items based on user preferences, style, and past purchases.
- Style Advice: Providing tips on how to coordinate outfits and stay up-to-date with trends.
- Visual Search: Allowing users to upload images of clothing and find similar items online.
By the end of this tutorial, you’ll have a working AI fashion assistant that you can customize and expand upon.
2. Prerequisites: Setting Up Your Development Environment
Before we dive into the code, let’s ensure you have the necessary tools installed:
- Python: You’ll need Python 3.6 or higher. Download the latest version from the official Python website (python.org/downloads/).
- pip: Python’s package installer, which typically comes bundled with Python. Verify it’s installed by running `pip –version` in your terminal.
- Virtual Environment (venv): Highly recommended to isolate project dependencies. Create one using:
python3 -m venv venv
Activate it:- Linux/macOS:
source venv/bin/activate
- Windows:
venv\Scripts\activate
- Linux/macOS:
- Django: Install Django within your activated virtual environment:
pip install Django
- Text Editor/IDE: Choose a text editor or Integrated Development Environment (IDE) like VS Code, PyCharm, or Sublime Text. VS Code is highly recommended for its Python support.
Video Demonstration: (Insert Link to a video demonstrating the environment setup here)
3. Project Setup: Creating a Django Project
Now that we have our environment ready, let’s create a new Django project:
- Create a project directory: Choose a location on your computer and create a new folder for your project (e.g., `ai_fashion_assistant`).
- Navigate to the directory in your terminal:
cd ai_fashion_assistant
- Create a Django project: Use the `django-admin` command:
django-admin startproject fashion_assistant_project .
(The dot at the end ensures the project files are created in the current directory) - Create a Django app: Inside the project directory, run:
python manage.py startapp fashion_app
- Register the app: Add `’fashion_app’` to the `INSTALLED_APPS` list in `fashion_assistant_project/settings.py`.
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'fashion_app', # Our fashion app ]
- Run migrations: This command creates the initial database tables.
python manage.py migrate
- Create a superuser: This allows you to access the Django admin panel.
python manage.py createsuperuser
Follow the prompts to create a username, email, and password. - Run the development server:
python manage.py runserver
- Access the Django admin panel: Open your web browser and navigate to `http://127.0.0.1:8000/admin/`. Log in with the superuser credentials you just created.
Explanation:
- `django-admin startproject` creates the basic project structure.
- `python manage.py startapp` creates a Django app, which is a modular component of your project. We’ll organize our fashion-related functionality within the `fashion_app`.
- `INSTALLED_APPS` tells Django which apps to include in the project.
- `python manage.py migrate` synchronizes your database schema with the models defined in your apps.
- `python manage.py createsuperuser` creates an administrator account for managing your website through the admin panel.
- `python manage.py runserver` starts the development server, allowing you to view your website in your browser.
Video Demonstration: (Insert Link to a video demonstrating the project setup here)
4. Model Creation: Designing the Database Schema
Now, let’s define the database models for our fashion app. We’ll need models to represent clothing items, users, and perhaps categories.
Open `fashion_app/models.py` and add the following models:
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class ClothingItem(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='clothing_images/') # Store images in media/clothing_images/
category = models.ForeignKey(Category, on_delete=models.CASCADE)
available_sizes = models.CharField(max_length=50, blank=True, null=True) # e.g., "S, M, L, XL"
color = models.CharField(max_length=50, blank=True, null=True)
style = models.CharField(max_length=100, blank=True, null=True) # e.g., "Casual", "Formal", "Bohemian"
brand = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.name
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
style_preferences = models.TextField(blank=True, null=True) # Store preferences as text, maybe JSON
preferred_sizes = models.CharField(max_length=50, blank=True, null=True)
def __str__(self):
return self.user.username
Explanation:
- Category: Represents categories of clothing items (e.g., “Shirts”, “Pants”, “Dresses”).
- ClothingItem: Represents a single clothing item with attributes like name, description, price, image, category, available sizes, color, style, and brand.
- UserProfile: Extends the built-in Django `User` model to store user-specific information like style preferences and preferred sizes. We use a `OneToOneField` to link each user to their profile.
- `upload_to=’clothing_images/’` specifies where uploaded images will be stored within your media directory. You’ll need to configure your `settings.py` file to handle media files (see below).
Configuration: `settings.py` (for Media Files)
Add the following lines to your `fashion_assistant_project/settings.py` file:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Then, in your `fashion_assistant_project/urls.py` file, add the following lines to serve media files during development:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... your other URL patterns ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Now, run migrations to create the tables in your database:
python manage.py makemigrations fashion_app
python manage.py migrate
You should now see the models in the Django admin panel.
Video Demonstration: (Insert Link to a video demonstrating the model creation here)
5. Data Ingestion: Populating the Database with Fashion Data
Now that our models are defined, we need to populate the database with some initial data. We can do this through the Django admin panel, or by creating custom data import scripts.
Option 1: Using the Django Admin Panel
- Log in to the Django admin panel (http://127.0.0.1:8000/admin/).
- Click on the “Categories” link under the “Fashion app” section.
- Add some categories like “Shirts”, “Pants”, “Dresses”, “Shoes”, etc.
- Click on the “Clothing items” link.
- Add clothing items, filling in the fields for each item (name, description, price, image, category, etc.). You’ll need to upload images for each item.
- For user profiles, first create a new user. Then create a UserProfile and assign it to that user.
Option 2: Creating a Data Import Script
This is a more efficient way to import large amounts of data. Let’s create a script to import data from a CSV file.
- Create a CSV file: Create a CSV file (e.g., `fashion_data.csv`) with the following columns (matching your model fields): `name,description,price,image,category,available_sizes,color,style,brand`. Populate the file with sample data. For the `image` column, you can simply put the filename of an image that you will place in the `media/clothing_images` directory. The `category` column should contain the *name* of the category.
- Create a data import script: Create a new file in your `fashion_app` directory (e.g., `import_data.py`) with the following code:
import csv import os import django # Set up Django environment (if not already set) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fashion_assistant_project.settings') django.setup() from fashion_app.models import ClothingItem, Category def import_clothing_data(csv_file): with open(csv_file, 'r', encoding='utf-8') as file: reader = csv.DictReader(file) for row in reader: # Get or create the category category_name = row.get('category') category, created = Category.objects.get_or_create(name=category_name) # Create the clothing item ClothingItem.objects.create( name=row.get('name'), description=row.get('description'), price=row.get('price'), image=row.get('image'), # Assuming image file is already in media/clothing_images category=category, available_sizes=row.get('available_sizes'), color=row.get('color'), style=row.get('style'), brand=row.get('brand'), ) print("Data import complete!") if __name__ == "__main__": #Put your CSV file name here csv_file_path = 'fashion_app/fashion_data.csv' import_clothing_data(csv_file_path)
- Run the script: In your terminal, run:
python fashion_app/import_data.py
Important Considerations:
- Image Handling: Make sure the images referenced in your CSV file are placed in the `media/clothing_images/` directory. The script assumes the image files already exist in the correct location.
- Error Handling: The script above doesn’t include robust error handling. In a production environment, you should add error handling to catch potential exceptions (e.g., invalid data types, missing files).
- Large Datasets: For very large datasets, consider using Django’s bulk_create method for better performance.
Video Demonstration: (Insert Link to a video demonstrating the data ingestion here)
6. AI Integration: Choosing and Implementing an AI Model
This is where the “AI” in our AI Fashion Assistant comes to life! We’ll integrate an AI model to provide personalized recommendations. There are several approaches we can take, depending on the complexity we desire. Here are a few options:
Option 1: Rule-Based Recommendations (Simple)
This is the simplest approach, involving defining rules based on user preferences and clothing attributes. While not “true” AI, it can provide basic recommendations.
def get_recommendations_rule_based(user_profile, clothing_items):
"""
Returns a list of clothing items that match the user's style preferences
and preferred sizes.
"""
recommendations = []
for item in clothing_items:
if user_profile.style_preferences in item.style and user_profile.preferred_sizes in item.available_sizes:
recommendations.append(item)
return recommendations
Option 2: Content-Based Filtering (Intermediate)
This approach uses item descriptions and user profiles to find similar items. We’ll use TF-IDF (Term Frequency-Inverse Document Frequency) to vectorize the text data and calculate cosine similarity.
- Install Scikit-learn:
pip install scikit-learn
- Implement Content-Based Filtering:
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity def get_recommendations_content_based(user_profile, clothing_items, num_recommendations=5): """ Returns a list of clothing items similar to the user's style preferences, using content-based filtering. """ # Combine user style preferences and item descriptions into a single corpus corpus = [user_profile.style_preferences] + [item.description for item in clothing_items] # Vectorize the corpus using TF-IDF vectorizer = TfidfVectorizer() tfidf_matrix = vectorizer.fit_transform(corpus) # Calculate cosine similarity between the user profile and all clothing items cosine_similarities = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:]) # Get the indices of the most similar items similar_indices = cosine_similarities.argsort()[0][::-1] # Return the top N most similar items recommendations = [clothing_items[i] for i in similar_indices[:num_recommendations]] return recommendations
Option 3: Collaborative Filtering (Advanced)
This approach requires user interaction data (e.g., ratings, purchase history) to find items that similar users have liked. This is more complex and requires more data.
For collaborative filtering, you’d typically use libraries like Surprise or implicit. This requires you to store user interactions (e.g., likes, purchases) in the database.
Example using Surprise (Conceptual – requires more setup):
# This is a highly simplified and conceptual example. Implementing
# collaborative filtering requires significantly more code and data.
# You'll need to install the Surprise library: pip install scikit-surprise
from surprise import Dataset, Reader, SVD
from surprise.model_selection import train_test_split
def get_recommendations_collaborative(user_id, clothing_items, ratings):
"""
Returns a list of clothing items recommended using collaborative filtering.
ratings should be a list of tuples: (user_id, item_id, rating)
"""
# Define a reader to parse the ratings data
reader = Reader(rating_scale=(1, 5)) # Assuming ratings are 1-5
# Load the data into a Surprise Dataset object
data = Dataset.load_from_df(ratings,reader)
# Split the data into training and testing sets
trainset, testset = train_test_split(data, test_size=.25)
# Choose an algorithm (e.g., SVD)
algo = SVD()
# Train the algorithm
algo.fit(trainset)
# Make predictions for the user on all clothing items
predictions = [algo.predict(user_id, item.id) for item in clothing_items] # Assumes ClothingItem has an 'id'
# Sort the predictions by estimated rating
predictions.sort(key=lambda x: x.est, reverse=True)
# Return the top N recommended items
recommendations = [item for item in clothing_items if item.id == predictions[0].iid]
return recommendations
Choosing the Right Approach:
- Rule-based: Good for simple recommendations with limited data. Easy to implement but less personalized.
- Content-based: Good when you have item descriptions and user profiles. Provides personalized recommendations based on content similarity.
- Collaborative filtering: Good when you have user interaction data. Provides the most personalized recommendations but requires a significant amount of data and more complex implementation.
For this tutorial, we’ll focus on Content-Based Filtering as it offers a good balance between simplicity and personalization.
Video Demonstration: (Insert Link to a video demonstrating the AI integration here, focusing on Content-Based Filtering)
7. Building the Recommendation Engine
Now that we have our AI model, let’s integrate it into our Django application. We’ll create a view that takes a user profile as input and returns a list of recommended clothing items.
- Create a `recommendations` view in `fashion_app/views.py`:
from django.shortcuts import render from .models import ClothingItem, UserProfile from .ai_models import get_recommendations_content_based # Import your AI model def recommendations(request): user = request.user # Get the current user try: user_profile = UserProfile.objects.get(user=user) #Get the User Profile if it exists. except UserProfile.DoesNotExist: user_profile = None if user_profile: clothing_items = ClothingItem.objects.all() recommendations = get_recommendations_content_based(user_profile, clothing_items) else: recommendations = [] #Handle the case if UserProfile is not set return render(request, 'fashion_app/recommendations.html', {'recommendations': recommendations})
- Create a URL pattern for the view in `fashion_app/urls.py` (create this file if it doesn’t exist):
from django.urls import path from . import views urlpatterns = [ path('recommendations/', views.recommendations, name='recommendations'), ]
Remember to include this `fashion_app/urls.py` in your main project `urls.py`
from django.urls import include, path urlpatterns = [ #other URLS path("fashion/", include("fashion_app.urls")), ]
- Create a template to display the recommendations (`fashion_app/templates/fashion_app/recommendations.html`):
<h1>Recommended Items</h1> <ul> {% for item in recommendations %} <li> <img src="{{ item.image.url }}" alt="{{ item.name }}" width="100"><br> <strong>{{ item.name }}</strong><br> {{ item.description }}<br> Price: ${{ item.price }} </li> {% empty %} <li>No recommendations found.</li> {% endfor %} </ul>
- Make sure the AI model file `fashion_app/ai_models.py` exists, containing the AI function: Create the file if you haven’t already done so, and place the Content-Based filtering code there.
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity def get_recommendations_content_based(user_profile, clothing_items, num_recommendations=5): """ Returns a list of clothing items similar to the user's style preferences, using content-based filtering. """ # Combine user style preferences and item descriptions into a single corpus corpus = [user_profile.style_preferences] + [item.description for item in clothing_items] # Vectorize the corpus using TF-IDF vectorizer = TfidfVectorizer() tfidf_matrix = vectorizer.fit_transform(corpus) # Calculate cosine similarity between the user profile and all clothing items cosine_similarities = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:]) # Get the indices of the most similar items similar_indices = cosine_similarities.argsort()[0][::-1] # Return the top N most similar items recommendations = [clothing_items[i] for i in similar_indices[:num_recommendations]] return recommendations
Now, when you navigate to `/fashion/recommendations/` (assuming you have a user logged in with a UserProfile set), you should see a list of recommended clothing items based on their style preferences.
Important: You will need to have a user logged in, and that user MUST have a `UserProfile` instance created and associated with them. Fill in some `style_preferences` for that user profile.
Video Demonstration: (Insert Link to a video demonstrating the recommendation engine implementation here)
8. User Interface: Designing the Frontend with HTML, CSS, and JavaScript
While our basic recommendation engine is functional, it’s not very user-friendly. Let’s improve the user interface with HTML, CSS, and JavaScript.
Improving the Recommendations Display
We can enhance the `recommendations.html` template to display clothing items in a more visually appealing way, and provide links to view details or purchase the items.
<h1>Recommended Items</h1>
<div class="recommendations-container">
{% for item in recommendations %}
<div class="recommendation-item">
<a href="#"><img src="{{ item.image.url }}" alt="{{ item.name }}" class="item-image"></a><br>
<strong>{{ item.name }}</strong><br>
<p class="item-description">{{ item.description|truncatewords:20 }}</p> <!-- Limit description length -->
<p>Price: ${{ item.price }}</p>
<a href="#" class="view-details-button">View Details</a> <!-- Replace # with actual URL -->
</div>
{% empty %}
<p>No recommendations found.</p>
{% endfor %}
</div>
CSS Styling (Create a `style.css` file in `fashion_app/static/fashion_app/`):
.recommendations-container {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
.recommendation-item {
width: 250px;
margin: 10px;
padding: 10px;
border: 1px solid #ccc;
text-align: center;
}
.item-image {
max-width: 100%;
height: auto;
}
.item-description {
margin-bottom: 10px;
}
.view-details-button {
background-color: #4CAF50;
color: white;
padding: 8px 12px;
text-decoration: none;
border-radius: 4px;
}
Link the CSS file in your `recommendations.html` template:
{% load static %} <!-- Load static files -->
<!DOCTYPE html>
<html>
<head>
<title>Recommended Items</title>
<link rel="stylesheet" href="{% static 'fashion_app/style.css' %}"> <!-- Link to your CSS file -->
</head>
<body>
<h1>Recommended Items</h1>
<div class="recommendations-container">
{% for item in recommendations %}
<div class="recommendation-item">
<a href="#"><img src="{{ item.image.url }}" alt="{{ item.name }}" class="item-image"></a><br>
<strong>{{ item.name }}</strong><br>
<p class="item-description">{{ item.description|truncatewords:20 }}</p>
<p>Price: ${{ item.price }}</p>
<a href="#" class="view-details-button">View Details</a>
</div>
{% empty %}
<p>No recommendations found.</p>
{% endfor %}
</div>
</body>
</html>
Collecting User Preferences
To make the recommendations more accurate, we need to collect user style preferences. Let’s create a form where users can specify their preferred styles and sizes.
- Create a form in `fashion_app/forms.py`:
from django import forms from .models import UserProfile class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['style_preferences', 'preferred_sizes'] # Include all fields from UserProfile you want to edit
- Create a view to handle the form in `fashion_app/views.py`:
from django.shortcuts import render, redirect from .forms import UserProfileForm from django.contrib.auth.decorators import login_required @login_required def update_profile(request): try: profile = UserProfile.objects.get(user=request.user) except UserProfile.DoesNotExist: profile = UserProfile(user=request.user) #create if it does not exist if request.method == 'POST': form = UserProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() return redirect('recommendations') # Redirect to recommendations after saving else: form = UserProfileForm(instance=profile) return render(request, 'fashion_app/update_profile.html', {'form': form})
- Create a URL pattern for the view in `fashion_app/urls.py`:
path('update_profile/', views.update_profile, name='update_profile'),
- Create a template for the form (`fashion_app/templates/fashion_app/update_profile.html`):
<h1>Update Your Profile</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <!-- Render the form as paragraphs --> <button type="submit">Save Profile</button> </form>
JavaScript Enhancements
While not essential for the basic functionality, JavaScript can be used to add features like:
- Dynamic Filtering: Allow users to filter recommendations based on category, size, or color.
- Image Zoom: Zoom in on clothing item images for a closer look.
- Interactive Style Quizzes: Gather user preferences through interactive quizzes.
Video Demonstration: (Insert Link to a video demonstrating the user interface improvements here, including CSS styling and the profile update form)
9. Deployment: Making Your Fashion Assistant Live
Once you’re happy with your AI fashion assistant, it’s time to deploy it to a live server. Here are some popular options:
- Heroku: A platform-as-a-service (PaaS) that’s easy to use and offers a free tier. Good for small projects and testing.
- PythonAnywhere: Another PaaS platform designed specifically for Python web applications. Offers free tier suitable for testing.
- DigitalOcean: A virtual private server (VPS) provider that gives you more control over your server environment. Requires more configuration but is more flexible.
- AWS (Amazon Web Services): A comprehensive cloud computing platform with a wide range of services. Suitable for large-scale applications.
- Google Cloud Platform (GCP): Similar to AWS, offering a wide range of cloud services.
General Deployment Steps (using Heroku as an example):
- Create a Heroku account and install the Heroku CLI.
- Create a `requirements.txt` file: This file lists all the Python packages required by your project. Generate it using:
pip freeze > requirements.txt
- Create a `Procfile`: This file tells Heroku how to run your application. Create a file named `Procfile` (without any extension) in the root directory of your project with the following content:
web