Datasets:
Download evaluation_kit/box_grouping/loading.py from RLALT/ACoPDoc: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/datasets/RLALT/ACoPDoc/resolve/main/evaluation_kit/box_grouping/loading.py
- Command line
-
hf download hf://datasets/RLALT/ACoPDoc/evaluation_kit/box_grouping/loading.py
-
curl -L -o loading.py https://huggingface.co/datasets/RLALT/ACoPDoc/resolve/main/evaluation_kit/box_grouping/loading.py
17.3 kB
| """Load annotation boxes and predicted rows from disk, and detect watermark rows.""" | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| import sys | |
| import unicodedata | |
| from collections import Counter | |
| from pathlib import Path | |
| from typing import Any | |
| from geometry import Box, rotated_rectangle_points, polygon_bounds | |
| from models import ( | |
| Word, | |
| AnnotationBox, | |
| PredictedRow, | |
| decomposable_container_box_ids, | |
| filter_redundant_annotation_boxes, | |
| ) | |
| WATERMARK_PATTERNS = ( | |
| { | |
| "tokens": ("national", "library", "of", "armenia", "ocr", "by", "portmind"), | |
| "token_counts": Counter( | |
| ("national", "library", "of", "armenia", "ocr", "by", "portmind") | |
| ), | |
| "distinctive_tokens": {"national", "library", "armenia", "ocr", "portmind"}, | |
| "normalized_text": "nationallibraryofarmeniaocrbyportmind", | |
| "max_edit_distance": 2, | |
| "min_distinctive_token_matches": 3, | |
| "min_token_count": 6, | |
| }, | |
| { | |
| "tokens": ("armenia", "ocr", "by", "portmind"), | |
| "token_counts": Counter(("armenia", "ocr", "by", "portmind")), | |
| "distinctive_tokens": {"armenia", "ocr", "portmind"}, | |
| "normalized_text": "armeniaocrbyportmind", | |
| "max_edit_distance": 2, | |
| "min_distinctive_token_matches": 2, | |
| "min_token_count": 4, | |
| }, | |
| { | |
| "tokens": ("national", "library", "of", "armenia"), | |
| "token_counts": Counter(("national", "library", "of", "armenia")), | |
| "distinctive_tokens": {"national", "library", "armenia"}, | |
| "normalized_text": "nationallibraryofarmenia", | |
| "max_edit_distance": 2, | |
| "min_distinctive_token_matches": 2, | |
| "min_token_count": 3, | |
| }, | |
| ) | |
| WATERMARK_TOKEN_VOCABULARY = frozenset( | |
| token for pattern in WATERMARK_PATTERNS for token in pattern["tokens"] | |
| ) | |
| NON_ARMENIAN_BOX_LETTER_RATIO_THRESHOLD = 0.9 | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument( | |
| "--annotations-json", | |
| type=Path, | |
| required=True, | |
| help="Path to the annotation JSON file.", | |
| ) | |
| parser.add_argument( | |
| "--predictions-csv", | |
| type=Path, | |
| required=True, | |
| help="Path to the predicted word-box CSV file.", | |
| ) | |
| parser.add_argument( | |
| "--coverage-threshold", | |
| type=float, | |
| default=1.0, | |
| help="Minimum fraction of words in a row that must fit a box for a full match.", | |
| ) | |
| parser.add_argument( | |
| "--failure-example-count", | |
| type=int, | |
| default=5, | |
| help="Number of example failures to include per failure type in the report.", | |
| ) | |
| parser.add_argument( | |
| "--filter", | |
| dest="filters", | |
| help=( | |
| "Optional comma-separated region filters, e.g. " | |
| "`non-armenian`, `graphics`, or `non-armenian,graphics`." | |
| ), | |
| ) | |
| parser.add_argument( | |
| "--unit-level", | |
| dest="unit_level", | |
| choices=["word", "line"], | |
| default="word", | |
| help="Granularity of predicted rows: 'word' or 'line'.", | |
| ) | |
| parser.add_argument( | |
| "--output", | |
| type=Path, | |
| help="Optional JSON path for the full report.", | |
| ) | |
| return parser.parse_args() | |
| def load_json(path: Path) -> Any: | |
| with path.open("r", encoding="utf-8") as handle: | |
| return json.load(handle) | |
| def pick_geometry_result(results: list[dict[str, Any]]) -> dict[str, Any] | None: | |
| candidates = [ | |
| result | |
| for result in results | |
| if {"x", "y", "width", "height"} <= set(result.get("value", {}).keys()) | |
| ] | |
| if not candidates: | |
| return None | |
| def priority(result: dict[str, Any]) -> tuple[int, str]: | |
| from_name = result.get("from_name", "") | |
| if from_name == "label": | |
| return (0, from_name) | |
| return (1, from_name) | |
| return sorted(candidates, key=priority)[0] | |
| def pick_transcription_result(results: list[dict[str, Any]]) -> dict[str, Any] | None: | |
| candidates = [ | |
| result | |
| for result in results | |
| if result.get("from_name") == "transcription" | |
| and "text" in result.get("value", {}) | |
| ] | |
| if not candidates: | |
| return None | |
| return candidates[0] | |
| def text_from_result(result: dict[str, Any]) -> str: | |
| raw_text = result.get("value", {}).get("text", []) | |
| if isinstance(raw_text, list): | |
| return "\n".join(str(item) for item in raw_text) | |
| if raw_text is None: | |
| return "" | |
| return str(raw_text) | |
| def parent_box_id_from_results(results: list[dict[str, Any]]) -> str | None: | |
| for result in results: | |
| if result.get("from_name") != "parent_id": | |
| continue | |
| raw_text = result.get("value", {}).get("text") | |
| if isinstance(raw_text, list) and raw_text: | |
| return str(raw_text[0]) | |
| return None | |
| def reading_order_from_results(results: list[dict[str, Any]]) -> int | None: | |
| for result in results: | |
| if result.get("from_name") != "reading_order": | |
| continue | |
| raw_text = result.get("value", {}).get("text") | |
| if isinstance(raw_text, list) and raw_text: | |
| try: | |
| return int(raw_text[0]) | |
| except (TypeError, ValueError): | |
| return None | |
| return None | |
| def labels_from_result(result: dict[str, Any]) -> tuple[str, ...]: | |
| raw_labels = result.get("value", {}).get("rectanglelabels", []) | |
| if not isinstance(raw_labels, list): | |
| return () | |
| return tuple(str(label) for label in raw_labels if str(label).strip()) | |
| def letter_script(character: str) -> str | None: | |
| if not unicodedata.category(character).startswith("L"): | |
| return None | |
| character_name = unicodedata.name(character, "") | |
| if character_name.startswith("ARMENIAN"): | |
| return "armenian" | |
| if character_name.startswith("LATIN"): | |
| return "latin" | |
| if character_name.startswith("CYRILLIC"): | |
| return "cyrillic" | |
| return "other_letter" | |
| def count_text_letter_scripts(text: str) -> Counter[str]: | |
| return Counter( | |
| script | |
| for character in text | |
| if (script := letter_script(character)) is not None | |
| ) | |
| def non_armenian_letter_ratio(text: str) -> tuple[int, int, float]: | |
| script_counts = count_text_letter_scripts(text) | |
| letter_count = sum(script_counts.values()) | |
| latin_or_cyrillic_letter_count = ( | |
| script_counts["latin"] + script_counts["cyrillic"] | |
| ) | |
| ratio = ( | |
| latin_or_cyrillic_letter_count / letter_count if letter_count else 0.0 | |
| ) | |
| return letter_count, latin_or_cyrillic_letter_count, ratio | |
| def load_annotation_boxes(path: Path) -> list[AnnotationBox]: | |
| data = load_json(path) | |
| grouped_results: dict[str, list[dict[str, Any]]] = {} | |
| for annotation in data.get("annotations", []): | |
| for result in annotation.get("result", []): | |
| result_id = result.get("id") | |
| if result_id is None: | |
| continue | |
| grouped_results.setdefault(str(result_id), []).append(result) | |
| boxes: list[AnnotationBox] = [] | |
| for box_id, results in grouped_results.items(): | |
| transcription_result = pick_transcription_result(results) | |
| geometry_result = pick_geometry_result(results) | |
| if geometry_result is None: | |
| continue | |
| geometry = geometry_result["value"] | |
| x = float(geometry["x"]) | |
| y = float(geometry["y"]) | |
| width = float(geometry["width"]) | |
| height = float(geometry["height"]) | |
| rotation = float(geometry.get("rotation", 0.0)) | |
| rect = Box( | |
| x_min=x, | |
| y_min=y, | |
| x_max=x + width, | |
| y_max=y + height, | |
| ) | |
| polygon = rotated_rectangle_points(x, y, width, height, rotation) | |
| text = ( | |
| text_from_result(transcription_result) | |
| if transcription_result is not None | |
| else "" | |
| ) | |
| labels = labels_from_result(geometry_result) | |
| if "Rule" in labels: | |
| continue | |
| letter_count, latin_or_cyrillic_count, ratio = non_armenian_letter_ratio( | |
| text | |
| ) | |
| boxes.append( | |
| AnnotationBox( | |
| box_id=box_id, | |
| rect=rect, | |
| text=text, | |
| has_transcription=transcription_result is not None, | |
| rotation=rotation, | |
| polygon=polygon, | |
| bounds=polygon_bounds(polygon), | |
| labels=labels, | |
| letter_count=letter_count, | |
| latin_or_cyrillic_letter_count=latin_or_cyrillic_count, | |
| non_armenian_letter_ratio=ratio, | |
| excluded_as_non_armenian_text=( | |
| ratio > NON_ARMENIAN_BOX_LETTER_RATIO_THRESHOLD | |
| ), | |
| parent_box_id=parent_box_id_from_results(results), | |
| reading_order=reading_order_from_results(results), | |
| ) | |
| ) | |
| decomposable_ids = decomposable_container_box_ids(boxes) | |
| boxes = [box for box in boxes if box.box_id not in decomposable_ids] | |
| return sorted( | |
| filter_redundant_annotation_boxes(boxes), | |
| key=lambda item: (item.bounds.y_min, item.bounds.x_min, item.box_id), | |
| ) | |
| def load_predicted_rows(path: Path, unit_level: str = "word") -> list[PredictedRow]: | |
| """Load predicted word boxes from an evaluation CSV, grouped into rows. | |
| For ``unit_level="line"``, rows sharing the same ``group_row`` value are | |
| assembled into one PredictedRow (a full text line built from its | |
| constituent words) — the CSV's own row grouping is authoritative. | |
| For ``unit_level="word"`` (the default), ``group_row`` is ignored and | |
| every CSV row becomes its own single-word PredictedRow. This matters for | |
| CSVs where multiple individual word boxes share a ``group_row`` because | |
| an upstream step assigned them to the same visual line (e.g. raw | |
| box_grouping/data CSVs): without this, a word-level evaluation would | |
| incorrectly treat that whole line as one atomic unit instead of scoring | |
| each word independently against the ground truth. | |
| """ | |
| grouped_words: dict[str, list[Word]] = {} | |
| with path.open("r", encoding="utf-8", newline="") as handle: | |
| reader = csv.DictReader(handle) | |
| for index, row in enumerate(reader): | |
| row_id = str(index) if unit_level == "word" else row["group_row"] | |
| word = Word( | |
| box=Box( | |
| x_min=float(row["x1"]), | |
| y_min=float(row["y1"]), | |
| x_max=float(row["x2"]), | |
| y_max=float(row["y2"]), | |
| ), | |
| text=row.get("text", ""), | |
| ) | |
| grouped_words.setdefault(row_id, []).append(word) | |
| return [ | |
| PredictedRow( | |
| row_id=row_id, | |
| words=sorted(words, key=lambda w: (w.box.x_min, w.box.y_min)), | |
| ) | |
| for row_id, words in grouped_words.items() | |
| ] | |
| def normalize_token(text: str) -> str: | |
| return "".join(character.lower() for character in text if character.isalnum()) | |
| def normalized_token_segments(text: str) -> list[str]: | |
| segments: list[str] = [] | |
| current_characters: list[str] = [] | |
| for character in text: | |
| if character.isalnum(): | |
| current_characters.append(character) | |
| continue | |
| if current_characters: | |
| normalized = normalize_token("".join(current_characters)) | |
| if normalized: | |
| segments.append(normalized) | |
| current_characters = [] | |
| if current_characters: | |
| normalized = normalize_token("".join(current_characters)) | |
| if normalized: | |
| segments.append(normalized) | |
| return segments | |
| def matches_watermark_pattern( | |
| normalized_tokens: list[str], pattern: dict[str, Any] | |
| ) -> bool: | |
| # Deferred import: text_metrics lives in evaluation/, not box_grouping/. | |
| # Avoids a top-level cycle (loading → text_metrics → spatial → loading). | |
| _evaluation = str(Path(__file__).resolve().parent.parent / "evaluation") | |
| if _evaluation not in sys.path: | |
| sys.path.insert(0, _evaluation) | |
| from text_metrics import edit_distance | |
| token_counts = Counter(normalized_tokens) | |
| distinctive_token_matches = len( | |
| set(token_counts) & pattern["distinctive_tokens"] | |
| ) | |
| if distinctive_token_matches < pattern["min_distinctive_token_matches"]: | |
| return False | |
| if len(normalized_tokens) >= pattern["min_token_count"] and all( | |
| count <= pattern["token_counts"].get(token, 0) | |
| for token, count in token_counts.items() | |
| ): | |
| return True | |
| normalized_text = "".join(normalized_tokens) | |
| if ( | |
| abs(len(normalized_text) - len(pattern["normalized_text"])) | |
| > pattern["max_edit_distance"] | |
| ): | |
| return False | |
| return ( | |
| edit_distance(normalized_text, pattern["normalized_text"]) | |
| <= pattern["max_edit_distance"] | |
| ) | |
| def normalized_row_tokens(predicted_row: PredictedRow) -> list[str]: | |
| normalized_tokens: list[str] = [] | |
| for word in predicted_row.words: | |
| normalized_tokens.extend(normalized_token_segments(word.text)) | |
| return normalized_tokens | |
| def is_watermark_row(predicted_row: PredictedRow) -> bool: | |
| normalized_tokens = normalized_row_tokens(predicted_row) | |
| if not normalized_tokens: | |
| return False | |
| return any( | |
| matches_watermark_pattern(normalized_tokens, pattern) | |
| for pattern in WATERMARK_PATTERNS | |
| ) | |
| def matches_watermark_subsequence(normalized_tokens: list[str]) -> bool: | |
| if not normalized_tokens: | |
| return False | |
| token_count = len(normalized_tokens) | |
| for pattern in WATERMARK_PATTERNS: | |
| pattern_tokens = pattern["tokens"] | |
| if token_count > len(pattern_tokens): | |
| continue | |
| for start_index in range(len(pattern_tokens) - token_count + 1): | |
| if ( | |
| tuple(normalized_tokens) | |
| == pattern_tokens[start_index : start_index + token_count] | |
| ): | |
| return True | |
| return False | |
| def watermark_row_ids( | |
| predicted_rows: list[PredictedRow], | |
| local_boxes_share_line_fn: Any, | |
| ) -> set[str]: | |
| """Return the set of row_ids that are part of a watermark (direct or fragmented).""" | |
| row_details = [ | |
| { | |
| "predicted_row": predicted_row, | |
| "row_box": _row_box(predicted_row), | |
| "normalized_tokens": normalized_row_tokens(predicted_row), | |
| "is_direct_watermark": is_watermark_row(predicted_row), | |
| } | |
| for predicted_row in predicted_rows | |
| ] | |
| ignored_row_ids = { | |
| detail["predicted_row"].row_id | |
| for detail in row_details | |
| if detail["is_direct_watermark"] | |
| } | |
| candidate_indexes = [ | |
| index | |
| for index, detail in enumerate(row_details) | |
| if detail["is_direct_watermark"] | |
| or ( | |
| detail["normalized_tokens"] | |
| and all( | |
| token in WATERMARK_TOKEN_VOCABULARY | |
| for token in detail["normalized_tokens"] | |
| ) | |
| ) | |
| ] | |
| visited_indexes: set[int] = set() | |
| for candidate_index in candidate_indexes: | |
| if candidate_index in visited_indexes: | |
| continue | |
| component_indexes: list[int] = [] | |
| pending_indexes = [candidate_index] | |
| visited_indexes.add(candidate_index) | |
| while pending_indexes: | |
| current_index = pending_indexes.pop() | |
| component_indexes.append(current_index) | |
| current_box = row_details[current_index]["row_box"] | |
| for other_index in candidate_indexes: | |
| if other_index in visited_indexes: | |
| continue | |
| if not local_boxes_share_line_fn( | |
| current_box, row_details[other_index]["row_box"] | |
| ): | |
| continue | |
| visited_indexes.add(other_index) | |
| pending_indexes.append(other_index) | |
| if len(component_indexes) < 2: | |
| continue | |
| ordered_component_indexes = sorted( | |
| component_indexes, | |
| key=lambda i: ( | |
| row_details[i]["row_box"].x_min, | |
| row_details[i]["row_box"].y_min, | |
| row_details[i]["predicted_row"].row_id, | |
| ), | |
| ) | |
| combined_tokens: list[str] = [] | |
| for component_index in ordered_component_indexes: | |
| combined_tokens.extend(row_details[component_index]["normalized_tokens"]) | |
| if any( | |
| matches_watermark_pattern(combined_tokens, pattern) | |
| for pattern in WATERMARK_PATTERNS | |
| ) or matches_watermark_subsequence(combined_tokens): | |
| ignored_row_ids.update( | |
| row_details[component_index]["predicted_row"].row_id | |
| for component_index in component_indexes | |
| ) | |
| return ignored_row_ids | |
| def _row_box(predicted_row: PredictedRow) -> Box: | |
| """Compute the bounding box of a predicted row without importing from spatial.""" | |
| return Box( | |
| x_min=min(word.box.x_min for word in predicted_row.words), | |
| y_min=min(word.box.y_min for word in predicted_row.words), | |
| x_max=max(word.box.x_max for word in predicted_row.words), | |
| y_max=max(word.box.y_max for word in predicted_row.words), | |
| ) | |