Spaces:
Runtime error
Runtime error
Download scripts/ingest.py from welcometoFightclub/acpc-testing-7: direct link, hf CLI and curl.
- Browser
- Download file 5.46 kB
-
https://huggingface.co/spaces/welcometoFightclub/acpc-testing-7/resolve/main/scripts/ingest.py
- Command line
-
hf download hf://spaces/welcometoFightclub/acpc-testing-7/scripts/ingest.py
-
curl -L -o ingest.py https://huggingface.co/spaces/welcometoFightclub/acpc-testing-7/resolve/main/scripts/ingest.py
5.46 kB
| """CLI ingestion script. | |
| Usage: | |
| python scripts/ingest.py <path> [--collection <name>] | |
| Chunks all .md / .txt files under <path>, enriches metadata, | |
| embeds (dense + sparse), and upserts to Qdrant. | |
| Options: | |
| --collection <name> Target Qdrant collection name. | |
| Defaults to settings.QDRANT_COLLECTION. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import asyncio | |
| import os | |
| import sys | |
| from pathlib import Path | |
| # Ensure project root is on sys.path when running as a standalone script | |
| sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) | |
| from loguru import logger | |
| from llama_index.core.schema import BaseNode | |
| from app.ingestion.chunker import TwoStageChunker | |
| from app.ingestion.embedder import get_embedder_singleton | |
| from app.ingestion.metadata import enrich_metadata | |
| from app.ingestion.vector_store import bootstrap_collection, new_qdrant_client, upsert_points | |
| from app.core.settings import settings | |
| SUPPORTED_EXT = {".md", ".markdown", ".txt"} | |
| def _discover_files(root: str) -> list[str]: | |
| root_p = Path(root) | |
| if root_p.is_file(): | |
| return [str(root_p)] if root_p.suffix.lower() in SUPPORTED_EXT else [] | |
| files: list[str] = [] | |
| for p in root_p.rglob("*"): | |
| if p.is_file() and p.suffix.lower() in SUPPORTED_EXT: | |
| files.append(str(p)) | |
| return sorted(files) | |
| async def ingest_path(root: str, collection_name: str | None = None) -> None: | |
| col = collection_name or settings.QDRANT_COLLECTION | |
| logger.info(f"Target collection: '{col}'") | |
| await bootstrap_collection(collection_name=col) | |
| chunker = TwoStageChunker() | |
| embedder = get_embedder_singleton() | |
| all_texts: list[str] = [] | |
| all_metas: list[dict] = [] | |
| all_nodes: list[BaseNode] = [] # kept for docstore | |
| files = _discover_files(root) | |
| if not files: | |
| logger.warning(f"No supported files (.md, .txt) found under '{root}'") | |
| return | |
| for fp in files: | |
| logger.info(f"Chunking: {fp}") | |
| nodes = chunker.chunk_file(fp) | |
| nodes = enrich_metadata(nodes, fp) | |
| all_nodes.extend(nodes) # collect ALL nodes (parent + child) for docstore | |
| for n in nodes: | |
| text = (n.text or "").strip() | |
| if not text: | |
| continue | |
| md = dict(n.metadata or {}) | |
| md["node_id"] = n.node_id | |
| all_texts.append(text) | |
| all_metas.append(md) | |
| if not all_texts: | |
| logger.warning("No non-empty chunks produced; aborting.") | |
| return | |
| logger.info(f"Fitting BM25 on {len(all_texts)} chunks...") | |
| embedder.bm25.fit(all_texts) | |
| logger.info(f"Embedding {len(all_texts)} chunks (batch size 100)...") | |
| dense = await embedder.embed_texts(all_texts, batch_size=100) | |
| sparse = [embedder.bm25.encode_document(t) for t in all_texts] | |
| logger.info(f"Upserting to '{col}'...") | |
| n = await upsert_points(None, all_texts, dense, sparse, all_metas, | |
| collection_name=col) | |
| logger.info(f"Upserted {n} points to '{col}'.") | |
| # Persist parent-child hierarchy so AutoMergingRetriever works after restart. | |
| # Each collection gets its own docstore directory to avoid cross-collection | |
| # hierarchy mix-ups. | |
| docstore_dir = os.path.join(settings.DOCSTORE_DIR, col) | |
| logger.info(f"Persisting docstore ({len(all_nodes)} nodes) → {docstore_dir}") | |
| from app.retrieval.rag_retriever import get_rag_retriever_singleton | |
| retriever = get_rag_retriever_singleton() | |
| # Override the retriever's docstore dir for this collection | |
| _persist_docstore(retriever, all_nodes, docstore_dir) | |
| logger.info("Done — ingestion complete.") | |
| def _persist_docstore(retriever, nodes: list, docstore_dir: str) -> None: | |
| """Add nodes to retriever docstore and persist to docstore_dir.""" | |
| from llama_index.core.storage.docstore import SimpleDocumentStore | |
| import os | |
| # Load existing docstore for this collection (or start fresh) | |
| docstore_file = os.path.join(docstore_dir, "docstore.json") | |
| if os.path.exists(docstore_file): | |
| try: | |
| docstore = SimpleDocumentStore.from_persist_dir(docstore_dir) | |
| logger.info(f"Merging into existing docstore ({len(docstore.docs)} docs)") | |
| except Exception as exc: | |
| logger.warning(f"Failed to load existing docstore ({exc}), starting fresh") | |
| docstore = SimpleDocumentStore() | |
| else: | |
| docstore = SimpleDocumentStore() | |
| try: | |
| docstore.add_documents(nodes) | |
| os.makedirs(docstore_dir, exist_ok=True) | |
| docstore.persist(persist_path=docstore_file) | |
| logger.info(f"Docstore saved: {len(docstore.docs)} total docs → {docstore_file}") | |
| except Exception as exc: | |
| logger.error(f"Docstore persist failed: {exc}") | |
| # Also update the live retriever's in-memory docstore | |
| try: | |
| retriever._docstore.add_documents(nodes) | |
| except Exception: | |
| pass | |
| def main() -> None: | |
| parser = argparse.ArgumentParser( | |
| description="Ingest .md/.txt documents into Qdrant." | |
| ) | |
| parser.add_argument("path", help="File or directory to ingest") | |
| parser.add_argument( | |
| "--collection", | |
| default=None, | |
| metavar="NAME", | |
| help=f"Qdrant collection name (default: {settings.QDRANT_COLLECTION!r})", | |
| ) | |
| args = parser.parse_args() | |
| asyncio.run(ingest_path(args.path, collection_name=args.collection)) | |
| if __name__ == "__main__": | |
| main() | |