Spaces:
Runtime error
Runtime error
Commit
·
f2638df
0
Parent(s):
Initial clean commit
Browse files- .gitattributes +35 -0
- .gitignore +14 -0
- README.md +10 -0
- app/__init__.py +0 -0
- app/api/__init__.py +0 -0
- app/api/image_router.py +160 -0
- app/core/__init__.py +0 -0
- app/core/clients.py +57 -0
- app/core/config.py +11 -0
- app/main.py +35 -0
- app/schemas/__init__.py +0 -0
- app/schemas/image.py +43 -0
- app/services/__init__.py +0 -0
- app/services/image_service.py +181 -0
- requirements.txt +61 -0
.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python virtual environment
|
| 2 |
+
venv/
|
| 3 |
+
.venv/
|
| 4 |
+
|
| 5 |
+
# Python cache files
|
| 6 |
+
__pycache__/
|
| 7 |
+
*.pyc
|
| 8 |
+
|
| 9 |
+
# Environment variables (IMPORTANT for security)
|
| 10 |
+
.env
|
| 11 |
+
|
| 12 |
+
# IDE files (optional, but good practice)
|
| 13 |
+
.idea/
|
| 14 |
+
.vscode/
|
README.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Virtual Try On
|
| 3 |
+
emoji: 🐠
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: docker
|
| 7 |
+
pinned: false
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app/__init__.py
ADDED
|
File without changes
|
app/api/__init__.py
ADDED
|
File without changes
|
app/api/image_router.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from fastapi import APIRouter, HTTPException, Response, UploadFile, File, Form
|
| 3 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 4 |
+
from app.schemas import image as image_schemas
|
| 5 |
+
from app.services import image_service
|
| 6 |
+
from io import BytesIO
|
| 7 |
+
from typing import Optional, Dict, Any
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
router = APIRouter(
|
| 12 |
+
prefix="/api/v1",
|
| 13 |
+
tags=["Image Generation"]
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# --- Helper function for streaming image responses ---
|
| 17 |
+
def create_image_streaming_response(image_data: BytesIO, media_type: str = "image/png"):
|
| 18 |
+
"""
|
| 19 |
+
Creates a StreamingResponse for an image from BytesIO data.
|
| 20 |
+
"""
|
| 21 |
+
if not image_data:
|
| 22 |
+
raise HTTPException(status_code=404, detail="Image not found or could not be generated.")
|
| 23 |
+
|
| 24 |
+
image_data.seek(0) # Ensure the pointer is at the beginning of the BytesIO object
|
| 25 |
+
return StreamingResponse(image_data, media_type=media_type)
|
| 26 |
+
|
| 27 |
+
# --- Endpoints ---
|
| 28 |
+
|
| 29 |
+
@router.post("/enhance-prompt", response_model=image_schemas.EnhancePromptResponse)
|
| 30 |
+
async def enhance_prompt(request: image_schemas.EnhancePromptRequest):
|
| 31 |
+
logger.info(f"Received request to /enhance-prompt for: {request.raw_prompt[:50]}...")
|
| 32 |
+
try:
|
| 33 |
+
enhanced_prompt = image_service.enhance_user_prompt(request.raw_prompt)
|
| 34 |
+
logger.info("Successfully enhanced prompt.")
|
| 35 |
+
return image_schemas.EnhancePromptResponse(
|
| 36 |
+
raw_prompt=request.raw_prompt,
|
| 37 |
+
enhanced_prompt=enhanced_prompt
|
| 38 |
+
)
|
| 39 |
+
except Exception as e:
|
| 40 |
+
logger.error(f"Error in /enhance-prompt: {e}", exc_info=True)
|
| 41 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 42 |
+
|
| 43 |
+
@router.post("/generate-image", response_class=StreamingResponse) # Response class directly for image
|
| 44 |
+
async def generate_image(request: image_schemas.GenerateImageRequest):
|
| 45 |
+
"""
|
| 46 |
+
Generates an image from either a raw or an enhanced prompt.
|
| 47 |
+
Returns the image directly.
|
| 48 |
+
"""
|
| 49 |
+
logger.info("Received request to /generate-image")
|
| 50 |
+
try:
|
| 51 |
+
if request.enhanced_prompt:
|
| 52 |
+
image_prompt = request.enhanced_prompt
|
| 53 |
+
elif request.raw_prompt:
|
| 54 |
+
image_prompt = request.raw_prompt
|
| 55 |
+
else:
|
| 56 |
+
logger.warning("Bad request to /generate-image: No prompt provided.")
|
| 57 |
+
raise HTTPException(status_code=400, detail="Either raw_prompt or enhanced_prompt must be provided.")
|
| 58 |
+
|
| 59 |
+
# Service returns text and BytesIO
|
| 60 |
+
generated_text, image_bytes_io = image_service.generate_image_from_text(image_prompt)
|
| 61 |
+
|
| 62 |
+
if not image_bytes_io:
|
| 63 |
+
logger.error("Image generation failed or returned no image.")
|
| 64 |
+
# If text was returned, perhaps send that in a JSON error response
|
| 65 |
+
if generated_text:
|
| 66 |
+
raise HTTPException(status_code=500, detail=f"Image generation failed. Model response: {generated_text}")
|
| 67 |
+
raise HTTPException(status_code=500, detail="Image generation failed: No image data received.")
|
| 68 |
+
|
| 69 |
+
logger.info("Successfully generated image. Streaming response.")
|
| 70 |
+
return create_image_streaming_response(image_bytes_io)
|
| 71 |
+
|
| 72 |
+
except HTTPException: # Re-raise HTTPExceptions directly
|
| 73 |
+
raise
|
| 74 |
+
except Exception as e:
|
| 75 |
+
logger.error(f"Error in /generate-image: {e}", exc_info=True)
|
| 76 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 77 |
+
|
| 78 |
+
# --- update_image (MODIFIED) ---
|
| 79 |
+
@router.post("/update-image", response_class=StreamingResponse) # Response class is already correct
|
| 80 |
+
async def update_image(
|
| 81 |
+
image: UploadFile = File(..., description="The image to update (PNG, JPG)"),
|
| 82 |
+
text_instruction: str = Form(..., description="The text instruction for what to change.")
|
| 83 |
+
):
|
| 84 |
+
"""
|
| 85 |
+
Updates an existing image using a text instruction.
|
| 86 |
+
Returns the updated image directly.
|
| 87 |
+
"""
|
| 88 |
+
logger.info("Received request to /update-image")
|
| 89 |
+
|
| 90 |
+
# Check if the uploaded file is an image
|
| 91 |
+
if not image.content_type.startswith("image/"):
|
| 92 |
+
raise HTTPException(status_code=400, detail="Image must be an image type (e.g., image/png, image/jpeg).")
|
| 93 |
+
|
| 94 |
+
try:
|
| 95 |
+
# Read the image bytes from the uploaded file
|
| 96 |
+
image_bytes = await image.read()
|
| 97 |
+
|
| 98 |
+
# Service returns text and BytesIO
|
| 99 |
+
updated_text, updated_image_bytes_io = image_service.update_image_with_text(
|
| 100 |
+
text_instruction=text_instruction,
|
| 101 |
+
image_bytes=image_bytes # Pass the raw bytes to the service
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
if not updated_image_bytes_io:
|
| 105 |
+
logger.error("Image update failed or returned no image.")
|
| 106 |
+
if updated_text:
|
| 107 |
+
raise HTTPException(status_code=500, detail=f"Image update failed. Model response: {updated_text}")
|
| 108 |
+
raise HTTPException(status_code=500, detail="Image update failed: No image data received.")
|
| 109 |
+
|
| 110 |
+
logger.info("Successfully updated image. Streaming response.")
|
| 111 |
+
return create_image_streaming_response(updated_image_bytes_io)
|
| 112 |
+
|
| 113 |
+
except HTTPException:
|
| 114 |
+
raise
|
| 115 |
+
except Exception as e:
|
| 116 |
+
logger.error(f"Error in /update-image: {e}", exc_info=True)
|
| 117 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# --- New Virtual Try-On Endpoint with File Uploads ---
|
| 121 |
+
@router.post("/virtual-try-on")
|
| 122 |
+
async def virtual_try_on(
|
| 123 |
+
dress_image: UploadFile = File(..., description="The dress image for try-on (PNG, JPG)"),
|
| 124 |
+
person_image: UploadFile = File(..., description="The person image for try-on (PNG, JPG)")
|
| 125 |
+
) -> Response: # Return type is Response because it can be JSON or Image
|
| 126 |
+
"""
|
| 127 |
+
Performs a virtual try-on using an uploaded dress image and a person image.
|
| 128 |
+
Returns the try-on image directly or a JSON response with a summary if no image.
|
| 129 |
+
"""
|
| 130 |
+
logger.info("Received request to /virtual-try-on with image uploads.")
|
| 131 |
+
|
| 132 |
+
if not dress_image.content_type.startswith("image/"):
|
| 133 |
+
raise HTTPException(status_code=400, detail="Dress image must be an image type (e.g., image/png, image/jpeg).")
|
| 134 |
+
if not person_image.content_type.startswith("image/"):
|
| 135 |
+
raise HTTPException(status_code=400, detail="Person image must be an image type (e.g., image/png, image/jpeg).")
|
| 136 |
+
|
| 137 |
+
try:
|
| 138 |
+
dress_image_bytes = await dress_image.read()
|
| 139 |
+
person_image_bytes = await person_image.read()
|
| 140 |
+
|
| 141 |
+
# Service returns JSON summary (dict) and BytesIO object
|
| 142 |
+
summary, try_on_image_bytes_io = image_service.virtual_try_on(
|
| 143 |
+
dress_image_bytes=dress_image_bytes,
|
| 144 |
+
person_image_bytes=person_image_bytes
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
if try_on_image_bytes_io:
|
| 148 |
+
logger.info("Virtual try-on successful. Streaming image response.")
|
| 149 |
+
# If an image is returned, stream it directly
|
| 150 |
+
return create_image_streaming_response(try_on_image_bytes_io)
|
| 151 |
+
else:
|
| 152 |
+
logger.warning("Virtual try-on returned no image. Sending JSON summary.")
|
| 153 |
+
# If no image, return the JSON summary as a JSON response
|
| 154 |
+
return JSONResponse(content=summary)
|
| 155 |
+
|
| 156 |
+
except HTTPException:
|
| 157 |
+
raise
|
| 158 |
+
except Exception as e:
|
| 159 |
+
logger.error(f"Error in /virtual-try-on: {e}", exc_info=True)
|
| 160 |
+
raise HTTPException(status_code=500, detail=str(e))
|
app/core/__init__.py
ADDED
|
File without changes
|
app/core/clients.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
from langchain_groq import ChatGroq
|
| 4 |
+
from langchain_core.prompts import PromptTemplate
|
| 5 |
+
from google import genai
|
| 6 |
+
from .config import settings
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
# --- LLM (LangChain) Client ---
|
| 11 |
+
|
| 12 |
+
def get_llm():
|
| 13 |
+
"""Initializes and returns the ChatGroq LLM instance."""
|
| 14 |
+
logger.info("Initializing ChatGroq LLM...")
|
| 15 |
+
return ChatGroq(
|
| 16 |
+
model="meta-llama/llama-4-scout-17b-16e-instruct",
|
| 17 |
+
temperature=1,
|
| 18 |
+
max_tokens=1024,
|
| 19 |
+
api_key=settings.LANGCHAIN_API_KEY
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def get_prompt_template():
|
| 23 |
+
"""Returns the prompt enhancement template."""
|
| 24 |
+
return PromptTemplate.from_template('''
|
| 25 |
+
You are a Prompt Enhancement AI Assistant. Your task is to take the
|
| 26 |
+
user's raw image prompt and convert it into a detailed,
|
| 27 |
+
professional prompt optimized for generating high-quality AI image.
|
| 28 |
+
Enhance the prompt by including relevant details such as:
|
| 29 |
+
- Camera specifications (e.g., lens type, aperture, focal length)
|
| 30 |
+
- Lighting setup (e.g., natural light, studio lighting, soft shadows)
|
| 31 |
+
- Camera angle (e.g., top-down, macro, isometric, side view)
|
| 32 |
+
- Background style (e.g., plain white, minimalistic, outdoor, studio backdrop)
|
| 33 |
+
- Scene composition (e.g., centered product, depth of field, reflections)
|
| 34 |
+
Focus only on *Poster photography* — do not include humans or models.
|
| 35 |
+
Raw Prompt:
|
| 36 |
+
{Raw_Prompt}
|
| 37 |
+
Enhanced Prompt:
|
| 38 |
+
''')
|
| 39 |
+
|
| 40 |
+
# --- Google GenAI Client (FIXED) ---
|
| 41 |
+
def get_genai_client():
|
| 42 |
+
"""Initializes and returns the Google GenAI client (older SDK version)."""
|
| 43 |
+
try:
|
| 44 |
+
logger.info("Initializing Google GenAI Client...")
|
| 45 |
+
# Use the genai.Client from your original code
|
| 46 |
+
client = genai.Client(api_key=settings.GOOGLE_API_KEY)
|
| 47 |
+
logger.info("Google GenAI Client initialized successfully.")
|
| 48 |
+
return client
|
| 49 |
+
except Exception as e:
|
| 50 |
+
logger.error(f"Failed to initialize GenAI client: {e}")
|
| 51 |
+
raise
|
| 52 |
+
|
| 53 |
+
# --- Initialize Clients ---
|
| 54 |
+
llm = get_llm()
|
| 55 |
+
prompt_template = get_prompt_template()
|
| 56 |
+
# Export the client object
|
| 57 |
+
genai_client = get_genai_client()
|
app/core/config.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic_settings import BaseSettings
|
| 2 |
+
|
| 3 |
+
class Settings(BaseSettings):
|
| 4 |
+
LANGCHAIN_API_KEY: str
|
| 5 |
+
GOOGLE_API_KEY: str
|
| 6 |
+
|
| 7 |
+
class Config:
|
| 8 |
+
env_file = ".env"
|
| 9 |
+
|
| 10 |
+
# Create a single, validated settings instance
|
| 11 |
+
settings = Settings()
|
app/main.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import uvicorn
|
| 2 |
+
import logging
|
| 3 |
+
import sys
|
| 4 |
+
from fastapi import FastAPI
|
| 5 |
+
from app.api.image_router import router as image_router
|
| 6 |
+
|
| 7 |
+
# --- Logging Configuration ---
|
| 8 |
+
# We configure logging to output to stdout (standard output)
|
| 9 |
+
# This is best practice for services, as the environment (like Docker or Uvicorn)
|
| 10 |
+
# can then capture and manage the logs.
|
| 11 |
+
logging.basicConfig(
|
| 12 |
+
level=logging.INFO,
|
| 13 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
| 14 |
+
handlers=[logging.StreamHandler(sys.stdout)]
|
| 15 |
+
)
|
| 16 |
+
# ---
|
| 17 |
+
|
| 18 |
+
# Get a logger for this file
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
# Initialize the FastAPI app
|
| 22 |
+
app = FastAPI(title="Image Generation & Update API")
|
| 23 |
+
|
| 24 |
+
# Include your API routers
|
| 25 |
+
app.include_router(image_router)
|
| 26 |
+
|
| 27 |
+
# 1. Root endpoint
|
| 28 |
+
@app.get("/")
|
| 29 |
+
async def root():
|
| 30 |
+
logger.info("Root endpoint '/' was hit")
|
| 31 |
+
return {"message": "Welcome to the Image Generation API! Visit /docs for API documentation."}
|
| 32 |
+
|
| 33 |
+
# --- Run the app ---
|
| 34 |
+
if __name__ == "__main__":
|
| 35 |
+
uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True)
|
app/schemas/__init__.py
ADDED
|
File without changes
|
app/schemas/image.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel
|
| 2 |
+
from typing import Optional, Dict, Any
|
| 3 |
+
from fastapi import UploadFile, File # Import UploadFile and File
|
| 4 |
+
|
| 5 |
+
# --- Request Models ---
|
| 6 |
+
|
| 7 |
+
class EnhancePromptRequest(BaseModel):
|
| 8 |
+
raw_prompt: str
|
| 9 |
+
|
| 10 |
+
class GenerateImageRequest(BaseModel):
|
| 11 |
+
raw_prompt: Optional[str] = None
|
| 12 |
+
enhanced_prompt: Optional[str] = None
|
| 13 |
+
|
| 14 |
+
# UpdateImageRequest still needs base64 as it receives existing image for modification
|
| 15 |
+
class UpdateImageRequest(BaseModel):
|
| 16 |
+
text_instruction: str
|
| 17 |
+
image_base64: str
|
| 18 |
+
|
| 19 |
+
# VirtualTryOnRequest now expects UploadFile objects
|
| 20 |
+
# Note: For file uploads, it's often simpler to define them directly in the API endpoint function
|
| 21 |
+
# using `File()` or `Form()` for metadata, rather than in a Pydantic model for the request body.
|
| 22 |
+
# However, for consistency, we'll keep a schema here and handle parsing in the router.
|
| 23 |
+
# But for multipart/form-data, Pydantic models for request *body* are slightly different.
|
| 24 |
+
# The endpoint itself will directly take the UploadFile.
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# --- Response Models ---
|
| 28 |
+
|
| 29 |
+
class EnhancePromptResponse(BaseModel):
|
| 30 |
+
raw_prompt: str
|
| 31 |
+
enhanced_prompt: str
|
| 32 |
+
|
| 33 |
+
# These response models no longer contain image_base64
|
| 34 |
+
# The image itself will be the response body.
|
| 35 |
+
class GenerateImageOnlyResponse(BaseModel):
|
| 36 |
+
text: Optional[str] = None # Text can still be returned if the model generates it
|
| 37 |
+
|
| 38 |
+
class UpdateImageOnlyResponse(BaseModel):
|
| 39 |
+
text: Optional[str] = None
|
| 40 |
+
|
| 41 |
+
class VirtualTryOnResponse(BaseModel):
|
| 42 |
+
summary: Dict[str, Any]
|
| 43 |
+
# try_on_image will be the response body, so no base64 here
|
app/services/__init__.py
ADDED
|
File without changes
|
app/services/image_service.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import logging
|
| 3 |
+
import json
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from google.genai import types
|
| 7 |
+
from typing import Optional, Dict, Any
|
| 8 |
+
|
| 9 |
+
# Import our initialized clients
|
| 10 |
+
from app.core.clients import llm, prompt_template, genai_client
|
| 11 |
+
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
# --- New Constant for Virtual Try-On Prompt ---
|
| 15 |
+
VIRTUAL_TRY_ON_PROMPT = """
|
| 16 |
+
You are an expert image-editing agent. Perform a high-fidelity virtual try-on using two inputs:
|
| 17 |
+
|
| 18 |
+
- Input 1 (dress reference): the exact garment image to be transferred.
|
| 19 |
+
- Input 2 (person): the target person who must wear the garment.
|
| 20 |
+
|
| 21 |
+
Positive instructions (Do):
|
| 22 |
+
1. Produce exactly one photorealistic output image showing the person wearing the dress from Input 1.
|
| 23 |
+
2. Preserve the person's face, facial features, expression, hair, gender, skin tone, and body proportions — do NOT change identity.
|
| 24 |
+
3. Reproduce the dress design, color, pattern, fabric texture, and major details (buttons, seams, prints) faithfully — do NOT change these.
|
| 25 |
+
4. Match lighting, shadows, perspective, and scale so the garment appears naturally worn by the person.
|
| 26 |
+
5. If minor geometric adjustments are required to account for pose, make them subtle and keep dress details intact.
|
| 27 |
+
6. Also return a short text JSON summary with the form: {"success": true|false, "notes": "explain any limitations or changes"}.
|
| 28 |
+
|
| 29 |
+
Negative instructions (Do NOT):
|
| 30 |
+
1. Do NOT modify the person's face, gender, or identifying features.
|
| 31 |
+
2. Do NOT change the dress color, pattern, or main texture.
|
| 32 |
+
3. Do NOT add extra clothing items, logos, watermarks, offensive symbols, or unrelated props.
|
| 33 |
+
4. Do NOT produce empty responses, placeholders, or images containing text overlays.
|
| 34 |
+
5. Do NOT blur, heavily distort, or crop important parts of the person or dress.
|
| 35 |
+
|
| 36 |
+
Output requirements:
|
| 37 |
+
- Return a single photorealistic image (same orientation as the person image) and a short text JSON summary.
|
| 38 |
+
- No collages, no multiple thumbnail images, no visible watermarks.
|
| 39 |
+
- If the try-on cannot be done reliably, set "success": false and explain why in "notes".
|
| 40 |
+
|
| 41 |
+
When uncertain, err on the side of preserving the person's identity and the dress fidelity.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def enhance_user_prompt(raw_prompt: str) -> str:
|
| 45 |
+
logger.info(f"Enhancing prompt: {raw_prompt[:50]}...")
|
| 46 |
+
formatted_prompt = prompt_template.invoke({"Raw_Prompt": raw_prompt})
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
response = llm.invoke(formatted_prompt)
|
| 50 |
+
logger.info("Prompt enhancement successful.")
|
| 51 |
+
return response.content
|
| 52 |
+
except Exception as e:
|
| 53 |
+
logger.error(f"Error during prompt enhancement: {e}", exc_info=True)
|
| 54 |
+
raise
|
| 55 |
+
|
| 56 |
+
# Returns BytesIO object, not base64 string
|
| 57 |
+
def generate_image_from_text(image_prompt: str) -> tuple[Optional[str], Optional[BytesIO]]:
|
| 58 |
+
"""Generates an image using the GenAI client, returning text and BytesIO."""
|
| 59 |
+
logger.info(f"Generating image with prompt: {image_prompt[:50]}...")
|
| 60 |
+
|
| 61 |
+
generation_config = types.GenerateContentConfig(
|
| 62 |
+
response_modalities=['Text', 'Image']
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
try:
|
| 66 |
+
response = genai_client.models.generate_content(
|
| 67 |
+
model="gemini-2.0-flash-exp-image-generation",
|
| 68 |
+
contents=image_prompt,
|
| 69 |
+
config=generation_config
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
logger.info("Image generation call successful.")
|
| 73 |
+
|
| 74 |
+
generated_text = None
|
| 75 |
+
generated_image_bytes = None
|
| 76 |
+
|
| 77 |
+
for part in response.candidates[0].content.parts:
|
| 78 |
+
if part.text is not None:
|
| 79 |
+
generated_text = part.text
|
| 80 |
+
elif part.inline_data is not None:
|
| 81 |
+
logger.info("Processing generated image data...")
|
| 82 |
+
# Image is directly from model, convert to BytesIO
|
| 83 |
+
generated_image_bytes = BytesIO(part.inline_data.data)
|
| 84 |
+
|
| 85 |
+
return generated_text, generated_image_bytes
|
| 86 |
+
except Exception as e:
|
| 87 |
+
logger.error(f"Error during image generation: {e}", exc_info=True)
|
| 88 |
+
raise
|
| 89 |
+
|
| 90 |
+
# Returns BytesIO object, not base64 string
|
| 91 |
+
def update_image_with_text(text_instruction: str, image_bytes: bytes) -> tuple[Optional[str], Optional[BytesIO]]:
|
| 92 |
+
"""Updates an existing image based on a text instruction, returning text and BytesIO."""
|
| 93 |
+
logger.info("Opening image from bytes for update...")
|
| 94 |
+
|
| 95 |
+
try:
|
| 96 |
+
# MODIFICATION: Open image directly from bytes, not base64
|
| 97 |
+
image = Image.open(BytesIO(image_bytes))
|
| 98 |
+
except Exception as e:
|
| 99 |
+
logger.error(f"Failed to open image from bytes: {e}", exc_info=True)
|
| 100 |
+
raise ValueError("Invalid image data. The uploaded file is corrupt or not an image.")
|
| 101 |
+
|
| 102 |
+
logger.info(f"Updating image with instruction: {text_instruction[:50]}...")
|
| 103 |
+
|
| 104 |
+
generation_config = types.GenerateContentConfig(
|
| 105 |
+
response_modalities=['Text', 'Image']
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
try:
|
| 109 |
+
response = genai_client.models.generate_content(
|
| 110 |
+
model="gemini-2.0-flash-exp-image-generation",
|
| 111 |
+
contents=[text_instruction, image],
|
| 112 |
+
config=generation_config
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
logger.info("Image update call successful.")
|
| 116 |
+
|
| 117 |
+
updated_text = None
|
| 118 |
+
updated_image_bytes = None
|
| 119 |
+
|
| 120 |
+
for part in response.candidates[0].content.parts:
|
| 121 |
+
if part.text is not None:
|
| 122 |
+
updated_text = part.text
|
| 123 |
+
elif part.inline_data is not None:
|
| 124 |
+
logger.info("Processing updated image data...")
|
| 125 |
+
updated_image_bytes = BytesIO(part.inline_data.data)
|
| 126 |
+
|
| 127 |
+
return updated_text, updated_image_bytes
|
| 128 |
+
except Exception as e:
|
| 129 |
+
logger.error(f"Error during image update: {e}", exc_info=True)
|
| 130 |
+
raise
|
| 131 |
+
# --- New Virtual Try-On Service ---
|
| 132 |
+
# Accepts raw bytes for dress and person images
|
| 133 |
+
def virtual_try_on(dress_image_bytes: bytes, person_image_bytes: bytes) -> tuple[Dict[str, Any], Optional[BytesIO]]:
|
| 134 |
+
"""Performs virtual try-on using raw image bytes, returning summary and BytesIO."""
|
| 135 |
+
|
| 136 |
+
logger.info("Opening images for virtual try-on.")
|
| 137 |
+
try:
|
| 138 |
+
dress_image = Image.open(BytesIO(dress_image_bytes))
|
| 139 |
+
person_image = Image.open(BytesIO(person_image_bytes))
|
| 140 |
+
except Exception as e:
|
| 141 |
+
logger.error(f"Failed to open image from bytes: {e}", exc_info=True)
|
| 142 |
+
raise ValueError("Invalid image data. One or both uploaded files are corrupt or not images.")
|
| 143 |
+
|
| 144 |
+
try:
|
| 145 |
+
logger.info("Calling GenAI model for virtual try-on...")
|
| 146 |
+
config = types.GenerateContentConfig(
|
| 147 |
+
response_modalities=["Text", "Image"]
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
response = genai_client.models.generate_content(
|
| 151 |
+
model="gemini-2.0-flash-exp",
|
| 152 |
+
contents=[VIRTUAL_TRY_ON_PROMPT, dress_image, person_image],
|
| 153 |
+
config=config
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
logger.info("Virtual try-on call successful.")
|
| 157 |
+
|
| 158 |
+
result_summary = {"success": False, "notes": "No text response from model."}
|
| 159 |
+
result_image_bytes = None
|
| 160 |
+
|
| 161 |
+
for part in response.candidates[0].content.parts:
|
| 162 |
+
if part.text is not None:
|
| 163 |
+
try:
|
| 164 |
+
result_summary = json.loads(part.text)
|
| 165 |
+
logger.info("Parsed JSON summary from model.")
|
| 166 |
+
except json.JSONDecodeError:
|
| 167 |
+
logger.warning(f"Model returned non-JSON text: {part.text}")
|
| 168 |
+
result_summary = {
|
| 169 |
+
"success": False,
|
| 170 |
+
"notes": "Model returned non-JSON text.",
|
| 171 |
+
"raw_text": part.text
|
| 172 |
+
}
|
| 173 |
+
elif part.inline_data is not None:
|
| 174 |
+
logger.info("Processing generated try-on image data...")
|
| 175 |
+
result_image_bytes = BytesIO(part.inline_data.data)
|
| 176 |
+
|
| 177 |
+
return result_summary, result_image_bytes
|
| 178 |
+
|
| 179 |
+
except Exception as e:
|
| 180 |
+
logger.error(f"Error during virtual try-on model call: {e}", exc_info=True)
|
| 181 |
+
raise
|
requirements.txt
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
annotated-doc==0.0.3
|
| 2 |
+
annotated-types==0.7.0
|
| 3 |
+
anyio==4.11.0
|
| 4 |
+
cachetools==6.2.1
|
| 5 |
+
certifi==2025.10.5
|
| 6 |
+
charset-normalizer==3.4.4
|
| 7 |
+
click==8.3.0
|
| 8 |
+
distro==1.9.0
|
| 9 |
+
fastapi==0.120.0
|
| 10 |
+
google-ai-generativelanguage==0.6.15
|
| 11 |
+
google-api-core==2.27.0
|
| 12 |
+
google-api-python-client==2.185.0
|
| 13 |
+
google-auth==2.41.1
|
| 14 |
+
google-auth-httplib2==0.2.0
|
| 15 |
+
google-genai==1.46.0
|
| 16 |
+
google-generativeai==0.8.5
|
| 17 |
+
googleapis-common-protos==1.71.0
|
| 18 |
+
groq==0.33.0
|
| 19 |
+
grpcio==1.76.0
|
| 20 |
+
grpcio-status==1.71.2
|
| 21 |
+
h11==0.16.0
|
| 22 |
+
httpcore==1.0.9
|
| 23 |
+
httplib2==0.31.0
|
| 24 |
+
httptools==0.7.1
|
| 25 |
+
httpx==0.28.1
|
| 26 |
+
idna==3.11
|
| 27 |
+
jsonpatch==1.33
|
| 28 |
+
jsonpointer==3.0.0
|
| 29 |
+
langchain-core==1.0.1
|
| 30 |
+
langchain-groq==1.0.0
|
| 31 |
+
langsmith==0.4.38
|
| 32 |
+
orjson==3.11.4
|
| 33 |
+
packaging==25.0
|
| 34 |
+
pillow==12.0.0
|
| 35 |
+
proto-plus==1.26.1
|
| 36 |
+
protobuf==5.29.5
|
| 37 |
+
pyasn1==0.6.1
|
| 38 |
+
pyasn1_modules==0.4.2
|
| 39 |
+
pydantic==2.12.3
|
| 40 |
+
pydantic-settings==2.11.0
|
| 41 |
+
pydantic_core==2.41.4
|
| 42 |
+
pyparsing==3.2.5
|
| 43 |
+
python-dotenv==1.2.0
|
| 44 |
+
python-multipart==0.0.20
|
| 45 |
+
PyYAML==6.0.3
|
| 46 |
+
requests==2.32.5
|
| 47 |
+
requests-toolbelt==1.0.0
|
| 48 |
+
rsa==4.9.1
|
| 49 |
+
sniffio==1.3.1
|
| 50 |
+
starlette==0.48.0
|
| 51 |
+
tenacity==9.1.2
|
| 52 |
+
tqdm==4.67.1
|
| 53 |
+
typing-inspection==0.4.2
|
| 54 |
+
typing_extensions==4.15.0
|
| 55 |
+
uritemplate==4.2.0
|
| 56 |
+
urllib3==2.5.0
|
| 57 |
+
uvicorn==0.38.0
|
| 58 |
+
uvloop==0.22.1
|
| 59 |
+
watchfiles==1.1.1
|
| 60 |
+
websockets==15.0.1
|
| 61 |
+
zstandard==0.25.0
|