Spaces:
Running on Zero
Running on Zero
File size: 18,691 Bytes
7444944 5432d4d cc460a9 5432d4d 7444944 5432d4d 7444944 5432d4d cd39318 323c4df cd39318 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d cc460a9 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d cc460a9 5432d4d cc460a9 5432d4d cc460a9 7444944 cc460a9 7444944 cc460a9 7444944 5432d4d 7444944 cc460a9 7444944 cc460a9 7444944 cc460a9 7444944 5432d4d cc460a9 7444944 5432d4d cc460a9 7444944 5432d4d 20ded56 7444944 cc460a9 7444944 cc460a9 5432d4d cc460a9 5432d4d cc460a9 7444944 cc460a9 5432d4d 7444944 cd39318 5432d4d cc460a9 cd39318 7444944 5432d4d 7444944 5432d4d 7444944 cd39318 7444944 5432d4d 7444944 cd39318 7444944 5432d4d cd39318 5432d4d cd39318 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d cd39318 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d cc460a9 7444944 5432d4d 261676a 7444944 cc460a9 7444944 261676a 7444944 cc460a9 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 cd39318 7444944 cd39318 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 0d966d8 7444944 5432d4d 7444944 cc460a9 7444944 cc460a9 20af115 7444944 d888e5f 7444944 5432d4d 7444944 cd39318 5432d4d 7444944 cd39318 7444944 5432d4d cc460a9 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d 7444944 5432d4d cd39318 5432d4d 261676a cc460a9 7444944 5432d4d 7444944 5432d4d cc460a9 5432d4d 7444944 5432d4d 20ded56 5432d4d 7444944 5432d4d 20ded56 cc460a9 5432d4d 7444944 0d966d8 7444944 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 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 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 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 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 | import spaces
import html
import json
import re
import tempfile
from functools import lru_cache
from pathlib import Path
import gradio as gr
import torch
from huggingface_hub import hf_hub_download
from inference import (
MODEL_REPO_ID,
load_lemmatizer,
load_registry,
)
REGISTRY = load_registry()
TARGET_COL_IDX = 2
BATCH_SIZE = 32
REPLACEMENTS = {
'๎
': 'ะธ',
'๎': 'า',
'๎': 'า',
'๎': 'ั',
'๎': 'ัค',
'๎': 'ะฝ',
'๎': 'า',
'๎': 'า',
'๎': '~',
'๎ณ': 'โทฆา',
'๎': ' โทฎ',
'๎': 'าฬ',
'๎': 'าฬ',
'๎': 'โทน',
'๎': 'ั',
'๎': 'โทน',
'๎': ':',
'๎๎': 'ะงโทน',
'๎': 'ะพ',
'๎': 'ั',
'๎ง': 'ะต',
'๎ฌ': 'อ ',
'๎ฎ': 'ยทฬ',
'๎ฏ': 'ยทฬ',
'โทญโทญ๎ฒ': 'า',
'๎ฒ': 'า',
'๎ฑ': 'า',
'๎': 'โทฉ',
'๎': '๊ถ',
'๎': 'ะพั',
'๎': '๊',
'๎ณ': 'โทฟ',
'๎': 'โทฟ',
'๎': 'ัง',
' ๎': 'ั',
'๎ก': 'ัฑ',
'๎ฃ': 'ัค',
'๎': 'ัา',
'๊ณ': 'ั',
'๊ฏ': 'า',
'๎ณ': 'อก',
'๎
': 'อ ',
'๎ั': 'ัั',
'๎': 'ั',
'โทฃ๎': 'โทฃอก',
'๎ณโทฎ': 'โทฃอก',
'โทฏ๎ณ': 'ฬอ ',
'๎': '๊ฉฬ',
'๎ัง': 'ััง',
'๎': 'า',
'๎': '๊บ',
'๎': 'ะฎ',
'๎': '๊ป',
'โทค': '',
}
ORDERED_REPLACEMENTS = sorted(
REPLACEMENTS.items(),
key=lambda item: len(item[0]),
reverse=True,
)
def preprocess_text(text):
text = str(text or "")
for source, replacement in ORDERED_REPLACEMENTS:
text = text.replace(source, replacement)
return text.strip()
def display_name(item):
return f"{item['language']} - {item['treebank']}"
LANGUAGES = sorted(
{
item["language"]
for item in REGISTRY.values()
}
)
DISPLAY_TO_ID = {
display_name(item): model_id
for model_id, item in REGISTRY.items()
}
def treebank_choices(language):
return sorted(
display_name(item)
for item in REGISTRY.values()
if item["language"] == language
)
def default_language():
preferred = "Old Church Slavonic"
if preferred in LANGUAGES:
return preferred
return LANGUAGES[0] if LANGUAGES else None
def default_treebank(language):
choices = treebank_choices(language)
preferred = "Old Church Slavonic - Combined Model"
if preferred in choices:
return preferred
return choices[0] if choices else None
def update_treebanks(language):
choices = treebank_choices(language)
return gr.Dropdown(
choices=choices,
value=default_treebank(language),
)
def selected_model_id(selected_name):
if (
not selected_name
or selected_name not in DISPLAY_TO_ID
):
raise ValueError(
"Please select a valid model."
)
return DISPLAY_TO_ID[selected_name]
@lru_cache(maxsize=8)
def load_vocab_chars_for_model(model_id):
item = REGISTRY[model_id]
vocab_path = hf_hub_download(
repo_id=MODEL_REPO_ID,
repo_type="model",
filename=item["vocab_file"],
)
with open(vocab_path, encoding="utf8") as file:
vocab_data = json.load(file)
return set(vocab_data["char2idx"]) - {
"<pad>",
"<sos>",
"<eos>",
"<unk>",
}
def unsupported_input_for_model(
text,
allowed_chars,
max_bad_ratio=0.60,
min_checked_chars=4,
):
checked = []
bad = []
ignored = {
".",
",",
";",
":",
"!",
"?",
"'",
'"',
"(",
")",
"[",
"]",
"/",
}
for character in text:
if character.isspace():
continue
if character.isdigit():
continue
if character in ignored:
continue
checked.append(character)
if character not in allowed_chars:
bad.append(character)
if len(checked) < min_checked_chars:
return False, []
bad_ratio = len(bad) / len(checked)
return (
bad_ratio >= max_bad_ratio,
sorted(set(bad)),
)
def make_html_table(tokens, lemmas):
if not tokens:
return ""
rows = []
for token, lemma in zip(tokens, lemmas):
rows.append(
"<tr>"
f"<td>{html.escape(token)}</td>"
f"<td>{html.escape(lemma)}</td>"
"</tr>"
)
return (
'<div id="token-card">'
'<table class="lemma-table">'
"<thead>"
"<tr>"
"<th>Word</th>"
"<th>Lemma</th>"
"</tr>"
"</thead>"
"<tbody>"
f"{''.join(rows)}"
"</tbody>"
"</table>"
"</div>"
)
@spaces.GPU(duration=60)
def lemmatize_sentence(sentence, selected_name):
sentence = str(sentence or "").strip()
if not sentence:
return "", ""
try:
processed_sentence = preprocess_text(sentence)
if not processed_sentence:
return "", ""
model_id = selected_model_id(
selected_name
)
allowed_chars = load_vocab_chars_for_model(
model_id
)
is_bad, bad = unsupported_input_for_model(
processed_sentence,
allowed_chars,
)
if is_bad:
message = (
"The processed input contains too many "
"characters that are not present in the "
"selected model vocabulary. "
"Unsupported characters: "
+ " ".join(bad[:20])
)
return (
"",
f"<p>{html.escape(message)}</p>",
)
tokens = processed_sentence.split()
lemmatizer = load_lemmatizer(
model_id=model_id,
device="cuda",
)
lemmas = lemmatizer.lemmatize_sentence(
tokens
)
result = " ".join(lemmas)
table = make_html_table(tokens, lemmas)
del lemmatizer
torch.cuda.empty_cache()
return result, table
except Exception as error:
torch.cuda.empty_cache()
return (
"",
f"<p>{html.escape(str(error))}</p>",
)
def parse_conllu_sentences_from_text(text):
text = text.strip()
sentences = []
for block in re.split(r"\n\n+", text):
sentence = []
for line in block.splitlines():
if not line:
continue
if line.startswith("#"):
continue
columns = line.split("\t")
if len(columns) != 10:
continue
token_id = columns[0]
if "-" in token_id or "." in token_id:
continue
processed_form = preprocess_text(
columns[1]
)
if processed_form:
sentence.append(processed_form)
if sentence:
sentences.append(sentence)
return sentences
def make_source_for_token(
tokens,
index,
k_context,
sep_char,
):
form = tokens[index]
left_context = tokens[
max(0, index - k_context):index
]
right_context = tokens[
index + 1:index + 1 + k_context
]
left = " ".join(left_context).strip()
right = " ".join(right_context).strip()
src_left = left + " " if left else ""
src_right = " " + right if right else ""
return (
f"{src_left}"
f"{sep_char}"
f"{form}"
f"{sep_char}"
f"{src_right}"
)
def make_all_sources_from_conllu(
text,
lemmatizer,
):
sentences = parse_conllu_sentences_from_text(
text
)
sources = []
for tokens in sentences:
for index in range(len(tokens)):
source = make_source_for_token(
tokens=tokens,
index=index,
k_context=lemmatizer.k_context,
sep_char=lemmatizer.sep_char,
)
sources.append(source)
return sources
def predict_sources_batched(
sources,
lemmatizer,
batch_size=BATCH_SIZE,
):
predictions = []
if not sources:
return predictions
pad_id = lemmatizer.vocab.char2idx["<pad>"]
sos_id = lemmatizer.vocab.char2idx["<sos>"]
eos_id = lemmatizer.vocab.char2idx["<eos>"]
for start in range(
0,
len(sources),
batch_size,
):
batch_sources = sources[
start:start + batch_size
]
source_ids_list = []
source_lengths = []
for source_string in batch_sources:
source_ids = (
[sos_id]
+ lemmatizer.vocab.encode(
source_string
)
+ [eos_id]
)
source_ids_list.append(source_ids)
source_lengths.append(
len(source_ids)
)
maximum_length = max(source_lengths)
padded = [
ids
+ [pad_id]
* (maximum_length - len(ids))
for ids in source_ids_list
]
source_tensor = torch.tensor(
padded,
dtype=torch.long,
device=lemmatizer.device,
)
length_tensor = torch.tensor(
source_lengths,
dtype=torch.long,
device=lemmatizer.device,
)
batch_predictions = (
lemmatizer.model.generate(
source_tensor,
length_tensor,
lemmatizer.vocab,
max_len=lemmatizer.max_gen_len,
)
)
predictions.extend(batch_predictions)
return predictions
def write_back_conllu(input_text, predictions):
text = input_text.rstrip("\n")
blocks = re.split(r"\n\n+", text)
output_blocks = []
prediction_index = 0
for block in blocks:
new_lines = []
for line in block.split("\n"):
if not line or line.startswith("#"):
new_lines.append(line)
continue
columns = line.split("\t")
if len(columns) != 10:
new_lines.append(line)
continue
token_id = columns[0]
if "-" in token_id or "." in token_id:
new_lines.append(line)
continue
if prediction_index < len(predictions):
prediction = predictions[
prediction_index
]
else:
prediction = "_"
columns[TARGET_COL_IDX] = (
prediction if prediction else "_"
)
new_lines.append(
"\t".join(columns)
)
prediction_index += 1
output_blocks.append(
"\n".join(new_lines)
)
output_text = (
"\n\n".join(output_blocks).rstrip()
+ "\n\n"
)
return output_text, prediction_index
@spaces.GPU(duration=120)
def lemmatize_conllu_file(
file_obj,
selected_name,
):
if file_obj is None:
return (
gr.update(
value=None,
visible=False,
),
"Please upload a CoNLL-U file.",
)
try:
model_id = selected_model_id(
selected_name
)
input_path = Path(file_obj)
with input_path.open(
encoding="utf8"
) as file:
text = file.read()
lemmatizer = load_lemmatizer(
model_id=model_id,
device="cuda",
)
sources = make_all_sources_from_conllu(
text,
lemmatizer,
)
predictions = predict_sources_batched(
sources,
lemmatizer,
)
output_text, total = write_back_conllu(
text,
predictions,
)
safe_name = re.sub(
r"[^A-Za-z0-9_]+",
"",
selected_name.replace(
" ",
"_",
).replace(
"-",
"_",
),
)
output_path = (
Path(tempfile.gettempdir())
/ (
f"{input_path.stem}."
f"{safe_name}."
"lemmatized.conllu"
)
)
with output_path.open(
"w",
encoding="utf8",
newline="\n",
) as file:
file.write(output_text)
del lemmatizer
torch.cuda.empty_cache()
message = (
f"Done. Wrote {total:,} lemma predictions.\n"
"PUA replacements were applied before inference.\n"
"Input column: FORM.\n"
"Updated column: LEMMA.\n"
"Original FORM values and all other columns were preserved."
)
return (
gr.update(
value=str(output_path),
visible=True,
),
message,
)
except Exception as error:
torch.cuda.empty_cache()
return (
gr.update(
value=None,
visible=False,
),
f"Error: {error}",
)
def reset_download_button(file_obj):
return (
gr.update(
value=None,
visible=False,
),
"",
)
CUSTOM_CSS = """
body {
background: linear-gradient(
135deg,
#eaf3ff 0%,
#ffffff 48%,
#dbeafe 100%
);
}
.gradio-container {
max-width: 980px !important;
margin: auto !important;
font-family: Arial, Helvetica, sans-serif !important;
}
#main-card {
background: #ffffff;
border: 1px solid #bfdbfe;
border-radius: 26px;
padding: 30px;
box-shadow: 0 20px 50px rgba(15, 23, 42, 0.16);
}
#title {
text-align: center;
color: #020617;
font-size: 2.5rem;
font-weight: 900;
}
#subtitle {
text-align: center;
color: #1e40af;
font-size: 1.05rem;
line-height: 1.55;
}
#badge-row {
text-align: center;
margin-bottom: 1.2rem;
}
#badge-row span {
display: inline-block;
background: #eff6ff;
color: #1e3a8a;
border: 1px solid #bfdbfe;
border-radius: 999px;
padding: 7px 13px;
margin: 4px;
font-weight: 700;
}
button {
background: linear-gradient(
90deg,
#020617,
#1d4ed8
) !important;
color: #ffffff !important;
border-radius: 16px !important;
font-weight: 900 !important;
}
#token-card {
background: #f8fbff;
border: 1.5px solid #1d4ed8;
border-radius: 18px;
padding: 18px;
}
.lemma-table {
width: 100%;
border-collapse: collapse;
}
.lemma-table th {
background: #1d4ed8;
color: white;
padding: 12px;
text-align: left;
}
.lemma-table td {
padding: 12px;
border-bottom: 1px solid #bfdbfe;
}
footer {
display: none !important;
}
"""
DEFAULT_LANGUAGE = default_language()
DEFAULT_TREEBANK = default_treebank(
DEFAULT_LANGUAGE
)
APP_THEME = gr.themes.Soft(
primary_hue="blue",
secondary_hue="sky",
neutral_hue="slate",
)
with gr.Blocks(
title="OCS Combined Lemmatizer",
) as demo:
with gr.Column(elem_id="main-card"):
gr.Markdown(
"# Old Church Slavonic Lemmatizer Demo",
elem_id="title",
)
gr.Markdown(
"Paste a tokenized sentence or upload a "
"CoNLL-U file to generate lemma predictions. "
"PUA characters are normalized before tokenization.",
elem_id="subtitle",
)
gr.HTML(
"""
<div id="badge-row">
<span>Old Church Slavonic</span>
<span>Combined Model</span>
<span>PUA Normalization</span>
<span>Context-aware</span>
<span>ZeroGPU</span>
</div>
"""
)
with gr.Row():
language_input = gr.Dropdown(
label="Language",
choices=LANGUAGES,
value=DEFAULT_LANGUAGE,
)
treebank_input = gr.Dropdown(
label="Model",
choices=treebank_choices(
DEFAULT_LANGUAGE
),
value=DEFAULT_TREEBANK,
)
with gr.Tab("Sentence"):
sentence_input = gr.Textbox(
label="Input sentence",
lines=5,
placeholder=(
"Enter a whitespace-tokenized sentence"
),
)
sentence_button = gr.Button(
"Lemmatize sentence"
)
sentence_output = gr.Textbox(
label="Lemmatized sentence",
lines=5,
)
token_output = gr.HTML()
with gr.Tab("CoNLL-U file"):
conllu_input = gr.File(
label="Upload CoNLL-U file",
file_types=[".conllu", ".txt"],
type="filepath",
)
conllu_button = gr.Button(
"Lemmatize CoNLL-U file"
)
conllu_output = gr.DownloadButton(
label="Download result",
value=None,
visible=False,
)
conllu_message = gr.Textbox(
label="Status",
lines=5,
)
language_input.change(
fn=update_treebanks,
inputs=language_input,
outputs=treebank_input,
)
sentence_button.click(
fn=lemmatize_sentence,
inputs=[
sentence_input,
treebank_input,
],
outputs=[
sentence_output,
token_output,
],
)
conllu_input.change(
fn=reset_download_button,
inputs=conllu_input,
outputs=[
conllu_output,
conllu_message,
],
)
conllu_button.click(
fn=lemmatize_conllu_file,
inputs=[
conllu_input,
treebank_input,
],
outputs=[
conllu_output,
conllu_message,
],
)
demo.queue()
demo.launch(
server_name="0.0.0.0",
server_port=7860,
ssr_mode=False,
theme=APP_THEME,
css=CUSTOM_CSS,
footer_links=[],
) |