Update app.py
Browse files
app.py
CHANGED
|
@@ -1,703 +1,427 @@
|
|
| 1 |
-
import os
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
import gradio as gr
|
| 5 |
-
import torch
|
| 6 |
-
import numpy as np
|
| 7 |
import pandas as pd
|
| 8 |
-
|
|
|
|
| 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 |
-
|
| 45 |
-
|
| 46 |
-
|
| 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 |
-
|
| 54 |
-
|
| 55 |
-
|
| 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 |
-
|
| 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 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
box-shadow:none!important;
|
| 140 |
-
border:0!important;
|
| 141 |
-
}
|
| 142 |
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 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 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
border-color: var(--primary-600) !important;
|
| 164 |
-
color:#0b1b19 !important;
|
| 165 |
}
|
| 166 |
|
| 167 |
-
/*
|
| 168 |
-
.
|
| 169 |
-
background:
|
| 170 |
-
border-color: var(--primary-600) !important;
|
| 171 |
-
color:#0b1b19 !important;
|
| 172 |
}
|
| 173 |
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
border:
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
}
|
| 183 |
|
| 184 |
-
/*
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
|
|
|
|
|
|
| 188 |
cursor:pointer;
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
border-radius:10px;
|
| 193 |
border:1px solid var(--primary-600);
|
| 194 |
-
background: transparent; /* same as page */
|
| 195 |
color:#0b1b19;
|
| 196 |
-
|
| 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 |
-
|
| 250 |
-
#
|
| 251 |
-
|
|
|
|
| 252 |
}
|
| 253 |
|
| 254 |
-
/*
|
| 255 |
-
|
| 256 |
-
background:
|
| 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 |
-
#
|
| 288 |
# ----------------------------
|
| 289 |
-
|
| 290 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
|
| 292 |
# ----------------------------
|
| 293 |
-
# CSV
|
| 294 |
# ----------------------------
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 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
|
| 332 |
-
|
| 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 |
-
|
| 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 |
-
#
|
| 358 |
# ----------------------------
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
if
|
| 367 |
-
return
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
|
| 375 |
# ----------------------------
|
| 376 |
-
#
|
| 377 |
# ----------------------------
|
| 378 |
-
tag_to_features, features_to_tag, VEC_LEN, FEATURE_COLS = load_tag_mappings(TAGS_FILEPATH)
|
| 379 |
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
|
| 385 |
-
|
| 386 |
-
|
|
|
|
| 387 |
|
| 388 |
-
|
| 389 |
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
if g and code not in HIDE_CODES.get(g, set()):
|
| 394 |
-
GROUPS[g].append((i, code, col))
|
| 395 |
|
| 396 |
-
def
|
| 397 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
|
| 399 |
-
|
| 400 |
-
for
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
|
|
|
| 404 |
|
| 405 |
-
|
| 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 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 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 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 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 |
-
|
| 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 |
-
|
| 547 |
-
|
|
|
|
| 548 |
|
| 549 |
-
|
|
|
|
| 550 |
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
vec_i += 1
|
| 560 |
-
return rows
|
| 561 |
|
| 562 |
-
|
| 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: [{
|
| 587 |
)
|
| 588 |
-
btn = gr.Button("Marka / Tag",
|
| 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=False)
|
| 595 |
with results_hdr:
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 602 |
|
| 603 |
out_df = gr.Dataframe(
|
| 604 |
-
value=pd.DataFrame(columns=[
|
| 605 |
-
|
| 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=[
|
| 614 |
-
|
| 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 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
|
| 626 |
-
|
| 627 |
-
|
|
|
|
| 628 |
|
| 629 |
return (
|
| 630 |
rows,
|
| 631 |
gr.update(value=df_main, visible=True),
|
| 632 |
gr.update(value=df_mean),
|
| 633 |
-
gr.update(value=
|
| 634 |
-
gr.update(visible=True),
|
| 635 |
-
gr.update(visible=True),
|
| 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
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
|
|
|
|
|
|
|
|
|
| 648 |
|
|
|
|
| 649 |
return (
|
| 650 |
-
lang_value,
|
| 651 |
gr.update(value=df_main),
|
| 652 |
gr.update(value=df_mean),
|
| 653 |
-
gr.update(value=
|
| 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 |
-
|
| 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,
|
| 669 |
-
outputs=[state, out_df, out_mean_df, overview_md, expanded_acc, results_hdr,
|
| 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 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 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 |
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import re
|
|
|
|
|
|
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from huggingface_hub import InferenceClient
|
| 7 |
|
| 8 |
# ----------------------------
|
| 9 |
# Config
|
| 10 |
# ----------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
MODEL_REPO = "Setur/BRAGD"
|
| 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 |
+
:root{
|
| 28 |
+
--primary-500: #89AFA9; /* active + hover */
|
| 29 |
+
--primary-200: #CFE1DD; /* inactive */
|
| 30 |
+
--primary-600: #6f948e;
|
| 31 |
+
--page-bg: #f6f7f8;
|
| 32 |
+
--panel-bg: transparent;
|
| 33 |
+
--text: #111;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
}
|
| 35 |
|
| 36 |
+
body, .gradio-container{
|
| 37 |
+
background: var(--page-bg) !important;
|
| 38 |
+
color: var(--text);
|
|
|
|
|
|
|
| 39 |
}
|
| 40 |
|
| 41 |
+
/* Kill random panel backgrounds */
|
| 42 |
+
.gradio-container .block, .gradio-container .wrap, .gradio-container .gr-panel{
|
| 43 |
+
background: var(--panel-bg) !important;
|
|
|
|
|
|
|
| 44 |
}
|
| 45 |
|
| 46 |
+
/* Textbox: DO NOT TOUCH VISUALLY (keep white, clean, consistent) */
|
| 47 |
+
#input_box textarea{
|
| 48 |
+
background: #fff !important;
|
| 49 |
+
border: 1px solid rgba(0,0,0,0.10) !important;
|
| 50 |
+
border-radius: 8px !important;
|
| 51 |
+
box-shadow: 0 2px 6px rgba(0,0,0,0.06) !important;
|
| 52 |
+
font-size: 18px !important;
|
| 53 |
+
line-height: 1.4 !important;
|
| 54 |
+
padding: 16px !important;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
/* Big Marka button */
|
| 58 |
+
#tag_btn button{
|
| 59 |
+
background: var(--primary-500) !important;
|
| 60 |
+
color: #0b1b19 !important;
|
| 61 |
+
border: 1px solid var(--primary-600) !important;
|
| 62 |
+
border-radius: 8px !important;
|
| 63 |
+
font-weight: 700 !important;
|
| 64 |
+
font-size: 18px !important;
|
| 65 |
+
padding: 12px 16px !important;
|
| 66 |
+
box-shadow: 0 2px 8px rgba(0,0,0,0.10) !important;
|
| 67 |
+
}
|
| 68 |
+
#tag_btn button:hover{
|
| 69 |
+
filter: brightness(0.98);
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
/* Results header row */
|
| 73 |
+
#results_hdr{
|
| 74 |
+
margin-top: 8px;
|
| 75 |
+
align-items: center;
|
| 76 |
}
|
| 77 |
|
| 78 |
+
/* Language switch (Radio styled as buttons) */
|
| 79 |
+
#lang_col { display:flex; justify-content:flex-end; }
|
| 80 |
+
#lang_radio { display:flex; justify-content:flex-end; gap:0.6rem; background:transparent !important; }
|
| 81 |
+
#lang_radio fieldset, #lang_radio .wrap, #lang_radio .gr-form{ background:transparent !important; border:none !important; padding:0 !important; margin:0 !important; }
|
| 82 |
+
#lang_radio input[type="radio"]{ display:none !important; }
|
| 83 |
+
#lang_radio label{
|
| 84 |
cursor:pointer;
|
| 85 |
+
padding:0.38rem 1.05rem;
|
| 86 |
+
border-radius:0.65rem;
|
| 87 |
+
background:var(--primary-200);
|
|
|
|
| 88 |
border:1px solid var(--primary-600);
|
|
|
|
| 89 |
color:#0b1b19;
|
| 90 |
+
font-weight:600;
|
| 91 |
+
box-shadow: 0 1px 2px rgba(0,0,0,0.06);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
margin:0 !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
}
|
| 94 |
+
#lang_radio label:hover{ background:var(--primary-500); }
|
| 95 |
+
#lang_radio label:has(input:checked){
|
| 96 |
+
background:var(--primary-500);
|
| 97 |
+
border-color:var(--primary-600);
|
| 98 |
}
|
| 99 |
|
| 100 |
+
/* Tables */
|
| 101 |
+
.gr-dataframe, .gr-dataframe table{
|
| 102 |
+
background: #fff !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
}
|
| 104 |
"""
|
| 105 |
|
| 106 |
# ----------------------------
|
| 107 |
+
# Tag label loading
|
| 108 |
# ----------------------------
|
| 109 |
+
|
| 110 |
+
def load_tag_labels(path: str):
|
| 111 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 112 |
+
data = json.load(f)
|
| 113 |
+
return data
|
| 114 |
+
|
| 115 |
+
LABELS = load_tag_labels(TAG_LABELS_PATH)
|
| 116 |
|
| 117 |
# ----------------------------
|
| 118 |
+
# Tag overview CSV loading (word class -> codes)
|
| 119 |
# ----------------------------
|
| 120 |
+
|
| 121 |
+
def load_tag_overview_csv(path: str):
|
| 122 |
+
"""
|
| 123 |
+
Expects columns: 'word_class', 'tag_code'
|
| 124 |
+
"""
|
| 125 |
+
try:
|
| 126 |
+
df = pd.read_csv(path)
|
| 127 |
+
except Exception:
|
| 128 |
+
return {}
|
| 129 |
+
|
| 130 |
+
# normalize column names
|
| 131 |
+
cols = {c.lower().strip(): c for c in df.columns}
|
| 132 |
+
wc_col = cols.get("word_class")
|
| 133 |
+
code_col = cols.get("tag_code")
|
| 134 |
+
if not wc_col or not code_col:
|
| 135 |
+
return {}
|
| 136 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
out = {}
|
| 138 |
+
for wc, g in df.groupby(wc_col):
|
| 139 |
+
out[str(wc)] = sorted(set(str(x) for x in g[code_col].dropna().tolist()))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
return out
|
| 141 |
|
| 142 |
+
CODES_BY_WC = load_tag_overview_csv(TAG_OVERVIEW_CSV)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
# ----------------------------
|
| 145 |
+
# Model call
|
| 146 |
# ----------------------------
|
| 147 |
+
|
| 148 |
+
def run_model(sentence: str):
|
| 149 |
+
"""
|
| 150 |
+
Calls HF Inference API, returns list of dict rows:
|
| 151 |
+
[{"word":..., "tag":..., "analysis":...}, ...]
|
| 152 |
+
"""
|
| 153 |
+
sentence = (sentence or "").strip()
|
| 154 |
+
if not sentence:
|
| 155 |
+
return []
|
| 156 |
+
|
| 157 |
+
# The model returns token-level predictions; we assume BRAGD returns full tokens + tag string.
|
| 158 |
+
# We'll call text-generation or token-classification style; adjust if needed.
|
| 159 |
+
# Using InferenceClient.text_generation is safest for many Spaces, but we keep a robust fallback.
|
| 160 |
+
try:
|
| 161 |
+
# If your endpoint is a custom pipeline, you may need .post with raw JSON.
|
| 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 |
+
# Tag explanation logic
|
| 201 |
# ----------------------------
|
|
|
|
| 202 |
|
| 203 |
+
def label_for(lang: str, group: str, key: str, default: str = ""):
|
| 204 |
+
try:
|
| 205 |
+
return LABELS[lang][group][key]
|
| 206 |
+
except Exception:
|
| 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 |
+
# DGd special: suppress “no degree”
|
| 266 |
+
if wc == "D" and tag.startswith("DGd") and lang == "fo":
|
| 267 |
+
parts = [p for p in parts if p != "eingin stigbending"]
|
| 268 |
|
| 269 |
+
return ", ".join([p for p in parts if p])
|
| 270 |
|
| 271 |
+
# ----------------------------
|
| 272 |
+
# Rendering
|
| 273 |
+
# ----------------------------
|
|
|
|
|
|
|
| 274 |
|
| 275 |
+
def render(rows, lang: str):
|
| 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 |
+
data = []
|
| 289 |
+
for r in rows:
|
| 290 |
+
w = r.get("word", "")
|
| 291 |
+
t = r.get("tag", "")
|
| 292 |
+
a = analysis_text(t, lang)
|
| 293 |
+
data.append([w, t, a])
|
| 294 |
|
| 295 |
+
df_main = pd.DataFrame(data, columns=cols)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
+
# Expanded tags: keep simple but useful (word class + raw tag)
|
| 298 |
+
df_mean = pd.DataFrame(
|
| 299 |
+
[{"tag": r.get("tag", ""), "analysis": analysis_text(r.get("tag", ""), lang)} for r in rows],
|
| 300 |
+
columns=["tag", "analysis"],
|
| 301 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
+
return df_main, df_mean, build_overview(lang)
|
| 304 |
+
|
| 305 |
+
def build_overview(lang: str):
|
| 306 |
+
"""
|
| 307 |
+
Build the Tag Overview content from CODES_BY_WC + labels.
|
| 308 |
+
"""
|
| 309 |
+
lines = []
|
| 310 |
+
title = "Markayvirlit / Tag Overview" if lang == "fo" else "Tag Overview"
|
| 311 |
+
lines.append(f"### {title}")
|
| 312 |
+
lines.append("")
|
| 313 |
+
|
| 314 |
+
# Word class name mapping
|
| 315 |
+
for wc, codes in sorted(CODES_BY_WC.items(), key=lambda x: x[0]):
|
| 316 |
+
wc_name = label_for(lang, "word_class", wc, wc)
|
| 317 |
+
lines.append(f"**{wc} — {wc_name}**")
|
| 318 |
+
if codes:
|
| 319 |
+
lines.append(", ".join(codes))
|
| 320 |
+
else:
|
| 321 |
+
lines.append("_—_")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
lines.append("")
|
|
|
|
| 323 |
|
| 324 |
+
return "\n".join(lines)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
|
| 326 |
+
# ----------------------------
|
| 327 |
+
# UI
|
| 328 |
+
# ----------------------------
|
| 329 |
|
| 330 |
+
with gr.Blocks(css=CSS, title="Marka") as demo:
|
| 331 |
+
state = gr.State([]) # stores last tagged rows
|
| 332 |
|
| 333 |
+
with gr.Row():
|
| 334 |
+
with gr.Column(scale=2):
|
| 335 |
+
inp = gr.Textbox(
|
| 336 |
+
label="",
|
| 337 |
+
placeholder="Skriv her...",
|
| 338 |
+
lines=6,
|
| 339 |
+
elem_id="input_box",
|
| 340 |
+
)
|
|
|
|
|
|
|
| 341 |
|
| 342 |
+
with gr.Column(scale=1, min_width=360):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
gr.Markdown(
|
| 344 |
+
"## Marka\n\n"
|
| 345 |
"Skriv ein setning í kassan og fá hann markaðan.\n\n"
|
| 346 |
+
f"Myndil / Model: [{MODEL_REPO}](https://huggingface.co/{MODEL_REPO})"
|
| 347 |
)
|
| 348 |
+
btn = gr.Button("Marka / Tag", elem_id="tag_btn")
|
|
|
|
|
|
|
|
|
|
| 349 |
|
| 350 |
# Hide results header + toggle until Tag
|
| 351 |
results_hdr = gr.Row(elem_id="results_hdr", visible=False)
|
| 352 |
with results_hdr:
|
| 353 |
+
with gr.Column(scale=1):
|
| 354 |
+
results_title = gr.Markdown("### Úrslit / Results")
|
| 355 |
+
with gr.Column(scale=0, min_width=260, elem_id="lang_col"):
|
| 356 |
+
lang_radio = gr.Radio(
|
| 357 |
+
choices=[("Føroyskt","fo"), ("English","en")],
|
| 358 |
+
value="fo",
|
| 359 |
+
show_label=False,
|
| 360 |
+
interactive=True,
|
| 361 |
+
elem_id="lang_radio",
|
| 362 |
+
)
|
| 363 |
|
| 364 |
out_df = gr.Dataframe(
|
| 365 |
+
value=pd.DataFrame(columns=["Orð", "Mark", "Útgreining"]),
|
| 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=["tag", "analysis"]),
|
| 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"), elem_id="overview_md")
|
| 380 |
|
| 381 |
+
# ----------------------------
|
| 382 |
+
# Callbacks
|
| 383 |
+
# ----------------------------
|
| 384 |
|
| 385 |
+
def on_tag(sentence, lang_value):
|
| 386 |
+
rows = run_model(sentence)
|
| 387 |
+
df_main, df_mean, _ = render(rows, lang_value)
|
| 388 |
|
| 389 |
return (
|
| 390 |
rows,
|
| 391 |
gr.update(value=df_main, visible=True),
|
| 392 |
gr.update(value=df_mean),
|
| 393 |
+
gr.update(value=build_overview(lang_value)),
|
| 394 |
+
gr.update(visible=True), # expanded_acc
|
| 395 |
+
gr.update(visible=True), # results_hdr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
)
|
| 397 |
|
| 398 |
+
def on_lang(rows, lang_value):
|
| 399 |
+
# Allow switching the overview even before anything is tagged.
|
| 400 |
+
if not rows:
|
| 401 |
+
return (
|
| 402 |
+
gr.update(),
|
| 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=build_overview(lang_value)),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
)
|
| 413 |
|
| 414 |
+
# Wiring
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
btn.click(
|
| 416 |
on_tag,
|
| 417 |
+
inputs=[inp, lang_radio],
|
| 418 |
+
outputs=[state, out_df, out_mean_df, overview_md, expanded_acc, results_hdr],
|
|
|
|
|
|
|
| 419 |
)
|
| 420 |
|
| 421 |
+
lang_radio.change(
|
| 422 |
+
on_lang,
|
| 423 |
+
inputs=[state, lang_radio],
|
| 424 |
+
outputs=[out_df, out_mean_df, overview_md],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
queue=False,
|
| 426 |
)
|
| 427 |
|