Spaces:
Running
Running
axeronis commited on
Commit ·
a76cbc6
1
Parent(s): 5a54992
feat(multimodal): add Vision analysis for images and document content
Browse files- backend/app/api/telegram_webhook.py +102 -0
- backend/app/api/webhook.py +27 -7
- backend/app/services/llm_client.py +68 -0
backend/app/api/telegram_webhook.py
CHANGED
|
@@ -313,3 +313,105 @@ async def transcribe_telegram_voice(bot_token: str, file_id: str) -> str:
|
|
| 313 |
except Exception as e:
|
| 314 |
logger.error(f"❌ Voice transcription failed: {e}")
|
| 315 |
return "[Voice Message] (Не удалось распознать)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
except Exception as e:
|
| 314 |
logger.error(f"❌ Voice transcription failed: {e}")
|
| 315 |
return "[Voice Message] (Не удалось распознать)"
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
async def analyze_telegram_image(bot_token: str, file_id: str) -> str:
|
| 319 |
+
"""Download and analyze Telegram image using Gemini Vision."""
|
| 320 |
+
try:
|
| 321 |
+
logger.info("📷 Processing Telegram image...")
|
| 322 |
+
|
| 323 |
+
async with httpx.AsyncClient() as client:
|
| 324 |
+
# Get file path
|
| 325 |
+
file_res = await client.get(
|
| 326 |
+
f"https://api.telegram.org/bot{bot_token}/getFile?file_id={file_id}"
|
| 327 |
+
)
|
| 328 |
+
file_data = file_res.json()
|
| 329 |
+
|
| 330 |
+
if not file_data.get("ok"):
|
| 331 |
+
logger.error(f"Failed to get file path: {file_data}")
|
| 332 |
+
return "[Фото] (Ошибка загрузки)"
|
| 333 |
+
|
| 334 |
+
file_path = file_data["result"]["file_path"]
|
| 335 |
+
download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}"
|
| 336 |
+
|
| 337 |
+
# Download file
|
| 338 |
+
img_res = await client.get(download_url)
|
| 339 |
+
img_res.raise_for_status()
|
| 340 |
+
img_bytes = img_res.content
|
| 341 |
+
|
| 342 |
+
# Determine mime type from file extension
|
| 343 |
+
ext = file_path.split(".")[-1].lower()
|
| 344 |
+
mime_map = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "webp": "image/webp", "gif": "image/gif"}
|
| 345 |
+
mime_type = mime_map.get(ext, "image/jpeg")
|
| 346 |
+
|
| 347 |
+
# Analyze with Gemini Vision
|
| 348 |
+
from app.services.llm_client import get_llm_client
|
| 349 |
+
llm = get_llm_client()
|
| 350 |
+
analysis = await llm.analyze_image(img_bytes, mime_type=mime_type)
|
| 351 |
+
|
| 352 |
+
logger.info(f"✅ Image analysis: {analysis[:50]}...")
|
| 353 |
+
return f"[Фото: {analysis}]"
|
| 354 |
+
|
| 355 |
+
except Exception as e:
|
| 356 |
+
logger.error(f"❌ Image analysis failed: {e}")
|
| 357 |
+
return "[Фото] (Не удалось проанализировать)"
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
async def analyze_telegram_document(bot_token: str, file_id: str, mime_type: str, file_name: str) -> str:
|
| 361 |
+
"""Download and analyze Telegram document."""
|
| 362 |
+
try:
|
| 363 |
+
logger.info(f"📄 Processing Telegram document: {file_name} ({mime_type})")
|
| 364 |
+
|
| 365 |
+
async with httpx.AsyncClient() as client:
|
| 366 |
+
# Get file path
|
| 367 |
+
file_res = await client.get(
|
| 368 |
+
f"https://api.telegram.org/bot{bot_token}/getFile?file_id={file_id}"
|
| 369 |
+
)
|
| 370 |
+
file_data = file_res.json()
|
| 371 |
+
|
| 372 |
+
if not file_data.get("ok"):
|
| 373 |
+
logger.error(f"Failed to get file path: {file_data}")
|
| 374 |
+
return f"[Документ: {file_name}] (Ошибка загрузки)"
|
| 375 |
+
|
| 376 |
+
file_path = file_data["result"]["file_path"]
|
| 377 |
+
download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}"
|
| 378 |
+
|
| 379 |
+
# Download file
|
| 380 |
+
doc_res = await client.get(download_url)
|
| 381 |
+
doc_res.raise_for_status()
|
| 382 |
+
doc_bytes = doc_res.content
|
| 383 |
+
|
| 384 |
+
# Handle based on file type
|
| 385 |
+
if mime_type and mime_type.startswith("image/"):
|
| 386 |
+
# It's an image sent as document
|
| 387 |
+
from app.services.llm_client import get_llm_client
|
| 388 |
+
llm = get_llm_client()
|
| 389 |
+
analysis = await llm.analyze_image(doc_bytes, mime_type=mime_type)
|
| 390 |
+
logger.info(f"✅ Document (image) analysis: {analysis[:50]}...")
|
| 391 |
+
return f"[Документ-изображение: {analysis}]"
|
| 392 |
+
|
| 393 |
+
elif mime_type == "application/pdf":
|
| 394 |
+
# PDF - try to extract text or analyze as image
|
| 395 |
+
from app.services.llm_client import get_llm_client
|
| 396 |
+
llm = get_llm_client()
|
| 397 |
+
# Gemini can analyze PDFs directly
|
| 398 |
+
analysis = await llm.analyze_document(doc_bytes, mime_type="application/pdf", file_name=file_name)
|
| 399 |
+
logger.info(f"✅ PDF analysis: {analysis[:50]}...")
|
| 400 |
+
return f"[PDF-документ '{file_name}': {analysis}]"
|
| 401 |
+
|
| 402 |
+
elif mime_type and mime_type.startswith("text/"):
|
| 403 |
+
# Text file - read directly
|
| 404 |
+
try:
|
| 405 |
+
text_content = doc_bytes.decode("utf-8")[:2000] # Limit to 2000 chars
|
| 406 |
+
logger.info(f"✅ Text file read: {len(text_content)} chars")
|
| 407 |
+
return f"[Текстовый файл '{file_name}':\n{text_content}]"
|
| 408 |
+
except:
|
| 409 |
+
return f"[Документ: {file_name}] (Не удалось прочитать текст)"
|
| 410 |
+
|
| 411 |
+
else:
|
| 412 |
+
# Unknown format
|
| 413 |
+
return f"[Документ: {file_name}] (Формат {mime_type or 'неизвестен'} не поддерживается для анализа)"
|
| 414 |
+
|
| 415 |
+
except Exception as e:
|
| 416 |
+
logger.error(f"❌ Document analysis failed: {e}")
|
| 417 |
+
return f"[Документ: {file_name}] (Ошибка анализа)"
|
backend/app/api/webhook.py
CHANGED
|
@@ -16,7 +16,7 @@ from app.services.email import get_email_service
|
|
| 16 |
from app.services.subscription_manager import SubscriptionManager
|
| 17 |
from app.core.config import settings
|
| 18 |
from app.core.logging import get_logger
|
| 19 |
-
from app.api.telegram_webhook import transcribe_telegram_voice
|
| 20 |
|
| 21 |
logger = get_logger(__name__)
|
| 22 |
|
|
@@ -240,6 +240,8 @@ async def telegram_webhook(
|
|
| 240 |
voice_file_id = voice.get("file_id") if voice else None
|
| 241 |
photo_file_id = photo_list[-1]["file_id"] if photo_list else None
|
| 242 |
doc_file_id = document.get("file_id") if document else None
|
|
|
|
|
|
|
| 243 |
|
| 244 |
# Process voice message (transcribe to text)
|
| 245 |
if voice_file_id and tenant.telegram_bot_token:
|
|
@@ -250,14 +252,32 @@ async def telegram_webhook(
|
|
| 250 |
logger.error(f"❌ Voice transcription failed: {e}")
|
| 251 |
user_text = "[Голосовое сообщение - не удалось распознать]"
|
| 252 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
# If still no text after all processing, use placeholder
|
| 254 |
if not user_text:
|
| 255 |
-
|
| 256 |
-
user_text = "[Фото]"
|
| 257 |
-
elif doc_file_id:
|
| 258 |
-
user_text = "[Документ]"
|
| 259 |
-
else:
|
| 260 |
-
user_text = "[Медиа-сообщение]"
|
| 261 |
|
| 262 |
# Tenant already fetched and validated above
|
| 263 |
|
|
|
|
| 16 |
from app.services.subscription_manager import SubscriptionManager
|
| 17 |
from app.core.config import settings
|
| 18 |
from app.core.logging import get_logger
|
| 19 |
+
from app.api.telegram_webhook import transcribe_telegram_voice, analyze_telegram_image, analyze_telegram_document
|
| 20 |
|
| 21 |
logger = get_logger(__name__)
|
| 22 |
|
|
|
|
| 240 |
voice_file_id = voice.get("file_id") if voice else None
|
| 241 |
photo_file_id = photo_list[-1]["file_id"] if photo_list else None
|
| 242 |
doc_file_id = document.get("file_id") if document else None
|
| 243 |
+
doc_mime_type = document.get("mime_type") if document else None
|
| 244 |
+
doc_file_name = document.get("file_name", "document") if document else None
|
| 245 |
|
| 246 |
# Process voice message (transcribe to text)
|
| 247 |
if voice_file_id and tenant.telegram_bot_token:
|
|
|
|
| 252 |
logger.error(f"❌ Voice transcription failed: {e}")
|
| 253 |
user_text = "[Голосовое сообщение - не удалось распознать]"
|
| 254 |
|
| 255 |
+
# Process photo (analyze with Vision)
|
| 256 |
+
elif photo_file_id and tenant.telegram_bot_token and not user_text:
|
| 257 |
+
try:
|
| 258 |
+
user_text = await analyze_telegram_image(tenant.telegram_bot_token, photo_file_id)
|
| 259 |
+
logger.info(f"📷 Image analyzed: {user_text[:50]}...")
|
| 260 |
+
except Exception as e:
|
| 261 |
+
logger.error(f"❌ Image analysis failed: {e}")
|
| 262 |
+
user_text = "[Фото - не удалось проанализировать]"
|
| 263 |
+
|
| 264 |
+
# Process document (analyze based on type)
|
| 265 |
+
elif doc_file_id and tenant.telegram_bot_token and not user_text:
|
| 266 |
+
try:
|
| 267 |
+
user_text = await analyze_telegram_document(
|
| 268 |
+
tenant.telegram_bot_token,
|
| 269 |
+
doc_file_id,
|
| 270 |
+
doc_mime_type,
|
| 271 |
+
doc_file_name
|
| 272 |
+
)
|
| 273 |
+
logger.info(f"📄 Document analyzed: {user_text[:50]}...")
|
| 274 |
+
except Exception as e:
|
| 275 |
+
logger.error(f"❌ Document analysis failed: {e}")
|
| 276 |
+
user_text = f"[Документ: {doc_file_name}] (Ошибка анализа)"
|
| 277 |
+
|
| 278 |
# If still no text after all processing, use placeholder
|
| 279 |
if not user_text:
|
| 280 |
+
user_text = "[Медиа-сообщение без содержимого]"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
# Tenant already fetched and validated above
|
| 283 |
|
backend/app/services/llm_client.py
CHANGED
|
@@ -279,6 +279,74 @@ class GeminiLLMClient:
|
|
| 279 |
async def generate_speech(self, text: str, voice: str = "onyx") -> bytes:
|
| 280 |
"""Generate audio from text using configured VoiceService."""
|
| 281 |
return await voice_service.generate_audio(text, voice)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
|
| 283 |
@lru_cache()
|
| 284 |
def get_llm_client():
|
|
|
|
| 279 |
async def generate_speech(self, text: str, voice: str = "onyx") -> bytes:
|
| 280 |
"""Generate audio from text using configured VoiceService."""
|
| 281 |
return await voice_service.generate_audio(text, voice)
|
| 282 |
+
|
| 283 |
+
async def analyze_image(self, image_bytes: bytes, mime_type: str = "image/jpeg") -> str:
|
| 284 |
+
"""
|
| 285 |
+
Analyze image using Gemini Vision capabilities.
|
| 286 |
+
Returns a concise description of the image content.
|
| 287 |
+
"""
|
| 288 |
+
prompt = """Опиши кратко (1-2 предложения), что изображено на этой картинке.
|
| 289 |
+
Если это скриншот, документ, график или диаграмма - опиши основное содержимое.
|
| 290 |
+
Если это товар - опиши его название и характеристики.
|
| 291 |
+
Ответ на русском языке."""
|
| 292 |
+
|
| 293 |
+
try:
|
| 294 |
+
loop = asyncio.get_event_loop()
|
| 295 |
+
|
| 296 |
+
content = types.Content(
|
| 297 |
+
parts=[
|
| 298 |
+
types.Part.from_bytes(data=image_bytes, mime_type=mime_type),
|
| 299 |
+
types.Part.from_text(text=prompt)
|
| 300 |
+
]
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
response = await loop.run_in_executor(
|
| 304 |
+
None,
|
| 305 |
+
lambda: self.client.models.generate_content(
|
| 306 |
+
model=self.default_model_name,
|
| 307 |
+
contents=content
|
| 308 |
+
)
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
return response.text.strip()
|
| 312 |
+
|
| 313 |
+
except Exception as e:
|
| 314 |
+
logger.error(f"Image analysis failed: {e}")
|
| 315 |
+
raise LLMAPIError(f"Image analysis failed: {e}")
|
| 316 |
+
|
| 317 |
+
async def analyze_document(self, doc_bytes: bytes, mime_type: str, file_name: str) -> str:
|
| 318 |
+
"""
|
| 319 |
+
Analyze document (PDF, etc.) using Gemini capabilities.
|
| 320 |
+
Returns a summary of the document content.
|
| 321 |
+
"""
|
| 322 |
+
prompt = f"""Проанализируй этот документ '{file_name}' и кратко опиши его содержимое (2-3 предложения).
|
| 323 |
+
Если это PDF - выдели основные темы и ключевую информацию.
|
| 324 |
+
Если это таблица или данные - опиши их суть.
|
| 325 |
+
Ответ на русском языке."""
|
| 326 |
+
|
| 327 |
+
try:
|
| 328 |
+
loop = asyncio.get_event_loop()
|
| 329 |
+
|
| 330 |
+
content = types.Content(
|
| 331 |
+
parts=[
|
| 332 |
+
types.Part.from_bytes(data=doc_bytes, mime_type=mime_type),
|
| 333 |
+
types.Part.from_text(text=prompt)
|
| 334 |
+
]
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
response = await loop.run_in_executor(
|
| 338 |
+
None,
|
| 339 |
+
lambda: self.client.models.generate_content(
|
| 340 |
+
model=self.default_model_name,
|
| 341 |
+
contents=content
|
| 342 |
+
)
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
return response.text.strip()
|
| 346 |
+
|
| 347 |
+
except Exception as e:
|
| 348 |
+
logger.error(f"Document analysis failed: {e}")
|
| 349 |
+
raise LLMAPIError(f"Document analysis failed: {e}")
|
| 350 |
|
| 351 |
@lru_cache()
|
| 352 |
def get_llm_client():
|