import gradio as gr import torch from torch.nn.functional import softmax from transformers import AutoTokenizer, AutoModelForSequenceClassification MODEL_ID = "celalkartoglu/tr-sentiment-bert-win-v1" LABELS = ["Negative","Notr","Positive"] MAX_LEN_DEFAULT = 256 tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID) model.eval() def postprocess_label(probs, min_conf=0.55, close_gap=0.10): neg, notr, pos = probs top = probs.argmax() # düşük güven: Notr if probs[top] < min_conf: return "Notr" # Neg ve Pos birbirine çok yakınsa: Notr if abs(neg - pos) < close_gap and (notr >= 0.30 or probs[top] < 0.60): return "Notr" return LABELS[int(top)] @torch.inference_mode() def infer_one(text, max_len=MAX_LEN_DEFAULT, use_rule=False, min_conf=0.55, close_gap=0.10): text = (text or "").strip() if not text: return "", {"Negative": 0.0, "Notr": 0.0, "Positive": 0.0} inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=int(max_len)) logits = model(**inputs).logits probs = softmax(logits, dim=-1).squeeze().tolist() scores = {LABELS[i]: float(probs[i]) for i in range(3)} label = postprocess_label(torch.tensor(probs), min_conf, close_gap) if use_rule else LABELS[int(torch.tensor(probs).argmax())] return label, scores def infer_batch(texts, max_len=MAX_LEN_DEFAULT, use_rule=False, min_conf=0.55, close_gap=0.10): if isinstance(texts, str): rows = [t.strip() for t in texts.split("\n") if t.strip()] else: rows = texts or [] results = [] for t in rows: lbl, scores = infer_one(t, max_len, use_rule, min_conf, close_gap) results.append([t, lbl, scores["Negative"], scores["Notr"], scores["Positive"]]) return results def export_csv(table): import pandas as pd df = pd.DataFrame(table, columns=["text","label","Negative","Notr","Positive"]) return gr.File.update(value=df.to_csv(index=False).encode("utf-8"), visible=True) theme = gr.themes.Soft(primary_hue="blue", neutral_hue="slate") CUSTOM_CSS = """ #title h1 { font-weight: 800; letter-spacing: -0.02em; } footer {opacity:.7} """ with gr.Blocks(theme=theme, css=CUSTOM_CSS, title="Türkçe Duygu Analizi | BERT") as demo: with gr.Row(): with gr.Column(scale=7): gr.Markdown( "
Model: celalkartoglu/tr-sentiment-bert-win-v1 | Sınıflar: Negative, Notr, Positive
" "