Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 4 |
+
from huggingface_hub import hf_hub_download
|
| 5 |
+
|
| 6 |
+
REPO_ID = "SentilyticsOPJ/bertic_model"
|
| 7 |
+
FILENAME = "bertic_model.pt"
|
| 8 |
+
|
| 9 |
+
path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME)
|
| 10 |
+
obj = torch.load(path, map_location="cpu", weights_only=False)
|
| 11 |
+
|
| 12 |
+
hf_model_name = obj["hf_model_name"]
|
| 13 |
+
labels = obj["label_classes"]
|
| 14 |
+
max_len = obj["max_len"]
|
| 15 |
+
|
| 16 |
+
tokenizer = AutoTokenizer.from_pretrained(hf_model_name)
|
| 17 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 18 |
+
hf_model_name,
|
| 19 |
+
num_labels=len(labels),
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
model.load_state_dict(obj["state_dict"])
|
| 23 |
+
model.eval()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def predict(text):
|
| 27 |
+
if not text.strip():
|
| 28 |
+
return ""
|
| 29 |
+
enc = tokenizer(
|
| 30 |
+
text,
|
| 31 |
+
max_length=max_len,
|
| 32 |
+
padding="max_length",
|
| 33 |
+
truncation=True,
|
| 34 |
+
return_tensors="pt",
|
| 35 |
+
)
|
| 36 |
+
with torch.no_grad():
|
| 37 |
+
logits = model(
|
| 38 |
+
input_ids=enc["input_ids"],
|
| 39 |
+
attention_mask=enc["attention_mask"],
|
| 40 |
+
).logits
|
| 41 |
+
return labels[int(logits.argmax(1))]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
demo = gr.Interface(
|
| 45 |
+
fn=predict,
|
| 46 |
+
inputs=gr.Textbox(lines=3, placeholder="Unesi tekst...", label="Text"),
|
| 47 |
+
outputs=gr.Textbox(label="Sentiment"),
|
| 48 |
+
title="Sentiment Analysis (BERTić, fine-tuned)",
|
| 49 |
+
description="Five-class sentiment: mixed, negative, neutral, positive, sarcastic.",
|
| 50 |
+
examples=["Volim kavu", "Ovaj doktor je loš", "Dan je bio ok"],
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
demo.launch()
|