tejani commited on
Commit
61a3a58
·
verified ·
1 Parent(s): b83b8f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -15
app.py CHANGED
@@ -2,6 +2,7 @@ from fastapi import FastAPI, HTTPException, UploadFile, File
2
  from pydantic import BaseModel
3
  import requests
4
  from fastapi.middleware.cors import CORSMiddleware
 
5
  import os
6
  import uuid
7
  from pathlib import Path
@@ -13,31 +14,40 @@ logger = logging.getLogger(__name__)
13
 
14
  app = FastAPI()
15
 
16
- # Add CORS middleware to allow requests from Hugging Face Spaces frontend
17
  app.add_middleware(
18
  CORSMiddleware,
19
- allow_origins=["*"], # Adjust for production to specific origins
20
  allow_credentials=True,
21
  allow_methods=["*"],
22
  allow_headers=["*"],
23
  )
24
 
 
 
 
 
 
25
  # Define the request model
26
  class TryOnRequest(BaseModel):
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}")
@@ -51,8 +61,8 @@ async def save_file_and_get_url(file: UploadFile) -> str:
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
- public_url = f"https://tejani-tryapi.hf.space/file={str(file_path)}"
56
  logger.info(f"Generated public URL: {public_url}")
57
 
58
  # Test URL accessibility
@@ -60,6 +70,8 @@ async def save_file_and_get_url(file: UploadFile) -> str:
60
  response = requests.head(public_url, timeout=5)
61
  if response.status_code != 200:
62
  logger.warning(f"Public URL {public_url} returned status {response.status_code}")
 
 
63
  except requests.exceptions.RequestException as e:
64
  logger.error(f"Failed to access public URL {public_url}: {str(e)}")
65
 
@@ -68,7 +80,7 @@ async def save_file_and_get_url(file: UploadFile) -> str:
68
  logger.error(f"Error in save_file_and_get_url: {str(e)}")
69
  raise HTTPException(status_code=500, detail=f"Error processing file: {str(e)}")
70
 
71
- # Updated endpoint to handle file uploads and proxy the request
72
  @app.post("/try-on")
73
  async def try_on(
74
  human_img: UploadFile = File(...),
@@ -109,13 +121,13 @@ async def try_on(
109
  "garment_url": garment_url
110
  }
111
  except requests.exceptions.RequestException as e:
112
- logger.error(f"Error forwarding request: {str(e)}")
113
  raise HTTPException(status_code=500, detail=f"Error forwarding request: {str(e)}")
114
  except Exception as e:
115
  logger.error(f"Error in try_on endpoint: {str(e)}")
116
  raise HTTPException(status_code=500, detail=f"Error processing request: {str(e)}")
117
 
118
- # Health check endpoint for Hugging Face Spaces
119
  @app.get("/")
120
  async def root():
121
  return {"message": "FastAPI proxy for try-on API with file upload is running"}
@@ -124,8 +136,8 @@ async def root():
124
  @app.get("/list-files")
125
  async def list_files():
126
  try:
127
- files = [str(f) for f in UPLOAD_DIR.glob("*") if f.is_file()]
128
- logger.info(f"Files in {UPLOAD_DIR}: {files}")
129
  return {"files": files}
130
  except Exception as e:
131
  logger.error(f"Error listing files: {str(e)}")
 
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
 
14
 
15
  app = FastAPI()
16
 
17
+ # Add CORS middleware
18
  app.add_middleware(
19
  CORSMiddleware,
20
+ allow_origins=["*"], # Adjust for production
21
  allow_credentials=True,
22
  allow_methods=["*"],
23
  allow_headers=["*"],
24
  )
25
 
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
  # Define the request model
32
  class TryOnRequest(BaseModel):
33
  garmentDesc: str
34
  category: str
35
 
36
+ # Allowed file extensions
37
+ ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png"}
 
38
 
39
  # Helper function to save file and generate public URL
40
  async def save_file_and_get_url(file: UploadFile) -> str:
41
  try:
42
+ # Validate file extension
43
+ file_extension = f".{file.filename.split('.')[-1].lower()}"
44
+ if file_extension not in ALLOWED_EXTENSIONS:
45
+ logger.error(f"Invalid file extension for {file.filename}: {file_extension}")
46
+ raise HTTPException(status_code=400, detail=f"File extension {file_extension} not allowed. Use JPG or PNG.")
47
+
48
  # Generate unique filename
49
+ unique_filename = f"{uuid.uuid4()}{file_extension}"
50
+ file_path = STATIC_DIR / unique_filename
 
51
 
52
  # Save file
53
  logger.info(f"Saving file to {file_path}")
 
61
  raise HTTPException(status_code=500, detail="Failed to save file")
62
 
63
  # Generate public URL
64
+ space_id = os.getenv("SPACE_ID", "tejani-tryapi")
65
+ public_url = f"https://{space_id}.hf.space/static/{unique_filename}"
66
  logger.info(f"Generated public URL: {public_url}")
67
 
68
  # Test URL accessibility
 
70
  response = requests.head(public_url, timeout=5)
71
  if response.status_code != 200:
72
  logger.warning(f"Public URL {public_url} returned status {response.status_code}")
73
+ else:
74
+ logger.info(f"Public URL {public_url} is accessible")
75
  except requests.exceptions.RequestException as e:
76
  logger.error(f"Failed to access public URL {public_url}: {str(e)}")
77
 
 
80
  logger.error(f"Error in save_file_and_get_url: {str(e)}")
81
  raise HTTPException(status_code=500, detail=f"Error processing file: {str(e)}")
82
 
83
+ # Endpoint to handle file uploads and proxy the request
84
  @app.post("/try-on")
85
  async def try_on(
86
  human_img: UploadFile = File(...),
 
121
  "garment_url": garment_url
122
  }
123
  except requests.exceptions.RequestException as e:
124
+ logger.error(f"Error forwarding request: {unofficial: {str(e)}")
125
  raise HTTPException(status_code=500, detail=f"Error forwarding request: {str(e)}")
126
  except Exception as e:
127
  logger.error(f"Error in try_on endpoint: {str(e)}")
128
  raise HTTPException(status_code=500, detail=f"Error processing request: {str(e)}")
129
 
130
+ # Health check endpoint
131
  @app.get("/")
132
  async def root():
133
  return {"message": "FastAPI proxy for try-on API with file upload is running"}
 
136
  @app.get("/list-files")
137
  async def list_files():
138
  try:
139
+ files = [str(f) for f in STATIC_DIR.glob("*") if f.is_file()]
140
+ logger.info(f"Files in {STATIC_DIR}: {files}")
141
  return {"files": files}
142
  except Exception as e:
143
  logger.error(f"Error listing files: {str(e)}")