Ziad Meligy commited on
Commit
bfe1fa6
·
1 Parent(s): f1ec150

Pushing to space Dicom

Browse files
Files changed (2) hide show
  1. main.py +74 -0
  2. utils.py +17 -1
main.py CHANGED
@@ -1,7 +1,11 @@
1
  from fastapi import FastAPI, File, UploadFile, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
 
3
  from generate_report import generate_report
4
  from utils import convert_to_png
 
 
 
5
  import io
6
 
7
 
@@ -41,6 +45,76 @@ async def upload_image(file: UploadFile = File(...)):
41
  raise HTTPException(status_code=500, detail=str(e))
42
 
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
 
46
 
 
1
  from fastapi import FastAPI, File, UploadFile, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.responses import JSONResponse
4
  from generate_report import generate_report
5
  from utils import convert_to_png
6
+ from utils import dicom_to_png
7
+ import pydicom
8
+ import tempfile
9
  import io
10
 
11
 
 
45
  raise HTTPException(status_code=500, detail=str(e))
46
 
47
 
48
+ @app.post("/generate_report_dicom")
49
+ async def generate_report_dicom(file: UploadFile = File(...)):
50
+ """
51
+ Generate radiology report from DICOM file.
52
+ Checks if the DICOM is an X-ray, converts it to PNG, and generates a report.
53
+ """
54
+ try:
55
+ # Validate file type
56
+ if not file.filename.lower().endswith(('.dcm', '.dicom')):
57
+ raise HTTPException(status_code=400, detail="File must be a DICOM file (.dcm or .dicom)")
58
+
59
+ # Read DICOM file
60
+ file_content = await file.read()
61
+
62
+ # Create a temporary file to store DICOM data
63
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.dcm') as temp_file:
64
+ temp_file.write(file_content)
65
+ temp_file_path = temp_file.name
66
+
67
+ try:
68
+ # Read DICOM data
69
+ dicom_data = pydicom.dcmread(temp_file_path)
70
+
71
+ # # Check if it's an X-ray
72
+ # if not is_xray_dicom(dicom_data):
73
+ # return JSONResponse(
74
+ # {"error": "DICOM file does not appear to be an X-ray image"},
75
+ # status_code=400
76
+ # )
77
+
78
+ # Convert DICOM to PNG
79
+ image = dicom_to_png(dicom_data)
80
+
81
+ report= generate_report(image) # Generate report using the image
82
+
83
+ # Get additional DICOM metadata for context
84
+ metadata = {}
85
+ if hasattr(dicom_data, 'PatientID'):
86
+ metadata['patient_id'] = str(dicom_data.PatientID)
87
+ if hasattr(dicom_data, 'StudyDate'):
88
+ metadata['study_date'] = str(dicom_data.StudyDate)
89
+ if hasattr(dicom_data, 'Modality'):
90
+ metadata['modality'] = str(dicom_data.Modality)
91
+ if hasattr(dicom_data, 'BodyPartExamined'):
92
+ metadata['body_part'] = str(dicom_data.BodyPartExamined)
93
+
94
+ return JSONResponse({
95
+ "generated_report": report,
96
+ "dicom_metadata": metadata,
97
+ "image_info": {
98
+ "width": image.width,
99
+ "height": image.height,
100
+ "mode": image.mode
101
+ }
102
+ })
103
+
104
+ finally:
105
+ # Clean up temporary file
106
+ import os
107
+ try:
108
+ os.unlink(temp_file_path)
109
+ except:
110
+ pass
111
+
112
+ except HTTPException:
113
+ raise
114
+ except Exception as e:
115
+ return JSONResponse({"error": str(e)}, status_code=500)
116
+
117
+
118
 
119
 
120
 
utils.py CHANGED
@@ -36,4 +36,20 @@ async def convert_to_png(file: UploadFile) -> Image.Image:
36
  image = Image.fromarray(pixel_array).convert("RGB")
37
  return image
38
 
39
- raise HTTPException(status_code=400, detail="Unsupported media type")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  image = Image.fromarray(pixel_array).convert("RGB")
37
  return image
38
 
39
+ raise HTTPException(status_code=400, detail="Unsupported media type")
40
+
41
+ def dicom_to_png(ds):
42
+ pixel_array = ds.pixel_array
43
+
44
+ # Normalize if needed (handle 16-bit images)
45
+ if pixel_array.dtype != np.uint8:
46
+ # Scale to 0-255
47
+ pixel_array = pixel_array.astype(np.float32)
48
+ pixel_array -= pixel_array.min()
49
+ pixel_array /= pixel_array.max()
50
+ pixel_array *= 255.0
51
+ pixel_array = pixel_array.astype(np.uint8)
52
+
53
+ # Convert to PIL Image
54
+ img = Image.fromarray(pixel_array).convert("RGB")
55
+ return img