Team Ai
Apppublic

ISilgiz/finecode-javascript

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py106 linesDownload Raw Back to root
1import streamlit as st2from transformers import RobertaForSequenceClassification, RobertaTokenizer3import torch4import re5from PIL import Image6 7 8# Загрузка модели9@st.cache_resource10def load_model():11    model_name = "models"  # Укажи путь к своей модели или используй URL с Hugging Face12    model = RobertaForSequenceClassification.from_pretrained(model_name)13    tokenizer = RobertaTokenizer.from_pretrained(model_name)14    return model, tokenizer15 16# Функция форматирования кода17def format_code(code):18    content = remove_comments(code)19    lines = content.splitlines()20    joined_instructions = []21    current_instruction = []22    open_braces = 023    open_parentheses = 024 25    for line in lines:26        stripped_line = line.strip()27        if not stripped_line:28            continue29 30        open_braces += stripped_line.count('{')31        open_braces -= stripped_line.count('}')32        open_parentheses += stripped_line.count('(')33        open_parentheses -= stripped_line.count(')')34 35        current_instruction.append(stripped_line)36 37        if open_braces == 0 and open_parentheses == 0 and (stripped_line.endswith(';') or stripped_line.endswith('}') or stripped_line.endswith('{')):38            instruction = ' '.join(current_instruction).strip()39            joined_instructions.append(re.sub(r'\s+', ' ', instruction))40            current_instruction = []41 42    if current_instruction:43        instruction = ' '.join(current_instruction).strip()44        joined_instructions.append(re.sub(r'\s+', ' ', instruction))45 46    return '\n'.join(joined_instructions)47 48# Функция для удаления комментариев из кода49def remove_comments(content):50    content = re.sub(r'//.*', '', content)51    content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL)52    return content53 54# Классификация кода55def 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 result62 63# Интерфейс Streamlit64def main():65    st.title("Классификатор кода")66    67    code_input = st.text_area("Введите код для классификации", height=300)68    69    if st.button("Классифицировать"):70        model, tokenizer = load_model()71        result = classify_code(model, tokenizer, code_input)72        st.write(f"Классификация: {result}")73 74if __name__ == "__main__":75    main()76 77st.markdown("---")  # Добавляет еще одну горизонтальную линию78 79# Заголовок и описание модели80st.title("Оценка модели для классификации кода")81st.markdown("""82Это приложение демонстрирует основные метрики качества обученной модели для классификации корректности кода.83Здесь представлены метрики.84""")85 86st.header("Потери на обучающем наборе данных.")87roc_image = Image.open("m_loss.PNG")  # Замените на ваш путь к файлу изображения88st.image(roc_image, caption='Потери на обучающем наборе данных.', use_column_width=True)89 90st.header("График, отображает норму градиента")91roc_image = Image.open("m_grad_norm.PNG")  # Замените на ваш путь к файлу изображения92st.image(roc_image, caption='График, отображает норму градиента', use_column_width=True)93 94st.header("Скорость обучения модели на протяжении всего процесса обучения.")95roc_image = Image.open("m_learning_rate.PNG")  # Замените на ваш путь к файлу изображения96st.image(roc_image, caption='Скорость обучения модели на протяжении всего процесса обучения.', use_column_width=True)97 98st.header("На графике показано, как изменяется метрика train/epoch в зависимости от шага (Step) в процессе обучения модели машинного обучения.")99roc_image = Image.open("m_epoch.PNG")  # Замените на ваш путь к файлу изображения100st.image(roc_image, caption='На графике показано, как изменяется метрика train/epoch в зависимости от шага (Step) в процессе обучения модели машинного обучения.', use_column_width=True)101 102# Personal information at the bottom of the interface103st.markdown("---")  # Adds a horizontal line for separation104st.markdown("**Full Name:** ilgiz Sulaymanov")105st.markdown("**Place of Study:** Zhusup Balasagyn Kyrgyz National University")106st.markdown("**Email:** sulaymanovilgiz00@gmail.com")