Spaces:
Running
Running
| # app.py | |
| import os | |
| import io | |
| import tempfile | |
| from fastapi import FastAPI, UploadFile, File, HTTPException | |
| from fastapi.responses import JSONResponse, FileResponse | |
| from ecg_model import predictor # your predictor instance | |
| import scipy.io | |
| app = FastAPI(title="ECG Analysis API") | |
| async def extract_signals(file: UploadFile = File(...)): | |
| """ | |
| Upload an ECG IMAGE (png/jpg). Returns extracted 12-lead signals (list of lists). | |
| """ | |
| try: | |
| content = await file.read() | |
| result = predictor.analyze_image(content, visualize=False) | |
| if result is None: | |
| raise HTTPException(status_code=400, detail="Failed to extract signals or analyze image") | |
| # return signals and basic metadata | |
| return JSONResponse({ | |
| "filename": file.filename, | |
| "signals": result.get("signals"), | |
| "confidence": result.get("confidence"), | |
| "predicted_conditions": result.get("predicted_conditions"), | |
| "probabilities": result.get("probabilities"), | |
| "risk_score": result.get("risk_score") | |
| }) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def create_mat(file: UploadFile = File(...)): | |
| """ | |
| Upload an ECG IMAGE and receive a .mat file containing: | |
| - val : ndarray (12 x 1000) signals | |
| - meta: dict with filename and sampling info | |
| Returns the .mat file as a download. | |
| """ | |
| try: | |
| content = await file.read() | |
| result = predictor.analyze_image(content, visualize=False) | |
| # if result is None or "signals" not in result: | |
| # raise HTTPException(status_code=400, detail="Failed to extract signals") | |
| signals = result["signals"] | |
| # # ensure numpy array | |
| # arr = None | |
| try: | |
| # import numpy as np | |
| # arr = np.array(signals, dtype=np.float32) | |
| return {"val": signals} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Signals conversion error: {e}") | |
| # create temp .mat | |
| # # tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".mat") | |
| # mat_dict = {"val": arr} | |
| # scipy.io.savemat(tmp.name, mat_dict) | |
| # tmp.close() | |
| # return FileResponse(tmp.name, filename=f"{os.path.splitext(file.filename)[0]}.mat", media_type="application/octet-stream") | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |