File size: 2,636 Bytes
c716961
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# 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")




@app.post("/extract_signals/")
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))

@app.post("/create_mat/")
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))