code refinement
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- release/page-pipeline/infer.py +10 -10
- release/turkic-line-detector-yolo11s/infer.py +6 -6
- release/turkic-ocr-paddleocr-vl-1.6/infer.py +14 -17
- release/turkic-ocr-ppocrv6-medium/infer.py +14 -18
- release/turkic-ocr-qwen3-vl-2b/infer.py +14 -17
- scripts/b1_page_check/b1_page_check.py +3 -3
- scripts/b1_page_check/detb1_page_check.py +3 -3
- scripts/j2/collect.py +1 -1
- scripts/j2/control_report.py +1 -1
- scripts/j2/controls2_report.py +3 -3
- scripts/j2/eligibility.py +8 -8
- scripts/j2/fetch_weights_loadtest.py +2 -2
- scripts/j2/make_controls2_set.py +0 -2
- scripts/j2/raw_samples.py +1 -1
- scripts/j2/run_screen.py +5 -5
- scripts/k1_build_split.py +0 -4
- scripts/k1_labels_all.py +0 -2
- scripts/kohtd_leak_scan.py +1 -1
- scripts/r5/r5_build_real.py +2 -3
- scripts/r5/r5_registry.py +0 -3
- scripts/r5_erran/erran_analysis.py +6 -6
- scripts/r5_erran/erran_sample.py +1 -1
- scripts/r5_freeze/compare_parsers.py +3 -3
- scripts/r5_linedet/inspect_models.sbatch +0 -1
- scripts/r5_loopguard/lg_a1_first_step.py +5 -5
- scripts/r5_loopguard/lg_det_prep.py +2 -2
- scripts/r5_loopguard/lg_detect.py +3 -3
- scripts/r5_loopguard/lg_flags.py +1 -1
- scripts/r5_loopguard/lg_run_gpu.sh +0 -7
- scripts/r5_loopguard/lg_smoke_check.py +1 -1
- scripts/r5_loopguard/om_baseline.py +4 -4
- scripts/r5_loopguard/om_build_pages.py +3 -3
- scripts/r5_loopguard/om_common.py +3 -3
- scripts/r5_loopguard/om_eval_pages.py +7 -7
- scripts/r5_loopguard/om_guard.py +0 -7
- scripts/r5_loopguard/om_lg_select.py +2 -2
- scripts/r5_loopguard/om_score.py +1 -1
- scripts/r5_onemodel/om_baseline.py +4 -4
- scripts/r5_onemodel/om_build_pages.py +3 -3
- scripts/r5_onemodel/om_common.py +3 -3
- scripts/r5_onemodel/om_eval_pages.py +7 -7
- scripts/r5_onemodel/om_probe.py +6 -6
- scripts/r5_onemodel/om_score.py +1 -1
- scripts/r5_onemodel/om_smoke_check.py +1 -2
- scripts/r5_onemodel/om_train.py +8 -8
- scripts/r5_ref/ref_check_tasks.py +1 -1
- scripts/r5_ref/ref_flor_predict.py +1 -1
- scripts/r5_ref/ref_flor_train.py +2 -7
- scripts/r5_ref/ref_make_mix_lists.py +1 -1
- scripts/r5_ref/ref_paper_metrics.py +2 -2
release/page-pipeline/infer.py
CHANGED
|
@@ -27,16 +27,16 @@ import os
|
|
| 27 |
os.environ.setdefault("HF_HUB_OFFLINE", "1")
|
| 28 |
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
|
| 29 |
|
| 30 |
-
import argparse
|
| 31 |
-
import csv
|
| 32 |
-
import importlib.util
|
| 33 |
-
import json
|
| 34 |
-
import subprocess
|
| 35 |
-
import sys
|
| 36 |
-
import tempfile
|
| 37 |
-
import time
|
| 38 |
-
|
| 39 |
-
from PIL import Image
|
| 40 |
|
| 41 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 42 |
IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp")
|
|
|
|
| 27 |
os.environ.setdefault("HF_HUB_OFFLINE", "1")
|
| 28 |
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
|
| 29 |
|
| 30 |
+
import argparse
|
| 31 |
+
import csv
|
| 32 |
+
import importlib.util
|
| 33 |
+
import json
|
| 34 |
+
import subprocess
|
| 35 |
+
import sys
|
| 36 |
+
import tempfile
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
from PIL import Image
|
| 40 |
|
| 41 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 42 |
IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp")
|
release/turkic-line-detector-yolo11s/infer.py
CHANGED
|
@@ -19,11 +19,11 @@ import tempfile
|
|
| 19 |
os.environ.setdefault("YOLO_OFFLINE", "1") # no network access, no analytics, no font download
|
| 20 |
os.environ.setdefault("YOLO_CONFIG_DIR", os.path.join(tempfile.gettempdir(), "ultralytics_cfg_turkic_ocr"))
|
| 21 |
|
| 22 |
-
import argparse
|
| 23 |
-
import csv
|
| 24 |
-
import json
|
| 25 |
-
import sys
|
| 26 |
-
import time
|
| 27 |
|
| 28 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 29 |
IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp")
|
|
@@ -71,7 +71,7 @@ def main():
|
|
| 71 |
for rid, path in items:
|
| 72 |
try:
|
| 73 |
r = det.predict(path, imgsz=1280, conf=a.conf, iou=0.6, max_det=300, device=dev, verbose=False)[0]
|
| 74 |
-
except Exception as ex:
|
| 75 |
sys.stderr.write("cannot read %s: %s\n" % (path, repr(ex)[:120]))
|
| 76 |
fo.write("%s\t0\t[]\t[]\n" % rid)
|
| 77 |
continue
|
|
|
|
| 19 |
os.environ.setdefault("YOLO_OFFLINE", "1") # no network access, no analytics, no font download
|
| 20 |
os.environ.setdefault("YOLO_CONFIG_DIR", os.path.join(tempfile.gettempdir(), "ultralytics_cfg_turkic_ocr"))
|
| 21 |
|
| 22 |
+
import argparse
|
| 23 |
+
import csv
|
| 24 |
+
import json
|
| 25 |
+
import sys
|
| 26 |
+
import time
|
| 27 |
|
| 28 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 29 |
IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp")
|
|
|
|
| 71 |
for rid, path in items:
|
| 72 |
try:
|
| 73 |
r = det.predict(path, imgsz=1280, conf=a.conf, iou=0.6, max_det=300, device=dev, verbose=False)[0]
|
| 74 |
+
except Exception as ex:
|
| 75 |
sys.stderr.write("cannot read %s: %s\n" % (path, repr(ex)[:120]))
|
| 76 |
fo.write("%s\t0\t[]\t[]\n" % rid)
|
| 77 |
continue
|
release/turkic-ocr-paddleocr-vl-1.6/infer.py
CHANGED
|
@@ -25,18 +25,18 @@ os.environ.setdefault("HF_HUB_OFFLINE", "1")
|
|
| 25 |
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
|
| 26 |
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
| 27 |
|
| 28 |
-
import argparse
|
| 29 |
-
import copy
|
| 30 |
-
import csv
|
| 31 |
-
import json
|
| 32 |
-
import re
|
| 33 |
-
import sys
|
| 34 |
-
import time
|
| 35 |
-
import unicodedata
|
| 36 |
|
| 37 |
-
import torch
|
| 38 |
-
import transformers
|
| 39 |
-
from PIL import Image
|
| 40 |
|
| 41 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 42 |
INSTR = "Transcribe the text in this image exactly."
|
|
@@ -50,7 +50,6 @@ def norm(text):
|
|
| 50 |
return _WS.sub(" ", unicodedata.normalize("NFC", text or "")).strip()
|
| 51 |
|
| 52 |
|
| 53 |
-
# ----------------------------------------------------------------------------------------- copied from vlm_common.py
|
| 54 |
def template_kwargs(proc, tok):
|
| 55 |
"""enable_thinking=False for every model whose chat template uses that variable; others get no extra variable."""
|
| 56 |
texts = []
|
|
@@ -135,7 +134,6 @@ def generate_batch(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev,
|
|
| 135 |
return recs
|
| 136 |
|
| 137 |
|
| 138 |
-
# ----------------------------------------------------------------------------------------- the reader
|
| 139 |
class Reader:
|
| 140 |
"""Loads the model of this package once; read() turns PIL images into texts."""
|
| 141 |
|
|
@@ -178,14 +176,14 @@ class Reader:
|
|
| 178 |
try:
|
| 179 |
recs = generate_batch(self.model, self.proc, self.tok, chunk, max_new, self.tmpl_kw, self.gc, self.stop_set,
|
| 180 |
self.dev, self.dtype)
|
| 181 |
-
except Exception as ex:
|
| 182 |
sys.stderr.write("batch failed (%s); reading one image at a time\n" % repr(ex)[:150])
|
| 183 |
recs = []
|
| 184 |
for im in chunk:
|
| 185 |
try:
|
| 186 |
recs += generate_batch(self.model, self.proc, self.tok, [im], max_new, self.tmpl_kw, self.gc, self.stop_set,
|
| 187 |
self.dev, self.dtype)
|
| 188 |
-
except Exception as ex2:
|
| 189 |
recs.append({"raw": "", "n_new": 0, "hit_cap": False, "conf": None, "conf_min": None, "error": repr(ex2)[:200]})
|
| 190 |
for r in recs:
|
| 191 |
r["text"] = norm(r["raw"])
|
|
@@ -193,7 +191,6 @@ class Reader:
|
|
| 193 |
return out
|
| 194 |
|
| 195 |
|
| 196 |
-
# ----------------------------------------------------------------------------------------- input and output
|
| 197 |
def collect_inputs(images=None, manifest=None):
|
| 198 |
"""List of (id, path). A manifest is a TSV with a header and the columns id and image (other columns are ignored)."""
|
| 199 |
if manifest:
|
|
@@ -232,7 +229,7 @@ def main():
|
|
| 232 |
try:
|
| 233 |
imgs.append(Image.open(p).convert("RGB"))
|
| 234 |
keep.append(i)
|
| 235 |
-
except Exception as ex:
|
| 236 |
sys.stderr.write("cannot read %s: %s\n" % (p, repr(ex)[:120]))
|
| 237 |
t1 = time.time()
|
| 238 |
recs = reader.read(imgs, a.unit, a.batch_size)
|
|
|
|
| 25 |
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
|
| 26 |
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
| 27 |
|
| 28 |
+
import argparse
|
| 29 |
+
import copy
|
| 30 |
+
import csv
|
| 31 |
+
import json
|
| 32 |
+
import re
|
| 33 |
+
import sys
|
| 34 |
+
import time
|
| 35 |
+
import unicodedata
|
| 36 |
|
| 37 |
+
import torch
|
| 38 |
+
import transformers
|
| 39 |
+
from PIL import Image
|
| 40 |
|
| 41 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 42 |
INSTR = "Transcribe the text in this image exactly."
|
|
|
|
| 50 |
return _WS.sub(" ", unicodedata.normalize("NFC", text or "")).strip()
|
| 51 |
|
| 52 |
|
|
|
|
| 53 |
def template_kwargs(proc, tok):
|
| 54 |
"""enable_thinking=False for every model whose chat template uses that variable; others get no extra variable."""
|
| 55 |
texts = []
|
|
|
|
| 134 |
return recs
|
| 135 |
|
| 136 |
|
|
|
|
| 137 |
class Reader:
|
| 138 |
"""Loads the model of this package once; read() turns PIL images into texts."""
|
| 139 |
|
|
|
|
| 176 |
try:
|
| 177 |
recs = generate_batch(self.model, self.proc, self.tok, chunk, max_new, self.tmpl_kw, self.gc, self.stop_set,
|
| 178 |
self.dev, self.dtype)
|
| 179 |
+
except Exception as ex:
|
| 180 |
sys.stderr.write("batch failed (%s); reading one image at a time\n" % repr(ex)[:150])
|
| 181 |
recs = []
|
| 182 |
for im in chunk:
|
| 183 |
try:
|
| 184 |
recs += generate_batch(self.model, self.proc, self.tok, [im], max_new, self.tmpl_kw, self.gc, self.stop_set,
|
| 185 |
self.dev, self.dtype)
|
| 186 |
+
except Exception as ex2:
|
| 187 |
recs.append({"raw": "", "n_new": 0, "hit_cap": False, "conf": None, "conf_min": None, "error": repr(ex2)[:200]})
|
| 188 |
for r in recs:
|
| 189 |
r["text"] = norm(r["raw"])
|
|
|
|
| 191 |
return out
|
| 192 |
|
| 193 |
|
|
|
|
| 194 |
def collect_inputs(images=None, manifest=None):
|
| 195 |
"""List of (id, path). A manifest is a TSV with a header and the columns id and image (other columns are ignored)."""
|
| 196 |
if manifest:
|
|
|
|
| 229 |
try:
|
| 230 |
imgs.append(Image.open(p).convert("RGB"))
|
| 231 |
keep.append(i)
|
| 232 |
+
except Exception as ex:
|
| 233 |
sys.stderr.write("cannot read %s: %s\n" % (p, repr(ex)[:120]))
|
| 234 |
t1 = time.time()
|
| 235 |
recs = reader.read(imgs, a.unit, a.batch_size)
|
release/turkic-ocr-ppocrv6-medium/infer.py
CHANGED
|
@@ -33,19 +33,19 @@ import os
|
|
| 33 |
|
| 34 |
os.environ.setdefault("HF_HUB_OFFLINE", "1")
|
| 35 |
|
| 36 |
-
import argparse
|
| 37 |
-
import csv
|
| 38 |
-
import json
|
| 39 |
-
import math
|
| 40 |
-
import sys
|
| 41 |
-
import time
|
| 42 |
-
import unicodedata
|
| 43 |
-
|
| 44 |
-
import numpy as np
|
| 45 |
-
import torch
|
| 46 |
-
import torch.nn.functional as F
|
| 47 |
-
from PIL import Image
|
| 48 |
-
from safetensors.torch import load_file
|
| 49 |
|
| 50 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 51 |
IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp")
|
|
@@ -59,7 +59,6 @@ NEG = -1e30
|
|
| 59 |
LN10 = math.log(10.0)
|
| 60 |
|
| 61 |
|
| 62 |
-
# ----------------------------------------------------------------------------------------- images (data.py pil_tensor, collate)
|
| 63 |
def pil_tensor(im, height):
|
| 64 |
im = im.convert("RGB")
|
| 65 |
w, h = im.size
|
|
@@ -77,7 +76,6 @@ def collate(tensors):
|
|
| 77 |
return torch.stack([F.pad(s, (0, wmax - s.shape[2])) for s in tensors]), seq_lens
|
| 78 |
|
| 79 |
|
| 80 |
-
# ----------------------------------------------------------------------------------------- network (models.py PPOCRArm.infer)
|
| 81 |
class Recognizer:
|
| 82 |
def __init__(self, model_dir=None, device="auto", threads=0):
|
| 83 |
from kraken.lib.codec import PytorchCodec
|
|
@@ -172,7 +170,6 @@ class Recognizer:
|
|
| 172 |
return out
|
| 173 |
|
| 174 |
|
| 175 |
-
# ----------------------------------------------------------------------------------------- character language model (lm_decode.py)
|
| 176 |
_LM = None
|
| 177 |
_L2C = None
|
| 178 |
|
|
@@ -292,7 +289,6 @@ class CharLM:
|
|
| 292 |
return [_decode_one(j) for j in jobs]
|
| 293 |
|
| 294 |
|
| 295 |
-
# ----------------------------------------------------------------------------------------- input and output
|
| 296 |
def collect_inputs(images=None, manifest=None):
|
| 297 |
"""List of (id, path). A manifest is a TSV with a header and the columns id and image (other columns are ignored)."""
|
| 298 |
if manifest:
|
|
@@ -339,7 +335,7 @@ def main():
|
|
| 339 |
try:
|
| 340 |
imgs.append(Image.open(p).convert("RGB"))
|
| 341 |
keep.append(i)
|
| 342 |
-
except Exception as ex:
|
| 343 |
sys.stderr.write("cannot read %s: %s\n" % (p, repr(ex)[:120]))
|
| 344 |
t1 = time.time()
|
| 345 |
outs = rec.read(imgs, a.batch_size, a.decode, lm, a.workers, a.sort, a.batch_pad)
|
|
|
|
| 33 |
|
| 34 |
os.environ.setdefault("HF_HUB_OFFLINE", "1")
|
| 35 |
|
| 36 |
+
import argparse
|
| 37 |
+
import csv
|
| 38 |
+
import json
|
| 39 |
+
import math
|
| 40 |
+
import sys
|
| 41 |
+
import time
|
| 42 |
+
import unicodedata
|
| 43 |
+
|
| 44 |
+
import numpy as np
|
| 45 |
+
import torch
|
| 46 |
+
import torch.nn.functional as F
|
| 47 |
+
from PIL import Image
|
| 48 |
+
from safetensors.torch import load_file
|
| 49 |
|
| 50 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 51 |
IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp")
|
|
|
|
| 59 |
LN10 = math.log(10.0)
|
| 60 |
|
| 61 |
|
|
|
|
| 62 |
def pil_tensor(im, height):
|
| 63 |
im = im.convert("RGB")
|
| 64 |
w, h = im.size
|
|
|
|
| 76 |
return torch.stack([F.pad(s, (0, wmax - s.shape[2])) for s in tensors]), seq_lens
|
| 77 |
|
| 78 |
|
|
|
|
| 79 |
class Recognizer:
|
| 80 |
def __init__(self, model_dir=None, device="auto", threads=0):
|
| 81 |
from kraken.lib.codec import PytorchCodec
|
|
|
|
| 170 |
return out
|
| 171 |
|
| 172 |
|
|
|
|
| 173 |
_LM = None
|
| 174 |
_L2C = None
|
| 175 |
|
|
|
|
| 289 |
return [_decode_one(j) for j in jobs]
|
| 290 |
|
| 291 |
|
|
|
|
| 292 |
def collect_inputs(images=None, manifest=None):
|
| 293 |
"""List of (id, path). A manifest is a TSV with a header and the columns id and image (other columns are ignored)."""
|
| 294 |
if manifest:
|
|
|
|
| 335 |
try:
|
| 336 |
imgs.append(Image.open(p).convert("RGB"))
|
| 337 |
keep.append(i)
|
| 338 |
+
except Exception as ex:
|
| 339 |
sys.stderr.write("cannot read %s: %s\n" % (p, repr(ex)[:120]))
|
| 340 |
t1 = time.time()
|
| 341 |
outs = rec.read(imgs, a.batch_size, a.decode, lm, a.workers, a.sort, a.batch_pad)
|
release/turkic-ocr-qwen3-vl-2b/infer.py
CHANGED
|
@@ -25,18 +25,18 @@ os.environ.setdefault("HF_HUB_OFFLINE", "1")
|
|
| 25 |
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
|
| 26 |
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
| 27 |
|
| 28 |
-
import argparse
|
| 29 |
-
import copy
|
| 30 |
-
import csv
|
| 31 |
-
import json
|
| 32 |
-
import re
|
| 33 |
-
import sys
|
| 34 |
-
import time
|
| 35 |
-
import unicodedata
|
| 36 |
|
| 37 |
-
import torch
|
| 38 |
-
import transformers
|
| 39 |
-
from PIL import Image
|
| 40 |
|
| 41 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 42 |
INSTR = "Transcribe the text in this image exactly."
|
|
@@ -50,7 +50,6 @@ def norm(text):
|
|
| 50 |
return _WS.sub(" ", unicodedata.normalize("NFC", text or "")).strip()
|
| 51 |
|
| 52 |
|
| 53 |
-
# ----------------------------------------------------------------------------------------- copied from vlm_common.py
|
| 54 |
def template_kwargs(proc, tok):
|
| 55 |
"""enable_thinking=False for every model whose chat template uses that variable; others get no extra variable."""
|
| 56 |
texts = []
|
|
@@ -135,7 +134,6 @@ def generate_batch(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev,
|
|
| 135 |
return recs
|
| 136 |
|
| 137 |
|
| 138 |
-
# ----------------------------------------------------------------------------------------- the reader
|
| 139 |
class Reader:
|
| 140 |
"""Loads the model of this package once; read() turns PIL images into texts."""
|
| 141 |
|
|
@@ -178,14 +176,14 @@ class Reader:
|
|
| 178 |
try:
|
| 179 |
recs = generate_batch(self.model, self.proc, self.tok, chunk, max_new, self.tmpl_kw, self.gc, self.stop_set,
|
| 180 |
self.dev, self.dtype)
|
| 181 |
-
except Exception as ex:
|
| 182 |
sys.stderr.write("batch failed (%s); reading one image at a time\n" % repr(ex)[:150])
|
| 183 |
recs = []
|
| 184 |
for im in chunk:
|
| 185 |
try:
|
| 186 |
recs += generate_batch(self.model, self.proc, self.tok, [im], max_new, self.tmpl_kw, self.gc, self.stop_set,
|
| 187 |
self.dev, self.dtype)
|
| 188 |
-
except Exception as ex2:
|
| 189 |
recs.append({"raw": "", "n_new": 0, "hit_cap": False, "conf": None, "conf_min": None, "error": repr(ex2)[:200]})
|
| 190 |
for r in recs:
|
| 191 |
r["text"] = norm(r["raw"])
|
|
@@ -193,7 +191,6 @@ class Reader:
|
|
| 193 |
return out
|
| 194 |
|
| 195 |
|
| 196 |
-
# ----------------------------------------------------------------------------------------- input and output
|
| 197 |
def collect_inputs(images=None, manifest=None):
|
| 198 |
"""List of (id, path). A manifest is a TSV with a header and the columns id and image (other columns are ignored)."""
|
| 199 |
if manifest:
|
|
@@ -232,7 +229,7 @@ def main():
|
|
| 232 |
try:
|
| 233 |
imgs.append(Image.open(p).convert("RGB"))
|
| 234 |
keep.append(i)
|
| 235 |
-
except Exception as ex:
|
| 236 |
sys.stderr.write("cannot read %s: %s\n" % (p, repr(ex)[:120]))
|
| 237 |
t1 = time.time()
|
| 238 |
recs = reader.read(imgs, a.unit, a.batch_size)
|
|
|
|
| 25 |
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
|
| 26 |
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
| 27 |
|
| 28 |
+
import argparse
|
| 29 |
+
import copy
|
| 30 |
+
import csv
|
| 31 |
+
import json
|
| 32 |
+
import re
|
| 33 |
+
import sys
|
| 34 |
+
import time
|
| 35 |
+
import unicodedata
|
| 36 |
|
| 37 |
+
import torch
|
| 38 |
+
import transformers
|
| 39 |
+
from PIL import Image
|
| 40 |
|
| 41 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 42 |
INSTR = "Transcribe the text in this image exactly."
|
|
|
|
| 50 |
return _WS.sub(" ", unicodedata.normalize("NFC", text or "")).strip()
|
| 51 |
|
| 52 |
|
|
|
|
| 53 |
def template_kwargs(proc, tok):
|
| 54 |
"""enable_thinking=False for every model whose chat template uses that variable; others get no extra variable."""
|
| 55 |
texts = []
|
|
|
|
| 134 |
return recs
|
| 135 |
|
| 136 |
|
|
|
|
| 137 |
class Reader:
|
| 138 |
"""Loads the model of this package once; read() turns PIL images into texts."""
|
| 139 |
|
|
|
|
| 176 |
try:
|
| 177 |
recs = generate_batch(self.model, self.proc, self.tok, chunk, max_new, self.tmpl_kw, self.gc, self.stop_set,
|
| 178 |
self.dev, self.dtype)
|
| 179 |
+
except Exception as ex:
|
| 180 |
sys.stderr.write("batch failed (%s); reading one image at a time\n" % repr(ex)[:150])
|
| 181 |
recs = []
|
| 182 |
for im in chunk:
|
| 183 |
try:
|
| 184 |
recs += generate_batch(self.model, self.proc, self.tok, [im], max_new, self.tmpl_kw, self.gc, self.stop_set,
|
| 185 |
self.dev, self.dtype)
|
| 186 |
+
except Exception as ex2:
|
| 187 |
recs.append({"raw": "", "n_new": 0, "hit_cap": False, "conf": None, "conf_min": None, "error": repr(ex2)[:200]})
|
| 188 |
for r in recs:
|
| 189 |
r["text"] = norm(r["raw"])
|
|
|
|
| 191 |
return out
|
| 192 |
|
| 193 |
|
|
|
|
| 194 |
def collect_inputs(images=None, manifest=None):
|
| 195 |
"""List of (id, path). A manifest is a TSV with a header and the columns id and image (other columns are ignored)."""
|
| 196 |
if manifest:
|
|
|
|
| 229 |
try:
|
| 230 |
imgs.append(Image.open(p).convert("RGB"))
|
| 231 |
keep.append(i)
|
| 232 |
+
except Exception as ex:
|
| 233 |
sys.stderr.write("cannot read %s: %s\n" % (p, repr(ex)[:120]))
|
| 234 |
t1 = time.time()
|
| 235 |
recs = reader.read(imgs, a.unit, a.batch_size)
|
scripts/b1_page_check/b1_page_check.py
CHANGED
|
@@ -24,10 +24,10 @@ a = ap.parse_args()
|
|
| 24 |
assert "test" not in os.path.basename(a.pages).lower(), "refusing a test page list"
|
| 25 |
|
| 26 |
sys.path.insert(0, a.vlma)
|
| 27 |
-
import torch
|
| 28 |
-
from PIL import Image
|
| 29 |
|
| 30 |
-
import vlm_common as vc
|
| 31 |
|
| 32 |
torch.set_num_threads(a.threads)
|
| 33 |
PROMPTS = {"spot": "Spotting:", "ocr": "OCR:", "instr": vc.INSTR}
|
|
|
|
| 24 |
assert "test" not in os.path.basename(a.pages).lower(), "refusing a test page list"
|
| 25 |
|
| 26 |
sys.path.insert(0, a.vlma)
|
| 27 |
+
import torch
|
| 28 |
+
from PIL import Image
|
| 29 |
|
| 30 |
+
import vlm_common as vc
|
| 31 |
|
| 32 |
torch.set_num_threads(a.threads)
|
| 33 |
PROMPTS = {"spot": "Spotting:", "ocr": "OCR:", "instr": vc.INSTR}
|
scripts/b1_page_check/detb1_page_check.py
CHANGED
|
@@ -21,10 +21,10 @@ a = ap.parse_args()
|
|
| 21 |
assert "test" not in os.path.basename(a.pages).lower()
|
| 22 |
|
| 23 |
sys.path.insert(0, a.vlma)
|
| 24 |
-
import torch
|
| 25 |
-
from PIL import Image
|
| 26 |
|
| 27 |
-
import vlm_common as vc
|
| 28 |
|
| 29 |
torch.set_num_threads(a.threads)
|
| 30 |
SCHOOL = "/path/to/TURKIC_OCR_DATA/data/raw/school_notebooks_ru"
|
|
|
|
| 21 |
assert "test" not in os.path.basename(a.pages).lower()
|
| 22 |
|
| 23 |
sys.path.insert(0, a.vlma)
|
| 24 |
+
import torch
|
| 25 |
+
from PIL import Image
|
| 26 |
|
| 27 |
+
import vlm_common as vc
|
| 28 |
|
| 29 |
torch.set_num_threads(a.threads)
|
| 30 |
SCHOOL = "/path/to/TURKIC_OCR_DATA/data/raw/school_notebooks_ru"
|
scripts/j2/collect.py
CHANGED
|
@@ -40,7 +40,7 @@ def read_jsonl(path):
|
|
| 40 |
continue
|
| 41 |
try:
|
| 42 |
recs.append(json.loads(line))
|
| 43 |
-
except Exception:
|
| 44 |
bad += 1
|
| 45 |
return recs, bad
|
| 46 |
|
|
|
|
| 40 |
continue
|
| 41 |
try:
|
| 42 |
recs.append(json.loads(line))
|
| 43 |
+
except Exception:
|
| 44 |
bad += 1
|
| 45 |
return recs, bad
|
| 46 |
|
scripts/j2/control_report.py
CHANGED
|
@@ -29,7 +29,7 @@ for dev, root in roots:
|
|
| 29 |
for line in open(pp, encoding="utf-8"):
|
| 30 |
try:
|
| 31 |
r = json.loads(line)
|
| 32 |
-
except Exception:
|
| 33 |
continue
|
| 34 |
preds[r["crop_file"]] = r
|
| 35 |
for H in (40, 80):
|
|
|
|
| 29 |
for line in open(pp, encoding="utf-8"):
|
| 30 |
try:
|
| 31 |
r = json.loads(line)
|
| 32 |
+
except Exception:
|
| 33 |
continue
|
| 34 |
preds[r["crop_file"]] = r
|
| 35 |
for H in (40, 80):
|
scripts/j2/controls2_report.py
CHANGED
|
@@ -25,7 +25,7 @@ def read_preds(path):
|
|
| 25 |
for line in open(path, encoding="utf-8"):
|
| 26 |
try:
|
| 27 |
r = json.loads(line)
|
| 28 |
-
except Exception:
|
| 29 |
continue
|
| 30 |
preds[r["crop_file"]] = r
|
| 31 |
return preds
|
|
@@ -51,7 +51,7 @@ def block(name, model, rows, preds, pick):
|
|
| 51 |
ay = sl.aggregate(lang["ky"]) if lang["ky"] else {}
|
| 52 |
lab = dict(rows)
|
| 53 |
five = " | ".join(f"{lab[c]} => {preds[c]['raw']!r}" for c in pick if c in preds)
|
| 54 |
-
fmt = lambda d, k: f"{d[k]:.4f}" if k in d else ""
|
| 55 |
return "\t".join([name, model, str(len(sc)), f"{a['cer_pooled']:.4f}", f"{a['cer_mean_cap1']:.4f}", f"{a['exact']:.4f}",
|
| 56 |
fmt(ak, "cer_pooled"), fmt(ay, "cer_pooled"), f"{a['hr4_loop_share']:.4f}", f"{a['empty_share']:.4f}",
|
| 57 |
f"{a['other_script_share']:.4f}", five])
|
|
@@ -70,7 +70,7 @@ stored, stretch, fonts = (read_list(os.path.join(c2, n)) for n in
|
|
| 70 |
("contrast_stored_screen_set_v1.tsv", "contrast_stretch_screen_set_v1.tsv", "fonts_screen_set_v1.tsv"))
|
| 71 |
printed40 = [(c, l) for c, l in read_list(printed_list) if "_h40_" in c]
|
| 72 |
for m in models:
|
| 73 |
-
first5 = lambda rows: [c for c, _ in rows[:5]]
|
| 74 |
for name, rows, root in (("A1 KOHTD first 300 crops, as stored", stored, "out_stored"),
|
| 75 |
("A2 KOHTD first 300 crops, contrast stretch p1-p99", stretch, "out_stretch")):
|
| 76 |
r = block(name, m, rows, read_preds(os.path.join(c2, root, m, "s1", "preds.jsonl")), first5(rows))
|
|
|
|
| 25 |
for line in open(path, encoding="utf-8"):
|
| 26 |
try:
|
| 27 |
r = json.loads(line)
|
| 28 |
+
except Exception:
|
| 29 |
continue
|
| 30 |
preds[r["crop_file"]] = r
|
| 31 |
return preds
|
|
|
|
| 51 |
ay = sl.aggregate(lang["ky"]) if lang["ky"] else {}
|
| 52 |
lab = dict(rows)
|
| 53 |
five = " | ".join(f"{lab[c]} => {preds[c]['raw']!r}" for c in pick if c in preds)
|
| 54 |
+
fmt = lambda d, k: f"{d[k]:.4f}" if k in d else ""
|
| 55 |
return "\t".join([name, model, str(len(sc)), f"{a['cer_pooled']:.4f}", f"{a['cer_mean_cap1']:.4f}", f"{a['exact']:.4f}",
|
| 56 |
fmt(ak, "cer_pooled"), fmt(ay, "cer_pooled"), f"{a['hr4_loop_share']:.4f}", f"{a['empty_share']:.4f}",
|
| 57 |
f"{a['other_script_share']:.4f}", five])
|
|
|
|
| 70 |
("contrast_stored_screen_set_v1.tsv", "contrast_stretch_screen_set_v1.tsv", "fonts_screen_set_v1.tsv"))
|
| 71 |
printed40 = [(c, l) for c, l in read_list(printed_list) if "_h40_" in c]
|
| 72 |
for m in models:
|
| 73 |
+
first5 = lambda rows: [c for c, _ in rows[:5]]
|
| 74 |
for name, rows, root in (("A1 KOHTD first 300 crops, as stored", stored, "out_stored"),
|
| 75 |
("A2 KOHTD first 300 crops, contrast stretch p1-p99", stretch, "out_stretch")):
|
| 76 |
r = block(name, m, rows, read_preds(os.path.join(c2, root, m, "s1", "preds.jsonl")), first5(rows))
|
scripts/j2/eligibility.py
CHANGED
|
@@ -120,7 +120,7 @@ for short, repo, design_params, size_class in rows:
|
|
| 120 |
got.append(os.path.relpath(os.path.join(root, fn), local))
|
| 121 |
rec["downloaded_files"] = sorted(g for g in got if not g.startswith(".cache"))
|
| 122 |
assert not any(g.endswith(".py") for g in got), "a .py file was downloaded"
|
| 123 |
-
except Exception as e:
|
| 124 |
rec["errors"].append("fetch: " + repr(e)[:300])
|
| 125 |
json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1)
|
| 126 |
print(short, "FETCH ERROR", repr(e)[:200], flush=True)
|
|
@@ -135,7 +135,7 @@ for short, repo, design_params, size_class in rows:
|
|
| 135 |
rec.update(native_info(cfg_dict))
|
| 136 |
archs = cfg_dict.get("architectures") or []
|
| 137 |
rec["arch_class_in_transformers"] = [bool(getattr(transformers, a, None)) for a in archs]
|
| 138 |
-
except Exception as e:
|
| 139 |
rec["errors"].append("config read: " + repr(e)[:300])
|
| 140 |
cfg_dict = {}
|
| 141 |
|
|
@@ -145,7 +145,7 @@ for short, repo, design_params, size_class in rows:
|
|
| 145 |
cfg = transformers.AutoConfig.from_pretrained(local, trust_remote_code=False)
|
| 146 |
rec["autoconfig_class"] = type(cfg).__module__ + "." + type(cfg).__name__
|
| 147 |
rec["autoconfig_native"] = type(cfg).__module__.startswith("transformers.")
|
| 148 |
-
except Exception as e:
|
| 149 |
rec["autoconfig_native"] = False
|
| 150 |
rec["errors"].append("AutoConfig: " + repr(e)[:300])
|
| 151 |
|
|
@@ -178,7 +178,7 @@ for short, repo, design_params, size_class in rows:
|
|
| 178 |
rec["meta_params_unique"] = n
|
| 179 |
rec["meta_construct_ok"] = True
|
| 180 |
del m
|
| 181 |
-
except Exception as e:
|
| 182 |
rec["meta_construct_ok"] = False
|
| 183 |
rec["errors"].append("meta construct: " + repr(e)[:300])
|
| 184 |
|
|
@@ -189,7 +189,7 @@ for short, repo, design_params, size_class in rows:
|
|
| 189 |
kind = "hf"
|
| 190 |
rec["tokenizer_class"] = type(tok).__module__ + "." + type(tok).__name__
|
| 191 |
rec["tokenizer_native"] = type(tok).__module__.startswith("transformers.")
|
| 192 |
-
except Exception as e:
|
| 193 |
rec["errors"].append("AutoTokenizer: " + repr(e)[:300])
|
| 194 |
tj = os.path.join(local, "tokenizer.json")
|
| 195 |
if os.path.exists(tj):
|
|
@@ -199,7 +199,7 @@ for short, repo, design_params, size_class in rows:
|
|
| 199 |
kind = "raw"
|
| 200 |
rec["tokenizer_class"] = "tokenizers.Tokenizer(from tokenizer.json, data only)"
|
| 201 |
rec["tokenizer_native"] = True
|
| 202 |
-
except Exception as e2:
|
| 203 |
rec["errors"].append("tokenizers.from_file: " + repr(e2)[:300])
|
| 204 |
rec["tokenizer_kind"] = kind
|
| 205 |
if tok is not None:
|
|
@@ -221,7 +221,7 @@ for short, repo, design_params, size_class in rows:
|
|
| 221 |
rec["e3_labels_bad_examples"] = [[a, b] for a, b in bad_l[:12]]
|
| 222 |
rec["e3_labels_bad_strip_equal"] = sum(1 for a, b in bad_l if a.strip() == b.strip())
|
| 223 |
rec["e3_unk_ids_labels"] = unk_l
|
| 224 |
-
except Exception as e:
|
| 225 |
rec["errors"].append("roundtrip: " + repr(e)[:300] + traceback.format_exc()[-300:])
|
| 226 |
|
| 227 |
# processor, trust_remote_code=False
|
|
@@ -231,7 +231,7 @@ for short, repo, design_params, size_class in rows:
|
|
| 231 |
rec["processor_native"] = type(proc).__module__.startswith("transformers.")
|
| 232 |
tmpl = getattr(proc, "chat_template", None)
|
| 233 |
rec["chat_template_present"] = bool(tmpl) or bool(getattr(getattr(proc, "tokenizer", None), "chat_template", None))
|
| 234 |
-
except Exception as e:
|
| 235 |
rec["processor_native"] = False
|
| 236 |
rec["errors"].append("AutoProcessor: " + repr(e)[:300])
|
| 237 |
|
|
|
|
| 120 |
got.append(os.path.relpath(os.path.join(root, fn), local))
|
| 121 |
rec["downloaded_files"] = sorted(g for g in got if not g.startswith(".cache"))
|
| 122 |
assert not any(g.endswith(".py") for g in got), "a .py file was downloaded"
|
| 123 |
+
except Exception as e:
|
| 124 |
rec["errors"].append("fetch: " + repr(e)[:300])
|
| 125 |
json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1)
|
| 126 |
print(short, "FETCH ERROR", repr(e)[:200], flush=True)
|
|
|
|
| 135 |
rec.update(native_info(cfg_dict))
|
| 136 |
archs = cfg_dict.get("architectures") or []
|
| 137 |
rec["arch_class_in_transformers"] = [bool(getattr(transformers, a, None)) for a in archs]
|
| 138 |
+
except Exception as e:
|
| 139 |
rec["errors"].append("config read: " + repr(e)[:300])
|
| 140 |
cfg_dict = {}
|
| 141 |
|
|
|
|
| 145 |
cfg = transformers.AutoConfig.from_pretrained(local, trust_remote_code=False)
|
| 146 |
rec["autoconfig_class"] = type(cfg).__module__ + "." + type(cfg).__name__
|
| 147 |
rec["autoconfig_native"] = type(cfg).__module__.startswith("transformers.")
|
| 148 |
+
except Exception as e:
|
| 149 |
rec["autoconfig_native"] = False
|
| 150 |
rec["errors"].append("AutoConfig: " + repr(e)[:300])
|
| 151 |
|
|
|
|
| 178 |
rec["meta_params_unique"] = n
|
| 179 |
rec["meta_construct_ok"] = True
|
| 180 |
del m
|
| 181 |
+
except Exception as e:
|
| 182 |
rec["meta_construct_ok"] = False
|
| 183 |
rec["errors"].append("meta construct: " + repr(e)[:300])
|
| 184 |
|
|
|
|
| 189 |
kind = "hf"
|
| 190 |
rec["tokenizer_class"] = type(tok).__module__ + "." + type(tok).__name__
|
| 191 |
rec["tokenizer_native"] = type(tok).__module__.startswith("transformers.")
|
| 192 |
+
except Exception as e:
|
| 193 |
rec["errors"].append("AutoTokenizer: " + repr(e)[:300])
|
| 194 |
tj = os.path.join(local, "tokenizer.json")
|
| 195 |
if os.path.exists(tj):
|
|
|
|
| 199 |
kind = "raw"
|
| 200 |
rec["tokenizer_class"] = "tokenizers.Tokenizer(from tokenizer.json, data only)"
|
| 201 |
rec["tokenizer_native"] = True
|
| 202 |
+
except Exception as e2:
|
| 203 |
rec["errors"].append("tokenizers.from_file: " + repr(e2)[:300])
|
| 204 |
rec["tokenizer_kind"] = kind
|
| 205 |
if tok is not None:
|
|
|
|
| 221 |
rec["e3_labels_bad_examples"] = [[a, b] for a, b in bad_l[:12]]
|
| 222 |
rec["e3_labels_bad_strip_equal"] = sum(1 for a, b in bad_l if a.strip() == b.strip())
|
| 223 |
rec["e3_unk_ids_labels"] = unk_l
|
| 224 |
+
except Exception as e:
|
| 225 |
rec["errors"].append("roundtrip: " + repr(e)[:300] + traceback.format_exc()[-300:])
|
| 226 |
|
| 227 |
# processor, trust_remote_code=False
|
|
|
|
| 231 |
rec["processor_native"] = type(proc).__module__.startswith("transformers.")
|
| 232 |
tmpl = getattr(proc, "chat_template", None)
|
| 233 |
rec["chat_template_present"] = bool(tmpl) or bool(getattr(getattr(proc, "tokenizer", None), "chat_template", None))
|
| 234 |
+
except Exception as e:
|
| 235 |
rec["processor_native"] = False
|
| 236 |
rec["errors"].append("AutoProcessor: " + repr(e)[:300])
|
| 237 |
|
scripts/j2/fetch_weights_loadtest.py
CHANGED
|
@@ -81,7 +81,7 @@ for short in shorts:
|
|
| 81 |
rec["ckpt_params_header"] = ck_params
|
| 82 |
rec["ckpt_tensors_header"] = ck_tensors
|
| 83 |
rec["download_seconds"] = round(time.time() - t0, 1)
|
| 84 |
-
except Exception as e:
|
| 85 |
rec["errors"].append("fetch: " + repr(e)[:400])
|
| 86 |
json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1)
|
| 87 |
print(short, "FETCH ERROR", repr(e)[:300], flush=True)
|
|
@@ -120,7 +120,7 @@ for short in shorts:
|
|
| 120 |
else "FAIL")
|
| 121 |
rec["load_seconds"] = round(time.time() - t1, 1)
|
| 122 |
del model
|
| 123 |
-
except Exception as e:
|
| 124 |
rec["load_gate"] = "FAIL"
|
| 125 |
rec["errors"].append("load: " + repr(e)[:500])
|
| 126 |
json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False, default=str)
|
|
|
|
| 81 |
rec["ckpt_params_header"] = ck_params
|
| 82 |
rec["ckpt_tensors_header"] = ck_tensors
|
| 83 |
rec["download_seconds"] = round(time.time() - t0, 1)
|
| 84 |
+
except Exception as e:
|
| 85 |
rec["errors"].append("fetch: " + repr(e)[:400])
|
| 86 |
json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1)
|
| 87 |
print(short, "FETCH ERROR", repr(e)[:300], flush=True)
|
|
|
|
| 120 |
else "FAIL")
|
| 121 |
rec["load_seconds"] = round(time.time() - t1, 1)
|
| 122 |
del model
|
| 123 |
+
except Exception as e:
|
| 124 |
rec["load_gate"] = "FAIL"
|
| 125 |
rec["errors"].append("load: " + repr(e)[:500])
|
| 126 |
json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False, default=str)
|
scripts/j2/make_controls2_set.py
CHANGED
|
@@ -14,7 +14,6 @@ spec.loader.exec_module(cs)
|
|
| 14 |
os.makedirs(os.path.join(out_dir, "img_stretch"), exist_ok=True)
|
| 15 |
os.makedirs(os.path.join(out_dir, "img_fonts"), exist_ok=True)
|
| 16 |
|
| 17 |
-
# ---- A: contrast
|
| 18 |
rows = []
|
| 19 |
with open(screen_set, encoding="utf-8", newline="") as f:
|
| 20 |
f.readline()
|
|
@@ -48,7 +47,6 @@ print("A: 300 crops; grey 1st/99th percentile mean before %.1f / %.1f, after %.1
|
|
| 48 |
print("A: crops whose 1st percentile was already below 30: %d; whose 99th was above 225: %d" % (
|
| 49 |
sum(1 for v in p1b if v < 30), sum(1 for v in p99b if v > 225)))
|
| 50 |
|
| 51 |
-
# ---- B: handwriting fonts
|
| 52 |
words = []
|
| 53 |
with open(words_tsv, encoding="utf-8", newline="") as f:
|
| 54 |
f.readline()
|
|
|
|
| 14 |
os.makedirs(os.path.join(out_dir, "img_stretch"), exist_ok=True)
|
| 15 |
os.makedirs(os.path.join(out_dir, "img_fonts"), exist_ok=True)
|
| 16 |
|
|
|
|
| 17 |
rows = []
|
| 18 |
with open(screen_set, encoding="utf-8", newline="") as f:
|
| 19 |
f.readline()
|
|
|
|
| 47 |
print("A: crops whose 1st percentile was already below 30: %d; whose 99th was above 225: %d" % (
|
| 48 |
sum(1 for v in p1b if v < 30), sum(1 for v in p99b if v > 225)))
|
| 49 |
|
|
|
|
| 50 |
words = []
|
| 51 |
with open(words_tsv, encoding="utf-8", newline="") as f:
|
| 52 |
f.readline()
|
scripts/j2/raw_samples.py
CHANGED
|
@@ -26,7 +26,7 @@ for model in sorted(os.listdir(out_root)):
|
|
| 26 |
for line in open(pp, encoding="utf-8"):
|
| 27 |
try:
|
| 28 |
r = json.loads(line)
|
| 29 |
-
except Exception:
|
| 30 |
continue
|
| 31 |
preds[r["crop_file"]] = r
|
| 32 |
done = [c for c in sample if c in preds]
|
|
|
|
| 26 |
for line in open(pp, encoding="utf-8"):
|
| 27 |
try:
|
| 28 |
r = json.loads(line)
|
| 29 |
+
except Exception:
|
| 30 |
continue
|
| 31 |
preds[r["crop_file"]] = r
|
| 32 |
done = [c for c in sample if c in preds]
|
scripts/j2/run_screen.py
CHANGED
|
@@ -131,7 +131,7 @@ revision = None
|
|
| 131 |
try:
|
| 132 |
lt = json.load(open(os.path.join(os.path.dirname(os.path.abspath(args.out_root)), "j11_stage1_kohtd", "loadtest", args.short + ".json")))
|
| 133 |
revision = lt.get("revision")
|
| 134 |
-
except Exception:
|
| 135 |
pass
|
| 136 |
|
| 137 |
|
|
@@ -177,7 +177,7 @@ def generate_batch(imgs):
|
|
| 177 |
new = out[:, in_len:]
|
| 178 |
try:
|
| 179 |
texts = processor.batch_decode(new, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
| 180 |
-
except Exception:
|
| 181 |
texts = tok.batch_decode(new, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
| 182 |
recs = []
|
| 183 |
for r in range(new.shape[0]):
|
|
@@ -202,7 +202,7 @@ def run_scale(scale, out_dir, bs, list_crops):
|
|
| 202 |
for line in open(pred_path, encoding="utf-8"):
|
| 203 |
try:
|
| 204 |
done.add(json.loads(line)["crop_file"])
|
| 205 |
-
except Exception:
|
| 206 |
pass
|
| 207 |
todo = [c for c in list_crops if c not in done]
|
| 208 |
print(f"[{args.short}] scale {scale}x: done {len(done)}, to do {len(todo)}", flush=True)
|
|
@@ -222,7 +222,7 @@ def run_scale(scale, out_dir, bs, list_crops):
|
|
| 222 |
imgs = [load_image(c, scale) for c in batch]
|
| 223 |
t_img = time.time() - ti
|
| 224 |
recs, t_pre, t_gen = generate_batch(imgs)
|
| 225 |
-
except Exception as e:
|
| 226 |
print(f"[{args.short}] batch failed ({repr(e)[:200]}); one crop at a time", flush=True)
|
| 227 |
if use_cuda:
|
| 228 |
torch.cuda.empty_cache()
|
|
@@ -233,7 +233,7 @@ def run_scale(scale, out_dir, bs, list_crops):
|
|
| 233 |
recs.append(r1[0])
|
| 234 |
t_pre += a
|
| 235 |
t_gen += g
|
| 236 |
-
except Exception as e2:
|
| 237 |
errors += 1
|
| 238 |
recs.append({"raw": "", "n_new": 0, "hit_cap": False, "n_img_tokens": -1, "in_len": -1,
|
| 239 |
"error": repr(e2)[:300]})
|
|
|
|
| 131 |
try:
|
| 132 |
lt = json.load(open(os.path.join(os.path.dirname(os.path.abspath(args.out_root)), "j11_stage1_kohtd", "loadtest", args.short + ".json")))
|
| 133 |
revision = lt.get("revision")
|
| 134 |
+
except Exception:
|
| 135 |
pass
|
| 136 |
|
| 137 |
|
|
|
|
| 177 |
new = out[:, in_len:]
|
| 178 |
try:
|
| 179 |
texts = processor.batch_decode(new, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
| 180 |
+
except Exception:
|
| 181 |
texts = tok.batch_decode(new, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
| 182 |
recs = []
|
| 183 |
for r in range(new.shape[0]):
|
|
|
|
| 202 |
for line in open(pred_path, encoding="utf-8"):
|
| 203 |
try:
|
| 204 |
done.add(json.loads(line)["crop_file"])
|
| 205 |
+
except Exception:
|
| 206 |
pass
|
| 207 |
todo = [c for c in list_crops if c not in done]
|
| 208 |
print(f"[{args.short}] scale {scale}x: done {len(done)}, to do {len(todo)}", flush=True)
|
|
|
|
| 222 |
imgs = [load_image(c, scale) for c in batch]
|
| 223 |
t_img = time.time() - ti
|
| 224 |
recs, t_pre, t_gen = generate_batch(imgs)
|
| 225 |
+
except Exception as e:
|
| 226 |
print(f"[{args.short}] batch failed ({repr(e)[:200]}); one crop at a time", flush=True)
|
| 227 |
if use_cuda:
|
| 228 |
torch.cuda.empty_cache()
|
|
|
|
| 233 |
recs.append(r1[0])
|
| 234 |
t_pre += a
|
| 235 |
t_gen += g
|
| 236 |
+
except Exception as e2:
|
| 237 |
errors += 1
|
| 238 |
recs.append({"raw": "", "n_new": 0, "hit_cap": False, "n_img_tokens": -1, "in_len": -1,
|
| 239 |
"error": repr(e2)[:300]})
|
scripts/k1_build_split.py
CHANGED
|
@@ -1,7 +1,3 @@
|
|
| 1 |
-
# K1 (runs on the cluster): build the KOHTD form-disjoint split exactly as OUT/split_spec_v1.txt says.
|
| 2 |
-
# usage: python k1_build_split.py <labels_all.tsv> <out_dir> <checksum_file> <key_mode: form|block10> <scan_map.tsv|none>
|
| 3 |
-
# scan_map.tsv: header, then "stem<TAB>sheet" for scan-named crops shown to be cuts of a sheet (their split = that sheet's form's split)
|
| 4 |
-
# Text only: no image is read.
|
| 5 |
import collections
|
| 6 |
import hashlib
|
| 7 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import collections
|
| 2 |
import hashlib
|
| 3 |
import os
|
scripts/k1_labels_all.py
CHANGED
|
@@ -1,5 +1,3 @@
|
|
| 1 |
-
# K1 (runs on the cluster, ZEN4): read every KOHTD ann file (JSON with the label) and write one TSV: file stem, label.
|
| 2 |
-
# Text only; no image is read. usage: python k1_labels_all.py <HK_dataset/ann dir> <out_tsv>
|
| 3 |
import json
|
| 4 |
import os
|
| 5 |
import sys
|
|
|
|
|
|
|
|
|
|
| 1 |
import json
|
| 2 |
import os
|
| 3 |
import sys
|
scripts/kohtd_leak_scan.py
CHANGED
|
@@ -21,7 +21,7 @@ OUT = sys.argv[1]
|
|
| 21 |
WORKERS = int(sys.argv[2])
|
| 22 |
SEED = 20261125
|
| 23 |
PREFIX = "KOHTD-split-v1-2026-11-20:"
|
| 24 |
-
STD_MIN = 5.0
|
| 25 |
ASPECT_LOG = math.log(1.15) # aspect-ratio gate: within 15 percent
|
| 26 |
EXPECT = {"train_numbered": 80513, "validation": 16238, "test": 18615, "scan": 24989}
|
| 27 |
FONT = "/path/to/TURKIC_OCR_CODE/.venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf"
|
|
|
|
| 21 |
WORKERS = int(sys.argv[2])
|
| 22 |
SEED = 20261125
|
| 23 |
PREFIX = "KOHTD-split-v1-2026-11-20:"
|
| 24 |
+
STD_MIN = 5.0
|
| 25 |
ASPECT_LOG = math.log(1.15) # aspect-ratio gate: within 15 percent
|
| 26 |
EXPECT = {"train_numbered": 80513, "validation": 16238, "test": 18615, "scan": 24989}
|
| 27 |
FONT = "/path/to/TURKIC_OCR_CODE/.venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf"
|
scripts/r5/r5_build_real.py
CHANGED
|
@@ -116,7 +116,7 @@ def stage_kohtd():
|
|
| 116 |
altered[sp] += 1
|
| 117 |
if key_type == "numbered":
|
| 118 |
grp = "kohtd_form_" + form_id
|
| 119 |
-
else:
|
| 120 |
grp = "kohtd_scan_" + crop_file[:-4].replace("word_croped_", "", 1).rsplit("_", 2)[0]
|
| 121 |
rows.append(row("kohtd:" + crop_file[:-4], KOHTD_IMG / crop_file, t, "kk", "Cyrl", "hand_real",
|
| 122 |
"kohtd", "val" if sp == "val" else sp, grp, "word"))
|
|
@@ -361,7 +361,7 @@ def school_page_job(args):
|
|
| 361 |
if im.size != (W, H):
|
| 362 |
return fn, [], {"error": "size_mismatch", "got": im.size, "want": (W, H)}
|
| 363 |
page = cv2.cvtColor(np.array(im.convert("RGB")), cv2.COLOR_RGB2BGR)
|
| 364 |
-
except Exception as e:
|
| 365 |
return fn, [], {"error": repr(e)}
|
| 366 |
out_rows = []
|
| 367 |
skipped = collections.Counter()
|
|
@@ -693,7 +693,6 @@ def stage_dedupe():
|
|
| 693 |
print(json.dumps(info, ensure_ascii=False)[:3500])
|
| 694 |
|
| 695 |
|
| 696 |
-
|
| 697 |
# synthetic manifests: hash and report-only duplicate check
|
| 698 |
def synth_manifest_names():
|
| 699 |
return sorted(q.stem for pat in ("synth_*.tsv", "az_localdoc_*.tsv") for q in MAN.glob(pat) if q.stem.rsplit("_", 1)[-1] in ("train", "val", "test"))
|
|
|
|
| 116 |
altered[sp] += 1
|
| 117 |
if key_type == "numbered":
|
| 118 |
grp = "kohtd_form_" + form_id
|
| 119 |
+
else:
|
| 120 |
grp = "kohtd_scan_" + crop_file[:-4].replace("word_croped_", "", 1).rsplit("_", 2)[0]
|
| 121 |
rows.append(row("kohtd:" + crop_file[:-4], KOHTD_IMG / crop_file, t, "kk", "Cyrl", "hand_real",
|
| 122 |
"kohtd", "val" if sp == "val" else sp, grp, "word"))
|
|
|
|
| 361 |
if im.size != (W, H):
|
| 362 |
return fn, [], {"error": "size_mismatch", "got": im.size, "want": (W, H)}
|
| 363 |
page = cv2.cvtColor(np.array(im.convert("RGB")), cv2.COLOR_RGB2BGR)
|
| 364 |
+
except Exception as e:
|
| 365 |
return fn, [], {"error": repr(e)}
|
| 366 |
out_rows = []
|
| 367 |
skipped = collections.Counter()
|
|
|
|
| 693 |
print(json.dumps(info, ensure_ascii=False)[:3500])
|
| 694 |
|
| 695 |
|
|
|
|
| 696 |
# synthetic manifests: hash and report-only duplicate check
|
| 697 |
def synth_manifest_names():
|
| 698 |
return sorted(q.stem for pat in ("synth_*.tsv", "az_localdoc_*.tsv") for q in MAN.glob(pat) if q.stem.rsplit("_", 1)[-1] in ("train", "val", "test"))
|
scripts/r5/r5_registry.py
CHANGED
|
@@ -66,7 +66,6 @@ p2info = json.load(open(R5 / "p2_slice_info.json")) if (R5 / "p2_slice_info.json
|
|
| 66 |
p2_final = bool(p2info.get("final"))
|
| 67 |
|
| 68 |
sets = [
|
| 69 |
-
# ---- validation sets (selection only; never used for the final claim)
|
| 70 |
entry("V1", "kohtd_screen_v1", "val",
|
| 71 |
"KOHTD validation screen set of the zero-shot screen: at most 15 crops per validation form, 3,678 crops (screen rule v1). Selection of B1 and B2 by amendment 3.2 C6 uses CER on this set.", False,
|
| 72 |
group_unit="KOHTD form", source_of_list="records/R4/J2_screen/screen_set_v1.tsv, sha256 aca23aed02629f884cd533761ca2553951eb91cc9b15120a25c88071f54198ec (matches the cluster copy), used unchanged",
|
|
@@ -91,7 +90,6 @@ sets = [
|
|
| 91 |
entry("synth_typed_val", "synth_typed_val", "val", "Synthetic typed line crops (500 per language-script planned).", False, group_unit="source document", owner="GEN"),
|
| 92 |
entry("synth_clutter_val", "synth_clutter_val", "val", "Clutter crops with no text; the target is the empty string (500 planned). Measures hallucination.", False, owner="GEN"),
|
| 93 |
entry("synth_pages_val", "synth_pages_val", "val", "Composed pages with line boxes and polygons (300 planned), for detector validation.", False, owner="GEN"),
|
| 94 |
-
# ---- test sets (locked)
|
| 95 |
entry("kohtd_test", "kohtd_test", "test", "Primary endpoint P1: CER on all 18,615 KOHTD test crops of 305 forms.", True,
|
| 96 |
group_unit="KOHTD form", endpoint="P1", split_rule="K1 split v1, share 85..99 of the form hash",
|
| 97 |
caution="form-disjoint, not writer-disjoint (writer ids do not exist); labels are crowd labels (two volunteers agreeing)"),
|
|
@@ -138,7 +136,6 @@ reg = {
|
|
| 138 |
}
|
| 139 |
json.dump(reg, open(R5 / "evalsets.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
|
| 140 |
|
| 141 |
-
# ---- effective mix_v1 shares
|
| 142 |
n_train = {k: mstats[k]["rows"] for k in ("kohtd_train", "hkr_train", "chd_train", "school_train") if k in mstats}
|
| 143 |
latin_items = 0 # no Turkish (or other Latin-script) handwriting word or line set is held: the Turkish sets are single characters
|
| 144 |
latin_cap_share = min(0.05, 5 * latin_items / 1e6)
|
|
|
|
| 66 |
p2_final = bool(p2info.get("final"))
|
| 67 |
|
| 68 |
sets = [
|
|
|
|
| 69 |
entry("V1", "kohtd_screen_v1", "val",
|
| 70 |
"KOHTD validation screen set of the zero-shot screen: at most 15 crops per validation form, 3,678 crops (screen rule v1). Selection of B1 and B2 by amendment 3.2 C6 uses CER on this set.", False,
|
| 71 |
group_unit="KOHTD form", source_of_list="records/R4/J2_screen/screen_set_v1.tsv, sha256 aca23aed02629f884cd533761ca2553951eb91cc9b15120a25c88071f54198ec (matches the cluster copy), used unchanged",
|
|
|
|
| 90 |
entry("synth_typed_val", "synth_typed_val", "val", "Synthetic typed line crops (500 per language-script planned).", False, group_unit="source document", owner="GEN"),
|
| 91 |
entry("synth_clutter_val", "synth_clutter_val", "val", "Clutter crops with no text; the target is the empty string (500 planned). Measures hallucination.", False, owner="GEN"),
|
| 92 |
entry("synth_pages_val", "synth_pages_val", "val", "Composed pages with line boxes and polygons (300 planned), for detector validation.", False, owner="GEN"),
|
|
|
|
| 93 |
entry("kohtd_test", "kohtd_test", "test", "Primary endpoint P1: CER on all 18,615 KOHTD test crops of 305 forms.", True,
|
| 94 |
group_unit="KOHTD form", endpoint="P1", split_rule="K1 split v1, share 85..99 of the form hash",
|
| 95 |
caution="form-disjoint, not writer-disjoint (writer ids do not exist); labels are crowd labels (two volunteers agreeing)"),
|
|
|
|
| 136 |
}
|
| 137 |
json.dump(reg, open(R5 / "evalsets.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
|
| 138 |
|
|
|
|
| 139 |
n_train = {k: mstats[k]["rows"] for k in ("kohtd_train", "hkr_train", "chd_train", "school_train") if k in mstats}
|
| 140 |
latin_items = 0 # no Turkish (or other Latin-script) handwriting word or line set is held: the Turkish sets are single characters
|
| 141 |
latin_cap_share = min(0.05, 5 * latin_items / 1e6)
|
scripts/r5_erran/erran_analysis.py
CHANGED
|
@@ -9,12 +9,12 @@ import unicodedata
|
|
| 9 |
import numpy as np
|
| 10 |
|
| 11 |
sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src")
|
| 12 |
-
from r5eval import stats
|
| 13 |
-
from r5eval.align import align_ops, lev_fast
|
| 14 |
-
from r5eval.analyse import COLLAPSE, LETTERS, LEN_EDGES, length_bucket
|
| 15 |
-
from r5eval.ioutil import read_manifest, read_preds, read_meta_tsv, sha256_file, write_json_atomic
|
| 16 |
-
from r5eval.lookalike import PARTNER, repair_label
|
| 17 |
-
from r5eval.textnorm import fold_lower, char_script_set, norm
|
| 18 |
|
| 19 |
D = "/path/to/TURKIC_OCR_DATA"
|
| 20 |
PREDS = D + "/outputs/r5/preds"
|
|
|
|
| 9 |
import numpy as np
|
| 10 |
|
| 11 |
sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src")
|
| 12 |
+
from r5eval import stats
|
| 13 |
+
from r5eval.align import align_ops, lev_fast
|
| 14 |
+
from r5eval.analyse import COLLAPSE, LETTERS, LEN_EDGES, length_bucket
|
| 15 |
+
from r5eval.ioutil import read_manifest, read_preds, read_meta_tsv, sha256_file, write_json_atomic
|
| 16 |
+
from r5eval.lookalike import PARTNER, repair_label
|
| 17 |
+
from r5eval.textnorm import fold_lower, char_script_set, norm
|
| 18 |
|
| 19 |
D = "/path/to/TURKIC_OCR_DATA"
|
| 20 |
PREDS = D + "/outputs/r5/preds"
|
scripts/r5_erran/erran_sample.py
CHANGED
|
@@ -7,7 +7,7 @@ import numpy as np
|
|
| 7 |
from PIL import Image, ImageDraw, ImageFont
|
| 8 |
|
| 9 |
sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src")
|
| 10 |
-
from r5eval.ioutil import read_manifest
|
| 11 |
|
| 12 |
SEED = 20261122
|
| 13 |
N_PER_ARM = 120
|
|
|
|
| 7 |
from PIL import Image, ImageDraw, ImageFont
|
| 8 |
|
| 9 |
sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src")
|
| 10 |
+
from r5eval.ioutil import read_manifest
|
| 11 |
|
| 12 |
SEED = 20261122
|
| 13 |
N_PER_ARM = 120
|
scripts/r5_freeze/compare_parsers.py
CHANGED
|
@@ -20,11 +20,11 @@ def key(manifest, flt):
|
|
| 20 |
|
| 21 |
|
| 22 |
readers = {}
|
| 23 |
-
from linedet.data import load_mix as ld_load
|
| 24 |
readers["LINEDET linedet.data.load_mix"] = {key(c["manifest"], c["filter"]): (c["share"], c["name"]) for c in ld_load(yml)}
|
| 25 |
-
import ref_make_mix_lists as REF
|
| 26 |
readers["REF ref_make_mix_lists.load_mix"] = {key(c["manifest"], c["filter"]): (c["share"], c["name"]) for c in REF.load_mix(yml)}
|
| 27 |
-
from r5eval.ktrain import read_mix_leaves
|
| 28 |
kt = read_mix_leaves(yml)
|
| 29 |
readers["EVALCODE r5eval.ktrain.read_mix_leaves (no shares)"] = {key(c["manifest"], c["filter"]): (None, c["name"]) for c in kt}
|
| 30 |
s = json.load(open(vsum, encoding="utf-8"))
|
|
|
|
| 20 |
|
| 21 |
|
| 22 |
readers = {}
|
| 23 |
+
from linedet.data import load_mix as ld_load
|
| 24 |
readers["LINEDET linedet.data.load_mix"] = {key(c["manifest"], c["filter"]): (c["share"], c["name"]) for c in ld_load(yml)}
|
| 25 |
+
import ref_make_mix_lists as REF
|
| 26 |
readers["REF ref_make_mix_lists.load_mix"] = {key(c["manifest"], c["filter"]): (c["share"], c["name"]) for c in REF.load_mix(yml)}
|
| 27 |
+
from r5eval.ktrain import read_mix_leaves
|
| 28 |
kt = read_mix_leaves(yml)
|
| 29 |
readers["EVALCODE r5eval.ktrain.read_mix_leaves (no shares)"] = {key(c["manifest"], c["filter"]): (None, c["name"]) for c in kt}
|
| 30 |
s = json.load(open(vsum, encoding="utf-8"))
|
scripts/r5_linedet/inspect_models.sbatch
CHANGED
|
@@ -16,7 +16,6 @@ $HOME/.local/bin/uv pip freeze --python $CODE/.venv_kraken/bin/python > $DATA/ou
|
|
| 16 |
OUT=$DATA/outputs/r5/linedet/base_models
|
| 17 |
mkdir -p $OUT
|
| 18 |
SITE=$CODE/.venv_kraken/lib/python3.12/site-packages
|
| 19 |
-
# rule 0.11: sha256 of every .py file of the maker packages that can run
|
| 20 |
find $SITE/kraken $SITE/ultralytics -name '*.py' | sort | xargs sha256sum > $DATA/outputs/r5/linedet/maker_py_sha256.txt
|
| 21 |
wc -l $DATA/outputs/r5/linedet/maker_py_sha256.txt
|
| 22 |
cd $CODE
|
|
|
|
| 16 |
OUT=$DATA/outputs/r5/linedet/base_models
|
| 17 |
mkdir -p $OUT
|
| 18 |
SITE=$CODE/.venv_kraken/lib/python3.12/site-packages
|
|
|
|
| 19 |
find $SITE/kraken $SITE/ultralytics -name '*.py' | sort | xargs sha256sum > $DATA/outputs/r5/linedet/maker_py_sha256.txt
|
| 20 |
wc -l $DATA/outputs/r5/linedet/maker_py_sha256.txt
|
| 21 |
cd $CODE
|
scripts/r5_loopguard/lg_a1_first_step.py
CHANGED
|
@@ -5,12 +5,12 @@ import sys
|
|
| 5 |
|
| 6 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 7 |
sys.path.insert(0, HERE)
|
| 8 |
-
import om_common as C
|
| 9 |
-
import om_text as T
|
| 10 |
|
| 11 |
-
import torch
|
| 12 |
-
from PIL import Image
|
| 13 |
-
from transformers import NoRepeatNGramLogitsProcessor
|
| 14 |
|
| 15 |
ap = argparse.ArgumentParser()
|
| 16 |
ap.add_argument("--ids", required=True)
|
|
|
|
| 5 |
|
| 6 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 7 |
sys.path.insert(0, HERE)
|
| 8 |
+
import om_common as C
|
| 9 |
+
import om_text as T
|
| 10 |
|
| 11 |
+
import torch
|
| 12 |
+
from PIL import Image
|
| 13 |
+
from transformers import NoRepeatNGramLogitsProcessor
|
| 14 |
|
| 15 |
ap = argparse.ArgumentParser()
|
| 16 |
ap.add_argument("--ids", required=True)
|
scripts/r5_loopguard/lg_det_prep.py
CHANGED
|
@@ -8,8 +8,8 @@ import zipfile
|
|
| 8 |
|
| 9 |
CODE = "/path/to/TURKIC_OCR_CODE"
|
| 10 |
sys.path.insert(0, CODE + "/src")
|
| 11 |
-
from linedet import det_prep as DP
|
| 12 |
-
from linedet.common import DATA, write_tsv
|
| 13 |
|
| 14 |
csv.field_size_limit(10 ** 9)
|
| 15 |
HEADER = ["id", "image", "width", "height", "scale", "n_lines", "boxes_json", "polys_json", "baselines_json", "ref_lines_json", "note"]
|
|
|
|
| 8 |
|
| 9 |
CODE = "/path/to/TURKIC_OCR_CODE"
|
| 10 |
sys.path.insert(0, CODE + "/src")
|
| 11 |
+
from linedet import det_prep as DP
|
| 12 |
+
from linedet.common import DATA, write_tsv
|
| 13 |
|
| 14 |
csv.field_size_limit(10 ** 9)
|
| 15 |
HEADER = ["id", "image", "width", "height", "scale", "n_lines", "boxes_json", "polys_json", "baselines_json", "ref_lines_json", "note"]
|
scripts/r5_loopguard/lg_detect.py
CHANGED
|
@@ -7,7 +7,7 @@ import time
|
|
| 7 |
os.environ.setdefault("YOLO_OFFLINE", "1")
|
| 8 |
os.environ.setdefault("YOLO_CONFIG_DIR", "/path/to/TURKIC_OCR_DATA/tmp/ultralytics_cfg")
|
| 9 |
|
| 10 |
-
import torch
|
| 11 |
|
| 12 |
csv.field_size_limit(10 ** 9)
|
| 13 |
ap = argparse.ArgumentParser()
|
|
@@ -21,7 +21,7 @@ ap.add_argument("--max-pages", type=int, default=0)
|
|
| 21 |
ap.add_argument("--threads", type=int, default=16)
|
| 22 |
a = ap.parse_args()
|
| 23 |
torch.set_num_threads(a.threads)
|
| 24 |
-
from ultralytics import YOLO
|
| 25 |
|
| 26 |
with open(a.pages, encoding="utf-8", newline="") as f:
|
| 27 |
pages = list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))
|
|
@@ -33,7 +33,7 @@ if os.path.exists(a.out):
|
|
| 33 |
for ln in open(a.out, encoding="utf-8"):
|
| 34 |
try:
|
| 35 |
done.add(json.loads(ln)["id"])
|
| 36 |
-
except Exception:
|
| 37 |
pass
|
| 38 |
det = YOLO(a.weights)
|
| 39 |
with open(a.out, "a", encoding="utf-8") as fo:
|
|
|
|
| 7 |
os.environ.setdefault("YOLO_OFFLINE", "1")
|
| 8 |
os.environ.setdefault("YOLO_CONFIG_DIR", "/path/to/TURKIC_OCR_DATA/tmp/ultralytics_cfg")
|
| 9 |
|
| 10 |
+
import torch
|
| 11 |
|
| 12 |
csv.field_size_limit(10 ** 9)
|
| 13 |
ap = argparse.ArgumentParser()
|
|
|
|
| 21 |
ap.add_argument("--threads", type=int, default=16)
|
| 22 |
a = ap.parse_args()
|
| 23 |
torch.set_num_threads(a.threads)
|
| 24 |
+
from ultralytics import YOLO
|
| 25 |
|
| 26 |
with open(a.pages, encoding="utf-8", newline="") as f:
|
| 27 |
pages = list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))
|
|
|
|
| 33 |
for ln in open(a.out, encoding="utf-8"):
|
| 34 |
try:
|
| 35 |
done.add(json.loads(ln)["id"])
|
| 36 |
+
except Exception:
|
| 37 |
pass
|
| 38 |
det = YOLO(a.weights)
|
| 39 |
with open(a.out, "a", encoding="utf-8") as fo:
|
scripts/r5_loopguard/lg_flags.py
CHANGED
|
@@ -5,7 +5,7 @@ import sys
|
|
| 5 |
|
| 6 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 7 |
sys.path.insert(0, HERE)
|
| 8 |
-
import om_text as T
|
| 9 |
|
| 10 |
ap = argparse.ArgumentParser()
|
| 11 |
ap.add_argument("mode", choices=["val", "heldout"])
|
|
|
|
| 5 |
|
| 6 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 7 |
sys.path.insert(0, HERE)
|
| 8 |
+
import om_text as T
|
| 9 |
|
| 10 |
ap = argparse.ArgumentParser()
|
| 11 |
ap.add_argument("mode", choices=["val", "heldout"])
|
scripts/r5_loopguard/lg_run_gpu.sh
CHANGED
|
@@ -93,26 +93,21 @@ score() { # tag, om_score options...: any non-zero exit stops the job before a
|
|
| 93 |
}
|
| 94 |
hostname; nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null || echo "no GPU visible (device $DEV)"; date -u +%FT%TZ
|
| 95 |
echo "LOOPGUARD-1 job $SLURM_JOB_ID, resubmission $N of $MAXR, device $DEV, out $O, limit $LIMIT s, dry ${DRY:-no}"
|
| 96 |
-
# ---- 0 checks
|
| 97 |
( cd / && sha256sum -c --quiet $S/lg_pins_val.sha256 ) || fail "a pinned validation input changed" 3
|
| 98 |
if [ -z "$DRY" ]; then
|
| 99 |
grep -q '"passed": true' $OFFICIAL/prep.done.json 2>/dev/null || fail "prep.done.json missing or not passed" 3
|
| 100 |
( cd / && sha256sum -c --quiet $S/lg_pins_heldout.sha256 ) || fail "a pinned held-out input changed" 3
|
| 101 |
fi
|
| 102 |
echo "=== checks passed $(date -u +%FT%TZ)"
|
| 103 |
-
# ---- 0b the fresh control arm A0 (unguarded, all validation pages, batch 8, no batch-1 probe)
|
| 104 |
evalpages A0 A0 gen_val,school_val "--batch 8 --batch1-probe 0"
|
| 105 |
-
# ---- 1, 2 validation arms
|
| 106 |
evalpages A1 A1 gen_val,school_val
|
| 107 |
evalpages A2 A2 gen_val,school_val
|
| 108 |
-
# ---- 2b acceptance (before any score is read)
|
| 109 |
$PK -I $S/lg_accept.py --a0 $A0F --a1 $O/page_preds/A1 --a2 $O/page_preds/A2 --stored $A0STORED --tol 0.01 --out $O/acceptance.json $XA
|
| 110 |
RC=$?
|
| 111 |
if [ $RC -ne 0 ]; then
|
| 112 |
[ -z "$DRY" ] && fail "acceptance checks (exit $RC): investigate before scoring; no selection, no UNSEAL" 4
|
| 113 |
echo "DRY RUN: acceptance failed (exit $RC), continuing to exercise the scorer"
|
| 114 |
fi
|
| 115 |
-
# ---- 3 validation scoring and selection
|
| 116 |
if [ ! -f $O/selection.json ]; then
|
| 117 |
echo "=== validation scoring $(date -u +%FT%TZ)"
|
| 118 |
$PK -I $S/lg_flags.py val --a2 $O/page_preds/A2 --a0 $A0F --out $O/flags_val.json || fail "flags"
|
|
@@ -128,7 +123,6 @@ fi
|
|
| 128 |
SEL=$(head -n 1 $O/SELECTED)
|
| 129 |
echo "selected: $SEL"
|
| 130 |
if [ -n "$DRY" ]; then echo "DRY RUN: stops after selection; held-out stages are never run in a dry run"; rm -f $GUARD; exit 0; fi
|
| 131 |
-
# ---- 4 held-out runs, only under the unseal token
|
| 132 |
if [ ! -f $UNSEAL ]; then
|
| 133 |
if [ "$SEL" != "NONE" ]; then fail "arm $SEL was selected but no unseal token exists (see selection.json unseal_decision)" 6; fi
|
| 134 |
echo "=== no arm eligible: the held-out sets stay sealed $(date -u +%FT%TZ)"
|
|
@@ -143,7 +137,6 @@ case "$SEL" in
|
|
| 143 |
evalpages $SEL $SEL clutter_spot "--max-new 256"
|
| 144 |
;;
|
| 145 |
esac
|
| 146 |
-
# ---- 5 held-out scoring and confirmation
|
| 147 |
if [ ! -f $O/confirm.json ]; then
|
| 148 |
echo "=== held-out scoring $(date -u +%FT%TZ)"
|
| 149 |
$PK -I $S/lg_flags.py heldout --a0obs $O/page_preds/A0obs --out $O/flags_test.json || fail "held-out flags"
|
|
|
|
| 93 |
}
|
| 94 |
hostname; nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null || echo "no GPU visible (device $DEV)"; date -u +%FT%TZ
|
| 95 |
echo "LOOPGUARD-1 job $SLURM_JOB_ID, resubmission $N of $MAXR, device $DEV, out $O, limit $LIMIT s, dry ${DRY:-no}"
|
|
|
|
| 96 |
( cd / && sha256sum -c --quiet $S/lg_pins_val.sha256 ) || fail "a pinned validation input changed" 3
|
| 97 |
if [ -z "$DRY" ]; then
|
| 98 |
grep -q '"passed": true' $OFFICIAL/prep.done.json 2>/dev/null || fail "prep.done.json missing or not passed" 3
|
| 99 |
( cd / && sha256sum -c --quiet $S/lg_pins_heldout.sha256 ) || fail "a pinned held-out input changed" 3
|
| 100 |
fi
|
| 101 |
echo "=== checks passed $(date -u +%FT%TZ)"
|
|
|
|
| 102 |
evalpages A0 A0 gen_val,school_val "--batch 8 --batch1-probe 0"
|
|
|
|
| 103 |
evalpages A1 A1 gen_val,school_val
|
| 104 |
evalpages A2 A2 gen_val,school_val
|
|
|
|
| 105 |
$PK -I $S/lg_accept.py --a0 $A0F --a1 $O/page_preds/A1 --a2 $O/page_preds/A2 --stored $A0STORED --tol 0.01 --out $O/acceptance.json $XA
|
| 106 |
RC=$?
|
| 107 |
if [ $RC -ne 0 ]; then
|
| 108 |
[ -z "$DRY" ] && fail "acceptance checks (exit $RC): investigate before scoring; no selection, no UNSEAL" 4
|
| 109 |
echo "DRY RUN: acceptance failed (exit $RC), continuing to exercise the scorer"
|
| 110 |
fi
|
|
|
|
| 111 |
if [ ! -f $O/selection.json ]; then
|
| 112 |
echo "=== validation scoring $(date -u +%FT%TZ)"
|
| 113 |
$PK -I $S/lg_flags.py val --a2 $O/page_preds/A2 --a0 $A0F --out $O/flags_val.json || fail "flags"
|
|
|
|
| 123 |
SEL=$(head -n 1 $O/SELECTED)
|
| 124 |
echo "selected: $SEL"
|
| 125 |
if [ -n "$DRY" ]; then echo "DRY RUN: stops after selection; held-out stages are never run in a dry run"; rm -f $GUARD; exit 0; fi
|
|
|
|
| 126 |
if [ ! -f $UNSEAL ]; then
|
| 127 |
if [ "$SEL" != "NONE" ]; then fail "arm $SEL was selected but no unseal token exists (see selection.json unseal_decision)" 6; fi
|
| 128 |
echo "=== no arm eligible: the held-out sets stay sealed $(date -u +%FT%TZ)"
|
|
|
|
| 137 |
evalpages $SEL $SEL clutter_spot "--max-new 256"
|
| 138 |
;;
|
| 139 |
esac
|
|
|
|
| 140 |
if [ ! -f $O/confirm.json ]; then
|
| 141 |
echo "=== held-out scoring $(date -u +%FT%TZ)"
|
| 142 |
$PK -I $S/lg_flags.py heldout --a0obs $O/page_preds/A0obs --out $O/flags_test.json || fail "held-out flags"
|
scripts/r5_loopguard/lg_smoke_check.py
CHANGED
|
@@ -5,7 +5,7 @@ import sys
|
|
| 5 |
|
| 6 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 7 |
sys.path.insert(0, HERE)
|
| 8 |
-
import om_text as T
|
| 9 |
|
| 10 |
D = "/path/to/TURKIC_OCR_DATA"
|
| 11 |
ap = argparse.ArgumentParser()
|
|
|
|
| 5 |
|
| 6 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 7 |
sys.path.insert(0, HERE)
|
| 8 |
+
import om_text as T
|
| 9 |
|
| 10 |
D = "/path/to/TURKIC_OCR_DATA"
|
| 11 |
ap = argparse.ArgumentParser()
|
scripts/r5_loopguard/om_baseline.py
CHANGED
|
@@ -8,11 +8,11 @@ import unicodedata
|
|
| 8 |
|
| 9 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 10 |
sys.path.insert(0, HERE)
|
| 11 |
-
import om_common as C
|
| 12 |
-
import om_text as T
|
| 13 |
|
| 14 |
-
import torch
|
| 15 |
-
from PIL import Image
|
| 16 |
|
| 17 |
vc = C.vc
|
| 18 |
csv.field_size_limit(10 ** 9)
|
|
|
|
| 8 |
|
| 9 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 10 |
sys.path.insert(0, HERE)
|
| 11 |
+
import om_common as C
|
| 12 |
+
import om_text as T
|
| 13 |
|
| 14 |
+
import torch
|
| 15 |
+
from PIL import Image
|
| 16 |
|
| 17 |
vc = C.vc
|
| 18 |
csv.field_size_limit(10 ** 9)
|
scripts/r5_loopguard/om_build_pages.py
CHANGED
|
@@ -12,7 +12,7 @@ import zipfile
|
|
| 12 |
|
| 13 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 14 |
sys.path.insert(0, HERE)
|
| 15 |
-
import om_text as T
|
| 16 |
|
| 17 |
csv.field_size_limit(10 ** 9)
|
| 18 |
DATA = "/path/to/TURKIC_OCR_DATA"
|
|
@@ -70,7 +70,7 @@ def _open_original(job):
|
|
| 70 |
orient = None
|
| 71 |
try:
|
| 72 |
orient = im.getexif().get(0x0112)
|
| 73 |
-
except Exception:
|
| 74 |
orient = "unreadable"
|
| 75 |
im.load()
|
| 76 |
return im, src_sha, orient
|
|
@@ -121,7 +121,7 @@ def work(job):
|
|
| 121 |
"n_target_lines": len(kept), "target_chars": len(target), "over_cap": len(tgt_ids) > T.TARGET_CAP,
|
| 122 |
"counts": cnt, "roundtrip": rt, "roundtrip_ok": all(rt.values())}
|
| 123 |
return rec
|
| 124 |
-
except Exception as e:
|
| 125 |
import traceback
|
| 126 |
return {"id": job["id"], "set": job["set"], "error": repr(e)[:300], "trace": traceback.format_exc()[-1200:]}
|
| 127 |
|
|
|
|
| 12 |
|
| 13 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 14 |
sys.path.insert(0, HERE)
|
| 15 |
+
import om_text as T
|
| 16 |
|
| 17 |
csv.field_size_limit(10 ** 9)
|
| 18 |
DATA = "/path/to/TURKIC_OCR_DATA"
|
|
|
|
| 70 |
orient = None
|
| 71 |
try:
|
| 72 |
orient = im.getexif().get(0x0112)
|
| 73 |
+
except Exception:
|
| 74 |
orient = "unreadable"
|
| 75 |
im.load()
|
| 76 |
return im, src_sha, orient
|
|
|
|
| 121 |
"n_target_lines": len(kept), "target_chars": len(target), "over_cap": len(tgt_ids) > T.TARGET_CAP,
|
| 122 |
"counts": cnt, "roundtrip": rt, "roundtrip_ok": all(rt.values())}
|
| 123 |
return rec
|
| 124 |
+
except Exception as e:
|
| 125 |
import traceback
|
| 126 |
return {"id": job["id"], "set": job["set"], "error": repr(e)[:300], "trace": traceback.format_exc()[-1200:]}
|
| 127 |
|
scripts/r5_loopguard/om_common.py
CHANGED
|
@@ -9,10 +9,10 @@ HERE = os.path.dirname(os.path.abspath(__file__))
|
|
| 9 |
if HERE not in sys.path:
|
| 10 |
sys.path.insert(0, HERE)
|
| 11 |
|
| 12 |
-
import torch
|
| 13 |
|
| 14 |
-
import om_text as T
|
| 15 |
-
import vlm_common as vc
|
| 16 |
|
| 17 |
SHORT = "paddleocr_vl_1_6"
|
| 18 |
CODE = "/path/to/TURKIC_OCR_CODE"
|
|
|
|
| 9 |
if HERE not in sys.path:
|
| 10 |
sys.path.insert(0, HERE)
|
| 11 |
|
| 12 |
+
import torch
|
| 13 |
|
| 14 |
+
import om_text as T
|
| 15 |
+
import vlm_common as vc
|
| 16 |
|
| 17 |
SHORT = "paddleocr_vl_1_6"
|
| 18 |
CODE = "/path/to/TURKIC_OCR_CODE"
|
scripts/r5_loopguard/om_eval_pages.py
CHANGED
|
@@ -9,12 +9,12 @@ from datetime import datetime, timezone
|
|
| 9 |
|
| 10 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 11 |
sys.path.insert(0, HERE)
|
| 12 |
-
import om_common as C
|
| 13 |
-
import om_text as T
|
| 14 |
|
| 15 |
-
import torch
|
| 16 |
-
import transformers
|
| 17 |
-
from PIL import Image
|
| 18 |
|
| 19 |
vc = C.vc
|
| 20 |
csv.field_size_limit(10 ** 9)
|
|
@@ -202,14 +202,14 @@ for s in sets:
|
|
| 202 |
single = False
|
| 203 |
try:
|
| 204 |
recs = gen(imgs)
|
| 205 |
-
except Exception as ex:
|
| 206 |
say("batch failed %s; one at a time (batch composition changes: byte identity with A0 not expected here)" % repr(ex)[:150])
|
| 207 |
single = True
|
| 208 |
recs = []
|
| 209 |
for im in imgs:
|
| 210 |
try:
|
| 211 |
recs += gen([im])
|
| 212 |
-
except Exception as ex2:
|
| 213 |
recs.append({"raw": "", "n_new": 0, "hit_cap": False, "n_visual": None, "error": repr(ex2)[:200]})
|
| 214 |
dt = time.time() - t1
|
| 215 |
for r, im, x in zip(bb, imgs, recs):
|
|
|
|
| 9 |
|
| 10 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 11 |
sys.path.insert(0, HERE)
|
| 12 |
+
import om_common as C
|
| 13 |
+
import om_text as T
|
| 14 |
|
| 15 |
+
import torch
|
| 16 |
+
import transformers
|
| 17 |
+
from PIL import Image
|
| 18 |
|
| 19 |
vc = C.vc
|
| 20 |
csv.field_size_limit(10 ** 9)
|
|
|
|
| 202 |
single = False
|
| 203 |
try:
|
| 204 |
recs = gen(imgs)
|
| 205 |
+
except Exception as ex:
|
| 206 |
say("batch failed %s; one at a time (batch composition changes: byte identity with A0 not expected here)" % repr(ex)[:150])
|
| 207 |
single = True
|
| 208 |
recs = []
|
| 209 |
for im in imgs:
|
| 210 |
try:
|
| 211 |
recs += gen([im])
|
| 212 |
+
except Exception as ex2:
|
| 213 |
recs.append({"raw": "", "n_new": 0, "hit_cap": False, "n_visual": None, "error": repr(ex2)[:200]})
|
| 214 |
dt = time.time() - t1
|
| 215 |
for r, im, x in zip(bb, imgs, recs):
|
scripts/r5_loopguard/om_guard.py
CHANGED
|
@@ -255,7 +255,6 @@ def selftest(a):
|
|
| 255 |
t0 = time.time()
|
| 256 |
rep = {"design": DESIGN_ID, "started_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "checks": {}, "facts": {}}
|
| 257 |
C = rep["checks"]
|
| 258 |
-
# --- the installed transformers has what the arms use
|
| 259 |
rep["facts"]["transformers"] = transformers.__version__
|
| 260 |
rep["facts"]["torch"] = torch.__version__
|
| 261 |
sig = inspect.signature(GenerationMixin.generate).parameters
|
|
@@ -273,13 +272,11 @@ def selftest(a):
|
|
| 273 |
rep["facts"]["vocab_for_tests"] = vocab
|
| 274 |
nl_like = [i for i in range(len(tok)) if i != NL_ID and "\n" in tok.decode([i], skip_special_tokens=False, clean_up_tokenization_spaces=False)]
|
| 275 |
rep["facts"]["other_tokens_whose_text_contains_a_newline"] = {"count": len(nl_like), "first_ids": nl_like[:20]}
|
| 276 |
-
# --- LogitsProcessorList calls the guard (2-argument signature) and leaves scores alone when nothing fires
|
| 277 |
g = LineLoopGuard(3, 1, ids)
|
| 278 |
sc = torch.zeros((1, vocab))
|
| 279 |
out = LogitsProcessorList([g])(torch.zeros((1, 3), dtype=torch.long), sc)
|
| 280 |
C["processor_list_calls_guard"] = out is sc and g.calls == 1
|
| 281 |
|
| 282 |
-
# --- synthetic rows
|
| 283 |
syn = {}
|
| 284 |
A, B_, Cc, D, E = 1000, 1001, 1002, 1003, 1004
|
| 285 |
base_unit = [500, 501, 502, 503, 504, 505, 506, 507]
|
|
@@ -330,7 +327,6 @@ def selftest(a):
|
|
| 330 |
C["synthetic_equal_to_design_triggers"] = all(eq)
|
| 331 |
rep["synthetic"] = syn
|
| 332 |
|
| 333 |
-
# --- enforced mode: masks after a fire, location tokens untouched, then newline/end, then free; batch rows independent
|
| 334 |
prompt = 4
|
| 335 |
unit = [700, 701, 702]
|
| 336 |
row0 = [A] + unit * 12 # fires at its last token
|
|
@@ -406,7 +402,6 @@ def selftest(a):
|
|
| 406 |
C["clean_ids_identity_without_events"] = clean_ids(gen, [], end_ids=ids["end_ids"]) == gen
|
| 407 |
rep["clean_example"] = {"events": st.events, "in_len": len(gen), "out_len": len(cl)}
|
| 408 |
|
| 409 |
-
# --- every reference target (train + val pages) through the guard: no event, no score change
|
| 410 |
ref = {}
|
| 411 |
rows_all = []
|
| 412 |
for s in ("school_train", "gen_train", "school_val", "gen_val"):
|
|
@@ -429,7 +424,6 @@ def selftest(a):
|
|
| 429 |
C["references_no_fire_no_score_change"] = all(v["pages_fired"] == 0 and v["calls_with_changed_scores"] == 0
|
| 430 |
and v["pages_fired_design_triggers"] == 0 for v in ref.values())
|
| 431 |
|
| 432 |
-
# --- stored validation outputs (re-tokenised, as the design's check): observe mode fires on the predicted pages
|
| 433 |
from tokenizers import Tokenizer
|
| 434 |
fr = json.load(open(a.final_rule, encoding="utf-8"))
|
| 435 |
tk = Tokenizer.from_file(os.path.join(a.tokenizer_dir, "tokenizer.json"))
|
|
@@ -456,7 +450,6 @@ def selftest(a):
|
|
| 456 |
and changed == 0)
|
| 457 |
rep["stored_outputs"] = out_pages
|
| 458 |
|
| 459 |
-
# --- A1 sanity: NoRepeatNGramLogitsProcessor(20) bans the continuation of a repeated 20-gram, nothing on a fresh row
|
| 460 |
nr = NoRepeatNGramLogitsProcessor(NGRAM)
|
| 461 |
unit5 = [800, 801, 802, 803, 804]
|
| 462 |
row = torch.tensor([[0] * 5 + unit5 * 5], dtype=torch.long) # 25 generated tokens, period 5
|
|
|
|
| 255 |
t0 = time.time()
|
| 256 |
rep = {"design": DESIGN_ID, "started_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "checks": {}, "facts": {}}
|
| 257 |
C = rep["checks"]
|
|
|
|
| 258 |
rep["facts"]["transformers"] = transformers.__version__
|
| 259 |
rep["facts"]["torch"] = torch.__version__
|
| 260 |
sig = inspect.signature(GenerationMixin.generate).parameters
|
|
|
|
| 272 |
rep["facts"]["vocab_for_tests"] = vocab
|
| 273 |
nl_like = [i for i in range(len(tok)) if i != NL_ID and "\n" in tok.decode([i], skip_special_tokens=False, clean_up_tokenization_spaces=False)]
|
| 274 |
rep["facts"]["other_tokens_whose_text_contains_a_newline"] = {"count": len(nl_like), "first_ids": nl_like[:20]}
|
|
|
|
| 275 |
g = LineLoopGuard(3, 1, ids)
|
| 276 |
sc = torch.zeros((1, vocab))
|
| 277 |
out = LogitsProcessorList([g])(torch.zeros((1, 3), dtype=torch.long), sc)
|
| 278 |
C["processor_list_calls_guard"] = out is sc and g.calls == 1
|
| 279 |
|
|
|
|
| 280 |
syn = {}
|
| 281 |
A, B_, Cc, D, E = 1000, 1001, 1002, 1003, 1004
|
| 282 |
base_unit = [500, 501, 502, 503, 504, 505, 506, 507]
|
|
|
|
| 327 |
C["synthetic_equal_to_design_triggers"] = all(eq)
|
| 328 |
rep["synthetic"] = syn
|
| 329 |
|
|
|
|
| 330 |
prompt = 4
|
| 331 |
unit = [700, 701, 702]
|
| 332 |
row0 = [A] + unit * 12 # fires at its last token
|
|
|
|
| 402 |
C["clean_ids_identity_without_events"] = clean_ids(gen, [], end_ids=ids["end_ids"]) == gen
|
| 403 |
rep["clean_example"] = {"events": st.events, "in_len": len(gen), "out_len": len(cl)}
|
| 404 |
|
|
|
|
| 405 |
ref = {}
|
| 406 |
rows_all = []
|
| 407 |
for s in ("school_train", "gen_train", "school_val", "gen_val"):
|
|
|
|
| 424 |
C["references_no_fire_no_score_change"] = all(v["pages_fired"] == 0 and v["calls_with_changed_scores"] == 0
|
| 425 |
and v["pages_fired_design_triggers"] == 0 for v in ref.values())
|
| 426 |
|
|
|
|
| 427 |
from tokenizers import Tokenizer
|
| 428 |
fr = json.load(open(a.final_rule, encoding="utf-8"))
|
| 429 |
tk = Tokenizer.from_file(os.path.join(a.tokenizer_dir, "tokenizer.json"))
|
|
|
|
| 450 |
and changed == 0)
|
| 451 |
rep["stored_outputs"] = out_pages
|
| 452 |
|
|
|
|
| 453 |
nr = NoRepeatNGramLogitsProcessor(NGRAM)
|
| 454 |
unit5 = [800, 801, 802, 803, 804]
|
| 455 |
row = torch.tensor([[0] * 5 + unit5 * 5], dtype=torch.long) # 25 generated tokens, period 5
|
scripts/r5_loopguard/om_lg_select.py
CHANGED
|
@@ -7,7 +7,7 @@ import time
|
|
| 7 |
|
| 8 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 9 |
sys.path.insert(0, HERE)
|
| 10 |
-
import om_text as T
|
| 11 |
|
| 12 |
OFFICIAL_ROOT = os.path.dirname(T.OFFICIAL_UNSEAL)
|
| 13 |
VAL = {"gen_val": 300, "school_val": 150}
|
|
@@ -129,7 +129,7 @@ def select(a):
|
|
| 129 |
try:
|
| 130 |
sel["diagnostics_file"] = os.path.join(root, "diagnostics_val.json")
|
| 131 |
json.dump(diagnostics(root, a.a0, a.stored), open(sel["diagnostics_file"], "w"), indent=1)
|
| 132 |
-
except Exception as e:
|
| 133 |
sel["diagnostics_error"] = repr(e)[:200]
|
| 134 |
p = os.path.join(root, "selection.json")
|
| 135 |
json.dump(sel, open(p, "w"), indent=1)
|
|
|
|
| 7 |
|
| 8 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 9 |
sys.path.insert(0, HERE)
|
| 10 |
+
import om_text as T
|
| 11 |
|
| 12 |
OFFICIAL_ROOT = os.path.dirname(T.OFFICIAL_UNSEAL)
|
| 13 |
VAL = {"gen_val": 300, "school_val": 150}
|
|
|
|
| 129 |
try:
|
| 130 |
sel["diagnostics_file"] = os.path.join(root, "diagnostics_val.json")
|
| 131 |
json.dump(diagnostics(root, a.a0, a.stored), open(sel["diagnostics_file"], "w"), indent=1)
|
| 132 |
+
except Exception as e:
|
| 133 |
sel["diagnostics_error"] = repr(e)[:200]
|
| 134 |
p = os.path.join(root, "selection.json")
|
| 135 |
json.dump(sel, open(p, "w"), indent=1)
|
scripts/r5_loopguard/om_score.py
CHANGED
|
@@ -10,7 +10,7 @@ import numpy as np
|
|
| 10 |
|
| 11 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
sys.path.insert(0, HERE)
|
| 13 |
-
import om_text as T
|
| 14 |
|
| 15 |
DATA = "/path/to/TURKIC_OCR_DATA"
|
| 16 |
CODE = "/path/to/TURKIC_OCR_CODE"
|
|
|
|
| 10 |
|
| 11 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
sys.path.insert(0, HERE)
|
| 13 |
+
import om_text as T
|
| 14 |
|
| 15 |
DATA = "/path/to/TURKIC_OCR_DATA"
|
| 16 |
CODE = "/path/to/TURKIC_OCR_CODE"
|
scripts/r5_onemodel/om_baseline.py
CHANGED
|
@@ -8,11 +8,11 @@ import unicodedata
|
|
| 8 |
|
| 9 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 10 |
sys.path.insert(0, HERE)
|
| 11 |
-
import om_common as C
|
| 12 |
-
import om_text as T
|
| 13 |
|
| 14 |
-
import torch
|
| 15 |
-
from PIL import Image
|
| 16 |
|
| 17 |
vc = C.vc
|
| 18 |
csv.field_size_limit(10 ** 9)
|
|
|
|
| 8 |
|
| 9 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 10 |
sys.path.insert(0, HERE)
|
| 11 |
+
import om_common as C
|
| 12 |
+
import om_text as T
|
| 13 |
|
| 14 |
+
import torch
|
| 15 |
+
from PIL import Image
|
| 16 |
|
| 17 |
vc = C.vc
|
| 18 |
csv.field_size_limit(10 ** 9)
|
scripts/r5_onemodel/om_build_pages.py
CHANGED
|
@@ -12,7 +12,7 @@ import zipfile
|
|
| 12 |
|
| 13 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 14 |
sys.path.insert(0, HERE)
|
| 15 |
-
import om_text as T
|
| 16 |
|
| 17 |
csv.field_size_limit(10 ** 9)
|
| 18 |
DATA = "/path/to/TURKIC_OCR_DATA"
|
|
@@ -70,7 +70,7 @@ def _open_original(job):
|
|
| 70 |
orient = None
|
| 71 |
try:
|
| 72 |
orient = im.getexif().get(0x0112)
|
| 73 |
-
except Exception:
|
| 74 |
orient = "unreadable"
|
| 75 |
im.load()
|
| 76 |
return im, src_sha, orient
|
|
@@ -121,7 +121,7 @@ def work(job):
|
|
| 121 |
"n_target_lines": len(kept), "target_chars": len(target), "over_cap": len(tgt_ids) > T.TARGET_CAP,
|
| 122 |
"counts": cnt, "roundtrip": rt, "roundtrip_ok": all(rt.values())}
|
| 123 |
return rec
|
| 124 |
-
except Exception as e:
|
| 125 |
import traceback
|
| 126 |
return {"id": job["id"], "set": job["set"], "error": repr(e)[:300], "trace": traceback.format_exc()[-1200:]}
|
| 127 |
|
|
|
|
| 12 |
|
| 13 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 14 |
sys.path.insert(0, HERE)
|
| 15 |
+
import om_text as T
|
| 16 |
|
| 17 |
csv.field_size_limit(10 ** 9)
|
| 18 |
DATA = "/path/to/TURKIC_OCR_DATA"
|
|
|
|
| 70 |
orient = None
|
| 71 |
try:
|
| 72 |
orient = im.getexif().get(0x0112)
|
| 73 |
+
except Exception:
|
| 74 |
orient = "unreadable"
|
| 75 |
im.load()
|
| 76 |
return im, src_sha, orient
|
|
|
|
| 121 |
"n_target_lines": len(kept), "target_chars": len(target), "over_cap": len(tgt_ids) > T.TARGET_CAP,
|
| 122 |
"counts": cnt, "roundtrip": rt, "roundtrip_ok": all(rt.values())}
|
| 123 |
return rec
|
| 124 |
+
except Exception as e:
|
| 125 |
import traceback
|
| 126 |
return {"id": job["id"], "set": job["set"], "error": repr(e)[:300], "trace": traceback.format_exc()[-1200:]}
|
| 127 |
|
scripts/r5_onemodel/om_common.py
CHANGED
|
@@ -9,10 +9,10 @@ HERE = os.path.dirname(os.path.abspath(__file__))
|
|
| 9 |
if HERE not in sys.path:
|
| 10 |
sys.path.insert(0, HERE)
|
| 11 |
|
| 12 |
-
import torch
|
| 13 |
|
| 14 |
-
import om_text as T
|
| 15 |
-
import vlm_common as vc
|
| 16 |
|
| 17 |
SHORT = "paddleocr_vl_1_6"
|
| 18 |
CODE = "/path/to/TURKIC_OCR_CODE"
|
|
|
|
| 9 |
if HERE not in sys.path:
|
| 10 |
sys.path.insert(0, HERE)
|
| 11 |
|
| 12 |
+
import torch
|
| 13 |
|
| 14 |
+
import om_text as T
|
| 15 |
+
import vlm_common as vc
|
| 16 |
|
| 17 |
SHORT = "paddleocr_vl_1_6"
|
| 18 |
CODE = "/path/to/TURKIC_OCR_CODE"
|
scripts/r5_onemodel/om_eval_pages.py
CHANGED
|
@@ -8,12 +8,12 @@ from datetime import datetime, timezone
|
|
| 8 |
|
| 9 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 10 |
sys.path.insert(0, HERE)
|
| 11 |
-
import om_common as C
|
| 12 |
-
import om_text as T
|
| 13 |
|
| 14 |
-
import torch
|
| 15 |
-
import transformers
|
| 16 |
-
from PIL import Image
|
| 17 |
|
| 18 |
vc = C.vc
|
| 19 |
csv.field_size_limit(10 ** 9)
|
|
@@ -152,13 +152,13 @@ for s in sets:
|
|
| 152 |
t1 = time.time()
|
| 153 |
try:
|
| 154 |
recs = C.generate_pages(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev)
|
| 155 |
-
except Exception as ex:
|
| 156 |
say("batch failed %s; one at a time" % repr(ex)[:150])
|
| 157 |
recs = []
|
| 158 |
for im in imgs:
|
| 159 |
try:
|
| 160 |
recs += C.generate_pages(model, proc, tok, [im], max_new, tmpl_kw, gc, stop_set, dev)
|
| 161 |
-
except Exception as ex2:
|
| 162 |
recs.append({"raw": "", "n_new": 0, "hit_cap": False, "n_visual": None, "error": repr(ex2)[:200]})
|
| 163 |
dt = time.time() - t1
|
| 164 |
for r, im, x in zip(bb, imgs, recs):
|
|
|
|
| 8 |
|
| 9 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 10 |
sys.path.insert(0, HERE)
|
| 11 |
+
import om_common as C
|
| 12 |
+
import om_text as T
|
| 13 |
|
| 14 |
+
import torch
|
| 15 |
+
import transformers
|
| 16 |
+
from PIL import Image
|
| 17 |
|
| 18 |
vc = C.vc
|
| 19 |
csv.field_size_limit(10 ** 9)
|
|
|
|
| 152 |
t1 = time.time()
|
| 153 |
try:
|
| 154 |
recs = C.generate_pages(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev)
|
| 155 |
+
except Exception as ex:
|
| 156 |
say("batch failed %s; one at a time" % repr(ex)[:150])
|
| 157 |
recs = []
|
| 158 |
for im in imgs:
|
| 159 |
try:
|
| 160 |
recs += C.generate_pages(model, proc, tok, [im], max_new, tmpl_kw, gc, stop_set, dev)
|
| 161 |
+
except Exception as ex2:
|
| 162 |
recs.append({"raw": "", "n_new": 0, "hit_cap": False, "n_visual": None, "error": repr(ex2)[:200]})
|
| 163 |
dt = time.time() - t1
|
| 164 |
for r, im, x in zip(bb, imgs, recs):
|
scripts/r5_onemodel/om_probe.py
CHANGED
|
@@ -7,12 +7,12 @@ import time
|
|
| 7 |
|
| 8 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 9 |
sys.path.insert(0, HERE)
|
| 10 |
-
import om_common as C
|
| 11 |
-
import om_text as T
|
| 12 |
|
| 13 |
-
import torch
|
| 14 |
-
import transformers
|
| 15 |
-
from PIL import Image
|
| 16 |
|
| 17 |
vc = C.vc
|
| 18 |
ap = argparse.ArgumentParser()
|
|
@@ -76,7 +76,7 @@ try:
|
|
| 76 |
from transformers import image_utils
|
| 77 |
src = inspect.getsource(image_utils.load_image)
|
| 78 |
rep["load_image_mentions_exif_transpose"] = "exif_transpose" in src
|
| 79 |
-
except Exception as e:
|
| 80 |
rep["load_image_source"] = repr(e)[:200]
|
| 81 |
|
| 82 |
# timing: one full page sample vs one crop sample, forward + backward, bf16, gradient checkpointing
|
|
|
|
| 7 |
|
| 8 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 9 |
sys.path.insert(0, HERE)
|
| 10 |
+
import om_common as C
|
| 11 |
+
import om_text as T
|
| 12 |
|
| 13 |
+
import torch
|
| 14 |
+
import transformers
|
| 15 |
+
from PIL import Image
|
| 16 |
|
| 17 |
vc = C.vc
|
| 18 |
ap = argparse.ArgumentParser()
|
|
|
|
| 76 |
from transformers import image_utils
|
| 77 |
src = inspect.getsource(image_utils.load_image)
|
| 78 |
rep["load_image_mentions_exif_transpose"] = "exif_transpose" in src
|
| 79 |
+
except Exception as e:
|
| 80 |
rep["load_image_source"] = repr(e)[:200]
|
| 81 |
|
| 82 |
# timing: one full page sample vs one crop sample, forward + backward, bf16, gradient checkpointing
|
scripts/r5_onemodel/om_score.py
CHANGED
|
@@ -10,7 +10,7 @@ import numpy as np
|
|
| 10 |
|
| 11 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
sys.path.insert(0, HERE)
|
| 13 |
-
import om_text as T
|
| 14 |
|
| 15 |
DATA = "/path/to/TURKIC_OCR_DATA"
|
| 16 |
CODE = "/path/to/TURKIC_OCR_CODE"
|
|
|
|
| 10 |
|
| 11 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
sys.path.insert(0, HERE)
|
| 13 |
+
import om_text as T
|
| 14 |
|
| 15 |
DATA = "/path/to/TURKIC_OCR_DATA"
|
| 16 |
CODE = "/path/to/TURKIC_OCR_CODE"
|
scripts/r5_onemodel/om_smoke_check.py
CHANGED
|
@@ -7,7 +7,7 @@ import sys
|
|
| 7 |
|
| 8 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 9 |
sys.path.insert(0, HERE)
|
| 10 |
-
import om_text as T
|
| 11 |
|
| 12 |
DATA = "/path/to/TURKIC_OCR_DATA"
|
| 13 |
PAGECHK = DATA + "/outputs/r5/b1_page_check"
|
|
@@ -91,7 +91,6 @@ def main():
|
|
| 91 |
it["spotting_generation_parses"] = {"by_model": gen_items, "passed": parse_ok,
|
| 92 |
"rule": "base PaddleOCR-VL 1.6 output on the generated val pages parses into lines with boxes; leader and smoke-trained outputs parse without error"}
|
| 93 |
|
| 94 |
-
# 5 baseline reproduces the PAGECHK detector + leader readings
|
| 95 |
ref = {}
|
| 96 |
for p in glob.glob(PAGECHK + "/*_detB1_c*.jsonl"):
|
| 97 |
for r in jl(p):
|
|
|
|
| 7 |
|
| 8 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 9 |
sys.path.insert(0, HERE)
|
| 10 |
+
import om_text as T
|
| 11 |
|
| 12 |
DATA = "/path/to/TURKIC_OCR_DATA"
|
| 13 |
PAGECHK = DATA + "/outputs/r5/b1_page_check"
|
|
|
|
| 91 |
it["spotting_generation_parses"] = {"by_model": gen_items, "passed": parse_ok,
|
| 92 |
"rule": "base PaddleOCR-VL 1.6 output on the generated val pages parses into lines with boxes; leader and smoke-trained outputs parse without error"}
|
| 93 |
|
|
|
|
| 94 |
ref = {}
|
| 95 |
for p in glob.glob(PAGECHK + "/*_detB1_c*.jsonl"):
|
| 96 |
for r in jl(p):
|
scripts/r5_onemodel/om_train.py
CHANGED
|
@@ -11,12 +11,12 @@ from datetime import datetime, timezone
|
|
| 11 |
|
| 12 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 13 |
sys.path.insert(0, HERE)
|
| 14 |
-
import om_common as C
|
| 15 |
-
import om_text as T
|
| 16 |
|
| 17 |
-
import torch
|
| 18 |
-
import transformers
|
| 19 |
-
from PIL import Image
|
| 20 |
|
| 21 |
vc = C.vc
|
| 22 |
csv.field_size_limit(10 ** 9)
|
|
@@ -68,7 +68,7 @@ STOP = {"flag": False, "why": ""}
|
|
| 68 |
T_PROC = time.time()
|
| 69 |
|
| 70 |
|
| 71 |
-
def _sig(signum, frame):
|
| 72 |
STOP["flag"] = True
|
| 73 |
STOP["why"] = "signal %d" % signum
|
| 74 |
|
|
@@ -256,11 +256,11 @@ def _wi(_):
|
|
| 256 |
ctypes.CDLL("libc.so.6", use_errno=True).prctl(1, signal.SIGKILL, 0, 0, 0)
|
| 257 |
if os.getppid() != PARENT:
|
| 258 |
os._exit(0)
|
| 259 |
-
except Exception:
|
| 260 |
pass
|
| 261 |
try:
|
| 262 |
os.nice(10)
|
| 263 |
-
except Exception:
|
| 264 |
pass
|
| 265 |
torch.set_num_threads(1)
|
| 266 |
|
|
|
|
| 11 |
|
| 12 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 13 |
sys.path.insert(0, HERE)
|
| 14 |
+
import om_common as C
|
| 15 |
+
import om_text as T
|
| 16 |
|
| 17 |
+
import torch
|
| 18 |
+
import transformers
|
| 19 |
+
from PIL import Image
|
| 20 |
|
| 21 |
vc = C.vc
|
| 22 |
csv.field_size_limit(10 ** 9)
|
|
|
|
| 68 |
T_PROC = time.time()
|
| 69 |
|
| 70 |
|
| 71 |
+
def _sig(signum, frame):
|
| 72 |
STOP["flag"] = True
|
| 73 |
STOP["why"] = "signal %d" % signum
|
| 74 |
|
|
|
|
| 256 |
ctypes.CDLL("libc.so.6", use_errno=True).prctl(1, signal.SIGKILL, 0, 0, 0)
|
| 257 |
if os.getppid() != PARENT:
|
| 258 |
os._exit(0)
|
| 259 |
+
except Exception:
|
| 260 |
pass
|
| 261 |
try:
|
| 262 |
os.nice(10)
|
| 263 |
+
except Exception:
|
| 264 |
pass
|
| 265 |
torch.set_num_threads(1)
|
| 266 |
|
scripts/r5_ref/ref_check_tasks.py
CHANGED
|
@@ -3,7 +3,7 @@ import os
|
|
| 3 |
import sys
|
| 4 |
|
| 5 |
sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src")
|
| 6 |
-
from linedet import driver
|
| 7 |
|
| 8 |
spec = json.load(open(sys.argv[1]))
|
| 9 |
names = {t["name"] for t in spec["tasks"]}
|
|
|
|
| 3 |
import sys
|
| 4 |
|
| 5 |
sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src")
|
| 6 |
+
from linedet import driver
|
| 7 |
|
| 8 |
spec = json.load(open(sys.argv[1]))
|
| 9 |
names = {t["name"] for t in spec["tasks"]}
|
scripts/r5_ref/ref_flor_predict.py
CHANGED
|
@@ -10,7 +10,7 @@ import numpy as np
|
|
| 10 |
|
| 11 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
sys.path.insert(0, HERE)
|
| 13 |
-
import ref_common as rc
|
| 14 |
|
| 15 |
INPUT_SIZE = (1024, 128, 1)
|
| 16 |
MAX_TEXT = 128
|
|
|
|
| 10 |
|
| 11 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
sys.path.insert(0, HERE)
|
| 13 |
+
import ref_common as rc
|
| 14 |
|
| 15 |
INPUT_SIZE = (1024, 128, 1)
|
| 16 |
MAX_TEXT = 128
|
scripts/r5_ref/ref_flor_train.py
CHANGED
|
@@ -13,7 +13,7 @@ import numpy as np
|
|
| 13 |
|
| 14 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 15 |
sys.path.insert(0, HERE)
|
| 16 |
-
import ref_common as rc
|
| 17 |
|
| 18 |
INPUT_SIZE = (1024, 128, 1)
|
| 19 |
MAX_TEXT = 128
|
|
@@ -94,7 +94,6 @@ def main():
|
|
| 94 |
log.write(s + "\n")
|
| 95 |
log.flush()
|
| 96 |
|
| 97 |
-
# ---- data (text only here; images are read by the worker processes)
|
| 98 |
MIXRUN = a.run == "iii"
|
| 99 |
if MIXRUN:
|
| 100 |
trn, val = rc.read_manifest(a.mix_list), []
|
|
@@ -125,7 +124,6 @@ def main():
|
|
| 125 |
chars = json.load(open(os.path.join(a.refdata, "charset_%s.json" % a.run), encoding="utf-8"))["chars"]
|
| 126 |
say("run", a.run, "train", len(trn), "val", len(val), "charset", len(chars))
|
| 127 |
|
| 128 |
-
# ---- worker pool before TensorFlow is imported (fork after CUDA initialisation is unsafe)
|
| 129 |
pool = mp.get_context("fork").Pool(a.workers, initializer=_winit, initargs=(rc.HTRFLOR_SRC, pool_path, 20261121))
|
| 130 |
|
| 131 |
os.environ.setdefault("TF_FORCE_GPU_ALLOW_GROWTH", "true")
|
|
@@ -144,7 +142,7 @@ def main():
|
|
| 144 |
from network.model import HTRModel # pinned
|
| 145 |
from data.generator import Tokenizer # pinned
|
| 146 |
from data import preproc as pp # pinned (normalization)
|
| 147 |
-
from tensorflow.keras import backend as K
|
| 148 |
from itertools import groupby
|
| 149 |
|
| 150 |
class KzTokenizer(Tokenizer):
|
|
@@ -170,7 +168,6 @@ def main():
|
|
| 170 |
y = [np.pad(v, (0, tok.maxlen - len(v))) for v in y]
|
| 171 |
return np.asarray(y, dtype=np.int16)
|
| 172 |
|
| 173 |
-
# ---- batch streams
|
| 174 |
if MIXRUN:
|
| 175 |
steps = (len(trn) // a.batch) // 4 if not a.steps_per_epoch else a.steps_per_epoch # quarter of the run per Keras epoch
|
| 176 |
else:
|
|
@@ -219,7 +216,6 @@ def main():
|
|
| 219 |
f, sl = pend.popleft()
|
| 220 |
yield pp.normalization(f.get()), encode_batch([val[i] for i in sl])
|
| 221 |
|
| 222 |
-
# ---- model (pinned)
|
| 223 |
model = HTRModel(architecture="flor", input_size=INPUT_SIZE, vocab_size=tok.vocab_size, beam_width=10,
|
| 224 |
stop_tolerance=a.stop_patience, reduce_tolerance=a.reduce_patience)
|
| 225 |
model.compile(learning_rate=0.001)
|
|
@@ -238,7 +234,6 @@ def main():
|
|
| 238 |
rl = [c for c in cbs if c.__class__.__name__ == "ReduceLROnPlateau"][0]
|
| 239 |
mc = [c for c in cbs if c.__class__.__name__ == "ModelCheckpoint"][0]
|
| 240 |
|
| 241 |
-
# ---- resume state
|
| 242 |
rdir = os.path.join(a.out, "resume")
|
| 243 |
os.makedirs(rdir, exist_ok=True)
|
| 244 |
state_path = os.path.join(rdir, "state.json")
|
|
|
|
| 13 |
|
| 14 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 15 |
sys.path.insert(0, HERE)
|
| 16 |
+
import ref_common as rc
|
| 17 |
|
| 18 |
INPUT_SIZE = (1024, 128, 1)
|
| 19 |
MAX_TEXT = 128
|
|
|
|
| 94 |
log.write(s + "\n")
|
| 95 |
log.flush()
|
| 96 |
|
|
|
|
| 97 |
MIXRUN = a.run == "iii"
|
| 98 |
if MIXRUN:
|
| 99 |
trn, val = rc.read_manifest(a.mix_list), []
|
|
|
|
| 124 |
chars = json.load(open(os.path.join(a.refdata, "charset_%s.json" % a.run), encoding="utf-8"))["chars"]
|
| 125 |
say("run", a.run, "train", len(trn), "val", len(val), "charset", len(chars))
|
| 126 |
|
|
|
|
| 127 |
pool = mp.get_context("fork").Pool(a.workers, initializer=_winit, initargs=(rc.HTRFLOR_SRC, pool_path, 20261121))
|
| 128 |
|
| 129 |
os.environ.setdefault("TF_FORCE_GPU_ALLOW_GROWTH", "true")
|
|
|
|
| 142 |
from network.model import HTRModel # pinned
|
| 143 |
from data.generator import Tokenizer # pinned
|
| 144 |
from data import preproc as pp # pinned (normalization)
|
| 145 |
+
from tensorflow.keras import backend as K
|
| 146 |
from itertools import groupby
|
| 147 |
|
| 148 |
class KzTokenizer(Tokenizer):
|
|
|
|
| 168 |
y = [np.pad(v, (0, tok.maxlen - len(v))) for v in y]
|
| 169 |
return np.asarray(y, dtype=np.int16)
|
| 170 |
|
|
|
|
| 171 |
if MIXRUN:
|
| 172 |
steps = (len(trn) // a.batch) // 4 if not a.steps_per_epoch else a.steps_per_epoch # quarter of the run per Keras epoch
|
| 173 |
else:
|
|
|
|
| 216 |
f, sl = pend.popleft()
|
| 217 |
yield pp.normalization(f.get()), encode_batch([val[i] for i in sl])
|
| 218 |
|
|
|
|
| 219 |
model = HTRModel(architecture="flor", input_size=INPUT_SIZE, vocab_size=tok.vocab_size, beam_width=10,
|
| 220 |
stop_tolerance=a.stop_patience, reduce_tolerance=a.reduce_patience)
|
| 221 |
model.compile(learning_rate=0.001)
|
|
|
|
| 234 |
rl = [c for c in cbs if c.__class__.__name__ == "ReduceLROnPlateau"][0]
|
| 235 |
mc = [c for c in cbs if c.__class__.__name__ == "ModelCheckpoint"][0]
|
| 236 |
|
|
|
|
| 237 |
rdir = os.path.join(a.out, "resume")
|
| 238 |
os.makedirs(rdir, exist_ok=True)
|
| 239 |
state_path = os.path.join(rdir, "state.json")
|
scripts/r5_ref/ref_make_mix_lists.py
CHANGED
|
@@ -11,7 +11,7 @@ import numpy as np
|
|
| 11 |
|
| 12 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 13 |
sys.path.insert(0, HERE)
|
| 14 |
-
import ref_common as rc
|
| 15 |
|
| 16 |
_WS = re.compile(r"\s+")
|
| 17 |
|
|
|
|
| 11 |
|
| 12 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 13 |
sys.path.insert(0, HERE)
|
| 14 |
+
import ref_common as rc
|
| 15 |
|
| 16 |
_WS = re.compile(r"\s+")
|
| 17 |
|
scripts/r5_ref/ref_paper_metrics.py
CHANGED
|
@@ -5,11 +5,11 @@ import sys
|
|
| 5 |
|
| 6 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 7 |
sys.path.insert(0, HERE)
|
| 8 |
-
import ref_common as rc
|
| 9 |
|
| 10 |
sys.path.insert(0, rc.HTRFLOR_SRC)
|
| 11 |
from data import evaluation as flor_eval # pinned # noqa: E402
|
| 12 |
-
import editdistance
|
| 13 |
|
| 14 |
|
| 15 |
def metrics(refs, hyps):
|
|
|
|
| 5 |
|
| 6 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 7 |
sys.path.insert(0, HERE)
|
| 8 |
+
import ref_common as rc
|
| 9 |
|
| 10 |
sys.path.insert(0, rc.HTRFLOR_SRC)
|
| 11 |
from data import evaluation as flor_eval # pinned # noqa: E402
|
| 12 |
+
import editdistance
|
| 13 |
|
| 14 |
|
| 15 |
def metrics(refs, hyps):
|