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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -19
app.py CHANGED
@@ -7,6 +7,8 @@ from fastapi.responses import HTMLResponse
7
  import uuid
8
  from pathlib import Path
9
  import logging
 
 
10
 
11
  # Set up logging
12
  logging.basicConfig(level=logging.INFO)
@@ -26,6 +28,11 @@ app.add_middleware(
26
  # Mount static directory for serving files
27
  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
  # Alternative directory (uncomment to use /tmp/gradio)
@@ -59,12 +66,17 @@ async def save_file_and_get_url(file: UploadFile) -> str:
59
  content = await file.read()
60
  buffer.write(content)
61
 
62
- # Verify file exists
63
  if not file_path.exists():
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)
@@ -73,7 +85,7 @@ async def save_file_and_get_url(file: UploadFile) -> str:
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:
@@ -165,6 +177,40 @@ async def get_file(filename: str):
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():
@@ -172,10 +218,14 @@ async def test_upload_form():
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>
@@ -186,23 +236,37 @@ async def test_upload_form():
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)}")
 
7
  import uuid
8
  from pathlib import Path
9
  import logging
10
+ import os
11
+ import stat
12
 
13
  # Set up logging
14
  logging.basicConfig(level=logging.INFO)
 
28
  # Mount static directory for serving files
29
  STATIC_DIR = Path("/home/user/app/static")
30
  STATIC_DIR.mkdir(parents=True, exist_ok=True)
31
+ # Set directory permissions to ensure accessibility
32
+ try:
33
+ os.chmod(STATIC_DIR, stat.S_IRWXU | stat.S_IRWXG | stat.S_IROTH | stat.S_IXOTH)
34
+ except Exception as e:
35
+ logger.error(f"Failed to set permissions for {STATIC_DIR}: {str(e)}")
36
  app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
37
 
38
  # Alternative directory (uncomment to use /tmp/gradio)
 
66
  content = await file.read()
67
  buffer.write(content)
68
 
69
+ # Verify file exists and set permissions
70
  if not file_path.exists():
71
  logger.error(f"File {file_path} was not saved correctly")
72
  raise HTTPException(status_code=500, detail="Failed to save file")
73
+ try:
74
+ os.chmod(file_path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IROTH)
75
+ logger.info(f"Set permissions for {file_path}")
76
+ except Exception as e:
77
+ logger.error(f"Failed to set permissions for {file_path}: {str(e)}")
78
 
79
+ # Generate public URL
80
  space_id = "tejani-tryapi"
81
  public_url = f"https://{space_id}.hf.space/static/{unique_filename}"
82
  # Alternative URL for /tmp/gradio (uncomment if using /tmp/gradio)
 
85
 
86
  # Test URL accessibility
87
  try:
88
+ response = requests.head(public_url, timeout=20)
89
  if response.status_code != 200:
90
  logger.warning(f"Public URL {public_url} returned status {response.status_code}")
91
  else:
 
177
  logger.error(f"Error serving file {filename}: {str(e)}")
178
  raise HTTPException(status_code=500, detail=f"Error serving file: {str(e)}")
179
 
180
+ # Debug endpoint to check file existence and permissions
181
+ @app.get("/check-file/{filename}")
182
+ async def check_file(filename: str):
183
+ try:
184
+ file_path = STATIC_DIR / filename
185
+ if not file_path.exists():
186
+ logger.error(f"File {file_path} not found")
187
+ raise HTTPException(status_code=404, detail="File not found")
188
+
189
+ stats = os.stat(file_path)
190
+ permissions = oct(stats.st_mode)[-3:]
191
+ logger.info(f"File {file_path} exists with permissions {permissions}")
192
+ return {
193
+ "file": str(file_path),
194
+ "exists": True,
195
+ "permissions": permissions
196
+ }
197
+ except Exception as e:
198
+ logger.error(f"Error checking file {filename}: {str(e)}")
199
+ raise HTTPException(status_code=500, detail=f"Error checking file: {str(e)}")
200
+
201
+ # Endpoint to clean stored files
202
+ @app.get("/clean-files")
203
+ async def clean_files():
204
+ try:
205
+ for f in STATIC_DIR.glob("*"):
206
+ if f.is_file():
207
+ f.unlink()
208
+ logger.info(f"Cleaned all files in {STATIC_DIR}")
209
+ return {"message": "Files cleaned"}
210
+ except Exception as e:
211
+ logger.error(f"Error cleaning files: {str(e)}")
212
+ raise HTTPException(status_code=500, detail=f"Error cleaning files: {str(e)}")
213
+
214
  # Frontend for testing file uploads
215
  @app.get("/test-upload", response_class=HTMLResponse)
216
  async def test_upload_form():
 
218
  <html>
219
  <head>
220
  <title>Test File Upload</title>
221
+ <style>
222
+ body { font-family: Arial, sans-serif; margin: 20px; }
223
+ .response { margin-top: 20px; padding: 10px; border: 1px solid #ccc; }
224
+ </style>
225
  </head>
226
  <body>
227
  <h1>Test File Upload</h1>
228
+ <form action="/try-on" method="post" enctype="multipart/form-data" onsubmit="showResponse(event)">
229
  <label for="human_img">Human Image (JPG/PNG):</label><br>
230
  <input type="file" id="human_img" name="human_img" accept=".jpg,.jpeg,.png" required><br><br>
231
  <label for="garment">Garment Image (JPG/PNG):</label><br>
 
236
  <input type="text" id="category" name="category" value="upper_body"><br><br>
237
  <input type="submit" value="Upload and Try On">
238
  </form>
239
+ <div id="response" class="response" style="display: none;"></div>
240
  <h2>Debug Tools</h2>
241
  <p><a href="/list-files">List Stored Files</a></p>
242
+ <p><a href="/clean-files">Clean Stored Files</a></p>
243
+ <script>
244
+ async function showResponse(event) {
245
+ event.preventDefault();
246
+ const form = event.target;
247
+ const formData = new FormData(form);
248
+ try {
249
+ const response = await fetch('/try-on', {
250
+ method: 'POST',
251
+ body: formData
252
+ });
253
+ const result = await response.json();
254
+ const responseDiv = document.getElementById('response');
255
+ responseDiv.style.display = 'block';
256
+ responseDiv.innerHTML = `
257
+ <h3>Response</h3>
258
+ <p><strong>Status Code:</strong> ${result.status_code}</p>
259
+ <p><strong>Human Image URL:</strong> <a href="${result.human_img_url}" target="_blank">${result.human_img_url}</a></p>
260
+ <p><strong>Garment URL:</strong> <a href="${result.garment_url}" target="_blank">${result.garment_url}</a></p>
261
+ <p><strong>API Response:</strong> <pre>${JSON.stringify(result.response, null, 2)}</pre></p>
262
+ `;
263
+ } catch (error) {
264
+ document.getElementById('response').style.display = 'block';
265
+ document.getElementById('response').innerHTML = `<p><strong>Error:</strong> ${error.message}</p>`;
266
+ }
267
+ }
268
+ </script>
269
  </body>
270
  </html>
271
  """
272
+ return HTMLResponse(content=html_content)