Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import streamlit as st
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 4 |
+
import torch
|
| 5 |
+
import numpy as np
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
@st.cache_resource
|
| 9 |
+
def load_model():
|
| 10 |
+
model = AutoModelForSequenceClassification.from_pretrained("your-model-path")
|
| 11 |
+
tokenizer = AutoTokenizer.from_pretrained("your-model-path")
|
| 12 |
+
return tokenizer, model
|
| 13 |
+
|
| 14 |
+
def get_top95(labels, probs):
|
| 15 |
+
sorted_indices = torch.argsort(probs, descending=True)
|
| 16 |
+
sorted_probs = probs[sorted_indices]
|
| 17 |
+
sorted_labels = labels[sorted_indices]
|
| 18 |
+
|
| 19 |
+
cumulative = torch.cumsum(sorted_probs, dim=0)
|
| 20 |
+
cutoff = torch.where(cumulative >= 0.95)[0]
|
| 21 |
+
last_idx = cutoff[0].item() + 1 if len(cutoff) > 0 else len(sorted_probs)
|
| 22 |
+
|
| 23 |
+
return list(zip(sorted_labels[:last_idx], sorted_probs[:last_idx].tolist()))
|
| 24 |
+
|
| 25 |
+
# UI
|
| 26 |
+
st.set_page_config(page_title="Article Topic Classifier")
|
| 27 |
+
st.title("🔬 Article Topic Classifier")
|
| 28 |
+
st.markdown("Enter the **title** and optionally **abstract** of the article.")
|
| 29 |
+
|
| 30 |
+
title = st.text_input("Title", placeholder="e.g. Neural Networks for Quantum Physics")
|
| 31 |
+
abstract = st.text_area("Abstract (optional)", placeholder="e.g. We explore the application of neural nets...")
|
| 32 |
+
|
| 33 |
+
if st.button("Classify"):
|
| 34 |
+
if not title and not abstract:
|
| 35 |
+
st.warning("Please enter at least the title.")
|
| 36 |
+
else:
|
| 37 |
+
tokenizer, model = load_model()
|
| 38 |
+
|
| 39 |
+
text = title + ". " + abstract if abstract else title
|
| 40 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True)
|
| 41 |
+
with torch.no_grad():
|
| 42 |
+
outputs = model(**inputs)
|
| 43 |
+
probs = torch.nn.functional.softmax(outputs.logits[0], dim=-1)
|
| 44 |
+
|
| 45 |
+
with open("labels.json") as f:
|
| 46 |
+
id2label = json.load(f)
|
| 47 |
+
|
| 48 |
+
top_labels = get_top95(id2label, probs)
|
| 49 |
+
|
| 50 |
+
st.subheader("📚 Top topics (95% confidence)")
|
| 51 |
+
for label, prob in top_labels:
|
| 52 |
+
st.markdown(f"- **{label}**: {prob:.3f}")
|