import os import csv import numpy as np import cv2 import time import torch from PIL import Image import Levenshtein import psutil def calc_cer(pred, gt): if not gt: return float(len(pred)) return Levenshtein.distance(pred, gt) / max(len(gt), 1) def calc_wer(pred, gt): pred_words = pred.split() gt_words = gt.split() if not gt_words: return float(len(pred_words)) return Levenshtein.distance(pred_words, gt_words) / max(len(gt_words), 1) def main(): print("Loading PARSeq...") parseq = torch.hub.load('baudm/parseq', 'parseq', pretrained=True).eval() import torchvision.transforms as T img_transform = T.Compose([ T.Resize((32, 128), T.InterpolationMode.BICUBIC), T.ToTensor(), T.Normalize(0.5, 0.5) ]) # We will load TrOCR predictions from forensics.json and apply regex, or we just rely on the stored CER=0.3238 # But wait, we need exact comparison to identify TrOCR right/PARSeq wrong, etc. # Actually, I can just load the predictions I saved from the adversarial experiment? # No, adversarial experiment didn't save the strings, it just printed them. # Let me re-run TrOCR Regex locally or just load the base predictions from forensics.json and regex them! import json import re print("Loading forensics.json for TrOCR Base predictions...") with open("forensics.json", "r") as f: saved = json.load(f) trocr_base_preds = saved["large"] def regex_cleanup(text): cleaned = re.sub(r'\s+[.,?!;:\]\)]+$', '', text) return cleaned.strip() trocr_preds = [regex_cleanup(p) for p in trocr_base_preds] print("Loading dataset...") with open("iam_words_sample/iam_sample.csv", "r", encoding="utf-8") as f: data = list(csv.DictReader(f))[:300] parseq_preds = [] parseq_confs = [] latencies = [] process = psutil.Process() start_mem = process.memory_info().rss / 1024 / 1024 print("Running PARSeq benchmark...") with torch.no_grad(): for i, row in enumerate(data): t0 = time.time() img = Image.open(row["crop_path"]).convert('RGB') # PARSeq transform img = img_transform(img).unsqueeze(0) logits = parseq(img) pred = logits.softmax(-1) label, confidence = parseq.tokenizer.decode(pred) parseq_preds.append(label[0]) # confidence is a tensor of per-character confidences. we can take the product or mean # Actually, mean of log probs is better, but mean of probs is fine for now conf = confidence[0].mean().item() parseq_confs.append(conf) latencies.append(time.time() - t0) if (i+1) % 50 == 0: print(f"[{i+1}/300] Processed.") end_mem = process.memory_info().rss / 1024 / 1024 # Metrics gts = [row["ground_truth"] for row in data] p_cer = sum(calc_cer(p, g) for p, g in zip(parseq_preds, gts)) / len(gts) p_wer = sum(calc_wer(p, g) for p, g in zip(parseq_preds, gts)) / len(gts) t_cer = sum(calc_cer(p, g) for p, g in zip(trocr_preds, gts)) / len(gts) t_wer = sum(calc_wer(p, g) for p, g in zip(trocr_preds, gts)) / len(gts) p50_lat = np.percentile(latencies, 50) p95_lat = np.percentile(latencies, 95) print("\n=== BENCHMARK RESULTS ===") print(f"TrOCR-Large + Regex - CER: {t_cer:.4f} | WER: {t_wer:.4f}") print(f"PARSeq - CER: {p_cer:.4f} | WER: {p_wer:.4f}") print(f"PARSeq Latency - P50: {p50_lat*1000:.1f}ms | P95: {p95_lat*1000:.1f}ms") print(f"PARSeq Memory Delta - {end_mem - start_mem:.1f} MB") # Win/Loss Matrix both_correct = 0 both_wrong = 0 parseq_wins = 0 trocr_wins = 0 parseq_wins_log = [] trocr_wins_log = [] for gt, t, p in zip(gts, trocr_preds, parseq_preds): if t == gt and p == gt: both_correct += 1 elif t != gt and p != gt: both_wrong += 1 elif p == gt and t != gt: parseq_wins += 1 parseq_wins_log.append((gt, t, p)) elif t == gt and p != gt: trocr_wins += 1 trocr_wins_log.append((gt, t, p)) print(f"\n=== WIN/LOSS MATRIX ===") print(f"Both Correct : {both_correct}") print(f"Both Wrong : {both_wrong}") print(f"PARSeq Wins : {parseq_wins} (PARSeq right, TrOCR wrong)") print(f"TrOCR Wins : {trocr_wins} (TrOCR right, PARSeq wrong)") print("\n[Examples where PARSeq won (TrOCR failed)]:") for gt, t, p in parseq_wins_log[:10]: print(f"GT: '{gt}' | TrOCR: '{t}' | PARSeq: '{p}'") print("\n[Examples where TrOCR won (PARSeq failed)]:") for gt, t, p in trocr_wins_log[:10]: print(f"GT: '{gt}' | TrOCR: '{t}' | PARSeq: '{p}'") if __name__ == "__main__": main()