forked from HSE_team/BetterCallPraskovia
Messages for indexing
This commit is contained in:
parent
1b550e6503
commit
570f0b7ea7
@ -3,6 +3,7 @@ Use cases для работы с документами
|
||||
"""
|
||||
from uuid import UUID
|
||||
from typing import BinaryIO, Optional
|
||||
import httpx
|
||||
from src.domain.entities.document import Document
|
||||
from src.domain.repositories.document_repository import IDocumentRepository
|
||||
from src.domain.repositories.collection_repository import ICollectionRepository
|
||||
@ -10,6 +11,7 @@ from src.domain.repositories.collection_access_repository import ICollectionAcce
|
||||
from src.application.services.document_parser_service import DocumentParserService
|
||||
from src.application.services.rag_service import RAGService
|
||||
from src.shared.exceptions import NotFoundError, ForbiddenError
|
||||
from src.shared.config import settings
|
||||
|
||||
|
||||
class DocumentUseCases:
|
||||
@ -60,12 +62,34 @@ class DocumentUseCases:
|
||||
)
|
||||
return await self.document_repository.create(document)
|
||||
|
||||
async def _send_telegram_notification(self, telegram_id: str, message: str):
|
||||
"""Отправить уведомление пользователю через Telegram Bot API"""
|
||||
if not settings.TELEGRAM_BOT_TOKEN:
|
||||
return
|
||||
|
||||
try:
|
||||
url = f"https://api.telegram.org/bot{settings.TELEGRAM_BOT_TOKEN}/sendMessage"
|
||||
async with httpx.AsyncClient(timeout=5.0) as client:
|
||||
response = await client.post(
|
||||
url,
|
||||
json={
|
||||
"chat_id": telegram_id,
|
||||
"text": message,
|
||||
"parse_mode": "HTML"
|
||||
}
|
||||
)
|
||||
if response.status_code != 200:
|
||||
print(f"Failed to send Telegram notification: {response.status_code}")
|
||||
except Exception as e:
|
||||
print(f"Error sending Telegram notification: {e}")
|
||||
|
||||
async def upload_and_parse_document(
|
||||
self,
|
||||
collection_id: UUID,
|
||||
file: BinaryIO,
|
||||
filename: str,
|
||||
user_id: UUID
|
||||
user_id: UUID,
|
||||
telegram_id: Optional[str] = None
|
||||
) -> Document:
|
||||
"""Загрузить и распарсить документ, затем автоматически проиндексировать"""
|
||||
collection = await self.collection_repository.get_by_id(collection_id)
|
||||
@ -86,11 +110,33 @@ class DocumentUseCases:
|
||||
)
|
||||
document = await self.document_repository.create(document)
|
||||
|
||||
if self.rag_service:
|
||||
if self.rag_service and telegram_id:
|
||||
try:
|
||||
await self.rag_service.index_document(document)
|
||||
await self._send_telegram_notification(
|
||||
telegram_id,
|
||||
"🔄 <b>Начинаю индексацию документа...</b>\n\n"
|
||||
f"Документ: <b>{title}</b>\n"
|
||||
"Это может занять некоторое время."
|
||||
)
|
||||
|
||||
chunks = await self.rag_service.index_document(document)
|
||||
|
||||
await self._send_telegram_notification(
|
||||
telegram_id,
|
||||
"✅ <b>Индексация завершена!</b>\n\n"
|
||||
f"Документ: <b>{title}</b>\n"
|
||||
f"Проиндексировано чанков: <b>{len(chunks)}</b>\n\n"
|
||||
"Теперь вы можете задавать вопросы по этому документу."
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"Ошибка при автоматической индексации документа {document.document_id}: {e}")
|
||||
if telegram_id:
|
||||
await self._send_telegram_notification(
|
||||
telegram_id,
|
||||
"⚠️ <b>Ошибка при индексации</b>\n\n"
|
||||
f"Документ загружен, но индексация не завершена.\n"
|
||||
f"Ошибка: {str(e)[:200]}"
|
||||
)
|
||||
|
||||
return document
|
||||
|
||||
|
||||
@ -69,7 +69,8 @@ async def upload_document(
|
||||
collection_id=collection_id,
|
||||
file=file.file,
|
||||
filename=file.filename,
|
||||
user_id=current_user.user_id
|
||||
user_id=current_user.user_id,
|
||||
telegram_id=current_user.telegram_id
|
||||
)
|
||||
return DocumentResponse.from_entity(document)
|
||||
|
||||
|
||||
@ -360,8 +360,9 @@ async def process_upload_document(message: Message, state: FSMContext):
|
||||
|
||||
if result:
|
||||
await message.answer(
|
||||
f"<b>Документ загружен</b>\n\n"
|
||||
f"Название: <b>{result.get('title', filename)}</b>",
|
||||
f"<b>✅ Документ загружен и добавлен в коллекцию</b>\n\n"
|
||||
f"<b>Название:</b> {result.get('title', filename)}\n\n"
|
||||
f"📄 Документ сейчас индексируется. Вы получите уведомление, когда индексация завершится.\n\n",
|
||||
parse_mode="HTML"
|
||||
)
|
||||
else:
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user