import asyncio import logging from app.config import GEMINI_API_KEY import google.genai as genai from google.api_core.exceptions import GoogleAPIError _SUMMARY_MODEL = "gemini-1.5-flash" _gemini_client = None if GEMINI_API_KEY: try: _gemini_client = genai.Client(api_key=GEMINI_API_KEY) logging.info(f"[summary_service] Initialized google.genai client with model={_SUMMARY_MODEL}") except Exception as e: logging.exception(f"[summary_service] Failed to init google.genai client: {e}") _gemini_client = None else: logging.warning("[summary_service] GEMINI_API_KEY is not set, summary will be empty") async def generate_summary(text: str) -> str: """ Tạo tóm tắt ngắn gọn 3-5 câu, một đoạn văn duy nhất. Fallback: trả "" nếu không có model hoặc lỗi. """ if not _gemini_client: return "" prompt = f""" Bạn là chuyên gia tóm tắt. Hãy tóm tắt văn bản sau thành một đoạn văn duy nhất. Yêu cầu: 1. Viết khoảng 3-5 câu, tổng hợp đầy đủ chủ đề và các ý chính. 2. Viết liền mạch, KHÔNG xuống dòng, KHÔNG dùng gạch đầu dòng hay đánh số. 3. Chỉ dựa trên thông tin được cung cấp, tuyệt đối KHÔNG tự thêm thông tin bên ngoài. 4. Trả về VĂN BẢN THUẦN (plain text), không bọc trong ``` hoặc JSON. Văn bản: \"\"\"{text}\"\"\" """ loop = asyncio.get_event_loop() def call(): resp = _gemini_client.models.generate_content( model=_SUMMARY_MODEL, contents=prompt, ) return (resp.text or "").strip() try: result = await loop.run_in_executor(None, call) # clean backticks nếu model có lỡ bọc return result.replace("```", "").strip() except GoogleAPIError as e: logging.error(f"[summary_service] Gemini API error: {e}") except Exception as e: logging.exception(f"[summary_service] generate_summary failed: {e}") return ""