|
from fastapi import FastAPI, File, UploadFile, HTTPException, Form |
|
from fastapi.responses import FileResponse |
|
from fastapi.staticfiles import StaticFiles |
|
import requests |
|
import os |
|
import uuid |
|
import shutil |
|
from tempfile import NamedTemporaryFile |
|
|
|
app = FastAPI() |
|
|
|
|
|
STATIC_DIR = "/app/static" |
|
os.makedirs(STATIC_DIR, exist_ok=True) |
|
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static") |
|
|
|
|
|
CHANGE_CLOTHES_API = os.environ.get('URL') |
|
|
|
@app.post("/try-on/") |
|
async def try_on( |
|
human_img: UploadFile = File(...), |
|
garment_img: UploadFile = File(...), |
|
garment_desc: str = Form("dresses"), |
|
category: str = Form("dresses") |
|
): |
|
try: |
|
|
|
human_filename = f"{uuid.uuid4()}_{human_img.filename}" |
|
garment_filename = f"{uuid.uuid4()}_{garment_img.filename}" |
|
|
|
|
|
human_path = os.path.join(STATIC_DIR, human_filename) |
|
garment_path = os.path.join(STATIC_DIR, garment_filename) |
|
|
|
try: |
|
|
|
with open(human_path, "wb") as f: |
|
shutil.copyfileobj(human_img.file, f) |
|
|
|
with open(garment_path, "wb") as f: |
|
shutil.copyfileobj(garment_img.file, f) |
|
|
|
|
|
base_url = "https://tejani-tryapi.hf.space" |
|
human_url = f"{base_url}/static/{human_filename}" |
|
garment_url = f"{base_url}/static/{garment_filename}" |
|
|
|
print(human_url) |
|
print(garment_url) |
|
|
|
|
|
headers = { |
|
"accept": "*/*", |
|
"f": str(uuid.uuid4()).replace("-", ""), |
|
} |
|
|
|
data = { |
|
"humanImg": human_url, |
|
"garment": garment_url, |
|
"garmentDesc": garment_desc, |
|
"category": category, |
|
} |
|
|
|
|
|
response = requests.post(CHANGE_CLOTHES_API, headers=headers, data=data, timeout=60) |
|
|
|
|
|
if response.status_code != 200: |
|
raise HTTPException(status_code=response.status_code, detail="Error calling ChangeClothesAI API") |
|
|
|
|
|
|
|
|
|
|
|
return response.json() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
finally: |
|
human_img.file.close() |
|
garment_img.file.close() |
|
|
|
except Exception as e: |
|
raise HTTPException(status_code=500, detail=f"Error processing files: {str(e)}") |
|
|
|
if __name__ == "__main__": |
|
import uvicorn |
|
uvicorn.run(app, host="0.0.0.0", port=7860) |