Spaces:
Sleeping
Sleeping
Download cert_study_app/services/concept_note_service.py from Kentlo/cert-study-app: direct link, hf CLI and curl.
- Browser
- Download file 5.77 kB
-
https://huggingface.co/spaces/Kentlo/cert-study-app/resolve/main/cert_study_app/services/concept_note_service.py
- Command line
-
hf download hf://spaces/Kentlo/cert-study-app/cert_study_app/services/concept_note_service.py
-
curl -L -o concept_note_service.py https://huggingface.co/spaces/Kentlo/cert-study-app/resolve/main/cert_study_app/services/concept_note_service.py
5.77 kB
| 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], | |
| } | |