Commit ·
d9a3362
1
Parent(s): 92e6087
update
Browse files- app.py +97 -4
- init_venv.py +2 -1
- requirements.txt +2 -0
app.py
CHANGED
|
@@ -12,6 +12,8 @@ from typing import Any
|
|
| 12 |
import pandas as pd
|
| 13 |
import gradio as gr
|
| 14 |
import pycountry
|
|
|
|
|
|
|
| 15 |
from transformers import AutoModelForTokenClassification, AutoTokenizer, pipeline
|
| 16 |
|
| 17 |
from fleurs_cache import fetch_random_fleurs_sentence, fetch_random_fleurs_sentence_mix
|
|
@@ -20,6 +22,8 @@ from tatoeba import fetch_random_tatoeba_sentence, fetch_random_tatoeba_sentence
|
|
| 20 |
|
| 21 |
|
| 22 |
MODEL_CHECKPOINT = "DerivedFunction/polyglot-tagger-v2"
|
|
|
|
|
|
|
| 23 |
MIN_ARTIFACT_SPAN_CHARS = 4
|
| 24 |
MIN_ARTIFACT_CONFIDENCE = 0.5
|
| 25 |
ARTIFACT_SPAN_WEIGHT = 0.35
|
|
@@ -38,6 +42,13 @@ def get_pipeline():
|
|
| 38 |
)
|
| 39 |
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
def normalize_label(label: str) -> str:
|
| 42 |
if label.startswith(("B-", "I-")):
|
| 43 |
label = label[2:]
|
|
@@ -115,17 +126,41 @@ def make_lang_chip_label(lang: str, stat: dict[str, float | int], score: float)
|
|
| 115 |
def build_chip_button_updates(
|
| 116 |
ranked: list[tuple[str, dict[str, float | int]]],
|
| 117 |
classifier_scores: dict[str, float],
|
|
|
|
| 118 |
max_chips: int = 6,
|
| 119 |
) -> list[dict[str, Any]]:
|
| 120 |
"""Return button updates for the top-ranked languages."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
updates: list[dict[str, Any]] = []
|
| 122 |
for idx in range(max_chips):
|
| 123 |
-
if idx < len(
|
| 124 |
-
lang
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
updates.append(
|
| 126 |
gr.update(
|
| 127 |
-
value=
|
| 128 |
visible=True,
|
|
|
|
| 129 |
)
|
| 130 |
)
|
| 131 |
else:
|
|
@@ -157,6 +192,7 @@ def build_ui_state(
|
|
| 157 |
|
| 158 |
def build_example_validation(
|
| 159 |
classifier_scores: dict[str, float],
|
|
|
|
| 160 |
expected_langs: list[str],
|
| 161 |
) -> dict[str, Any]:
|
| 162 |
"""Compare derived scores against known source languages."""
|
|
@@ -175,10 +211,28 @@ def build_example_validation(
|
|
| 175 |
precision = true_positive / (true_positive + false_positive) if (true_positive + false_positive) else 0.0
|
| 176 |
recall = true_positive / (true_positive + false_negative) if (true_positive + false_negative) else 0.0
|
| 177 |
validation_score = (2 * precision * recall / (precision + recall)) if (precision + recall) else 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
return {
|
| 180 |
"expected_langs": expected_langs,
|
| 181 |
"predicted_langs": predicted_langs,
|
|
|
|
| 182 |
"top_lang": top_lang,
|
| 183 |
"top_score": top_score,
|
| 184 |
"true_positive": true_positive,
|
|
@@ -190,6 +244,12 @@ def build_example_validation(
|
|
| 190 |
"recall": recall,
|
| 191 |
"top_match": false_positive == 0 and false_negative == 0,
|
| 192 |
"validation_score": validation_score,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
}
|
| 194 |
|
| 195 |
|
|
@@ -208,6 +268,9 @@ def render_validation_html(validation: dict[str, Any], *, source_label: str) ->
|
|
| 208 |
validation_score = float(validation.get("validation_score", 0.0))
|
| 209 |
precision = float(validation.get("precision", 0.0))
|
| 210 |
recall = float(validation.get("recall", 0.0))
|
|
|
|
|
|
|
|
|
|
| 211 |
top_match = bool(validation.get("top_match"))
|
| 212 |
status_label = "Match" if top_match else "Mismatch"
|
| 213 |
status_class = "validation-pass" if top_match else "validation-warn"
|
|
@@ -226,6 +289,7 @@ def render_validation_html(validation: dict[str, Any], *, source_label: str) ->
|
|
| 226 |
<div class="validation-subtitle">
|
| 227 |
expected: {expected_langs}
|
| 228 |
| predicted: {predicted_langs}
|
|
|
|
| 229 |
| top: {top_lang.upper()}
|
| 230 |
| top score: {top_score:.1%}
|
| 231 |
| tp: {true_positive}
|
|
@@ -233,6 +297,8 @@ def render_validation_html(validation: dict[str, Any], *, source_label: str) ->
|
|
| 233 |
| fn: {false_negative}
|
| 234 |
| precision: {precision:.1%}
|
| 235 |
| recall: {recall:.1%}
|
|
|
|
|
|
|
| 236 |
</div>
|
| 237 |
</div>
|
| 238 |
"""
|
|
@@ -288,6 +354,25 @@ def render_language_reference_html() -> str:
|
|
| 288 |
"""
|
| 289 |
|
| 290 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
def fetch_random_cached_sentence() -> dict[str, Any]:
|
| 292 |
"""Randomly sample a sentence from either cached source."""
|
| 293 |
if random.random() < 0.5:
|
|
@@ -444,6 +529,8 @@ def predict(text: str) -> tuple[str, pd.DataFrame, dict[str, Any], dict[str, Any
|
|
| 444 |
|
| 445 |
nlp = get_pipeline()
|
| 446 |
entities = nlp(text)
|
|
|
|
|
|
|
| 447 |
|
| 448 |
rows: list[dict[str, Any]] = []
|
| 449 |
token_counts: Counter[str] = Counter()
|
|
@@ -531,9 +618,11 @@ def predict(text: str) -> tuple[str, pd.DataFrame, dict[str, Any], dict[str, Any
|
|
| 531 |
"entities": entities,
|
| 532 |
"selected_lang": dominant_lang,
|
| 533 |
"ranked_langs": [lang for lang, _ in ranked],
|
|
|
|
|
|
|
| 534 |
"text": text,
|
| 535 |
}
|
| 536 |
-
chip_updates = build_chip_button_updates(ranked, classifier_scores) if lang_stats else [gr.update(value="", visible=False) for _ in range(6)]
|
| 537 |
return summary, spans, raw, ui_state, "", *chip_updates
|
| 538 |
|
| 539 |
|
|
@@ -543,6 +632,7 @@ def load_random_tatoeba_example() -> tuple[str, str, pd.DataFrame, dict[str, Any
|
|
| 543 |
summary, spans, raw, ui_state, _, *chip_updates = predict(text)
|
| 544 |
validation = build_example_validation(
|
| 545 |
raw.get("classifier_scores", {}),
|
|
|
|
| 546 |
[sentence.get("lang_iso2", "")],
|
| 547 |
)
|
| 548 |
raw = {
|
|
@@ -573,6 +663,7 @@ def load_random_tatoeba_mix_example() -> tuple[str, str, pd.DataFrame, dict[str,
|
|
| 573 |
summary, spans, raw, ui_state, _, *chip_updates = predict(text)
|
| 574 |
validation = build_example_validation(
|
| 575 |
raw.get("classifier_scores", {}),
|
|
|
|
| 576 |
mix.get("langs", []),
|
| 577 |
)
|
| 578 |
raw = {
|
|
@@ -612,6 +703,7 @@ def load_random_fleurs_example() -> tuple[str, str, pd.DataFrame, dict[str, Any]
|
|
| 612 |
summary, spans, raw, ui_state, _, *chip_updates = predict(text)
|
| 613 |
validation = build_example_validation(
|
| 614 |
raw.get("classifier_scores", {}),
|
|
|
|
| 615 |
[sentence.get("lang_iso2", "")],
|
| 616 |
)
|
| 617 |
raw = {
|
|
@@ -653,6 +745,7 @@ def load_random_fleurs_mix_example() -> tuple[str, str, pd.DataFrame, dict[str,
|
|
| 653 |
summary, spans, raw, ui_state, _, *chip_updates = predict(text)
|
| 654 |
validation = build_example_validation(
|
| 655 |
raw.get("classifier_scores", {}),
|
|
|
|
| 656 |
mix.get("langs", []),
|
| 657 |
)
|
| 658 |
raw = {
|
|
|
|
| 12 |
import pandas as pd
|
| 13 |
import gradio as gr
|
| 14 |
import pycountry
|
| 15 |
+
import fasttext
|
| 16 |
+
from huggingface_hub import hf_hub_download
|
| 17 |
from transformers import AutoModelForTokenClassification, AutoTokenizer, pipeline
|
| 18 |
|
| 19 |
from fleurs_cache import fetch_random_fleurs_sentence, fetch_random_fleurs_sentence_mix
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
MODEL_CHECKPOINT = "DerivedFunction/polyglot-tagger-v2"
|
| 25 |
+
FASTTEXT_MODEL_REPO = "facebook/fasttext-language-identification"
|
| 26 |
+
FASTTEXT_MODEL_FILENAME = "model.bin"
|
| 27 |
MIN_ARTIFACT_SPAN_CHARS = 4
|
| 28 |
MIN_ARTIFACT_CONFIDENCE = 0.5
|
| 29 |
ARTIFACT_SPAN_WEIGHT = 0.35
|
|
|
|
| 42 |
)
|
| 43 |
|
| 44 |
|
| 45 |
+
@lru_cache(maxsize=1)
|
| 46 |
+
def get_fasttext_model():
|
| 47 |
+
"""Load the reference fastText language ID model once."""
|
| 48 |
+
model_path = hf_hub_download(repo_id=FASTTEXT_MODEL_REPO, filename=FASTTEXT_MODEL_FILENAME)
|
| 49 |
+
return fasttext.load_model(model_path)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
def normalize_label(label: str) -> str:
|
| 53 |
if label.startswith(("B-", "I-")):
|
| 54 |
label = label[2:]
|
|
|
|
| 126 |
def build_chip_button_updates(
|
| 127 |
ranked: list[tuple[str, dict[str, float | int]]],
|
| 128 |
classifier_scores: dict[str, float],
|
| 129 |
+
fasttext_scores: dict[str, float] | None = None,
|
| 130 |
max_chips: int = 6,
|
| 131 |
) -> list[dict[str, Any]]:
|
| 132 |
"""Return button updates for the top-ranked languages."""
|
| 133 |
+
fasttext_scores = fasttext_scores or {}
|
| 134 |
+
fasttext_ranked = sorted(fasttext_scores.items(), key=lambda item: item[1], reverse=True)
|
| 135 |
+
fasttext_rank = {lang: idx for idx, (lang, _) in enumerate(fasttext_ranked)}
|
| 136 |
+
model_ranked = [lang for lang, _ in ranked]
|
| 137 |
+
union_langs = sorted(
|
| 138 |
+
set(model_ranked) | set(fasttext_scores.keys()),
|
| 139 |
+
key=lambda lang: max(classifier_scores.get(lang, 0.0), fasttext_scores.get(lang, 0.0)),
|
| 140 |
+
reverse=True,
|
| 141 |
+
)
|
| 142 |
updates: list[dict[str, Any]] = []
|
| 143 |
for idx in range(max_chips):
|
| 144 |
+
if idx < len(union_langs):
|
| 145 |
+
lang = union_langs[idx]
|
| 146 |
+
model_score = classifier_scores.get(lang, 0.0)
|
| 147 |
+
fast_score = fasttext_scores.get(lang, 0.0)
|
| 148 |
+
in_fasttext = lang in fasttext_scores
|
| 149 |
+
in_model = model_score > 0.0
|
| 150 |
+
if in_model and in_fasttext:
|
| 151 |
+
variant = "primary"
|
| 152 |
+
elif in_fasttext:
|
| 153 |
+
variant = "secondary"
|
| 154 |
+
else:
|
| 155 |
+
variant = "stop"
|
| 156 |
+
source_tag = "both" if in_model and in_fasttext else ("ft" if in_fasttext else "model")
|
| 157 |
+
fast_rank = fasttext_rank.get(lang)
|
| 158 |
+
fast_rank_text = f" #{fast_rank + 1}" if fast_rank is not None else ""
|
| 159 |
updates.append(
|
| 160 |
gr.update(
|
| 161 |
+
value=f"{lang.upper()} M {model_score:.0%} | FT {fast_score:.0%}{fast_rank_text}",
|
| 162 |
visible=True,
|
| 163 |
+
variant=variant,
|
| 164 |
)
|
| 165 |
)
|
| 166 |
else:
|
|
|
|
| 192 |
|
| 193 |
def build_example_validation(
|
| 194 |
classifier_scores: dict[str, float],
|
| 195 |
+
reference_scores: dict[str, float] | None,
|
| 196 |
expected_langs: list[str],
|
| 197 |
) -> dict[str, Any]:
|
| 198 |
"""Compare derived scores against known source languages."""
|
|
|
|
| 211 |
precision = true_positive / (true_positive + false_positive) if (true_positive + false_positive) else 0.0
|
| 212 |
recall = true_positive / (true_positive + false_negative) if (true_positive + false_negative) else 0.0
|
| 213 |
validation_score = (2 * precision * recall / (precision + recall)) if (precision + recall) else 0.0
|
| 214 |
+
reference_scores = reference_scores or {}
|
| 215 |
+
reference_predicted = sorted(
|
| 216 |
+
(lang for lang, score in reference_scores.items() if score > 0.0),
|
| 217 |
+
key=lambda lang: reference_scores.get(lang, 0.0),
|
| 218 |
+
reverse=True,
|
| 219 |
+
)
|
| 220 |
+
reference_set = set(reference_predicted)
|
| 221 |
+
reference_tp = len(expected_set & reference_set)
|
| 222 |
+
reference_fp = len(reference_set - expected_set)
|
| 223 |
+
reference_fn = len(expected_set - reference_set)
|
| 224 |
+
reference_precision = reference_tp / (reference_tp + reference_fp) if (reference_tp + reference_fp) else 0.0
|
| 225 |
+
reference_recall = reference_tp / (reference_tp + reference_fn) if (reference_tp + reference_fn) else 0.0
|
| 226 |
+
reference_score = (
|
| 227 |
+
2 * reference_precision * reference_recall / (reference_precision + reference_recall)
|
| 228 |
+
if (reference_precision + reference_recall)
|
| 229 |
+
else 0.0
|
| 230 |
+
)
|
| 231 |
|
| 232 |
return {
|
| 233 |
"expected_langs": expected_langs,
|
| 234 |
"predicted_langs": predicted_langs,
|
| 235 |
+
"reference_langs": reference_predicted,
|
| 236 |
"top_lang": top_lang,
|
| 237 |
"top_score": top_score,
|
| 238 |
"true_positive": true_positive,
|
|
|
|
| 244 |
"recall": recall,
|
| 245 |
"top_match": false_positive == 0 and false_negative == 0,
|
| 246 |
"validation_score": validation_score,
|
| 247 |
+
"reference_true_positive": reference_tp,
|
| 248 |
+
"reference_false_positive": reference_fp,
|
| 249 |
+
"reference_false_negative": reference_fn,
|
| 250 |
+
"reference_precision": reference_precision,
|
| 251 |
+
"reference_recall": reference_recall,
|
| 252 |
+
"reference_score": reference_score,
|
| 253 |
}
|
| 254 |
|
| 255 |
|
|
|
|
| 268 |
validation_score = float(validation.get("validation_score", 0.0))
|
| 269 |
precision = float(validation.get("precision", 0.0))
|
| 270 |
recall = float(validation.get("recall", 0.0))
|
| 271 |
+
reference_score = float(validation.get("reference_score", 0.0))
|
| 272 |
+
reference_precision = float(validation.get("reference_precision", 0.0))
|
| 273 |
+
reference_recall = float(validation.get("reference_recall", 0.0))
|
| 274 |
top_match = bool(validation.get("top_match"))
|
| 275 |
status_label = "Match" if top_match else "Mismatch"
|
| 276 |
status_class = "validation-pass" if top_match else "validation-warn"
|
|
|
|
| 289 |
<div class="validation-subtitle">
|
| 290 |
expected: {expected_langs}
|
| 291 |
| predicted: {predicted_langs}
|
| 292 |
+
| vs: {reference_score:.1%}
|
| 293 |
| top: {top_lang.upper()}
|
| 294 |
| top score: {top_score:.1%}
|
| 295 |
| tp: {true_positive}
|
|
|
|
| 297 |
| fn: {false_negative}
|
| 298 |
| precision: {precision:.1%}
|
| 299 |
| recall: {recall:.1%}
|
| 300 |
+
| ref precision: {reference_precision:.1%}
|
| 301 |
+
| ref recall: {reference_recall:.1%}
|
| 302 |
</div>
|
| 303 |
</div>
|
| 304 |
"""
|
|
|
|
| 354 |
"""
|
| 355 |
|
| 356 |
|
| 357 |
+
def predict_fasttext(text: str, k: int = 5) -> dict[str, Any]:
|
| 358 |
+
"""Return fastText language predictions for comparison."""
|
| 359 |
+
model = get_fasttext_model()
|
| 360 |
+
labels, scores = model.predict(text, k=k)
|
| 361 |
+
predictions = [
|
| 362 |
+
{
|
| 363 |
+
"lang": label.removeprefix("__label__"),
|
| 364 |
+
"score": float(score),
|
| 365 |
+
}
|
| 366 |
+
for label, score in zip(labels, scores)
|
| 367 |
+
]
|
| 368 |
+
return {
|
| 369 |
+
"model": FASTTEXT_MODEL_REPO,
|
| 370 |
+
"predictions": predictions,
|
| 371 |
+
"top_lang": predictions[0]["lang"] if predictions else None,
|
| 372 |
+
"top_score": predictions[0]["score"] if predictions else 0.0,
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
|
| 376 |
def fetch_random_cached_sentence() -> dict[str, Any]:
|
| 377 |
"""Randomly sample a sentence from either cached source."""
|
| 378 |
if random.random() < 0.5:
|
|
|
|
| 529 |
|
| 530 |
nlp = get_pipeline()
|
| 531 |
entities = nlp(text)
|
| 532 |
+
fasttext_result = predict_fasttext(text)
|
| 533 |
+
fasttext_scores = {item["lang"]: item["score"] for item in fasttext_result.get("predictions", [])}
|
| 534 |
|
| 535 |
rows: list[dict[str, Any]] = []
|
| 536 |
token_counts: Counter[str] = Counter()
|
|
|
|
| 618 |
"entities": entities,
|
| 619 |
"selected_lang": dominant_lang,
|
| 620 |
"ranked_langs": [lang for lang, _ in ranked],
|
| 621 |
+
"fasttext": fasttext_result,
|
| 622 |
+
"fasttext_scores": fasttext_scores,
|
| 623 |
"text": text,
|
| 624 |
}
|
| 625 |
+
chip_updates = build_chip_button_updates(ranked, classifier_scores, fasttext_scores) if lang_stats else [gr.update(value="", visible=False) for _ in range(6)]
|
| 626 |
return summary, spans, raw, ui_state, "", *chip_updates
|
| 627 |
|
| 628 |
|
|
|
|
| 632 |
summary, spans, raw, ui_state, _, *chip_updates = predict(text)
|
| 633 |
validation = build_example_validation(
|
| 634 |
raw.get("classifier_scores", {}),
|
| 635 |
+
raw.get("fasttext_scores", {}),
|
| 636 |
[sentence.get("lang_iso2", "")],
|
| 637 |
)
|
| 638 |
raw = {
|
|
|
|
| 663 |
summary, spans, raw, ui_state, _, *chip_updates = predict(text)
|
| 664 |
validation = build_example_validation(
|
| 665 |
raw.get("classifier_scores", {}),
|
| 666 |
+
raw.get("fasttext_scores", {}),
|
| 667 |
mix.get("langs", []),
|
| 668 |
)
|
| 669 |
raw = {
|
|
|
|
| 703 |
summary, spans, raw, ui_state, _, *chip_updates = predict(text)
|
| 704 |
validation = build_example_validation(
|
| 705 |
raw.get("classifier_scores", {}),
|
| 706 |
+
raw.get("fasttext_scores", {}),
|
| 707 |
[sentence.get("lang_iso2", "")],
|
| 708 |
)
|
| 709 |
raw = {
|
|
|
|
| 745 |
summary, spans, raw, ui_state, _, *chip_updates = predict(text)
|
| 746 |
validation = build_example_validation(
|
| 747 |
raw.get("classifier_scores", {}),
|
| 748 |
+
raw.get("fasttext_scores", {}),
|
| 749 |
mix.get("langs", []),
|
| 750 |
)
|
| 751 |
raw = {
|
init_venv.py
CHANGED
|
@@ -38,7 +38,8 @@ BASE_PACKAGES = [
|
|
| 38 |
|
| 39 |
CUSTOM_PACKAGES = [
|
| 40 |
"gradio",
|
| 41 |
-
"pycountry"
|
|
|
|
| 42 |
]
|
| 43 |
|
| 44 |
# Packages for the classification server
|
|
|
|
| 38 |
|
| 39 |
CUSTOM_PACKAGES = [
|
| 40 |
"gradio",
|
| 41 |
+
"pycountry",
|
| 42 |
+
"fasttext",
|
| 43 |
]
|
| 44 |
|
| 45 |
# Packages for the classification server
|
requirements.txt
CHANGED
|
@@ -5,3 +5,5 @@ pandas
|
|
| 5 |
datasets
|
| 6 |
pyarrow
|
| 7 |
pycountry
|
|
|
|
|
|
|
|
|
| 5 |
datasets
|
| 6 |
pyarrow
|
| 7 |
pycountry
|
| 8 |
+
fasttext
|
| 9 |
+
huggingface_hub
|