Spaces:
Sleeping
Sleeping
shrijayan
commited on
Commit
·
99d76a5
1
Parent(s):
86fffcf
Refactor file upload handling to support single file processing and improve error handling
Browse files
main.py
CHANGED
@@ -11,10 +11,14 @@ from fastapi.middleware.cors import CORSMiddleware
|
|
11 |
app = FastAPI()
|
12 |
logger = setup_logging()
|
13 |
|
|
|
|
|
|
|
|
|
14 |
|
15 |
app.add_middleware(
|
16 |
CORSMiddleware,
|
17 |
-
allow_origins=
|
18 |
allow_credentials=True,
|
19 |
allow_methods=["*"],
|
20 |
allow_headers=["*"],
|
@@ -94,24 +98,40 @@ def extract_address_data(file_stream):
|
|
94 |
|
95 |
@app.post("/upload")
|
96 |
async def upload_files(files: list[UploadFile] = File(...)):
|
97 |
-
"""Handle
|
98 |
try:
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
|
116 |
except Exception as e:
|
117 |
logger.error(f"Processing error: {str(e)}")
|
|
|
11 |
app = FastAPI()
|
12 |
logger = setup_logging()
|
13 |
|
14 |
+
allow_origins = [
|
15 |
+
"https://*.hf.space",
|
16 |
+
"http://localhost:7860"
|
17 |
+
]
|
18 |
|
19 |
app.add_middleware(
|
20 |
CORSMiddleware,
|
21 |
+
allow_origins=allow_origins,
|
22 |
allow_credentials=True,
|
23 |
allow_methods=["*"],
|
24 |
allow_headers=["*"],
|
|
|
98 |
|
99 |
@app.post("/upload")
|
100 |
async def upload_files(files: list[UploadFile] = File(...)):
|
101 |
+
"""Handle file uploads and return processed file(s)"""
|
102 |
try:
|
103 |
+
if len(files) == 1:
|
104 |
+
# Handle single file
|
105 |
+
file = files[0]
|
106 |
+
if not allowed_file(file.filename):
|
107 |
+
raise HTTPException(status_code=400, detail="Invalid file type")
|
108 |
+
|
109 |
+
file_stream = await file.read()
|
110 |
+
output = process_uploaded_file(BytesIO(file_stream))
|
111 |
+
|
112 |
+
return StreamingResponse(
|
113 |
+
output,
|
114 |
+
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
115 |
+
headers={"Content-Disposition": f"attachment; filename=processed_{file.filename}"}
|
116 |
+
)
|
117 |
+
else:
|
118 |
+
# Handle multiple files as ZIP
|
119 |
+
zip_buffer = BytesIO()
|
120 |
+
with zipfile.ZipFile(zip_buffer, 'a', zipfile.ZIP_DEFLATED) as zip_file:
|
121 |
+
for file in files:
|
122 |
+
if not allowed_file(file.filename):
|
123 |
+
continue
|
124 |
+
|
125 |
+
file_stream = await file.read()
|
126 |
+
output = process_uploaded_file(BytesIO(file_stream))
|
127 |
+
zip_file.writestr(f"processed_{file.filename}", output.getvalue())
|
128 |
+
|
129 |
+
zip_buffer.seek(0)
|
130 |
+
return StreamingResponse(
|
131 |
+
zip_buffer,
|
132 |
+
media_type="application/zip",
|
133 |
+
headers={"Content-Disposition": "attachment; filename=processed_files.zip"}
|
134 |
+
)
|
135 |
|
136 |
except Exception as e:
|
137 |
logger.error(f"Processing error: {str(e)}")
|