From fe05dbc0b0e065d95c3c637e834581764a10fc4f Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Wed, 22 Jul 2026 01:05:35 +0330 Subject: [PATCH] init --- .gitignore | 10 ++ README.md | 102 +++++++++++++++++ download_dataset.py | 273 ++++++++++++++++++++++++++++++++++++++++++++ find_duplicates.py | 78 +++++++++++++ merge_datasets.py | 209 +++++++++++++++++++++++++++++++++ ocr_dataset.py | 97 ++++++++++++++++ tests/__init__.py | 1 + tests/test_tools.py | 199 ++++++++++++++++++++++++++++++++ verify_labels.py | 158 +++++++++++++++++++++++++ 9 files changed, 1127 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100755 download_dataset.py create mode 100755 find_duplicates.py create mode 100755 merge_datasets.py create mode 100644 ocr_dataset.py create mode 100644 tests/__init__.py create mode 100644 tests/test_tools.py create mode 100755 verify_labels.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2ddffcd --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +.idea/ +.venv/ +__pycache__/ +*.py[cod] +.pytest_cache/ +dist/ +build/ +*.egg-info/ +captcha.jpg +dataset/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..3593e16 --- /dev/null +++ b/README.md @@ -0,0 +1,102 @@ +# Persian number OCR dataset tools + +These dependency-free Python scripts build and manually label an exact-hash-indexed +image dataset. They require Python 3.10 or newer. The verification script also +requires a [Kitty terminal](https://sw.kovidgoyal.net/kitty/) installation. + +## 1. Download the images + +The API is expected to return the raw bytes of one JPEG, PNG, GIF, BMP, or WebP +image per HTTP request. The default target is one million successfully downloaded +images: + +```bash +python download_dataset.py --url 'https://example.com/random-number-image' +``` + +Headers and query parameters can be repeated. Quote URLs containing `{index}`; +the placeholder is replaced with the zero-based image number: + +```bash +python download_dataset.py \ + --url 'https://example.com/captcha?id={index}' \ + --header 'Authorization=Bearer YOUR_TOKEN' \ + --param 'format=png' \ + --workers 16 \ + --count 1000000 +``` + +Output is sharded to avoid putting one million files in one directory: + +```text +dataset/ +├── labels.csv +└── images/ + ├── 000000/ + ├── 000001/ + └── ... +``` + +`labels.csv` always has these columns: + +```text +filename,label,batch_id,verified,hash +``` + +`hash` is the SHA-256 of the exact response bytes. `label` starts empty and +`verified` starts at `0`. The downloader appends and flushes incrementally, so +rerunning the same command resumes toward `--count`. Tune `--workers` and +`--delay` to respect the API's published rate limit. + +## 2. Merge downloads from multiple machines or directories + +Each source can be a dataset directory or its `labels.csv` file. The output must +not already exist: + +```bash +python merge_datasets.py \ + /path/to/download-1/dataset \ + /path/to/download-2/dataset \ + /path/to/download-3/dataset \ + --output combined_dataset +``` + +The merge preserves every label, verification flag, and hash while assigning new +collision-free filenames and batch IDs. Source files are never changed. The +result is first built in a neighboring staging directory and moved into place +only after it completes. Exact duplicates are intentionally retained for review +with `find_duplicates.py`. + +Copying is safest and is the default. If all datasets are on the same filesystem, +`--mode hardlink` makes the merge much faster and uses almost no additional image +storage. Hard-linked source and destination files share the same underlying data. + +## 3. Find exact duplicates + +```bash +python find_duplicates.py \ + --csv combined_dataset/labels.csv \ + --output combined_dataset/duplicates.csv +``` + +This reads stored hashes without reopening the images and writes +`dataset/duplicates.csv`. Every duplicate row points to the first filename with +the same hash. It reports exact byte-for-byte duplicates, not merely similar +images. + +## 4. Verify labels in Kitty + +Run this inside Kitty: + +```bash +python verify_labels.py --csv combined_dataset/labels.csv +``` + +For each unverified image, enter its number. Persian (`۰۱۲۳`), Arabic (`٠١٢٣`), +and ASCII digits are accepted and normalized to ASCII by default. Press `s` or +Enter to skip, or `q`/Ctrl-C to save and quit. Existing verified rows are skipped. +Use `--reverify` to review them and `--start N` to begin after row `N`. + +The verifier builds a complete temporary CSV and atomically replaces the original +when you quit, so the CSV cannot be left half-written. If it is interrupted while +copying or displaying rather than at the prompt, the original CSV remains unchanged. diff --git a/download_dataset.py b/download_dataset.py new file mode 100755 index 0000000..1d5a086 --- /dev/null +++ b/download_dataset.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +"""Download a large, hash-indexed OCR image dataset from an HTTP API.""" + +from __future__ import annotations + +import argparse +import concurrent.futures +import os +import random +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass +from pathlib import Path + +from ocr_dataset import ( + atomic_write, + image_extension, + open_dataset_for_append, + scan_dataset, + sha256_bytes, +) + + +@dataclass(frozen=True) +class DownloadedImage: + index: int + data: bytes + content_type: str + + +class Progress: + def __init__(self, current: int, total: int) -> None: + self.current = current + self.initial = current + self.total = total + self.started = time.monotonic() + self.last_width = 0 + + def update(self, current: int, failures: int = 0) -> None: + self.current = current + elapsed = max(time.monotonic() - self.started, 0.001) + newly_downloaded = max(current - self.initial, 0) + # Rate is scoped to this process, not previously resumed rows. + rate = newly_downloaded / elapsed + ratio = min(current / self.total, 1.0) if self.total else 1.0 + bar_width = 30 + filled = int(ratio * bar_width) + bar = "#" * filled + "-" * (bar_width - filled) + message = ( + f"\r[{bar}] {current:,}/{self.total:,} " + f"({ratio:6.2%}) {rate:,.1f} img/s failures={failures:,}" + ) + padding = " " * max(0, self.last_width - len(message)) + print(message + padding, end="", file=sys.stderr, flush=True) + self.last_width = len(message) + + def finish(self) -> None: + print(file=sys.stderr) + + +def parse_assignments(values: list[str], option: str) -> dict[str, str]: + result: dict[str, str] = {} + for value in values: + name, separator, content = value.partition("=") + if not separator or not name.strip(): + raise ValueError(f"{option} expects NAME=VALUE, got {value!r}") + result[name.strip()] = content + return result + + +def build_url(url: str, params: dict[str, str], index: int) -> str: + rendered = url.replace("{index}", str(index)) + if not params: + return rendered + parts = urllib.parse.urlsplit(rendered) + existing = urllib.parse.parse_qsl(parts.query, keep_blank_values=True) + query = urllib.parse.urlencode(existing + list(params.items())) + return urllib.parse.urlunsplit( + (parts.scheme, parts.netloc, parts.path, query, parts.fragment) + ) + + +def fetch_image( + *, + index: int, + url: str, + headers: dict[str, str], + params: dict[str, str], + timeout: float, + retries: int, + retry_backoff: float, + delay: float, +) -> DownloadedImage: + if delay: + time.sleep(delay) + + request_url = build_url(url, params, index) + last_error: Exception | None = None + for attempt in range(retries + 1): + try: + request = urllib.request.Request(request_url, headers=headers) + with urllib.request.urlopen(request, timeout=timeout) as response: + data = response.read() + content_type = response.headers.get("Content-Type", "") + if not data: + raise ValueError("API returned an empty response") + if content_type.lower().startswith(("text/", "application/json")): + preview = data[:120].decode("utf-8", errors="replace") + raise ValueError( + f"API returned {content_type!r}, not image bytes: {preview!r}" + ) + return DownloadedImage(index, data, content_type) + except (OSError, ValueError, urllib.error.HTTPError) as error: + last_error = error + if attempt < retries: + jitter = random.random() * 0.25 + time.sleep(retry_backoff * (2**attempt) + jitter) + assert last_error is not None + raise last_error + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--url", required=True, help="Image API URL; {index} is optional") + parser.add_argument("--output", type=Path, default=Path("dataset")) + parser.add_argument("--count", type=int, default=1_000_000) + parser.add_argument("--workers", type=int, default=16) + parser.add_argument("--batch-size", type=int, default=10_000) + parser.add_argument("--timeout", type=float, default=30.0) + parser.add_argument("--retries", type=int, default=4) + parser.add_argument("--retry-backoff", type=float, default=0.5) + parser.add_argument("--delay", type=float, default=0.0, help="Delay per request") + parser.add_argument("--max-failures", type=int, default=100) + parser.add_argument("--flush-every", type=int, default=100) + parser.add_argument( + "--header", action="append", default=[], metavar="NAME=VALUE", + help="HTTP header; repeat as needed", + ) + parser.add_argument( + "--param", action="append", default=[], metavar="NAME=VALUE", + help="Query parameter; repeat as needed", + ) + return parser.parse_args() + + +def validate_args(args: argparse.Namespace) -> None: + for name in ("count", "workers", "batch_size", "flush_every"): + if getattr(args, name) <= 0: + raise ValueError(f"--{name.replace('_', '-')} must be greater than zero") + if args.retries < 0 or args.max_failures <= 0: + raise ValueError("--retries must be non-negative and --max-failures positive") + + +def main() -> int: + args = parse_args() + try: + validate_args(args) + headers = parse_assignments(args.header, "--header") + params = parse_assignments(args.param, "--param") + except ValueError as error: + print(f"error: {error}", file=sys.stderr) + return 2 + + headers.setdefault("User-Agent", "tci-ocr-dataset-builder/1.0") + csv_path = args.output / "labels.csv" + try: + completed, next_index = scan_dataset(csv_path) + except (OSError, ValueError) as error: + print(f"error: cannot resume dataset: {error}", file=sys.stderr) + return 2 + + if completed >= args.count: + print(f"Dataset already contains {completed:,} images (target: {args.count:,}).") + return 0 + + output, writer = open_dataset_for_append(csv_path) + progress = Progress(completed, args.count) + progress.update(completed) + failures = 0 + written_this_run = 0 + + def submit(executor: concurrent.futures.ThreadPoolExecutor, index: int): + return executor.submit( + fetch_image, + index=index, + url=args.url, + headers=headers, + params=params, + timeout=args.timeout, + retries=args.retries, + retry_backoff=args.retry_backoff, + delay=args.delay, + ) + + executor = concurrent.futures.ThreadPoolExecutor( + max_workers=args.workers, thread_name_prefix="image-download" + ) + pending: dict[concurrent.futures.Future[DownloadedImage], int] = {} + try: + initial = min(args.workers, args.count - completed) + for index in range(next_index, next_index + initial): + pending[submit(executor, index)] = index + next_index += initial + + while pending and completed < args.count: + done, _ = concurrent.futures.wait( + pending, return_when=concurrent.futures.FIRST_COMPLETED + ) + for future in done: + index = pending.pop(future) + try: + downloaded = future.result() + except Exception as error: + failures += 1 + print(f"\nrequest {index} failed: {error}", file=sys.stderr) + if failures >= args.max_failures: + raise RuntimeError( + f"stopped after {failures} failed requests" + ) from error + pending[submit(executor, index)] = index + continue + + extension = image_extension(downloaded.data, downloaded.content_type) + batch_id = downloaded.index // args.batch_size + relative = Path("images") / f"{batch_id:06d}" / ( + f"{downloaded.index:09d}{extension}" + ) + atomic_write(args.output / relative, downloaded.data) + writer.writerow( + { + "filename": relative.as_posix(), + "label": "", + "batch_id": str(batch_id), + "verified": "0", + "hash": sha256_bytes(downloaded.data), + } + ) + completed += 1 + written_this_run += 1 + if written_this_run % args.flush_every == 0: + output.flush() + os.fsync(output.fileno()) + progress.update(completed, failures) + + if next_index < args.count and completed + len(pending) < args.count: + pending[submit(executor, next_index)] = next_index + next_index += 1 + except KeyboardInterrupt: + print("\nInterrupted; saving completed rows...", file=sys.stderr) + return_code = 130 + except RuntimeError as error: + print(f"\nerror: {error}", file=sys.stderr) + return_code = 1 + else: + return_code = 0 + finally: + for future in pending: + future.cancel() + executor.shutdown(wait=False, cancel_futures=True) + output.flush() + os.fsync(output.fileno()) + output.close() + progress.finish() + + print(f"Saved {completed:,} rows in {csv_path}") + return return_code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/find_duplicates.py b/find_duplicates.py new file mode 100755 index 0000000..c8465c3 --- /dev/null +++ b/find_duplicates.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Find exact duplicate images using hashes already stored in labels.csv.""" + +from __future__ import annotations + +import argparse +import csv +import sys +from pathlib import Path + +from ocr_dataset import read_rows + + +DUPLICATE_COLUMNS = ( + "hash", + "canonical_filename", + "duplicate_filename", + "batch_id", + "label", + "verified", +) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--csv", type=Path, default=Path("dataset/labels.csv")) + parser.add_argument( + "--output", type=Path, default=Path("dataset/duplicates.csv") + ) + return parser.parse_args() + + +def main() -> int: + args = parse_args() + first_by_hash: dict[str, str] = {} + rows = 0 + duplicates = 0 + missing_hashes = 0 + args.output.parent.mkdir(parents=True, exist_ok=True) + + try: + with args.output.open("w", newline="", encoding="utf-8") as output: + writer = csv.DictWriter(output, fieldnames=DUPLICATE_COLUMNS) + writer.writeheader() + for row in read_rows(args.csv): + rows += 1 + digest = row["hash"].strip().lower() + if not digest: + missing_hashes += 1 + continue + canonical = first_by_hash.setdefault(digest, row["filename"]) + if canonical == row["filename"]: + continue + duplicates += 1 + writer.writerow( + { + "hash": digest, + "canonical_filename": canonical, + "duplicate_filename": row["filename"], + "batch_id": row["batch_id"], + "label": row["label"], + "verified": row["verified"], + } + ) + except (OSError, ValueError) as error: + print(f"error: {error}", file=sys.stderr) + return 1 + + print(f"Scanned {rows:,} rows; found {duplicates:,} duplicate files.") + if missing_hashes: + print(f"Warning: {missing_hashes:,} rows had no hash and were skipped.") + print(f"Report: {args.output}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) + diff --git a/merge_datasets.py b/merge_datasets.py new file mode 100755 index 0000000..2edc0f1 --- /dev/null +++ b/merge_datasets.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +"""Merge multiple OCR dataset directories into one collision-free dataset.""" + +from __future__ import annotations + +import argparse +import csv +import os +import shutil +import sys +import time +from dataclasses import dataclass +from pathlib import Path + +from ocr_dataset import CSV_COLUMNS, read_rows, sha256_file + + +@dataclass(frozen=True) +class DatasetSource: + csv_path: Path + root: Path + rows: int + + +class Progress: + def __init__(self, total: int) -> None: + self.total = total + self.started = time.monotonic() + self.last_drawn = 0.0 + self.last_width = 0 + + def update(self, completed: int, *, force: bool = False) -> None: + now = time.monotonic() + if not force and completed != self.total and now - self.last_drawn < 0.1: + return + elapsed = max(now - self.started, 0.001) + ratio = completed / self.total if self.total else 1.0 + filled = int(min(ratio, 1.0) * 30) + bar = "#" * filled + "-" * (30 - filled) + message = ( + f"\r[{bar}] {completed:,}/{self.total:,} " + f"({ratio:6.2%}) {completed / elapsed:,.1f} images/s" + ) + print( + message + " " * max(0, self.last_width - len(message)), + end="", + file=sys.stderr, + flush=True, + ) + self.last_width = len(message) + self.last_drawn = now + + def finish(self, completed: int) -> None: + self.update(completed, force=True) + print(file=sys.stderr) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "sources", + nargs="+", + type=Path, + help="Dataset directories or labels.csv files to merge", + ) + parser.add_argument( + "--output", type=Path, default=Path("merged_dataset"), + help="New destination directory (default: merged_dataset)", + ) + parser.add_argument("--batch-size", type=int, default=10_000) + parser.add_argument( + "--mode", + choices=("copy", "hardlink"), + default="copy", + help="Copy images, or hard-link them to save disk space", + ) + parser.add_argument( + "--flush-every", + type=int, + default=1_000, + help="Flush labels.csv after this many rows", + ) + return parser.parse_args() + + +def resolve_source(path: Path) -> tuple[Path, Path]: + if path.is_dir(): + csv_path = path / "labels.csv" + root = path + else: + csv_path = path + root = path.parent + if not csv_path.is_file(): + raise FileNotFoundError(f"dataset CSV not found: {csv_path}") + return csv_path.resolve(), root.resolve() + + +def count_source(csv_path: Path) -> int: + return sum(1 for _ in read_rows(csv_path)) + + +def safe_source_image(root: Path, filename: str) -> Path: + if not filename: + raise ValueError("encountered an empty filename") + image = (root / filename).resolve() + if not image.is_relative_to(root): + raise ValueError(f"image path escapes its dataset directory: {filename!r}") + if not image.is_file(): + raise FileNotFoundError(f"source image not found: {image}") + return image + + +def transfer_image(source: Path, destination: Path, mode: str) -> None: + destination.parent.mkdir(parents=True, exist_ok=True) + if mode == "hardlink": + os.link(source, destination) + else: + shutil.copyfile(source, destination) + + +def main() -> int: + args = parse_args() + if args.batch_size <= 0 or args.flush_every <= 0: + print("error: --batch-size and --flush-every must be positive", file=sys.stderr) + return 2 + + output = args.output.resolve() + if output.exists(): + print(f"error: output already exists: {output}", file=sys.stderr) + return 2 + + try: + resolved = [resolve_source(source) for source in args.sources] + if any(root == output or root in output.parents for _, root in resolved): + raise ValueError("the output directory cannot be inside a source dataset") + sources = [ + DatasetSource(csv_path, root, count_source(csv_path)) + for csv_path, root in resolved + ] + except (OSError, ValueError) as error: + print(f"error: {error}", file=sys.stderr) + return 2 + + total = sum(source.rows for source in sources) + output.parent.mkdir(parents=True, exist_ok=True) + staging = output.parent / f".{output.name}.merge-{os.getpid()}" + if staging.exists(): + print(f"error: staging directory already exists: {staging}", file=sys.stderr) + return 2 + + staging.mkdir() + progress = Progress(total) + progress.update(0, force=True) + completed = 0 + + try: + csv_path = staging / "labels.csv" + with csv_path.open("w", newline="", encoding="utf-8") as output_file: + writer = csv.DictWriter(output_file, fieldnames=CSV_COLUMNS) + writer.writeheader() + for source in sources: + for row in read_rows(source.csv_path): + source_image = safe_source_image(source.root, row["filename"]) + batch_id = completed // args.batch_size + suffix = source_image.suffix.lower() or ".img" + relative = ( + Path("images") + / f"{batch_id:06d}" + / f"{completed:09d}{suffix}" + ) + transfer_image(source_image, staging / relative, args.mode) + writer.writerow( + { + "filename": relative.as_posix(), + "label": row["label"], + "batch_id": str(batch_id), + "verified": row["verified"], + "hash": row["hash"] or sha256_file(source_image), + } + ) + completed += 1 + if completed % args.flush_every == 0: + output_file.flush() + progress.update(completed) + output_file.flush() + os.fsync(output_file.fileno()) + + staging.rename(output) + except (OSError, ValueError) as error: + progress.finish(completed) + print(f"error after {completed:,} images: {error}", file=sys.stderr) + print(f"Incomplete staging data was left at: {staging}", file=sys.stderr) + return 1 + except KeyboardInterrupt: + progress.finish(completed) + print("Interrupted.", file=sys.stderr) + print(f"Incomplete staging data was left at: {staging}", file=sys.stderr) + return 130 + + progress.finish(completed) + print( + f"Merged {completed:,} images from {len(sources):,} datasets into {output}" + ) + print("Exact duplicate hashes were preserved; run find_duplicates.py to report them.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/ocr_dataset.py b/ocr_dataset.py new file mode 100644 index 0000000..b553460 --- /dev/null +++ b/ocr_dataset.py @@ -0,0 +1,97 @@ +"""Shared helpers for the Persian-number OCR dataset scripts.""" + +from __future__ import annotations + +import csv +import hashlib +import os +from pathlib import Path +from typing import Iterator, TextIO + + +CSV_COLUMNS = ("filename", "label", "batch_id", "verified", "hash") + + +def sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str: + digest = hashlib.sha256() + with path.open("rb") as source: + while chunk := source.read(chunk_size): + digest.update(chunk) + return digest.hexdigest() + + +def image_extension(data: bytes, content_type: str = "") -> str: + """Return a conservative extension using magic bytes first.""" + if data.startswith(b"\xff\xd8\xff"): + return ".jpg" + if data.startswith(b"\x89PNG\r\n\x1a\n"): + return ".png" + if data.startswith((b"GIF87a", b"GIF89a")): + return ".gif" + if data.startswith(b"BM"): + return ".bmp" + if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP": + return ".webp" + + media_type = content_type.partition(";")[0].strip().lower() + return { + "image/jpeg": ".jpg", + "image/png": ".png", + "image/gif": ".gif", + "image/bmp": ".bmp", + "image/webp": ".webp", + }.get(media_type, ".img") + + +def open_dataset_for_append(path: Path) -> tuple[TextIO, csv.DictWriter]: + path.parent.mkdir(parents=True, exist_ok=True) + exists = path.exists() and path.stat().st_size > 0 + output = path.open("a", newline="", encoding="utf-8") + writer = csv.DictWriter(output, fieldnames=CSV_COLUMNS) + if not exists: + writer.writeheader() + output.flush() + return output, writer + + +def read_rows(path: Path) -> Iterator[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as source: + reader = csv.DictReader(source) + if reader.fieldnames != list(CSV_COLUMNS): + raise ValueError( + f"{path} has columns {reader.fieldnames!r}; expected {list(CSV_COLUMNS)!r}" + ) + yield from reader + + +def scan_dataset(path: Path) -> tuple[int, int]: + """Return (row count, next numeric image id).""" + if not path.exists() or path.stat().st_size == 0: + return 0, 0 + + count = 0 + highest_id = -1 + for row in read_rows(path): + count += 1 + try: + highest_id = max(highest_id, int(Path(row["filename"]).stem)) + except ValueError: + # Custom filenames do not prevent resuming; count remains a safe fallback. + pass + return count, max(count, highest_id + 1) + + +def atomic_write(path: Path, data: bytes) -> None: + """Write bytes without leaving a partially written image at the final path.""" + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp") + try: + with temporary.open("wb") as output: + output.write(data) + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..a3f1f19 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for the dataset command-line tools.""" diff --git a/tests/test_tools.py b/tests/test_tools.py new file mode 100644 index 0000000..6596a88 --- /dev/null +++ b/tests/test_tools.py @@ -0,0 +1,199 @@ +from __future__ import annotations + +import csv +import hashlib +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + + +PROJECT = Path(__file__).resolve().parents[1] +PNG = b"\x89PNG\r\n\x1a\n" + b"test-image-payload" + + +class ToolTests(unittest.TestCase): + def make_dataset( + self, + root: Path, + *, + label: str, + verified: str, + digest: str, + ) -> Path: + image = root / "images" / "000000" / "000000000.png" + image.parent.mkdir(parents=True) + image.write_bytes(PNG) + csv_path = root / "labels.csv" + with csv_path.open("w", newline="", encoding="utf-8") as output: + writer = csv.DictWriter( + output, + fieldnames=["filename", "label", "batch_id", "verified", "hash"], + ) + writer.writeheader() + writer.writerow( + { + "filename": image.relative_to(root).as_posix(), + "label": label, + "batch_id": "0", + "verified": verified, + "hash": digest, + } + ) + return image + + def test_downloader_resumes_and_duplicate_finder_reports(self): + with tempfile.TemporaryDirectory() as temp: + dataset = Path(temp) / "dataset" + fixture = Path(temp) / "image.png" + fixture.write_bytes(PNG) + url = fixture.as_uri() + first = subprocess.run( + [ + sys.executable, + str(PROJECT / "download_dataset.py"), + "--url", url, + "--output", str(dataset), + "--count", "3", + "--workers", "2", + "--flush-every", "1", + ], + text=True, + capture_output=True, + ) + self.assertEqual(first.returncode, 0, first.stderr) + second = subprocess.run( + [ + sys.executable, + str(PROJECT / "download_dataset.py"), + "--url", url, + "--output", str(dataset), + "--count", "5", + "--workers", "2", + ], + text=True, + capture_output=True, + ) + self.assertEqual(second.returncode, 0, second.stderr) + + with (dataset / "labels.csv").open(newline="", encoding="utf-8") as f: + rows = list(csv.DictReader(f)) + self.assertEqual(len(rows), 5) + self.assertEqual(list(rows[0]), ["filename", "label", "batch_id", "verified", "hash"]) + self.assertEqual(rows[0]["hash"], hashlib.sha256(PNG).hexdigest()) + self.assertTrue(all((dataset / row["filename"]).is_file() for row in rows)) + + report = dataset / "duplicates.csv" + result = subprocess.run( + [ + sys.executable, + str(PROJECT / "find_duplicates.py"), + "--csv", str(dataset / "labels.csv"), + "--output", str(report), + ], + text=True, + capture_output=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + with report.open(newline="", encoding="utf-8") as f: + duplicates = list(csv.DictReader(f)) + self.assertEqual(len(duplicates), 4) + + def test_verifier_normalizes_persian_digits_and_saves_on_quit(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + image = root / "images" / "000000" / "000000000.png" + image.parent.mkdir(parents=True) + image.write_bytes(PNG) + csv_path = root / "labels.csv" + with csv_path.open("w", newline="", encoding="utf-8") as output: + writer = csv.DictWriter( + output, + fieldnames=["filename", "label", "batch_id", "verified", "hash"], + ) + writer.writeheader() + for suffix in ("0", "1"): + writer.writerow( + { + "filename": image.relative_to(root).as_posix(), + "label": "", + "batch_id": "0", + "verified": "0", + "hash": hashlib.sha256(PNG + suffix.encode()).hexdigest(), + } + ) + + binary_dir = root / "bin" + binary_dir.mkdir() + fake_kitten = binary_dir / "kitten" + fake_kitten.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + fake_kitten.chmod(0o755) + environment = os.environ.copy() + environment["PATH"] = f"{binary_dir}{os.pathsep}{environment.get('PATH', '')}" + result = subprocess.run( + [ + sys.executable, + str(PROJECT / "verify_labels.py"), + "--csv", str(csv_path), + ], + input="۱۲۳\nq\n", + text=True, + capture_output=True, + env=environment, + ) + self.assertEqual(result.returncode, 0, result.stderr) + with csv_path.open(newline="", encoding="utf-8") as source: + rows = list(csv.DictReader(source)) + self.assertEqual(rows[0]["label"], "123") + self.assertEqual(rows[0]["verified"], "1") + self.assertEqual(rows[1]["verified"], "0") + + def test_merger_reindexes_images_and_preserves_metadata(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + expected_hash = hashlib.sha256(PNG).hexdigest() + source_one = root / "download-one" + source_two = root / "download-two" + original_one = self.make_dataset( + source_one, label="123", verified="1", digest=expected_hash + ) + original_two = self.make_dataset( + source_two, label="", verified="0", digest="" + ) + destination = root / "combined" + + result = subprocess.run( + [ + sys.executable, + str(PROJECT / "merge_datasets.py"), + str(source_one), + str(source_two / "labels.csv"), + "--output", str(destination), + "--batch-size", "1", + ], + text=True, + capture_output=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + with (destination / "labels.csv").open( + newline="", encoding="utf-8" + ) as source: + rows = list(csv.DictReader(source)) + + self.assertEqual(len(rows), 2) + self.assertEqual([row["batch_id"] for row in rows], ["0", "1"]) + self.assertEqual([row["label"] for row in rows], ["123", ""]) + self.assertEqual([row["verified"] for row in rows], ["1", "0"]) + self.assertEqual([row["hash"] for row in rows], [expected_hash] * 2) + self.assertNotEqual(rows[0]["filename"], rows[1]["filename"]) + self.assertTrue( + all((destination / row["filename"]).read_bytes() == PNG for row in rows) + ) + self.assertTrue(original_one.is_file()) + self.assertTrue(original_two.is_file()) + + +if __name__ == "__main__": + unittest.main() diff --git a/verify_labels.py b/verify_labels.py new file mode 100755 index 0000000..d5aae06 --- /dev/null +++ b/verify_labels.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Show OCR images with Kitty and interactively verify their labels.""" + +from __future__ import annotations + +import argparse +import csv +import os +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +from ocr_dataset import CSV_COLUMNS + + +DIGIT_TRANSLATION = str.maketrans( + "۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "01234567890123456789" +) +ALLOWED_DIGITS = frozenset("0123456789۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩") + + +def kitty_command() -> list[str] | None: + if executable := shutil.which("kitten"): + return [executable, "icat"] + if executable := shutil.which("kitty"): + return [executable, "+kitten", "icat"] + return None + + +def show_image(command: list[str], image: Path) -> None: + subprocess.run( + command + ["--clear", "--transfer-mode=file", str(image)], + check=True, + ) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--csv", type=Path, default=Path("dataset/labels.csv")) + parser.add_argument( + "--images-root", + type=Path, + help="Root for CSV filenames (default: directory containing the CSV)", + ) + parser.add_argument("--start", type=int, default=0, help="Skip this many CSV rows") + parser.add_argument( + "--reverify", action="store_true", help="Also prompt for verified rows" + ) + parser.add_argument( + "--keep-digit-script", + action="store_true", + help="Keep Persian/Arabic digits instead of normalizing labels to ASCII", + ) + return parser.parse_args() + + +def main() -> int: + args = parse_args() + command = kitty_command() + if command is None: + print( + "error: Kitty's 'kitten' or 'kitty' executable was not found in PATH", + file=sys.stderr, + ) + return 2 + if args.start < 0: + print("error: --start must be non-negative", file=sys.stderr) + return 2 + + root = args.images_root or args.csv.parent + verified_now = 0 + quit_requested = False + temporary_path: Path | None = None + + try: + with args.csv.open(newline="", encoding="utf-8") as source: + reader = csv.DictReader(source) + if reader.fieldnames != list(CSV_COLUMNS): + raise ValueError( + f"columns are {reader.fieldnames!r}; expected {list(CSV_COLUMNS)!r}" + ) + + file_descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{args.csv.name}.", suffix=".tmp", dir=args.csv.parent + ) + temporary_path = Path(temporary_name) + with os.fdopen(file_descriptor, "w", newline="", encoding="utf-8") as output: + writer = csv.DictWriter(output, fieldnames=CSV_COLUMNS) + writer.writeheader() + + for index, row in enumerate(reader): + should_prompt = ( + index >= args.start + and (args.reverify or row["verified"].strip() != "1") + and not quit_requested + ) + if should_prompt: + image = root / row["filename"] + if not image.is_file(): + print(f"\nMissing image, skipped: {image}", file=sys.stderr) + else: + show_image(command, image) + while True: + current = row["label"] or "unlabeled" + try: + answer = input( + f"[{index + 1}] {row['filename']} " + f"(current: {current}) number [s=skip, q=quit]: " + ).strip() + except (KeyboardInterrupt, EOFError): + print("\nSaving and quitting...", file=sys.stderr) + quit_requested = True + break + if answer.lower() == "q": + quit_requested = True + break + if answer.lower() == "s" or not answer: + break + if not all(character in ALLOWED_DIGITS for character in answer): + print("Enter digits only (ASCII, Persian, or Arabic).") + continue + normalized = ( + answer if args.keep_digit_script else answer.translate(DIGIT_TRANSLATION) + ) + row["label"] = normalized + row["verified"] = "1" + verified_now += 1 + break + writer.writerow(row) + + output.flush() + os.fsync(output.fileno()) + + assert temporary_path is not None + os.replace(temporary_path, args.csv) + temporary_path = None + except KeyboardInterrupt: + print("\nInterrupted. The current CSV was left unchanged.", file=sys.stderr) + return 130 + except (OSError, ValueError, subprocess.CalledProcessError) as error: + print(f"error: {error}. The current CSV was left unchanged.", file=sys.stderr) + return 1 + finally: + if temporary_path is not None: + temporary_path.unlink(missing_ok=True) + try: + subprocess.run(command + ["--clear"], check=False) if command else None + except OSError: + pass + + print(f"Saved {verified_now:,} newly verified labels to {args.csv}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())