Spaces:
Runtime error
Runtime error
hataheriandani commited on
Commit ·
2d5ea4f
1
Parent(s): 2dbc58d
Initial commit
Browse files- Jupiter_Group +1 -0
- app.py +107 -0
- requirements.txt +8 -0
Jupiter_Group
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Subproject commit 2dbc58d26610d920a2ce0f2e8b8a31ade6c4751e
|
app.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import (
|
| 5 |
+
AutoTokenizer,
|
| 6 |
+
AutoModelForSequenceClassification,
|
| 7 |
+
pipeline
|
| 8 |
+
)
|
| 9 |
+
from transformers_interpret import SequenceClassificationExplainer
|
| 10 |
+
import gradio as gr
|
| 11 |
+
|
| 12 |
+
# ---------------------------
|
| 13 |
+
# Configuration
|
| 14 |
+
# ---------------------------
|
| 15 |
+
SEED = 42
|
| 16 |
+
MODEL_ID = "sosohrabian/my-fine-tuned-bert" # مدل شما در Model Hub
|
| 17 |
+
|
| 18 |
+
# ---------------------------
|
| 19 |
+
# Setup Reproducibility
|
| 20 |
+
# ---------------------------
|
| 21 |
+
random.seed(SEED)
|
| 22 |
+
np.random.seed(SEED)
|
| 23 |
+
torch.manual_seed(SEED)
|
| 24 |
+
if torch.cuda.is_available():
|
| 25 |
+
torch.cuda.manual_seed_all(SEED)
|
| 26 |
+
|
| 27 |
+
USE_MPS = torch.backends.mps.is_available()
|
| 28 |
+
device = torch.device("mps" if USE_MPS else "cpu")
|
| 29 |
+
print("Using device:", device)
|
| 30 |
+
|
| 31 |
+
# ---------------------------
|
| 32 |
+
# Load model and tokenizer from Model Hub
|
| 33 |
+
# ---------------------------
|
| 34 |
+
print("Loading model from:", MODEL_ID)
|
| 35 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 36 |
+
model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID)
|
| 37 |
+
|
| 38 |
+
# ---------------------------
|
| 39 |
+
# Prepare pipeline and explainer
|
| 40 |
+
# ---------------------------
|
| 41 |
+
label_names = {0: "World", 1: "Sports", 2: "Business", 3: "Sci/Tech"}
|
| 42 |
+
|
| 43 |
+
device_index = 0 if torch.cuda.is_available() else -1
|
| 44 |
+
clf = pipeline("text-classification", model=model, tokenizer=tokenizer, top_k=None, device=device_index)
|
| 45 |
+
explainer = SequenceClassificationExplainer(model=model, tokenizer=tokenizer)
|
| 46 |
+
|
| 47 |
+
# ---------------------------
|
| 48 |
+
# Prediction and explanation functions
|
| 49 |
+
# ---------------------------
|
| 50 |
+
def predict(text: str):
|
| 51 |
+
"""Predicts the class probabilities for a given input text."""
|
| 52 |
+
text = (text or "").strip()
|
| 53 |
+
if not text:
|
| 54 |
+
return {}
|
| 55 |
+
out = clf(text, truncation=True)
|
| 56 |
+
if isinstance(out, list) and isinstance(out[0], list):
|
| 57 |
+
out = out[0]
|
| 58 |
+
results = {}
|
| 59 |
+
for o in sorted(out, key=lambda x: -x["score"]):
|
| 60 |
+
idx = int(o["label"].split("_")[1])
|
| 61 |
+
results[label_names[idx]] = float(o["score"])
|
| 62 |
+
return results
|
| 63 |
+
|
| 64 |
+
def explain_html(text: str) -> str:
|
| 65 |
+
"""Generates HTML visualization of important words."""
|
| 66 |
+
text = (text or "").strip()
|
| 67 |
+
if not text:
|
| 68 |
+
return "<i>Enter text to see highlighted words.</i>"
|
| 69 |
+
atts = explainer(text)
|
| 70 |
+
toks = [t for t, _ in atts]
|
| 71 |
+
scores = np.abs([s for _, s in atts])
|
| 72 |
+
smin, smax = float(np.min(scores)), float(np.max(scores))
|
| 73 |
+
scores = (scores - smin) / (smax - smin + 1e-8)
|
| 74 |
+
spans = [
|
| 75 |
+
f"<span style='background: rgba(255,0,0,{0.15+0.85*s:.2f});"
|
| 76 |
+
f"padding:2px 3px; margin:1px; border-radius:4px; display:inline-block'>{tok}</span>"
|
| 77 |
+
for tok, s in zip(toks, scores)
|
| 78 |
+
]
|
| 79 |
+
return "<div style='line-height:2'>" + " ".join(spans) + "</div>"
|
| 80 |
+
|
| 81 |
+
def predict_and_explain(text: str):
|
| 82 |
+
"""Runs both prediction and explanation."""
|
| 83 |
+
return predict(text), explain_html(text)
|
| 84 |
+
|
| 85 |
+
# ---------------------------
|
| 86 |
+
# Gradio App
|
| 87 |
+
# ---------------------------
|
| 88 |
+
demo = gr.Interface(
|
| 89 |
+
fn=predict_and_explain,
|
| 90 |
+
inputs=gr.Textbox(lines=3, label="Enter news headline"),
|
| 91 |
+
outputs=[
|
| 92 |
+
gr.Label(num_top_classes=4, label="Predicted topic"),
|
| 93 |
+
gr.HTML(label="Important-word highlights"),
|
| 94 |
+
],
|
| 95 |
+
title="AG News Topic Classifier (Fine-tuned BERT)",
|
| 96 |
+
description="Classifies news headlines and highlights words that influenced the prediction.",
|
| 97 |
+
theme="default",
|
| 98 |
+
examples=[
|
| 99 |
+
["Apple unveils new iPhone during annual event"],
|
| 100 |
+
["The stock market saw major gains today"],
|
| 101 |
+
["Scientists discover new exoplanet"],
|
| 102 |
+
["The local team wins the championship"],
|
| 103 |
+
],
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy
|
| 2 |
+
torch
|
| 3 |
+
datasets
|
| 4 |
+
transformers
|
| 5 |
+
accelerate
|
| 6 |
+
scikit-learn
|
| 7 |
+
transformers-interpret
|
| 8 |
+
gradio
|