Spaces:
Sleeping
Sleeping
File size: 10,533 Bytes
ea961f6 5fd310b ea961f6 e955397 ea961f6 e955397 ea961f6 e955397 ea961f6 e955397 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | """
FastAPI Server for Style Analysis
This server provides REST API endpoints for AI-powered style analysis
using Google's Gemini AI. It analyzes user-uploaded images for:
- Body type and features
- Body alignment and posture
- Skin tone and undertones
- Face shape
- Personalized style recommendations
"""
import os
import io
import base64
from datetime import datetime
from pathlib import Path
from typing import Optional
from fastapi import FastAPI, File, UploadFile, HTTPException, Form
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from PIL import Image
from dotenv import load_dotenv
from analyzer import StyleAnalyzer
# Load environment variables
env_path = Path(__file__).parent.parent / "opentryon" / ".env"
load_dotenv(env_path)
# Create output directory for saving analyzed images (optional)
OUTPUT_DIR = Path("outputs/style_analysis")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
app = FastAPI(
title="AI Style Analysis API",
description="AI-powered style analysis using Google Gemini for body type, skin tone, and fashion recommendations",
version="1.0.0"
)
# CORS middleware to allow requests from frontend
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:3000",
"http://127.0.0.1:3000",
"http://localhost:5173",
"http://127.0.0.1:5173",
"https://style-ai-virutal-stylish-and-trends.vercel.app"
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize analyzer
try:
analyzer = StyleAnalyzer()
analyzer_available = True
except Exception as e:
print(f"Warning: StyleAnalyzer initialization failed: {e}")
analyzer_available = False
@app.get("/")
async def root():
"""Root endpoint for health checks"""
return {"status": "running", "service": "style-analysis"}
@app.get("/health")
async def health():
"""Health check endpoint"""
return {
"status": "healthy",
"analyzer_available": analyzer_available
}
@app.post("/api/v1/analyze")
async def analyze_style(
image: UploadFile = File(..., description="User photo for style analysis"),
save_image: bool = Form(default=False, description="Save uploaded image to disk"),
detailed: bool = Form(default=True, description="Provide detailed analysis")
):
"""
Comprehensive style analysis of user image.
Analyzes:
- Body type (rectangle, triangle, inverted triangle, hourglass, oval)
- Body alignment and posture
- Skin tone (fair, light, medium, olive, tan, brown, deep)
- Skin undertones (cool, warm, neutral)
- Face shape (oval, round, square, heart, diamond, oblong)
- Personalized style recommendations
- Color palette suggestions
Args:
image: User photo file
save_image: Whether to save the uploaded image
detailed: Whether to provide detailed analysis and recommendations
Returns:
JSON response with comprehensive style analysis
"""
if not analyzer_available:
raise HTTPException(
status_code=503,
detail="Style analyzer is not available. Check Gemini API configuration."
)
try:
# Read image
image_bytes = await image.read()
pil_image = Image.open(io.BytesIO(image_bytes))
print(f"[DEBUG] Image loaded: {pil_image.size}, mode: {pil_image.mode}")
# Optionally save image
saved_path = None
if save_image:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
filename = f"analysis_{timestamp}.png"
filepath = OUTPUT_DIR / filename
# Save in RGB mode
if pil_image.mode != 'RGB':
pil_image = pil_image.convert('RGB')
pil_image.save(str(filepath), 'PNG')
saved_path = str(filepath)
print("[DEBUG] Starting analysis...")
# Perform analysis
result = analyzer.analyze_image(pil_image, detailed=detailed)
print(f"[DEBUG] Analysis result: success={result.get('success')}")
print(f"[DEBUG] Result keys: {list(result.keys())}")
if not result.get('success', False):
print(f"[ERROR] Analysis failed: {result.get('message', 'Unknown error')}")
raise HTTPException(
status_code=500,
detail=result.get('message', 'Analysis failed')
)
# Build response
response_data = {
"success": True,
"analysis": {
"body_type": result.get('body_type', ''),
"body_alignment": result.get('body_alignment', ''),
"skin_tone": result.get('skin_tone', ''),
"skin_undertone": result.get('skin_undertone', ''),
"face_shape": result.get('face_shape', ''),
"height_estimate": result.get('height_estimate', ''),
"style_recommendations": result.get('style_recommendations', []),
"outfit_suggestions": result.get('outfit_suggestions', []),
"color_palette": result.get('color_palette', {}),
"detailed_analysis": result.get('detailed_analysis', '')
},
"raw_analysis": result.get('raw_analysis', ''),
"image_info": {
"width": pil_image.width,
"height": pil_image.height,
"mode": pil_image.mode,
"format": pil_image.format or "Unknown"
}
}
if saved_path:
response_data["saved_path"] = saved_path
return JSONResponse(response_data)
except HTTPException:
raise
except Exception as e:
import traceback
error_details = f"Error analyzing image: {str(e)}\n{traceback.format_exc()}"
print(error_details)
raise HTTPException(
status_code=500,
detail=f"Error analyzing image: {str(e)}"
)
@app.post("/api/v1/analyze/tryon")
async def analyze_for_tryon(
image: UploadFile = File(..., description="User photo for virtual try-on analysis"),
save_image: bool = Form(default=False, description="Save uploaded image to disk")
):
"""
Analyze image for virtual try-on readiness.
Provides:
- Image quality assessment
- Pose quality for try-on
- Body type for garment fitting
- Garment fit recommendations
- Try-on readiness score (1-10)
- Improvement suggestions
Args:
image: User photo file
save_image: Whether to save the uploaded image
Returns:
JSON response with virtual try-on analysis
"""
if not analyzer_available:
raise HTTPException(
status_code=503,
detail="Style analyzer is not available. Check Gemini API configuration."
)
try:
# Read image
image_bytes = await image.read()
pil_image = Image.open(io.BytesIO(image_bytes))
# Optionally save image
saved_path = None
if save_image:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
filename = f"tryon_analysis_{timestamp}.png"
filepath = OUTPUT_DIR / filename
if pil_image.mode != 'RGB':
pil_image = pil_image.convert('RGB')
pil_image.save(str(filepath), 'PNG')
saved_path = str(filepath)
# Perform virtual try-on analysis
result = analyzer.analyze_for_virtual_tryon(pil_image)
if not result.get('success', False):
raise HTTPException(
status_code=500,
detail=result.get('message', 'Analysis failed')
)
# Build response
response_data = {
"success": True,
"tryon_analysis": result.get('analysis', ''),
"raw_response": result.get('raw_response', ''),
"image_dimensions": result.get('image_dimensions', {})
}
if saved_path:
response_data["saved_path"] = saved_path
return JSONResponse(response_data)
except HTTPException:
raise
except Exception as e:
import traceback
error_details = f"Error analyzing image: {str(e)}\n{traceback.format_exc()}"
print(error_details)
raise HTTPException(
status_code=500,
detail=f"Error analyzing image: {str(e)}"
)
@app.post("/api/v1/analyze/quick")
async def quick_analyze(
image: UploadFile = File(..., description="User photo for quick analysis")
):
"""
Quick style analysis (less detailed, faster response).
Provides:
- Body type
- Posture/alignment
- Skin tone with undertone
- Face shape
- Quick style suggestions
Args:
image: User photo file
Returns:
JSON response with quick style analysis
"""
if not analyzer_available:
raise HTTPException(
status_code=503,
detail="Style analyzer is not available. Check Gemini API configuration."
)
try:
# Read image
image_bytes = await image.read()
pil_image = Image.open(io.BytesIO(image_bytes))
# Perform quick analysis (detailed=False)
result = analyzer.analyze_image(pil_image, detailed=False)
if not result.get('success', False):
raise HTTPException(
status_code=500,
detail=result.get('message', 'Analysis failed')
)
# Build response
response_data = {
"success": True,
"quick_analysis": result.get('raw_analysis', ''),
"image_info": {
"width": pil_image.width,
"height": pil_image.height
}
}
return JSONResponse(response_data)
except HTTPException:
raise
except Exception as e:
import traceback
error_details = f"Error analyzing image: {str(e)}\n{traceback.format_exc()}"
print(error_details)
raise HTTPException(
status_code=500,
detail=f"Error analyzing image: {str(e)}"
)
if __name__ == "__main__":
uvicorn.run("api_server:app", host="0.0.0.0", port=7860, reload=True)
|