-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpipeline_multipage.py
More file actions
2295 lines (1813 loc) · 80.1 KB
/
Copy pathpipeline_multipage.py
File metadata and controls
2295 lines (1813 loc) · 80.1 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
# -*- coding: utf-8 -*-
"""pipeline_multipage.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1kVRCAPJDDpeWj2ILhDiEPEGZu0-QA3-d
## SETUP
Monto Drive e definisco i percorsi per MP-DocVQA. In più rispetto alla
versione single-page, definisco WINDOW_SIZE: il numero di pagine del
documento che passo al modello, centrate sulla pagina che contiene la
risposta (W=1 equivale al caso single-page).
"""
# ══ SETUP GLOBALE ══ CELLA DA RUNNARE SEMPRE
from google.colab import drive
drive.mount('/content/drive')
import json, os, re, random, tarfile, gc
from collections import Counter, defaultdict
SEED = 42
random.seed(SEED)
# ── Percorsi ──
DRIVE_DIR = '/content/drive/MyDrive/MP-docvqa'
QAS_DIR = f'{DRIVE_DIR}/qas'
IMG_DIR = f'{DRIVE_DIR}/qas/images' # ← immagini già su Drive, no tar
BENCH_PATH = f'{DRIVE_DIR}/benchmark_final.json'
PRED_DIR = f'{DRIVE_DIR}/predictions'
os.makedirs(PRED_DIR, exist_ok=True)
# Bilanciamento ragionevole
N_ENTITY = 34 # ~33% delle corrotte
N_ELEMENT = 33 # ~33% delle corrotte
N_LAYOUT = 33 # ~33% delle corrotte
N_CLEAN = 100 # 50/50 con le corrotte
# Totale: 100 corrotte + 100 clean = 200 campioni
# ── Parametro finestra MP-DocVQA ──
# 1 = solo pagina della risposta (equivalente a single-page)
# 2 = pagina risposta + una pagina adiacente
# 3 = finestra più ampia
WINDOW_SIZE = 2
"""## CARICAMENTO DATI
Carico le annotazioni di MP-DocVQA (train + validation). A differenza di
SP-DocVQA qui non c'è il campo question_types: aggiungo un placeholder per
riusare lo stesso campionamento stratificato della versione single-page.
"""
# ── Caricamento annotazioni MP-DocVQA (train + val) ──
with open(f'{QAS_DIR}/train.json') as f:
data_train = json.load(f)
with open(f'{QAS_DIR}/val.json') as f:
data_val = json.load(f)
all_data = data_train['data'] + data_val['data']
# MP-DocVQA non ha question_types — aggiunge placeholder
for s in all_data:
if 'question_types' not in s:
s['question_types'] = ['unknown']
print(f"Train: {len(data_train['data'])} | Val: {len(data_val['data'])} | Totale: {len(all_data)}")
print("\nEsempio di campione:")
campi = ('questionId', 'question', 'page_ids', 'answers', 'answer_page_idx')
esempio = {k: all_data[0][k] for k in campi}
print(json.dumps(esempio, indent=2))
print("\nCampi disponibili:", list(all_data[0].keys()))
"""## PARTE 1 — CORRUPTION ENGINE
Stessa logica della versione single-page (le stesse 3 funzioni: entity,
element, layout). Cambia solo come ricavo l'immagine da mostrare al
modello: prendo la pagina che contiene la risposta da
page_ids[answer_page_idx].
"""
# ── Corruption Engine ──
# Regola fondamentale: la corruzione rende l'informazione richiesta ASSENTE dal documento.
# La domanda rimane grammaticalmente corretta, l'unanswerability si scopre SOLO guardando l'immagine.
import spacy
# Carica il modello NLP di spaCy per riconoscere le entità nelle domande (date, luoghi, ecc.)
# Se non è installato, lo scarica automaticamente.
try:
nlp = spacy.load("en_core_web_sm")
except OSError:
import subprocess
subprocess.run(["python", "-m", "spacy", "download", "en_core_web_sm"], check=True)
nlp = spacy.load("en_core_web_sm")
######################################## ENTITY ####################################
ENTITY_POOLS = {
"DATE": ["March 2027", "1965", "April 12, 2031", "the year 2044",
"September 1958", "February 2003", "July 1999", "October 2015"],
"GPE": ["Reykjavik", "Montevideo", "Tashkent", "Wellington",
"Nairobi", "Bratislava", "Ulaanbaatar"],
"LOC": ["the Andes", "the Baltic Sea", "the Sahara", "the Pyrenees", "the Gobi Desert"],
"ORG": ["Zentech Holdings", "Marwick & Vale", "the Halverson Institute",
"Penrose Corp", "Valtrade Group", "Nordex Solutions"],
"PERSON": ["Eleanor Whitfield", "Marcus Delgado", "Priya Ramachandran",
"Tobias Lindqvist", "Fatima Al-Rashid", "Chen Wei"],
"CARDINAL": ["847", "13", "2,915", "66", "1,204", "342", "7,800", "29"],
"MONEY": ["$3,720", "$48.50", "$192,000", "$7.25", "$5,430", "$0.99"],
"PERCENT": ["73%", "12.4%", "5%", "88%", "31%", "6.7%"],
"ORDINAL": ["seventh", "twenty-third", "ninth", "fifteenth", "fourth"],
"TIME": ["3:45 PM", "11:20 AM", "midnight", "6:00 AM", "9:30 PM"],
"QUANTITY": ["12 kilometers", "3.5 liters", "80 kg", "450 grams", "2.3 miles"],
}
# Parole interrogative: evita di sostituire "when" o "what" scambiandoli per entità
INTERROGATIVE = {"which", "what", "when", "how", "where", "who", "many", "much"}
# Numeri generici che spaCy classifica come CARDINAL ma non sono entità significative
# Es: "one table", "few rows" — sostituirli non renderebbe la domanda unanswerable
CARDINAL_BLACKLIST = {
"one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "few", "many", "several", "some", "any", "no"
}
# Pattern da escludere:
# - "year-old" / "years-old": età, non date (es. "a 5 year-old company")
# - r"^[A-Z]{2,5}$": acronimi puri come "USA", "CEO" — spaCy li vede come ORG ma non sono sostituibili
BLACKLIST_PATTERNS = ["year-old", "years-old", r"^[A-Z]{2,5}$"]
def blacklisted(text):
"""
Restituisce True se l'entità NON deve essere sostituita.
Controlla due casi:
- pattern regex (iniziano con ^): es. acronimi come "USA", "CEO"
- sottostringa semplice: es. "year-old" dentro "5 year-old company"
"""
for pattern in BLACKLIST_PATTERNS:
if pattern.startswith("^"):
# È un pattern regex: controlla se il testo corrisponde esattamente
if re.match(pattern, text):
return True
else:
# È una parola semplice: controlla se compare nel testo
if pattern in text.lower():
return True
return False
def entity_candidates(doc):
"""
Restituisce la lista delle entità della domanda che possono essere sostituite.
Un'entità è candidata solo se supera tutti e 4 i filtri:
"""
candidates = []
for ent in doc.ents:
# 1) Il tipo di entità deve essere tra quelli che sappiamo sostituire
if ent.label_ not in ENTITY_POOLS:
continue
# 2) La prima parola non deve essere interrogativa (es. "what", "when")
# spaCy a volte classifica queste parole come entità per errore
if ent.text.split()[0].lower() in INTERROGATIVE:
continue
# 3) Il testo non deve essere in blacklist (acronimi, età, ecc.)
if blacklisted(ent.text):
continue
# 4) I CARDINAL generici ("one", "few", "many"...) non sono entità significative
if ent.label_ == "CARDINAL" and ent.text.lower() in CARDINAL_BLACKLIST:
continue
candidates.append(ent)
return candidates
def corrupt_entity(question, doc=None):
"""
Sostituisce una entità nella domanda con un valore diverso dello stesso tipo.
Restituisce (domanda_corrotta, descrizione_della_modifica) oppure None se non è possibile.
"""
# Analizza la domanda con spaCy (se non è già stata analizzata)
if doc is None:
doc = nlp(question)
# Trova le entità sostituibili
candidates = entity_candidates(doc)
if not candidates:
return None
# Sceglie una entità a caso tra i candidati
ent = random.choice(candidates)
# Prende i valori del pool escludendo il valore originale
# (per evitare di "sostituire" con la stessa cosa)
pool = []
for v in ENTITY_POOLS[ent.label_]:
if v.lower() != ent.text.lower():
pool.append(v)
# Se il pool è vuoto non si può corrompere
if not pool:
return None
# Controllo di sicurezza: il carattere subito dopo l'entità deve essere
# uno spazio o punteggiatura, altrimenti la sostituzione produrrebbe
# una parola "incollata" al testo successivo (es. "2019report")
# Se l'entità è l'ultima parola della domanda, non c'è nessun carattere dopo
if ent.end_char < len(question):
char_after_entity = question[ent.end_char]
else:
char_after_entity = " " # spazio fittizio: nessun problema di incollamento
if char_after_entity not in " .,;:?!\n)'\"":
return None
# Sostituisce l'entità originale con il nuovo valore
new_val = random.choice(pool)
corrupted_question = question[:ent.start_char] + new_val + question[ent.end_char:]
# Descrizione della modifica (utile per il debug e la relazione)
detail = f"{ent.text} ({ent.label_}) -> {new_val}"
return corrupted_question, detail
######################################## ELEMENTS ####################################
# ELEMENT: gruppi semanticamente lontani. Sostituire tra gruppi DIVERSI riduce il rischio
# che l'elemento sostitutivo sia comunque presente nella pagina (label noise).
ELEMENT_GROUPS = [
["table", "row", "column", "sheet", "field"], # elementi tabulari
["figure", "chart", "graph", "diagram"], # elementi visivi
["footnote", "caption", "header", "heading", "section"], # elementi testuali
]
# Lista piatta di tutti gli elementi di pagina (tutti i gruppi uniti in una lista sola)
ELEMENTS = []
for group in ELEMENT_GROUPS:
for element in group:
ELEMENTS.append(element)
def corrupt_element(question):
# Trova tutti gli elementi di pagina presenti nella domanda
found = []
for element in ELEMENTS:
if re.search(rf"\b{element}\b", question, re.I):
found.append(element)
if not found:
return None
# Sceglie a caso quale elemento sostituire
target = random.choice(found)
# Raccoglie tutti gli elementi di gruppi DIVERSI da quello del target
other_group_elements = []
for group in ELEMENT_GROUPS:
if target not in group:
other_group_elements.extend(group)
replacement = random.choice(other_group_elements)
corrupted_question = re.sub(rf"\b{target}\b", replacement, question, count=1, flags=re.I)
detail = f"{target} -> {replacement}"
return corrupted_question, detail
######################################## LAYOUT ####################################
# LAYOUT: opposti spaziali + posizioni ordinali legate a nomi strutturali
LAYOUT_OPPOSITES = {
"top left": ["bottom right"], "top right": ["bottom left"],
"bottom left": ["top right"], "bottom right": ["top left"],
"upper left": ["lower right"], "upper right": ["lower left"],
"lower left": ["upper right"], "lower right": ["upper left"],
"top": ["bottom"], "bottom": ["top"], "left": ["right"], "right": ["left"],
"upper": ["lower"], "lower": ["upper"], "above": ["below"], "below": ["above"],
"corner": ["center"],
}
POSITIONAL = {"first": ["last","third"], "last": ["first","third"],
"second": ["last","first"], "third": ["first","last"]}
STRUCT_NOUN = r"(row|column|page|section|paragraph|line|item|entry|table|figure)"
def corrupt_layout(question):
"""
Sostituisce un riferimento spaziale o ordinale nella domanda con il suo opposto.
Restituisce (domanda_corrotta, descrizione) oppure None se non trova nulla da corrompere.
"""
q = question.lower()
# ── Parte 1: termini spaziali (top, bottom, left, right, ecc.) ──
# Scorre dal più lungo al più corto per trovare prima "top left" rispetto a "top"
for term in sorted(LAYOUT_OPPOSITES, key=len, reverse=True):
term_escaped = re.escape(term)
# Il termine deve essere seguito da una parola strutturale del documento
# per escludere usi generici come "top priority" o "left alone"
is_position_reference = re.search(
rf"\b{term_escaped}\s+(the\s+)?(of|corner|part|side|margin|page|section|table|figure)\b", q
)
if is_position_reference:
replacement = random.choice(LAYOUT_OPPOSITES[term])
corrupted_question = re.sub(rf"\b{term_escaped}\b", replacement, question, count=1, flags=re.I)
detail = f"{term} -> {replacement}"
return corrupted_question, detail
# ── Parte 2: posizioni ordinali + nome strutturale (es. "first row", "last column") ──
for word, alternatives in POSITIONAL.items():
if re.search(rf"\b{word}\b\s+{STRUCT_NOUN}", q):
replacement = random.choice(alternatives)
corrupted_question = re.sub(rf"\b{word}\b", replacement, question, count=1, flags=re.I)
detail = f"{word} -> {replacement}"
return corrupted_question, detail
return None
# Dizionario che mappa ogni tipo di corruzione alla sua funzione
CORRUPTORS = {
"entity": corrupt_entity,
"element": corrupt_element,
"layout": corrupt_layout,
}
"""## CORRUZIONE + CAMPIONAMENTO
Applico le tre funzioni di corruzione con campionamento stratificato e
campiono in parallelo le domande clean, per arrivare a un benchmark
bilanciato 50/50 (stessa logica del single-page).
"""
# ── Pool di candidati, campionamento stratificato e applicazione delle corruzioni ──
random.seed(SEED)
questions = [s["question"] for s in all_data]
pools = {
"entity": [],
"element": [],
"layout": []
}
for doc, s in zip(nlp.pipe(questions, batch_size=512), all_data):
if entity_candidates(doc):
pools["entity"].append(s)
if corrupt_element(s["question"]):
pools["element"].append(s)
if corrupt_layout(s["question"]):
pools["layout"].append(s)
print("Domande corrompibili per tipo:", {k: len(v) for k, v in pools.items()})
used_qids = set()
seen_questions = set()
def sample_and_corrupt(pool, ctype, n):
corruption_fn = CORRUPTORS[ctype]
by_type = defaultdict(list)
for s in pool:
by_type[s['question_types'][0]].append(s)
quota = max(1, n // len(by_type))
records = []
def try_add(s):
question_normalized = re.sub(r'\s+', ' ', s['question'].lower().strip())
if s['questionId'] in used_qids or question_normalized in seen_questions:
return False
result = corruption_fn(s["question"])
if result is None:
return False
corrupted_question, detail = result
used_qids.add(s['questionId'])
seen_questions.add(question_normalized)
# ── MP-DocVQA: ricava la pagina della risposta da page_ids ──
answer_page = s["page_ids"][s["answer_page_idx"]]
records.append({
**s,
"image": answer_page, # pagina che contiene la risposta
"question": corrupted_question,
"original_question": s["question"],
"corruption_type": ctype,
"corruption_detail": detail,
"label": "unanswerable"
})
return True
for question_type, samples in by_type.items():
added = 0
for s in random.sample(samples, len(samples)):
if added == quota or len(records) == n:
break
if try_add(s):
added += 1
for s in random.sample(pool, len(pool)):
if len(records) == n:
break
try_add(s)
return records
entity_data = sample_and_corrupt(pools["entity"], "entity", N_ENTITY)
element_data = sample_and_corrupt(pools["element"], "element", N_ELEMENT)
layout_data = sample_and_corrupt(pools["layout"], "layout", N_LAYOUT)
corrupted_data = entity_data + element_data + layout_data
n_entity = len([d for d in corrupted_data if d['corruption_type'] == 'entity'])
n_element = len([d for d in corrupted_data if d['corruption_type'] == 'element'])
n_layout = len([d for d in corrupted_data if d['corruption_type'] == 'layout'])
print(f"Entity: {n_entity}/{N_ENTITY}")
print(f"Element: {n_element}/{N_ELEMENT}")
print(f"Layout: {n_layout}/{N_LAYOUT}")
# ── Campionamento clean ──
clean_pool = [s for s in all_data if s['questionId'] not in used_qids]
by_type = defaultdict(list)
for s in clean_pool:
by_type[s['question_types'][0]].append(s)
clean_data = []
quota = N_CLEAN // len(by_type)
for question_type, samples in by_type.items():
n_to_take = min(quota, len(samples))
clean_data += random.sample(samples, n_to_take)
already_used = {c['questionId'] for c in clean_data}
extra_pool = [s for s in clean_pool if s['questionId'] not in already_used]
remaining = N_CLEAN - len(clean_data)
clean_data += random.sample(extra_pool, min(remaining, len(extra_pool)))
# ── MP-DocVQA: aggiunge campo image anche per i clean ──
clean_data = [
{
**s,
"image": s["page_ids"][s["answer_page_idx"]],
"label": "answerable",
"corruption_type": "clean"
}
for s in clean_data
]
print(f"\nCorrotte: {len(corrupted_data)} | Clean: {len(clean_data)}")
print("Distribuzione corruzioni:", dict(Counter(d['corruption_type'] for d in corrupted_data)))
for ctype in ["entity", "element", "layout"]:
esempio = next(d for d in corrupted_data if d["corruption_type"] == ctype)
print(f"\n[{ctype}]")
print(f" Originale : {esempio['original_question']}")
print(f" Corrotta : {esempio['question']}")
print(f" Modifica : {esempio['corruption_detail']}")
print(f" Pagina : {esempio['image']}")
"""## LLM AS A JUDGE
Verifica qualità con LLM-as-a-judge. Il judge (LLaMA-3.3-70B via Groq) è
volutamente text-only, non vede l'immagine: una corruzione è valida solo se
- well_formed : la domanda è grammaticalmente corretta e naturale;
- needs_document : dal solo testo è impossibile capire che è unanswerable,
serve ispezionare il documento.
Se un criterio fallisce, la domanda viene riscritta automaticamente (max 1
tentativo) e ri-giudicata.
"""
# ── LLM-as-a-judge (Groq, llama-3.3-70b) ──
!pip install groq -q
from groq import Groq
from google.colab import userdata
import time
# Inizializza il client Groq con la chiave API
groq_client = Groq(api_key=userdata.get("GROQ_API_KEY"))
# ── Prompt di sistema: ruolo del judge ──
JUDGE_SYSTEM = "You are an expert annotator for document question answering benchmarks."
# ── Prompt di valutazione ──
# Il judge valuta la domanda corrotta su due criteri:
# 1. well_formed -> la domanda è grammaticalmente corretta e naturale
# 2. needs_document -> dal solo testo non si capisce che è unanswerable,
# bisogna guardare l'immagine del documento
JUDGE_PROMPT = """
Original question: {orig}
Corrupted question: {corr}
Corruption type: {ctype}
The corrupted question will be shown to a vision model together with a document image.
Evaluate it on two criteria:
1. well_formed: the question is grammatically correct and reads naturally.
2. needs_document: from the text alone it is impossible to tell the question is
unanswerable — one must look at the document image to find out.
Reply ONLY with this JSON:
{{"well_formed": true, "needs_document": true, "reason": "..."}}
"""
# ── Prompt di riscrittura ──
# Se la domanda fallisce uno dei criteri, il judge prova a riscriverla
# mantenendo la corruzione ma migliorando forma e naturalezza
REWRITE_PROMPT = """
Original question: {orig}
Corrupted question: {corr}
Corruption type: {ctype}
Problem: {reason}
Rewrite the corrupted question so that:
- it is grammatically correct and natural
- it PRESERVES the corruption (do not restore the original value)
- its unanswerability can only be verified by looking at the document image
Reply ONLY with this JSON:
{{"rewritten_question": "..."}}
"""
def call_api(messages, max_tokens=200, max_retries=3):
"""
Chiama l'API di Groq e restituisce il testo della risposta.
Se riceve un errore di rate limit (429), aspetta e riprova.
"""
for attempt in range(max_retries):
try:
response = groq_client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=messages,
max_tokens=max_tokens,
temperature=0.0
)
return response.choices[0].message.content
except Exception as e:
if "429" in str(e):
wait_seconds = 10 * (attempt + 1)
print(f"Rate limit raggiunto, aspetto {wait_seconds}s...")
time.sleep(wait_seconds)
else:
raise
return None
def extract_json(text):
"""
Estrae il primo oggetto JSON dalla risposta del judge.
Restituisce None se non trova JSON valido.
"""
match = re.search(r"\{.*\}", text or "", re.S)
if match is None:
return None
try:
return json.loads(match.group())
except json.JSONDecodeError:
return None
def evaluate(sample, question):
"""
Chiede al judge di valutare la domanda corrotta.
Restituisce un dizionario con well_formed, needs_document e reason.
"""
messages = [
{"role": "system", "content": JUDGE_SYSTEM},
{"role": "user", "content": JUDGE_PROMPT.format(
orig = sample["original_question"],
corr = question,
ctype = sample["corruption_type"]
)}
]
raw_response = call_api(messages)
result = extract_json(raw_response)
if result is None:
return {"well_formed": None, "needs_document": None, "reason": "PARSE_FAIL"}
return result
def rewrite(sample, question, reason):
"""
Chiede al judge di riscrivere la domanda che non ha superato la valutazione.
Restituisce la domanda riscritta oppure None se la riscrittura fallisce.
"""
messages = [
{"role": "system", "content": JUDGE_SYSTEM},
{"role": "user", "content": REWRITE_PROMPT.format(
orig = sample["original_question"],
corr = question,
ctype = sample["corruption_type"],
reason = reason
)}
]
raw_response = call_api(messages)
result = extract_json(raw_response)
if result is None:
return None
return result.get("rewritten_question")
def is_valid(verdict):
"""
Restituisce True se la domanda ha superato entrambi i criteri del judge.
"""
return verdict.get("well_formed") is True and verdict.get("needs_document") is True
# ── Valutazione di ogni domanda corrotta ──
MAX_REWRITES = 1 # al massimo 1 tentativo di riscrittura per domanda
for i, sample in enumerate(corrupted_data):
current_question = sample["question"]
n_rewrites = 0
# Valutazione iniziale
verdict = evaluate(sample, current_question)
# Se non valida, prova a riscrivere una volta
if not is_valid(verdict) and n_rewrites < MAX_REWRITES:
rewritten = rewrite(sample, current_question, verdict.get("reason", ""))
n_rewrites += 1
if rewritten is not None:
current_question = rewritten
verdict = evaluate(sample, current_question)
# Salva la domanda finale nel record
if current_question != sample["question"]:
sample["question_before_rewrite"] = sample["question"]
sample["question"] = current_question
# Salva il verdetto nel record
sample["n_rewrites"] = n_rewrites
sample["judge_verdict"] = "KEEP" if is_valid(verdict) else "REJECT"
sample["judge_reason"] = verdict.get("reason", "")
# Stampa il progresso
tag = f"R{n_rewrites}" if n_rewrites > 0 else " "
print(f"[{i+1:02d}/{len(corrupted_data)}] {tag} {sample['judge_verdict']:6s} "
f"({sample['corruption_type']}) {current_question[:60]}")
# Conta quanti KEEP e quanti REJECT
conteggio_verdetti = Counter(s['judge_verdict'] for s in corrupted_data)
print("\nVerdetti finali:")
print(f" KEEP : {conteggio_verdetti['KEEP']}")
print(f" REJECT : {conteggio_verdetti['REJECT']}")
"""## BILANCIAMENTO E SALVATAGGIO SU DRIVE
Stessa procedura della versione single-page: tengo solo i KEEP del judge,
bilancio 50/50 con le clean, salvo benchmark_final.json. Le immagini di
MP-DocVQA (22GB) le ho già processate ed estratte in locale: qui verifico
solo che quelle necessarie al benchmark siano presenti su Drive.
"""
# ── Bilanciamento e salvataggio del benchmark su Drive ──
random.seed(SEED)
# Tiene solo le domande approvate dal judge
corrupted_keep = [d for d in corrupted_data if d["judge_verdict"] == "KEEP"]
n_reject = len(corrupted_data) - len(corrupted_keep)
# Rimuove altrettante clean per mantenere il bilanciamento 50/50
# Esempio: 5 REJECT -> rimuove 5 clean -> rimane sempre metà corrotte, metà clean
if n_reject > 0:
clean_data = random.sample(clean_data, len(clean_data) - n_reject)
# Unisce corrotte e clean, mescola per non averle in ordine
benchmark_final = corrupted_keep + clean_data
random.shuffle(benchmark_final)
# Salva il benchmark su Drive (sovrascrive se esiste già)
with open(BENCH_PATH, "w") as f:
json.dump(benchmark_final, f, indent=2)
print(f"Benchmark salvato in: {BENCH_PATH}")
print(f" Unanswerable : {len(corrupted_keep)}")
print(f" Answerable : {len(clean_data)}")
print(f" Totale : {len(benchmark_final)}")
# ── Immagini del benchmark ──
# Il file tar completo (22GB) è stato processato in locale.
# Le immagini necessarie al benchmark sono state estratte
# e caricate su Drive in IMG_DIR.
IMG_DIR = f'{DRIVE_DIR}/qas/images'
# Verifica che le immagini necessarie siano presenti
needed = set()
for s in benchmark_final:
page_ids = s.get("page_ids", [s["image"]])
answer_idx = s.get("answer_page_idx", 0)
start = max(0, answer_idx - WINDOW_SIZE // 2)
end = min(len(page_ids), start + WINDOW_SIZE)
for pid in page_ids[start:end]:
needed.add(f"{pid}.jpg")
missing = {f for f in needed if not os.path.isfile(os.path.join(IMG_DIR, f))}
print(f"Immagini necessarie : {len(needed)}")
print(f" presenti su Drive : {len(needed) - len(missing)}")
print(f" mancanti : {len(missing)}")
if missing:
for m in sorted(missing)[:5]:
print(f" [!] {m}")
def wrap(text, width=45):
return "\n".join(textwrap.wrap(text, width))
def show_grid(corruption_type, n=6):
samples = [d for d in corrupted_keep if d["corruption_type"] == corruption_type][:n]
fig, axes = plt.subplots(2, 3, figsize=(18, 16))
fig.suptitle(f"Spot-check: {corruption_type.upper()}", fontweight='bold', fontsize=14)
for ax, sample in zip(axes.flat, samples):
# pagina della risposta (page_id già salvato nel campo "image")
image_path = os.path.join(IMG_DIR, f"{sample['image']}.jpg") # ← .jpg
try:
image = Image.open(image_path).convert('RGB')
ax.imshow(image)
except FileNotFoundError:
ax.text(0.5, 0.5, "Immagine\nnon trovata",
ha='center', va='center', transform=ax.transAxes)
ax.axis('off')
ax.set_title(
f"ORI: {wrap(sample['original_question'])}\n"
f"\nCOR: {wrap(sample['question'])}\n"
f"\nMOD: {wrap(sample['corruption_detail'])}\n"
f"\nPAG: {sample['image']}\n"
f"TOT pagine doc: {len(sample.get('page_ids', []))}", # ← info multi-page
fontsize=7,
loc='left'
)
plt.tight_layout()
plt.show()
for corruption_type in ["entity", "element", "layout"]:
show_grid(corruption_type)
from PIL import Image
import matplotlib.pyplot as plt
import textwrap
def show_window(sample, window_size=2):
page_ids = sample["page_ids"]
answer_idx = sample["answer_page_idx"]
start = max(0, answer_idx - window_size // 2)
end = min(len(page_ids), start + window_size)
window = page_ids[start:end]
fig, axes = plt.subplots(1, len(window), figsize=(8 * len(window), 10))
if len(window) == 1:
axes = [axes]
for ax, pid in zip(axes, window):
img_path = os.path.join(IMG_DIR, f"{pid}.jpg")
try:
ax.imshow(Image.open(img_path).convert('RGB'))
except FileNotFoundError:
ax.text(0.5, 0.5, "Non trovata", ha='center', va='center', transform=ax.transAxes)
ax.set_title(f"{pid}" + (" ← RISPOSTA" if pid == sample['image'] else ""), fontsize=9)
ax.axis('off')
plt.suptitle(
f"TIPO: {sample.get('corruption_type','').upper()}\n"
f"MODIFICA: {sample.get('corruption_detail','')}\n"
f"ORIGINALE: {sample.get('original_question','')}\n"
f"CORROTTA: {sample['question']}",
fontsize=10, ha='left', x=0.01
)
plt.tight_layout()
plt.show()
# Esempio su un campione per tipo
for ctype in ["entity", "element", "layout"]:
sample = next(s for s in corrupted_keep if s["corruption_type"] == ctype)
show_window(sample)
# ── Caricamento benchmark da Drive ──
# Esegui questa cella dopo ogni restart del runtime prima di procedere con la Parte 2.
with open(BENCH_PATH) as f:
benchmark_final = json.load(f)
# Ricostruisce le variabili necessarie per le celle successive
corrupted_keep = [s for s in benchmark_final if s["label"] == "unanswerable"]
clean_data = [s for s in benchmark_final if s["label"] == "answerable"]
print(f"Benchmark caricato: {len(benchmark_final)} campioni")
print(f" Unanswerable : {len(corrupted_keep)}")
print(f" Answerable : {len(clean_data)}")
print()
"""## PARTE 2 : Benchmark
## INFERENZA BASELINE
Come nella versione single-page, ma qui il modello riceve una FINESTRA di
pagine (definita da WINDOW_SIZE) invece di una sola immagine: tutte le
pagine della finestra vengono passate insieme al prompt testuale.
"""
# ══ SETUP GLOBALE MP-DocVQA ══ (rieseguire dopo OGNI restart)
from google.colab import drive
drive.mount('/content/drive')
import json, os, re, random, shutil, gc
from collections import Counter, defaultdict
import torch
from PIL import Image
SEED = 42
random.seed(SEED)
# ── Percorsi ──
DRIVE_DIR = '/content/drive/MyDrive/MP-docvqa'
QAS_DIR = f'{DRIVE_DIR}/qas'
IMG_SRC = f'{DRIVE_DIR}/qas/images' # immagini su Drive
IMG_DIR = '/content/mpdocvqa_images' # destinazione locale (RAM/SSD Colab)
BENCH_PATH = f'{DRIVE_DIR}/benchmark_final.json'
PRED_DIR = f'{DRIVE_DIR}/predictions'
os.makedirs(PRED_DIR, exist_ok=True)
os.makedirs(IMG_DIR, exist_ok=True)
# ── Parametri benchmark ──
N_ENTITY = 34
N_ELEMENT = 33
N_LAYOUT = 33
N_CLEAN = 100
WINDOW_SIZE = 2
# ── Carica benchmark ──
with open(BENCH_PATH) as f:
benchmark_final = json.load(f)
print(f"Benchmark: {len(benchmark_final)} campioni")
print(f"Window size: {WINDOW_SIZE}")
# ── Copia immagini necessarie da Drive a /content/ ──
# Drive è lento per lettura random durante l'inferenza;
# copiare tutto in locale all'inizio è molto più veloce.
needed = set()
for s in benchmark_final:
page_ids = s.get("page_ids", [s["image"]])
answer_idx = s.get("answer_page_idx", 0)
start = max(0, answer_idx - WINDOW_SIZE // 2)
end = min(len(page_ids), start + WINDOW_SIZE)
for pid in page_ids[start:end]:
needed.add(f"{pid}.jpg")
missing = {f for f in needed if not os.path.isfile(os.path.join(IMG_DIR, f))}
print(f"Immagini necessarie : {len(needed)}")
print(f" già in /content/ : {len(needed) - len(missing)}")
print(f" da copiare : {len(missing)}")
for fname in missing:
src = os.path.join(IMG_SRC, fname)
dst = os.path.join(IMG_DIR, fname)
if os.path.isfile(src):
shutil.copy2(src, dst)
else:
print(f" [!] Non trovata su Drive: {fname}")
print("Immagini pronte in /content/")
import torch
from PIL import Image
with open(BENCH_PATH) as f:
benchmark_final = json.load(f)
print(f"Benchmark caricato da Drive: {len(benchmark_final)} campioni")
# ── Funzione finestra MP-DocVQA ──
def get_window_pages(sample, window_size=None):
global WINDOW_SIZE
if window_size is None:
window_size = WINDOW_SIZE
page_ids = sample["page_ids"]
answer_idx = sample["answer_page_idx"]
start = max(0, answer_idx - window_size // 2)
end = min(len(page_ids), start + window_size)
return page_ids[start:end]
def resolve_image_path(page_id):
filename = f"{page_id}.jpg" # ← .jpg non .png
full_path = os.path.join(IMG_DIR, filename)
if not os.path.isfile(full_path):
raise FileNotFoundError(f"Immagine non trovata: {full_path}")
return full_path
BASE_INSTRUCTION = (
"You are a binary classifier. "
"Look at the document pages and decide whether "
"the question can be answered using ONLY the information visible in the provided pages."
)
FEW_SHOT_EXAMPLES = """
Example 1:
Question: "What is the value shown in the bottom-left table?"
Reasoning: The provided pages contain a table at the top-right, not bottom-left.
The referenced element does not exist in this position.
Answer: UNANSWERABLE
Example 2:
Question: "What is the total amount due?"
Reasoning: The provided pages contain a row labeled 'Total Amount Due' with a value.
The information requested is present in the document.
Answer: ANSWERABLE
"""
KNOWLEDGE_NOTE = """Before answering, verify the following in the provided document pages:
- Entities: check that any name, date, number, or organization mentioned
in the question actually appears in the pages.
- Elements: check that any referenced element (table, figure, chart, footnote)
exists in the pages.
- Layout: check that any referenced position (top, bottom, left, right)
matches the actual position of elements in the pages.
Only after this verification, answer with ANSWERABLE or UNANSWERABLE."""
COT_INSTRUCTION = """Think step by step:
1) What does the question ask for?
2) Is it visible in any of the provided document pages?
- YES → ANSWERABLE
- NO → UNANSWERABLE
Your last line must be exactly: ANSWERABLE or UNANSWERABLE."""
SYSTEM_MESSAGE = (
"You are a binary classifier. "
"You must reply with ONLY one word: ANSWERABLE or UNANSWERABLE. "
"Never extract text from the document. Never answer the question itself."
)
def build_prompt(question, strategy="baseline"):
if strategy == "baseline":
return f"{BASE_INSTRUCTION}\n\nQuestion: {question}"
if strategy == "few_shot":
return f"{BASE_INSTRUCTION}\n\n{FEW_SHOT_EXAMPLES}\n\nQuestion: {question}"
if strategy == "cot":
return f"Question: {question}\n\n{COT_INSTRUCTION}"
if strategy == "knowledge":
return f"{BASE_INSTRUCTION}\n\n{KNOWLEDGE_NOTE}\n\nQuestion: {question}"
raise ValueError(f"Strategia sconosciuta: '{strategy}'")
def normalize_pred(raw):
text = (raw or "").lower()