Michael commited on
Commit Β·
4df3f85
1
Parent(s): 0d15c66
Bug fix.
Browse filesFiles changed (3)
- app.py+39-120
- create_rag_retriever.py+205-53
- dp_vocab.txt+1334-46
57 unmodified lines58596061626364149 unmodified lines2142152162172182192202212222232242252262271 unmodified line2292302312322332341349 unmodified lines15841585158615871588158915901591276 unmodified lines1868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419752253 unmodified lines42294230423142324233423442354236423742384239424042414242424342444245424642474248424957 unmodified linesimport gradio as grfrom openai import OpenAIfrom langchain_community.embeddings import HuggingFaceEmbeddingsfrom create_rag_retriever import load_retriever_componentsimport numpy as npimport hashlibfrom langchain_core.documents import Document149 unmodified lines# Default fallback tweet dataset (empty; populated per-scenario at runtime).FALLBACK_TWEET_DATA = []RAG_K = 60RAG_FETCH_K = 10000RAG_LINKAGE_STORED_EXCERPT_LENGTH = 500ATTR_INFERENCE_EVIDENCE_STORED_EXCERPT_LENGTH = 500# ββ RAG Linkage Similarity Thresholds ββββββββββββββββββββββββROUGE_L_THRESHOLD = 0.15 # Minimum ROUGE-L score (0.0-1.0)COSINE_SIM_THRESHOLD = 0.15 # Minimum cosine similarity (0.0-1.0)MIN_COMBINED_SCORE = 0.2 # Minimum combined similarity scoreROUGE_WEIGHT = 0.3 # Weight for ROUGE-L in combined scoreCOSINE_WEIGHT = 0.7 # Weight for cosine similarity in combined score1 unmodified lineMIN_NGRAM_WORDS = 4 # Minimum words in a phrase to highlightMAX_NGRAM_WORDS = 7 # Maximum words in a phrase to highlight# ββ Privacy / Differential Privacy βββββββββββββββββββββββββββMAX_POSSIBLE_EPS = 100.0INFERENCE_LIFT_THRESHOLD = 01349 unmodified linesHybridRetriever instance or None if failed"""try:from create_rag_retriever import HybridRetrieverlogger.info(f"Building retriever from CSV: {csv_file_path}")if progress:progress(0.25, desc="Loading CSV data...")276 unmodified lines"""Strip digits and special characters."""return re.sub(r'[^a-zA-Z]', '', text.lower())class HybridRetriever:"""Hybrid retriever (semantic + BM25 + entity)."""def __init__(self, vectorstore, bm25=None, entity_index=None, documents=None,semantic_weight=0.4, bm25_weight=0.3, entity_weight=0.3):self.vectorstore = vectorstoreself.bm25 = bm25self.entity_index = entity_index or defaultdict(list)self.documents = documents or []self.semantic_weight = semantic_weightself.bm25_weight = bm25_weightself.entity_weight = entity_weightdef retrieve(self, query, k=10, fetch_k=100):"""Hybrid retrieval."""# Simplified: just use semantic search# Full implementation would combine semantic + BM25 + entitysemantic_results = self.vectorstore.similarity_search(query, k=fetch_k)return semantic_results[:k]class DPRetriever:"""Differentially private retriever using exponential mechanism.Sensitivity is computed empirically from the actual utility range of thecandidate documents rather than a fixed constant. This data-adaptiveapproach (Dwork & Roth 2014; Koga et al. 2024 "Privacy-preserving RAGwith DP") gives a tighter bound, improving the privacy-utility trade-offwithout weakening the formal Ξ΅-DP guarantee.For the exponential mechanism the sensitivity Ξu of the utility function uis defined as:Ξu = max_{d, d'} |u(d, q) - u(d', q)|When u(d, q) = max_dist - dist(d, q) (distance-to-similarity inversion),Ξu equals the range of utilities across the candidate pool. We clamp itto a configurable minimum (sensitivity_cap) to guard against degeneratecases where all candidates are equidistant from the query.Parameters----------base_retriever : HybridRetrieverThe underlying retriever whose vectorstore provides FAISS scores.epsilon : floatDP privacy budget. Smaller = stronger privacy.sensitivity_cap : floatFloor value for the computed sensitivity. Set to a small positivenumber (default 1e-3) so the mechanism stays well-defined even whenall utility values are identical. For most corpora the empiricalrange will be far larger than this cap, so it has no practical effect."""def __init__(self, base_retriever, epsilon=1.0, sensitivity_cap=1e-3):self.base_retriever = base_retrieverself.epsilon = epsilonself.sensitivity_cap = sensitivity_capdef retrieve(self, query, k=10, fetch_k=100, seed=None):"""Retrieve documents with differential privacy."""if seed is not None:np.random.seed(seed)# Get candidatestry:candidates = self.base_retriever.vectorstore.similarity_search_with_score(query, k=fetch_k)except:# Fallback if vectorstore doesn't support scoresdocs = self.base_retriever.vectorstore.similarity_search(query, k=fetch_k)return docs[:k]if not candidates:return []docs, base_scores = zip(*candidates)base_scores = np.array(base_scores)# Convert L2 distances to similarities (higher is better)if base_scores[0] >= base_scores[-1]:utilities = base_scores.copy() # similarity scores β higher is betterelse:max_dist = base_scores.max() + 1e-10utilities = max_dist - base_scores # distance scores β lower is better# ββ Empirical sensitivity (Dwork & Roth 2014; Koga et al. 2024) ββββ# Sensitivity = range of the utility function across the candidate pool.# This is the tightest valid bound for the exponential mechanism when# the utility function is score-based and bounded by the data at hand.u_range = float(utilities.max() - utilities.min())sensitivity = max(u_range, self.sensitivity_cap)# Exponential mechanism: P(d) β exp(Ξ΅ Β· u(d) / 2Ξu)probabilities = np.exp((self.epsilon * utilities) / (2.0 * sensitivity))probabilities = probabilities / probabilities.sum()# Sample k documents without replacementselected_indices = np.random.choice(len(docs), size=min(k, len(docs)), replace=False, p=probabilities)return [docs[i] for i in selected_indices]# ============================================================2253 unmodified lineslogger.info(f"[LOCAL] RAG retrieval use_rag={use_rag}; retriever={retriever}")if use_rag and retriever is not None:try:# if epsilon != float('inf'):# logger.info(f" Using DP retrieval (Ξ΅={epsilon})")# dp_retriever = DPRetriever(retriever, epsilon=epsilon)# retrieved = dp_retriever.retrieve(user_input, k=RAG_K, fetch_k=RAG_FETCH_K)# else:# retrieved = retriever.retrieve(user_input, k=RAG_K)retrieved = retriever.retrieve(llm_input, k=RAG_K)logger.info(f" Using standard retrieval (Retrieval DP disabled)")logger.info(f">>>>>>> RAG RETRIEVED: {retrieved}")u_rag = [] # computed concurrently inside make_concurrent_llm_calls_optimizedretrieval_elapsed = time.time() - retrieval_start# for r in retrieved:# print(r)# print("\n")logger.info(f" β Retrieved {len(retrieved)} docs in {retrieval_elapsed:.2f}s (LOCAL)")except Exception as e:logger.info(f" β RAG retrieval error: {e}")retrieved = []57 unmodified lines58596061626364149 unmodified lines2142152162172182192202212222232242252262271 unmodified line2292302312322332342352362371349 unmodified lines158715881589159015911592276 unmodified lines18691870187118721873187418751876187718781879188018811882188318841885188618871888188918902253 unmodified lines414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416857 unmodified linesimport gradio as grfrom openai import OpenAIfrom langchain_community.embeddings import HuggingFaceEmbeddingsfrom create_rag_retriever import load_retriever_components, DPRetriever, HybridRetrieverimport numpy as npimport hashlibfrom langchain_core.documents import Document149 unmodified lines# Default fallback tweet dataset (empty; populated per-scenario at runtime).FALLBACK_TWEET_DATA = []RAG_K = 50RAG_FETCH_K = 10000RAG_LINKAGE_STORED_EXCERPT_LENGTH = 500ATTR_INFERENCE_EVIDENCE_STORED_EXCERPT_LENGTH = 500# ββ RAG Linkage Similarity Thresholds ββββββββββββββββββββββββROUGE_L_THRESHOLD = 0.16 # Minimum ROUGE-L score (0.0-1.0)COSINE_SIM_THRESHOLD = 0.16 # Minimum cosine similarity (0.0-1.0)MIN_COMBINED_SCORE = 0.2 # Minimum combined similarity scoreROUGE_WEIGHT = 0.3 # Weight for ROUGE-L in combined scoreCOSINE_WEIGHT = 0.7 # Weight for cosine similarity in combined score1 unmodified lineMIN_NGRAM_WORDS = 4 # Minimum words in a phrase to highlightMAX_NGRAM_WORDS = 7 # Maximum words in a phrase to highlightRAG_MIN_SIMILARITY_THRESHOLD = 0.25 # baseline threshold when DP is offRAG_DP_THRESHOLD_SCALE = 1.5 # how fast the threshold rises as Ξ΅ falls# ββ Privacy / Differential Privacy βββββββββββββββββββββββββββMAX_POSSIBLE_EPS = 100.0INFERENCE_LIFT_THRESHOLD = 01349 unmodified linesHybridRetriever instance or None if failed"""try:logger.info(f"Building retriever from CSV: {csv_file_path}")if progress:progress(0.25, desc="Loading CSV data...")276 unmodified lines"""Strip digits and special characters."""return re.sub(r'[^a-zA-Z]', '', text.lower())def epsilon_adjusted_threshold(epsilon, base=RAG_MIN_SIMILARITY_THRESHOLD, scale=RAG_DP_THRESHOLD_SCALE):"""Compute a similarity threshold that tightens as epsilon falls.At epsilon=inf (no DP) β threshold = base (e.g. 0.30)At epsilon=1 β threshold β base + 0.12 (e.g. 0.42)At epsilon=0.1 β threshold β base + 0.29 (e.g. 0.59)The log1p curve means the boost is largest at very small epsilon(strong privacy) and negligible at large epsilon (no privacy).The cap at 0.92 prevents the threshold from becoming unreachable."""if epsilon == float("inf"):return baseboost = scale * math.log1p(1.0 / max(epsilon, 1e-6))return min(base + boost, 0.92)# ============================================================2253 unmodified lineslogger.info(f"[LOCAL] RAG retrieval use_rag={use_rag}; retriever={retriever}")if use_rag and retriever is not None:try:min_sim = epsilon_adjusted_threshold(epsilon)logger.info(" Using threshold-filtered retrieval (min_sim=%.3f, Ξ΅=%s)", min_sim, epsilon)if epsilon != float('inf'):# Layer 1: threshold filter# Layer 2: exponential-mechanism sampling (Retrieval DP)pre_filtered = retriever.retrieve(llm_input, k=RAG_FETCH_K, fetch_k=RAG_FETCH_K, min_similarity=min_sim)logger.info(f">>>>>>> RAG RETRIEVED pre_filtered: {retrieved}")if pre_filtered:dp_retriever = DPRetriever(retriever, epsilon=epsilon)# Pass pre-filtered docs only β DPRetriever re-samples from themretrieved = dp_retriever.retrieve(llm_input, k=RAG_K, fetch_k=len(pre_filtered))logger.info(f">>>>>>> RAG RETRIEVED post_filtered: {retrieved}")else:retrieved = []else:retrieved = retriever.retrieve(llm_input, k=RAG_K, fetch_k=RAG_FETCH_K, min_similarity=min_sim)logger.info(f">>>>>>> RAG RETRIEVED: {retrieved}")retrieval_elapsed = time.time() - retrieval_startlogger.info(f" β Retrieved {len(retrieved)} docs in {retrieval_elapsed:.2f}s (LOCAL)")except Exception as e:logger.info(f" β RAG retrieval error: {e}")retrieved = []
1234211 unmodified lines21621721821922022122222346 unmodified lines27027127227327427510 unmodified lines2862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263 unmodified lines3303313323333343353363373383393401 unmodified line342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395110 unmodified lines506507508509510511import loggingimport sysimport osimport re211 unmodified linesclass HybridRetriever:"""Hybrid retriever combining semantic, lexical, and entity-based search."""def __init__(self,documents,46 unmodified linesself.entity_index[clean_token].append(i)print(f" β Entity index built ({len(self.entity_index)} unique entities)")def _reciprocal_rank_fusion(self, rankings, k=60):"""Combine multiple rankings using RRF."""scores = defaultdict(float)10 unmodified lines"""Retrieve using only semantic search (for comparison)."""return self.vectorstore.similarity_search(query, k=k)def retrieve(self, query, k=10, fetch_k=100):"""Hybrid retrieval combining semantic, BM25, and entity matching."""# 1. Semantic searchsemantic_results = self.vectorstore.similarity_search(query, k=fetch_k)semantic_ranking = list(range(len(semantic_results)))# 2. BM25 searchquery_tokens = word_tokenize(query.lower())bm25_scores = self.bm25.get_scores(query_tokens)bm25_ranking = np.argsort(bm25_scores)[::-1][:fetch_k].tolist()# 3. Entity matching with stripped charactersquery_lower = query.lower()entity_matches = set()# Extract potential entities from query and strip special charsquery_tokens_for_entity = re.split(r'[;,\s.!?]+', query_lower)for query_token in query_tokens_for_entity:clean_query_token = strip_special_chars(query_token)if len(clean_query_token) > 2:# Check if this cleaned token matches any entityfor entity, doc_ids in self.entity_index.items():if clean_query_token in entity or entity in clean_query_token:entity_matches.update(doc_ids)entity_ranking = list(entity_matches)[:fetch_k]# Combine with RRFrankings = {"semantic": semantic_ranking,"bm25": bm25_ranking,"entity": entity_ranking,}# Weight rankingsweighted_rankings = {}if self.semantic_weight > 0:weighted_rankings["semantic"] = semantic_ranking3 unmodified linesweighted_rankings["entity"] = entity_rankingscores, sources = self._reciprocal_rank_fusion(weighted_rankings)# Sort by score and return top-k documentssorted_doc_ids = sorted(scores.keys(), key=lambda x: scores[x], reverse=True)[:k]return [self.documents[i] for i in sorted_doc_ids]# ==============================================================================1 unmodified line# ==============================================================================class DPRetriever:"""Differentially private retriever using exponential mechanism."""def __init__(self, base_retriever, epsilon=1.0):self.base_retriever = base_retrieverself.epsilon = epsilondef retrieve(self, query, k=10, fetch_k=100, method="exponential", seed=None,epsilon_total=None, track_budget=False, return_diagnostics=False):"""Retrieve documents with differential privacy.Uses exponential mechanism to add noise to retrieval scores."""if epsilon_total is not None:epsilon = epsilon_totalelse:epsilon = self.epsilonif seed is not None:np.random.seed(seed)# Get candidate poolcandidates = self.base_retriever.vectorstore.similarity_search_with_score(query, k=fetch_k)if not candidates:return []# Apply exponential mechanismdocs, base_scores = zip(*candidates)base_scores = np.array(base_scores)# Convert distances to similarities (lower distance = higher similarity)max_dist = base_scores.max() + 1e-10utilities = max_dist - base_scores# Add noise using exponential mechanismsensitivity = 2.0 # Conservative estimateprobabilities = np.exp((epsilon * utilities) / (2 * sensitivity))probabilities = probabilities / probabilities.sum()# Sample k documents without replacementselected_indices = np.random.choice(len(docs), size=min(k, len(docs)), replace=False, p=probabilities)return [docs[i] for i in selected_indices]110 unmodified linesif __name__ == "__main__":RETRIEVER_SAVE_PATH = r"C:\Users\user\Datasets\Panorama Synthetic Data RAG\faiss_panorama_retriever_components.pkl"if os.path.exists(RETRIEVER_SAVE_PATH):retriever = load_retriever_components(RETRIEVER_SAVE_PATH)12345211 unmodified lines21721821922022122222322422522622722822923023123223323446 unmodified lines28128228328428528628728828929029129229329429510 unmodified lines3063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194203 unmodified lines4244254264274284294304314324334344354364374384394401 unmodified line442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542110 unmodified lines653654655656657658659660661662663import loggingimport mathimport sysimport osimport re211 unmodified linesclass HybridRetriever:"""Hybrid retriever combining semantic (FAISS), lexical (BM25), andentity-based search with Reciprocal Rank Fusion (RRF).The ``retrieve`` method accepts an optional ``min_similarity``threshold. When set, only documents whose normalised semanticsimilarity to the query meets or exceeds that value are eligible forretrieval. This makes the system sensitive to Input-DP perturbation:a heavily noised query will drift away from the persona corpus andreturn fewer β or zero β documents, so the system's output correctlyreflects the privacy protection that is active."""def __init__(self,documents,46 unmodified linesself.entity_index[clean_token].append(i)print(f" β Entity index built ({len(self.entity_index)} unique entities)")# ββ Content-to-corpus-index lookup (used by threshold filtering) ββββββ# Maps page_content β list of corpus indices so that FAISS results# (which are Document objects, not indices) can be mapped back to# their position in self.documents. Duplicate page_content values# are handled by storing all matching indices.self._content_to_indices = defaultdict(list)for i, doc in enumerate(self.documents):self._content_to_indices[doc.page_content].append(i)def _reciprocal_rank_fusion(self, rankings, k=60):"""Combine multiple rankings using RRF."""scores = defaultdict(float)10 unmodified lines"""Retrieve using only semantic search (for comparison)."""return self.vectorstore.similarity_search(query, k=k)def retrieve(self, query, k=10, fetch_k=100, min_similarity=None):"""Hybrid retrieval combining semantic, BM25, and entity matching.Parameters----------query : strThe search query (may be DP-perturbed).k : intMaximum number of documents to return.fetch_k : intCandidate pool size passed to FAISS.min_similarity : float or NoneWhen set, only documents whose normalised semantic similarityto the query meets or exceeds this value are eligible.Documents below the threshold are excluded from ALL threeranking components (semantic, BM25, entity) before RRF.Pass None (default) to disable filtering and preserve theoriginal behaviour.Returns-------list[Document]Up to k documents, potentially fewer (or empty) whenmin_similarity is strict relative to the query."""# ββ 1. Semantic search WITH scores βββββββββββββββββββββββββββββββββββtry:candidates = self.vectorstore.similarity_search_with_score(query, k=fetch_k)except Exception:# Fallback: vectorstore does not expose scores β no thresholddocs = self.vectorstore.similarity_search(query, k=fetch_k)candidates = [(doc, 0.0) for doc in docs]if not candidates:return []raw_docs, raw_scores = zip(*candidates)raw_scores = list(raw_scores)# ββ Normalise scores to similarity β [0, 1] βββββββββββββββββββββββββ# FAISS/IndexFlatL2 returns L2 distances (ascending: closer = smaller).# IndexFlatIP on normalised vectors returns cosine scores (descending).if len(raw_scores) >= 2 and raw_scores[0] <= raw_scores[-1]:# L2 distances: invert so that higher = more similarmax_dist = max(raw_scores) + 1e-10similarities = [1.0 - s / max_dist for s in raw_scores]else:# Already similarity scores; clamp to [0, 1]similarities = [max(0.0, min(1.0, s)) for s in raw_scores]# ββ Apply similarity threshold ββββββββββββββββββββββββββββββββββββββββif min_similarity is not None:passing_pairs = [(doc, sim)for doc, sim in zip(raw_docs, similarities)if sim >= min_similarity]if not passing_pairs:logger.info(" HybridRetriever: 0/%d candidates above threshold %.3f"" β returning []",len(raw_docs), min_similarity,)return []# Build the set of *corpus* indices that passed the threshold.# This is used to restrict BM25 and entity rankings to the# same document subset, ensuring all three components only# vote for threshold-passing documents.valid_corpus_indices = set()for doc, _ in passing_pairs:for idx in self._content_to_indices.get(doc.page_content, []):valid_corpus_indices.add(idx)# Semantic ranking: use actual corpus indices for filtered docs# so they are consistent with BM25/entity namespace.semantic_ranking = []for doc, _ in passing_pairs:for idx in self._content_to_indices.get(doc.page_content, []):semantic_ranking.append(idx)break # one representative index per doc is enough for RRFelse:# No threshold: preserve original behaviour (range-based indices).valid_corpus_indices = Nonesemantic_ranking = list(range(len(raw_docs)))# ββ 2. BM25 search βββββββββββββββββββββββββββββββββββββββββββββββββββquery_tokens = word_tokenize(query.lower())bm25_scores = self.bm25.get_scores(query_tokens)bm25_ranking = np.argsort(bm25_scores)[::-1][:fetch_k].tolist()if valid_corpus_indices is not None:bm25_ranking = [i for i in bm25_ranking if i in valid_corpus_indices]# ββ 3. Entity matching βββββββββββββββββββββββββββββββββββββββββββββββquery_lower = query.lower()entity_matches = set()for query_token in re.split(r'[;,\s.!?]+', query_lower):clean_query_token = strip_special_chars(query_token)if len(clean_query_token) > 2:for entity, doc_ids in self.entity_index.items():if clean_query_token in entity or entity in clean_query_token:entity_matches.update(doc_ids)entity_ranking = list(entity_matches)[:fetch_k]if valid_corpus_indices is not None:entity_ranking = [i for i in entity_ranking if i in valid_corpus_indices]# ββ 4. Reciprocal Rank Fusion βββββββββββββββββββββββββββββββββββββββββweighted_rankings = {}if self.semantic_weight > 0:weighted_rankings["semantic"] = semantic_ranking3 unmodified linesweighted_rankings["entity"] = entity_rankingscores, sources = self._reciprocal_rank_fusion(weighted_rankings)sorted_doc_ids = sorted(scores.keys(), key=lambda x: scores[x], reverse=True)[:k]result = [self.documents[i] for i in sorted_doc_ids]logger.info(" HybridRetriever: returning %d/%d docs (min_similarity=%s)",len(result), len(candidates),f"{min_similarity:.3f}" if min_similarity is not None else "None",)return result# ==============================================================================1 unmodified line# ==============================================================================class DPRetriever:"""Differentially private retriever using the Exponential Mechanism.Sensitivity is computed *empirically* from the actual utility range ofthe candidate pool rather than a fixed constant. This data-adaptiveapproach (Dwork & Roth 2014; Koga et al. 2024) gives a tighter bound,improving the privacy-utility trade-off without weakening the formalΞ΅-DP guarantee.For the exponential mechanism the sensitivity Ξu of utility function u is:Ξu = max_{d, d'} |u(d, q) β u(d', q)|When u(d, q) = max_dist β dist(d, q) (distance-to-similarity inversion),Ξu equals the range of utilities across the candidate pool. We clamp itto ``sensitivity_cap`` to guard against degenerate cases where allcandidates are equidistant from the query.Parameters----------base_retriever : HybridRetrieverThe underlying retriever whose vectorstore provides FAISS scores.epsilon : floatDP privacy budget. Smaller Ξ΅ β stronger privacy.sensitivity_cap : floatFloor value for the empirical sensitivity (default 1e-3). Formost corpora the empirical range will be far larger than this capso it has no practical effect."""def __init__(self, base_retriever, epsilon=1.0, sensitivity_cap=1e-3):self.base_retriever = base_retrieverself.epsilon = epsilonself.sensitivity_cap = sensitivity_capdef retrieve(self, query, k=10, fetch_k=100, seed=None):"""Retrieve up to k documents with differential privacy.Uses the Exponential Mechanism: each candidate document is sampledwith probability proportional to exp(Ξ΅ Β· u(d) / 2Ξu), where u isthe normalised similarity utility and Ξu is the empirical range.Parameters----------query : strSearch query (may be DP-perturbed).k : intNumber of documents to return.fetch_k : intCandidate pool size fetched from FAISS before sampling.seed : int or NoneOptional random seed for reproducibility.Returns-------list[Document]k documents sampled with DP-weighted probabilities."""if seed is not None:np.random.seed(seed)# Fetch candidate pooltry:candidates = self.base_retriever.vectorstore.similarity_search_with_score(query, k=fetch_k)except Exception:# Fallback: vectorstore does not expose scoresdocs = self.base_retriever.vectorstore.similarity_search(query, k=fetch_k)return docs[:k]if not candidates:return []docs, base_scores = zip(*candidates)base_scores = np.array(base_scores)# ββ Convert raw scores to a utility where higher = better ββββββββββββ# FAISS with L2: scores are distances (ascending) β invert# FAISS with IP: scores are similarities (descending) β use as-isif base_scores[0] >= base_scores[-1]:utilities = base_scores.copy() # already similarity scoreselse:max_dist = base_scores.max() + 1e-10utilities = max_dist - base_scores # invert L2 distances# ββ Empirical sensitivity (Dwork & Roth 2014; Koga et al. 2024) βββββu_range = float(utilities.max() - utilities.min())sensitivity = max(u_range, self.sensitivity_cap)# ββ Exponential mechanism: P(d) β exp(Ξ΅ Β· u(d) / 2Ξu) ββββββββββββββprobabilities = np.exp((self.epsilon * utilities) / (2.0 * sensitivity))probabilities = probabilities / probabilities.sum()# Sample k documents without replacementselected_indices = np.random.choice(len(docs), size=min(k, len(docs)), replace=False, p=probabilities)return [docs[i] for i in selected_indices]110 unmodified linesif __name__ == "__main__":# retriever = load_retriever_components("./faiss_persona_sarah_chen_retriever_components.pkl")retriever = load_retriever_components("./faiss_panorama_retriever_components.pkl")# save_retriever_components(retriever, "./faiss_persona_sarah_chen_retriever_components.pkl")save_retriever_components(retriever, "./faiss_panorama_retriever_components.pkl")RETRIEVER_SAVE_PATH = r"C:\Users\user\Datasets\Panorama Synthetic Data RAG\faiss_panorama_retriever_components.pkl"if os.path.exists(RETRIEVER_SAVE_PATH):retriever = load_retriever_components(RETRIEVER_SAVE_PATH)
15 unmodified lines1617181920212212 unmodified lines353637383940411 unmodified line43444546474849503 unmodified lines54555657585960616263646526 unmodified lines9293949596979855 unmodified lines1541551561571581591601611621631641656 unmodified lines1721731741751761771787 unmodified lines1861871881891901911921931944 unmodified lines1992002012022032042053 unmodified lines20921021121221321421513 unmodified lines22923023123223323423540 unmodified lines2762772782792802812822 unmodified lines28528628728828929029120 unmodified lines31231331431531631731820 unmodified lines3393403413423433443457 unmodified lines35335435535635735835911 unmodified lines3713723733743753763772 unmodified lines3803813823833843853863873883893903913923933943953963973983994004011 unmodified line4034044054064074084094104114124134144154164174184194204214224234 unmodified lines42842943043143243343443543643743843944044144244344444544644744810 unmodified lines45946046146246346446546627 unmodified lines4944954964974984995005015025035042 unmodified lines50750850951051151251351451551651751851952052167 unmodified lines5895905915925935945955965975985992 unmodified lines60260360415 unmodified linescitizenparticipantcontributorrepresentativecolleagueclientcustomer12 unmodified lines# ββ Age / life-stage βββββββββββββββββββββββββββββββββββββββββββββββββββββββββyoungadultseniorgraduatestudent1 unmodified lineveteranexperiencedjuniorentry-levelmid-careerestablishedseasonedupcoming3 unmodified linesbeginnerintermediateadvancedearly-careerlate-careerapprenticetraineepostgraduateundergraduatefreshmansophomoreretiree26 unmodified linescentraldomesticoverseasinternationalremotenearbyprovincial55 unmodified linesstrugglingsecureinsecurewell-offunderprivilegedaffluentcashfundcapitalassetliabilityrevenue6 unmodified linespensiondividendinteresttaxinsurance# ββ Marital / relationship ββββββββββββββββββββββββββββββββββββββββββββββββββββ7 unmodified lineshouseholdrelationshippersonalcloseromanticdomesticfamilialmutualshared4 unmodified linesexclusivecasualseriousstablesupportivecaringdevoted3 unmodified lines# ββ Work / profession βββββββββββββββββββββββββββββββββββββββββββββββββββββββββworkingemployedprofessionalanalystresearcherdeveloper13 unmodified linesadvisoroperatorexecutiveadministratorinstructortrainerofficer40 unmodified linestherapymedicationrecoveryrehabilitationnutritionexercisediet2 unmodified linesdiagnosisprescriptionprocedurespecialistconsultationexaminationtest20 unmodified lineseducationlearningtrainingqualificationcertificatediplomadegree20 unmodified linesenrollmentgraduationadmissionexaminationassignmentprojectlaboratory7 unmodified linessolutionissuetopicsubjectmatterexperienceperspective11 unmodified linesdifferenceimpacteffectbenefitriskoptionchoice2 unmodified linesprocessmethodapproachenvironmentcontextbackgroundfieldsectorindustryrolepositiontaskprojectgoaltargetopportunitychallengelifestyleroutinescheduleactivityfactor1 unmodified lineelementfeaturerequirementconditioncircumstanceresourcesupportservicesystemnetworkcommunitygrouporganizationinstitution# ββ General adjectives ββββββββββββββββββββββββββββββββββββββββββββββββββββββββgoodbadgreatdifficulteasy4 unmodified linescommonspecificgeneralpersonalpublicprivatecurrentrecentpositivenegativesignificantmajorminorvariousuniquetypicalstandardadvancedbasiccomplexsimple10 unmodified linesconfidentpreparedqualifiedexperiencedknowledgeableskilledcapableable27 unmodified lines# ββ General verbs βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββworkhelpsupportmanagehandlefinduseneedwantthink2 unmodified linesunderstandconsiderbelievetrymakegetgivetakekeepstaymovechangeimprovereduceincrease67 unmodified linesconnectlinkrelateassociateinvolveincludeexcludeconsiderignorefocusprioritize2 unmodified linesmodifycustomizepersonalize15 unmodified lines16171819202112 unmodified lines3435363738391 unmodified line4142434445463 unmodified lines50515253545556575826 unmodified lines85868788899055 unmodified lines1461471481491501511521531546 unmodified lines1611621631641651667 unmodified lines1741751761771781791804 unmodified lines1851861871881891903 unmodified lines19419519619719819913 unmodified lines21321421521621721840 unmodified lines2592602612622632642 unmodified lines26726826927027127220 unmodified lines29329429529629729820 unmodified lines3193203213223233247 unmodified lines33233333433533633711 unmodified lines3493503513523533542 unmodified lines3573583593603613623633643653663673683693703713723731 unmodified line3753763773783793803813823833843853863873883893903913924 unmodified lines39739839940040140240340440540640740840941041110 unmodified lines42242342442542642727 unmodified lines4554564574584594604614624632 unmodified lines46646746846947047147247347447547647767 unmodified lines5455465475485495505515525532 unmodified lines5565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189215 unmodified linescitizenparticipantcontributorcolleagueclientcustomer12 unmodified lines# ββ Age / life-stage βββββββββββββββββββββββββββββββββββββββββββββββββββββββββyoungseniorgraduatestudent1 unmodified lineveteranexperiencedjuniorestablishedseasonedupcoming3 unmodified linesbeginnerintermediateadvancedapprenticetraineepostgraduatefreshmansophomoreretiree26 unmodified linescentraldomesticoverseasremotenearbyprovincial55 unmodified linesstrugglingsecureinsecureaffluentcashfundassetliabilityrevenue6 unmodified linespensiondividendinterestinsurance# ββ Marital / relationship ββββββββββββββββββββββββββββββββββββββββββββββββββββ7 unmodified lineshouseholdrelationshippersonalromanticfamilialmutualshared4 unmodified linesexclusivecasualserioussupportivecaringdevoted3 unmodified lines# ββ Work / profession βββββββββββββββββββββββββββββββββββββββββββββββββββββββββworkingemployedanalystresearcherdeveloper13 unmodified linesadvisoroperatorexecutiveinstructortrainerofficer40 unmodified linestherapymedicationrecoverynutritionexercisediet2 unmodified linesdiagnosisprescriptionprocedureconsultationexaminationtest20 unmodified lineseducationlearningtrainingcertificatediplomadegree20 unmodified linesenrollmentgraduationadmissionassignmentprojectlaboratory7 unmodified linessolutionissuetopicmatterexperienceperspective11 unmodified linesdifferenceimpacteffectriskoptionchoice2 unmodified linesprocessmethodapproachcontextbackgroundfieldindustryrolepositiontaskgoaltargetopportunitychallengescheduleactivityfactor1 unmodified lineelementfeaturerequirementcircumstanceresourcesupportservicesystemnetworkgrouporganizationinstitution# ββ General adjectives ββββββββββββββββββββββββββββββββββββββββββββββββββββββββgoodgreatdifficulteasy4 unmodified linescommonspecificgeneralcurrentrecentpositivenegativesignificantvariousuniquetypicalstandardbasiccomplexsimple10 unmodified linesconfidentpreparedqualifiedskilledcapableable27 unmodified lines# ββ General verbs βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββworkhelpmanagehandlefindneedwantthink2 unmodified linesunderstandconsiderbelievemakegivetakekeepstaymoveimprovereduceincrease67 unmodified linesconnectlinkrelateinvolveincludeexcludeignorefocusprioritize2 unmodified linesmodifycustomizepersonalize# ===========================================================================# AUGMENTED SECTION β stop-word-cleaned (1834 total)# Generated : 2026-03-17 (stop words removed)# Filter : 4-12 chars, alpha only, deduplicated# ===========================================================================# ββ Extended medical / mental health ββββββββββββββββββββββββββββββββββββanxietydepressionstressdisorderpsychiatricpsychiatristcounselingpsychologistdosagerefillreferralprognosissymptomsprocedurescardiologistneurologistpediatriciangynecologistoncologistradiologistorthopedicurologistnephrologistallergistinternistpathologistobstetricianradiographeroccupationalspeechrespiratorycognitivebehavioraltelehealthtelemedicineoutpatientinpatientambulatorysurgicalnoninvasivepalliativeintegrativealternativemindfulnessmeditationrelaxationbreathinginsomniafatiguemigraineheadachenauseadizzinessvertigoarthritisdiabeteshypertensionasthmaobesityanemiathyroidinfectioninflammationallergyallergiesautoimmuneneurologicalemotionalrecurringintermittentprogressivedegenerativeremissionrelapsehealingpreventioninterventionurinestoolsalivabiopsyimagingultrasoundmammogramvaccinevaccinationimmunizationboosterantibodyantibioticsantiviralswardemergencyintensiveobstetricpediatricgeriatricintakedischargeaftercarecopaydeductiblepremiumformularyappealgrievancedenialapprovalclaimstroketumorcystpolypulcerfracturesprainstrainconcussionlacerationbruisingswellingrednessrashburnwoundscarretentionedemaabscessherniaruptureprolapsedislocationhemorrhagebleedingclottingthrombosisembolisminfarctionseizureepilepsydementiaalzheimerparkinsonsclerosisfibromyalgialupuspsoriasiseczemarosaceavitiligoosteoporosisrheumatoidgouttendinitisbursitisneuropathysciaticascoliosiskyphosisherniatedtonsillitissinusitisbronchitispneumoniapleurisypericarditismyocarditisendocarditistachycardiabradycardiacolonoscopyendoscopygastroscopylaparoscopyarthroscopyaspirationdrainageirrigationdebridementsuturingcastingsplintingtractionbracingprostheticsorthoticschemotherapyradiationhormonetargetedbiologicalroboticintravenoussubcutaneoustopicaltransdermalinhalednebulizedsublingual# ββ Extended occupations and roles ββββββββββββββββββββββββββββββββββββββfishermanfisherfarmerranchershepherdherderforesterloggerminersteelworkerwelderfabricatormachinistmillwrightcarpenterjoinerglazierroofertilerbricklayerstonemasonplastererpainterdecoratorupholstererfloorerlandscaperhousekeeperjanitorcustodiancleanerlaunderertailorseamstresscobblerjewelerwatchmakeropticianaudiologistpodiatristchiropractorosteopathnaturopathhomeopathmidwifeparamedicphlebotomistfirefightersecuritywardenrangerinspectorcustomsimmigrationcaseworkerprobationparoleadvocatemediatorinterpretertranslatoreditorproofreaderpublisherillustratorphotographervideographeranimatorfilmmakerproducerscreenwriterplaywrightlyricistcomposermusicianperformerconductorbakerconfectionerpastrybutcherfishmongergreengrocergrocerbaristabartenderwaiterwaitresshosthostessconciergeactuarybrokerdealerinvestorrecruiterheadhuntermarketeradvertiserpublicistinfluencerstrategistfundraiserpoliticianlegislatordiplomatambassadorconsulprofessorlecturertutormentorfacilitatorprincipalprovostchancellor# ββ Family and relationships ββββββββββββββββββββββββββββββββββββββββββββspousehusbandwifegirlfriendboyfriendfianceeparentmotherfatherdaughtersiblingbrothersisterchildgrandparentgrandmothergrandfathergrandchildgrandsonuncleauntnephewniececousinrelativecaregiverguardianstepparentstepmotherstepfatherstepchildstepsiblingfosteradoptiveextendednuclearblendeddependentbeneficiarydivorcedwidowedseparatedremarriedcohabitingengagedfriendshipmentorshiproommatehousemateflatmate# ββ Common adverbs and qualifiers βββββββββββββββββββββββββββββββββββββββcurrentlypreviouslyformerlytypicallyregularlyconsistentlyoccasionallypartlygraduallycarefullythoroughlyproperlydirectlyindirectlyactivelypassivelyopenlyprivatelypubliclyformallyinformallypersonallyacademicallyfinanciallymedicallylegallylocallynationallyregionallygloballyremotelyimmediatelyurgentlyeventuallyultimatelyinitiallyobviouslyseeminglyreportedlyroughlypreciselyadequatelysufficientlystronglyweaklymoderatelyincreasinglyeffectivelyefficientlysuccessfullyvoluntarilyseparatelyindividuallycollectively# ββ Extended location and geography βββββββββββββββββββββββββββββββββββββstreetavenueboulevardhighwaytrailapartmentsuitebuildingcampuscompoundworkplacefactorywarehousedepotterminalstationairportseaportharborsuburbanexurbanparishprovincecantondepartmentcontinenthemisphereequatorialtropicalsubtropicaltemperatearcticalpineinlandriversidelakesidehillsideuptownmidtownperipheryfringenortheastnorthwestsoutheastsouthwestmidwesternpacificatlanticcaribbeanscandinavian# ββ Technology and digital ββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½οΏ½βββcomputerlaptoptabletsmartphonedevicekeyboardinternetwirelessbroadbandfibercablesatellitesoftwarehardwareplatformapplicationdatabaseservercloudstoragebackupencryptionprivacyfirewallwebsitebrowsersearchmessagingonlinevirtualhybriddistributedasynchronousproductivitycoordinationworkflowaccountprofileloginpasswordusernamecredentialnotificationalertremindercalendarspreadsheetpresentationarchivevideoaudiopodcaststreamingbroadcastrecordingplaybackalgorithmautomationanalyticsdashboardreportinginsightupgradeupdatepatchversionreleasedeploymentmaintenancesubscriptionlicensemembership# ββ Insurance legal and finance extension βββββββββββββββββββββββββββββββcoveragecoinsurancequalifyingprovidergenericgatekeepermedicaidmedicaremarketplaceexchangeannuityportfolioequitybondyieldallocationrebalancingwithdrawaldepositcontributionretirementcheckingoverdraftstatementtransactionmerchantvendorpayeecreditdebitoutstandingamortizationrefinanceconsolidatebankruptcyforeclosuregarnishmentliencollateralcomplianceregulationstatuteordinancejurisdictionnegligenceindemnitywarrantyguaranteeremedyarbitrationmediationlitigationjudgmentcontractclauseamendmentaddendumdisclosureconsentwaivernotarizecertifyauthenticatewitness# ββ Social and community ββββββββββββββββββββββββββββββββββββββββββββββββnonprofitcharityfoundationcommitteecouncilcoalitionalliancepartnershipoutreachengagementadvocacyawarenesscampaigninitiativehotlinehelplinediversityinclusionbelongingculturallinguisticreligiousethnicmarginalizedunderservedvulnerableempowermentresiliencecapacitycivicdemocracypolicyreformlegislationgrassrootsstakeholder# ββ Work environment and employment βββββββββββββββββββββββββββββββββββββbonusincentivecommissionovertimefulltimepermanentseasonalfreelanceonsitepromotiondemotiontransferreassignmentrotationperformanceevaluationappraisalfeedbackmilestoneobjectivemetriccompetencyassessmentonboardingorientationshadowingoffboardingresignationterminationredundancylayoffseveranceunionbargainingdisputeharassmentretaliationethicsconductintegritytransparencygovernancecultureleadershiphierarchydivisionsquadforecastheadcountprocurementsupplieroutsourcingauditqualityintellectualpatenttrademarkcopyrightlicensingroyalty# ββ Education extended ββββββββββββββββββββββββββββββββββββββββββββββββββliteracynumeracycreativityteamworkmediakindergartenelementaryvocationalpolytechnicflippedmasterysyllabusrubricformativesummativediagnosticauthentictutorialdiscussiontextbookworkbookjournalarticlefellowshiprecognitionarticulationregistrationdeferralsuspensionexpulsioncommencementalumnicareerplacementinternshipcooperativevolunteering# ββ Common general nouns ββββββββββββββββββββββββββββββββββββββββββββββββabilityabsenceaccidentachievementactionadditionadvantageaffairagreementargumentassistanceattentionattitudeauthoritybarrierbehaviorboardbodybranchcategorycauseceilingchaptercharacterclassclimatecommentcommitmentcomponentconferenceconflictconversationcorporationdeadlinedebatedemanddescriptiondestinationdetaildirectiondisplaydistancedistributiondomaindraftdurationdutyemphasisemploymentenergyentranceentryexceptionexistenceexpansionexplanationextensionfailurefigureformatframeworkfunctionfundinggenerationguidancehabithistoryidentityimportanceimpressionindicatorinformationinspectionintegrationintentioninterviewinvolvementlanguagelayerlessonlimitationmanagementmannermarginmeaningmechanismmeetingmentionmissionmixturemodificationmomentmovementnatureobligationobservationoccasionoverviewownershippatternperiodphasepracticepresencepriorityproductionprogressprovisionquantityrangeratereactionreasonreferencerelevanceresponserevisionselectionshortagespacestatusstrategystrengthstructuresubstancesummarytimelinetransitiontrenduncertaintyvalidationvaluevarietyvisionvolume# ββ Common general adjectives βββββββββββββββοΏ½οΏ½οΏ½βββββββββββββββββββββββββββabsoluteacceptableaccurateactualadditionaladverseannualapplicableapproximateawarebalancedbriefbroadcarefulclearconsistentcontinuouscorrectcriticaldecisivedetaileddistinctdiversedominantdynamicessentialexactexistingexpectedextensiveexternalextremefairfamiliarfrequentfundamentalgenuineglobalgradualgrowinghelpfulhistoricalimmediateinclusiveinitialintegratedinternallogicalmeaningfulminimalnationalnaturalnotableoriginalpartialpotentialprimaryproperreasonableremainingresponsivesimilarstructuredsuccessfulsustainablesystemicthoroughtimelytransparentvalidvitalvoluntarywidespreadneutralopenprofoundrapidrealisticregularrelatedrobustsensitivesharpsolidstrictsuperiorsystematictendertotaluniversalupdatedusefulverbalverticalvisiblevisualvocalwrittenfunctionalinteractivelegitimatemeasurableoperationalparallel# ββ Common general verbs ββββββββββββββββββββββββββββββββββββββββββββββββacceptacknowledgeacquireactivateaffectaffirmalignallocateallowannounceapproveassignassistattainauthorizeavoidbegincalculatecheckclarifyclassifycollectconfirmcontrolconvertconveycooperatedefinedependdesignatedirectenableestablishexpandextendfollowformulatefulfillgenerateguidehighlightincorporateindicateinformintroducelaunchleveragelistenlocatemeetminimizenegotiatenotifyoperateoutlineprepareproceedpromoteprotectpublishpursueraiserecognizerecruitreferreflectretainselectsendservesolvespecifystandardizestrengthenstreamlinevalidateverifywelcomecapturecommitcontinuediscovereducateempowerenhanceexamineexpressgatherinvestjustifymotivateobserveovercomepreventproducereachrealizeregulatereinforcerepresentrestoreseeksimplifystimulatesustaintackleutilize# ββ Broad common English words ββββββββββββββββββββββββββββββββββββββββββabroadadmitadoptadvanceadviceafraidagreealarmalmostamountangeranimalappeararisearriveassumeattachattackattendattractbasisbirthblockbreakbringburstcalmcarryceasecertainchainchairchargechartcheapchiefcleanclothcoastcolorcompetecontentcopycorecountcovercrimecrosscrowddailydamagedeaddealdeardeepdelaydifferdividedoubtdrawdriveearlyeartheffortentererroreventexampleexistfacefallfalsefavorfightfilefirefixedforceformfrontgivenglassgrowthhappyheardheavyholdhouseidealimagelargelegallightlimitlittlelowermodelnightnorthnotedphonepressprovepullpushrecallremainremovereturnrightriverroadroomroundroutesaveseemsenseshortsleepsmallsouthspeakspendstaffstandstorestyletermthicktraintrialtruetrustusualvisitvoicewatchwaterwholewordwritezeroalonedeeplyhardlikelysometimesbackbasebestcarecasedatedonefactfailfastfillfirmfishflowfoodfullgainheadhighhomehopehourkindlandlateleadlifelikelinelivelookmarkmeanmindmissnamenewsnotepagepainpartpastplaypoorreadrealrulesafeselfshowsignslowsorttalkteamtellturntypewaitwalkwarmweakweekwishyear
app.py+39-120
create_rag_retriever.py+205-53
dp_vocab.txt+1334-46