Update app.py
Browse files
app.py
CHANGED
|
@@ -2,8 +2,7 @@ import os
|
|
| 2 |
import torch
|
| 3 |
import pandas as pd
|
| 4 |
import gradio as gr
|
| 5 |
-
from
|
| 6 |
-
from transformers import AutoTokenizer, AutoModelForTokenClassification
|
| 7 |
|
| 8 |
# =========================================================================
|
| 9 |
# 1. Sabitler ve Model Yükleme
|
|
@@ -16,9 +15,9 @@ HF_MODEL_ID = "LiProject/BERT-Turkish-Lemmatization-V2"
|
|
| 16 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 17 |
|
| 18 |
try:
|
| 19 |
-
# Model ve Tokenizer'ı
|
| 20 |
tok = AutoTokenizer.from_pretrained(HF_MODEL_ID, use_fast=True)
|
| 21 |
-
mdl =
|
| 22 |
print(f"Model yükleme başarılı: {HF_MODEL_ID} ({DEVICE} üzerinde)")
|
| 23 |
|
| 24 |
except Exception as e:
|
|
@@ -26,93 +25,48 @@ except Exception as e:
|
|
| 26 |
exit(1)
|
| 27 |
|
| 28 |
# =========================================================================
|
| 29 |
-
# 2.
|
| 30 |
-
# =========================================================================
|
| 31 |
-
|
| 32 |
-
def build_id2label_from_config(cfg):
|
| 33 |
-
# Modelin config dosyasından id2label'ı güvenilir bir şekilde okur
|
| 34 |
-
n = getattr(cfg, "num_labels", None)
|
| 35 |
-
if n is None:
|
| 36 |
-
if isinstance(getattr(cfg, "id2label", None), dict): n = len(cfg.id2label)
|
| 37 |
-
elif isinstance(getattr(cfg, "label2id", None), dict): n = len(cfg.label2id)
|
| 38 |
-
else: raise ValueError("num_labels/id2label/label2id yok.")
|
| 39 |
-
|
| 40 |
-
labels = [f"LABEL_{i}" for i in range(n)]
|
| 41 |
-
id2label = getattr(cfg, "id2label", None)
|
| 42 |
-
|
| 43 |
-
if id2label:
|
| 44 |
-
if isinstance(id2label, dict):
|
| 45 |
-
for k,v in id2label.items():
|
| 46 |
-
try: i = int(k)
|
| 47 |
-
except:
|
| 48 |
-
try: i = int(float(k))
|
| 49 |
-
except: continue
|
| 50 |
-
if 0 <= i < n: labels[i] = str(v)
|
| 51 |
-
elif isinstance(id2label, (list,tuple)) and len(id2label)==n:
|
| 52 |
-
labels = [str(x) for x in id2label]
|
| 53 |
-
|
| 54 |
-
l2i = getattr(cfg, "label2id", None)
|
| 55 |
-
if isinstance(l2i, dict):
|
| 56 |
-
for lbl, idx_ in l2i.items():
|
| 57 |
-
try: i = int(idx_)
|
| 58 |
-
except:
|
| 59 |
-
try: i = int(float(idx_))
|
| 60 |
-
except: continue
|
| 61 |
-
if 0 <= i < n and labels[i].startswith("LABEL_"):
|
| 62 |
-
labels[i] = str(lbl)
|
| 63 |
-
|
| 64 |
-
for i,v in enumerate(labels):
|
| 65 |
-
if v.startswith("LABEL_"): labels[i] = str(i)
|
| 66 |
-
|
| 67 |
-
return labels
|
| 68 |
-
|
| 69 |
-
ID2LABEL = build_id2label_from_config(mdl.config)
|
| 70 |
-
|
| 71 |
-
# =========================================================================
|
| 72 |
-
# 3. Inference ve Çıktı Formatı
|
| 73 |
# =========================================================================
|
| 74 |
|
| 75 |
@torch.inference_mode()
|
| 76 |
def lemmatize_rows(multiline_text: str):
|
| 77 |
-
"""Metni işler ve kelime
|
| 78 |
rows = []
|
| 79 |
sentences = [s.strip() for s in multiline_text.splitlines() if s.strip()]
|
| 80 |
|
| 81 |
if not sentences:
|
| 82 |
-
return pd.DataFrame(
|
| 83 |
|
| 84 |
for sent in sentences:
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
for i, wid in enumerate(word_ids):
|
| 94 |
-
if wid is not None:
|
| 95 |
-
idxs_by_word[wid].append(i)
|
| 96 |
-
|
| 97 |
-
for wid in sorted(idxs_by_word.keys()):
|
| 98 |
-
sub_idxs = idxs_by_word[wid]
|
| 99 |
-
|
| 100 |
-
start = offsets[sub_idxs[0]][0]
|
| 101 |
-
end = offsets[sub_idxs[-1]][1]
|
| 102 |
-
surface = sent[start:end] if (start is not None and end is not None) else ""
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
# Modelin tahmin ettiği kök (lemma)
|
| 108 |
-
lemma = ID2LABEL[pid] if pid < len(ID2LABEL) else str(pid)
|
| 109 |
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
return pd.DataFrame(rows)
|
| 113 |
|
| 114 |
def add_sentence_separators(df: pd.DataFrame, char: str = "-", repeat: int = 10) -> pd.DataFrame:
|
| 115 |
"""Görünürlük için cümleler arasına ayraç satırları ekler."""
|
|
|
|
|
|
|
|
|
|
| 116 |
rows, prev = [], None
|
| 117 |
for _, r in df.iterrows():
|
| 118 |
if prev is not None and r["Full_Sentence"] != prev:
|
|
@@ -133,13 +87,13 @@ def run_and_save(text):
|
|
| 133 |
return df_view, out_path
|
| 134 |
|
| 135 |
examples = [
|
| 136 |
-
"
|
| 137 |
-
"
|
| 138 |
"Bana hikayenin sonunu anlattılar."
|
| 139 |
]
|
| 140 |
|
| 141 |
# =========================================================================
|
| 142 |
-
#
|
| 143 |
# =========================================================================
|
| 144 |
|
| 145 |
theme = gr.themes.Soft(primary_hue="slate", neutral_hue="slate")
|
|
|
|
| 2 |
import torch
|
| 3 |
import pandas as pd
|
| 4 |
import gradio as gr
|
| 5 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
|
|
|
| 6 |
|
| 7 |
# =========================================================================
|
| 8 |
# 1. Sabitler ve Model Yükleme
|
|
|
|
| 15 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 16 |
|
| 17 |
try:
|
| 18 |
+
# Model ve Tokenizer'ı Seq2Seq (Encoder-Decoder) mantığına uygun yükle
|
| 19 |
tok = AutoTokenizer.from_pretrained(HF_MODEL_ID, use_fast=True)
|
| 20 |
+
mdl = AutoModelForSeq2SeqLM.from_pretrained(HF_MODEL_ID).to(DEVICE).eval()
|
| 21 |
print(f"Model yükleme başarılı: {HF_MODEL_ID} ({DEVICE} üzerinde)")
|
| 22 |
|
| 23 |
except Exception as e:
|
|
|
|
| 25 |
exit(1)
|
| 26 |
|
| 27 |
# =========================================================================
|
| 28 |
+
# 2. Inference ve Çıktı Formatı
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
# =========================================================================
|
| 30 |
|
| 31 |
@torch.inference_mode()
|
| 32 |
def lemmatize_rows(multiline_text: str):
|
| 33 |
+
"""Metni işler ve kelime-kök eşleşmesini içeren DataFrame döndürür."""
|
| 34 |
rows = []
|
| 35 |
sentences = [s.strip() for s in multiline_text.splitlines() if s.strip()]
|
| 36 |
|
| 37 |
if not sentences:
|
| 38 |
+
return pd.DataFrame(columns=["Full_Sentence", "Word", "Lemma"])
|
| 39 |
|
| 40 |
for sent in sentences:
|
| 41 |
+
# 1. Orijinal cümleyi modele ver
|
| 42 |
+
inputs = tok(sent, return_tensors="pt", truncation=True, max_length=512).to(DEVICE)
|
| 43 |
+
|
| 44 |
+
# 2. Köklerden oluşan yeni cümleyi üret (generate)
|
| 45 |
+
outputs = mdl.generate(**inputs, max_length=512)
|
| 46 |
+
|
| 47 |
+
# 3. Üretilen tokenları metne çevir
|
| 48 |
+
lemmatized_sent = tok.decode(outputs[0], skip_special_tokens=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
+
# Kelimeleri boşluklardan bölerek eşleştir
|
| 51 |
+
orig_words = sent.split()
|
| 52 |
+
lemma_words = lemmatized_sent.split()
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
# Orijinal cümledeki kelime sayısıyla, üretilen kök say��sını eşleştiriyoruz
|
| 55 |
+
# (Eğer model fazla veya eksik kelime üretirse tablo bozulmasın diye max uzunluk alınıyor)
|
| 56 |
+
max_len = max(len(orig_words), len(lemma_words))
|
| 57 |
+
|
| 58 |
+
for i in range(max_len):
|
| 59 |
+
w = orig_words[i] if i < len(orig_words) else ""
|
| 60 |
+
l = lemma_words[i] if i < len(lemma_words) else ""
|
| 61 |
+
rows.append({"Full_Sentence": sent, "Word": w, "Lemma": l})
|
| 62 |
|
| 63 |
return pd.DataFrame(rows)
|
| 64 |
|
| 65 |
def add_sentence_separators(df: pd.DataFrame, char: str = "-", repeat: int = 10) -> pd.DataFrame:
|
| 66 |
"""Görünürlük için cümleler arasına ayraç satırları ekler."""
|
| 67 |
+
if df.empty:
|
| 68 |
+
return df
|
| 69 |
+
|
| 70 |
rows, prev = [], None
|
| 71 |
for _, r in df.iterrows():
|
| 72 |
if prev is not None and r["Full_Sentence"] != prev:
|
|
|
|
| 87 |
return df_view, out_path
|
| 88 |
|
| 89 |
examples = [
|
| 90 |
+
"Kedilerimizden biri çok hızlıca koştu",
|
| 91 |
+
"Gözlükçüler dükkanlarını erkenden açtılar.",
|
| 92 |
"Bana hikayenin sonunu anlattılar."
|
| 93 |
]
|
| 94 |
|
| 95 |
# =========================================================================
|
| 96 |
+
# 3. Gradio Arayüzü
|
| 97 |
# =========================================================================
|
| 98 |
|
| 99 |
theme = gr.themes.Soft(primary_hue="slate", neutral_hue="slate")
|