triflix commited on
Commit
bda6ce3
·
verified ·
1 Parent(s): 1e56d5e

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +61 -0
main.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app/main.py
2
+ import os
3
+ import uuid
4
+ import json
5
+ import logging
6
+
7
+ from fastapi import FastAPI, UploadFile, File, Form, HTTPException
8
+ from fastapi.middleware.cors import CORSMiddleware
9
+ from starlette.responses import JSONResponse
10
+
11
+ from .pipeline import process_file
12
+
13
+ logger = logging.getLogger("uvicorn.error")
14
+ app = FastAPI(title="HF-Space Data Pipeline API")
15
+
16
+ app.add_middleware(
17
+ CORSMiddleware,
18
+ allow_origins=["*"],
19
+ allow_methods=["*"],
20
+ allow_headers=["*"],
21
+ )
22
+
23
+ TMP_DIR = os.getenv("TMP_DIR", "/tmp")
24
+ os.makedirs(TMP_DIR, exist_ok=True)
25
+
26
+ @app.get("/health")
27
+ def health():
28
+ return {"status": "ok"}
29
+
30
+ @app.post("/process-file")
31
+ async def process_file_endpoint(file: UploadFile = File(...), sheet: str = Form(None)):
32
+ # save uploaded file to /tmp and process synchronously (deterministic)
33
+ filename = file.filename or f"upload-{uuid.uuid4().hex}"
34
+ safe_name = f"{uuid.uuid4().hex}-{filename}"
35
+ path = os.path.join(TMP_DIR, safe_name)
36
+ try:
37
+ contents = await file.read()
38
+ with open(path, "wb") as f:
39
+ f.write(contents)
40
+ except Exception as e:
41
+ raise HTTPException(status_code=500, detail=f"failed to save upload: {e}")
42
+
43
+ try:
44
+ result = process_file(path, sheet=sheet)
45
+ except Exception as e:
46
+ logger.exception("processing failed")
47
+ raise HTTPException(status_code=500, detail=f"processing failed: {e}")
48
+
49
+ return JSONResponse(content=result)
50
+
51
+ # convenience route to process an existing file path inside the container (dev/testing)
52
+ @app.post("/process-path")
53
+ def process_path_endpoint(path: str, sheet: str = None):
54
+ if not os.path.exists(path):
55
+ raise HTTPException(status_code=404, detail="file not found")
56
+ try:
57
+ result = process_file(path, sheet=sheet)
58
+ except Exception as e:
59
+ logger.exception("processing failed")
60
+ raise HTTPException(status_code=500, detail=f"processing failed: {e}")
61
+ return JSONResponse(content=result)