File size: 2,047 Bytes
0785301
a6d62e8
 
983ffca
a6d62e8
 
 
 
 
 
0785301
 
a6d62e8
 
 
 
 
 
0785301
a6d62e8
0785301
 
 
a6d62e8
 
 
 
 
0785301
 
 
a6d62e8
 
 
 
 
 
 
 
 
 
 
0785301
 
 
 
a6d62e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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 ""