/
aastray
/
StudentPart
Обзор
Документация
Войти
/
aastray
/
StudentPart
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
service/src/services/template_parser.py
123 строки
4 KB
aastray
Реализован функционал загрузки файлов и просмотра документов, удалены базовые эндпоинты, обновлена документация
10 янв 2026, 15:38
10 янв 2026, 15:38
4d47c55
Код
Авторство
О чём код?
""" Сервис для парсинга DOCX шаблонов документов. Поиск переменных типа {{ variable_name }} в шаблонах. """ from docx import Document from typing import List, Dict, Tuple import os import re def extract_variable_name(text: str) -> str: """ Извлекает имя переменной из текста вида {{ variable_name }}. Args: text: Текст с переменной, например "{{ org_name_full }}" Returns: str: Имя переменной, например "org_name_full" """ # Убираем фигурные скобки и пробелы match = re.search(r'\{\{\s*(\w+)\s*\}\}', text) if match: return match.group(1) return text.strip() def find_template_variables(doc_path: str) -> List[str]: """ Поиск всех переменных типа {{ variable_name }} в DOCX документе. Args: doc_path: Путь к DOCX файлу Returns: List[str]: Список уникальных имен переменных """ if not os.path.exists(doc_path): raise FileNotFoundError(f"Файл шаблона не найден: {doc_path}") doc = Document(doc_path) variables = set() # Используем set для уникальности # Паттерн для поиска переменных {{ variable_name }} pattern = re.compile(r'\{\{\s*(\w+)\s*\}\}') # Поиск в параграфах for paragraph in doc.paragraphs: # Получаем весь текст параграфа full_text = ''.join([run.text for run in paragraph.runs]) matches = pattern.findall(full_text) variables.update(matches) # Поиск в таблицах for table in doc.tables: for row in table.rows: for cell in row.cells: for paragraph in cell.paragraphs: full_text = ''.join([run.text for run in paragraph.runs]) matches = pattern.findall(full_text) variables.update(matches) return sorted(list(variables)) def find_colored_fields(doc_path: str) -> Tuple[List[Dict[str, str]], List[Dict[str, str]]]: """ Поиск переменных в DOCX документе (для обратной совместимости). Теперь ищет переменные типа {{ variable_name }}. Args: doc_path: Путь к DOCX файлу Returns: Tuple[List[Dict], List[Dict]]: (поля студента, поля системы) Каждое поле - словарь с ключами 'text' и 'field_name' """ variables = find_template_variables(doc_path) # Все переменные считаются полями студента (заполняются из анкеты) # Поля системы (зелёные) определяются отдельно, если нужно student_fields = [] system_fields = [] # Список переменных, которые заполняются системой/преподавателем system_variables = { 'university_supervisor_full_name', # Руководитель от ТИУ 'proxy_number', # Номер доверенности 'proxy_date', # Дата доверенности 'org_premises', # Перечень помещений 'practice_department', # Структурное подразделение } for var_name in variables: field_info = { 'text': f'{{{{ {var_name} }}}}', 'field_name': var_name } if var_name in system_variables: system_fields.append(field_info) else: student_fields.append(field_info) return student_fields, system_fields def parse_template(template_path: str) -> Dict[str, List[Dict[str, str]]]: """ Парсит шаблон документа и возвращает информацию о полях. Args: template_path: Путь к файлу шаблона Returns: Dict с ключами 'student_fields' и 'system_fields' """ student_fields, system_fields = find_colored_fields(template_path) return { 'student_fields': student_fields, 'system_fields': system_fields }