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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
# API Documentation

## Base Information

**Base URL**: `http://localhost:8005`  
**API Version**: `1.0.0`  
**Protocol**: HTTP/HTTPS  
**Content Type**: `application/json` (default)

---

## Table of Contents

1. [Authentication](#authentication)
2. [Health Check](#health-check)
3. [Single Image Analysis](#single-image-analysis)
4. [Batch Image Analysis](#batch-image-analysis)
5. [Batch Progress Tracking](#batch-progress-tracking)
6. [Report Export](#report-export)
7. [Error Handling](#error-handling)
8. [Rate Limits](#rate-limits)
9. [Data Models](#data-models)

---

## Authentication

**Current Version**: No authentication required (intended for internal deployment)

**Future Versions**: API key authentication planned
```bash
# Planned header format
Authorization: Bearer <api_key>
```

---

## Health Check

### `GET /health`

Check if the API server is operational.

**Request**
```bash
curl -X GET http://localhost:8005/health
```

**Response** (`200 OK`)
```json
{
  "status": "ok",
  "version": "1.0.0"
}
```

---

## Single Image Analysis

### `POST /analyze/image`

Analyze a single image for AI-generation indicators.

**Request**

```bash
curl -X POST http://localhost:8005/analyze/image \
  -F "file=@/path/to/image.jpg"
```

**Parameters**

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `file` | File | Yes | Image file (JPG/PNG/WEBP, max 10MB) |

**Response** (`200 OK`)

```json
{
  "success": true,
  "message": "Image analysis completed",
  "data": {
    "filename": "example.jpg",
    "status": "REVIEW_REQUIRED",
    "overall_score": 0.73,
    "confidence": 73,
    "signals": [
      {
        "name": "Gradient Field PCA",
        "metric_type": "gradient",
        "score": 0.81,
        "status": "flagged",
        "explanation": "Detected irregular gradient patterns typical of diffusion models. Natural photos show consistent lighting gradients shaped by physics."
      },
      {
        "name": "Frequency Analysis",
        "metric_type": "frequency",
        "score": 0.68,
        "status": "warning",
        "explanation": "Frequency patterns show some irregularities. Requires further review."
      },
      {
        "name": "Noise Analysis",
        "metric_type": "noise",
        "score": 0.72,
        "status": "flagged",
        "explanation": "Noise pattern is unnaturally uniform. Real camera sensors produce characteristic noise patterns."
      },
      {
        "name": "Texture Analysis",
        "metric_type": "texture",
        "score": 0.65,
        "status": "warning",
        "explanation": "Some texture regions appear overly uniform. Further analysis recommended."
      },
      {
        "name": "Color Analysis",
        "metric_type": "color",
        "score": 0.54,
        "status": "warning",
        "explanation": "Some color histogram irregularities detected."
      }
    ],
    "metric_results": {
      "gradient": {
        "metric_type": "gradient",
        "score": 0.81,
        "confidence": 0.87,
        "details": {
          "eigenvalue_ratio": 0.72,
          "gradient_vectors_sampled": 10000,
          "threshold": 0.85
        }
      },
      "frequency": {
        "metric_type": "frequency",
        "score": 0.68,
        "confidence": 0.65,
        "details": {
          "hf_ratio": 0.38,
          "hf_anomaly": 0.45,
          "roughness": 0.032,
          "spectral_deviation": 0.21
        }
      },
      "noise": {
        "metric_type": "noise",
        "score": 0.72,
        "confidence": 0.78,
        "details": {
          "mean_noise": 1.12,
          "cv": 0.18,
          "patches_valid": 42,
          "patches_total": 100
        }
      },
      "texture": {
        "metric_type": "texture",
        "score": 0.65,
        "confidence": 0.71,
        "details": {
          "smooth_ratio": 0.45,
          "contrast_mean": 18.3,
          "entropy_mean": 4.2,
          "patches_used": 50
        }
      },
      "color": {
        "metric_type": "color",
        "score": 0.54,
        "confidence": 0.58,
        "details": {
          "saturation_stats": {
            "mean_saturation": 0.68,
            "high_sat_ratio": 0.23,
            "very_high_sat_ratio": 0.06
          },
          "histogram_stats": {
            "roughness_mean": 0.021,
            "channels_analyzed": 3
          },
          "hue_stats": {
            "top3_concentration": 0.58,
            "gap_ratio": 0.32
          }
        }
      }
    },
    "processing_time": 2.34,
    "image_size": [1920, 1080],
    "timestamp": "2024-12-19T14:32:15.123456"
  },
  "timestamp": "2024-12-19T14:32:15.123456"
}
```

**Status Values**
- `LIKELY_AUTHENTIC`: Score < 0.65 (default threshold)
- `REVIEW_REQUIRED`: Score >= 0.65

**Signal Status Values**
- `passed`: Score < 0.40
- `warning`: Score >= 0.40 and < 0.70
- `flagged`: Score >= 0.70

---

## Batch Image Analysis

### `POST /analyze/batch`

Analyze multiple images in a single request with parallel processing.

**Request**

```bash
curl -X POST http://localhost:8005/analyze/batch \
  -F "files=@image1.jpg" \
  -F "files=@image2.png" \
  -F "files=@image3.webp"
```

**Parameters**

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `files` | File[] | Yes | Multiple image files (max 50 per batch) |

**Response** (`200 OK`)

```json
{
  "success": true,
  "message": "Batch analysis completed",
  "data": {
    "batch_id": "550e8400-e29b-41d4-a716-446655440000",
    "result": {
      "total_images": 3,
      "processed": 3,
      "failed": 0,
      "results": [
        {
          "filename": "image1.jpg",
          "status": "REVIEW_REQUIRED",
          "overall_score": 0.73,
          "confidence": 73,
          "signals": [...],
          "metric_results": {...},
          "processing_time": 2.1,
          "image_size": [1920, 1080],
          "timestamp": "2024-12-19T14:32:15.123456"
        },
        {
          "filename": "image2.png",
          "status": "LIKELY_AUTHENTIC",
          "overall_score": 0.42,
          "confidence": 42,
          "signals": [...],
          "metric_results": {...},
          "processing_time": 2.3,
          "image_size": [2048, 1536],
          "timestamp": "2024-12-19T14:32:17.234567"
        },
        {
          "filename": "image3.webp",
          "status": "LIKELY_AUTHENTIC",
          "overall_score": 0.38,
          "confidence": 38,
          "signals": [...],
          "metric_results": {...},
          "processing_time": 1.9,
          "image_size": [1024, 768],
          "timestamp": "2024-12-19T14:32:19.345678"
        }
      ],
      "summary": {
        "likely_authentic": 2,
        "review_required": 1,
        "success_rate": 100,
        "processed": 3,
        "failed": 0,
        "avg_score": 0.510,
        "avg_confidence": 51,
        "avg_proc_time": 2.10
      },
      "total_processing_time": 6.3,
      "timestamp": "2024-12-19T14:32:19.345678"
    }
  },
  "timestamp": "2024-12-19T14:32:19.345678"
}
```

**Batch Constraints**
- Maximum images per batch: **50**
- Maximum file size per image: **10 MB**
- Timeout per image: **30 seconds**
- Total batch timeout: **15 minutes**

---

## Batch Progress Tracking

### `GET /batch/{batch_id}/progress`

Track the progress of a batch analysis job.

**Request**

```bash
curl -X GET http://localhost:8005/batch/550e8400-e29b-41d4-a716-446655440000/progress
```

**Response - Processing** (`200 OK`)

```json
{
  "status": "processing",
  "progress": {
    "current": 7,
    "total": 10,
    "filename": "image_007.jpg"
  }
}
```

**Response - Completed** (`200 OK`)

```json
{
  "status": "completed",
  "progress": {
    "current": 10,
    "total": 10,
    "filename": "image_010.jpg"
  },
  "result": {
    "total_images": 10,
    "processed": 10,
    "failed": 0,
    "results": [...],
    "summary": {...},
    "total_processing_time": 21.4,
    "timestamp": "2024-12-19T14:35:22.123456"
  }
}
```

**Response - Failed** (`200 OK`)

```json
{
  "status": "failed",
  "error": "Processing timeout exceeded"
}
```

**Status Values**
- `processing`: Batch is currently being analyzed
- `completed`: All images processed successfully
- `failed`: Batch processing encountered fatal error
- `interrupted`: Processing was manually stopped

---

## Report Export

### CSV Export

#### `GET /report/csv/{batch_id}` or `POST /report/csv/{batch_id}`

Download detailed batch analysis as CSV file.

**Request**

```bash
curl -X GET http://localhost:8005/report/csv/550e8400-e29b-41d4-a716-446655440000 \
  -o report.csv
```

**Response**

- Content-Type: `text/csv`
- File download with comprehensive analysis data
- Includes: per-image results, metric breakdowns, forensic details

**CSV Structure**
```
BATCH STATISTICS
Total Images,10
Successfully Processed,10
Failed,0
...

ANALYSIS RESULTS
Filename,Status,Overall Score,Confidence,Processing Time
image1.jpg,REVIEW_REQUIRED,0.73,73,2.1
image2.png,LIKELY_AUTHENTIC,0.42,42,2.3
...

IMAGE 1 DETAILED ANALYSIS
Metric Name,Score,Status,Explanation
Gradient Field PCA,0.81,flagged,Detected irregular gradient patterns...
...
```

---

### PDF Export

#### `GET /report/pdf/{batch_id}` or `POST /report/pdf/{batch_id}`

Download detailed batch analysis as PDF report.

**Request**

```bash
curl -X GET http://localhost:8005/report/pdf/550e8400-e29b-41d4-a716-446655440000 \
  -o report.pdf
```

**Response**

- Content-Type: `application/pdf`
- Professional formatted report with:
  - Executive summary
  - Per-image analysis sections
  - Visual metric breakdowns
  - Forensic details
  - Recommendations

---

## Error Handling

### Error Response Format

All errors return a standardized JSON structure:

```json
{
  "success": false,
  "message": "Error description",
  "error": "Detailed error message",
  "timestamp": "2024-12-19T14:32:15.123456"
}
```

### HTTP Status Codes

| Code | Meaning | Description |
|------|---------|-------------|
| `200` | OK | Request successful |
| `400` | Bad Request | Invalid input (file format, size, etc.) |
| `404` | Not Found | Batch ID not found |
| `413` | Payload Too Large | File size exceeds 10MB |
| `422` | Unprocessable Entity | Validation error |
| `499` | Client Closed Request | Processing interrupted |
| `500` | Internal Server Error | Server-side processing error |

### Common Error Scenarios

**File Too Large**
```json
{
  "success": false,
  "message": "Validation error",
  "error": "File size 12582912 bytes exceeds maximum 10485760 bytes",
  "timestamp": "2024-12-19T14:32:15.123456"
}
```

**Unsupported Format**
```json
{
  "success": false,
  "message": "Validation error",
  "error": "File extension .gif not allowed. Allowed: .jpg, .jpeg, .png, .webp",
  "timestamp": "2024-12-19T14:32:15.123456"
}
```

**Batch Not Found**
```json
{
  "success": false,
  "message": "Batch not found",
  "error": null,
  "timestamp": "2024-12-19T14:32:15.123456"
}
```

**Processing Timeout**
```json
{
  "success": false,
  "message": "Processing timeout",
  "error": "Image analysis exceeded 30 second timeout",
  "timestamp": "2024-12-19T14:32:45.123456"
}
```

---

## Rate Limits

**Current Version**: No rate limiting implemented

**Recommended Production Limits**:
- Single image analysis: **60 requests/minute per IP**
- Batch analysis: **10 requests/minute per IP**
- Report downloads: **30 requests/minute per IP**

---

## Data Models

### MetricResult

```typescript
{
  metric_type: "gradient" | "frequency" | "noise" | "texture" | "color",
  score: number,        // 0.0 - 1.0
  confidence: number,   // 0.0 - 1.0
  details: object       // Metric-specific forensic data
}
```

### DetectionSignal

```typescript
{
  name: string,
  metric_type: "gradient" | "frequency" | "noise" | "texture" | "color",
  score: number,        // 0.0 - 1.0
  status: "passed" | "warning" | "flagged",
  explanation: string
}
```

### AnalysisResult

```typescript
{
  filename: string,
  status: "LIKELY_AUTHENTIC" | "REVIEW_REQUIRED",
  overall_score: number,      // 0.0 - 1.0
  confidence: number,         // 0 - 100
  signals: DetectionSignal[],
  metric_results: {
    [key: string]: MetricResult
  },
  processing_time: number,    // seconds
  image_size: [number, number],
  timestamp: string           // ISO 8601 format
}
```

### BatchAnalysisResult

```typescript
{
  total_images: number,
  processed: number,
  failed: number,
  results: AnalysisResult[],
  summary: {
    likely_authentic: number,
    review_required: number,
    success_rate: number,     // percentage
    processed: number,
    failed: number,
    avg_score: number,
    avg_confidence: number,
    avg_proc_time: number
  },
  total_processing_time: number,
  timestamp: string
}
```

---

## Usage Examples

### Python

```python
import requests

# Single image analysis
with open('image.jpg', 'rb') as f:
    response = requests.post(
        'http://localhost:8005/analyze/image',
        files={'file': f}
    )
    result = response.json()
    print(f"Status: {result['data']['status']}")
    print(f"Score: {result['data']['overall_score']}")

# Batch analysis
files = [
    ('files', open('img1.jpg', 'rb')),
    ('files', open('img2.png', 'rb')),
    ('files', open('img3.webp', 'rb'))
]
response = requests.post(
    'http://localhost:8005/analyze/batch',
    files=files
)
batch_result = response.json()
batch_id = batch_result['data']['batch_id']

# Download CSV report
csv_response = requests.get(f'http://localhost:8005/report/csv/{batch_id}')
with open('report.csv', 'wb') as f:
    f.write(csv_response.content)
```

### JavaScript (Node.js)

```javascript
const FormData = require('form-data');
const fs = require('fs');
const axios = require('axios');

// Single image analysis
const form = new FormData();
form.append('file', fs.createReadStream('image.jpg'));

axios.post('http://localhost:8005/analyze/image', form, {
  headers: form.getHeaders()
})
.then(response => {
  console.log('Status:', response.data.data.status);
  console.log('Score:', response.data.data.overall_score);
})
.catch(error => {
  console.error('Error:', error.response.data);
});

// Batch analysis
const batchForm = new FormData();
batchForm.append('files', fs.createReadStream('img1.jpg'));
batchForm.append('files', fs.createReadStream('img2.png'));

axios.post('http://localhost:8005/analyze/batch', batchForm, {
  headers: batchForm.getHeaders()
})
.then(response => {
  const batchId = response.data.data.batch_id;
  console.log('Batch ID:', batchId);
  
  // Download PDF report
  return axios.get(`http://localhost:8005/report/pdf/${batchId}`, {
    responseType: 'arraybuffer'
  });
})
.then(pdfResponse => {
  fs.writeFileSync('report.pdf', pdfResponse.data);
  console.log('Report downloaded');
});
```

### cURL

```bash
# Single image
curl -X POST http://localhost:8005/analyze/image \
  -F "file=@image.jpg" \
  | jq '.data.status, .data.overall_score'

# Batch processing
curl -X POST http://localhost:8005/analyze/batch \
  -F "files=@img1.jpg" \
  -F "files=@img2.png" \
  -F "files=@img3.webp" \
  | jq '.data.batch_id'

# Progress tracking
curl -X GET http://localhost:8005/batch/{batch_id}/progress

# Download reports
curl -X GET http://localhost:8005/report/csv/{batch_id} -o report.csv
curl -X GET http://localhost:8005/report/pdf/{batch_id} -o report.pdf
```

---

## Changelog

### Version 1.0.0 (Current)
- Initial API release
- Single and batch image analysis
- CSV, JSON, PDF export
- Progress tracking
- Multi-metric ensemble detection

### Planned Features
- API key authentication
- Webhook callbacks for async processing
- Custom threshold configuration per request
- Historical analysis lookup
- Metrics-only API endpoints

---

*API Documentation Version: 1.0*  
*Last Updated: December 2025*