tejani commited on
Commit
dba2f84
·
verified ·
1 Parent(s): e522daa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -6
app.py CHANGED
@@ -1,9 +1,9 @@
1
- from fastapi import FastAPI, HTTPException, UploadFile, File
2
  from pydantic import BaseModel
3
  import requests
4
  from fastapi.middleware.cors import CORSMiddleware
5
  from fastapi.staticfiles import StaticFiles
6
- import os
7
  import uuid
8
  from pathlib import Path
9
  import logging
@@ -28,6 +28,10 @@ STATIC_DIR = Path("/home/user/app/static")
28
  STATIC_DIR.mkdir(parents=True, exist_ok=True)
29
  app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
30
 
 
 
 
 
31
  # Define the request model
32
  class TryOnRequest(BaseModel):
33
  garmentDesc: str
@@ -60,12 +64,16 @@ async def save_file_and_get_url(file: UploadFile) -> str:
60
  logger.error(f"File {file_path} was not saved correctly")
61
  raise HTTPException(status_code=500, detail="Failed to save file")
62
 
63
- public_url = f"https://tejani-tryapi.hf.space/static/{unique_filename}"
 
 
 
 
64
  logger.info(f"Generated public URL: {public_url}")
65
 
66
  # Test URL accessibility
67
  try:
68
- response = requests.head(public_url, timeout=5)
69
  if response.status_code != 200:
70
  logger.warning(f"Public URL {public_url} returned status {response.status_code}")
71
  else:
@@ -96,7 +104,7 @@ async def try_on(
96
 
97
  headers = {
98
  "accept": "*/*",
99
- "f": "sdasdwsKaVgUoxa5j1jzcFtziPx",
100
  }
101
 
102
  data = {
@@ -139,4 +147,62 @@ async def list_files():
139
  return {"files": files}
140
  except Exception as e:
141
  logger.error(f"Error listing files: {str(e)}")
142
- raise HTTPException(status_code=500, detail=f"Error listing files: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, UploadFile, File, Response
2
  from pydantic import BaseModel
3
  import requests
4
  from fastapi.middleware.cors import CORSMiddleware
5
  from fastapi.staticfiles import StaticFiles
6
+ from fastapi.responses import HTMLResponse
7
  import uuid
8
  from pathlib import Path
9
  import logging
 
28
  STATIC_DIR.mkdir(parents=True, exist_ok=True)
29
  app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
30
 
31
+ # Alternative directory (uncomment to use /tmp/gradio)
32
+ # STATIC_DIR = Path("/tmp/gradio")
33
+ # STATIC_DIR.mkdir(parents=True, exist_ok=True)
34
+
35
  # Define the request model
36
  class TryOnRequest(BaseModel):
37
  garmentDesc: str
 
64
  logger.error(f"File {file_path} was not saved correctly")
65
  raise HTTPException(status_code=500, detail="Failed to save file")
66
 
67
+ # Generate public URL with hardcoded space_id
68
+ space_id = "tejani-tryapi"
69
+ public_url = f"https://{space_id}.hf.space/static/{unique_filename}"
70
+ # Alternative URL for /tmp/gradio (uncomment if using /tmp/gradio)
71
+ # public_url = f"https://{space_id}.hf.space/file={str(file_path)}"
72
  logger.info(f"Generated public URL: {public_url}")
73
 
74
  # Test URL accessibility
75
  try:
76
+ response = requests.head(public_url, timeout=15)
77
  if response.status_code != 200:
78
  logger.warning(f"Public URL {public_url} returned status {response.status_code}")
79
  else:
 
104
 
105
  headers = {
106
  "accept": "*/*",
107
+ "f": "sdfdsfsKaVgUoxa5j1jzcFtziPx",
108
  }
109
 
110
  data = {
 
147
  return {"files": files}
148
  except Exception as e:
149
  logger.error(f"Error listing files: {str(e)}")
150
+ raise HTTPException(status_code=500, detail=f"Error listing files: {str(e)}")
151
+
152
+ # Debug endpoint to manually serve a file
153
+ @app.get("/get-file/{filename}")
154
+ async def get_file(filename: str):
155
+ try:
156
+ file_path = STATIC_DIR / filename
157
+ if not file_path.exists():
158
+ logger.error(f"File {file_path} not found")
159
+ raise HTTPException(status_code=404, detail="File not found")
160
+
161
+ with file_path.open("rb") as f:
162
+ content = f.read()
163
+ return Response(content=content, media_type="image/jpeg")
164
+ except Exception as e:
165
+ logger.error(f"Error serving file {filename}: {str(e)}")
166
+ raise HTTPException(status_code=500, detail=f"Error serving file: {str(e)}")
167
+
168
+ # Frontend for testing file uploads
169
+ @app.get("/test-upload", response_class=HTMLResponse)
170
+ async def test_upload_form():
171
+ html_content = """
172
+ <html>
173
+ <head>
174
+ <title>Test File Upload</title>
175
+ </head>
176
+ <body>
177
+ <h1>Test File Upload</h1>
178
+ <form action="/try-on" method="post" enctype="multipart/form-data">
179
+ <label for="human_img">Human Image (JPG/PNG):</label><br>
180
+ <input type="file" id="human_img" name="human_img" accept=".jpg,.jpeg,.png" required><br><br>
181
+ <label for="garment">Garment Image (JPG/PNG):</label><br>
182
+ <input type="file" id="garment" name="garment" accept=".jpg,.jpeg,.png" required><br><br>
183
+ <label for="garment_desc">Garment Description:</label><br>
184
+ <input type="text" id="garment_desc" name="garment_desc" value=""><br><br>
185
+ <label for="category">Category:</label><br>
186
+ <input type="text" id="category" name="category" value="upper_body"><br><br>
187
+ <input type="submit" value="Upload and Try On">
188
+ </form>
189
+ <h2>Debug Tools</h2>
190
+ <p><a href="/list-files">List Stored Files</a></p>
191
+ <p><a href="/clean-files">Clean Stored unnamed: Files</a></p>
192
+ </body>
193
+ </html>
194
+ """
195
+ return HTMLResponse(content=html_content)
196
+
197
+ # Endpoint to clean stored files
198
+ @app.get("/clean-files")
199
+ async def clean_files():
200
+ try:
201
+ for f in STATIC_DIR.glob("*"):
202
+ if f.is_file():
203
+ f.unlink()
204
+ logger.info(f"Cleaned all files in {STATIC_DIR}")
205
+ return {"message": "Files cleaned"}
206
+ except Exception as e:
207
+ logger.error(f"Error cleaning files: {str(e)}")
208
+ raise HTTPException(status_code=500, detail=f"Error cleaning files: {str(e)}")