File size: 5,768 Bytes
9381502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88c7275
 
 
 
 
9381502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
from __future__ import annotations

import json
import re
from typing import Optional

import requests
from sqlalchemy import or_

from cert_study_app.config import DEFAULT_USER
from cert_study_app.models import ConceptNote, Question


CONCEPT_PROMPT = """
๋„ˆ๋Š” ์ž๊ฒฉ์ฆ ์‹œํ—˜ ํ•™์Šต ๋…ธํŠธ ํ๋ ˆ์ดํ„ฐ๋‹ค.
์•„๋ž˜ ๋ฌธ์ œ์—์„œ ์ €์žฅํ•  ๋งŒํ•œ ๊ฐœ๋… ํ›„๋ณด๋ฅผ 1~3๊ฐœ๋งŒ ์ œ์•ˆํ•˜๋ผ.
๋„ˆ๋ฌด ์„ธ๋ถ€์ ์ธ ๋ฌธ์ œ ์ƒํ™ฉ์ด ์•„๋‹ˆ๋ผ ์žฌ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์‹œํ—˜ ๊ฐœ๋…์œผ๋กœ ์ถ”์ƒํ™”ํ•˜๋ผ.
JSON๋งŒ ๋ฐ˜ํ™˜ํ•˜๋ผ.

ํ˜•์‹:
{
  "concepts": [
    {
      "concept_name": "๊ฐœ๋…๋ช…",
      "summary": "ํ•ต์‹ฌ ์š”์•ฝ 1~2๋ฌธ์žฅ",
      "exam_point": "์‹œํ—˜์žฅ์—์„œ ๊ธฐ์–ตํ•  ํฌ์ธํŠธ",
      "trap_point": "ํ—ท๊ฐˆ๋ฆด ํฌ์ธํŠธ",
      "keywords": ["keyword1", "keyword2"]
    }
  ]
}

๋ฌธ์ œ:
{stem}

๋ณด๊ธฐ:
{options}

์ •๋‹ต:
{answer}

ํ•ด์„ค:
{explanation}
"""


def _json_from_response(text: str) -> dict:
    match = re.search(r"\{.*\}", text or "", re.S)
    if match:
        text = match.group(0)
    try:
        return json.loads(text)
    except Exception:
        return {"concepts": []}


class ConceptNoteService:
    def __init__(self, db):
        self.db = db

    def generate_candidates(
        self,
        question_id: int,
        model: str = "qwen2.5:14b",
        base_url: str = "http://localhost:11434",
    ) -> list[dict]:
        question = self.db.query(Question).filter(Question.id == question_id).first()
        if not question:
            return []

        prompt = CONCEPT_PROMPT.format(
            stem=(question.stem or "")[:1600],
            options="\n".join(str(option) for option in question.get_options())[:1200],
            answer=question.answer or "",
            explanation=(question.explanation or "")[:1600],
        )
        payload = {
            "model": model,
            "prompt": prompt,
            "stream": False,
            "format": "json",
            "think": False,
            "options": {"temperature": 0, "num_predict": 700},
        }
        try:
            response = requests.post(f"{base_url.rstrip('/')}/api/generate", json=payload, timeout=120)
            response.raise_for_status()
        except requests.RequestException as exc:
            raise RuntimeError(f"Ollama API ์—ฐ๊ฒฐ ์‹คํŒจ ({base_url}): {exc}") from exc
        parsed = _json_from_response(response.json().get("response", ""))
        concepts = parsed.get("concepts") if isinstance(parsed, dict) else []
        return [self._normalize_candidate(item) for item in concepts if isinstance(item, dict)][:3]

    def save_candidate(
        self,
        candidate: dict,
        question_id: int,
        user_id: str = DEFAULT_USER,
    ) -> ConceptNote:
        question = self.db.query(Question).filter(Question.id == question_id).first()
        note = ConceptNote(
            concept_name=str(candidate.get("concept_name") or "").strip()[:255],
            summary=str(candidate.get("summary") or "").strip(),
            exam_point=str(candidate.get("exam_point") or "").strip(),
            trap_point=str(candidate.get("trap_point") or "").strip(),
            source=question.source if question else None,
            source_question_id=question_id,
            user_id=user_id,
        )
        note.set_keywords(candidate.get("keywords") or [])
        self.db.add(note)
        self.db.commit()
        self.db.refresh(note)
        return note

    def list_notes(self, source: Optional[str] = None, query: str = "", limit: int = 100) -> list[ConceptNote]:
        rows = self.db.query(ConceptNote)
        if source:
            rows = rows.filter(ConceptNote.source == source)
        if query:
            like = f"%{query.strip()}%"
            rows = rows.filter(
                or_(
                    ConceptNote.concept_name.ilike(like),
                    ConceptNote.summary.ilike(like),
                    ConceptNote.exam_point.ilike(like),
                    ConceptNote.trap_point.ilike(like),
                    ConceptNote.keywords.ilike(like),
                )
            )
        return rows.order_by(ConceptNote.updated_at.desc(), ConceptNote.id.desc()).limit(limit).all()

    def get_note(self, note_id: int) -> ConceptNote | None:
        return self.db.query(ConceptNote).filter(ConceptNote.id == note_id).first()

    def related_questions(self, note: ConceptNote, limit: int = 20) -> list[Question]:
        keywords = [note.concept_name, *note.keyword_list()]
        keywords = [keyword for keyword in keywords if str(keyword or "").strip()]
        if not keywords:
            return []
        filters = []
        for keyword in keywords[:8]:
            like = f"%{keyword}%"
            filters.append(Question.stem.ilike(like))
            filters.append(Question.explanation.ilike(like))
            filters.append(Question.raw_text.ilike(like))
        query = self.db.query(Question).filter(Question.parse_status == "approved")
        if note.source:
            query = query.filter(Question.source == note.source)
        return query.filter(or_(*filters)).order_by(Question.id.asc()).limit(limit).all()

    def _normalize_candidate(self, item: dict) -> dict:
        keywords = item.get("keywords") or []
        if isinstance(keywords, str):
            keywords = [keyword.strip() for keyword in re.split(r"[,#]", keywords) if keyword.strip()]
        return {
            "concept_name": str(item.get("concept_name") or "").strip(),
            "summary": str(item.get("summary") or "").strip(),
            "exam_point": str(item.get("exam_point") or "").strip(),
            "trap_point": str(item.get("trap_point") or "").strip(),
            "keywords": [str(keyword).strip() for keyword in keywords if str(keyword).strip()][:8],
        }