File size: 6,927 Bytes
26c7cba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# Pathora Colposcopy API Documentation

## Overview
FastAPI backend for Pathora Colposcopy Assistant with AI model inference and LLM capabilities.

## Base URL
- Local: `http://localhost:8000`
- Production: `https://huggingface.co/spaces/ManalifeAI/Pathora_Colposcopy_Assistant`

---

## Endpoints

### Health Check
**GET** `/health`

Check API health status and verify AI models and LLM availability.

**Response:**
```json
{
  "status": "healthy",
  "service": "Pathora Colposcopy API",
  "ai_models": {
    "acetowhite_model": "loaded",
    "cervix_model": "loaded"
  },
  "llm": {
    "gemini_available": true,
    "api_key_configured": true
  }
}
```

---

## AI Model Endpoints

### 1. Acetowhite Contour Detection
**POST** `/api/infer-aw-contour`

Detect acetowhite lesions and generate contour overlays.

**Parameters:**
- `file` (UploadFile): Image file
- `conf_threshold` (float, optional): Confidence threshold (0.0-1.0, default: 0.4)

**Response:**
```json
{
  "status": "success",
  "message": "Inference completed successfully",
  "result_image": "base64_encoded_image",
  "contours": [
    {
      "points": [[x1, y1], [x2, y2], ...],
      "area": 1234.5,
      "confidence": 0.85
    }
  ],
  "detections": 2,
  "confidence_threshold": 0.4
}
```

### 2. Cervix Bounding Box Detection
**POST** `/api/infer-cervix-bbox`

Detect cervix location and return bounding boxes.

**Parameters:**
- `file` (UploadFile): Image file
- `conf_threshold` (float, optional): Confidence threshold (0.0-1.0, default: 0.4)

**Response:**
```json
{
  "status": "success",
  "message": "Cervix bounding box detection completed",
  "result_image": "base64_encoded_image",
  "bounding_boxes": [
    {
      "x1": 100,
      "y1": 150,
      "x2": 400,
      "y2": 450,
      "confidence": 0.92,
      "class": "cervix"
    }
  ],
  "detections": 1,
  "frame_width": 1920,
  "frame_height": 1080,
  "confidence_threshold": 0.4
}
```

### 3. Batch Image Inference
**POST** `/api/batch-infer`

Process multiple images for acetowhite detection in one request.

**Parameters:**
- `files` (List[UploadFile]): Multiple image files
- `conf_threshold` (float, optional): Confidence threshold (default: 0.4)

**Response:**
```json
{
  "status": "completed",
  "total_files": 3,
  "results": [
    {
      "filename": "image1.jpg",
      "status": "success",
      "result_image": "base64...",
      "contours": [...],
      "detections": 2
    }
  ]
}
```

### 4. Single Frame Analysis
**POST** `/infer/image`

Analyze single image for cervix quality assessment.

**Parameters:**
- `file` (UploadFile): Image file

**Response:**
```json
{
  "status": "Excellent",
  "quality_percent": 95,
  "cervix_detected": true,
  "focus_score": 0.89,
  "brightness_score": 0.92
}
```

### 5. Video Frame Analysis
**POST** `/infer/video`

Process video frames for quality assessment.

**Parameters:**
- `file` (UploadFile): Video file

**Response:**
```json
{
  "total_frames": 150,
  "results": [
    {
      "frame": 0,
      "status": "Excellent",
      "quality_percent": 95
    }
  ]
}
```

---

## LLM Endpoints

### 6. Chat with AI Assistant
**POST** `/api/chat`

Conversational AI endpoint for colposcopy guidance.

**Request Body:**
```json
{
  "message": "What are the signs of high-grade lesions?",
  "history": [
    {
      "role": "user",
      "text": "Hello"
    },
    {
      "role": "bot",
      "text": "Hello! I'm Pathora AI..."
    }
  ],
  "system_prompt": "Optional custom system prompt"
}
```

**Response:**
```json
{
  "status": "success",
  "response": "High-grade lesions typically show...",
  "model": "gemini-1.5-flash"
}
```

### 7. Generate Colposcopy Report
**POST** `/api/generate-report`

Generate comprehensive colposcopy report based on patient data and findings.

**Request Body:**
```json
{
  "patient_data": {
    "age": 35,
    "gravida": 2,
    "para": 2,
    "lmp": "2024-02-01",
    "indication": "Abnormal Pap smear"
  },
  "exam_findings": {
    "native": {
      "cervix_visible": true,
      "transformation_zone": "Type 1"
    },
    "acetic_acid": {
      "acetowhite_lesions": true,
      "location": "6-9 o'clock"
    },
    "green_filter": {
      "vascular_patterns": "Punctation"
    },
    "lugol": {
      "iodine_uptake": "Partial"
    }
  },
  "images": [],
  "system_prompt": "Optional custom prompt"
}
```

**Response:**
```json
{
  "status": "success",
  "report": "COLPOSCOPY REPORT\n\nCLINICAL SUMMARY:\n...",
  "model": "gemini-1.5-flash"
}
```

---

## Environment Variables

Required for LLM functionality:

```bash
GEMINI_API_KEY=your_api_key_here
VITE_GEMINI_API_KEY=your_api_key_here  # For frontend compatibility
```

Get your API key from: https://makersuite.google.com/app/apikey

---

## Error Responses

All endpoints return standardized error responses:

```json
{
  "detail": "Error message description"
}
```

**Common HTTP Status Codes:**
- `400`: Bad Request (invalid file, parameters)
- `500`: Internal Server Error (AI model error, processing failure)
- `503`: Service Unavailable (LLM not configured, API key missing)

---

## Model Information

### AI Models
- **Acetowhite Detection**: YOLO-based segmentation model (`AW_yolo.pt`)
- **Cervix Detection**: YOLO-based object detection model (`cervix_yolo.pt`)

### LLM Model
- **Gemini 1.5 Flash**: Google's generative AI for chat and report generation
  - Temperature: 0.4 (balanced between creativity and consistency)
  - Max Output Tokens: 2048

---

## Usage Examples

### Python
```python
import requests

# AI Model Inference
with open('image.jpg', 'rb') as f:
    response = requests.post(
        'http://localhost:8000/api/infer-aw-contour',
        files={'file': f},
        data={'conf_threshold': 0.5}
    )
    result = response.json()

# Chat
response = requests.post(
    'http://localhost:8000/api/chat',
    json={
        'message': 'What is Reid colposcopic index?',
        'history': []
    }
)
chat_result = response.json()
```

### JavaScript/TypeScript
```typescript
// AI Model Inference
const formData = new FormData();
formData.append('file', imageFile);
formData.append('conf_threshold', '0.5');

const response = await fetch('/api/infer-aw-contour', {
  method: 'POST',
  body: formData
});
const result = await response.json();

// Chat
const chatResponse = await fetch('/api/chat', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    message: 'Explain transformation zone types',
    history: []
  })
});
const chatResult = await chatResponse.json();
```

---

## Development

### Running Locally
```bash
# Install dependencies
cd backend
pip install -r requirements.txt

# Set environment variables
export GEMINI_API_KEY=your_key

# Run server
uvicorn backend.app:app --reload --host 0.0.0.0 --port 8000
```

### Building with Docker
```bash
docker build -t pathora-colpo .
docker run -p 7860:7860 -e GEMINI_API_KEY=your_key pathora-colpo
```