Spaces:
Sleeping
Sleeping
File size: 3,335 Bytes
30702d2 9dcd727 05896d5 67773b7 3ef7005 619e320 05896d5 ebb24cc 05896d5 67773b7 05896d5 3ef7005 05896d5 9dcd727 faf3ebe 9dcd727 05896d5 9dcd727 05896d5 9dcd727 05896d5 9dcd727 44a96bc 9dcd727 fc22fb7 9dcd727 aa601b6 9b1f066 fbf6406 05896d5 8340440 9dcd727 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
import streamlit as st
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
import re
from nltk.tokenize import RegexpTokenizer
from bs4 import BeautifulSoup as bs
from nltk.corpus import stopwords
import nltk
nltk.download('stopwords')
nltk.download('punkt')
import pandas as pd
# Замените 'username/имя-вашей-модели' на путь к вашей модели на Hugging Face
model_name = 'Yerzhxn/class_vac'
# Загрузка токенизатора и модели
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)
# Перемещение модели на устройство (если есть GPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
def preprocess(sentence):
soup = bs(sentence, features="html.parser")
sentence = soup.get_text()
soup = bs(sentence, features="html.parser")
sentence = soup.get_text()
sentence = str(sentence)
sentence = sentence.lower()
sentence = sentence.replace('{html}',"")
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', sentence)
rem_url = re.sub(r'http\S+', '',cleantext)
rem_num = re.sub('[0-9]+', '', rem_url)
tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize(rem_num)
filtered_words = [w for w in tokens if not w in stopwords.words('russian')]
return " ".join(filtered_words)
# Интерфейс Streamlit
st.title("Тестирование классификации текста")
st.write("Введите текст, чтобы узнать предсказанный класс.")
# Поле ввода текста
input_text = st.text_area("Введите текст здесь", "")
df = pd.read_excel('me.xlsx')
if st.button("Предсказать"):
if input_text:
input_text = preprocess(input_text)
# Преобразование текста в формат, подходящий для модели
inputs = tokenizer(input_text, return_tensors="pt", truncation=True, padding=True)
inputs = {key: value.to(device) for key, value in inputs.items()}
# Прогон текста через модель и получение предсказания
with torch.no_grad():
outputs = model(**inputs)
# Преобразование выходных данных в вероятности
logits = outputs.logits
probabilities = F.softmax(logits, dim=1)
# Определение класса и его вероятности
max_prob, predicted_class = torch.max(probabilities, dim=1)
# Проверка вероятности для отображения результата
if max_prob.item() > 0.35:
st.write(f"Предсказанный класс: {predicted_class.item()}, вероятность: {max_prob.item():.2f}")
dataframe = df[df['label']==predicted_class.item()]
str1 = dataframe['PROF_NAME']
st.write(str1.iloc[0])
else:
st.write("Модель не уверена в предсказании (вероятность меньше 35%).")
else:
st.write("Пожалуйста, введите текст для классификации.")
|