-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1843 lines (1506 loc) · 55.3 KB
/
server.py
File metadata and controls
1843 lines (1506 loc) · 55.3 KB
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
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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import cv2
import numpy as np
from risk_evolution import risk_weight_evolution
import torch
from pathlib import Path
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from PIL import Image
import torchvision.transforms as transforms
from scipy import ndimage
import io
import random
import time
from torchvision.datasets import MNIST
from torchvision.transforms import GaussianBlur
from sklearn.metrics import confusion_matrix
from fastapi.responses import StreamingResponse
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table
from reportlab.lib.styles import getSampleStyleSheet
from datetime import datetime
import os
from dotenv import load_dotenv
from pymongo import MongoClient
from model_def import MNISTCNN
from download_modes import ensure_models
import re
import pytesseract
import easyocr
# Configure Tesseract path for Windows
import platform
if platform.system() == "Windows":
_tesseract_path = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
if os.path.exists(_tesseract_path):
pytesseract.pytesseract.tesseract_cmd = _tesseract_path
# Initialize EasyOCR reader (fallback for handwriting)
_easyocr_reader = None
def get_easyocr_reader():
global _easyocr_reader
if _easyocr_reader is None:
_easyocr_reader = easyocr.Reader(['en'], gpu=torch.cuda.is_available())
return _easyocr_reader
import io
from torchvision.datasets import CIFAR10
from model_def import CIFARCNN
import torch.quantization as quant
load_dotenv()
MONGODB_URI = os.getenv("MONGODB_URI")
if not MONGODB_URI:
raise RuntimeError("MONGODB_URI missing from .env")
# =========================
# TORCH CONFIG
# =========================
torch.set_grad_enabled(False)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
# =========================
# APP
# =========================
app = FastAPI()
# =========================
# MONGO CONNECTION
# =========================
mongo_client = MongoClient(MONGODB_URI)
# Atlas URL DB NAME → fintech-auth
mongo_db = mongo_client["fintech-auth"]
mongo_results = mongo_db["model_results"]
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
BASE_DIR = Path(__file__).resolve().parent
MODEL_DIR = BASE_DIR / "model"
DATA_DIR = BASE_DIR / "data"
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
MODEL_FILES = [
"baseline_mnist.pth",
"kd_mnist.pth",
"lrf_mnist.pth",
"pruned_mnist.pth",
"quantized_mnist.pth",
"ws_mnist.pth",
]
CIFAR_MODEL_FILES = [
"baseline_cifar.pth",
"kd_cifar.pth",
"lrf_cifar.pth",
"pruned_cifar.pth",
"quantized_cifar.pth",
"ws_cifar.pth",
]
# ==================================================
# PDF HELPER → BUILD METRIC TABLE
# ==================================================
def build_perturbation_transform(
blur=0,
rotation=0,
noise_std=0,
erase_pct=0
):
t = [
transforms.Grayscale(1),
transforms.Resize((28, 28)),
]
if rotation > 0:
t.append(
transforms.RandomRotation(
degrees=(-rotation, rotation),
fill=0
)
)
if blur > 0:
t.append(GaussianBlur(5, blur))
t.append(transforms.ToTensor())
if noise_std > 0:
t.append(
transforms.Lambda(
lambda x: torch.clamp(
x + noise_std * torch.randn_like(x),
0, 1
)
)
)
if erase_pct > 0:
t.append(
transforms.RandomErasing(
p=1.0,
scale=(erase_pct, erase_pct),
value=0
)
)
return transforms.Compose(t)
def build_cifar_perturbation_transform(
blur=0, rotation=0, noise_std=0
):
t = [transforms.Resize((32, 32))]
if rotation > 0:
t.append(transforms.RandomRotation(rotation))
if blur > 0:
t.append(GaussianBlur(5, blur))
t.append(transforms.ToTensor())
if noise_std > 0:
t.append(transforms.Lambda(
lambda x: torch.clamp(x + noise_std * torch.randn_like(x), 0, 1)
))
return transforms.Compose(t)
def build_pdf_metric_rows(result_models: dict):
rows = [[
"Model",
"Confidence (%)",
"Latency (ms)",
"Entropy",
"Stability",
"Risk Score"
]]
def pick(data, *keys, default="-"):
for k in keys:
if k in data and data[k] is not None:
return round(data[k], 4) if isinstance(data[k], float) else data[k]
return default
for model_name, data in result_models.items():
eval_data = data.get("evaluation", {})
rows.append([
model_name,
pick(data, "confidence_percent", "confidence_mean"),
pick(data, "latency_ms", "latency_mean"),
pick(data, "entropy", "entropy_mean"),
pick(data, "stability", "stability_mean"),
pick(eval_data, "risk_score"),
])
return rows
# =========================
# LOAD KD MNIST MODEL
# =========================
MNIST_MODELS = {}
CIFAR_MODELS = {}
@app.on_event("startup")
def startup_event():
"""
Runs once when the app starts.
Ensures models exist and loads them into memory.
"""
ensure_models()
load_models()
def load_models():
MNIST_MODELS.clear()
CIFAR_MODELS.clear()
# ---------- MNIST ----------
for f in MODEL_FILES:
path = MODEL_DIR / f
model = MNISTCNN().to(DEVICE)
model.load_state_dict(torch.load(path, map_location=DEVICE), strict=False)
model.eval()
MNIST_MODELS[f] = model
print("✅ MNIST models loaded")
# ---------- CIFAR ----------
for f in CIFAR_MODEL_FILES:
path = MODEL_DIR / f
state_dict = torch.load(path, map_location="cpu")
# 🔥 FIX: dequantize only quantized CIFAR
if "quantized" in f:
print(f"⚠️ Dequantizing {f}")
for k, v in state_dict.items():
if hasattr(v, "dequantize"):
state_dict[k] = v.dequantize()
model = CIFARCNN().to(DEVICE)
model.load_state_dict(state_dict, strict=False)
model.eval()
CIFAR_MODELS[f] = model
print("✅ CIFAR models loaded")
def set_seed(seed: int):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
# =========================
# TRANSFORM
# =========================
TRANSFORM = transforms.Compose([
transforms.ToTensor(), # already 28x28
])
CIFAR_CLEAN = transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
])
def CIFAR_NOISY(std=0.1):
return transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Lambda(
lambda x: torch.clamp(
x + std * torch.randn_like(x), 0, 1
)
),
])
#==================
# ENHANCE KEYSTROKE
#==================
def enhance_strokes(gray):
kernel = np.ones((2, 2), np.uint8)
# close gaps in strokes
gray = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel)
# thicken strokes slightly
gray = cv2.dilate(gray, kernel, iterations=0)
return gray
# =========================
# CLEAN IMAGE (CHEQUE SAFE)
# =========================
def clean_image(img: Image.Image):
img = np.array(img.convert("L"))
img = enhance_strokes(img)
_, img = cv2.threshold(
img, 0, 255,
cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
)
return img
# =========================
# MNIST NORMALIZATION (CRITICAL)
# =========================
def normalize_mnist_digit(digit_img):
"""
Convert segmented digit into MNIST-style 28x28 image
digit_img: binary image (white digit on black background)
"""
# 1️⃣ Crop tight bounding box
coords = cv2.findNonZero(digit_img)
if coords is None:
return None
x, y, w, h = cv2.boundingRect(coords)
digit_img = digit_img[y:y+h, x:x+w]
# 2️⃣ Aspect-ratio safe resize (max side = 20)
h, w = digit_img.shape
scale = 20.0 / max(h, w)
new_w = max(1, int(w * scale))
new_h = max(1, int(h * scale))
digit_img = cv2.resize(
digit_img,
(new_w, new_h),
interpolation=cv2.INTER_AREA
)
# 3️⃣ Place in 28x28 canvas (centered)
canvas = np.zeros((28, 28), dtype=np.uint8)
y_offset = (28 - new_h) // 2
x_offset = (28 - new_w) // 2
canvas[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = digit_img
# 4️⃣ Center-of-mass alignment (CRITICAL for MNIST)
cy, cx = ndimage.center_of_mass(canvas)
if np.isnan(cx) or np.isnan(cy):
return None
shift_x = int(round(14 - cx))
shift_y = int(round(14 - cy))
canvas = ndimage.shift(
canvas,
shift=(shift_y, shift_x),
mode="constant",
cval=0
)
return Image.fromarray(canvas.astype(np.uint8))
# =========================
# SEGMENT DIGITS (OPENCV)
# =========================
def segment_digits(img):
num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(
img, connectivity=8
)
digits = []
for i in range(1, num_labels): # skip background
x, y, w, h, area = stats[i]
if area < 80 or w < 8 or h < 15:
continue
digit = img[y:y+h, x:x+w]
digits.append((x, digit))
digits.sort(key=lambda d: d[0])
return [d[1] for d in digits]
# =========================
# MNIST INFERENCE
# =========================
@torch.inference_mode()
def classify_digit(img):
model = MNIST_MODELS["kd_mnist.pth"] # ✅ explicit
tensor = TRANSFORM(img).unsqueeze(0).to(DEVICE)
probs = torch.softmax(model(tensor), dim=1)[0]
top = torch.topk(probs, 3)
return [
{
"digit": int(d),
"confidence": round(float(c * 100), 2)
}
for d, c in zip(top.indices.cpu(), top.values.cpu())
]
# =========================
# API
# =========================
# ==================================================
# TRANSFORMS
# ==================================================
CLEAN = transforms.Compose([
transforms.Grayscale(1),
transforms.Resize((28, 28)),
transforms.ToTensor(),
])
def NOISY(std=0.2):
return transforms.Compose([
transforms.Grayscale(1),
transforms.Resize((28, 28)),
transforms.ToTensor(),
transforms.Lambda(lambda x: torch.clamp(
x + std * torch.randn_like(x), 0.0, 1.0
)),
])
def BLUR():
return transforms.Compose([
transforms.Grayscale(1),
transforms.Resize((28, 28)),
GaussianBlur(5, 1.0),
transforms.ToTensor(),
])
def NOISY_BLUR(std=0.2):
return transforms.Compose([
transforms.Grayscale(1),
transforms.Resize((28, 28)),
GaussianBlur(5, 1.0),
transforms.ToTensor(),
transforms.Lambda(lambda x: torch.clamp(
x + std * torch.randn_like(x), 0.0, 1.0
)),
])
def compute_far_frr_generic(y_true, y_pred, num_classes):
cm = confusion_matrix(y_true, y_pred, labels=list(range(num_classes)))
total = cm.sum()
FARs, FRRs = [], []
for c in range(num_classes):
TP = cm[c, c]
FP = cm[:, c].sum() - TP
FN = cm[c, :].sum() - TP
TN = total - TP - FP - FN
FARs.append(FP / (FP + TN + 1e-8))
FRRs.append(FN / (FN + TP + 1e-8))
return cm.tolist(), round(np.mean(FARs), 4), round(np.mean(FRRs), 4)
def risk_score(FAR, FRR, alpha=0.5, beta=0.5):
return round(alpha * FAR + beta * FRR, 4)
# ======================================================
# INFERENCE CORE
# ======================================================
@torch.inference_mode()
def run_batch(images, true_labels=None):
batch = torch.stack(images).to(DEVICE)
out = {}
for name, model in MNIST_MODELS.items():
start = time.perf_counter()
logits = model(batch)
probs = torch.softmax(logits, dim=1)
preds = probs.argmax(dim=1).cpu().numpy()
entry = {
"latency_ms": round((time.perf_counter() - start) * 1000 / len(batch), 3),
"confidence_percent": round(probs.max(dim=1).values.mean().item() * 100, 2),
"entropy": round(float(-(probs * torch.log(probs + 1e-8)).sum(dim=1).mean()), 4),
"stability": round(float(logits.std()), 4),
"ram_mb": 0.0,
}
if true_labels is not None:
cm, FAR, FRR = compute_far_frr_generic(true_labels, preds, num_classes=10)
entry["evaluation"] = {
"confusion_matrix": cm,
"FAR": FAR,
"FRR": FRR,
"risk_score": risk_score(FAR, FRR)
}
out[name] = entry
return out
@torch.inference_mode()
def run_batch_cifar(images, true_labels=None):
batch = torch.stack(images).to(DEVICE)
out = {}
for name, model in CIFAR_MODELS.items():
start = time.perf_counter()
logits = model(batch)
probs = torch.softmax(logits, dim=1)
preds = probs.argmax(dim=1).cpu().numpy()
entry = {
"latency_ms": round((time.perf_counter() - start) * 1000 / len(batch), 3),
"confidence_percent": round(
probs.max(dim=1).values.mean().item() * 100, 2
),
"entropy": round(
float(-(probs * torch.log(probs + 1e-8)).sum(dim=1).mean()), 4
),
"stability": round(float(logits.std()), 4),
"ram_mb": 0.0,
}
if true_labels is not None:
cm, FAR, FRR = compute_far_frr_generic(true_labels, preds, num_classes=10)
entry["evaluation"] = {
"confusion_matrix": cm,
"FAR": FAR,
"FRR": FRR,
"risk_score": risk_score(FAR, FRR),
}
out[name] = entry
return out
# ==================================================
# INFERENCE (MULTI RUN – NOISY)
# ==================================================
def run_noisy_multi_eval(build_fn, true_labels, runs=5):
acc = {k: [] for k in MNIST_MODELS}
all_preds = {k: [] for k in MNIST_MODELS}
for r in range(runs):
set_seed(42 + r)
images = build_fn()
res = run_batch(images)
for m, v in res.items():
acc[m].append(v)
batch = torch.stack(images).to(DEVICE)
for name, model in MNIST_MODELS.items():
logits = model(batch)
preds = torch.softmax(logits, dim=1).argmax(dim=1)
all_preds[name].extend(preds.cpu().numpy())
final = {}
for m, vals in acc.items():
entry = {
"latency_mean": round(np.mean([x["latency_ms"] for x in vals]), 3),
"latency_std": round(np.std([x["latency_ms"] for x in vals]), 3),
"confidence_mean": round(np.mean([x["confidence_percent"] for x in vals]), 2),
"confidence_std": round(np.std([x["confidence_percent"] for x in vals]), 2),
"entropy_mean": round(np.mean([x["entropy"] for x in vals]), 4),
"entropy_std": round(np.std([x["entropy"] for x in vals]), 4),
"stability_mean": round(np.mean([x["stability"] for x in vals]), 4),
"stability_std": round(np.std([x["stability"] for x in vals]), 4),
}
repeated_labels = true_labels * runs
cm, FAR, FRR = compute_far_frr_generic(
repeated_labels,
all_preds[m],
num_classes=10
)
entry["evaluation"] = {
"confusion_matrix": cm,
"FAR": FAR,
"FRR": FRR,
"risk_score": risk_score(FAR, FRR)
}
final[m] = entry
return final
# ==================================================
# SINGLE IMAGE (WITH STRESS SUPPORT)
# ==================================================
@app.post("/run")
async def run(
image: UploadFile = File(...),
expected_digit: int = Form(...),
# ⭐ STRESS CONTROLS
blur: float = Form(0),
rotation: float = Form(0),
noise: float = Form(0),
erase: float = Form(0),
):
img = Image.open(io.BytesIO(await image.read())).convert("L")
use_stress = blur > 0 or rotation > 0 or noise > 0 or erase > 0
if use_stress:
transform = build_perturbation_transform(
blur=blur,
rotation=rotation,
noise_std=noise,
erase_pct=erase
)
tensor_img = transform(img)
else:
tensor_img = CLEAN(img)
# ---------- RUN INFERENCE ----------
mnist_results = run_batch(
[tensor_img],
true_labels=[expected_digit]
)
ea_result = risk_weight_evolution(mnist_results)
# ---------- BUILD DOCUMENT ----------
doc = {
"createdAt": datetime.utcnow(),
"data": {
"MNIST": mnist_results,
"ea_optimization": ea_result
},
"meta": {
"evaluation_type": "SINGLE",
"source": "IMAGE_UPLOAD",
"expected_digit": expected_digit,
"stress_applied": use_stress,
}
}
inserted = mongo_results.insert_one(doc)
# ---------- RETURN ID ----------
return {
"id": str(inserted.inserted_id)
}
@app.post("/run-dataset")
async def run_dataset(
dataset_name: str = Form(...),
blur: float = Form(0),
rotation: float = Form(0),
noise: float = Form(0),
erase: float = Form(0),
):
if not dataset_name:
raise HTTPException(400, "dataset_name required")
# ---------------- LOAD DATASETS ----------------
base = MNIST(root=DATA_DIR, train=False, download=True)
cifar = CIFAR10(root=DATA_DIR, train=False, download=True)
use_stress = blur > 0 or rotation > 0 or noise > 0 or erase > 0
# ============================================================
# CIFAR EVALUATION
# ============================================================
cifar_transform = (
build_cifar_perturbation_transform(
blur=blur,
rotation=rotation,
noise_std=noise
)
if use_stress else CIFAR_CLEAN
)
MAX_CIFAR = 1000
cifar_imgs = [cifar_transform(cifar[i][0]) for i in range(MAX_CIFAR)]
cifar_lbls = [cifar[i][1] for i in range(MAX_CIFAR)]
cifar_results = run_batch_cifar(cifar_imgs, cifar_lbls)
# Static baseline (alpha = 0.5)
cifar_static_scores = {
name: model["evaluation"]["risk_score"]
for name, model in cifar_results.items()
}
cifar_static_best = min(cifar_static_scores, key=cifar_static_scores.get)
# EA optimization for CIFAR
cifar_ea_result = risk_weight_evolution(cifar_results)
# ============================================================
# MNIST EVALUATION
# ============================================================
if use_stress:
mnist_transform = build_perturbation_transform(
blur=blur,
rotation=rotation,
noise_std=noise,
erase_pct=erase
)
else:
mnist_transform = CLEAN
# Dataset selection
if dataset_name == "MNIST_100":
limit = 100
images = [mnist_transform(base[i][0]) for i in range(limit)]
labels = [base[i][1] for i in range(limit)]
mnist_results = run_batch(images, labels)
elif dataset_name == "MNIST_500":
limit = 500
images = [mnist_transform(base[i][0]) for i in range(limit)]
labels = [base[i][1] for i in range(limit)]
mnist_results = run_batch(images, labels)
elif dataset_name == "MNIST_FULL":
limit = len(base)
images = [mnist_transform(base[i][0]) for i in range(limit)]
labels = [base[i][1] for i in range(limit)]
mnist_results = run_batch(images, labels)
elif dataset_name.startswith("MNIST_NOISY"):
limit = 100 if "100" in dataset_name else 500
labels = [base[i][1] for i in range(limit)]
if "BLUR" in dataset_name:
build_fn = lambda: [NOISY_BLUR()(base[i][0]) for i in range(limit)]
else:
build_fn = lambda: [NOISY()(base[i][0]) for i in range(limit)]
mnist_results = run_noisy_multi_eval(
build_fn,
true_labels=labels
)
else:
raise HTTPException(400, "Unknown dataset")
# ---------------- STATIC BASELINE (α=0.5) ----------------
mnist_static_scores = {
name: model["evaluation"]["risk_score"]
for name, model in mnist_results.items()
}
mnist_static_best = min(mnist_static_scores, key=mnist_static_scores.get)
# ---------------- EA OPTIMIZATION ----------------
mnist_ea_result = risk_weight_evolution(mnist_results)
# ============================================================
# BUILD DOCUMENT
# ============================================================
doc = {
"createdAt": datetime.utcnow(),
"data": {
"MNIST": mnist_results,
"CIFAR": cifar_results,
"ea_optimization": {
"MNIST": mnist_ea_result,
"CIFAR": cifar_ea_result,
},
"static_baseline": {
"MNIST_best_model": mnist_static_best,
"CIFAR_best_model": cifar_static_best,
}
},
"meta": {
"evaluation_type": "DATASET",
"dataset_type": dataset_name,
"num_images": limit,
"stress_applied": use_stress,
}
}
inserted = mongo_results.insert_one(doc)
return {
"id": str(inserted.inserted_id)
}
# ==================================================
# OCR
# ==================================================
import pytesseract
@app.post("/verify")
async def verify(image: UploadFile = File(...), raw_text: str = Form(...)):
img = Image.open(image.file).convert("L").resize((128, 32))
ocr_text = pytesseract.image_to_string(
img,
config="--psm 10 --oem 1 -c tessedit_char_whitelist=0123456789",
).strip()
errors = []
max_len = max(len(raw_text), len(ocr_text))
for i in range(max_len):
typed_char = raw_text[i] if i < len(raw_text) else ""
ocr_char = ocr_text[i] if i < len(ocr_text) else ""
if typed_char != ocr_char:
errors.append({
"position": i + 1,
"typed_char": typed_char,
"ocr_char": ocr_char,
})
return {
"verdict": "VALID_TYPED_TEXT" if not errors else "INVALID_OR_AMBIGUOUS",
"final_output": ocr_text,
"errors": errors,
"why": (
"OCR output perfectly matches typed text."
if not errors
else "One or more characters differ between typed text and OCR output."
),
}
import base64
def encode_img(img):
_, buf = cv2.imencode(".png", img)
return base64.b64encode(buf).decode()
CONF_MARGIN = 5 # +/- window for ambiguous
@app.post("/verify-digit-only")
async def verify_digit_only(
image: UploadFile = File(...),
confidence_threshold: float = Form(0.90) # 0.0 – 1.0
):
try:
raw = Image.open(image.file).convert("L")
# ===== PREPROCESS =====
cleaned = clean_image(raw)
digit_imgs = segment_digits(cleaned)
if not digit_imgs:
return {
"verdict": "INVALID",
"digits": "",
"analysis": [],
"preview": None
}
threshold_pct = confidence_threshold * 100
buffer_pct = threshold_pct - 5
analysis = []
final_digits = []
verdict = "VALID"
preview_cropped = None
preview_norm = None
# ===== DIGIT LOOP =====
for i, dimg in enumerate(digit_imgs):
# Save first cropped preview
if preview_cropped is None:
preview_cropped = encode_img(dimg)
mnist_img = normalize_mnist_digit(dimg)
if mnist_img is None:
verdict = "INVALID"
analysis.append({
"position": i + 1,
"predicted": None,
"confidence": 0,
"status": "INVALID"
})
final_digits.append("?")
continue
# Save normalized preview
if preview_norm is None:
preview_norm = encode_img(np.array(mnist_img))
# ===== MODEL INFERENCE (.pth) =====
preds = classify_digit(mnist_img)
best = preds[0]
conf = best["confidence"]
# ===== B MODE DECISION =====
if conf >= threshold_pct:
status = "VALID"
elif conf >= buffer_pct:
status = "AMBIGUOUS"
if verdict != "INVALID":
verdict = "AMBIGUOUS"
else:
status = "INVALID"
verdict = "INVALID"
analysis.append({
"position": i + 1,
"predicted": str(best["digit"]),
"confidence": conf,
"status": status,
"possible_values": [p["digit"] for p in preds]
})
final_digits.append(str(best["digit"]))
return {
"verdict": verdict,
"digits": "".join(final_digits),
"analysis": analysis,
"preview": {
"original": encode_img(np.array(raw)),
"cropped": preview_cropped,
"normalized": preview_norm
}
}
except Exception as e:
return {
"verdict": "ERROR",
"message": str(e)
}
# ==================================================
# PDF EXPORT
# ==================================================
from bson import ObjectId
from fastapi import HTTPException
from fastapi.responses import StreamingResponse
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from datetime import datetime
import io
@app.get("/export/pdf/{id}")
def export_pdf_from_db(id: str):
try:
# =========================
# FETCH RESULT FROM DB
# =========================
doc = mongo_results.find_one({"_id": ObjectId(id)})
if not doc:
raise HTTPException(404, "Result not found")
models_by_family = doc["data"]
meta = doc.get("meta", {})
# =========================
# PDF SETUP
# =========================
buffer = io.BytesIO()
styles = getSampleStyleSheet()
title_style = ParagraphStyle(
"TitleStyle",
parent=styles["Title"],
fontSize=26,
textColor=colors.HexColor("#1e3a8a"),
alignment=1,
)
section_style = ParagraphStyle(
"SectionStyle",
parent=styles["Heading2"],
textColor=colors.HexColor("#2563eb"),
)
story = []
# =========================
# TITLE
# =========================
story.append(Paragraph("Model Evaluation Report", title_style))
story.append(Spacer(1, 12))