Spaces:
Running
Running
Update app/main.py
Browse files- app/main.py +19 -6
app/main.py
CHANGED
@@ -72,19 +72,32 @@ async def predict(file: UploadFile = File(...)):
|
|
72 |
if not success:
|
73 |
raise HTTPException(status_code=500, detail="Model failed to load")
|
74 |
|
75 |
-
# Validate file type
|
76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
raise HTTPException(status_code=400, detail="File must be an image")
|
78 |
|
79 |
# Read and process image
|
80 |
logger.info(f"Processing image: {file.filename}")
|
81 |
image_data = await file.read()
|
82 |
|
83 |
-
# Optimize image processing
|
84 |
try:
|
85 |
image = Image.open(io.BytesIO(image_data))
|
86 |
-
|
87 |
-
image
|
|
|
|
|
|
|
|
|
88 |
|
89 |
# Resize large images to improve speed
|
90 |
max_size = (1024, 1024)
|
@@ -94,7 +107,7 @@ async def predict(file: UploadFile = File(...)):
|
|
94 |
|
95 |
except Exception as e:
|
96 |
logger.error(f"Image processing error: {e}")
|
97 |
-
raise HTTPException(status_code=400, detail="Invalid image
|
98 |
|
99 |
# Run prediction with timeout
|
100 |
try:
|
|
|
72 |
if not success:
|
73 |
raise HTTPException(status_code=500, detail="Model failed to load")
|
74 |
|
75 |
+
# Validate file type - more robust approach
|
76 |
+
# Don't rely solely on content_type as it might be incorrect
|
77 |
+
valid_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']
|
78 |
+
filename_lower = (file.filename or '').lower()
|
79 |
+
|
80 |
+
# Check both content type and file extension
|
81 |
+
is_valid_content_type = file.content_type and file.content_type.startswith('image/')
|
82 |
+
is_valid_extension = any(filename_lower.endswith(ext) for ext in valid_extensions)
|
83 |
+
|
84 |
+
if not (is_valid_content_type or is_valid_extension):
|
85 |
+
logger.warning(f"Invalid file type: content_type={file.content_type}, filename={file.filename}")
|
86 |
raise HTTPException(status_code=400, detail="File must be an image")
|
87 |
|
88 |
# Read and process image
|
89 |
logger.info(f"Processing image: {file.filename}")
|
90 |
image_data = await file.read()
|
91 |
|
92 |
+
# Optimize image processing with better error handling
|
93 |
try:
|
94 |
image = Image.open(io.BytesIO(image_data))
|
95 |
+
|
96 |
+
# Verify it's actually an image by trying to get basic info
|
97 |
+
image.verify() # This will raise an exception if not a valid image
|
98 |
+
|
99 |
+
# Reopen the image since verify() closes it
|
100 |
+
image = Image.open(io.BytesIO(image_data)).convert("RGB")
|
101 |
|
102 |
# Resize large images to improve speed
|
103 |
max_size = (1024, 1024)
|
|
|
107 |
|
108 |
except Exception as e:
|
109 |
logger.error(f"Image processing error: {e}")
|
110 |
+
raise HTTPException(status_code=400, detail="Invalid or corrupted image file")
|
111 |
|
112 |
# Run prediction with timeout
|
113 |
try:
|