File size: 3,928 Bytes
eb8805a
 
bfe1fa6
eb8805a
 
bfe1fa6
 
 
eb8805a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57fef69
 
 
 
 
eb8805a
 
 
57fef69
 
 
 
eb8805a
57fef69
eb8805a
57fef69
eb8805a
 
 
bfe1fa6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a58046
 
 
 
bfe1fa6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a58046
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from generate_report import generate_report
from utils import convert_to_png
from utils import dicom_to_png
import pydicom
import tempfile
import io


app = FastAPI(title="FastAPI Example App", version="0.1.0")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def read_root():
    return {"message": "Hello oopa"}

@app.post("/upload-image/")
async def upload_image(file: UploadFile = File(...)):
    try:
        print(f"βœ… Received file: {file.filename}")
        
        image = await convert_to_png(file)  # this may hang
        print(f"βœ… Image converted to PNG")

        image_io = io.BytesIO()
        image.save(image_io, format="PNG")
        image_data = image_io.getvalue()
        
        report = generate_report(image_data)  # this may also hang
        print(f"βœ… Report generated")

        return {"report": report}

    except Exception as e:
        print(f"❌ Error: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))
    

@app.post("/generate_report_dicom")
async def generate_report_dicom(file: UploadFile = File(...)):
    """
    Generate radiology report from DICOM file.
    Checks if the DICOM is an X-ray, converts it to PNG, and generates a report.
    """
    try:
        # Validate file type
        if not file.filename.lower().endswith(('.dcm', '.dicom')):
            raise HTTPException(status_code=400, detail="File must be a DICOM file (.dcm or .dicom)")
        
        # Read DICOM file
        file_content = await file.read()
        
        # Create a temporary file to store DICOM data
        with tempfile.NamedTemporaryFile(delete=False, suffix='.dcm') as temp_file:
            temp_file.write(file_content)
            temp_file_path = temp_file.name
        
        try:
            # Read DICOM data
            dicom_data = pydicom.dcmread(temp_file_path)
            
            # # Check if it's an X-ray
            # if not is_xray_dicom(dicom_data):
            #     return JSONResponse(
            #         {"error": "DICOM file does not appear to be an X-ray image"},
            #         status_code=400
            #     )
            
            # Convert DICOM to PNG
            image = dicom_to_png(dicom_data)
            image_io = io.BytesIO()
            image.save(image_io, format="PNG")
            image_data = image_io.getvalue()
            report= generate_report(image_data)  # Generate report using the image
            
            # Get additional DICOM metadata for context
            metadata = {}
            if hasattr(dicom_data, 'PatientID'):
                metadata['patient_id'] = str(dicom_data.PatientID)
            if hasattr(dicom_data, 'StudyDate'):
                metadata['study_date'] = str(dicom_data.StudyDate)
            if hasattr(dicom_data, 'Modality'):
                metadata['modality'] = str(dicom_data.Modality)
            if hasattr(dicom_data, 'BodyPartExamined'):
                metadata['body_part'] = str(dicom_data.BodyPartExamined)
            
            return JSONResponse({
                "generated_report": report,
                "dicom_metadata": metadata,
                "image_info": {
                    "width": image.width,
                    "height": image.height,
                    "mode": image.mode
                }
            })
            
        finally:
            # Clean up temporary file
            import os
            try:
                os.unlink(temp_file_path)
            except:
                pass
                
    except HTTPException:
        raise
    except Exception as e:
        return JSONResponse({"error": str(e)}, status_code=500)