Spaces:
Build error
Build error
File size: 5,445 Bytes
cedc2e4 d2509c7 | 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | import os
import json
import pickle
from typing import List, Dict, Tuple
import numpy as np
import faiss
from sentence_transformers import SentenceTransformer
from pypdf import PdfReader
from .config import (
DATA_DIR,
URLS_PATH,
FAISS_INDEX_PATH,
DOCSTORE_PATH,
EMBED_MODEL_NAME,
)
from .fetcher import fetch_page_text
DOCS_DIR = os.path.join(DATA_DIR, "docs")
def ensure_data_dir():
os.makedirs(DATA_DIR, exist_ok=True)
os.makedirs(DOCS_DIR, exist_ok=True) # safe even if empty
def load_urls() -> List[str]:
"""
Expects data/urls.json like:
{ "urls": ["https://...", "https://..."] }
"""
if not os.path.exists(URLS_PATH):
# If urls.json missing, we allow ingestion to continue with local docs only
return []
with open(URLS_PATH, "r", encoding="utf-8") as f:
obj = json.load(f)
urls = obj.get("urls", [])
return [u.strip() for u in urls if isinstance(u, str) and u.strip()]
def chunk_text(text: str, chunk_size_words: int = 900, overlap_words: int = 150) -> List[str]:
"""
Simple word-based chunking (fast + reliable).
"""
text = (text or "").strip()
if not text:
return []
words = text.split()
chunks = []
i = 0
step = max(1, chunk_size_words - overlap_words)
while i < len(words):
chunk = words[i:i + chunk_size_words]
chunks.append(" ".join(chunk))
i += step
return chunks
# -------------------------
# URL ingestion
# -------------------------
def build_docs_from_urls(urls: List[str]) -> List[Dict]:
docs: List[Dict] = []
for url in urls:
try:
page = fetch_page_text(url, use_cache=True)
chunks = chunk_text(page.get("text", ""))
for idx, ch in enumerate(chunks):
docs.append({
"text": ch,
"meta": {
"source_type": "url",
"url": page.get("url", url),
"title": page.get("title", url),
"chunk": idx,
}
})
except Exception:
# skip bad URLs but continue ingestion
continue
return docs
# -------------------------
# Local docs ingestion
# -------------------------
def list_local_files() -> List[str]:
"""
Reads local files from data/docs/
Supported: .txt, .md, .pdf (text-based PDFs)
"""
if not os.path.exists(DOCS_DIR):
return []
paths = []
for name in os.listdir(DOCS_DIR):
p = os.path.join(DOCS_DIR, name)
if not os.path.isfile(p):
continue
ext = os.path.splitext(name)[1].lower()
if ext in [".txt", ".md", ".pdf"]:
paths.append(p)
return sorted(paths)
def read_text_file(path: str) -> str:
with open(path, "r", encoding="utf-8", errors="ignore") as f:
return f.read()
def read_pdf_text(path: str) -> str:
"""
Works best on selectable-text PDFs.
Scanned/image-only PDFs will extract very little.
"""
reader = PdfReader(path)
parts = []
for page in reader.pages:
try:
parts.append(page.extract_text() or "")
except Exception:
continue
return "\n".join(parts).strip()
def build_docs_from_files(file_paths: List[str]) -> List[Dict]:
docs: List[Dict] = []
for path in file_paths:
name = os.path.basename(path)
ext = os.path.splitext(name)[1].lower()
try:
if ext in [".txt", ".md"]:
text = read_text_file(path)
elif ext == ".pdf":
text = read_pdf_text(path)
else:
continue
except Exception:
continue
chunks = chunk_text(text)
for idx, ch in enumerate(chunks):
docs.append({
"text": ch,
"meta": {
"source_type": "file",
"url": f"file://{name}",
"title": name,
"chunk": idx,
}
})
return docs
# -------------------------
# Index building
# -------------------------
def build_faiss_index(docs: List[Dict]) -> None:
model = SentenceTransformer(EMBED_MODEL_NAME)
texts = [d["text"] for d in docs]
emb = model.encode(texts, normalize_embeddings=True, show_progress_bar=True)
emb = np.array(emb, dtype="float32")
index = faiss.IndexFlatIP(emb.shape[1])
index.add(emb)
faiss.write_index(index, FAISS_INDEX_PATH)
with open(DOCSTORE_PATH, "wb") as f:
pickle.dump(docs, f)
def run_ingestion():
ensure_data_dir()
urls = load_urls()
url_docs = build_docs_from_urls(urls) if urls else []
file_paths = list_local_files()
file_docs = build_docs_from_files(file_paths) if file_paths else []
docs = url_docs + file_docs
if not docs:
raise RuntimeError(
"No documents found.\n"
"- Add URLs to data/urls.json OR\n"
"- Add files to data/docs/ (.txt, .md, .pdf)"
)
build_faiss_index(docs)
print("✅ Ingestion complete")
print(f"URLs: {len(urls)}")
print(f"Local files: {len(file_paths)}")
print(f"Chunks: {len(docs)}")
print(f"Saved index: {FAISS_INDEX_PATH}")
print(f"Saved docs: {DOCSTORE_PATH}")
if __name__ == "__main__":
run_ingestion() |