triflix commited on
Commit
c0942d9
·
verified ·
1 Parent(s): 8563ad4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -0
app.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+ import shutil
4
+ from typing import Optional
5
+
6
+ from fastapi import FastAPI, Request, UploadFile, File, Form
7
+ from fastapi.responses import JSONResponse, HTMLResponse
8
+ from fastapi.staticfiles import StaticFiles
9
+ from fastapi.templating import Jinja2Templates
10
+ from fastapi.encoders import jsonable_encoder
11
+
12
+ # Assumes pipeline_with_agents.py (with process_file and to_json_serializable) is in same folder
13
+ from pipeline_with_agents import process_file, to_json_serializable
14
+
15
+ app = FastAPI()
16
+
17
+ # Templates folder named "templates"
18
+ templates = Jinja2Templates(directory="templates")
19
+
20
+ # Ensure tmp dir exists and is writable (Hugging Face requires writable /tmp)
21
+ TMP_DIR = os.environ.get("TMPDIR", "/tmp")
22
+ os.makedirs(TMP_DIR, exist_ok=True)
23
+
24
+ @app.get("/", response_class=HTMLResponse)
25
+ async def index(request: Request):
26
+ return templates.TemplateResponse("index.html", {"request": request})
27
+
28
+ @app.post("/analyze")
29
+ async def analyze(file: UploadFile = File(...), sheet: Optional[str] = Form(None)):
30
+ # Save to a tmp file under TMP_DIR
31
+ suffix = os.path.splitext(file.filename)[1] or ".xlsx"
32
+ with tempfile.NamedTemporaryFile(dir=TMP_DIR, delete=False, suffix=suffix) as tmp:
33
+ tmp_path = tmp.name
34
+ content = await file.read()
35
+ tmp.write(content)
36
+
37
+ try:
38
+ # Call the user's pipeline. This returns a serializable python dict.
39
+ result = process_file(tmp_path, sheet=sheet, model=os.environ.get("GEMINI_MODEL", "gemini-2.5-flash-lite"))
40
+ # Convert non-json-native numpy/pandas types
41
+ json_safe = jsonable_encoder(result, custom_encoder={})
42
+ return JSONResponse(content=json_safe)
43
+ finally:
44
+ try:
45
+ os.remove(tmp_path)
46
+ except Exception:
47
+ pass
48
+
49
+ # Small health endpoint
50
+ @app.get("/healthz")
51
+ async def health():
52
+ return {"status": "ok"}