Add new file
This commit is contained in:
77
core/functions/summarize_document.py
Normal file
77
core/functions/summarize_document.py
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
Модуль суммаризации документа.
|
||||||
|
Создаёт краткий пересказ, сохраняя ключевые факты и цифры.
|
||||||
|
|
||||||
|
АДАПТАЦИЯ: теперь функция принимает промпт как аргумент.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from core.services.giga_client import GigaClient
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
async def summarize_document(
|
||||||
|
giga: GigaClient,
|
||||||
|
text: str,
|
||||||
|
title: str,
|
||||||
|
prompt_text: str,
|
||||||
|
bot_config,
|
||||||
|
) -> str:
|
||||||
|
"""
|
||||||
|
Суммаризирует документ.
|
||||||
|
|
||||||
|
Аргументы:
|
||||||
|
giga (GigaClient): клиент GigaChat
|
||||||
|
text (str): полный текст документа
|
||||||
|
title (str): название документа
|
||||||
|
prompt_text (str): содержимое промпта суммаризации
|
||||||
|
bot_config (BotConfig): объект конфигурации
|
||||||
|
|
||||||
|
Возвращает:
|
||||||
|
str: краткое изложение документа или сообщение об ошибке
|
||||||
|
"""
|
||||||
|
if not prompt_text:
|
||||||
|
logger.error("Промпт суммаризации не загружен")
|
||||||
|
return "Не удалось загрузить промпт для суммаризации."
|
||||||
|
|
||||||
|
summary_cfg = getattr(bot_config, 'summary', {})
|
||||||
|
temperature = summary_cfg.get('temperature', 0.1)
|
||||||
|
max_chars = summary_cfg.get('max_chars', 8000)
|
||||||
|
|
||||||
|
# Обрезаем текст, если он слишком длинный
|
||||||
|
if len(text) > max_chars:
|
||||||
|
# Обрезаем по границам предложений (используем razdel)
|
||||||
|
try:
|
||||||
|
from razdel import sentenize
|
||||||
|
sentences = [sent.text for sent in sentenize(text)]
|
||||||
|
except ImportError:
|
||||||
|
import re
|
||||||
|
sentences = re.split(r'(?<=[.!?])\s+', text)
|
||||||
|
|
||||||
|
truncated = []
|
||||||
|
current_len = 0
|
||||||
|
for sent in sentences:
|
||||||
|
if current_len + len(sent) <= max_chars:
|
||||||
|
truncated.append(sent)
|
||||||
|
current_len += len(sent)
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
text = ' '.join(truncated)
|
||||||
|
logger.warning(f"Текст обрезан до {max_chars} символов по границам предложений")
|
||||||
|
|
||||||
|
full_prompt = f"{prompt_text}\n\nНазвание документа: {title}\nТекст:\n{text}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = await giga.chat(
|
||||||
|
history=[],
|
||||||
|
query=full_prompt,
|
||||||
|
system_prompt=None,
|
||||||
|
file_id=None,
|
||||||
|
temperature=temperature
|
||||||
|
)
|
||||||
|
return response.strip()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Ошибка суммаризации: {e}", exc_info=True)
|
||||||
|
return "Не удалось создать суммаризацию."
|
||||||
Reference in New Issue
Block a user