/
serkatrinaa
/
final_project_base
Обзор
Документация
Войти
/
serkatrinaa
/
final_project_base
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/utils.py
219 строк
6 KB
Katya Mashnina
project done
28 дек 2025, 23:22
28 дек 2025, 23:22
cc88ff0
Код
Авторство
О чём код?
""" Utility functions for the essay grading system. """ import json import os from typing import List, Optional def load_text_file(filepath: str) -> str: """ Load text content from a file. Args: filepath: Path to the text file. Returns: Content of the file as string. Raises: FileNotFoundError: If file doesn't exist. IOError: If file cannot be read. """ if not os.path.exists(filepath): raise FileNotFoundError(f"File not found: {filepath}") with open(filepath, 'r', encoding='utf-8') as f: return f.read() def save_text_file(filepath: str, content: str) -> None: """ Save text content to a file. Args: filepath: Path to save the file. content: Text content to save. """ os.makedirs(os.path.dirname(filepath) or '.', exist_ok=True) with open(filepath, 'w', encoding='utf-8') as f: f.write(content) def load_reference_texts(directory: str) -> List[str]: """ Load all text files from a directory as reference texts. Args: directory: Path to directory containing reference texts. Returns: List of text contents from all .txt files in directory. """ if not os.path.isdir(directory): return [] texts = [] for filename in os.listdir(directory): if filename.endswith('.txt'): filepath = os.path.join(directory, filename) try: texts.append(load_text_file(filepath)) except (IOError, UnicodeDecodeError): continue return texts def export_result_to_json( result: dict, filepath: str, indent: int = 2 ) -> None: """ Export grading result to JSON file. Args: result: Grading result dictionary. filepath: Path to save JSON file. indent: JSON indentation level. """ os.makedirs(os.path.dirname(filepath) or '.', exist_ok=True) with open(filepath, 'w', encoding='utf-8') as f: json.dump(result, f, ensure_ascii=False, indent=indent) def load_result_from_json(filepath: str) -> dict: """ Load grading result from JSON file. Args: filepath: Path to JSON file. Returns: Grading result dictionary. """ with open(filepath, 'r', encoding='utf-8') as f: return json.load(f) def format_score_bar( score: float, max_score: float, width: int = 20 ) -> str: """ Create a visual progress bar for a score. Args: score: Current score. max_score: Maximum possible score. width: Width of the bar in characters. Returns: String representation of progress bar. """ if max_score == 0: return "[" + "-" * width + "]" ratio = min(score / max_score, 1.0) filled = int(ratio * width) empty = width - filled bar = "█" * filled + "░" * empty percentage = ratio * 100 return f"[{bar}] {percentage:.1f}%" def print_colored_result(result: dict) -> None: """ Print grading result with visual formatting. Args: result: Grading result dictionary. """ print("\n" + "=" * 60) print(" РЕЗУЛЬТАТЫ ОЦЕНИВАНИЯ ЭССЕ") print("=" * 60) score = result.get("total_score", 0) max_score = result.get("max_score", 100) grade = result.get("grade", "N/A") letter = result.get("letter_grade", "N/A") print(f"\nИтоговый балл: {score:.1f}/{max_score}") print(f"Оценка: {grade} ({letter})") print(format_score_bar(score, max_score, 30)) print("\n" + "-" * 60) print("КРИТЕРИИ:") print("-" * 60) criteria_names = { "readability": "Читаемость", "grammar": "Грамматика", "plagiarism": "Оригинальность", "sentiment": "Тональность", "structure": "Структура" } criteria_results = result.get("criteria_results", {}) for key, name in criteria_names.items(): if key in criteria_results: crit = criteria_results[key] c_score = crit.get("score", 0) c_max = crit.get("max_score", 25) print(f"\n{name}:") print(f" {format_score_bar(c_score, c_max, 20)} ({c_score:.1f}/{c_max:.1f})") print(f" {crit.get('feedback', '')}") recommendations = result.get("recommendations", []) if recommendations: print("\n" + "-" * 60) print("РЕКОМЕНДАЦИИ:") print("-" * 60) for i, rec in enumerate(recommendations, 1): print(f" {i}. {rec}") print("\n" + "=" * 60) def validate_essay_length( text: str, min_words: int = 100, max_words: Optional[int] = None ) -> tuple: """ Validate essay length. Args: text: Essay text. min_words: Minimum word count. max_words: Maximum word count (None for no limit). Returns: Tuple of (is_valid, word_count, message). """ word_count = len(text.split()) if word_count < min_words: return ( False, word_count, f"Эссе слишком короткое: {word_count} слов " f"(минимум {min_words})" ) if max_words and word_count > max_words: return ( False, word_count, f"Эссе слишком длинное: {word_count} слов " f"(максимум {max_words})" ) return (True, word_count, f"Длина эссе: {word_count} слов")