Update app.py
Browse files
app.py
CHANGED
|
@@ -1,32 +1,166 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
from transformers import pipeline
|
| 3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
# Загружаем модель (замените на вашу модель, если нужно)
|
| 5 |
-
|
| 6 |
try:
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
except OSError as e:
|
| 9 |
st.error(f"Ошибка загрузки модели: {e}. Убедитесь, что модель доступна или укажите другую.")
|
| 10 |
st.stop() # Ос��ановка выполнения приложения при ошибке
|
| 11 |
|
| 12 |
|
| 13 |
-
|
| 14 |
-
# tokenizer =
|
| 15 |
-
# topic_classifier = pipeline("text-classification", model=model, tokenizer=tokenizer)
|
| 16 |
-
topic_classifier = pipeline("text-classification")
|
| 17 |
-
|
| 18 |
-
text = "This is an example sentence for topic classification."
|
| 19 |
-
result = topic_classifier(text)
|
| 20 |
-
print(result)
|
| 21 |
-
|
| 22 |
-
def classify_text(title, description, candidate_labels, show_all=False, threshold=0.95):
|
| 23 |
"""
|
| 24 |
Классифицирует текст и возвращает результаты в отсортированном виде.
|
| 25 |
|
| 26 |
Args:
|
| 27 |
title (str): Заголовок текста.
|
| 28 |
description (str): Краткое описание текста.
|
| 29 |
-
candidate_labels (list): Список меток-кандидатов.
|
| 30 |
show_all (bool): Показывать ли все результаты, независимо от порога.
|
| 31 |
threshold (float): Порог суммарной вероятности.
|
| 32 |
|
|
@@ -34,23 +168,28 @@ def classify_text(title, description, candidate_labels, show_all=False, threshol
|
|
| 34 |
list: Отсортированный список результатов классификации.
|
| 35 |
"""
|
| 36 |
text = f"{title} {description}" # Объединяем заголовок и описание
|
|
|
|
| 37 |
try:
|
|
|
|
| 38 |
results = topic_classifier(text)
|
| 39 |
# results = topic_classifier(text, candidate_labels, multi_label=True) # multi_label=True для нескольких меток
|
| 40 |
except Exception as e:
|
| 41 |
st.error(f"Ошибка классификации: {e}")
|
| 42 |
return []
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
| 46 |
|
| 47 |
if show_all:
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
| 49 |
else:
|
| 50 |
cumulative_prob = 0
|
| 51 |
filtered_results = []
|
| 52 |
-
for
|
| 53 |
-
filtered_results.append((label, score))
|
| 54 |
cumulative_prob += score
|
| 55 |
if cumulative_prob >= threshold:
|
| 56 |
break
|
|
@@ -64,18 +203,13 @@ st.title("Классификация статей")
|
|
| 64 |
title = st.text_input("Заголовок статьи")
|
| 65 |
description = st.text_area("Краткое описание статьи", height=150)
|
| 66 |
|
| 67 |
-
# Ввод меток-кандидатов (разделенных запятыми)
|
| 68 |
-
default_labels = "политика, экономика, спорт, культура, технологии, наука, происшествия"
|
| 69 |
-
candidate_labels_str = st.text_input("Метки-кандидаты (через запятую)", default_labels)
|
| 70 |
-
candidate_labels = [label.strip() for label in candidate_labels_str.split(",") if label.strip()]
|
| 71 |
-
|
| 72 |
# Кнопка "Классифицировать"
|
| 73 |
if st.button("Классифицировать"):
|
| 74 |
-
if not title or not description
|
| 75 |
-
st.warning("Пожалуйста, заполните
|
| 76 |
else:
|
| 77 |
with st.spinner("Идет классификация..."): # Индикатор загрузки
|
| 78 |
-
results = classify_text(title, description
|
| 79 |
if results:
|
| 80 |
st.subheader("Результаты классификации (с ограничением по вероятности):")
|
| 81 |
for label, score in results:
|
|
@@ -90,5 +224,5 @@ if st.button("Классифицировать"):
|
|
| 90 |
else:
|
| 91 |
st.info("Не удалось получить результаты классификации.")
|
| 92 |
|
| 93 |
-
elif title or description
|
| 94 |
st.warning("Пожалуйста, заполните все поля.")
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
from transformers import pipeline
|
| 3 |
|
| 4 |
+
id_to_cat = {0: 'Performance',
|
| 5 |
+
1: 'Molecular Networks',
|
| 6 |
+
2: 'Operating Systems',
|
| 7 |
+
3: 'High Energy Astrophysical Phenomena',
|
| 8 |
+
4: 'Computational Finance',
|
| 9 |
+
5: 'General Finance',
|
| 10 |
+
6: 'Astrophysics of Galaxies',
|
| 11 |
+
7: 'Portfolio Management',
|
| 12 |
+
8: 'Functional Analysis',
|
| 13 |
+
9: 'Quantitative Methods',
|
| 14 |
+
10: 'Mathematical Software',
|
| 15 |
+
11: 'Computation',
|
| 16 |
+
12: 'Chemical Physics',
|
| 17 |
+
13: 'Information Theory',
|
| 18 |
+
14: 'Classical Physics',
|
| 19 |
+
15: 'Subcellular Processes',
|
| 20 |
+
16: 'Medical Physics',
|
| 21 |
+
17: 'Differential Geometry',
|
| 22 |
+
18: 'Biomolecules',
|
| 23 |
+
19: 'Metric Geometry',
|
| 24 |
+
20: 'Cryptography and Security',
|
| 25 |
+
21: 'Instrumentation and Methods for Astrophysics',
|
| 26 |
+
22: 'General Mathematics',
|
| 27 |
+
23: 'Computational Complexity',
|
| 28 |
+
24: 'Soft Condensed Matter',
|
| 29 |
+
25: 'Analysis of PDEs',
|
| 30 |
+
26: 'Human-Computer Interaction',
|
| 31 |
+
27: 'Classical Analysis and ODEs',
|
| 32 |
+
28: 'Genomics',
|
| 33 |
+
29: 'Optimization and Control',
|
| 34 |
+
30: 'Applied Physics',
|
| 35 |
+
31: 'Computational Engineering, Finance, and Science',
|
| 36 |
+
32: 'Quantum Algebra',
|
| 37 |
+
33: 'Other Condensed Matter',
|
| 38 |
+
34: 'Category Theory',
|
| 39 |
+
35: 'Popular Physics',
|
| 40 |
+
36: 'General Topology',
|
| 41 |
+
37: 'Algebraic Topology',
|
| 42 |
+
38: 'Trading and Market Microstructure',
|
| 43 |
+
39: 'Numerical Analysis',
|
| 44 |
+
40: 'Applications',
|
| 45 |
+
41: 'Group Theory',
|
| 46 |
+
42: 'Cosmology and Nongalactic Astrophysics',
|
| 47 |
+
43: 'Mathematical Physics',
|
| 48 |
+
44: 'Econometrics',
|
| 49 |
+
45: 'Systems and Control',
|
| 50 |
+
46: 'Graphics',
|
| 51 |
+
47: 'Data Structures and Algorithms',
|
| 52 |
+
48: 'Operator Algebras',
|
| 53 |
+
49: 'Number Theory',
|
| 54 |
+
50: 'Robotics',
|
| 55 |
+
51: 'Nuclear Theory',
|
| 56 |
+
52: 'Neural and Evolutionary Computing',
|
| 57 |
+
53: 'Multimedia',
|
| 58 |
+
54: 'Information Retrieval',
|
| 59 |
+
55: 'Image and Video Processing',
|
| 60 |
+
56: 'Rings and Algebras',
|
| 61 |
+
57: 'Instrumentation and Detectors',
|
| 62 |
+
58: 'Social and Information Networks',
|
| 63 |
+
59: 'High Energy Physics - Lattice',
|
| 64 |
+
60: 'Emerging Technologies',
|
| 65 |
+
61: 'Strongly Correlated Electrons',
|
| 66 |
+
62: 'Representation Theory',
|
| 67 |
+
63: 'Space Physics',
|
| 68 |
+
64: 'Risk Management',
|
| 69 |
+
65: 'Disordered Systems and Neural Networks',
|
| 70 |
+
66: 'Databases',
|
| 71 |
+
67: 'Networking and Internet Architecture',
|
| 72 |
+
68: 'Computers and Society',
|
| 73 |
+
69: 'Hardware Architecture',
|
| 74 |
+
70: 'Chaotic Dynamics',
|
| 75 |
+
71: 'Mesoscale and Nanoscale Physics',
|
| 76 |
+
72: 'Computational Geometry',
|
| 77 |
+
73: 'Commutative Algebra',
|
| 78 |
+
74: 'Statistics Theory',
|
| 79 |
+
75: 'General Literature',
|
| 80 |
+
76: 'Physics and Society',
|
| 81 |
+
77: 'Geophysics',
|
| 82 |
+
78: 'Economics',
|
| 83 |
+
79: 'Quantum Physics',
|
| 84 |
+
80: 'Symbolic Computation',
|
| 85 |
+
81: 'Computational Physics',
|
| 86 |
+
82: 'Sound',
|
| 87 |
+
83: 'Multiagent Systems',
|
| 88 |
+
84: 'Signal Processing',
|
| 89 |
+
85: 'Adaptation and Self-Organizing Systems',
|
| 90 |
+
86: 'Other Computer Science',
|
| 91 |
+
87: 'Other Quantitative Biology',
|
| 92 |
+
88: 'Formal Languages and Automata Theory',
|
| 93 |
+
89: 'Populations and Evolution',
|
| 94 |
+
90: 'Spectral Theory',
|
| 95 |
+
91: 'Pattern Formation and Solitons',
|
| 96 |
+
92: 'Methodology',
|
| 97 |
+
93: 'Biological Physics',
|
| 98 |
+
94: 'General Physics',
|
| 99 |
+
95: 'Logic in Computer Science',
|
| 100 |
+
96: 'Complex Variables',
|
| 101 |
+
97: 'Optics',
|
| 102 |
+
98: 'Discrete Mathematics',
|
| 103 |
+
99: 'History and Overview',
|
| 104 |
+
100: 'Programming Languages',
|
| 105 |
+
101: 'Audio and Speech Processing',
|
| 106 |
+
102: 'Algebraic Geometry',
|
| 107 |
+
103: 'Neurons and Cognition',
|
| 108 |
+
104: 'High Energy Physics - Phenomenology',
|
| 109 |
+
105: 'History and Philosophy of Physics',
|
| 110 |
+
106: 'Earth and Planetary Astrophysics',
|
| 111 |
+
107: 'Pricing of Securities',
|
| 112 |
+
108: 'Distributed, Parallel, and Cluster Computing',
|
| 113 |
+
109: 'Tissues and Organs',
|
| 114 |
+
110: 'Cellular Automata and Lattice Gases',
|
| 115 |
+
111: 'Statistical Finance',
|
| 116 |
+
112: 'Materials Science',
|
| 117 |
+
113: 'High Energy Physics - Theory',
|
| 118 |
+
114: 'Digital Libraries',
|
| 119 |
+
115: 'Other Statistics',
|
| 120 |
+
116: 'Superconductivity',
|
| 121 |
+
117: 'Cell Behavior',
|
| 122 |
+
118: 'General Relativity and Quantum Cosmology',
|
| 123 |
+
119: 'Dynamical Systems',
|
| 124 |
+
120: 'Statistical Mechanics',
|
| 125 |
+
121: 'Fluid Dynamics',
|
| 126 |
+
122: 'Computer Science and Game Theory',
|
| 127 |
+
123: 'Logic',
|
| 128 |
+
124: 'Computer Vision and Pattern Recognition',
|
| 129 |
+
125: 'Solar and Stellar Astrophysics',
|
| 130 |
+
126: 'High Energy Physics - Experiment',
|
| 131 |
+
127: 'Software Engineering',
|
| 132 |
+
128: 'Combinatorics',
|
| 133 |
+
129: 'Data Analysis, Statistics and Probability',
|
| 134 |
+
130: 'Machine Learning',
|
| 135 |
+
131: 'Probability',
|
| 136 |
+
132: 'Atmospheric and Oceanic Physics',
|
| 137 |
+
133: 'Geometric Topology',
|
| 138 |
+
134: 'Computation and Language',
|
| 139 |
+
135: 'Quantum Gases',
|
| 140 |
+
136: 'Nuclear Experiment',
|
| 141 |
+
137: 'Artificial Intelligence'}
|
| 142 |
+
|
| 143 |
# Загружаем модель (замените на вашу модель, если нужно)
|
| 144 |
+
model_name = ''
|
| 145 |
try:
|
| 146 |
+
tokenizer = AutoTokenizer.from_pretrained('distilbert-base-cased')
|
| 147 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 148 |
+
model_name,
|
| 149 |
+
num_labels=len(id_to_cat),
|
| 150 |
+
problem_type="multi_label_classification"
|
| 151 |
+
)
|
| 152 |
except OSError as e:
|
| 153 |
st.error(f"Ошибка загрузки модели: {e}. Убедитесь, что модель доступна или укажите другую.")
|
| 154 |
st.stop() # Ос��ановка выполнения приложения при ошибке
|
| 155 |
|
| 156 |
|
| 157 |
+
def classify_text(title, description, show_all=False, threshold=0.95):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
"""
|
| 159 |
Классифицирует текст и возвращает результаты в отсортированном виде.
|
| 160 |
|
| 161 |
Args:
|
| 162 |
title (str): Заголовок текста.
|
| 163 |
description (str): Краткое описание текста.
|
|
|
|
| 164 |
show_all (bool): Показывать ли все результаты, независимо от порога.
|
| 165 |
threshold (float): Порог суммарной вероятности.
|
| 166 |
|
|
|
|
| 168 |
list: Отсортированный список результатов классификации.
|
| 169 |
"""
|
| 170 |
text = f"{title} {description}" # Объединяем заголовок и описание
|
| 171 |
+
topic_classifier = pipeline("text-classification", model=model, tokenizer=tokenizer, top_k = len(id_to_cat))
|
| 172 |
try:
|
| 173 |
+
|
| 174 |
results = topic_classifier(text)
|
| 175 |
# results = topic_classifier(text, candidate_labels, multi_label=True) # multi_label=True для нескольких меток
|
| 176 |
except Exception as e:
|
| 177 |
st.error(f"Ошибка классификации: {e}")
|
| 178 |
return []
|
| 179 |
|
| 180 |
+
for i in results[0]:
|
| 181 |
+
i['label'] = id_to_category[int(i['label'].split('_')[1])]
|
| 182 |
|
| 183 |
if show_all:
|
| 184 |
+
filtered_results = []
|
| 185 |
+
for i in results[0]:
|
| 186 |
+
filtered_results.append((i['label'], i['score']))
|
| 187 |
+
return filtered_results
|
| 188 |
else:
|
| 189 |
cumulative_prob = 0
|
| 190 |
filtered_results = []
|
| 191 |
+
for i in results[0]:
|
| 192 |
+
filtered_results.append((i['label'], i['score']))
|
| 193 |
cumulative_prob += score
|
| 194 |
if cumulative_prob >= threshold:
|
| 195 |
break
|
|
|
|
| 203 |
title = st.text_input("Заголовок статьи")
|
| 204 |
description = st.text_area("Краткое описание статьи", height=150)
|
| 205 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
# Кнопка "Классифицировать"
|
| 207 |
if st.button("Классифицировать"):
|
| 208 |
+
if not title or not description:
|
| 209 |
+
st.warning("Пожалуйста, заполните хотя бы одно поле.")
|
| 210 |
else:
|
| 211 |
with st.spinner("Идет классификация..."): # Индикатор загрузки
|
| 212 |
+
results = classify_text(title, description)
|
| 213 |
if results:
|
| 214 |
st.subheader("Результаты классификации (с ограничением по вероятности):")
|
| 215 |
for label, score in results:
|
|
|
|
| 224 |
else:
|
| 225 |
st.info("Не удалось получить результаты классификации.")
|
| 226 |
|
| 227 |
+
elif title or description: #небольшой костыль, чтобы при старте не было предупреждения
|
| 228 |
st.warning("Пожалуйста, заполните все поля.")
|