File size: 27,779 Bytes
2b2ba40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "bcf8bfe6-3c3f-42d6-b5fe-c46afed62587",
   "metadata": {},
   "source": [
    "# code de normalisation pour evaluer les 8 metrics d accuracy du text "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "60277596-11a4-436e-858d-9f8c06a69d50",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "βœ… 6/6 tests passΓ©s\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "import unicodedata\n",
    "\n",
    "\n",
    "def normalize_arabic_ocr(text: str, remove_markdown: bool = False) -> str:\n",
    "    \"\"\"\n",
    "    Pipeline de normalisation canonique pour benchmark OCR arabe.\n",
    "    À appliquer de manière IDENTIQUE sur GT et hypothèse OCR.\n",
    "\n",
    "    Γ‰tapes :\n",
    "      1.  (Optionnel) Suppression Markdown\n",
    "      2.  NFKC β€” formes de prΓ©sentation arabes\n",
    "      3.  Caractères invisibles (ZWJ, ZWNJ, marques bidi, BOM)\n",
    "      4.  Diacritiques arabes (tashkil)\n",
    "      5.  Tatweel / kashida\n",
    "      6.  Alef variants β†’ Ψ§\n",
    "      7.  Alef maqsura β†’ ي            ← nouveau\n",
    "      8.  Ta marbuta β†’ Ω‡\n",
    "      9.  Hamza sur support : Ψ€β†’Ωˆ  Ψ¦β†’ΩŠ\n",
    "      10. Ponctuation arabe + latine β†’ espace\n",
    "      11. Whitelist : garde arabe + chiffres + latin + espace  ← nouveau\n",
    "      12. Chiffres arabes-indiens β†’ ASCII\n",
    "      13. Latin β†’ minuscules           ← nouveau\n",
    "      14. Espaces multiples β†’ un seul, strip\n",
    "    \"\"\"\n",
    "    if not isinstance(text, str) or not text.strip():\n",
    "        return \"\"\n",
    "\n",
    "    # ── 1. Markdown (dΓ©sactivΓ© par dΓ©faut pour OCR pur) ──────────────────────\n",
    "    if remove_markdown:\n",
    "        text = re.sub(r'#{1,6}\\s*', '', text)\n",
    "        text = re.sub(r'^\\s*[-*+]\\s+', '', text, flags=re.MULTILINE)\n",
    "        text = re.sub(r'\\*{1,3}(.*?)\\*{1,3}', r'\\1', text, flags=re.DOTALL)\n",
    "        text = re.sub(r'`{1,3}.*?`{1,3}', ' ', text, flags=re.DOTALL)\n",
    "        text = re.sub(r'\\[([^\\]]*)\\]\\([^\\)]*\\)', r'\\1', text)\n",
    "        text = re.sub(r'!\\[[^\\]]*\\]\\([^\\)]*\\)', ' ', text)\n",
    "        text = re.sub(r'\\|', ' ', text)\n",
    "\n",
    "    # ── 2. NFKC ──────────────────────────────────────────────────────────────\n",
    "    # NFC ne suffit pas : NFKC dΓ©compose aussi les formes de prΓ©sentation\n",
    "    # arabes (Presentation Forms-A/B : ο»› ﻜ ﻟ ο»» …) trΓ¨s frΓ©quentes en OCR.\n",
    "    text = unicodedata.normalize('NFKC', text)\n",
    "\n",
    "    # ── 3. CaractΓ¨res invisibles & marques bidirectionnelles ─────────────────\n",
    "    text = re.sub(\n",
    "        r'[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u2064\\uFEFF\\u00AD]',\n",
    "        '', text\n",
    "    )\n",
    "\n",
    "    # ── 4. Diacritiques arabes (tashkil) ─────────────────────────────────────\n",
    "    text = re.sub(\n",
    "        r'[\\u064B-\\u065F'           # fatha, damma, kasra, shadda, sukun …\n",
    "        r'\\u0610-\\u061A'            # Arabic extended marks\n",
    "        r'\\u06D6-\\u06DC'\n",
    "        r'\\u06DF-\\u06E4'\n",
    "        r'\\u06E7\\u06E8'\n",
    "        r'\\u06EA-\\u06ED]',\n",
    "        '', text\n",
    "    )\n",
    "\n",
    "    # ── 5. Tatweel / kashida ─────────────────────────────────────────────────\n",
    "    text = text.replace('\\u0640', '')\n",
    "\n",
    "    # ── 6. Alef variants β†’ Ψ§ ─────────────────────────────────────────────────\n",
    "    text = re.sub(r'[\\u0622\\u0623\\u0625\\u0671\\u0672\\u0673\\u0675]', '\\u0627', text)\n",
    "\n",
    "    # ── 7. Alef maqsura β†’ ي ──────────────────────────────────────────────────\n",
    "    text = text.replace('\\u0649', '\\u064A')\n",
    "\n",
    "    # ── 8. Ta marbuta β†’ Ω‡ ────────────────────────────────────────────────────\n",
    "    text = text.replace('\\u0629', '\\u0647')\n",
    "\n",
    "    # ── 9. Hamza sur support ─────────────────────────────────────────────────\n",
    "    text = text.replace('\\u0624', '\\u0648')   # Ψ€ β†’ و\n",
    "    text = text.replace('\\u0626', '\\u064A')   # Ψ¦ β†’ ي\n",
    "\n",
    "    # ── 10. Ponctuation arabe + latine β†’ espace ──────────────────────────────\n",
    "    text = re.sub(r'[\\u060C\\u061B\\u061F\\u066A-\\u066D\\u0600-\\u0605]', ' ', text)\n",
    "    text = re.sub(r'[.,:;()\\[\\]{}\\-«»\"\\'!?/\\\\~@#$%^&*_+=<>|]', ' ', text)\n",
    "    \n",
    "    # ── 13. Latin β†’ minuscules ───────────────────────────────────────────────\n",
    "    text = text.lower()\n",
    "\n",
    "\n",
    "    # ── 11. Whitelist ─────────────────────────────────────────────────────────\n",
    "    # Conserve : bloc arabe (0600-06FF + 0750-077F), chiffres ASCII,\n",
    "    #            latin a-z (noms propres, acronymes), espace.\n",
    "    # Γ‰limine  : symboles math/monnaie, emojis, tirets typographiques,\n",
    "    #            guillemets exotiques, caractères de contrôle résiduels.\n",
    "    text = re.sub(r'[^\\u0600-\\u06FF\\u0750-\\u077Fa-z0-9\\s]', ' ', text)\n",
    "\n",
    "    # ── 12. Chiffres arabes-indiens β†’ ASCII ──────────────────────────────────\n",
    "    text = text.translate(str.maketrans('Ω Ω‘Ω’Ω£Ω€Ω₯Ω¦Ω§Ω¨Ω©', '0123456789'))\n",
    "\n",
    "    # ── 13. Latin β†’ minuscules ───────────────────────────────────────────────\n",
    "    text = text.lower()\n",
    "\n",
    "    # ── 14. Espaces multiples β†’ un seul ──────────────────────────────────────\n",
    "    return re.sub(r'\\s+', ' ', text).strip()\n",
    "\n",
    "\n",
    "# ─── VΓ©rification rapide ───────────────────────────────────────────────────\n",
    "if __name__ == '__main__':\n",
    "    samples = [\n",
    "        (\"Diacritiques\",   \"الكِΨͺَابُ Ψ§Ω„Ω…ΩΩΩΩŠΨ―Ω\",          \"Ψ§Ω„ΩƒΨͺΨ§Ψ¨ Ψ§Ω„Ω…ΩΩŠΨ―\"),\n",
    "        (\"Alef maqsura\",   \"Ω…ΩˆΨ³Ω‰ ΩˆΩŠΨ­ΩŠΩ‰\",                   \"Ω…ΩˆΨ³ΩŠ ويحيي\"),\n",
    "        (\"Formes prΓ©sent.\", \"ﻛﻠﻀﺔ\",                         \"ΩƒΩ„Ω…Ω‡\"),\n",
    "        (\"Invisible chars\",\"Ω…\\u200BΨ±\\u200FΨ­Ψ¨Ψ§\",             \"Ω…Ψ±Ψ­Ψ¨Ψ§\"),\n",
    "        (\"Whitelist\",      \"Ψ§Ω„Ψ³ΨΉΨ±: €15 أو 15€ !\",           \"Ψ§Ω„Ψ³ΨΉΨ± 15 او 15\"),\n",
    "        (\"Mixte latin\",    \"Ω†Ω…ΩˆΨ°Ψ¬ GPT-4 وClaude\",           \"Ω†Ω…ΩˆΨ°Ψ¬ gpt 4 وclaude\"),\n",
    "    ]\n",
    "    ok, fail = 0, 0\n",
    "    for name, inp, expected in samples:\n",
    "        result = normalize_arabic_ocr(inp)\n",
    "        status = \"βœ…\" if result == expected else \"❌\"\n",
    "        if result == expected:\n",
    "            ok += 1\n",
    "        else:\n",
    "            fail += 1\n",
    "            print(f\"{status} {name}: '{result}' β‰  '{expected}'\")\n",
    "    print(f\"\\n{'βœ…' if fail == 0 else '⚠️'} {ok}/{ok+fail} tests passΓ©s\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91743108-1eb3-47b7-a09e-bb3c048d7ee9",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from pathlib import Path\n",
    "\n",
    "input_folder  = Path(\"/home/skiredj.abderrahman/khalil/Benchmarking_OCR/Ground_truth_first_20_not_normalised\")\n",
    "output_folder = Path(\"/home/skiredj.abderrahman/khalil/Benchmarking_OCR/Ground_truth_first_20_normalised\")\n",
    "output_folder.mkdir(parents=True, exist_ok=True)\n",
    "\n",
    "for md_file in input_folder.glob(\"*.md\"):\n",
    "    text = md_file.read_text(encoding=\"utf-8\")\n",
    "    normalized = normalize_arabic_ocr(text, remove_markdown=True)\n",
    "    out_path = output_folder / md_file.name\n",
    "    out_path.write_text(normalized, encoding=\"utf-8\")\n",
    "    print(f\"βœ… {md_file.name}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "041e5c05-eb98-4b85-a4ec-a7367458a005",
   "metadata": {},
   "source": [
    "# code benchmarking.  evaluation des 8 metrics d accuracy + 1 metric TEDS pour les tableaux  (9 metrics )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4913d1b-5730-45dd-92d7-11c843fb014e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "import unicodedata\n",
    "import html as _html\n",
    "import json\n",
    "import editdistance\n",
    "import jiwer\n",
    "import sacrebleu\n",
    "from rouge_score import rouge_scorer as rs\n",
    "from apted import APTED, Config\n",
    "from lxml import etree\n",
    "from typing import Optional\n",
    "\n",
    "# ── Paths ─────────────────────────────────────────────────────────────────────\n",
    "GT_RAW_PATH  = \"/home/skiredj.abderrahman/khalil/Benchmarking_OCR/Ground_truth_first_20_not_normalised/1to17.md\"\n",
    "HYP_RAW_PATH = \"/home/skiredj.abderrahman/khalil/Benchmarking_OCR/tests_deepseek2_no_split/output_markdown_no_pageN/images_de_tests.md\"\n",
    "MODEL_NAME   = \"Deepseek2_without_split\"\n",
    "\n",
    "# ── Normalization ─────────────────────────────────────────────────────────────\n",
    "def normalize_arabic_ocr(text: str, remove_markdown: bool = False) -> str:\n",
    "    if not isinstance(text, str) or not text.strip():\n",
    "        return \"\"\n",
    "    if remove_markdown:\n",
    "        text = re.sub(r'#{1,6}\\s*', '', text)\n",
    "        text = re.sub(r'^\\s*[-*+]\\s+', '', text, flags=re.MULTILINE)\n",
    "        text = re.sub(r'\\*{1,3}(.*?)\\*{1,3}', r'\\1', text, flags=re.DOTALL)\n",
    "        text = re.sub(r'`{1,3}.*?`{1,3}', ' ', text, flags=re.DOTALL)\n",
    "        text = re.sub(r'\\[([^\\]]*)\\]\\([^\\)]*\\)', r'\\1', text)\n",
    "        text = re.sub(r'!\\[[^\\]]*\\]\\([^\\)]*\\)', ' ', text)\n",
    "        text = re.sub(r'\\|', ' ', text)\n",
    "    text = unicodedata.normalize('NFKC', text)\n",
    "    text = re.sub(r'[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u2064\\uFEFF\\u00AD]', '', text)\n",
    "    text = re.sub(\n",
    "        r'[\\u064B-\\u065F\\u0610-\\u061A\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED]',\n",
    "        '', text\n",
    "    )\n",
    "    text = text.replace('\\u0640', '')\n",
    "    text = re.sub(r'[\\u0622\\u0623\\u0625\\u0671\\u0672\\u0673\\u0675]', '\\u0627', text)\n",
    "    text = text.replace('\\u0649', '\\u064A')\n",
    "    text = text.replace('\\u0629', '\\u0647')\n",
    "    text = text.replace('\\u0624', '\\u0648')\n",
    "    text = text.replace('\\u0626', '\\u064A')\n",
    "    text = re.sub(r'[\\u060C\\u061B\\u061F\\u066A-\\u066D\\u0600-\\u0605]', ' ', text)\n",
    "    text = re.sub(r'[.,:;()\\[\\]{}\\-«»\"\\'!?/\\\\~@#$%^&*_+=<>|]', ' ', text)\n",
    "    text = text.lower()\n",
    "    text = re.sub(r'[^\\u0600-\\u06FF\\u0750-\\u077Fa-z0-9\\s]', ' ', text)\n",
    "    text = text.translate(str.maketrans('Ω Ω‘Ω’Ω£Ω€Ω₯Ω¦Ω§Ω¨Ω©', '0123456789'))\n",
    "    text = text.lower()\n",
    "    return re.sub(r'\\s+', ' ', text).strip()\n",
    "\n",
    "# ── Page splitter ─────────────────────────────────────────────────────────────\n",
    "def split_pages_raw(content: str) -> dict:\n",
    "    pattern = re.compile(r'^===\\s*(.+?)\\s*===$', re.MULTILINE)\n",
    "    matches  = list(pattern.finditer(content))\n",
    "    if not matches:\n",
    "        print(\"⚠️  No page separators found\")\n",
    "        return {\"page_01\": content.strip()}\n",
    "    pages = {}\n",
    "    for idx, m in enumerate(matches):\n",
    "        page_id = m.group(1).strip()\n",
    "        start   = m.end()\n",
    "        end     = matches[idx + 1].start() if idx + 1 < len(matches) else len(content)\n",
    "        text    = content[start:end].strip()\n",
    "        if text:\n",
    "            pages[page_id] = text\n",
    "    return pages\n",
    "\n",
    "# ── TEDS helpers ──────────────────────────────────────────────────────────────\n",
    "\n",
    "def _is_separator_row(row: str) -> bool:\n",
    "    \"\"\"True if row is a markdown separator like |---|---|\"\"\"\n",
    "    cells = [c.strip() for c in row.strip().strip('|').split('|')]\n",
    "    return bool(cells) and all(re.match(r'^[-:\\s]+$', c) for c in cells if c)\n",
    "\n",
    "\n",
    "def _expand_inline_table(line: str) -> Optional[str]:\n",
    "    \"\"\"\n",
    "    Detect and expand a single-line collapsed markdown table.\n",
    "\n",
    "    The HYP model outputs tables like:\n",
    "        header1 | header2 | ... | --- | --- | ... | cell1 | cell2 | ...\n",
    "    all on ONE line. We detect the separator fragment '| --- |' or '|---|'\n",
    "    and reconstruct a proper multi-line table.\n",
    "\n",
    "    Returns a multi-line markdown table string, or None if not detected.\n",
    "    \"\"\"\n",
    "    # Must contain a separator pattern inside the line\n",
    "    if not re.search(r'\\|\\s*-{2,}[\\s:]*\\|', line):\n",
    "        return None\n",
    "\n",
    "    # Tokenise: split on '|' but keep content\n",
    "    raw_cells = [c.strip() for c in line.split('|')]\n",
    "    # Remove leading/trailing empty strings from splitting\n",
    "    while raw_cells and raw_cells[0] == '':\n",
    "        raw_cells.pop(0)\n",
    "    while raw_cells and raw_cells[-1] == '':\n",
    "        raw_cells.pop()\n",
    "\n",
    "    if not raw_cells:\n",
    "        return None\n",
    "\n",
    "    # Find all separator positions (cells that look like '---', ':---:', etc.)\n",
    "    sep_positions = [i for i, c in enumerate(raw_cells) if re.match(r'^[-:\\s]+$', c) and len(c) >= 2]\n",
    "\n",
    "    if not sep_positions:\n",
    "        return None\n",
    "\n",
    "    # We expect separators to appear as a consecutive block.\n",
    "    # Strategy: find the first run of separator cells β†’ that marks the header/sep boundary.\n",
    "    # Rows are inferred by counting columns = number of separators.\n",
    "    n_cols = len(sep_positions)\n",
    "\n",
    "    # The separator cells should be consecutive; find where they start\n",
    "    sep_start = sep_positions[0]\n",
    "\n",
    "    # Everything before the separator block = header cells\n",
    "    header_cells = raw_cells[:sep_start]\n",
    "\n",
    "    # If header has more cells than n_cols, it might contain preamble text.\n",
    "    # Trim header to last n_cols cells.\n",
    "    if len(header_cells) > n_cols:\n",
    "        header_cells = header_cells[len(header_cells) - n_cols:]\n",
    "    elif len(header_cells) < n_cols:\n",
    "        # Pad header with empty cells\n",
    "        header_cells = [''] * (n_cols - len(header_cells)) + header_cells\n",
    "\n",
    "    # Everything after the separator block = data cells\n",
    "    data_cells = raw_cells[sep_start + n_cols:]\n",
    "\n",
    "    # Build rows from data_cells in chunks of n_cols\n",
    "    rows = []\n",
    "    for i in range(0, len(data_cells), n_cols):\n",
    "        chunk = data_cells[i:i + n_cols]\n",
    "        # Pad incomplete last row\n",
    "        while len(chunk) < n_cols:\n",
    "            chunk.append('')\n",
    "        rows.append(chunk)\n",
    "\n",
    "    if not rows:\n",
    "        return None\n",
    "\n",
    "    # Reconstruct multi-line markdown table\n",
    "    sep_row = '| ' + ' | '.join(['---'] * n_cols) + ' |'\n",
    "    header_row = '| ' + ' | '.join(header_cells) + ' |'\n",
    "    data_rows  = ['| ' + ' | '.join(r) + ' |' for r in rows]\n",
    "\n",
    "    return '\\n'.join([header_row, sep_row] + data_rows)\n",
    "\n",
    "\n",
    "def extract_md_tables(text: str) -> list:\n",
    "    \"\"\"\n",
    "    Extract markdown tables from text.\n",
    "    Handles both:\n",
    "      - Normal multi-line markdown tables (one row per line)\n",
    "      - Collapsed single-line tables (entire table on one line, as produced by some OCR models)\n",
    "    \"\"\"\n",
    "    tables = []\n",
    "    lines  = text.split('\\n')\n",
    "    cur    = []\n",
    "\n",
    "    for line in lines:\n",
    "        stripped = line.strip()\n",
    "\n",
    "        # ── Try to detect a collapsed single-line table ───────────────────\n",
    "        if re.search(r'\\|\\s*-{2,}[\\s:]*\\|', stripped):\n",
    "            # Flush any in-progress multi-line table first\n",
    "            if len(cur) >= 2:\n",
    "                tables.append('\\n'.join(cur))\n",
    "                cur = []\n",
    "            expanded = _expand_inline_table(stripped)\n",
    "            if expanded:\n",
    "                tables.append(expanded)\n",
    "            continue  # Don't add this raw line to cur\n",
    "\n",
    "        # ── Normal multi-line table accumulation ──────────────────────────\n",
    "        if stripped.startswith('|') or stripped.count('|') >= 2:\n",
    "            cur.append(stripped)\n",
    "        else:\n",
    "            if len(cur) >= 2:\n",
    "                tables.append('\\n'.join(cur))\n",
    "            cur = []\n",
    "\n",
    "    if len(cur) >= 2:\n",
    "        tables.append('\\n'.join(cur))\n",
    "\n",
    "    return tables\n",
    "\n",
    "\n",
    "def md_table_to_html(md: str) -> str:\n",
    "    lines = [l.strip() for l in md.strip().split('\\n') if l.strip()]\n",
    "    lines = [l for l in lines if not _is_separator_row(l)]\n",
    "    if not lines:\n",
    "        return '<table></table>'\n",
    "    rows = []\n",
    "    for i, line in enumerate(lines):\n",
    "        cells = [re.sub(r'\\s+', ' ', c.strip()) for c in line.strip('|').split('|')]\n",
    "        tag   = 'th' if i == 0 else 'td'\n",
    "        rows.append('<tr>' + ''.join(f'<{tag}>{_html.escape(c)}</{tag}>' for c in cells) + '</tr>')\n",
    "    return '<table>' + ''.join(rows) + '</table>'\n",
    "\n",
    "\n",
    "class AptedConfig(Config):\n",
    "    def rename(self, node1, node2):\n",
    "        t1 = re.sub(r'\\s+', ' ', (node1.text or '').strip())\n",
    "        t2 = re.sub(r'\\s+', ' ', (node2.text or '').strip())\n",
    "        return 0 if (node1.tag == node2.tag and t1 == t2) else 1\n",
    "    def children(self, node):\n",
    "        return list(node)\n",
    "\n",
    "def teds_score(ref_html: str, hyp_html: str) -> Optional[float]:\n",
    "    try:\n",
    "        rt = etree.fromstring(f'<root>{ref_html}</root>')\n",
    "        ht = etree.fromstring(f'<root>{hyp_html}</root>')\n",
    "        dist = APTED(rt, ht, AptedConfig()).compute_edit_distance()\n",
    "        n    = max(len(list(rt.iter())), len(list(ht.iter())))\n",
    "        return round((1.0 - dist / n) * 100, 2) if n > 0 else 0.0\n",
    "    except Exception as e:\n",
    "        print(f'TEDS error: {e}')\n",
    "        return None\n",
    "\n",
    "# ── Per-page evaluation ───────────────────────────────────────────────────────\n",
    "def evaluate_page(ref_raw: str, hyp_raw: str) -> dict:\n",
    "    ref = normalize_arabic_ocr(ref_raw, remove_markdown=True)\n",
    "    hyp = normalize_arabic_ocr(hyp_raw, remove_markdown=True)\n",
    "\n",
    "    if not ref or not hyp:\n",
    "        return {'status': 'empty_after_norm'}\n",
    "\n",
    "    rouge_sc = rs.RougeScorer(['rouge1', 'rougeL'], use_stemmer=False)\n",
    "    pg = {'status': 'ok', 'ref_chars': len(ref_raw), 'hyp_chars': len(hyp_raw)}\n",
    "\n",
    "    # NED\n",
    "    try:\n",
    "        ed = editdistance.eval(ref, hyp)\n",
    "        pg['NED'] = round(ed / max(len(ref), len(hyp), 1) * 100, 2)\n",
    "    except: pg['NED'] = None\n",
    "\n",
    "    # CER / WER β€” jiwer\n",
    "    try:\n",
    "        tf = jiwer.Compose([jiwer.Strip(), jiwer.ReduceToListOfListOfWords()])\n",
    "        pg['CER_jiwer'] = round(jiwer.cer(ref, hyp) * 100, 2)\n",
    "        pg['WER_jiwer'] = round(jiwer.wer(ref, hyp, reference_transform=tf, hypothesis_transform=tf) * 100, 2)\n",
    "    except: pg['CER_jiwer'] = pg['WER_jiwer'] = None\n",
    "\n",
    "    # CER / WER β€” dinglehopper\n",
    "    try:\n",
    "        from dinglehopper.character_error_rate import character_error_rate as dce\n",
    "        from dinglehopper.word_error_rate       import word_error_rate       as dwe\n",
    "        pg['CER_dh'] = round(float(dce(ref, hyp)) * 100, 2)\n",
    "        pg['WER_dh'] = round(float(dwe(ref, hyp)) * 100, 2)\n",
    "    except: pg['CER_dh'] = pg['WER_dh'] = None\n",
    "\n",
    "    # BLEU\n",
    "    try:\n",
    "        pg['BLEU'] = round(sacrebleu.sentence_bleu(hyp, [ref]).score, 2)\n",
    "    except: pg['BLEU'] = None\n",
    "\n",
    "    # ROUGE\n",
    "    try:\n",
    "        r = rouge_sc.score(ref, hyp)\n",
    "        pg['ROUGE_1'] = round(r['rouge1'].fmeasure * 100, 2)\n",
    "        pg['ROUGE_L'] = round(r['rougeL'].fmeasure * 100, 2)\n",
    "    except: pg['ROUGE_1'] = pg['ROUGE_L'] = None\n",
    "\n",
    "    # TEDS β€” on raw text (uses the fixed extractor)\n",
    "    ref_tables = extract_md_tables(ref_raw)\n",
    "    hyp_tables = extract_md_tables(hyp_raw)\n",
    "    pg['n_tables_ref'] = len(ref_tables)\n",
    "    pg['n_tables_hyp'] = len(hyp_tables)\n",
    "    if ref_tables:\n",
    "        teds_list = []\n",
    "        for i, rt in enumerate(ref_tables):\n",
    "            score = teds_score(md_table_to_html(rt), md_table_to_html(hyp_tables[i])) \\\n",
    "                    if i < len(hyp_tables) else 0.0\n",
    "            teds_list.append(score if score is not None else 0.0)\n",
    "        pg['TEDS'] = round(sum(teds_list) / len(teds_list), 2)\n",
    "    else:\n",
    "        pg['TEDS'] = None\n",
    "\n",
    "    return pg\n",
    "\n",
    "# ── Main ──────────────────────────────────────────────────────────────────────\n",
    "gt_raw_content  = open(GT_RAW_PATH,  encoding='utf-8').read().strip()\n",
    "hyp_raw_content = open(HYP_RAW_PATH, encoding='utf-8').read().strip()\n",
    "\n",
    "gt_pages  = split_pages_raw(gt_raw_content)\n",
    "hyp_pages = split_pages_raw(hyp_raw_content)\n",
    "\n",
    "print(f'GT  pages : {len(gt_pages)}  β†’ {list(gt_pages.keys())}')\n",
    "print(f'HYP pages : {len(hyp_pages)} β†’ {list(hyp_pages.keys())}')\n",
    "\n",
    "common   = sorted(set(gt_pages) & set(hyp_pages))\n",
    "only_gt  = set(gt_pages)  - set(hyp_pages)\n",
    "only_hyp = set(hyp_pages) - set(gt_pages)\n",
    "if only_gt:  print(f'⚠️  Only in GT  : {sorted(only_gt)}')\n",
    "if only_hyp: print(f'⚠️  Only in HYP : {sorted(only_hyp)}')\n",
    "print(f'\\nβœ… Common pages to evaluate : {len(common)}')\n",
    "\n",
    "per_page = {}\n",
    "for page_id in common:\n",
    "    per_page[page_id] = evaluate_page(gt_pages[page_id], hyp_pages[page_id])\n",
    "\n",
    "# ── Global averages ───────────────────────────────────────────────────────────\n",
    "def avg(k):\n",
    "    vals = [v[k] for v in per_page.values()\n",
    "            if isinstance(v, dict) and v.get('status') == 'ok' and v.get(k) is not None]\n",
    "    return round(sum(vals) / len(vals), 2) if vals else None\n",
    "\n",
    "overall = {k: avg(k) for k in ['NED','CER_jiwer','WER_jiwer','CER_dh','WER_dh','BLEU','ROUGE_1','ROUGE_L','TEDS']}\n",
    "\n",
    "# ── Print results ─────────────────────────────────────────────────────────────\n",
    "SEP = '=' * 60\n",
    "print(f'\\n{SEP}')\n",
    "print(f'  {MODEL_NAME}  β€”  {len(common)} pages')\n",
    "print(SEP)\n",
    "print(f\"  NED       : {overall['NED']}%          [↓ principal]\")\n",
    "print(f\"  CER_jiwer : {overall['CER_jiwer']}%   WER_jiwer : {overall['WER_jiwer']}%\")\n",
    "print(f\"  CER_dh    : {overall['CER_dh']}%   WER_dh    : {overall['WER_dh']}%\")\n",
    "print(f\"  BLEU      : {overall['BLEU']}      ROUGE-1 : {overall['ROUGE_1']}%   ROUGE-L : {overall['ROUGE_L']}%\")\n",
    "print(f\"  TEDS      : {overall['TEDS']}%         [None = no tables in GT page]\")\n",
    "print(SEP)\n",
    "\n",
    "print(f\"\\n{'─'*60}\")\n",
    "print(f'  Per-page breakdown')\n",
    "print(f\"{'─'*60}\")\n",
    "for page_id, pg in per_page.items():\n",
    "    if pg.get('status') == 'ok':\n",
    "        print(f'\\n  {page_id}')\n",
    "        print(f\"    NED:{pg['NED']}%  CER:{pg['CER_jiwer']}%  WER:{pg['WER_jiwer']}%  BLEU:{pg['BLEU']}  ROUGE-1:{pg['ROUGE_1']}%  TEDS:{pg['TEDS']}%\")\n",
    "        if pg['n_tables_ref'] or pg['n_tables_hyp']:\n",
    "            print(f\"    tables β†’ GT:{pg['n_tables_ref']}  HYP:{pg['n_tables_hyp']}\")\n",
    "    else:\n",
    "        print(f\"\\n  {page_id}  ⚠️  {pg.get('status')}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.20"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}