Spaces:
Paused
Paused
Ali Mohsin
commited on
Commit
·
2d65303
1
Parent(s):
45b7274
more fixes
Browse files
app.py
CHANGED
|
@@ -7,8 +7,10 @@ import gradio as gr
|
|
| 7 |
import numpy as np
|
| 8 |
import requests
|
| 9 |
import torch
|
| 10 |
-
from fastapi import FastAPI, Header, HTTPException
|
|
|
|
| 11 |
from pydantic import BaseModel
|
|
|
|
| 12 |
from PIL import Image
|
| 13 |
from starlette.staticfiles import StaticFiles
|
| 14 |
import threading
|
|
@@ -226,6 +228,7 @@ class Item(BaseModel):
|
|
| 226 |
embedding: Optional[List[float]] = None
|
| 227 |
category: Optional[str] = None
|
| 228 |
image_url: Optional[str] = None
|
|
|
|
| 229 |
|
| 230 |
|
| 231 |
class ComposeRequest(BaseModel):
|
|
@@ -356,6 +359,138 @@ def get_image_formats() -> dict:
|
|
| 356 |
"note": "Images are automatically converted to RGB mode for model processing"
|
| 357 |
}
|
| 358 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
@app.post("/tags/validate")
|
| 360 |
def validate_request_tags(tags: Dict[str, Any], x_api_key: Optional[str] = Header(None)) -> dict:
|
| 361 |
"""
|
|
@@ -465,19 +600,58 @@ def compose(req: ComposeRequest, x_api_key: Optional[str] = Header(None)) -> dic
|
|
| 465 |
|
| 466 |
Supports both legacy context dict format and new tag-based format.
|
| 467 |
Tags are processed and prioritized automatically.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
"""
|
| 469 |
require_api_key(x_api_key)
|
| 470 |
|
| 471 |
-
# Build items
|
| 472 |
-
items = [
|
| 473 |
-
|
|
|
|
|
|
|
|
|
|
| 474 |
"id": it.id,
|
| 475 |
"embedding": np.array(it.embedding, dtype=np.float32) if it.embedding is not None else None,
|
| 476 |
"category": it.category,
|
| 477 |
-
"image_url": it.image_url,
|
| 478 |
}
|
| 479 |
-
|
| 480 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 481 |
|
| 482 |
# Build context from request
|
| 483 |
context = req.context or {}
|
|
@@ -513,23 +687,52 @@ def compose(req: ComposeRequest, x_api_key: Optional[str] = Header(None)) -> dic
|
|
| 513 |
context[tag_name] = tag_value
|
| 514 |
|
| 515 |
# Validate tags
|
| 516 |
-
is_valid,
|
| 517 |
if not is_valid:
|
| 518 |
-
return
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
|
|
|
|
|
|
|
|
|
| 523 |
|
| 524 |
# Generate recommendations
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 533 |
|
| 534 |
|
| 535 |
@app.get("/artifacts")
|
|
|
|
| 7 |
import numpy as np
|
| 8 |
import requests
|
| 9 |
import torch
|
| 10 |
+
from fastapi import FastAPI, Header, HTTPException, UploadFile, File, Form
|
| 11 |
+
from fastapi.responses import JSONResponse
|
| 12 |
from pydantic import BaseModel
|
| 13 |
+
from typing import List as TypingList
|
| 14 |
from PIL import Image
|
| 15 |
from starlette.staticfiles import StaticFiles
|
| 16 |
import threading
|
|
|
|
| 228 |
embedding: Optional[List[float]] = None
|
| 229 |
category: Optional[str] = None
|
| 230 |
image_url: Optional[str] = None
|
| 231 |
+
image_base64: Optional[str] = None # Base64 encoded image
|
| 232 |
|
| 233 |
|
| 234 |
class ComposeRequest(BaseModel):
|
|
|
|
| 359 |
"note": "Images are automatically converted to RGB mode for model processing"
|
| 360 |
}
|
| 361 |
|
| 362 |
+
@app.post("/compose/upload")
|
| 363 |
+
async def compose_with_upload(
|
| 364 |
+
files: TypingList[UploadFile] = File(...),
|
| 365 |
+
occasion: str = Form("casual"),
|
| 366 |
+
weather: str = Form("any"),
|
| 367 |
+
style: str = Form("casual"),
|
| 368 |
+
num_outfits: int = Form(5),
|
| 369 |
+
color_preference: Optional[str] = Form(None),
|
| 370 |
+
fit_preference: Optional[str] = Form(None),
|
| 371 |
+
material_preference: Optional[str] = Form(None),
|
| 372 |
+
season: Optional[str] = Form(None),
|
| 373 |
+
time_of_day: Optional[str] = Form(None),
|
| 374 |
+
budget: Optional[str] = Form(None),
|
| 375 |
+
personal_style: Optional[str] = Form(None),
|
| 376 |
+
x_api_key: Optional[str] = Header(None)
|
| 377 |
+
) -> dict:
|
| 378 |
+
"""
|
| 379 |
+
Generate outfit recommendations from uploaded image files.
|
| 380 |
+
|
| 381 |
+
This endpoint accepts multipart/form-data with:
|
| 382 |
+
- files: Image files (JPG, PNG, WEBP, GIF, BMP, TIFF, etc.)
|
| 383 |
+
- All tag parameters as form fields
|
| 384 |
+
|
| 385 |
+
Returns personalized outfit recommendations.
|
| 386 |
+
"""
|
| 387 |
+
require_api_key(x_api_key)
|
| 388 |
+
|
| 389 |
+
if not files or len(files) < 2:
|
| 390 |
+
raise HTTPException(status_code=400, detail="At least 2 images required for outfit recommendations")
|
| 391 |
+
|
| 392 |
+
# Load images from uploaded files
|
| 393 |
+
items = []
|
| 394 |
+
errors = []
|
| 395 |
+
|
| 396 |
+
for i, file in enumerate(files):
|
| 397 |
+
try:
|
| 398 |
+
# Read file content
|
| 399 |
+
contents = await file.read()
|
| 400 |
+
|
| 401 |
+
# Load image from bytes
|
| 402 |
+
img = load_image_from_bytes(contents, convert_to_rgb=True, raise_on_error=False)
|
| 403 |
+
if img is None:
|
| 404 |
+
errors.append(f"Failed to load image from file {file.filename}")
|
| 405 |
+
continue
|
| 406 |
+
|
| 407 |
+
items.append({
|
| 408 |
+
"id": f"item_{i}",
|
| 409 |
+
"image": img,
|
| 410 |
+
"category": None # Will be auto-detected
|
| 411 |
+
})
|
| 412 |
+
except Exception as e:
|
| 413 |
+
errors.append(f"Error processing file {file.filename}: {str(e)}")
|
| 414 |
+
|
| 415 |
+
if len(items) < 2:
|
| 416 |
+
error_msg = f"Not enough valid images. Need at least 2, got {len(items)}."
|
| 417 |
+
if errors:
|
| 418 |
+
error_msg += f" Errors: {', '.join(errors[:3])}"
|
| 419 |
+
raise HTTPException(status_code=400, detail=error_msg)
|
| 420 |
+
|
| 421 |
+
# Build context
|
| 422 |
+
context = {
|
| 423 |
+
"occasion": occasion,
|
| 424 |
+
"weather": weather,
|
| 425 |
+
"style": style,
|
| 426 |
+
"outfit_style": style,
|
| 427 |
+
"num_outfits": num_outfits
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
# Add optional tags
|
| 431 |
+
if color_preference and color_preference != "None":
|
| 432 |
+
context["color_preference"] = color_preference
|
| 433 |
+
if fit_preference and fit_preference != "None":
|
| 434 |
+
context["fit_preference"] = fit_preference
|
| 435 |
+
if material_preference and material_preference != "None":
|
| 436 |
+
context["material_preference"] = material_preference
|
| 437 |
+
if season and season != "None":
|
| 438 |
+
context["season"] = season
|
| 439 |
+
if time_of_day and time_of_day != "None":
|
| 440 |
+
context["time_of_day"] = time_of_day
|
| 441 |
+
if budget and budget != "None":
|
| 442 |
+
context["budget"] = budget
|
| 443 |
+
if personal_style and personal_style != "None":
|
| 444 |
+
context["personal_style"] = personal_style
|
| 445 |
+
|
| 446 |
+
# Validate tags
|
| 447 |
+
is_valid, tag_errors = validate_tags(context)
|
| 448 |
+
if not is_valid:
|
| 449 |
+
return JSONResponse(
|
| 450 |
+
status_code=400,
|
| 451 |
+
content={
|
| 452 |
+
"error": "Invalid tags provided",
|
| 453 |
+
"errors": tag_errors,
|
| 454 |
+
"valid_tag_options": get_all_tag_options()
|
| 455 |
+
}
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
# Generate recommendations
|
| 459 |
+
try:
|
| 460 |
+
outfits = service.compose_outfits(items, context=context)
|
| 461 |
+
|
| 462 |
+
# Check for errors
|
| 463 |
+
if outfits and isinstance(outfits, list) and len(outfits) > 0:
|
| 464 |
+
if isinstance(outfits[0], dict) and "error" in outfits[0]:
|
| 465 |
+
return JSONResponse(
|
| 466 |
+
status_code=500,
|
| 467 |
+
content={
|
| 468 |
+
"error": "Recommendation generation failed",
|
| 469 |
+
"details": outfits[0].get("details", []),
|
| 470 |
+
"message": outfits[0].get("message", "Unknown error")
|
| 471 |
+
}
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
return {
|
| 475 |
+
"outfits": outfits,
|
| 476 |
+
"version": service.vit_version,
|
| 477 |
+
"tags_processed": True,
|
| 478 |
+
"context_used": context,
|
| 479 |
+
"items_processed": len(items),
|
| 480 |
+
"warnings": errors if errors else None
|
| 481 |
+
}
|
| 482 |
+
except Exception as e:
|
| 483 |
+
import traceback
|
| 484 |
+
traceback.print_exc()
|
| 485 |
+
return JSONResponse(
|
| 486 |
+
status_code=500,
|
| 487 |
+
content={
|
| 488 |
+
"error": "Internal server error",
|
| 489 |
+
"message": str(e),
|
| 490 |
+
"model_status": service.get_model_status()
|
| 491 |
+
}
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
@app.post("/tags/validate")
|
| 495 |
def validate_request_tags(tags: Dict[str, Any], x_api_key: Optional[str] = Header(None)) -> dict:
|
| 496 |
"""
|
|
|
|
| 600 |
|
| 601 |
Supports both legacy context dict format and new tag-based format.
|
| 602 |
Tags are processed and prioritized automatically.
|
| 603 |
+
|
| 604 |
+
Items can provide:
|
| 605 |
+
- image_url: URL to image (will be downloaded)
|
| 606 |
+
- image_base64: Base64 encoded image
|
| 607 |
+
- embedding: Pre-computed embedding (skips ResNet)
|
| 608 |
+
- category: Item category (optional, auto-detected if not provided)
|
| 609 |
"""
|
| 610 |
require_api_key(x_api_key)
|
| 611 |
|
| 612 |
+
# Build items with image loading
|
| 613 |
+
items = []
|
| 614 |
+
errors = []
|
| 615 |
+
|
| 616 |
+
for it in req.items:
|
| 617 |
+
item_dict = {
|
| 618 |
"id": it.id,
|
| 619 |
"embedding": np.array(it.embedding, dtype=np.float32) if it.embedding is not None else None,
|
| 620 |
"category": it.category,
|
|
|
|
| 621 |
}
|
| 622 |
+
|
| 623 |
+
# Load image from URL if provided
|
| 624 |
+
if it.image_url:
|
| 625 |
+
img = load_image_from_url(it.image_url, timeout=20, convert_to_rgb=True, raise_on_error=False)
|
| 626 |
+
if img is not None:
|
| 627 |
+
item_dict["image"] = img
|
| 628 |
+
else:
|
| 629 |
+
errors.append(f"Failed to load image from URL for item {it.id}: {it.image_url}")
|
| 630 |
+
|
| 631 |
+
# Load image from base64 if provided
|
| 632 |
+
elif it.image_base64:
|
| 633 |
+
try:
|
| 634 |
+
image_bytes = base64.b64decode(it.image_base64)
|
| 635 |
+
img = load_image_from_bytes(image_bytes, convert_to_rgb=True, raise_on_error=False)
|
| 636 |
+
if img is not None:
|
| 637 |
+
item_dict["image"] = img
|
| 638 |
+
else:
|
| 639 |
+
errors.append(f"Failed to load image from base64 for item {it.id}")
|
| 640 |
+
except Exception as e:
|
| 641 |
+
errors.append(f"Error decoding base64 image for item {it.id}: {str(e)}")
|
| 642 |
+
|
| 643 |
+
# If no image and no embedding, skip this item
|
| 644 |
+
if item_dict.get("image") is None and item_dict.get("embedding") is None:
|
| 645 |
+
errors.append(f"Item {it.id} has no image or embedding - skipping")
|
| 646 |
+
continue
|
| 647 |
+
|
| 648 |
+
items.append(item_dict)
|
| 649 |
+
|
| 650 |
+
if not items:
|
| 651 |
+
error_msg = "No valid items provided. All items failed to load or have no images/embeddings."
|
| 652 |
+
if errors:
|
| 653 |
+
error_msg += f" Errors: {', '.join(errors[:5])}"
|
| 654 |
+
raise HTTPException(status_code=400, detail=error_msg)
|
| 655 |
|
| 656 |
# Build context from request
|
| 657 |
context = req.context or {}
|
|
|
|
| 687 |
context[tag_name] = tag_value
|
| 688 |
|
| 689 |
# Validate tags
|
| 690 |
+
is_valid, tag_errors = validate_tags(context)
|
| 691 |
if not is_valid:
|
| 692 |
+
return JSONResponse(
|
| 693 |
+
status_code=400,
|
| 694 |
+
content={
|
| 695 |
+
"error": "Invalid tags provided",
|
| 696 |
+
"errors": tag_errors,
|
| 697 |
+
"valid_tag_options": get_all_tag_options()
|
| 698 |
+
}
|
| 699 |
+
)
|
| 700 |
|
| 701 |
# Generate recommendations
|
| 702 |
+
try:
|
| 703 |
+
outfits = service.compose_outfits(items, context=context)
|
| 704 |
+
|
| 705 |
+
# Check if compose_outfits returned an error
|
| 706 |
+
if outfits and isinstance(outfits, list) and len(outfits) > 0:
|
| 707 |
+
if isinstance(outfits[0], dict) and "error" in outfits[0]:
|
| 708 |
+
return JSONResponse(
|
| 709 |
+
status_code=500,
|
| 710 |
+
content={
|
| 711 |
+
"error": "Recommendation generation failed",
|
| 712 |
+
"details": outfits[0].get("details", []),
|
| 713 |
+
"message": outfits[0].get("message", "Unknown error")
|
| 714 |
+
}
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
return {
|
| 718 |
+
"outfits": outfits,
|
| 719 |
+
"version": service.vit_version,
|
| 720 |
+
"tags_processed": True,
|
| 721 |
+
"context_used": context,
|
| 722 |
+
"items_processed": len(items),
|
| 723 |
+
"warnings": errors if errors else None
|
| 724 |
+
}
|
| 725 |
+
except Exception as e:
|
| 726 |
+
import traceback
|
| 727 |
+
traceback.print_exc()
|
| 728 |
+
return JSONResponse(
|
| 729 |
+
status_code=500,
|
| 730 |
+
content={
|
| 731 |
+
"error": "Internal server error during recommendation generation",
|
| 732 |
+
"message": str(e),
|
| 733 |
+
"model_status": service.get_model_status()
|
| 734 |
+
}
|
| 735 |
+
)
|
| 736 |
|
| 737 |
|
| 738 |
@app.get("/artifacts")
|