Spaces:
Runtime error
Runtime error
Download retriever.py from julietarubis/internal-docs-qa: direct link, hf CLI and curl.
- Browser
- Download file 1.11 kB
-
https://huggingface.co/spaces/julietarubis/internal-docs-qa/resolve/main/retriever.py
- Command line
-
hf download hf://spaces/julietarubis/internal-docs-qa/retriever.py
-
curl -L -o retriever.py https://huggingface.co/spaces/julietarubis/internal-docs-qa/resolve/main/retriever.py
1.11 kB
| from sentence_transformers import SentenceTransformer | |
| import faiss | |
| import numpy as np | |
| from config import EMBEDDING_MODEL | |
| model = SentenceTransformer(EMBEDDING_MODEL) | |
| index = faiss.IndexFlatL2(384) | |
| docs = [] | |
| def chunk_text(text, max_length=500): | |
| sentences = text.split('. ') | |
| chunks = [] | |
| current_chunk = '' | |
| for sentence in sentences: | |
| if len(current_chunk) + len(sentence) <= max_length: | |
| current_chunk += sentence + '. ' | |
| else: | |
| chunks.append(current_chunk.strip()) | |
| current_chunk = sentence + '. ' | |
| if current_chunk: | |
| chunks.append(current_chunk.strip()) | |
| return chunks | |
| def build_index(doc_texts): | |
| global docs | |
| docs = [] | |
| all_chunks = [] | |
| for doc in doc_texts: | |
| chunks = chunk_text(doc) | |
| docs.extend(chunks) | |
| all_chunks.extend(chunks) | |
| embeddings = model.encode(all_chunks) | |
| index.add(np.array(embeddings)) | |
| def get_relevant_chunks(query, top_k=1): | |
| query_vec = model.encode([query]) | |
| D, I = index.search(np.array(query_vec), top_k) | |
| return "\n\n".join([docs[i] for i in I[0]]) | |