RateMyLook / app.py
ak0601's picture
Update app.py
c58036e verified
raw
history blame
2.17 kB
from fastapi import FastAPI, File, UploadFile, Form
from fastapi.responses import JSONResponse
import tempfile
from dotenv import load_dotenv
import os
import google.generativeai as genai
import json
import logging
load_dotenv()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
API_KEY = os.getenv("GOOGLE_API_KEY")
genai.configure(api_key=API_KEY)
model = genai.GenerativeModel("gemini-2.0-flash")
@app.post("/rate-outfit/")
async def rate_outfit(image: UploadFile = File(...), category: str = Form(...)):
if image.content_type not in ["image/jpeg", "image/png", "image/jpg"]:
return JSONResponse(content={"message": "Please review the image before uploading"})
tmp_path = None
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(image.filename)[1]) as tmp:
tmp.write(await image.read())
tmp_path = tmp.name
uploaded_file = genai.upload_file(path=tmp_path, display_name=image.filename)
prompt = (
f"You are an AI fashion assistant. Based on the category '{category}', analyze the provided image. "
"Extract the following information and provide the response ONLY as a valid JSON object, without explanations. "
"Schema: {\"Tag\": \"catchy phrase\", \"Feedback\": \"concise advice\"}. "
"If inappropriate, respond ONLY with {\"error\": \"Please upload an appropriate image\"}."
)
response = model.generate_content([prompt, uploaded_file])
result = json.loads(response.text.strip().replace('```json', '').replace('```', '').strip())
if "error" in result:
return JSONResponse(content={"message": "Please review the image before uploading"})
return JSONResponse(content=result)
except Exception as e:
logger.error(f"Error: {e}")
return JSONResponse(content={"message": "Please review the image before uploading"})
finally:
if tmp_path and os.path.exists(tmp_path):
os.remove(tmp_path)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)