Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| from transformers import RobertaForSequenceClassification, RobertaTokenizer | |
| import torch | |
| import re | |
| import streamlit as st | |
| from PIL import Image | |
| # Функция для загрузки модели | |
| def load_model(): | |
| model_name = "models_cpp" # Замените на путь к вашей модели | |
| model = RobertaForSequenceClassification.from_pretrained(model_name) | |
| tokenizer = RobertaTokenizer.from_pretrained(model_name) | |
| return model, tokenizer | |
| # Функция для удаления комментариев из кода | |
| def remove_comments(content): | |
| content = re.sub(r'//.*', '', content) | |
| content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL) | |
| return content | |
| # Функция для форматирования кода | |
| def format_code(code): | |
| content = remove_comments(code) | |
| lines = content.splitlines() | |
| joined_instructions = [] | |
| current_instruction = [] | |
| open_braces = 0 | |
| open_parentheses = 0 | |
| for line in lines: | |
| stripped_line = line.strip() | |
| if not stripped_line: | |
| continue | |
| open_braces += stripped_line.count('{') | |
| open_braces -= stripped_line.count('}') | |
| open_parentheses += stripped_line.count('(') | |
| open_parentheses -= stripped_line.count(')') | |
| current_instruction.append(stripped_line) | |
| if open_braces == 0 and open_parentheses == 0 and (stripped_line.endswith(';') or stripped_line.endswith('}') or stripped_line.endswith('{')): | |
| instruction = ' '.join(current_instruction).strip() | |
| joined_instructions.append(re.sub(r'\s+', ' ', instruction)) | |
| current_instruction = [] | |
| if current_instruction: | |
| instruction = ' '.join(current_instruction).strip() | |
| joined_instructions.append(re.sub(r'\s+', ' ', instruction)) | |
| return '\n'.join(joined_instructions) | |
| # Функция для классификации кода | |
| def classify_code(model, tokenizer, code): | |
| formatted_code = format_code(code) | |
| inputs = tokenizer(formatted_code, return_tensors="pt") | |
| outputs = model(**inputs) | |
| prediction = torch.argmax(outputs.logits, dim=1).item() | |
| result = "Правильный" if prediction == 1 else "Неправильный" | |
| return result | |
| # Интерфейс Streamlit | |
| st.title("Классификатор кода") | |
| st.markdown("Введите свой код в текстовое поле ниже и нажмите кнопку для классификации.") | |
| # Ввод кода через текстовое поле | |
| code_input = st.text_area("Введите ваш код здесь", height=300) | |
| # Кнопка для классификации | |
| if st.button("Классифицировать код"): | |
| model, tokenizer = load_model() # Загрузка модели | |
| result = classify_code(model, tokenizer, code_input) | |
| st.write(f"Классификация: **{result}**") | |
| st.markdown("---") # Добавляет еще одну горизонтальную линию | |
| # Заголовок и описание модели | |
| st.title("Оценка модели для классификации кода") | |
| st.markdown(""" | |
| Это приложение демонстрирует основные метрики качества обученной модели для классификации корректности кода. | |
| Здесь представлены метрики, такие как Accuracy, Precision, Recall, F1-Score, ROC-кривая и матрица ошибок. | |
| """) | |
| st.header("Метрики модели") | |
| metrics = { | |
| "Ошибка на обучающей выборке (Train Loss)": 0.2648, | |
| "Ошибка на тестовой выборке (Eval Loss)": 0.1514, | |
| "Точность (Accuracy)": 0.9545, | |
| "Полнота (Recall)": 0.9390, | |
| "Точность предсказаний (Precision)": 0.9694, | |
| "F1-мера (F1 Score)": 0.9539, | |
| "Логарифмическая потеря (Log Loss)": 1.3854, | |
| "Коэффициент корреляции Мэтьюса (MCC)": 0.9095, | |
| "Среднеквадратичная ошибка (MSE)": 7.9419, | |
| "Корень из среднеквадратичной ошибки (RMSE)": 2.8181, | |
| "Каппа Коэна (Cohen's Kappa)": 0.9090, | |
| "Точность в топ-5 (Top-5 Accuracy)": 1.0000, | |
| "Площадь под PR-кривой (PR AUC)": 0.9917, | |
| "Сбалансированная точность (Balanced Accuracy)": 0.9546, | |
| "Индекс Жаккара (Jaccard Index)": 0.9119 | |
| } | |
| # Отображение метрик | |
| for metric_name, value in metrics.items(): | |
| st.write(f"**{metric_name}:** {value:.4f}") | |
| # Вставка изображения ROC-кривой | |
| st.header("ROC-кривая") | |
| roc_image = Image.open("img_2.png") # Замените на ваш путь к файлу изображения | |
| st.image(roc_image, caption='ROC-кривая', use_column_width=True) | |
| # Вставка изображения матрицы ошибок | |
| st.header("Матрица ошибок") | |
| confusion_image = Image.open("img_1.png") # Замените на ваш путь к файлу изображения | |
| st.image(confusion_image, caption='Матрица ошибок', use_column_width=True) | |
| # Personal information at the bottom of the interface | |
| st.markdown("---") # Adds a horizontal line for separation | |
| st.markdown("**Full Name:** ilgiz Sulaymanov") | |
| st.markdown("**Place of Study:** Zhusup Balasagyn Kyrgyz National University") | |
| st.markdown("**Email:** sulaymanovilgiz00@gmail.com") |