Image-to-Text
PaddlePaddle
Persian
paddleocr
ocr
persian
handwriting
printed-text
pp-ocrv6
Reza2kn commited on
Commit
054400d
·
verified ·
1 Parent(s): c82efc9

Add training-kit/prepare_ppocrv6_pilot.py

Browse files
Files changed (1) hide show
  1. training-kit/prepare_ppocrv6_pilot.py +130 -0
training-kit/prepare_ppocrv6_pilot.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Prepare a small Persian PP-OCRv6 recognition pilot on a remote GPU."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import io
8
+ import json
9
+ import unicodedata
10
+ from collections import Counter
11
+ from pathlib import Path
12
+
13
+ import pyarrow.parquet as pq
14
+ from huggingface_hub import HfApi, hf_hub_download
15
+ from PIL import Image
16
+
17
+
18
+ def clean_text(value: str) -> str:
19
+ value = unicodedata.normalize("NFC", value).replace("\t", " ")
20
+ return " ".join(value.split())
21
+
22
+
23
+ def image_bytes(value: object) -> bytes:
24
+ if isinstance(value, dict) and value.get("bytes") is not None:
25
+ return value["bytes"]
26
+ raise ValueError("Expected an embedded Hugging Face image payload")
27
+
28
+
29
+ def read_gt(path: Path) -> list[tuple[Path, str]]:
30
+ rows = []
31
+ for raw in path.read_text(encoding="utf-8").splitlines():
32
+ key, text = raw.split(maxsplit=1)
33
+ rows.append((path.parent / f"{key}.png", clean_text(text)))
34
+ return rows
35
+
36
+
37
+ def first_parquet(repo: str) -> str:
38
+ files = HfApi().list_repo_files(repo, repo_type="dataset")
39
+ candidates = sorted(x for x in files if x.endswith(".parquet") and x.startswith("data/"))
40
+ if not candidates:
41
+ raise RuntimeError(f"No data parquet found in {repo}")
42
+ return candidates[0]
43
+
44
+
45
+ def extract_printed(repo: str, output: Path, train_count: int, eval_count: int) -> tuple[list, list]:
46
+ source = hf_hub_download(
47
+ repo, first_parquet(repo), repo_type="dataset", local_dir=output / "hf"
48
+ )
49
+ table = pq.read_table(source, columns=["image", "label"]).slice(0, train_count + eval_count)
50
+ rows = table.to_pylist()
51
+ if len(rows) < train_count + eval_count:
52
+ raise RuntimeError("Printed pilot shard does not contain enough rows")
53
+
54
+ destination = output / "images" / "printed"
55
+ destination.mkdir(parents=True, exist_ok=True)
56
+ converted = []
57
+ for index, row in enumerate(rows):
58
+ path = destination / f"{index:07d}.jpg"
59
+ with Image.open(io.BytesIO(image_bytes(row["image"]))) as image:
60
+ image.convert("RGB").save(path, "JPEG", quality=95)
61
+ converted.append((path, clean_text(row["label"])))
62
+ return converted[:train_count], converted[train_count:]
63
+
64
+
65
+ def load_hardword_text(repo: str, output: Path) -> list[str]:
66
+ source = hf_hub_download(
67
+ repo, first_parquet(repo), repo_type="dataset", local_dir=output / "hf"
68
+ )
69
+ return [clean_text(x) for x in pq.read_table(source, columns=["sentence"])["sentence"].to_pylist()]
70
+
71
+
72
+ def write_list(path: Path, rows: list[tuple[Path, str]], root: Path) -> None:
73
+ with path.open("w", encoding="utf-8") as handle:
74
+ for image, text in rows:
75
+ handle.write(f"{image.relative_to(root)}\t{text}\n")
76
+
77
+
78
+ def main() -> None:
79
+ parser = argparse.ArgumentParser()
80
+ parser.add_argument("--phtd", type=Path, required=True)
81
+ parser.add_argument("--output", type=Path, required=True)
82
+ parser.add_argument("--printed-train", type=int, default=4000)
83
+ parser.add_argument("--printed-eval", type=int, default=500)
84
+ args = parser.parse_args()
85
+
86
+ args.output.mkdir(parents=True, exist_ok=True)
87
+ handwriting_train = read_gt(args.phtd / "train" / "gt.txt")
88
+ handwriting_eval = read_gt(args.phtd / "val" / "gt.txt")
89
+ printed_train, printed_eval = extract_printed(
90
+ "Reza2kn/persian-printed-ocr-3.5m",
91
+ args.output,
92
+ args.printed_train,
93
+ args.printed_eval,
94
+ )
95
+ hardwords = load_hardword_text("Reza2kn/visualears-hardword-sentences", args.output)
96
+
97
+ train = handwriting_train + printed_train
98
+ evaluation = handwriting_eval + printed_eval
99
+ data_root = args.output.parent
100
+ write_list(args.output / "train_list.txt", train, data_root)
101
+ write_list(args.output / "val_list.txt", evaluation, data_root)
102
+
103
+ frequencies = Counter("".join(text for _, text in train + evaluation) + "".join(hardwords))
104
+ characters = sorted(
105
+ char for char in frequencies
106
+ if char != " " and char.isprintable() and char not in "\r\n\t"
107
+ )
108
+ (args.output / "persian_dict.txt").write_text(
109
+ "".join(f"{char}\n" for char in characters), encoding="utf-8"
110
+ )
111
+ summary = {
112
+ "train_rows": len(train),
113
+ "eval_rows": len(evaluation),
114
+ "handwriting_train": len(handwriting_train),
115
+ "handwriting_eval": len(handwriting_eval),
116
+ "printed_train": len(printed_train),
117
+ "printed_eval": len(printed_eval),
118
+ "hardword_sentences_for_charset": len(hardwords),
119
+ "characters": len(characters),
120
+ "max_train_characters": max(map(lambda row: len(row[1]), train)),
121
+ "max_eval_characters": max(map(lambda row: len(row[1]), evaluation)),
122
+ }
123
+ (args.output / "summary.json").write_text(
124
+ json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
125
+ )
126
+ print(json.dumps(summary, ensure_ascii=False))
127
+
128
+
129
+ if __name__ == "__main__":
130
+ main()