Spaces:
Runtime error
Runtime error
Download app.py from ntizhin/ArticleTaxonomy: direct link, hf CLI and curl.
- Browser
- Download file 2.5 kB
-
https://huggingface.co/spaces/ntizhin/ArticleTaxonomy/resolve/main/app.py
- Command line
-
hf download hf://spaces/ntizhin/ArticleTaxonomy/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ntizhin/ArticleTaxonomy/resolve/main/app.py
2.5 kB
| import streamlit as st | |
| import torch | |
| import numpy as np | |
| import pandas as pd | |
| from transformers import AutoTokenizer, AutoModelForSequenceClassification | |
| def get_header(): | |
| return """ | |
| <h1 style='text-align: center; margin-bottom: 0.5rem;'>Article Taxonomy PRO</h1> | |
| <div style='text-align: center; font-style: italic; margin-bottom: 2rem;'> | |
| Model predicts top taxonomy tags (Computer Science, Mathematics, Physics, Statistics)\n | |
| from your title and summary, sorted by relevance. | |
| </div> | |
| """ | |
| st.markdown(get_header(), unsafe_allow_html=True) | |
| 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() | |