import streamlit as st
import torch
import numpy as np
import pandas as pd
from transformers import AutoTokenizer, AutoModelForSequenceClassification
@st.cache_data
def get_header():
return """
Article Taxonomy PRO
Model predicts top taxonomy tags (Computer Science, Mathematics, Physics, Statistics)\n
from your title and summary, sorted by relevance.
"""
st.markdown(get_header(), unsafe_allow_html=True)
@st.cache_resource(show_spinner=False)
def load_model():
path_model = './checkpoint'
best_model = AutoModelForSequenceClassification.from_pretrained(path_model)
path_tokenizer = './tokenizer'
tokenizer = AutoTokenizer.from_pretrained(path_tokenizer)
return best_model, tokenizer
def tokenize_function(examples, tokenizer):
return tokenizer(examples, padding="max_length", truncation=True)
if 'model' not in st.session_state:
st.session_state.model, st.session_state.tokenizer = load_model()
id_to_tag = {
0: 'Computer Science',
1: 'Mathematics',
2: 'Physics',
3: 'Statistics'
}
st.header("Try to use!")
with st.form("article_form"):
title = st.text_area("Title*", max_chars=300, help="Your article's headline or main title")
text = st.text_area("Summary", height=400, help="Provide the article's abstract or key points")
submitted = st.form_submit_button("Submit")
if submitted:
if not title:
st.error("Please fill in all required fields (*)")
else:
text = text or ""
prompt = [title + '[SEP]' + text]
inputs = st.session_state.tokenizer(
text,
return_tensors="pt",
padding=True,
truncation=True,
max_length=512
)
with torch.no_grad():
logits = st.session_state.model(**inputs).logits[0]
probs = torch.softmax(logits, dim=0).numpy()
sorted_indices = np.argsort(-probs)
cum_sum = np.cumsum(probs[sorted_indices])
ids = sorted_indices[cum_sum < 0.95]
tags = [id_to_tag[id_] for id_ in ids]
st.success(tags[0])
if len(tags) > 1:
st.warning(tags[1])
if len(tags) > 2:
st.error(tags[2])
st.balloons()