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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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
# Lung Cancer Classification API - Flutter Integration Guidelines

Complete guide for integrating the Grad-CAM backend API into your Flutter application.

---

## Table of Contents
1. [API Overview](#api-overview)
2. [Base URL & Configuration](#base-url--configuration)
3. [Endpoints](#endpoints)
4. [Request/Response Formats](#requestresponse-formats)
5. [Image Handling](#image-handling)
6. [Error Handling](#error-handling)
7. [Code Examples](#code-examples)
8. [UI Integration](#ui-integration)
9. [Best Practices](#best-practices)
10. [Troubleshooting](#troubleshooting)

---

## API Overview

This API provides:
- **YOLO Tumor Detection**: Detects lung tumors in CT scan images
- **DenseNet121 Classification**: Classifies detected tumors into 4 cancer types
- **Grad-CAM Visualization**: Explains model predictions with attention heatmaps
- **CT Scan Validation**: Validates input is a medical image (not a color photo)

### Supported Cancer Classes
```
0. Adenocarcinoma (Class A)
1. Small Cell (Class B)
2. Large Cell (Class E)
3. Squamous Cell (Class G)
```

---

## Base URL & Configuration

### Development
```
Base URL: http://localhost:5001
```

### Production (Railway Deployment)
```
Base URL: https://your-railway-app.up.railway.app
```

### Environment Configuration
```dart
class ApiConfig {
  static const String baseUrl = 'http://localhost:5001'; // Change for production
  static const int timeout = 120; // seconds (image processing takes time)
  static const String apiVersion = 'v1.0.0';
}
```

---

## Endpoints

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

Check if API is running and models are loaded.

**Response:**
```json
{
  "status": "healthy",
  "model_loaded": true
}
```

---

### 2. Validate CT Scan
**POST** `/validate-ct`

Validate if uploaded image is a CT scan (grayscale check).

**Request:**
```
Content-Type: multipart/form-data
Body: 
  - file: <image_file>
```

**Response (Valid CT):**
```json
{
  "is_ct_scan": true,
  "color_score": 3.52,
  "message": "Valid CT scan - grayscale image detected"
}
```

**Response (Invalid - Color Image):**
```json
{
  "is_ct_scan": false,
  "color_score": 45.2,
  "message": "NOT a CT scan - color image detected (color_score=45.2)"
}
```

**Color Score Interpretation:**
- `< 6.0`: Valid CT scan (grayscale)
- `>= 6.0`: Not a CT scan (color image detected)

---

### 3. Analyze (YOLO + Classification + Grad-CAM)
**POST** `/analyze`

Complete pipeline: detect tumors β†’ classify β†’ generate heatmaps.

**Request:**
```
Content-Type: multipart/form-data
Body:
  - file: <image_file>
```

**Response (With Tumors):**
```json
{
  "success": true,
  "tumors_detected": 1,
  "detection_image": "base64_encoded_image_with_boxes",
  "heatmap_image": "base64_encoded_heatmap",
  "detections": [
    {
      "tumor_id": 1,
      "bbox": [161, 319, 225, 390],
      "bbox_with_padding": [149, 305, 237, 404],
      "prediction": "Small Cell (Class B)",
      "confidence": 44.62,
      "all_confidences": {
        "Adenocarcinoma (Class A)": 11.07,
        "Small Cell (Class B)": 44.62,
        "Large Cell (Class E)": 25.52,
        "Squamous Cell (Class G)": 18.79
      },
      "crop_image": "base64_encoded_crop",
      "heatmap_image": "base64_encoded_heatmap_of_crop"
    }
  ]
}
```

**Response (No Tumors):**
```json
{
  "success": true,
  "tumors_detected": 0,
  "detections": [],
  "detection_image": "base64_encoded_original_image",
  "message": "No tumors detected in this image"
}
```

**Response (Error):**
```json
{
  "error": "Could not load image"
}
```

---

## Request/Response Formats

### Multipart Form Data (Image Upload)

```dart
// Example using http package
var request = http.MultipartRequest('POST', Uri.parse('$baseUrl/analyze'));
request.files.add(
  http.MultipartFile.fromBytes(
    'file',
    imageBytes,
    filename: 'scan.jpg',
  ),
);
```

### Response Image Decoding

All images in responses are **base64-encoded JPEG**.

```dart
// Decode base64 to Image widget
Image.memory(
  base64Decode(response['detection_image']),
  fit: BoxFit.contain,
)
```

---

## Image Handling

### Supported Formats
- JPEG (.jpg, .jpeg)
- PNG (.png)
- Recommended: **JPEG** (faster processing)

### Image Size Recommendations
- **Minimum**: 256x256 pixels
- **Optimal**: 512x512 pixels
- **Maximum**: 2048x2048 pixels (will be resized internally)

### Image Acquisition

#### From Camera
```dart
import 'package:image_picker/image_picker.dart';

final picker = ImagePicker();
final pickedFile = await picker.pickImage(source: ImageSource.camera);

if (pickedFile != null) {
  final bytes = await pickedFile.readAsBytes();
  // Use bytes for upload
}
```

#### From Gallery
```dart
final pickedFile = await picker.pickImage(source: ImageSource.gallery);
if (pickedFile != null) {
  final bytes = await pickedFile.readAsBytes();
  // Use bytes for upload
}
```

#### From File
```dart
import 'dart:io';

File imageFile = File('/path/to/image.jpg');
final bytes = await imageFile.readAsBytes();
// Use bytes for upload
```

### Base64 Image Display

```dart
import 'dart:convert';

// Decode and display
Widget displayBase64Image(String base64String) {
  return Image.memory(
    base64Decode(base64String),
    fit: BoxFit.contain,
  );
}

// Or with error handling
Widget safeDisplayImage(String base64String) {
  try {
    return Image.memory(
      base64Decode(base64String),
      fit: BoxFit.contain,
      errorBuilder: (context, error, stackTrace) {
        return Center(child: Text('Failed to load image'));
      },
    );
  } catch (e) {
    return Center(child: Text('Invalid image data'));
  }
}
```

---

## Error Handling

### HTTP Status Codes

| Status | Meaning | Action |
|--------|---------|--------|
| 200 | Success | Process response |
| 400 | Bad Request | Check file format/size |
| 500 | Server Error | Retry or check logs |

### Common Errors

#### "No file uploaded"
```json
{"error": "No file uploaded"}
```
**Cause**: File not attached to request  
**Fix**: Ensure `file` field is included in multipart request

#### "Could not load image"
```json
{"error": "Could not load image"}
```
**Cause**: Corrupted or unsupported image format  
**Fix**: Use JPEG/PNG, verify file integrity

#### "YOLO model not loaded"
```json
{"error": "YOLO model not loaded"}
```
**Cause**: Backend not initialized properly  
**Fix**: Restart backend, check `models/best.pt` exists

#### Timeout
**Cause**: Image processing takes >120 seconds  
**Fix**: Reduce image size, check server performance

---

## Code Examples

### Complete Service Class

```dart
import 'package:http/http.dart' as http;
import 'dart:convert';

class LungCancerAnalysisService {
  final String baseUrl = 'http://localhost:5001';
  final int timeout = Duration(seconds: 120).inSeconds;

  // Health check
  Future<bool> healthCheck() async {
    try {
      final response = await http
          .get(Uri.parse('$baseUrl/health'))
          .timeout(Duration(seconds: 10));
      
      return response.statusCode == 200;
    } catch (e) {
      print('Health check failed: $e');
      return false;
    }
  }

  // Validate CT scan
  Future<ValidateCTResponse> validateCT(List<int> imageBytes) async {
    try {
      var request = http.MultipartRequest('POST', 
        Uri.parse('$baseUrl/validate-ct'));
      
      request.files.add(
        http.MultipartFile.fromBytes('file', imageBytes, filename: 'scan.jpg'),
      );
      
      request.headers['Accept'] = 'application/json';
      
      final streamedResponse = await request.send()
          .timeout(Duration(seconds: this.timeout));
      
      final response = await http.Response.fromStream(streamedResponse);
      
      if (response.statusCode == 200) {
        final json = jsonDecode(response.body);
        return ValidateCTResponse.fromJson(json);
      } else {
        throw Exception('Validation failed: ${response.body}');
      }
    } catch (e) {
      throw Exception('CT validation error: $e');
    }
  }

  // Full analysis with YOLO + Classification
  Future<AnalysisResponse> analyze(List<int> imageBytes) async {
    try {
      var request = http.MultipartRequest('POST', 
        Uri.parse('$baseUrl/analyze'));
      
      request.files.add(
        http.MultipartFile.fromBytes('file', imageBytes, filename: 'scan.jpg'),
      );
      
      request.headers['Accept'] = 'application/json';
      
      final streamedResponse = await request.send()
          .timeout(Duration(seconds: this.timeout));
      
      final response = await http.Response.fromStream(streamedResponse);
      
      if (response.statusCode == 200) {
        final json = jsonDecode(response.body);
        return AnalysisResponse.fromJson(json);
      } else {
        throw Exception('Analysis failed: ${response.body}');
      }
    } catch (e) {
      throw Exception('Analysis error: $e');
    }
  }
}

// Response models
class ValidateCTResponse {
  final bool isCTScan;
  final double colorScore;
  final String message;

  ValidateCTResponse({
    required this.isCTScan,
    required this.colorScore,
    required this.message,
  });

  factory ValidateCTResponse.fromJson(Map<String, dynamic> json) {
    return ValidateCTResponse(
      isCTScan: json['is_ct_scan'] ?? false,
      colorScore: (json['color_score'] ?? 0).toDouble(),
      message: json['message'] ?? '',
    );
  }
}

class AnalysisResponse {
  final bool success;
  final int tumorsDetected;
  final List<TumorDetection> detections;
  final String detectionImage; // base64
  final String heatmapImage;   // base64
  final String? message;

  AnalysisResponse({
    required this.success,
    required this.tumorsDetected,
    required this.detections,
    required this.detectionImage,
    required this.heatmapImage,
    this.message,
  });

  factory AnalysisResponse.fromJson(Map<String, dynamic> json) {
    return AnalysisResponse(
      success: json['success'] ?? false,
      tumorsDetected: json['tumors_detected'] ?? 0,
      detections: (json['detections'] as List)
          .map((d) => TumorDetection.fromJson(d))
          .toList(),
      detectionImage: json['detection_image'] ?? '',
      heatmapImage: json['heatmap_image'] ?? '',
      message: json['message'],
    );
  }
}

class TumorDetection {
  final int tumorId;
  final List<int> bbox;
  final List<int> bboxWithPadding;
  final String prediction;
  final double confidence;
  final Map<String, double> allConfidences;
  final String cropImage;     // base64
  final String heatmapImage;  // base64

  TumorDetection({
    required this.tumorId,
    required this.bbox,
    required this.bboxWithPadding,
    required this.prediction,
    required this.confidence,
    required this.allConfidences,
    required this.cropImage,
    required this.heatmapImage,
  });

  factory TumorDetection.fromJson(Map<String, dynamic> json) {
    return TumorDetection(
      tumorId: json['tumor_id'] ?? 0,
      bbox: List<int>.from(json['bbox'] ?? []),
      bboxWithPadding: List<int>.from(json['bbox_with_padding'] ?? []),
      prediction: json['prediction'] ?? 'Unknown',
      confidence: (json['confidence'] ?? 0).toDouble(),
      allConfidences: Map<String, double>.from(
        (json['all_confidences'] as Map).map(
          (k, v) => MapEntry(k, (v as num).toDouble()),
        ),
      ),
      cropImage: json['crop_image'] ?? '',
      heatmapImage: json['heatmap_image'] ?? '',
    );
  }
}
```

### Usage in Widget

```dart
class CancerAnalysisScreen extends StatefulWidget {
  @override
  _CancerAnalysisScreenState createState() => _CancerAnalysisScreenState();
}

class _CancerAnalysisScreenState extends State<CancerAnalysisScreen> {
  final service = LungCancerAnalysisService();
  
  bool isLoading = false;
  AnalysisResponse? result;
  String? errorMessage;

  void analyzeImage(List<int> imageBytes) async {
    setState(() {
      isLoading = true;
      errorMessage = null;
    });

    try {
      // Step 1: Validate CT scan
      final validation = await service.validateCT(imageBytes);
      
      if (!validation.isCTScan) {
        setState(() {
          errorMessage = 'Not a CT scan (score: ${validation.colorScore})';
          isLoading = false;
        });
        return;
      }

      // Step 2: Full analysis
      final analysis = await service.analyze(imageBytes);
      
      setState(() {
        result = analysis;
        isLoading = false;
      });

    } catch (e) {
      setState(() {
        errorMessage = 'Error: $e';
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Lung Cancer Analysis')),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.all(16),
          child: Column(
            children: [
              if (isLoading)
                Center(
                  child: Column(
                    children: [
                      CircularProgressIndicator(),
                      SizedBox(height: 16),
                      Text('Analyzing image...'),
                    ],
                  ),
                ),
              if (errorMessage != null)
                Container(
                  padding: EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.red.shade100,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Text(
                    errorMessage!,
                    style: TextStyle(color: Colors.red.shade900),
                  ),
                ),
              if (result != null)
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Card(
                      child: Padding(
                        padding: EdgeInsets.all(12),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'Tumors Detected: ${result!.tumorsDetected}',
                              style: Theme.of(context).textTheme.titleLarge,
                            ),
                            SizedBox(height: 16),
                            // Detection image
                            Text('Detection Image:'),
                            Image.memory(
                              base64Decode(result!.detectionImage),
                              fit: BoxFit.contain,
                            ),
                            SizedBox(height: 16),
                            // Heatmap image
                            Text('Heatmap (Highest Confidence):'),
                            Image.memory(
                              base64Decode(result!.heatmapImage),
                              fit: BoxFit.contain,
                            ),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 16),
                    // Individual tumor details
                    ...result!.detections.map((tumor) {
                      return Card(
                        child: Padding(
                          padding: EdgeInsets.all(12),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                'Tumor #${tumor.tumorId}',
                                style: Theme.of(context).textTheme.titleMedium,
                              ),
                              Text('Classification: ${tumor.prediction}'),
                              Text('Confidence: ${tumor.confidence.toStringAsFixed(2)}%'),
                              SizedBox(height: 12),
                              Text('All Confidences:'),
                              ...tumor.allConfidences.entries.map((e) {
                                return Text(
                                  '  ${e.key}: ${e.value.toStringAsFixed(2)}%',
                                );
                              }).toList(),
                              SizedBox(height: 12),
                              Text('Bounding Box: ${tumor.bbox}'),
                            ],
                          ),
                        ),
                      );
                    }).toList(),
                  ],
                ),
            ],
          ),
        ),
      ),
    );
  }
}
```

---

## UI Integration

### Recommended UI Flow

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Home Screen        β”‚
β”‚  - Upload Image     β”‚
β”‚  - Take Photo       β”‚
β”‚  - Gallery          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚
           β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Validation Screen   β”‚
β”‚ - Show Color Score  β”‚
β”‚ - CT Scan Check     β”‚
β”‚ - Retry/Continue    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚
           β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Loading Screen      β”‚
β”‚ - Progress Indicatorβ”‚
β”‚ - "Analyzing..."    β”‚
β”‚ - Timeout Handling  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚
           β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Results Screen       β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Detection Image  β”‚ β”‚
β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚
β”‚ β”‚ Heatmap Image    β”‚ β”‚
β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚
β”‚ β”‚ Tumor Details    β”‚ β”‚
β”‚ β”‚ - Confidence     β”‚ β”‚
β”‚ β”‚ - Classification β”‚ β”‚
β”‚ β”‚ - Per-class %    β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

### Confidence Visualization

```dart
Widget buildConfidenceBar(String className, double confidence) {
  final color = confidence > 0.4
      ? Colors.red
      : confidence > 0.2
          ? Colors.orange
          : Colors.green;

  return Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Text(className),
      LinearProgressIndicator(
        value: confidence / 100,
        minHeight: 8,
        backgroundColor: Colors.grey.shade300,
        valueColor: AlwaysStoppedAnimation(color),
      ),
      Text('${confidence.toStringAsFixed(2)}%'),
    ],
  );
}
```

### Image Display with Zoom

```dart
import 'package:photo_view/photo_view.dart';

Widget zoomableImage(String base64String) {
  return PhotoView(
    imageProvider: MemoryImage(base64Decode(base64String)),
    minScale: PhotoViewComputedScale.contained * 0.8,
    maxScale: PhotoViewComputedScale.covered * 2,
  );
}
```

---

## Best Practices

### 1. Handle Timeouts Gracefully
```dart
Future<AnalysisResponse> analyzeWithTimeout(List<int> imageBytes) async {
  try {
    return await service.analyze(imageBytes).timeout(
      Duration(seconds: 120),
      onTimeout: () => throw TimeoutException('Analysis took too long'),
    );
  } on TimeoutException {
    // Show user-friendly message
    // Suggest reducing image size
  }
}
```

### 2. Validate Before Upload
```dart
bool validateImage(List<int> imageBytes) {
  // Check file size (limit to 10MB)
  const maxSizeBytes = 10 * 1024 * 1024; // 10 MB
  if (imageBytes.length > maxSizeBytes) {
    return false;
  }
  
  // Check JPEG/PNG signature
  if (imageBytes[0] == 0xFF && imageBytes[1] == 0xD8) {
    return true; // JPEG
  }
  if (imageBytes[0] == 0x89 && imageBytes[1] == 0x50) {
    return true; // PNG
  }
  
  return false;
}
```

### 3. Cache Results
```dart
class AnalysisCache {
  static final Map<String, AnalysisResponse> _cache = {};

  static String hashImage(List<int> imageBytes) {
    return sha256.convert(imageBytes).toString();
  }

  static void store(List<int> imageBytes, AnalysisResponse response) {
    _cache[hashImage(imageBytes)] = response;
  }

  static AnalysisResponse? retrieve(List<int> imageBytes) {
    return _cache[hashImage(imageBytes)];
  }
}
```

### 4. Permission Handling
```dart
import 'package:permission_handler/permission_handler.dart';

Future<bool> requestCameraPermission() async {
  final status = await Permission.camera.request();
  return status.isGranted;
}

Future<bool> requestGalleryPermission() async {
  final status = await Permission.photos.request();
  return status.isGranted;
}
```

### 5. Network State Awareness
```dart
import 'package:connectivity_plus/connectivity_plus.dart';

bool isNetworkAvailable() {
  final connectivity = Connectivity();
  return connectivity.checkConnectivity().then((result) {
    return result != ConnectivityResult.none;
  });
}

// Show offline message if needed
```

---

## Troubleshooting

### Issue: "Connection refused"
**Cause**: Backend not running  
**Solution**: 
```bash
cd /path/to/backend
source .venv/bin/activate
python main.py
```

### Issue: "Image too large"
**Cause**: File size > 10MB  
**Solution**: Compress before upload
```dart
import 'package:flutter_image_compress/flutter_image_compress.dart';

List<int> compressImage(List<int> imageBytes) {
  return XFile.fromData(imageBytes)
      .compress(quality: 85)
      .then((file) => file.readAsBytes());
}
```

### Issue: "CORS Error"
**Cause**: Frontend URLs not whitelisted  
**Solution**: Backend already has CORS enabled via Flask-CORS

### Issue: "Timeout after 120s"
**Cause**: Large image or slow server  
**Solution**: 
- Reduce image resolution
- Check server CPU/memory
- Increase timeout threshold

### Issue: "Invalid base64 image"
**Cause**: Corrupted response data  
**Solution**: 
- Log full response: `print(response.body)`
- Check server error logs
- Retry with different image

### Issue: Model not loaded
**Error**: `"YOLO model not loaded"`  
**Cause**: `models/best.pt` missing  
**Solution**: Verify model files exist in backend

---

## Environment-Specific Configuration

### Development
```dart
const String API_BASE = 'http://localhost:5001';
const bool DEBUG = true;
const int TIMEOUT = 120;
```

### Staging
```dart
const String API_BASE = 'https://staging-api.railway.app';
const bool DEBUG = true;
const int TIMEOUT = 120;
```

### Production
```dart
const String API_BASE = 'https://your-production-api.railway.app';
const bool DEBUG = false;
const int TIMEOUT = 120;
```

### Switch at Runtime
```dart
String getBaseUrl() {
  if (kDebugMode) {
    return 'http://localhost:5001';
  }
  return 'https://your-production-api.railway.app';
}
```

---

## API Testing

### cURL Examples

**Validation:**
```bash
curl -X POST http://localhost:5001/validate-ct \
  -F "file=@path/to/scan.jpg"
```

**Analysis:**
```bash
curl -X POST http://localhost:5001/analyze \
  -F "file=@path/to/scan.jpg"
```

**Health Check:**
```bash
curl http://localhost:5001/health
```

### Postman Setup
1. Create POST request to `http://localhost:5001/analyze`
2. Go to "Body" tab β†’ Select "form-data"
3. Add key "file" (type: File)
4. Select image file
5. Send & view response

---

## Dependencies for Flutter

Add to `pubspec.yaml`:
```yaml
dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0
  image_picker: ^1.0.0
  photo_view: ^0.14.0
  flutter_image_compress: ^2.1.0
  permission_handler: ^11.4.0
  connectivity_plus: ^5.0.0
  crypto: ^3.0.0
```

---

## Performance Metrics

| Operation | Time | Notes |
|-----------|------|-------|
| Image Upload | 1-5s | Depends on image size & network |
| YOLO Detection | 5-15s | GPU faster if available |
| DenseNet Classification | 2-5s | Per tumor detected |
| Grad-CAM Heatmap | 2-3s | Per tumor |
| **Total** | **10-30s** | End-to-end (single tumor) |

---

## Support & Contact

For issues or questions:
1. Check [Troubleshooting](#troubleshooting) section
2. Review API logs: `python main.py` console output
3. Test with cURL first: ensure backend works
4. Check Flutter app logs: `flutter logs`
5. Verify network connectivity & firewall rules

---

**API Version**: 1.0.0  
**Last Updated**: March 8, 2026  
**Compatibility**: Flutter 3.0+ , Dart 3.0+