File size: 4,583 Bytes
828972c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | """English document eligibility using the corpus fastText model and voting rule."""
import hashlib
import os
import re
from functools import lru_cache
from pathlib import Path
MODEL_URL = "https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.bin"
MODEL_SHA256 = "7e69ec5451bc261cc7844e49e4792a85d7f09c06789ec800fc4a44aec362764e"
_BOUNDARY = re.compile(r"\n+|(?<=[.!?。!?])\s+")
_LETTER = re.compile(r"[^\W\d_]", re.UNICODE)
_LATIN_WORD = re.compile(r"\b[A-Za-z]+\b")
@lru_cache(maxsize=1)
def _model():
import fasttext
from torch.hub import download_url_to_file
configured = os.environ.get("ANAGRAM_LID_MODEL")
path = Path(configured).expanduser() if configured else Path.home() / ".cache/anagram/lid.176.bin"
if not configured and not path.is_file():
path.parent.mkdir(parents=True, exist_ok=True)
download_url_to_file(MODEL_URL, str(path), hash_prefix=MODEL_SHA256, progress=False)
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(1 << 20), b""):
digest.update(block)
if digest.hexdigest() != MODEL_SHA256:
raise ValueError(f"Unexpected language model at {path}")
return fasttext.load_model(str(path))
def _windows(text):
"""Use short paragraphs/sentences when possible and sample across long works."""
size = len(text)
if size < 120:
if size >= 36:
boundary = _BOUNDARY.search(text, 14, size - 14)
if boundary:
return [text[:boundary.start()], text[boundary.end():]]
return [text]
count = min(5, max(2, (size + 239) // 240))
if size > 1200:
return [text[i * (size - 240) // (count - 1):i * (size - 240) // (count - 1) + 240]
for i in range(count)]
edges = [0]
for i in range(1, count):
target = i * size // count
margin = min(48, size // (count * 3))
boundaries = [m.end() for m in _BOUNDARY.finditer(text, target - margin, target + margin)]
edges.append(min(boundaries, key=lambda x: abs(x - target)) if boundaries else target)
edges.append(size)
return [text[start:stop] for start, stop in zip(edges, edges[1:])]
def _score(text):
"""Chunks only enter this cache, never whole book-length strings."""
normalized = " ".join(text.replace("\x00", " ").split())
if not _LETTER.search(normalized) or re.fullmatch(r"[a-zA-Z][.!?]?", normalized):
return "uncertain", False
labels, scores = _model().predict(normalized, k=2)
if labels[0] == "__label__en":
if scores[0] >= .55:
return "english", True
# A fragment such as "Fix grammatical errors" supplies fewer n-grams.
# Permit a clear top-label margin on multiword fragments without treating
# ambiguous single words or proper names as affirmative English evidence.
if (len(normalized) <= 80 and scores[0] >= .28 and len(scores) > 1
and scores[0] - scores[1] >= .13 and len(_LATIN_WORD.findall(normalized)) >= 2):
return "english", True
# Titles and imperative fragments often omit terminal punctuation. Ask the
# same model about a normalized form only if it already ranked English in
# the top two. This supplies no extra words or purported English content.
if (len(normalized) <= 80 and scores[0] < .68 and "__label__en" in labels
and len(_LATIN_WORD.findall(normalized)) >= 2):
normalized_title = normalized.lower().rstrip(".!?") + "."
title_label, title_score = _model().predict(normalized_title, k=1)
threshold = .55 if labels[0] == "__label__en" else .68
if title_label[0] == "__label__en" and title_score[0] >= threshold:
return "english", True
if labels[0] == "__label__en":
return "uncertain", scores[0] >= .20
if scores[0] >= .60:
return "non_english", False
plausible = len(labels) > 1 and labels[1] == "__label__en" and scores[1] >= .20
return "uncertain", plausible
def _text_status(text):
pieces = _windows(text)
votes = [_score(piece) for piece in pieces]
english = sum(status == "english" for status, _ in votes)
foreign = sum(status == "non_english" for status, _ in votes)
if english and foreign:
return "mixed", False
if english * 2 >= len(votes):
return "english", True
if foreign * 2 >= len(votes):
return "non_english", False
return "uncertain", len(votes) == 1 and votes[0][1]
def document_language(text):
return _text_status(text)[0]
|