htr-tiny / htr /parse /quality.py
spboucher04's picture
Release HTR-Tiny-0.3.0 (WP-AI-0002)
ff8d20f verified
Raw History Blame Contribute Delete
2.77 kB
"""Paragraph quality scoring and language identification (eligibility for rewriting)."""
from __future__ import annotations
import re
from htr.parse.protect import PLACEHOLDER_RE
from htr.utils.text import split_sentences, word_count
try:
from langdetect import DetectorFactory, detect_langs
DetectorFactory.seed = 0
_HAS_LD = True
except Exception: # noqa: BLE001
_HAS_LD = False
_ALPHA = re.compile(r"[A-Za-z]")
_GARBAGE = re.compile(r"[^\x09\x0a\x20-\x7e -ɏͰ-Ͽ‐-‧‰-⁞€℀-⅏←-⇿∀-⋿①-⓿■-➿⟦⟧×·°µ′″]")
def detect_language(text: str) -> tuple[str | None, float]:
if not _HAS_LD or word_count(text) < 5:
return None, 0.0
try:
langs = detect_langs(text)
return (langs[0].lang, float(langs[0].prob)) if langs else (None, 0.0)
except Exception: # noqa: BLE001
return None, 0.0
def quality_score(text: str) -> tuple[float, list[str]]:
"""Heuristic quality in [0,1] with reasons. Penalises: too short/long, low alphabetic ratio, placeholder
density, garbage characters, broken hyphenation, missing sentence punctuation, all-caps, list-like fragments."""
flags: list[str] = []
n_words = word_count(text)
if n_words == 0:
return 0.0, ["empty"]
chars = len(text)
alpha_ratio = len(_ALPHA.findall(text)) / max(1, chars)
ph = len(PLACEHOLDER_RE.findall(text)) + text.count("$")
ph_density = ph / n_words
garbage = len(_GARBAGE.findall(text)) / max(1, chars)
sents = split_sentences(text)
n_sent = len(sents)
score = 1.0
if n_words < 40:
score -= 0.5
flags.append("short")
if n_words > 450:
score -= 0.3
flags.append("long")
if alpha_ratio < 0.6:
score -= 0.4
flags.append("low_alpha")
if ph_density > 0.15:
score -= 0.3
flags.append("placeholder_dense")
if garbage > 0.01:
score -= 0.4
flags.append("garbage_chars")
if n_sent < 2:
score -= 0.3
flags.append("single_sentence")
if not re.search(r"[.!?]\s*$", text):
score -= 0.2
flags.append("no_terminal_punct")
caps_words = sum(1 for w in text.split() if len(w) > 3 and w.isupper())
if caps_words / n_words > 0.2:
score -= 0.3
flags.append("many_caps")
if re.search(r"\w- \w", text) and len(re.findall(r"\w- \w", text)) / n_words > 0.02:
score -= 0.2
flags.append("broken_hyphenation")
if re.search(r"^(Table|Figure|Fig\.)\s*\d", text):
score -= 0.5
flags.append("caption_like")
avg_sent_words = n_words / max(1, n_sent)
if avg_sent_words < 6:
score -= 0.2
flags.append("fragmentary")
return max(0.0, min(1.0, score)), flags