File size: 7,591 Bytes
86f402d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
"""
Lesion Routes - CRUD for lesions and images
"""

from fastapi import APIRouter, HTTPException, UploadFile, File
from fastapi.responses import FileResponse
from pydantic import BaseModel
from dataclasses import asdict
from pathlib import Path
from PIL import Image
import io

from data.case_store import get_case_store

router = APIRouter()


class CreateLesionRequest(BaseModel):
    name: str
    location: str = ""


class UpdateLesionRequest(BaseModel):
    name: str = None
    location: str = None


# -------------------------------------------------------------------------
# Lesion CRUD
# -------------------------------------------------------------------------

@router.get("/{patient_id}/lesions")
def list_lesions(patient_id: str):
    """List all lesions for a patient"""
    store = get_case_store()

    patient = store.get_patient(patient_id)
    if not patient:
        raise HTTPException(status_code=404, detail="Patient not found")

    lesions = store.list_lesions(patient_id)

    result = []
    for lesion in lesions:
        images = store.list_images(patient_id, lesion.id)
        # Get the most recent image as thumbnail
        latest_image = images[-1] if images else None

        result.append({
            "id": lesion.id,
            "patient_id": lesion.patient_id,
            "name": lesion.name,
            "location": lesion.location,
            "created_at": lesion.created_at,
            "image_count": len(images),
            "latest_image": asdict(latest_image) if latest_image else None
        })

    return {"lesions": result}


@router.post("/{patient_id}/lesions")
def create_lesion(patient_id: str, req: CreateLesionRequest):
    """Create a new lesion for a patient"""
    store = get_case_store()

    patient = store.get_patient(patient_id)
    if not patient:
        raise HTTPException(status_code=404, detail="Patient not found")

    lesion = store.create_lesion(patient_id, req.name, req.location)
    return {
        "lesion": {
            **asdict(lesion),
            "image_count": 0,
            "images": []
        }
    }


@router.get("/{patient_id}/lesions/{lesion_id}")
def get_lesion(patient_id: str, lesion_id: str):
    """Get a lesion with all its images"""
    store = get_case_store()

    lesion = store.get_lesion(patient_id, lesion_id)
    if not lesion:
        raise HTTPException(status_code=404, detail="Lesion not found")

    images = store.list_images(patient_id, lesion_id)

    return {
        "lesion": {
            **asdict(lesion),
            "image_count": len(images),
            "images": [asdict(img) for img in images]
        }
    }


@router.patch("/{patient_id}/lesions/{lesion_id}")
def update_lesion(patient_id: str, lesion_id: str, req: UpdateLesionRequest):
    """Update a lesion's name or location"""
    store = get_case_store()

    lesion = store.get_lesion(patient_id, lesion_id)
    if not lesion:
        raise HTTPException(status_code=404, detail="Lesion not found")

    store.update_lesion(patient_id, lesion_id, req.name, req.location)

    # Return updated lesion
    lesion = store.get_lesion(patient_id, lesion_id)
    images = store.list_images(patient_id, lesion_id)

    return {
        "lesion": {
            **asdict(lesion),
            "image_count": len(images),
            "images": [asdict(img) for img in images]
        }
    }


@router.delete("/{patient_id}/lesions/{lesion_id}")
def delete_lesion(patient_id: str, lesion_id: str):
    """Delete a lesion and all its images"""
    store = get_case_store()

    lesion = store.get_lesion(patient_id, lesion_id)
    if not lesion:
        raise HTTPException(status_code=404, detail="Lesion not found")

    store.delete_lesion(patient_id, lesion_id)
    return {"success": True}


# -------------------------------------------------------------------------
# Image CRUD
# -------------------------------------------------------------------------

@router.post("/{patient_id}/lesions/{lesion_id}/images")
async def upload_image(patient_id: str, lesion_id: str, image: UploadFile = File(...)):
    """Upload a new image to a lesion's timeline"""
    store = get_case_store()

    lesion = store.get_lesion(patient_id, lesion_id)
    if not lesion:
        raise HTTPException(status_code=404, detail="Lesion not found")

    try:
        # Create image record
        img_record = store.add_image(patient_id, lesion_id)

        # Save the actual image file
        pil_image = Image.open(io.BytesIO(await image.read())).convert("RGB")
        image_path = store.save_lesion_image(patient_id, lesion_id, img_record.id, pil_image)

        # Update image record with path
        store.update_image(patient_id, lesion_id, img_record.id, image_path=image_path)

        # Return updated record
        img_record = store.get_image(patient_id, lesion_id, img_record.id)
        return {"image": asdict(img_record)}

    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Failed to upload image: {e}")


@router.get("/{patient_id}/lesions/{lesion_id}/images/{image_id}")
def get_image_record(patient_id: str, lesion_id: str, image_id: str):
    """Get an image record"""
    store = get_case_store()

    img = store.get_image(patient_id, lesion_id, image_id)
    if not img:
        raise HTTPException(status_code=404, detail="Image not found")

    return {"image": asdict(img)}


@router.get("/{patient_id}/lesions/{lesion_id}/images/{image_id}/file")
def get_image_file(patient_id: str, lesion_id: str, image_id: str):
    """Get the actual image file"""
    store = get_case_store()

    img = store.get_image(patient_id, lesion_id, image_id)
    if not img or not img.image_path:
        raise HTTPException(status_code=404, detail="Image not found")

    path = Path(img.image_path)
    if not path.exists():
        raise HTTPException(status_code=404, detail="Image file not found")

    return FileResponse(str(path), media_type="image/png")


@router.get("/{patient_id}/lesions/{lesion_id}/images/{image_id}/gradcam")
def get_gradcam_file(patient_id: str, lesion_id: str, image_id: str):
    """Get the GradCAM visualization for an image"""
    store = get_case_store()

    img = store.get_image(patient_id, lesion_id, image_id)
    if not img or not img.gradcam_path:
        raise HTTPException(status_code=404, detail="GradCAM not found")

    path = Path(img.gradcam_path)
    if not path.exists():
        raise HTTPException(status_code=404, detail="GradCAM file not found")

    return FileResponse(str(path), media_type="image/png")


# -------------------------------------------------------------------------
# Chat
# -------------------------------------------------------------------------

@router.get("/{patient_id}/lesions/{lesion_id}/chat")
def get_chat_history(patient_id: str, lesion_id: str):
    """Get chat history for a lesion"""
    store = get_case_store()

    lesion = store.get_lesion(patient_id, lesion_id)
    if not lesion:
        raise HTTPException(status_code=404, detail="Lesion not found")

    messages = store.get_chat_history(patient_id, lesion_id)
    return {"messages": [asdict(m) for m in messages]}


@router.delete("/{patient_id}/lesions/{lesion_id}/chat")
def clear_chat_history(patient_id: str, lesion_id: str):
    """Clear chat history for a lesion"""
    store = get_case_store()

    lesion = store.get_lesion(patient_id, lesion_id)
    if not lesion:
        raise HTTPException(status_code=404, detail="Lesion not found")

    store.clear_chat_history(patient_id, lesion_id)
    return {"success": True}