Update app.py
Browse files
app.py
CHANGED
|
@@ -1,427 +1,703 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import
|
| 3 |
-
|
| 4 |
-
import pandas as pd
|
| 5 |
import gradio as gr
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
# ----------------------------
|
| 9 |
# Config
|
| 10 |
# ----------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
|
| 13 |
-
TAG_LABELS_PATH = "tag_labels.json"
|
| 14 |
-
TAG_OVERVIEW_CSV = "Sosialurin-BRAGD_tags.csv"
|
| 15 |
-
|
| 16 |
-
# HF Inference API token should be set as a Space secret:
|
| 17 |
-
# Settings -> Secrets -> BRAGD_API_TOKEN
|
| 18 |
-
HF_TOKEN = os.getenv("BRAGD_API_TOKEN", "")
|
| 19 |
-
|
| 20 |
-
client = InferenceClient(model=MODEL_REPO, token=HF_TOKEN)
|
| 21 |
-
|
| 22 |
-
# ----------------------------
|
| 23 |
-
# Styling
|
| 24 |
-
# ----------------------------
|
| 25 |
|
| 26 |
-
CSS = """
|
| 27 |
-
:
|
| 28 |
-
--primary-
|
| 29 |
-
--
|
| 30 |
-
--primary-600: #6f948e;
|
| 31 |
-
--page-bg: #f6f7f8;
|
| 32 |
-
--panel-bg: transparent;
|
| 33 |
-
--text: #111;
|
| 34 |
}
|
| 35 |
|
| 36 |
-
|
|
|
|
| 37 |
background: var(--page-bg) !important;
|
| 38 |
-
color: var(--text);
|
| 39 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
/*
|
| 42 |
-
.
|
| 43 |
-
background:
|
|
|
|
|
|
|
| 44 |
}
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
/*
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
#input_box textarea{
|
| 48 |
-
background:
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
/* Results header row */
|
| 73 |
#results_hdr{
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
}
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
cursor:pointer;
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
| 88 |
border:1px solid var(--primary-600);
|
|
|
|
| 89 |
color:#0b1b19;
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
margin:0 !important;
|
|
|
|
|
|
|
|
|
|
| 93 |
}
|
| 94 |
-
#
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
}
|
| 99 |
|
| 100 |
-
/*
|
| 101 |
-
|
| 102 |
-
background:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
}
|
| 104 |
-
"""
|
| 105 |
|
| 106 |
-
|
| 107 |
-
#
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
| 114 |
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
# ----------------------------
|
| 118 |
-
#
|
| 119 |
# ----------------------------
|
|
|
|
|
|
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
if
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
out = {}
|
| 138 |
-
for
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
return out
|
| 141 |
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
# ----------------------------
|
| 145 |
-
#
|
| 146 |
# ----------------------------
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
""
|
| 153 |
-
|
| 154 |
-
if
|
| 155 |
-
return []
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
# Here we assume a simple text_generation that returns a tagged output.
|
| 163 |
-
# --- Replace this part if your Space already had a working call ---
|
| 164 |
-
out = client.text_generation(sentence, max_new_tokens=256)
|
| 165 |
-
# If your existing app already parses output, keep that logic below.
|
| 166 |
-
except Exception as e:
|
| 167 |
-
raise gr.Error(f"Model call failed: {e}")
|
| 168 |
-
|
| 169 |
-
# Try to parse rows from output if it's already JSON-like; otherwise fallback to line parsing.
|
| 170 |
-
rows = []
|
| 171 |
-
if isinstance(out, (list, dict)):
|
| 172 |
-
# If API returns structured rows, normalize
|
| 173 |
-
data = out
|
| 174 |
-
if isinstance(out, dict) and "rows" in out:
|
| 175 |
-
data = out["rows"]
|
| 176 |
-
if isinstance(data, list):
|
| 177 |
-
for r in data:
|
| 178 |
-
if isinstance(r, dict) and {"word", "tag"} <= set(r.keys()):
|
| 179 |
-
rows.append({"word": r.get("word", ""), "tag": r.get("tag", ""), "analysis": r.get("analysis", "")})
|
| 180 |
-
return rows
|
| 181 |
-
|
| 182 |
-
text = str(out)
|
| 183 |
-
|
| 184 |
-
# Fallback: accept formats like "word<TAB>tag" per line or "word tag" etc.
|
| 185 |
-
for line in text.splitlines():
|
| 186 |
-
line = line.strip()
|
| 187 |
-
if not line:
|
| 188 |
-
continue
|
| 189 |
-
if "\t" in line:
|
| 190 |
-
w, t = line.split("\t", 1)
|
| 191 |
-
else:
|
| 192 |
-
parts = line.split()
|
| 193 |
-
if len(parts) < 2:
|
| 194 |
-
continue
|
| 195 |
-
w, t = parts[0], parts[1]
|
| 196 |
-
rows.append({"word": w, "tag": t, "analysis": ""})
|
| 197 |
-
return rows
|
| 198 |
|
| 199 |
# ----------------------------
|
| 200 |
-
#
|
| 201 |
# ----------------------------
|
|
|
|
| 202 |
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
return default
|
| 208 |
-
|
| 209 |
-
def analysis_text(tag: str, lang: str):
|
| 210 |
-
"""
|
| 211 |
-
Build the readable analysis string from a BRAGD tag.
|
| 212 |
-
Keeps your earlier “rules” (no random punctuation analysis, supine-only for luttøkuháttur, etc.)
|
| 213 |
-
"""
|
| 214 |
-
tag = (tag or "").strip()
|
| 215 |
-
if not tag:
|
| 216 |
-
return ""
|
| 217 |
-
|
| 218 |
-
# Punctuation tags: keep short
|
| 219 |
-
if tag == "KE":
|
| 220 |
-
return "teksetting, setningsendi" if lang == "fo" else "punctuation, end of sentence"
|
| 221 |
-
if tag in {"KC"}:
|
| 222 |
-
return "teksetting, komma" if lang == "fo" else "punctuation, comma"
|
| 223 |
-
|
| 224 |
-
# Pull out word class (first char)
|
| 225 |
-
wc = tag[0]
|
| 226 |
-
wc_label = label_for(lang, "word_class", wc, wc)
|
| 227 |
-
|
| 228 |
-
# If DGd (preposition) in Faroese, don’t show “eingin stigbending”
|
| 229 |
-
parts = [wc_label]
|
| 230 |
-
|
| 231 |
-
# Helpers: add label only if it’s not the “none” type for some categories
|
| 232 |
-
def add(group, k, skip_if=None):
|
| 233 |
-
val = label_for(lang, group, k, "")
|
| 234 |
-
if not val:
|
| 235 |
-
return
|
| 236 |
-
if skip_if and val == skip_if:
|
| 237 |
-
return
|
| 238 |
-
parts.append(val)
|
| 239 |
-
|
| 240 |
-
# Very lightweight heuristic parsing:
|
| 241 |
-
# This assumes your tag labels cover these keys.
|
| 242 |
-
# If your previous app had more detailed parsing, keep it and just keep the UI fixes in this file.
|
| 243 |
-
# Here we preserve the visible output style.
|
| 244 |
-
# Gender / number / case / etc are typically subsequent chars.
|
| 245 |
-
# We’ll attempt common positions, but safely ignore unknowns.
|
| 246 |
-
|
| 247 |
-
# Example mapping by position is model-specific; keep safe:
|
| 248 |
-
# gender (2nd char), number (3rd), case (4th), etc.
|
| 249 |
-
if len(tag) >= 2:
|
| 250 |
-
add("gender", tag[1], skip_if=("eingin kyn" if lang == "fo" else "no gender"))
|
| 251 |
-
if len(tag) >= 3:
|
| 252 |
-
add("number", tag[2])
|
| 253 |
-
if len(tag) >= 4:
|
| 254 |
-
add("case", tag[3])
|
| 255 |
-
|
| 256 |
-
# Degree / definiteness / declension etc can vary; try a few more chars without forcing nonsense.
|
| 257 |
-
for i, grp in [(4, "definiteness"), (5, "degree"), (6, "declension"), (7, "person"), (8, "tense"), (9, "mood"), (10, "voice")]:
|
| 258 |
-
if len(tag) > i:
|
| 259 |
-
# Special rule: Faroese luttøkuháttur (participle/supine) should only show supine + voice
|
| 260 |
-
# If the word class is participle (L), we avoid adding mood/tense/person noise.
|
| 261 |
-
if wc == "L" and grp in {"person", "mood", "tense"}:
|
| 262 |
-
continue
|
| 263 |
-
add(grp, tag[i])
|
| 264 |
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
parts = [p for p in parts if p != "eingin stigbending"]
|
| 268 |
|
| 269 |
-
|
| 270 |
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
|
|
|
|
|
|
| 274 |
|
| 275 |
-
def
|
| 276 |
-
""
|
| 277 |
-
Returns:
|
| 278 |
-
df_main: Word/Tag/Analysis table
|
| 279 |
-
df_mean: Expanded tags table (optional)
|
| 280 |
-
overview_md: overview markdown
|
| 281 |
-
"""
|
| 282 |
-
# Main table
|
| 283 |
-
if lang == "fo":
|
| 284 |
-
cols = ["Orð", "Mark", "Útgreining"]
|
| 285 |
-
else:
|
| 286 |
-
cols = ["Word", "Tag", "Analysis"]
|
| 287 |
|
| 288 |
-
|
| 289 |
-
for
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
data.append([w, t, a])
|
| 294 |
|
| 295 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
lines.append("")
|
|
|
|
| 323 |
|
| 324 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
# ----------------------------
|
| 329 |
|
| 330 |
-
|
| 331 |
-
state = gr.State([]) # stores last tagged rows
|
| 332 |
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
|
|
|
|
|
|
| 341 |
|
| 342 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
gr.Markdown(
|
| 344 |
-
"## Marka\n
|
| 345 |
"Skriv ein setning í kassan og fá hann markaðan.\n\n"
|
| 346 |
-
f"Myndil / Model: [{
|
| 347 |
)
|
| 348 |
-
btn = gr.Button("Marka / Tag",
|
|
|
|
|
|
|
|
|
|
| 349 |
|
| 350 |
# Hide results header + toggle until Tag
|
| 351 |
-
results_hdr = gr.Row(elem_id="results_hdr", visible=
|
| 352 |
with results_hdr:
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
show_label=False,
|
| 360 |
-
interactive=True,
|
| 361 |
-
elem_id="lang_radio",
|
| 362 |
-
)
|
| 363 |
|
| 364 |
out_df = gr.Dataframe(
|
| 365 |
-
value=pd.DataFrame(columns=["
|
| 366 |
-
interactive=False,
|
|
|
|
| 367 |
visible=False,
|
| 368 |
)
|
| 369 |
|
| 370 |
expanded_acc = gr.Accordion("Útgreinað marking / Expanded tags", open=False, visible=False)
|
| 371 |
with expanded_acc:
|
| 372 |
out_mean_df = gr.Dataframe(
|
| 373 |
-
value=pd.DataFrame(columns=["
|
| 374 |
-
interactive=False,
|
|
|
|
| 375 |
)
|
| 376 |
|
| 377 |
overview_acc = gr.Accordion("Markayvirlit / Tag Overview", open=False, visible=True)
|
| 378 |
with overview_acc:
|
| 379 |
-
overview_md = gr.Markdown(build_overview("fo")
|
| 380 |
|
| 381 |
-
|
| 382 |
-
# Callbacks
|
| 383 |
-
# ----------------------------
|
| 384 |
-
|
| 385 |
-
def on_tag(sentence, lang_value):
|
| 386 |
rows = run_model(sentence)
|
| 387 |
-
df_main, df_mean,
|
|
|
|
|
|
|
|
|
|
| 388 |
|
| 389 |
return (
|
| 390 |
rows,
|
| 391 |
gr.update(value=df_main, visible=True),
|
| 392 |
gr.update(value=df_mean),
|
| 393 |
-
gr.update(value=
|
| 394 |
-
gr.update(visible=True),
|
| 395 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
)
|
| 397 |
|
| 398 |
-
def
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
gr.update(),
|
| 404 |
-
gr.update(value=build_overview(lang_value)),
|
| 405 |
-
)
|
| 406 |
|
| 407 |
-
df_main, df_mean, _ = render(rows, lang_value)
|
| 408 |
return (
|
|
|
|
| 409 |
gr.update(value=df_main),
|
| 410 |
gr.update(value=df_mean),
|
| 411 |
-
gr.update(value=
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
)
|
| 413 |
|
| 414 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
btn.click(
|
| 416 |
on_tag,
|
| 417 |
-
inputs=[inp,
|
| 418 |
-
outputs=[state, out_df, out_mean_df, overview_md, expanded_acc,
|
|
|
|
|
|
|
| 419 |
)
|
| 420 |
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
queue=False,
|
| 426 |
)
|
| 427 |
|
|
|
|
| 1 |
+
import os, re, string, json
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
|
|
|
|
| 4 |
import gradio as gr
|
| 5 |
+
import torch
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
+
from transformers import AutoTokenizer, AutoModelForTokenClassification
|
| 9 |
|
| 10 |
# ----------------------------
|
| 11 |
# Config
|
| 12 |
# ----------------------------
|
| 13 |
+
MODEL_ID = "Setur/BRAGD"
|
| 14 |
+
TAGS_FILEPATH = "Sosialurin-BRAGD_tags.csv"
|
| 15 |
+
LABELS_FILEPATH = "tag_labels.json"
|
| 16 |
+
HF_TOKEN = os.getenv("BRAGD")
|
| 17 |
+
|
| 18 |
+
if not HF_TOKEN:
|
| 19 |
+
raise RuntimeError("Missing BRAGD token secret (Space → Settings → Secrets → BRAGD).")
|
| 20 |
+
if not os.path.exists(LABELS_FILEPATH):
|
| 21 |
+
raise RuntimeError(f"Missing {LABELS_FILEPATH}. Add it to the Space repo root.")
|
| 22 |
+
|
| 23 |
+
INTERVALS = (
|
| 24 |
+
(15, 29), (30, 33), (34, 36), (37, 41), (42, 43), (44, 45), (46, 50),
|
| 25 |
+
(51, 53), (54, 60), (61, 63), (64, 66), (67, 70), (71, 72)
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
GROUP_ORDER = ["subcategory","gender","number","case","article","proper","degree","declension","mood","voice","tense","person","definiteness"]
|
| 29 |
+
HIDE_CODES = {"subcategory": {"B"}} # Subcategory B to be removed
|
| 30 |
+
|
| 31 |
+
UI = {
|
| 32 |
+
"fo": {"w":"Orð", "t":"Mark", "s":"Útgreining", "m":"Útgreinað marking"},
|
| 33 |
+
"en": {"w":"Word","t":"Tag", "s":"Analysis", "m":"Expanded tags"},
|
| 34 |
+
}
|
| 35 |
|
| 36 |
+
MODEL_LINK = "https://huggingface.co/Setur/BRAGD"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
CSS = """:root{
|
| 39 |
+
--primary-500:#89AFA9; --primary-600:#6F9992; --primary-700:#5B7F79;
|
| 40 |
+
--primary-100:#E1ECEA; --primary-200:#C6DAD6;
|
| 41 |
+
--page-bg:#f7f7f8;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
}
|
| 43 |
|
| 44 |
+
/* Page background */
|
| 45 |
+
html, body, .gradio-container{
|
| 46 |
background: var(--page-bg) !important;
|
|
|
|
| 47 |
}
|
| 48 |
+
body, .gradio-container, .prose, .markdown, textarea, input, select, button, table{
|
| 49 |
+
font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, "Noto Sans", sans-serif !important;
|
| 50 |
+
}
|
| 51 |
+
a{ color:var(--primary-700)!important; }
|
| 52 |
|
| 53 |
+
/* Primary button (Marka/Tag) */
|
| 54 |
+
.gr-button-primary, button.primary, .primary{
|
| 55 |
+
background:var(--primary-500)!important;
|
| 56 |
+
border-color:var(--primary-600)!important;
|
| 57 |
+
color:#0b1b19!important;
|
| 58 |
}
|
| 59 |
+
.gr-button-primary:hover, button.primary:hover, .primary:hover{ background:var(--primary-600)!important; }
|
| 60 |
+
.gr-button-primary{ padding:0.35rem 0.85rem!important; font-size:0.95rem!important; }
|
| 61 |
|
| 62 |
+
/* --- Keep the textbox exactly as-is: wrapper blends with page, textarea stays white --- */
|
| 63 |
+
#input_col, #input_col *{
|
| 64 |
+
background: transparent !important;
|
| 65 |
+
}
|
| 66 |
+
#input_col .gr-block, #input_col .gr-panel, #input_col .gr-box, #input_col .gr-group, #input_col .gr-form{
|
| 67 |
+
background: transparent !important;
|
| 68 |
+
box-shadow:none !important;
|
| 69 |
+
border:0 !important;
|
| 70 |
+
}
|
| 71 |
+
#input_box, #input_box > div, #input_box .wrap, #input_box .container{
|
| 72 |
+
background: transparent !important;
|
| 73 |
+
box-shadow:none !important;
|
| 74 |
+
border:0 !important;
|
| 75 |
+
}
|
| 76 |
#input_box textarea{
|
| 77 |
+
background:#ffffff !important;
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
/* Dataframe columns: keep Orð + Mark single-line */
|
| 81 |
+
.gr-dataframe table td:nth-child(1), .gr-dataframe table th:nth-child(1){
|
| 82 |
+
white-space: nowrap !important; width: 18% !important;
|
| 83 |
+
}
|
| 84 |
+
.gr-dataframe table td:nth-child(2), .gr-dataframe table th:nth-child(2){
|
| 85 |
+
white-space: nowrap !important; width: 18% !important;
|
| 86 |
+
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace !important;
|
| 87 |
+
}
|
| 88 |
+
.gr-dataframe table td:nth-child(3), .gr-dataframe table th:nth-child(3){
|
| 89 |
+
white-space: normal !important; width: 64% !important;
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
/* Selected = match Marka/Tag exactly */
|
| 93 |
+
/* Hover = subtle */
|
| 94 |
+
/* Keep selected button color on hover; only lighten UNSELECTED on hover */
|
| 95 |
+
/* Push language buttons fully to the right */
|
| 96 |
+
#results_hdr > .gr-markdown{
|
| 97 |
+
flex:1 1 auto !important;
|
| 98 |
+
}
|
| 99 |
+
/* Results header row: two-column layout, title left, toggle hard-right */
|
|
|
|
|
|
|
| 100 |
#results_hdr{
|
| 101 |
+
display:grid !important;
|
| 102 |
+
grid-template-columns: 1fr auto !important;
|
| 103 |
+
align-items:center !important;
|
| 104 |
+
gap:12px !important;
|
| 105 |
+
padding:0 !important;
|
| 106 |
+
margin:0 !important;
|
| 107 |
+
background:transparent !important;
|
| 108 |
+
box-shadow:none !important;
|
| 109 |
+
border:0 !important;
|
| 110 |
+
}
|
| 111 |
+
#results_hdr > .gr-column:first-child{ justify-self:start !important; }
|
| 112 |
+
#results_hdr > .gr-column:last-child{ justify-self:end !important; }
|
| 113 |
+
|
| 114 |
+
/* Language toggle (gr.Radio): style the LABEL as the button (robust across Gradio DOM variants) */
|
| 115 |
+
.lang_toggle{
|
| 116 |
+
background: transparent !important;
|
| 117 |
+
justify-self:end !important;
|
| 118 |
+
}
|
| 119 |
+
.lang_toggle fieldset{
|
| 120 |
+
border:0!important;
|
| 121 |
+
padding:0!important;
|
| 122 |
+
margin:0!important;
|
| 123 |
+
background:transparent!important;
|
| 124 |
+
}
|
| 125 |
+
.lang_toggle .wrap{
|
| 126 |
+
display:flex!important;
|
| 127 |
+
gap:10px!important;
|
| 128 |
+
background:transparent!important;
|
| 129 |
+
padding:0!important;
|
| 130 |
+
margin:0!important;
|
| 131 |
+
}
|
| 132 |
+
.lang_toggle input{
|
| 133 |
+
display:none!important;
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
/* Kill any default Gradio "pill" styling inside */
|
| 137 |
+
.lang_toggle label *{
|
| 138 |
+
background:transparent!important;
|
| 139 |
+
box-shadow:none!important;
|
| 140 |
+
border:0!important;
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
/* The actual button */
|
| 144 |
+
.lang_toggle label{
|
| 145 |
+
display:inline-flex !important;
|
| 146 |
+
align-items:center !important;
|
| 147 |
+
justify-content:center !important;
|
| 148 |
+
cursor:pointer !important;
|
| 149 |
+
user-select:none !important;
|
| 150 |
+
|
| 151 |
+
padding:0.35rem 0.85rem !important;
|
| 152 |
+
font-size:0.95rem !important;
|
| 153 |
+
border-radius:10px !important;
|
| 154 |
+
|
| 155 |
+
border:1px solid var(--primary-600) !important;
|
| 156 |
+
background: var(--primary-200) !important; /* inactive: lighter than #89AFA9 */
|
| 157 |
+
color:#0b1b19 !important; /* black-ish */
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
/* Active/selected */
|
| 161 |
+
.lang_toggle label:has(input:checked){
|
| 162 |
+
background: #89AFA9 !important;
|
| 163 |
+
border-color: var(--primary-600) !important;
|
| 164 |
+
color:#0b1b19 !important;
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
/* Hover: show #89AFA9 (inactive becomes active color on hover) */
|
| 168 |
+
.lang_toggle label:hover{
|
| 169 |
+
background:#89AFA9 !important;
|
| 170 |
+
border-color: var(--primary-600) !important;
|
| 171 |
+
color:#0b1b19 !important;
|
| 172 |
}
|
| 173 |
|
| 174 |
+
|
| 175 |
+
/* Remove Gradio's default label styling completely */
|
| 176 |
+
.lang_toggle label{
|
| 177 |
+
background:transparent!important;
|
| 178 |
+
border:0!important;
|
| 179 |
+
padding:0!important;
|
| 180 |
+
margin:0!important;
|
| 181 |
+
box-shadow:none!important;
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
/* Single visible button layer */
|
| 185 |
+
.lang_toggle label span{
|
| 186 |
+
all: unset;
|
| 187 |
+
display:inline-block;
|
| 188 |
cursor:pointer;
|
| 189 |
+
user-select:none;
|
| 190 |
+
padding:0.35rem 0.85rem;
|
| 191 |
+
font-size:0.95rem;
|
| 192 |
+
border-radius:10px;
|
| 193 |
border:1px solid var(--primary-600);
|
| 194 |
+
background: transparent; /* same as page */
|
| 195 |
color:#0b1b19;
|
| 196 |
+
box-shadow:none!important;
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
/* Selected state (robust selectors) */
|
| 200 |
+
.lang_toggle input:checked ~ span,
|
| 201 |
+
.lang_toggle label:has(input:checked) span{
|
| 202 |
+
background:var(--primary-500)!important;
|
| 203 |
+
border-color:var(--primary-600)!important;
|
| 204 |
+
color:#0b1b19!important;
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
/* Hover: only unselected gets light background */
|
| 208 |
+
.lang_toggle label:hover input:not(:checked) ~ span,
|
| 209 |
+
.lang_toggle label:hover:not(:has(input:checked)) span{
|
| 210 |
+
background:var(--primary-200)!important;
|
| 211 |
+
}
|
| 212 |
+
/* --- Language buttons (robust: 4 real buttons, show/hide to indicate active) --- */
|
| 213 |
+
#results_hdr{
|
| 214 |
+
display:grid !important;
|
| 215 |
+
grid-template-columns: 1fr auto !important;
|
| 216 |
+
align-items:center !important;
|
| 217 |
+
gap:12px !important;
|
| 218 |
+
padding:0 !important;
|
| 219 |
margin:0 !important;
|
| 220 |
+
background:transparent !important;
|
| 221 |
+
box-shadow:none !important;
|
| 222 |
+
border:0 !important;
|
| 223 |
}
|
| 224 |
+
#lang_buttons{
|
| 225 |
+
display:flex !important;
|
| 226 |
+
gap:10px !important;
|
| 227 |
+
justify-content:flex-end !important;
|
| 228 |
+
align-items:center !important;
|
| 229 |
+
flex-wrap:nowrap !important;
|
| 230 |
+
}
|
| 231 |
+
#lang_buttons .gr-button, #lang_buttons button{
|
| 232 |
+
padding:0.35rem 0.85rem !important;
|
| 233 |
+
font-size:0.95rem !important;
|
| 234 |
+
border-radius:10px !important;
|
| 235 |
}
|
| 236 |
|
| 237 |
+
/* Inactive: lighter than #89AFA9, black text */
|
| 238 |
+
#lang_fo_off, #lang_en_off{
|
| 239 |
+
background:var(--primary-200) !important;
|
| 240 |
+
border-color:var(--primary-600) !important;
|
| 241 |
+
color:#0b1b19 !important;
|
| 242 |
+
}
|
| 243 |
+
/* Hover inactive -> active color (#89AFA9) */
|
| 244 |
+
#lang_fo_off:hover, #lang_en_off:hover{
|
| 245 |
+
background:var(--primary-500) !important;
|
| 246 |
+
border-color:var(--primary-600) !important;
|
| 247 |
+
color:#0b1b19 !important;
|
| 248 |
+
}
|
| 249 |
+
/* Active: ensure black text */
|
| 250 |
+
#lang_fo_on, #lang_en_on{
|
| 251 |
+
color:#0b1b19 !important;
|
| 252 |
}
|
|
|
|
| 253 |
|
| 254 |
+
/* Keep header transparent, but DON'T nuke button backgrounds */
|
| 255 |
+
#results_hdr, #results_hdr > div{
|
| 256 |
+
background:transparent !important;
|
| 257 |
+
box-shadow:none !important;
|
| 258 |
+
border:0 !important;
|
| 259 |
+
}
|
| 260 |
|
| 261 |
+
/* Prevent Gradio from stacking/stretching language buttons */
|
| 262 |
+
#lang_buttons .gr-button, #lang_buttons button{
|
| 263 |
+
width:auto !important;
|
| 264 |
+
min-width:120px !important;
|
| 265 |
+
flex:0 0 auto !important;
|
| 266 |
+
}
|
| 267 |
|
| 268 |
+
/* Language button colors */
|
| 269 |
+
#lang_buttons .gr-button-primary, #lang_buttons button.primary{
|
| 270 |
+
background:#89AFA9 !important;
|
| 271 |
+
border-color:#6F9992 !important;
|
| 272 |
+
color:#0b1b19 !important;
|
| 273 |
+
}
|
| 274 |
+
#lang_buttons .gr-button-secondary, #lang_buttons button.secondary{
|
| 275 |
+
background:#C6DAD6 !important; /* light green */
|
| 276 |
+
border-color:#6F9992 !important;
|
| 277 |
+
color:#0b1b19 !important;
|
| 278 |
+
}
|
| 279 |
+
#lang_buttons .gr-button-secondary:hover, #lang_buttons button.secondary:hover{
|
| 280 |
+
background:#89AFA9 !important;
|
| 281 |
+
border-color:#6F9992 !important;
|
| 282 |
+
color:#0b1b19 !important;
|
| 283 |
+
}
|
| 284 |
+
"""
|
| 285 |
|
| 286 |
# ----------------------------
|
| 287 |
+
# Tokenization
|
| 288 |
# ----------------------------
|
| 289 |
+
def simp_tok(sentence: str):
|
| 290 |
+
return re.findall(r"\w+|[" + re.escape(string.punctuation) + "]", sentence)
|
| 291 |
|
| 292 |
+
# ----------------------------
|
| 293 |
+
# CSV mapping
|
| 294 |
+
# ----------------------------
|
| 295 |
+
def load_tag_mappings(path: str):
|
| 296 |
+
df = pd.read_csv(path)
|
| 297 |
+
feature_cols = list(df.columns[1:])
|
| 298 |
+
tag_to_features = {row["Original Tag"]: row[1:].values.astype(int) for _, row in df.iterrows()}
|
| 299 |
+
features_to_tag = {tuple(row[1:].values.astype(int)): row["Original Tag"] for _, row in df.iterrows()}
|
| 300 |
+
return tag_to_features, features_to_tag, len(feature_cols), feature_cols
|
| 301 |
+
|
| 302 |
+
def group_from_col(col: str):
|
| 303 |
+
if col == "Article": return ("article","A")
|
| 304 |
+
if col.startswith("No-Article "): return ("article", col.split()[-1])
|
| 305 |
+
if col == "Proper Noun": return ("proper","P")
|
| 306 |
+
if col.startswith("Not-Proper-Noun "): return ("proper", col.split()[-1])
|
| 307 |
+
|
| 308 |
+
prefixes = [
|
| 309 |
+
("Word Class ","word_class"),
|
| 310 |
+
("Subcategory ","subcategory"), ("No-Subcategory ","subcategory"),
|
| 311 |
+
("Gender ","gender"), ("No-Gender ","gender"),
|
| 312 |
+
("Number ","number"), ("No-Number ","number"),
|
| 313 |
+
("Case ","case"), ("No-Case ","case"),
|
| 314 |
+
("Degree ","degree"), ("No-Degree ","degree"),
|
| 315 |
+
("Declension ","declension"), ("No-Declension ","declension"),
|
| 316 |
+
("Mood ","mood"),
|
| 317 |
+
("Voice ","voice"), ("No-Voice ","voice"),
|
| 318 |
+
("Tense ","tense"), ("No-Tense ","tense"),
|
| 319 |
+
("Person ","person"), ("No-Person ","person"),
|
| 320 |
+
("Definite ","definiteness"), ("Indefinite ","definiteness"),
|
| 321 |
+
]
|
| 322 |
+
for p,g in prefixes:
|
| 323 |
+
if col.startswith(p):
|
| 324 |
+
return (g, col.split()[-1])
|
| 325 |
+
return (None,None)
|
| 326 |
+
|
| 327 |
+
def process_tag_features(tag_to_features: dict, intervals):
|
| 328 |
+
arrs = [np.array(tpl) for tpl in set(tuple(a) for a in tag_to_features.values())]
|
| 329 |
+
wt_masks = {wt:[a for a in arrs if a[wt]==1] for wt in range(15)}
|
| 330 |
out = {}
|
| 331 |
+
for wt,labels in wt_masks.items():
|
| 332 |
+
if not labels:
|
| 333 |
+
out[wt]=[]
|
| 334 |
+
continue
|
| 335 |
+
sum_labels = np.sum(np.array(labels), axis=0)
|
| 336 |
+
out[wt] = [iv for iv in intervals if np.sum(sum_labels[iv[0]:iv[1]+1]) != 0]
|
| 337 |
return out
|
| 338 |
|
| 339 |
+
def predict_vectors(logits, attention_mask, begin_tokens, dict_intervals, vec_len):
|
| 340 |
+
softmax = torch.nn.Softmax(dim=0)
|
| 341 |
+
vectors = []
|
| 342 |
+
for idx in range(len(logits)):
|
| 343 |
+
if attention_mask[idx].item()!=1 or begin_tokens[idx]!=1:
|
| 344 |
+
continue
|
| 345 |
+
pred = logits[idx]
|
| 346 |
+
vec = torch.zeros(vec_len, device=logits.device)
|
| 347 |
+
wt = torch.argmax(softmax(pred[0:15])).item()
|
| 348 |
+
vec[wt]=1
|
| 349 |
+
for (a,b) in dict_intervals.get(wt, []):
|
| 350 |
+
seg = pred[a:b+1]
|
| 351 |
+
k = torch.argmax(softmax(seg)).item()
|
| 352 |
+
vec[a+k]=1
|
| 353 |
+
vectors.append(vec)
|
| 354 |
+
return vectors
|
| 355 |
|
| 356 |
# ----------------------------
|
| 357 |
+
# Load labels
|
| 358 |
# ----------------------------
|
| 359 |
+
with open(LABELS_FILEPATH, "r", encoding="utf-8") as f:
|
| 360 |
+
LABELS = json.load(f)
|
| 361 |
+
|
| 362 |
+
def label_for(lang: str, group: str, wc: str, code: str) -> str:
|
| 363 |
+
lang = "fo" if lang=="fo" else "en"
|
| 364 |
+
by_wc = LABELS.get(lang, {}).get("by_word_class", {})
|
| 365 |
+
glob = LABELS.get(lang, {}).get("global", {})
|
| 366 |
+
if wc and wc in by_wc and code in by_wc[wc].get(group, {}):
|
| 367 |
+
return by_wc[wc][group][code]
|
| 368 |
+
return glob.get(group, {}).get(code, "")
|
| 369 |
+
|
| 370 |
+
def clean_label(s: str) -> str:
|
| 371 |
+
s = (s or "").strip()
|
| 372 |
+
s = re.sub(r"\s+", " ", s)
|
| 373 |
+
return s.strip(" -;,:").strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
|
| 375 |
# ----------------------------
|
| 376 |
+
# Load model + mapping
|
| 377 |
# ----------------------------
|
| 378 |
+
tag_to_features, features_to_tag, VEC_LEN, FEATURE_COLS = load_tag_mappings(TAGS_FILEPATH)
|
| 379 |
|
| 380 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, token=HF_TOKEN)
|
| 381 |
+
model = AutoModelForTokenClassification.from_pretrained(MODEL_ID, token=HF_TOKEN)
|
| 382 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 383 |
+
model.to(device); model.eval()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
|
| 385 |
+
if hasattr(model, "config") and hasattr(model.config, "num_labels") and model.config.num_labels != VEC_LEN:
|
| 386 |
+
raise RuntimeError(f"Label size mismatch: model={model.config.num_labels}, csv={VEC_LEN}. Wrong CSV?")
|
|
|
|
| 387 |
|
| 388 |
+
DICT_INTERVALS = process_tag_features(tag_to_features, INTERVALS)
|
| 389 |
|
| 390 |
+
GROUPS = defaultdict(list)
|
| 391 |
+
for i,col in enumerate(FEATURE_COLS):
|
| 392 |
+
g,code = group_from_col(col)
|
| 393 |
+
if g and code not in HIDE_CODES.get(g, set()):
|
| 394 |
+
GROUPS[g].append((i, code, col))
|
| 395 |
|
| 396 |
+
def vector_to_tag(vec: torch.Tensor) -> str:
|
| 397 |
+
return features_to_tag.get(tuple(vec.int().tolist()), "Unknown Tag")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
|
| 399 |
+
def wc_code(vec: torch.Tensor) -> str:
|
| 400 |
+
for idx,code,_ in GROUPS["word_class"]:
|
| 401 |
+
if int(vec[idx].item())==1:
|
| 402 |
+
return code
|
| 403 |
+
return ""
|
|
|
|
| 404 |
|
| 405 |
+
def group_code(vec: torch.Tensor, group: str) -> str:
|
| 406 |
+
hidden = HIDE_CODES.get(group, set())
|
| 407 |
+
for idx,code,_ in GROUPS.get(group, []):
|
| 408 |
+
if code in hidden:
|
| 409 |
+
continue
|
| 410 |
+
if int(vec[idx].item())==1:
|
| 411 |
+
return code
|
| 412 |
+
return ""
|
| 413 |
+
|
| 414 |
+
HIDE_IN_ANALYSIS = {("D","subcategory","G"), ("D","subcategory","N")}
|
| 415 |
+
VOICE_ANALYSIS = {
|
| 416 |
+
"fo": {"A": "gerðsøgn", "M": "miðalsøgn", "v": "orð luttøkuháttur"},
|
| 417 |
+
"en": {"A": "active voice", "M": "middle voice", "v": "supine form"},
|
| 418 |
+
}
|
| 419 |
|
| 420 |
+
def analysis_text(vec: torch.Tensor, lang: str) -> str:
|
| 421 |
+
lang = "fo" if lang=="fo" else "en"
|
| 422 |
+
tag = vector_to_tag(vec)
|
| 423 |
+
wc = wc_code(vec)
|
| 424 |
+
|
| 425 |
+
if tag == "DGd":
|
| 426 |
+
return "fyriseting" if lang=="fo" else "preposition"
|
| 427 |
+
|
| 428 |
+
mood = group_code(vec, "mood")
|
| 429 |
+
if mood == "U":
|
| 430 |
+
sup = label_for(lang, "mood", wc, "U") or ("luttøkuháttur" if lang=="fo" else "supine")
|
| 431 |
+
vcode = group_code(vec, "voice") or "v"
|
| 432 |
+
vlabel = VOICE_ANALYSIS[lang].get(vcode, VOICE_ANALYSIS[lang]["v"])
|
| 433 |
+
return f"{clean_label(sup)}, {clean_label(vlabel)}"
|
| 434 |
+
|
| 435 |
+
parts = []
|
| 436 |
+
if wc in {"P","C"}:
|
| 437 |
+
subc = group_code(vec, "subcategory")
|
| 438 |
+
subl = clean_label(label_for(lang, "subcategory", wc, subc) or "")
|
| 439 |
+
if subl:
|
| 440 |
+
parts.append(subl)
|
| 441 |
+
else:
|
| 442 |
+
wcl = clean_label(label_for(lang, "word_class", wc, wc) or wc)
|
| 443 |
+
if wcl:
|
| 444 |
+
parts.append(wcl)
|
| 445 |
|
| 446 |
+
for g in GROUP_ORDER:
|
| 447 |
+
c = group_code(vec, g)
|
| 448 |
+
if not c:
|
| 449 |
+
continue
|
| 450 |
+
if wc in {"P","C"} and g == "subcategory":
|
| 451 |
+
continue
|
| 452 |
+
if (wc, g, c) in HIDE_IN_ANALYSIS:
|
| 453 |
+
continue
|
| 454 |
+
lbl = clean_label(label_for(lang, g, wc, c) or label_for(lang, g, "", c) or "")
|
| 455 |
+
if lbl and lbl not in parts:
|
| 456 |
+
parts.append(lbl)
|
| 457 |
+
|
| 458 |
+
return ", ".join(parts)
|
| 459 |
+
|
| 460 |
+
def expanded_text(vec: torch.Tensor, lang: str) -> str:
|
| 461 |
+
lang = "fo" if lang=="fo" else "en"
|
| 462 |
+
wc = wc_code(vec)
|
| 463 |
+
parts = []
|
| 464 |
+
wc_lbl = label_for(lang, "word_class", wc, wc)
|
| 465 |
+
parts.append(f"{wc} – {wc_lbl}" if wc_lbl else wc)
|
| 466 |
+
for g in GROUP_ORDER:
|
| 467 |
+
c = group_code(vec, g)
|
| 468 |
+
if not c:
|
| 469 |
+
continue
|
| 470 |
+
lbl = label_for(lang, g, wc, c) or label_for(lang, g, "", c)
|
| 471 |
+
parts.append(f"{c} – {lbl}" if lbl else c)
|
| 472 |
+
return "; ".join([p for p in parts if p])
|
| 473 |
+
|
| 474 |
+
def compute_codes_by_wc():
|
| 475 |
+
codes = defaultdict(lambda: defaultdict(set))
|
| 476 |
+
for arr in tag_to_features.values():
|
| 477 |
+
arr = np.array(arr)
|
| 478 |
+
wc = None
|
| 479 |
+
for idx,code,_ in GROUPS["word_class"]:
|
| 480 |
+
if arr[idx]==1:
|
| 481 |
+
wc = code
|
| 482 |
+
break
|
| 483 |
+
if not wc:
|
| 484 |
+
continue
|
| 485 |
+
for g in GROUP_ORDER:
|
| 486 |
+
hidden = HIDE_CODES.get(g, set())
|
| 487 |
+
for idx,code,_ in GROUPS.get(g, []):
|
| 488 |
+
if code in hidden:
|
| 489 |
+
continue
|
| 490 |
+
if arr[idx]==1:
|
| 491 |
+
codes[wc][g].add(code)
|
| 492 |
+
return codes
|
| 493 |
+
|
| 494 |
+
CODES_BY_WC = compute_codes_by_wc()
|
| 495 |
+
|
| 496 |
+
def build_overview(lang: str) -> str:
|
| 497 |
+
lang = "fo" if lang=="fo" else "en"
|
| 498 |
+
title = "### Markayvirlit" if lang=="fo" else "### Tag Overview"
|
| 499 |
+
lines = [title, ""]
|
| 500 |
+
for wc in sorted(CODES_BY_WC.keys()):
|
| 501 |
+
wcl = label_for(lang, "word_class", wc, wc) or ""
|
| 502 |
+
lines.append(f"#### {wc} — {wcl}" if wcl else f"#### {wc}")
|
| 503 |
+
for g in GROUP_ORDER:
|
| 504 |
+
cs = sorted(CODES_BY_WC[wc].get(g, set()))
|
| 505 |
+
if not cs:
|
| 506 |
+
continue
|
| 507 |
+
group_name = {
|
| 508 |
+
"fo": {"subcategory":"Undirflokkur","gender":"Kyn","number":"Tal","case":"Fall","article":"Bundni/óbundni",
|
| 509 |
+
"proper":"Sernavn / felagsnavn","degree":"Stig","declension":"Bending","mood":"Háttur","voice":"Søgn",
|
| 510 |
+
"tense":"Tíð","person":"Persónur","definiteness":"Bundni/óbundni"},
|
| 511 |
+
"en": {"subcategory":"Subcategory","gender":"Gender","number":"Number","case":"Case","article":"Definiteness",
|
| 512 |
+
"proper":"Proper/common noun","degree":"Degree","declension":"Declension","mood":"Mood","voice":"Voice",
|
| 513 |
+
"tense":"Tense","person":"Person","definiteness":"Definiteness"},
|
| 514 |
+
}[lang].get(g, g)
|
| 515 |
+
lines.append(f"**{group_name}**")
|
| 516 |
+
for c in cs:
|
| 517 |
+
lbl = label_for(lang, g, wc, c) or label_for(lang, g, "", c)
|
| 518 |
+
lines.append(f"- `{c}` — {lbl}" if lbl else f"- `{c}`")
|
| 519 |
+
lines.append("")
|
| 520 |
lines.append("")
|
| 521 |
+
return "\n".join(lines).strip()
|
| 522 |
|
| 523 |
+
def run_model(sentence: str):
|
| 524 |
+
s = (sentence or "").strip()
|
| 525 |
+
if not s:
|
| 526 |
+
return []
|
| 527 |
+
tokens = simp_tok(s)
|
| 528 |
+
if not tokens:
|
| 529 |
+
return []
|
| 530 |
+
enc = tokenizer(tokens, is_split_into_words=True, add_special_tokens=True, max_length=128,
|
| 531 |
+
padding="max_length", truncation=True, return_attention_mask=True, return_tensors="pt")
|
| 532 |
+
input_ids = enc["input_ids"].to(device)
|
| 533 |
+
attention_mask = enc["attention_mask"].to(device)
|
| 534 |
+
word_ids = enc.word_ids(batch_index=0)
|
| 535 |
+
|
| 536 |
+
begin, last = [], None
|
| 537 |
+
for wid in word_ids:
|
| 538 |
+
if wid is None:
|
| 539 |
+
begin.append(0)
|
| 540 |
+
elif wid != last:
|
| 541 |
+
begin.append(1)
|
| 542 |
+
else:
|
| 543 |
+
begin.append(0)
|
| 544 |
+
last = wid
|
| 545 |
|
| 546 |
+
with torch.no_grad():
|
| 547 |
+
logits = model(input_ids=input_ids, attention_mask=attention_mask).logits[0]
|
|
|
|
| 548 |
|
| 549 |
+
vectors = predict_vectors(logits, attention_mask[0], begin, DICT_INTERVALS, VEC_LEN)
|
|
|
|
| 550 |
|
| 551 |
+
rows, vec_i, seen = [], 0, set()
|
| 552 |
+
for i,wid in enumerate(word_ids):
|
| 553 |
+
if wid is None or begin[i]!=1 or wid in seen:
|
| 554 |
+
continue
|
| 555 |
+
seen.add(wid)
|
| 556 |
+
word = tokens[wid] if wid < len(tokens) else "<UNK>"
|
| 557 |
+
vec = vectors[vec_i] if vec_i < len(vectors) else torch.zeros(VEC_LEN, device=device)
|
| 558 |
+
rows.append({"word": word, "vec": vec.int().tolist()})
|
| 559 |
+
vec_i += 1
|
| 560 |
+
return rows
|
| 561 |
|
| 562 |
+
def render(rows_state, lang: str):
|
| 563 |
+
lang = "fo" if lang=="fo" else "en"
|
| 564 |
+
df_cols = [UI[lang]["w"], UI[lang]["t"], UI[lang]["s"]]
|
| 565 |
+
dfm_cols = [UI[lang]["w"], UI[lang]["t"], UI[lang]["m"]]
|
| 566 |
+
if not rows_state:
|
| 567 |
+
return (pd.DataFrame(columns=df_cols), pd.DataFrame(columns=dfm_cols), build_overview(lang))
|
| 568 |
+
out_main, out_mean = [], []
|
| 569 |
+
for r in rows_state:
|
| 570 |
+
vec = torch.tensor(r["vec"])
|
| 571 |
+
tag = vector_to_tag(vec)
|
| 572 |
+
out_main.append([r["word"], tag, analysis_text(vec, lang)])
|
| 573 |
+
out_mean.append([r["word"], tag, expanded_text(vec, lang)])
|
| 574 |
+
return (pd.DataFrame(out_main, columns=df_cols), pd.DataFrame(out_mean, columns=dfm_cols), build_overview(lang))
|
| 575 |
+
|
| 576 |
+
theme = gr.themes.Soft()
|
| 577 |
+
|
| 578 |
+
with gr.Blocks(theme=theme, css=CSS, title="Marka") as demo:
|
| 579 |
+
with gr.Row(equal_height=True):
|
| 580 |
+
with gr.Column(scale=2, elem_id="input_col"):
|
| 581 |
+
inp = gr.Textbox(lines=6, placeholder="Skriva her ... / Type here ...", show_label=False, elem_id="input_box")
|
| 582 |
+
with gr.Column(scale=1, min_width=320):
|
| 583 |
gr.Markdown(
|
| 584 |
+
"## Marka\n"
|
| 585 |
"Skriv ein setning í kassan og fá hann markaðan.\n\n"
|
| 586 |
+
f"Myndil / Model: [{MODEL_ID}]({MODEL_LINK})"
|
| 587 |
)
|
| 588 |
+
btn = gr.Button("Marka / Tag", variant="primary")
|
| 589 |
+
|
| 590 |
+
state = gr.State([])
|
| 591 |
+
lang_state = gr.State("fo")
|
| 592 |
|
| 593 |
# Hide results header + toggle until Tag
|
| 594 |
+
results_hdr = gr.Row(elem_id="results_hdr", visible=True)
|
| 595 |
with results_hdr:
|
| 596 |
+
results_title = gr.Markdown("### Úrslit / Results")
|
| 597 |
+
with gr.Row(elem_id="lang_buttons"):
|
| 598 |
+
btn_lang_fo_on = gr.Button("Føroyskt", variant="primary", elem_id="lang_fo_on", visible=True)
|
| 599 |
+
btn_lang_fo_off = gr.Button("Føroyskt", variant="secondary", elem_id="lang_fo_off", visible=False)
|
| 600 |
+
btn_lang_en_on = gr.Button("English", variant="primary", elem_id="lang_en_on", visible=False)
|
| 601 |
+
btn_lang_en_off = gr.Button("English", variant="secondary", elem_id="lang_en_off", visible=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 602 |
|
| 603 |
out_df = gr.Dataframe(
|
| 604 |
+
value=pd.DataFrame(columns=[UI["fo"]["w"], UI["fo"]["t"], UI["fo"]["s"]]),
|
| 605 |
+
wrap=True, interactive=False, show_label=False,
|
| 606 |
+
row_count=(0, "fixed"), col_count=(3, "fixed"),
|
| 607 |
visible=False,
|
| 608 |
)
|
| 609 |
|
| 610 |
expanded_acc = gr.Accordion("Útgreinað marking / Expanded tags", open=False, visible=False)
|
| 611 |
with expanded_acc:
|
| 612 |
out_mean_df = gr.Dataframe(
|
| 613 |
+
value=pd.DataFrame(columns=[UI["fo"]["w"], UI["fo"]["t"], UI["fo"]["m"]]),
|
| 614 |
+
wrap=True, interactive=False, show_label=False,
|
| 615 |
+
row_count=(0, "fixed"), col_count=(3, "fixed"),
|
| 616 |
)
|
| 617 |
|
| 618 |
overview_acc = gr.Accordion("Markayvirlit / Tag Overview", open=False, visible=True)
|
| 619 |
with overview_acc:
|
| 620 |
+
overview_md = gr.Markdown(build_overview("fo"))
|
| 621 |
|
| 622 |
+
def on_tag(sentence, lang_current):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 623 |
rows = run_model(sentence)
|
| 624 |
+
df_main, df_mean, overview = render(rows, lang_current)
|
| 625 |
+
|
| 626 |
+
show_fo = (lang_current == "fo")
|
| 627 |
+
show_en = (lang_current == "en")
|
| 628 |
|
| 629 |
return (
|
| 630 |
rows,
|
| 631 |
gr.update(value=df_main, visible=True),
|
| 632 |
gr.update(value=df_mean),
|
| 633 |
+
gr.update(value=overview),
|
| 634 |
+
gr.update(visible=True), # expanded_acc
|
| 635 |
+
# results_hdr is always visible now
|
| 636 |
+
gr.update(visible=show_fo), # fo_on
|
| 637 |
+
gr.update(visible=not show_fo), # fo_off
|
| 638 |
+
gr.update(visible=show_en), # en_on
|
| 639 |
+
gr.update(visible=not show_en), # en_off
|
| 640 |
+
lang_current,
|
| 641 |
)
|
| 642 |
|
| 643 |
+
def on_set_lang(rows, lang_value):
|
| 644 |
+
df_main, df_mean, overview = render(rows, lang_value)
|
| 645 |
+
|
| 646 |
+
show_fo = (lang_value == "fo")
|
| 647 |
+
show_en = (lang_value == "en")
|
|
|
|
|
|
|
|
|
|
| 648 |
|
|
|
|
| 649 |
return (
|
| 650 |
+
lang_value,
|
| 651 |
gr.update(value=df_main),
|
| 652 |
gr.update(value=df_mean),
|
| 653 |
+
gr.update(value=overview),
|
| 654 |
+
gr.update(visible=show_fo),
|
| 655 |
+
gr.update(visible=not show_fo),
|
| 656 |
+
gr.update(visible=show_en),
|
| 657 |
+
gr.update(visible=not show_en),
|
| 658 |
)
|
| 659 |
|
| 660 |
+
def on_set_fo(rows):
|
| 661 |
+
return on_set_lang(rows, "fo")
|
| 662 |
+
|
| 663 |
+
def on_set_en(rows):
|
| 664 |
+
return on_set_lang(rows, "en")
|
| 665 |
+
|
| 666 |
btn.click(
|
| 667 |
on_tag,
|
| 668 |
+
inputs=[inp, lang_state],
|
| 669 |
+
outputs=[state, out_df, out_mean_df, overview_md, expanded_acc,
|
| 670 |
+
btn_lang_fo_on, btn_lang_fo_off, btn_lang_en_on, btn_lang_en_off, lang_state],
|
| 671 |
+
queue=False,
|
| 672 |
)
|
| 673 |
|
| 674 |
+
# Language switch (does NOT rerun the model; just re-renders existing rows)
|
| 675 |
+
btn_lang_fo_on.click(
|
| 676 |
+
on_set_fo,
|
| 677 |
+
inputs=[state],
|
| 678 |
+
outputs=[lang_state, out_df, out_mean_df, overview_md,
|
| 679 |
+
btn_lang_fo_on, btn_lang_fo_off, btn_lang_en_on, btn_lang_en_off],
|
| 680 |
+
queue=False,
|
| 681 |
+
)
|
| 682 |
+
btn_lang_fo_off.click(
|
| 683 |
+
on_set_fo,
|
| 684 |
+
inputs=[state],
|
| 685 |
+
outputs=[lang_state, out_df, out_mean_df, overview_md,
|
| 686 |
+
btn_lang_fo_on, btn_lang_fo_off, btn_lang_en_on, btn_lang_en_off],
|
| 687 |
+
queue=False,
|
| 688 |
+
)
|
| 689 |
+
btn_lang_en_on.click(
|
| 690 |
+
on_set_en,
|
| 691 |
+
inputs=[state],
|
| 692 |
+
outputs=[lang_state, out_df, out_mean_df, overview_md,
|
| 693 |
+
btn_lang_fo_on, btn_lang_fo_off, btn_lang_en_on, btn_lang_en_off],
|
| 694 |
+
queue=False,
|
| 695 |
+
)
|
| 696 |
+
btn_lang_en_off.click(
|
| 697 |
+
on_set_en,
|
| 698 |
+
inputs=[state],
|
| 699 |
+
outputs=[lang_state, out_df, out_mean_df, overview_md,
|
| 700 |
+
btn_lang_fo_on, btn_lang_fo_off, btn_lang_en_on, btn_lang_en_off],
|
| 701 |
queue=False,
|
| 702 |
)
|
| 703 |
|