sastsy commited on
Commit
09fa302
·
verified ·
1 Parent(s): 2208bc1

Upload 2 files

Browse files
Files changed (2) hide show
  1. src/label_encoder.json +87 -0
  2. src/streamlit_app.py +125 -37
src/label_encoder.json ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "0": "astro-ph.CO",
3
+ "1": "astro-ph.IM",
4
+ "2": "astro-ph.SR",
5
+ "3": "cmp-lg",
6
+ "4": "cond-mat.dis-nn",
7
+ "5": "cond-mat.mtrl-sci",
8
+ "6": "cond-mat.stat-mech",
9
+ "7": "cs.AI",
10
+ "8": "cs.AR",
11
+ "9": "cs.CC",
12
+ "10": "cs.CE",
13
+ "11": "cs.CG",
14
+ "12": "cs.CL",
15
+ "13": "cs.CR",
16
+ "14": "cs.CV",
17
+ "15": "cs.CY",
18
+ "16": "cs.DB",
19
+ "17": "cs.DC",
20
+ "18": "cs.DL",
21
+ "19": "cs.DM",
22
+ "20": "cs.DS",
23
+ "21": "cs.ET",
24
+ "22": "cs.FL",
25
+ "23": "cs.GR",
26
+ "24": "cs.GT",
27
+ "25": "cs.HC",
28
+ "26": "cs.IR",
29
+ "27": "cs.IT",
30
+ "28": "cs.LG",
31
+ "29": "cs.LO",
32
+ "30": "cs.MA",
33
+ "31": "cs.MM",
34
+ "32": "cs.MS",
35
+ "33": "cs.NA",
36
+ "34": "cs.NE",
37
+ "35": "cs.NI",
38
+ "36": "cs.OH",
39
+ "37": "cs.PF",
40
+ "38": "cs.PL",
41
+ "39": "cs.RO",
42
+ "40": "cs.SD",
43
+ "41": "cs.SE",
44
+ "42": "cs.SI",
45
+ "43": "cs.SY",
46
+ "44": "econ.EM",
47
+ "45": "eess.AS",
48
+ "46": "eess.IV",
49
+ "47": "eess.SP",
50
+ "48": "eess.SY",
51
+ "49": "gr-qc",
52
+ "50": "hep-ph",
53
+ "51": "math.CO",
54
+ "52": "math.DS",
55
+ "53": "math.FA",
56
+ "54": "math.LO",
57
+ "55": "math.NA",
58
+ "56": "math.OC",
59
+ "57": "math.PR",
60
+ "58": "math.ST",
61
+ "59": "nlin.AO",
62
+ "60": "physics.ao-ph",
63
+ "61": "physics.bio-ph",
64
+ "62": "physics.chem-ph",
65
+ "63": "physics.comp-ph",
66
+ "64": "physics.data-an",
67
+ "65": "physics.flu-dyn",
68
+ "66": "physics.geo-ph",
69
+ "67": "physics.med-ph",
70
+ "68": "physics.optics",
71
+ "69": "physics.soc-ph",
72
+ "70": "q-bio.BM",
73
+ "71": "q-bio.GN",
74
+ "72": "q-bio.MN",
75
+ "73": "q-bio.NC",
76
+ "74": "q-bio.PE",
77
+ "75": "q-bio.QM",
78
+ "76": "q-fin.CP",
79
+ "77": "q-fin.PM",
80
+ "78": "q-fin.ST",
81
+ "79": "q-fin.TR",
82
+ "80": "quant-ph",
83
+ "81": "stat.AP",
84
+ "82": "stat.CO",
85
+ "83": "stat.ME",
86
+ "84": "stat.ML"
87
+ }
src/streamlit_app.py CHANGED
@@ -1,40 +1,128 @@
1
- import altair as alt
 
 
 
2
  import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ import html
4
+ import unicodedata
5
  import numpy as np
 
6
  import streamlit as st
7
+ import torch
8
+ from transformers import AutoTokenizer, T5ForSequenceClassification
9
 
10
+ MODEL_DIR = "best_model"
11
+ LABEL_ENCODER = "label_encoder.json"
12
+ MAX_LENGTH = 256
13
+ TOP_PROB = 0.95
14
+ DEVICE = torch.device("cpu")
15
+ MIN_CHARS = 20
16
+ MAX_CHARS = 5000
17
+
18
+ def clean_text(text: str) -> str:
19
+ text = html.unescape(text)
20
+ text = unicodedata.normalize("NFKC", text)
21
+ text = re.sub(r"\$.*?\$", "", text)
22
+ text = re.sub(r"\\[a-zA-Z]+\{.*?\}", "", text)
23
+ text = re.sub(r"\s+", " ", text)
24
+ return text.strip()
25
+
26
+
27
+ def validate(title: str, abstract: str):
28
+ if len(title.strip()) < MIN_CHARS:
29
+ return f"Title too short (at least {MIN_CHARS} characters)"
30
+ if len(abstract.strip()) < MIN_CHARS:
31
+ return f"Abstract too short (at least {MIN_CHARS} characters)"
32
+ if len(title) > MAX_CHARS:
33
+ return f"Title too long (max {MAX_CHARS} characters)"
34
+ if len(abstract) > MAX_CHARS:
35
+ return f"Abstract too long (max {MAX_CHARS} characters)"
36
+ return None
37
+
38
+
39
+ @st.cache_resource(show_spinner="Loading model…")
40
+ def load_model():
41
+ try:
42
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR)
43
+ model = T5ForSequenceClassification.from_pretrained(MODEL_DIR)
44
+ model.to(DEVICE)
45
+ model.eval()
46
+ with open(LABEL_ENCODER) as f:
47
+ id2label = {int(k): v for k, v in json.load(f).items()}
48
+ return tokenizer, model, id2label
49
+ except FileNotFoundError as e:
50
+ st.error(f"Model files not found: {e}")
51
+ st.stop()
52
+ except Exception as e:
53
+ st.error(f"Failed to load model: {e}")
54
+ st.stop()
55
+
56
+
57
+ @st.cache_data(show_spinner=False)
58
+ def predict(title: str, abstract: str):
59
+ tokenizer, model, id2label = load_model()
60
+ if title and abstract:
61
+ text = f"classify: {clean_text(title)} [SEP] {clean_text(abstract)[:1000]}"
62
+ elif title:
63
+ text = f"classify: {clean_text(title)}"
64
+ else:
65
+ text = f"classify: {clean_text(abstract)[:1000]}"
66
+ eos_id = tokenizer.eos_token_id
67
+
68
+ enc = tokenizer(text, max_length=MAX_LENGTH, truncation=True, return_tensors="pt")
69
+ ids = enc["input_ids"][0].tolist()
70
+
71
+ if eos_id is not None and ids.count(eos_id) > 1:
72
+ ids = [t for t in ids[:-1] if t != eos_id] + [eos_id]
73
+
74
+ input_ids = torch.tensor([ids], dtype=torch.long).to(DEVICE)
75
+ attention_mask = torch.ones_like(input_ids)
76
+
77
+ try:
78
+ with torch.no_grad():
79
+ logits = model(input_ids=input_ids, attention_mask=attention_mask).logits
80
+ except Exception as e:
81
+ st.error(f"Model inference failed: {e}")
82
+ st.stop()
83
+
84
+ probs = torch.softmax(logits, dim=-1).cpu().numpy()[0]
85
+ sorted_idx = np.argsort(probs)[::-1]
86
+ cumsum = np.cumsum(probs[sorted_idx])
87
+
88
+ return [
89
+ {"label": id2label.get(int(i), f"class_{i}"), "probability": float(probs[i])}
90
+ for i in sorted_idx[:int(np.searchsorted(cumsum, TOP_PROB)) + 1]
91
+ ]
92
+
93
+
94
+ st.set_page_config(page_title="Paper Classifier", page_icon="📄", layout="centered")
95
+ st.title("📄 Research Paper Classifier")
96
+ st.caption("Predicts arXiv categories from a paper's title and abstract.")
97
+
98
+ load_model()
99
+
100
+ title = st.text_input("Title *", placeholder="e.g. Attention Is All You Need", max_chars=MAX_CHARS)
101
+ abstract = st.text_area("Abstract *", placeholder="Paste the abstract here…", height=200, max_chars=MAX_CHARS)
102
+
103
+ col1, col2 = st.columns([1, 4])
104
+ classify_btn = col1.button("Classify", type="primary", use_container_width=True)
105
+ col2.button("Clear", on_click=lambda: None, use_container_width=True)
106
+
107
+ if classify_btn:
108
+ error = validate(title, abstract)
109
+ if error:
110
+ st.warning(error)
111
+ if not clean_text(title) and not clean_text(abstract):
112
+ st.warning("Please enter at least a title or an abstract.")
113
+ else:
114
+ with st.spinner("Classifying…"):
115
+ results = predict(title, abstract)
116
+
117
+ st.divider()
118
+ st.subheader("Predicted categories")
119
+ st.caption(
120
+ f"Top-95% probability set * {len(results)} label(s) * "
121
+ f"combined probability {sum(r['probability'] for r in results):.1%}"
122
+ )
123
+
124
+ for r in results:
125
+ col1, col2 = st.columns([3, 1])
126
+ col1.markdown(f"**{r['label']}**")
127
+ col2.markdown(f"`{r['probability']:.1%}`")
128
+ st.progress(float(r["probability"]))