Update app.py
Browse files
app.py
CHANGED
@@ -5,6 +5,11 @@ from fastapi.middleware.cors import CORSMiddleware
|
|
5 |
import os
|
6 |
import uuid
|
7 |
from pathlib import Path
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
app = FastAPI()
|
10 |
|
@@ -22,25 +27,47 @@ class TryOnRequest(BaseModel):
|
|
22 |
garmentDesc: str
|
23 |
category: str
|
24 |
|
25 |
-
# Base directory for
|
26 |
UPLOAD_DIR = Path("/tmp/gradio")
|
27 |
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
28 |
|
29 |
# Helper function to save file and generate public URL
|
30 |
async def save_file_and_get_url(file: UploadFile) -> str:
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
# Updated endpoint to handle file uploads and proxy the request
|
46 |
@app.post("/try-on")
|
@@ -60,7 +87,7 @@ async def try_on(
|
|
60 |
|
61 |
headers = {
|
62 |
"accept": "*/*",
|
63 |
-
"f": "
|
64 |
}
|
65 |
|
66 |
data = {
|
@@ -70,6 +97,8 @@ async def try_on(
|
|
70 |
"category": category
|
71 |
}
|
72 |
|
|
|
|
|
73 |
# Forward request to the original API
|
74 |
response = requests.post(url, headers=headers, cookies={}, data=data)
|
75 |
response.raise_for_status()
|
@@ -81,11 +110,24 @@ async def try_on(
|
|
81 |
"garment_url": garment_url
|
82 |
}
|
83 |
except requests.exceptions.RequestException as e:
|
|
|
84 |
raise HTTPException(status_code=500, detail=f"Error forwarding request: {str(e)}")
|
85 |
except Exception as e:
|
86 |
-
|
|
|
87 |
|
88 |
# Health check endpoint for Hugging Face Spaces
|
89 |
@app.get("/")
|
90 |
async def root():
|
91 |
-
return {"message": "FastAPI proxy for try-on API with file upload is running"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
import os
|
6 |
import uuid
|
7 |
from pathlib import Path
|
8 |
+
import logging
|
9 |
+
|
10 |
+
# Set up logging
|
11 |
+
logging.basicConfig(level=logging.INFO)
|
12 |
+
logger = logging.getLogger(__name__)
|
13 |
|
14 |
app = FastAPI()
|
15 |
|
|
|
27 |
garmentDesc: str
|
28 |
category: str
|
29 |
|
30 |
+
# Base directory for file storage (use /tmp/gradio for Hugging Face Spaces)
|
31 |
UPLOAD_DIR = Path("/tmp/gradio")
|
32 |
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
33 |
|
34 |
# Helper function to save file and generate public URL
|
35 |
async def save_file_and_get_url(file: UploadFile) -> str:
|
36 |
+
try:
|
37 |
+
# Generate unique filename
|
38 |
+
file_extension = file.filename.split(".")[-1]
|
39 |
+
unique_filename = f"{uuid.uuid4()}.{file_extension}"
|
40 |
+
file_path = UPLOAD_DIR / unique_filename
|
41 |
+
|
42 |
+
# Save file
|
43 |
+
logger.info(f"Saving file to {file_path}")
|
44 |
+
with file_path.open("wb") as buffer:
|
45 |
+
content = await file.read()
|
46 |
+
buffer.write(content)
|
47 |
+
|
48 |
+
# Verify file exists
|
49 |
+
if not file_path.exists():
|
50 |
+
logger.error(f"File {file_path} was not saved correctly")
|
51 |
+
raise HTTPException(status_code=500, detail="Failed to save file")
|
52 |
+
|
53 |
+
# Generate public URL
|
54 |
+
# Use SPACE_ID environment variable or fallback to placeholder
|
55 |
+
space_id = os.getenv("SPACE_ID", "your-username-space-name")
|
56 |
+
public_url = f"https://tejani-tryapi.hf.space/file={str(file_path)}"
|
57 |
+
logger.info(f"Generated public URL: {public_url}")
|
58 |
+
|
59 |
+
# Test URL accessibility
|
60 |
+
try:
|
61 |
+
response = requests.head(public_url, timeout=5)
|
62 |
+
if response.status_code != 200:
|
63 |
+
logger.warning(f"Public URL {public_url} returned status {response.status_code}")
|
64 |
+
except requests.exceptions.RequestException as e:
|
65 |
+
logger.error(f"Failed to access public URL {public_url}: {str(e)}")
|
66 |
+
|
67 |
+
return public_url
|
68 |
+
except Exception as e:
|
69 |
+
logger.error(f"Error in save_file_and_get_url: {str(e)}")
|
70 |
+
raise HTTPException(status_code=500, detail=f"Error processing file: {str(e)}")
|
71 |
|
72 |
# Updated endpoint to handle file uploads and proxy the request
|
73 |
@app.post("/try-on")
|
|
|
87 |
|
88 |
headers = {
|
89 |
"accept": "*/*",
|
90 |
+
"f": "sdfdsfsKaVgUoxa5j1jzcFtziPx",
|
91 |
}
|
92 |
|
93 |
data = {
|
|
|
97 |
"category": category
|
98 |
}
|
99 |
|
100 |
+
logger.info(f"Forwarding request to {url} with data: {data}")
|
101 |
+
|
102 |
# Forward request to the original API
|
103 |
response = requests.post(url, headers=headers, cookies={}, data=data)
|
104 |
response.raise_for_status()
|
|
|
110 |
"garment_url": garment_url
|
111 |
}
|
112 |
except requests.exceptions.RequestException as e:
|
113 |
+
logger.error(f"Error forwarding request: {str(e)}")
|
114 |
raise HTTPException(status_code=500, detail=f"Error forwarding request: {str(e)}")
|
115 |
except Exception as e:
|
116 |
+
logger.error(f"Error in try_on endpoint: {str(e)}")
|
117 |
+
raise HTTPException(status_code=500, detail=f"Error processing request: {str(e)}")
|
118 |
|
119 |
# Health check endpoint for Hugging Face Spaces
|
120 |
@app.get("/")
|
121 |
async def root():
|
122 |
+
return {"message": "FastAPI proxy for try-on API with file upload is running"}
|
123 |
+
|
124 |
+
# Debug endpoint to list stored files
|
125 |
+
@app.get("/list-files")
|
126 |
+
async def list_files():
|
127 |
+
try:
|
128 |
+
files = [str(f) for f in UPLOAD_DIR.glob("*") if f.is_file()]
|
129 |
+
logger.info(f"Files in {UPLOAD_DIR}: {files}")
|
130 |
+
return {"files": files}
|
131 |
+
except Exception as e:
|
132 |
+
logger.error(f"Error listing files: {str(e)}")
|
133 |
+
raise HTTPException(status_code=500, detail=f"Error listing files: {str(e)}")
|