Style / rag.py
nexusbert's picture
initial commit
57117a0
from sentence_transformers import SentenceTransformer
import numpy as np
from typing import List, Tuple
import os
embedding_model = None
knowledge_base = []
knowledge_embeddings = None
def initialize_rag():
global embedding_model, knowledge_base, knowledge_embeddings
if embedding_model is not None:
return
print("Initializing RAG system...")
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
knowledge_base = build_fashion_knowledge_base()
print(f"Generating embeddings for {len(knowledge_base)} knowledge chunks...")
knowledge_embeddings = embedding_model.encode(
knowledge_base,
show_progress_bar=False,
convert_to_numpy=True
)
print("✓ RAG system initialized")
def build_fashion_knowledge_base() -> List[str]:
knowledge = []
knowledge.extend([
"Black is a versatile neutral that pairs well with white, beige, grey, navy, red, and blue. It creates strong contrast and works for both formal and casual occasions.",
"White is the most versatile color and pairs with almost any color. It works especially well with black, navy, grey, beige, and bold colors like red or blue.",
"Navy blue is a sophisticated color that pairs excellently with white, beige, khaki, grey, red, and yellow. It's more versatile than black for business settings.",
"Grey and gray are neutral colors that work with black, white, navy, beige, and blue. They provide a balanced, professional look.",
"Beige is a warm neutral that complements green, navy, brown, black, white, and blue. It adds warmth to outfits without being too bold.",
"Red is a bold color that pairs well with white, black, navy, blue, and beige. Use it as an accent or statement piece.",
"Brown works beautifully with beige, white, navy, green, and blue. It creates earthy, warm combinations perfect for autumn and winter.",
"Green pairs well with beige, white, grey, navy, black, and brown. It's versatile for both casual and professional settings.",
"Blue complements white, beige, khaki, grey, navy, and red. It's a classic color that works in many contexts.",
"Yellow is a vibrant color that pairs with navy, black, white, and grey. Use it sparingly as an accent color.",
"Pink works well with white, navy, grey, and black. It's feminine and can be dressed up or down.",
"Purple pairs with white, grey, black, and navy. It's a sophisticated color choice for special occasions.",
"Orange is bold and pairs best with navy, white, black, and beige. Use it as a statement piece.",
"Color harmony principles: Analogous colors (next to each other on color wheel) create harmonious looks. Complementary colors (opposites) create bold contrast. Neutral colors (black, white, grey, beige, navy) work with everything.",
])
knowledge.extend([
"For formal business settings, choose dark colors like navy, charcoal grey, or black. Pair with white or light-colored shirts. Add a blazer or suit jacket for authority.",
"Business professional attire: Dark suit (navy or charcoal), white or light blue dress shirt, leather dress shoes, and a tie. Keep accessories minimal and classic.",
"Business casual: Dark wash jeans or chinos, button-down shirt or polo, blazer optional, leather loafers or clean sneakers. Avoid overly distressed clothing.",
"For presentations and meetings, opt for navy or grey blazers with white or light blue shirts. This combination projects confidence and professionalism.",
"Project defense and academic presentations: Choose professional but approachable attire. A blazer with a simple shirt, dark jeans or trousers, and clean shoes work well.",
"Interview attire: Navy or charcoal suit, white dress shirt, conservative tie, polished dress shoes. Ensure everything is well-fitted and wrinkle-free.",
])
knowledge.extend([
"Casual weekend outfits: Pair jeans or chinos with t-shirts, hoodies, or casual shirts. Add sneakers or casual boots. Keep it comfortable and relaxed.",
"Streetwear style: Oversized hoodies, graphic tees, joggers or cargo pants, and statement sneakers. Mix bold colors and patterns for a modern look.",
"Smart casual: Chinos or dark jeans, button-down shirt or polo, casual blazer optional, clean sneakers or loafers. Balance comfort with style.",
"Casual blazer styling: Pair a blazer with a simple white t-shirt or graphic tee, dark jeans or chinos, and white sneakers or espadrilles. Add a crossbody bag and delicate accessories.",
"Hoodie combinations: Layer a hoodie under a denim or leather jacket. Pair with chinos or joggers and sneakers. Add a beanie for a streetwear vibe.",
])
knowledge.extend([
"For project defenses and presentations: Choose professional attire that's not too formal. A blazer with a simple shirt, dark jeans or trousers, and clean shoes. Colors like grey, navy, or white work well.",
"Date night outfits: Smart casual works best. Dark jeans or chinos, a well-fitted shirt or sweater, blazer optional, and clean shoes. Add a watch for sophistication.",
"Wedding attire: For guests, choose a suit or blazer with dress pants, dress shirt, and dress shoes. Avoid white (reserved for bride) and black (too formal for daytime). Navy, grey, or beige work well.",
"Party outfits: Express your style with bold colors, patterns, or statement pieces. Balance bold items with neutrals. Comfortable shoes are essential for dancing.",
"Workout and activewear: Choose moisture-wicking fabrics, supportive footwear, and comfortable fit. Function over fashion, but many brands offer stylish options.",
])
knowledge.extend([
"Spring fashion: Light colors, pastels, and breathable fabrics. Layer with light jackets or cardigans. White, beige, light blue, and soft pastels are popular.",
"Summer style: Lightweight fabrics, bright colors, and minimal layers. White, navy, and light colors keep you cool. Add sunglasses and hats for sun protection.",
"Autumn fashion: Rich colors like brown, burgundy, olive green, and navy. Layer with sweaters, cardigans, and light jackets. Boots and closed-toe shoes are appropriate.",
"Winter attire: Dark colors, warm fabrics like wool and cashmere, and proper layering. Black, navy, grey, and brown work well. Add coats, scarves, and boots.",
])
knowledge.extend([
"Blazer combinations: Pair with white t-shirt and jeans for casual chic, or with dress shirt and trousers for professional. Add loafers or sneakers depending on occasion.",
"White sneakers are versatile and pair with almost everything: jeans, chinos, dresses, and even suits for a modern twist. Keep them clean for best effect.",
"Jeans styling: Dark wash jeans are more versatile than light wash. Pair with t-shirts, button-downs, or sweaters. Add a blazer for smart casual.",
"Dress combinations: A simple dress can be dressed up with heels and a blazer, or down with sneakers and a denim jacket. Accessories change the formality level.",
"Sweater pairings: Layer sweaters over shirts for a preppy look, or wear alone with jeans or chinos. Cardigans work well over t-shirts or dresses.",
"Boots styling: Ankle boots work with jeans, dresses, and skirts. Knee-high boots pair with dresses and skirts. Keep the rest of the outfit balanced.",
])
knowledge.extend([
"Proper fit is essential: Clothes should fit well at shoulders, waist, and length. Avoid items that are too tight or too loose. Tailoring can make a big difference.",
"For a balanced silhouette: If wearing loose tops, pair with fitted bottoms. If wearing loose bottoms, pair with fitted tops. This creates visual balance.",
"Layering tips: Start with the thinnest layer closest to your body. Add progressively thicker layers. Ensure each layer is visible and contributes to the look.",
"Proportions matter: High-waisted pants elongate legs. Cropped jackets can make legs appear longer. Belt placement affects perceived waist position.",
])
knowledge.extend([
"Accessories complete an outfit: Watches, belts, bags, and jewelry add polish. Keep accessories proportional to your frame and appropriate for the occasion.",
"Bags and purses: Match the formality level. Structured bags for formal, casual crossbody or tote for everyday. Color should complement, not clash.",
"Belts: Match belt color to shoes for a cohesive look. Leather belts work with most outfits. Width should be proportional to your frame.",
"Watches: Classic watches work for most occasions. Sport watches are casual. Dress watches are for formal events. Match metal color to other accessories.",
"Jewelry: Delicate pieces for professional settings, bolder pieces for casual. Don't overdo it - choose one statement piece or a few complementary items.",
])
knowledge.extend([
"Color psychology: Blue conveys trust and professionalism. Black is powerful and sophisticated. White is clean and fresh. Red is bold and confident. Choose colors that match your message.",
"Neutral color palette: Black, white, grey, beige, and navy form a versatile neutral base. Add one or two accent colors for interest without overwhelming.",
"Monochromatic looks: Wearing different shades of the same color creates a sophisticated, cohesive look. Add texture variation for visual interest.",
"Bold color combinations: Pair one bold color with neutrals. For example, a red dress with black accessories, or a yellow top with navy pants.",
])
knowledge.extend([
"Timeless combinations: Navy and white, black and white, grey and navy, beige and brown. These combinations never go out of style.",
"Investment pieces: A well-fitted blazer, dark jeans, white sneakers, a classic watch, and a quality leather bag are versatile investments.",
"Quality over quantity: Fewer, well-made pieces create better outfits than many cheap items. Focus on fit, fabric quality, and versatility.",
"Personal style: While following guidelines, express your personality. Fashion rules are meant to be understood, then adapted to your style.",
])
knowledge.extend([
"White blouse combinations: Pairs with navy trousers, black pants, beige chinos, or jeans. Add a blazer in navy, black, or grey for professional look.",
"Navy blazer styling: Works with white shirts, beige chinos, grey trousers, or jeans. Versatile piece that elevates any outfit.",
"Black dress combinations: Add a colored blazer (navy, red, or beige), or keep it simple with black accessories. Works for many occasions.",
"Grey suit combinations: Pair with white, light blue, or pink shirts. Add a colored tie or pocket square for interest.",
"Beige trench coat: Classic piece that works over almost any outfit. Pairs with navy, black, white, and most colors.",
])
knowledge.extend([
"Sneakers: White sneakers are most versatile. They pair with jeans, chinos, dresses, and even suits for a modern look. Keep them clean.",
"Dress shoes: Leather oxfords or loafers for formal occasions. Match shoe color to belt. Black for formal, brown for business casual.",
"Boots: Ankle boots work with jeans and dresses. Chelsea boots are versatile for smart casual. Match boot style to outfit formality.",
"Heels: Nude heels elongate legs and work with most outfits. Black heels are classic. Match heel height to occasion and comfort level.",
])
return knowledge
def retrieve_relevant_context(query: str, top_k: int = 3) -> List[str]:
global embedding_model, knowledge_base, knowledge_embeddings
if embedding_model is None:
initialize_rag()
query_embedding = embedding_model.encode([query], convert_to_numpy=True)
similarities = np.dot(knowledge_embeddings, query_embedding.T).flatten()
top_indices = np.argsort(similarities)[::-1][:top_k]
relevant_chunks = [knowledge_base[idx] for idx in top_indices]
return relevant_chunks
def format_rag_context(relevant_chunks: List[str]) -> str:
if not relevant_chunks:
return ""
context = "Fashion Knowledge Base:\n"
for i, chunk in enumerate(relevant_chunks, 1):
context += f"{i}. {chunk}\n"
return context.strip()