ISilgiz commited on
Commit
2531924
·
verified ·
1 Parent(s): c082595

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -0
app.py CHANGED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from transformers import RobertaForSequenceClassification, RobertaTokenizer
3
+ import torch
4
+ import re
5
+ import streamlit as st
6
+ from PIL import Image
7
+
8
+ # Функция для загрузки модели
9
+ @st.cache_resource
10
+ def load_model():
11
+ model_name = "models_cpp" # Замените на путь к вашей модели
12
+ model = RobertaForSequenceClassification.from_pretrained(model_name)
13
+ tokenizer = RobertaTokenizer.from_pretrained(model_name)
14
+ return model, tokenizer
15
+
16
+ # Функция для удаления комментариев из кода
17
+ def remove_comments(content):
18
+ content = re.sub(r'//.*', '', content)
19
+ content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL)
20
+ return content
21
+
22
+ # Функция для форматирования кода
23
+ def format_code(code):
24
+ content = remove_comments(code)
25
+ lines = content.splitlines()
26
+ joined_instructions = []
27
+ current_instruction = []
28
+ open_braces = 0
29
+ open_parentheses = 0
30
+
31
+ for line in lines:
32
+ stripped_line = line.strip()
33
+ if not stripped_line:
34
+ continue
35
+
36
+ open_braces += stripped_line.count('{')
37
+ open_braces -= stripped_line.count('}')
38
+ open_parentheses += stripped_line.count('(')
39
+ open_parentheses -= stripped_line.count(')')
40
+
41
+ current_instruction.append(stripped_line)
42
+
43
+ if open_braces == 0 and open_parentheses == 0 and (stripped_line.endswith(';') or stripped_line.endswith('}') or stripped_line.endswith('{')):
44
+ instruction = ' '.join(current_instruction).strip()
45
+ joined_instructions.append(re.sub(r'\s+', ' ', instruction))
46
+ current_instruction = []
47
+
48
+ if current_instruction:
49
+ instruction = ' '.join(current_instruction).strip()
50
+ joined_instructions.append(re.sub(r'\s+', ' ', instruction))
51
+
52
+ return '\n'.join(joined_instructions)
53
+
54
+ # Функция для классификации кода
55
+ def classify_code(model, tokenizer, code):
56
+ formatted_code = format_code(code)
57
+ inputs = tokenizer(formatted_code, return_tensors="pt")
58
+ outputs = model(**inputs)
59
+ prediction = torch.argmax(outputs.logits, dim=1).item()
60
+ result = "Правильный" if prediction == 1 else "Неправильный"
61
+ return result
62
+
63
+ # Интерфейс Streamlit
64
+ st.title("Классификатор кода")
65
+ st.markdown("Введите свой код в текстовое поле ниже и нажмите кнопку для классификации.")
66
+
67
+ # Ввод кода через текстовое поле
68
+ code_input = st.text_area("Введите ваш код здесь", height=300)
69
+
70
+ # Кнопка для классификации
71
+ if st.button("Классифицировать код"):
72
+ model, tokenizer = load_model() # Загрузка модели
73
+ result = classify_code(model, tokenizer, code_input)
74
+ st.write(f"Классификация: **{result}**")
75
+
76
+ st.markdown("---") # Добавляет еще одну горизонтальную линию
77
+
78
+ # Заголовок и описание модели
79
+ st.title("Оценка модели для классификации кода")
80
+ st.markdown("""
81
+ Это приложение демонстрирует основные метрики качества обученной модели для классификации корректности кода.
82
+ Здесь представлены метрики, такие как Accuracy, Precision, Recall, F1-Score, ROC-кривая и матрица ошибок.
83
+ """)
84
+
85
+ st.header("Метрики модели")
86
+ metrics = {
87
+ "Ошибка на обучающей выборке (Train Loss)": 0.2648,
88
+ "Ошибка на тестовой выборке (Eval Loss)": 0.1514,
89
+ "Точность (Accuracy)": 0.9545,
90
+ "Полнота (Recall)": 0.9390,
91
+ "Точность предсказаний (Precision)": 0.9694,
92
+ "F1-мера (F1 Score)": 0.9539,
93
+ "Логарифмическая потеря (Log Loss)": 1.3854,
94
+ "Коэффициент корреляции Мэтьюса (MCC)": 0.9095,
95
+ "Среднеквадратичная ошибка (MSE)": 7.9419,
96
+ "Корень из среднеквадратичной ошибки (RMSE)": 2.8181,
97
+ "Каппа Коэна (Cohen's Kappa)": 0.9090,
98
+ "Точность в топ-5 (Top-5 Accuracy)": 1.0000,
99
+ "Площадь под PR-кривой (PR AUC)": 0.9917,
100
+ "Сбалансированная точность (Balanced Accuracy)": 0.9546,
101
+ "Индекс Жаккара (Jaccard Index)": 0.9119
102
+ }
103
+
104
+ # Отображение метрик
105
+ for metric_name, value in metrics.items():
106
+ st.write(f"**{metric_name}:** {value:.4f}")
107
+
108
+ # Вставка изображения ROC-кривой
109
+ st.header("ROC-кривая")
110
+ roc_image = Image.open("img_2.png") # Замените на ваш путь к файлу изображения
111
+ st.image(roc_image, caption='ROC-кривая', use_column_width=True)
112
+
113
+ # Вставка изображения матрицы ошибок
114
+ st.header("Матрица ошибок")
115
+ confusion_image = Image.open("img_1.png") # Замените на ваш путь к файлу изображения
116
+ st.image(confusion_image, caption='Матрица ошибок', use_column_width=True)
117
+
118
+
119
+ # Personal information at the bottom of the interface
120
+ st.markdown("---") # Adds a horizontal line for separation
121
+ st.markdown("**Full Name:** ilgiz Sulaymanov")
122
+ st.markdown("**Place of Study:** Zhusup Balasagyn Kyrgyz National University")
123
+ st.markdown("**Email:** sulaymanovilgiz00@gmail.com")