Spaces:
Runtime error
Runtime error
Update& change payload
Browse filesFiles changed (3)
123456781 unmodified line10111213141545 unmodified lines616263646566673 unmodified lines7172737475762 unmodified lines7980818283848586877 unmodified lines959697989910010110210322 unmodified lines126127128129130131import hashlibimport loggingfrom typing import Listfrom langchain_core.documents import Document as LangChainDocumentfrom .collection_utils import collection_matches_yearfrom .document_db import SessionLocal, list_active_collection_names1 unmodified linelogger = logging.getLogger(__name__)class CollectionRouterRetriever:def __init__(self,45 unmodified linesreturn active_collections[: self.top_n_collections]def _search_target_collections(self, query: str, collections: List[str], limit: int) -> List:if not collections:return []3 unmodified lineslogger.exception("Failed to embed query for collection routing")return []scored_docs = []for collection_name in collections:try:2 unmodified linesquery_vector=query_vector,limit=limit,with_payload=True,)except Exception:logger.exception("Qdrant search failed for collection=%s", collection_name)continuefor point in points:7 unmodified lines"source_file": payload.get("filename") or payload.get("stored_name") or "","source_relpath": payload.get("object_path") or payload.get("path") or "","object_path": payload.get("object_path") or "","folder_key": payload.get("folder_key") or "","collection_name": collection_name,"academic_year": payload.get("academic_year") or "","chunk_index": payload.get("chunk_index"),"page_number": payload.get("page_number"),}22 unmodified linesquery=query,collections=target_collections,limit=candidate_k,)if year_scoped:123456789101 unmodified line121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575845 unmodified lines1041051061071081091103 unmodified lines1141151161171181191201211221231242 unmodified lines1271281291301311321331341351367 unmodified lines14414514614714814915015115215315422 unmodified lines177178179180181182183import hashlibimport loggingimport refrom typing import List, Optionalfrom langchain_core.documents import Document as LangChainDocumentfrom qdrant_client.models import Filter, FieldCondition, HasIdCondition, MatchAnyfrom .collection_utils import collection_matches_yearfrom .document_db import SessionLocal, list_active_collection_names1 unmodified linelogger = logging.getLogger(__name__)def _build_year_filter(year_scope: Optional[str]) -> Optional[Filter]:"""Tạo Qdrant Filter từ year_scope (ví dụ: '2023-2024' hoặc '2023')."""if not year_scope:return Noneyear_targets = []year_scope = year_scope.strip()# Parse year_scope: có thể là "2023-2024" hoặc "2023"if "-" in year_scope:parts = year_scope.split("-")for p in parts:try:year_targets.append(int(p.strip()))except ValueError:passelse:try:year_targets.append(int(year_scope))except ValueError:passif not year_targets:return None# Sử dụng MatchAny để filter theo danh sách yearsfrom qdrant_client.models import HasIdCondition as QdrantHasIdtry:return Filter(must=[FieldCondition(key="years",match=MatchAny(any=year_targets),)])except Exception:# Fallback nếu MatchAny không workreturn Noneclass CollectionRouterRetriever:def __init__(self,45 unmodified linesreturn active_collections[: self.top_n_collections]def _search_target_collections(self, query: str, collections: List[str], limit: int, year_scope: Optional[str] = None) -> List:if not collections:return []3 unmodified lineslogger.exception("Failed to embed query for collection routing")return []# Tạo filter Qdrant nếu có year_scopeyear_filter = _build_year_filter(year_scope)if year_filter:logger.info(f"Áp dụng Qdrant Filter cho year_scope: {year_scope}")scored_docs = []for collection_name in collections:try:2 unmodified linesquery_vector=query_vector,limit=limit,with_payload=True,query_filter=year_filter, # NEW: Áp dụng Qdrant Filter native)except Exception as e:logger.exception(f"Qdrant search failed for collection={collection_name}: {e}")continuefor point in points:7 unmodified lines"source_file": payload.get("filename") or payload.get("stored_name") or "","source_relpath": payload.get("object_path") or payload.get("path") or "","object_path": payload.get("object_path") or "","source_url": payload.get("source_url") or "", # NEW: Thêm source_url"folder_key": payload.get("folder_key") or "","collection_name": collection_name,"academic_year": payload.get("academic_year") or "","years": payload.get("years") or [], # NEW: Thêm years array"chunk_index": payload.get("chunk_index"),"page_number": payload.get("page_number"),}22 unmodified linesquery=query,collections=target_collections,limit=candidate_k,year_scope=year_scope, # NEW: Pass year_scope để Qdrant Filter)if year_scoped:
1234512 unmodified lines181920212223241 unmodified line2627282930313233343575 unmodified lines1111121131141151161171181191201211221233 unmodified lines127128129130131132109 unmodified lines242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282import loggingimport osimport uuidfrom datetime import datetime, timezonefrom typing import List, Optional12 unmodified lines)from .chunking import smart_chunkingfrom .config import QDRANT_API_KEY, QDRANT_COLLECTION, QDRANT_URLfrom .document_db import Document, DocumentChunk, SessionLocalfrom .models import embeddingsfrom .text_utils import clean_text1 unmodified linelogger = logging.getLogger(__name__)_ALLOWED_EXTENSIONS = {".pdf", ".docx", ".txt"}_ENSURED_PAYLOAD_INDEX_COLLECTIONS = set()def _load_documents_for_ingest(path: str, extension: str) -> List[LangChainDocument]:extension = extension.lower()if extension not in _ALLOWED_EXTENSIONS:75 unmodified linesif collection_name in _ENSURED_PAYLOAD_INDEX_COLLECTIONS:returnfor field_name in ("object_path", "document_id"):client.create_payload_index(collection_name=collection_name,field_name=field_name,field_schema=PayloadSchemaType.KEYWORD,wait=True,)_ENSURED_PAYLOAD_INDEX_COLLECTIONS.add(collection_name)3 unmodified linesreturn "Index required but not found" in messagedef _delete_existing_document_points(client: QdrantClient,collection_name: str,109 unmodified lines_delete_existing_document_points(client, target_collection, source_object_ref, document.id)created_at = datetime.now(timezone.utc).isoformat()points: List[PointStruct] = []db_chunk_rows: List[DocumentChunk] = []for index, (chunk_doc, vector) in enumerate(zip(chunk_docs, vectors)):chunk_text = chunk_doc.page_contentmetadata = chunk_doc.metadata if isinstance(chunk_doc.metadata, dict) else {}point_id = str(uuid.uuid4())payload = {"document_id": document.id,"filename": document.original_name,"stored_name": document.stored_name,"path": effective_source_path or document.path,"object_path": source_object_ref,"folder_key": document.folder_key,"collection_name": target_collection,"source_file": metadata.get("source_file") or source_name,"source_relpath": metadata.get("source_relpath") or source_relpath,"academic_year": metadata.get("academic_year") or "ALL","page_number": metadata.get("page_number"),"source_updated_at": source_updated_at,"source_etag": source_etag,"chunk_index": index,"created_at": created_at,"content": chunk_text,}points.append(PointStruct(id=point_id, vector=vector, payload=payload))db_chunk_rows.append(DocumentChunk(document_id=document.id,chunk_index=index,content_preview=chunk_text[:200],qdrant_point_id=point_id,))client.upsert(collection_name=target_collection, points=points, wait=True)123456712 unmodified lines202122232425261 unmodified line282930313233343536373839404142434445464748495051525354555657585960616263646575 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631641651661671683 unmodified lines172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334109 unmodified lines444445446447448449450451452453454455456457458459460461462463import hashlibimport loggingimport osimport reimport uuidfrom datetime import datetime, timezonefrom typing import List, Optional12 unmodified lines)from .chunking import smart_chunkingfrom .config import QDRANT_API_KEY, QDRANT_COLLECTION, QDRANT_URL, SUPABASE_URL, SUPABASE_STORAGE_BUCKETfrom .document_db import Document, DocumentChunk, SessionLocalfrom .models import embeddingsfrom .text_utils import clean_text1 unmodified linelogger = logging.getLogger(__name__)ACTIVE_CODE_PATTERN = re.compile(r"(20\d{2})\s*[-_/]\s*(20\d{2})")_ALLOWED_EXTENSIONS = {".pdf", ".docx", ".txt"}_ENSURED_PAYLOAD_INDEX_COLLECTIONS = set()def _build_supabase_file_url(object_path: str) -> str:"""Tạo URL đầy đủ cho tài liệu từ Supabase Storage."""if not SUPABASE_URL or not SUPABASE_STORAGE_BUCKET or not object_path:return ""clean_path = object_path.lstrip("/")return f"{SUPABASE_URL}/storage/v1/object/public/{SUPABASE_STORAGE_BUCKET}/{clean_path}"def _extract_years_from_academic_year(academic_year: str) -> List[int]:"""Trích xuất danh sách năm từ chuỗi năm học (ví dụ '2023-2024' -> [2023, 2024])."""if not academic_year or academic_year == "ALL":return []years = []match = ACTIVE_CODE_PATTERN.search(academic_year)if match:try:start_year = int(match.group(1))end_year = int(match.group(2))years = [start_year, end_year]except (ValueError, IndexError):passreturn yearsdef _load_documents_for_ingest(path: str, extension: str) -> List[LangChainDocument]:extension = extension.lower()if extension not in _ALLOWED_EXTENSIONS:75 unmodified linesif collection_name in _ENSURED_PAYLOAD_INDEX_COLLECTIONS:return# KEYWORD indexes cho filtering nhanhfor field_name in ("object_path", "document_id", "content_hash"):try:client.create_payload_index(collection_name=collection_name,field_name=field_name,field_schema=PayloadSchemaType.KEYWORD,wait=True,)except Exception as e:logger.warning(f"Failed to create KEYWORD index for {field_name}: {e}")# INTEGER array index cho yearstry:client.create_payload_index(collection_name=collection_name,field_name="years",field_schema=PayloadSchemaType.INTEGER,wait=True,)except Exception as e:logger.warning(f"Failed to create INTEGER index for years: {e}")_ENSURED_PAYLOAD_INDEX_COLLECTIONS.add(collection_name)3 unmodified linesreturn "Index required but not found" in messagedef _get_or_create_deduplicated_points(client: QdrantClient,collection_name: str,chunk_docs: List[LangChainDocument],vectors: List,source_object_ref: str,document: Document,source_updated_at: Optional[str],source_etag: Optional[str],created_at: str,effective_source_path: Optional[str] = None,) -> tuple[List[PointStruct], List[DocumentChunk]]:"""Tích hợp MD5 deduplication: nếu content hash trùng, cập nhật years array thay vì tạo mới."""points: List[PointStruct] = []db_chunk_rows: List[DocumentChunk] = []for index, (chunk_doc, vector) in enumerate(zip(chunk_docs, vectors)):chunk_text = chunk_doc.page_contentmetadata = chunk_doc.metadata if isinstance(chunk_doc.metadata, dict) else {}# Tính content hashcontent_hash = hashlib.md5(chunk_text.encode('utf-8')).hexdigest()# Trích académie năm họcacademic_year = metadata.get("academic_year") or "ALL"years = _extract_years_from_academic_year(academic_year)# Tạo source URLsource_url = _build_supabase_file_url(source_object_ref)# Kiểm tra xem content_hash đã tồn tạiexisting_point_id = Nonetry:existing_points = client.scroll(collection_name=collection_name,limit=1,scroll_filter=Filter(must=[FieldCondition(key="content_hash",match=MatchValue(value=content_hash),)]),)if existing_points and existing_points[0]:# Nếu tìm thấy point với hash trùngexisting_point_id = existing_points[0][0].idlogger.info(f"Tìm thấy content đã tồn tại hash={content_hash[:8]}..., sẽ cập nhật years")except Exception as e:logger.debug(f"Không thể tìm kiếm existing points: {e}")if existing_point_id:# Merge years arraytry:existing_payload = client.retrieve(collection_name, [existing_point_id])[0].payloadexisting_years = set(existing_payload.get("years", []))merged_years = sorted(list(set(years) | existing_years))# Update payload với years mớiupdated_payload = {**existing_payload,"years": merged_years,"document_id": document.id, # Update document_id nếu tài liệu mới"source_updated_at": source_updated_at or existing_payload.get("source_updated_at"),}client.update_payload(collection_name=collection_name,payload_update=updated_payload,points=[existing_point_id],)logger.info(f"Đã cập nhật years cho hash {content_hash[:8]}...: {merged_years}")except Exception as e:logger.warning(f"Lỗi cập nhật years cho point đã tồn tại: {e}, sẽ tạo point mới")# Fallback: tạo point mớipoint_id = str(uuid.uuid4())payload = _build_payload(document, source_object_ref, chunk_text, index, metadata,academic_year, years, content_hash, source_url,source_updated_at, source_etag, created_at, effective_source_path)points.append(PointStruct(id=point_id, vector=vector, payload=payload))db_chunk_rows.append(DocumentChunk(document_id=document.id,chunk_index=index,content_preview=chunk_text[:200],qdrant_point_id=point_id,))else:# Tạo point mớipoint_id = str(uuid.uuid4())payload = _build_payload(document, source_object_ref, chunk_text, index, metadata,academic_year, years, content_hash, source_url,source_updated_at, source_etag, created_at, effective_source_path)points.append(PointStruct(id=point_id, vector=vector, payload=payload))db_chunk_rows.append(DocumentChunk(document_id=document.id,chunk_index=index,content_preview=chunk_text[:200],qdrant_point_id=point_id,))return points, db_chunk_rowsdef _build_payload(document: Document,source_object_ref: str,chunk_text: str,index: int,metadata: dict,academic_year: str,years: List[int],content_hash: str,source_url: str,source_updated_at: Optional[str],source_etag: Optional[str],created_at: str,effective_source_path: Optional[str] = None,) -> dict:"""Xây dựng payload dictionary cho point."""source_name = os.path.basename(source_object_ref) if source_object_ref else document.stored_namesource_relpath = source_object_ref or source_namereturn {"document_id": document.id,"filename": document.original_name,"stored_effective_source_path or name": document.stored_name,"path": document.path,"object_path": source_object_ref,"folder_key": document.folder_key,"collection_name": document.collection_name or "","source_file": metadata.get("source_file") or source_name,"source_relpath": metadata.get("source_relpath") or source_relpath,"source_url": source_url,"academic_year": academic_year,"years": years,"content_hash": content_hash,"page_number": metadata.get("page_number"),"source_updated_at": source_updated_at,"source_etag": source_etag,"chunk_index": index,"created_at": created_at,"content": chunk_text,}def _delete_existing_document_points(client: QdrantClient,collection_name: str,109 unmodified lines_delete_existing_document_points(client, target_collection, source_object_ref, document.id)created_at = datetime.now(timezone.utc).isoformat()# NEW: Sử dụng deduplication logicpoints, db_chunk_rows = _get_or_create_deduplicated_points(client=client,collection_name=target_collection,chunk_docs=chunk_docs,vectors=vectors,source_object_ref=source_object_ref,document=document,source_updated_at=source_updated_at,source_etag=source_etag,created_at=created_at,effective_source_path=effective_source_path,)client.upsert(collection_name=target_collection, points=points, wait=True)
12 unmodified lines1314151617184 unmodified lines232425262728294 unmodified lines3435363738394012 unmodified linesself.rrf_c = 60print(" BM25 sẵn sàng!")@staticmethoddef _doc_key(doc) -> str:metadata = doc.metadata if isinstance(doc.metadata, dict) else {}4 unmodified linesreturn f"{source}|{page}|{digest}"def search(self, query: str, k: int = 10, alpha: float = 0.6, year_scope: str | None = None) -> List:del year_scopeif not self.documents or k <= 0:return []4 unmodified lines# Lấy top k từ BM25tokenized_query = query.lower().split()candidate_k = min(max(k * 4, k), len(self.documents))bm25_top_docs = self.bm25.get_top_n(tokenized_query, self.documents, n=candidate_k)bm25_ranked = {}all_retrieved = {}12 unmodified lines1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768694 unmodified lines7475767778794 unmodified lines84858687888990919293949596979812 unmodified linesself.rrf_c = 60print(" BM25 sẵn sàng!")@staticmethoddef _filter_by_year_scope(documents: List, year_scope: str | None) -> List:"""Filter documents theo year_scope (ví dụ: '2023-2024' hoặc '2023')."""if not year_scope:return documentsfiltered = []year_targets = set()# Parse year_scope: có thể là "2023-2024" hoặc "2023"if "-" in year_scope:parts = year_scope.split("-")try:year_targets = {int(p.strip()) for p in parts if p.strip()}except ValueError:return documentselse:try:year_targets = {int(year_scope.strip())}except ValueError:return documentsfor doc in documents:metadata = doc.metadata if isinstance(doc.metadata, dict) else {}# Check years array (mới)doc_years = metadata.get("years", [])if isinstance(doc_years, list) and any(y in year_targets for y in doc_years):filtered.append(doc)continue# Check academic_year string (cũ, để backwards compatibility)academic_year = metadata.get("academic_year", "")if academic_year and academic_year != "ALL":doc_year_tokens = set()for potential_year in academic_year.split("-"):try:doc_year_tokens.add(int(potential_year.strip()))except ValueError:passif doc_year_tokens.intersection(year_targets):filtered.append(doc)continue# Include ALL documents không có year infoif not doc_years and academic_year == "ALL":filtered.append(doc)return filtered if filtered else documents@staticmethoddef _doc_key(doc) -> str:metadata = doc.metadata if isinstance(doc.metadata, dict) else {}4 unmodified linesreturn f"{source}|{page}|{digest}"def search(self, query: str, k: int = 10, alpha: float = 0.6, year_scope: str | None = None) -> List:if not self.documents or k <= 0:return []4 unmodified lines# Lấy top k từ BM25tokenized_query = query.lower().split()candidate_k = min(max(k * 4, k), len(self.documents))# Filter documents theo year_scope nếu códocs_to_search = self.documentsif year_scope:docs_to_search = self._filter_by_year_scope(self.documents, year_scope)if not docs_to_search:docs_to_search = self.documents # Fallback nếu không có doc match yearbm25_top_docs = self.bm25.get_top_n(tokenized_query, docs_to_search, n=candidate_k)bm25_ranked = {}all_retrieved = {}
core/collection_router_retriever.py+56-4
core/document_ingest_service.py+220-39
core/retriever.py+60-2