Spaces:
Sleeping
Sleeping
File size: 5,910 Bytes
9381502 88c7275 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 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | from __future__ import annotations
import os
import re
from dataclasses import dataclass
from typing import Iterable, Optional
from cert_study_app.config import BASE_DIR
DEFAULT_EMBEDDING_MODEL = os.getenv("EMBEDDING_MODEL", "BAAI/bge-m3")
@dataclass
class VectorSearchResult:
id: str
text: str
score: Optional[float] = None
metadata: Optional[dict] = None
class QuestionVectorStore:
def __init__(
self,
persist_dir: Optional[str] = None,
collection_name: str = "questions",
embedding_model: Optional[str] = None,
):
self.persist_dir = persist_dir or str(BASE_DIR / "chroma_db")
self.base_collection_name = collection_name
self.embedding_model = embedding_model or DEFAULT_EMBEDDING_MODEL
self.collection_name = _collection_name(collection_name, self.embedding_model)
self._client = None
self._collection = None
def _get_collection(self):
if self._collection is not None:
return self._collection
import chromadb
from chromadb.utils import embedding_functions
self._client = chromadb.PersistentClient(path=self.persist_dir)
embedding_function = embedding_functions.SentenceTransformerEmbeddingFunction(
model_name=self.embedding_model,
)
self._collection = self._client.get_or_create_collection(
self.collection_name,
embedding_function=embedding_function,
metadata={
"base_collection": self.base_collection_name,
"embedding_model": self.embedding_model,
},
)
return self._collection
def upsert_questions(self, questions: Iterable[dict]) -> int:
ids = []
documents = []
metadatas = []
for item in questions:
question_id = str(item["id"])
ids.append(question_id)
documents.append(_question_document(item))
metadatas.append(
{
"answer": item.get("answer", ""),
"category": item.get("category") or "",
"subcategory": item.get("subcategory") or "",
"source": item.get("source") or "",
"embedding_model": self.embedding_model,
}
)
if not ids:
return 0
self._get_collection().upsert(ids=ids, documents=documents, metadatas=metadatas)
return len(ids)
def upsert_documents(self, documents: Iterable[dict]) -> int:
ids = []
texts = []
metadatas = []
for item in documents:
doc_id = str(item["id"])
text = str(item.get("text") or "").strip()
if not doc_id or not text:
continue
ids.append(doc_id)
texts.append(text)
metadatas.append(
{
"source_type": item.get("source_type") or self.base_collection_name,
"source": item.get("source") or "",
"title": item.get("title") or "",
"url": item.get("url") or "",
"category": item.get("category") or "",
"subcategory": item.get("subcategory") or "",
"embedding_model": self.embedding_model,
}
)
if not ids:
return 0
self._get_collection().upsert(ids=ids, documents=texts, metadatas=metadatas)
return len(ids)
def search(self, query: str, k: int = 5, source: Optional[str] = None) -> list[VectorSearchResult]:
try:
collection = self._get_collection()
except Exception:
return []
try:
count = collection.count()
except Exception:
count = 0
if count == 0:
return []
kwargs = {"query_texts": [query], "n_results": min(k, count)}
if source:
kwargs["where"] = {"source": source}
try:
result = collection.query(**kwargs)
except Exception:
return []
ids = result.get("ids", [[]])[0]
documents = result.get("documents", [[]])[0]
distances = result.get("distances", [[]])[0] if result.get("distances") else []
metadatas = result.get("metadatas", [[]])[0] if result.get("metadatas") else []
items = []
for idx, item_id in enumerate(ids):
items.append(
VectorSearchResult(
id=item_id,
text=documents[idx] if idx < len(documents) else "",
score=distances[idx] if idx < len(distances) else None,
metadata=metadatas[idx] if idx < len(metadatas) else None,
)
)
return items
def _question_document(item: dict) -> str:
parts = [f"문제: {item.get('stem') or ''}"]
options = item.get("options") or {}
if isinstance(options, dict) and options:
rendered_options = "\n".join(f"{key}. {value}" for key, value in sorted(options.items()))
parts.append(f"보기:\n{rendered_options}")
elif isinstance(options, list) and options:
parts.append("보기:\n" + "\n".join(str(option) for option in options))
if item.get("answer"):
parts.append(f"정답: {item['answer']}")
if item.get("explanation"):
parts.append(f"해설: {item['explanation']}")
if item.get("category") or item.get("subcategory"):
parts.append(f"분류: {item.get('category') or ''} / {item.get('subcategory') or ''}")
return "\n".join(parts)
def _collection_name(base: str, embedding_model: str) -> str:
slug = re.sub(r"[^a-zA-Z0-9._-]+", "_", embedding_model).strip("_").lower()
name = f"{base}_{slug}" if slug else base
return name[:63].strip("._-") or base
|