Yerzhxn commited on
Commit
17278fa
·
verified ·
1 Parent(s): 475e44d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -49
app.py CHANGED
@@ -1,52 +1,43 @@
1
- import torch
2
- import torch.nn.functional as F
3
- import streamlit as st
4
- from transformers import BertTokenizer, BertForSequenceClassification
5
  import joblib
 
 
 
6
 
7
- # Загрузка модели, токенизатора и label_encoder
8
- model = torch.load("logistic_regression_model.pkl", map_location=torch.device('cpu'))
9
- tokenizer = joblib.load("tfidf_vectorizer.pkl")
10
-
11
- def predict_class_with_probabilities(text, model, tokenizer, max_len=128):
12
- model.eval()
13
-
14
- encodings = tokenizer(
15
- text,
16
- truncation=True,
17
- padding="max_length",
18
- max_length=max_len,
19
- return_tensors="pt"
20
- )
21
-
22
- with torch.no_grad():
23
- outputs = model(**encodings)
24
- logits = outputs.logits
25
-
26
- probabilities = F.softmax(logits, dim=1).squeeze().cpu().numpy()
27
- predicted_class = torch.argmax(logits, dim=1).item()
28
- predicted_label = str(predicted_class)
29
-
30
- return predicted_label, probabilities
31
-
32
- def main():
33
- st.title("Text Classification App with Hugging Face Space")
34
- st.write("Введите текст, чтобы получить предсказание и вероятности классов.")
35
-
36
- input_text = st.text_input("Введите текст для классификации:")
37
-
38
- if st.button("Предсказать"):
39
- if input_text:
40
- predicted_class, probabilities = predict_class_with_probabilities(input_text, model, tokenizer, label_encoder)
41
-
42
- st.write(f"**Предсказанный класс:** {predicted_class}")
43
- st.write("**Вероятности для каждого класса:**")
44
-
45
- for idx, prob in enumerate(probabilities):
46
- class_label = str(idx)
47
- st.write(f"{class_label}: {prob:.4f}")
48
  else:
49
- st.write("Пожалуйста, введите текст для предсказания.")
50
-
51
- if __name__ == "__main__":
52
- main()
 
 
 
 
 
1
  import joblib
2
+ import streamlit as st
3
+ import pandas as pd
4
+ import torch
5
 
6
+ # Загрузка модели и векторизатора
7
+ model = joblib.load('bert_model.pkl')
8
+ vectorizer = joblib.load('bert_tokenizer.pkl')
9
+
10
+ # Загрузка данных
11
+ data = pd.read_excel('DATA_new.xlsx')
12
+
13
+ # Функция для предсказания кода профессии
14
+ def predict_profession_code(profession_name):
15
+ profession_vector = vectorizer.transform([profession_name])
16
+ predicted_code = model.predict(profession_vector)[0]
17
+ return predicted_code
18
+
19
+ # Функция для поиска подходящих курсов по предсказанному коду
20
+ def get_matching_courses(predicted_code):
21
+ matching_courses = data[data['NKZ'] == predicted_code]['Course Title'].drop_duplicates().tolist()
22
+ return matching_courses[:10]
23
+
24
+ # Streamlit интерфейс
25
+ st.title("Поиск курсов по навыкам")
26
+ st.write("Введите навык")
27
+
28
+ profession_name = st.text_input("Название навыка")
29
+
30
+ if st.button("Найти курсы"):
31
+ if profession_name:
32
+ predicted_code = predict_profession_code(profession_name)
33
+ st.success(f"Предсказанный код профессии '{profession_name}': {predicted_code}")
34
+
35
+ matching_courses = get_matching_courses(predicted_code)
36
+ if matching_courses:
37
+ st.write("Подходящие курсы:")
38
+ for course in matching_courses:
39
+ st.write(f"- {course}")
 
 
 
 
 
 
 
40
  else:
41
+ st.write("Нет подходящих курсов для данного навыка.")
42
+ else:
43
+ st.error("Пожалуйста, введите название профессии.")