Spaces:
Sleeping
Sleeping
File size: 11,174 Bytes
b87aca1 | 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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 | """
Document Ingestion Pipeline
----------------------------
Loads the IJNet knowledge base, applies smart chunking strategies,
embeds documents, and stores them in a FAISS vector store.
Chunking Strategy:
- Structured records (opportunities): kept as single documents with rich metadata
- Unstructured text (articles): split with RecursiveCharacterTextSplitter
using semantic paragraph boundaries
- IJNet info: kept as single documents
Each chunk carries full metadata for source attribution and filtering.
"""
import json
import hashlib
from datetime import datetime
from pathlib import Path
from langchain_core.documents import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
# ---------------------------------------------------------------------------
# 1. DOCUMENT LOADING
# ---------------------------------------------------------------------------
def load_knowledge_base(path: str = "data/knowledge_base.json") -> dict:
"""Load the raw knowledge base JSON."""
with open(path, "r") as f:
return json.load(f)
# ---------------------------------------------------------------------------
# 2. SMART CHUNKING
# ---------------------------------------------------------------------------
def _opportunity_to_document(opp: dict) -> Document:
"""
Convert a structured opportunity record into a single LangChain Document.
Strategy: Compose a natural-language representation that includes all
searchable fields. This lets semantic search match on any aspect
(region, topic, type, deadline, eligibility) without needing separate
structured queries.
"""
# Build rich text representation
parts = [
f"Title: {opp['title']}",
f"Type: {opp['type'].capitalize()}",
f"Organization: {opp['organization']}",
f"Description: {opp['description']}",
f"Eligibility: {opp['eligibility']}",
f"Regions: {', '.join(opp['regions'])}",
f"Topics: {', '.join(opp['topics'])}",
f"Deadline: {opp['deadline']}",
f"Duration: {opp['duration']}",
f"Benefits: {opp['benefits']}",
f"Language: {opp['language']}",
]
text = "\n".join(parts)
metadata = {
"source": opp.get("source_url", ""),
"source_type": "opportunity",
"doc_id": opp["id"],
"title": opp["title"],
"opp_type": opp["type"],
"organization": opp["organization"],
"regions": ", ".join(opp["regions"]),
"topics": ", ".join(opp["topics"]),
"deadline": opp["deadline"],
"language": opp.get("language", "English"),
}
return Document(page_content=text, metadata=metadata)
def _article_to_chunks(article: dict, splitter: RecursiveCharacterTextSplitter) -> list[Document]:
"""
Split an article into semantic chunks, preserving metadata on each.
Strategy: Use paragraph-aware splitting. Articles are longer so we split
them, but keep chunks large enough to preserve context (~400-600 tokens).
"""
full_text = f"Article: {article['title']}\nAuthor: {article.get('author', 'IJNet Staff')}\n\n{article['full_text']}"
base_metadata = {
"source": article.get("source_url", ""),
"source_type": "article",
"doc_id": article["id"],
"title": article["title"],
"author": article.get("author", "IJNet Staff"),
"date": article.get("date", ""),
"section": article.get("section", ""),
"topics": ", ".join(article.get("topics", [])),
}
chunks = splitter.split_text(full_text)
documents = []
for i, chunk in enumerate(chunks):
meta = {**base_metadata, "chunk_index": i, "total_chunks": len(chunks)}
documents.append(Document(page_content=chunk, metadata=meta))
return documents
def _ijnet_info_to_document(info: dict) -> list[Document]:
"""Convert IJNet organizational info into documents."""
docs = []
# About document
about_text = (
f"About IJNet: {info['about']}\n\n"
f"IJNet is available in these languages: {', '.join(info['languages'])}.\n"
f"Website: {info['website']}"
)
docs.append(Document(
page_content=about_text,
metadata={
"source": info["website"],
"source_type": "ijnet_info",
"doc_id": "ijnet-about",
"title": "About IJNet",
}
))
# Services document
services_text = (
"IJNet Services and Offerings:\n" +
"\n".join(f"- {s}" for s in info["services"])
)
docs.append(Document(
page_content=services_text,
metadata={
"source": info["website"],
"source_type": "ijnet_info",
"doc_id": "ijnet-services",
"title": "IJNet Services",
}
))
return docs
def build_documents(kb: dict) -> list[Document]:
"""
Build the full document list from the knowledge base.
Returns documents ready for embedding and indexing.
"""
documents = []
# --- Opportunities: one doc per opportunity (no splitting) ---
for opp in kb.get("opportunities", []):
documents.append(_opportunity_to_document(opp))
# --- Articles: split into semantic chunks ---
splitter = RecursiveCharacterTextSplitter(
chunk_size=800, # ~200 tokens β small enough for precise retrieval
chunk_overlap=150, # overlap to preserve context at boundaries
separators=["\n\n", "\n", ". ", ", ", " "], # prefer paragraph boundaries
length_function=len,
)
for article in kb.get("articles", []):
if article.get("full_text"):
chunks = _article_to_chunks(article, splitter)
documents.extend(chunks)
# --- IJNet Info ---
if kb.get("ijnet_info"):
documents.extend(_ijnet_info_to_document(kb["ijnet_info"]))
return documents
# ---------------------------------------------------------------------------
# 3. EMBEDDING + VECTOR STORE
# ---------------------------------------------------------------------------
from langchain_core.embeddings import Embeddings as EmbeddingsBase
class SimpleEmbeddings(EmbeddingsBase):
"""
Lightweight TF-IDF-based fallback embeddings for environments where
HuggingFace model downloads are blocked. Uses sklearn's TfidfVectorizer
fit on the corpus vocabulary for decent keyword-aware embeddings.
NOT recommended for production β use HuggingFace sentence-transformers
when internet access is available.
"""
dimension: int = 384
def __init__(self, dimension: int = 384, **kwargs):
super().__init__(**kwargs)
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
self.dimension = dimension
self._vectorizer = TfidfVectorizer(max_features=dimension, stop_words="english")
self._fitted = False
self._np = np
def _ensure_fitted(self, texts: list[str]):
if not self._fitted:
self._vectorizer.fit(texts)
self._fitted = True
def embed_documents(self, texts: list[str]) -> list[list[float]]:
self._ensure_fitted(texts)
matrix = self._vectorizer.transform(texts).toarray()
result = self._np.zeros((len(texts), self.dimension))
cols = min(matrix.shape[1], self.dimension)
result[:, :cols] = matrix[:, :cols]
norms = self._np.linalg.norm(result, axis=1, keepdims=True)
norms[norms == 0] = 1
result = result / norms
return result.tolist()
def embed_query(self, text: str) -> list[float]:
return self.embed_documents([text])[0]
def get_embeddings(model_name: str = "sentence-transformers/all-MiniLM-L6-v2", use_fallback: bool = False):
"""
Initialize the embedding model.
Primary: HuggingFace sentence-transformers (requires internet on first run).
Fallback: TF-IDF based embeddings (works fully offline).
Args:
model_name: HuggingFace model name for sentence-transformers
use_fallback: Force using the lightweight TF-IDF fallback
"""
if use_fallback:
print("Using fallback TF-IDF embeddings (offline mode)")
return SimpleEmbeddings()
try:
from langchain_huggingface import HuggingFaceEmbeddings
return HuggingFaceEmbeddings(
model_name=model_name,
model_kwargs={"device": "cpu"},
encode_kwargs={"normalize_embeddings": True},
)
except Exception as e:
print(f"Warning: Could not load HuggingFace embeddings ({e})")
print("Falling back to TF-IDF embeddings.")
return SimpleEmbeddings()
def build_vector_store(
documents: list[Document],
embeddings=None,
save_path: str = "data/faiss_index"
) -> FAISS:
"""
Build and persist a FAISS vector store from documents.
"""
if embeddings is None:
embeddings = get_embeddings()
print(f"Building vector store with {len(documents)} documents...")
vector_store = FAISS.from_documents(documents, embeddings)
# Persist to disk
vector_store.save_local(save_path)
print(f"Vector store saved to {save_path}")
return vector_store
def load_vector_store(
save_path: str = "data/faiss_index",
embeddings=None
) -> FAISS:
"""Load a persisted FAISS vector store."""
if embeddings is None:
embeddings = get_embeddings()
return FAISS.load_local(
save_path, embeddings, allow_dangerous_deserialization=True
)
# ---------------------------------------------------------------------------
# 4. FULL INGESTION PIPELINE
# ---------------------------------------------------------------------------
def run_ingestion(
kb_path: str = "data/knowledge_base.json",
index_path: str = "data/faiss_index",
) -> FAISS:
"""
Complete ingestion pipeline: load β chunk β embed β store.
"""
print("=" * 50)
print("IJNet Knowledge Base Ingestion Pipeline")
print("=" * 50)
# Load
print("\n[1/4] Loading knowledge base...")
kb = load_knowledge_base(kb_path)
print(f" - {len(kb.get('opportunities', []))} opportunities")
print(f" - {len(kb.get('articles', []))} articles")
# Chunk
print("\n[2/4] Building documents with smart chunking...")
documents = build_documents(kb)
print(f" - {len(documents)} total document chunks")
# Show breakdown
by_type = {}
for doc in documents:
t = doc.metadata.get("source_type", "unknown")
by_type[t] = by_type.get(t, 0) + 1
for t, count in by_type.items():
print(f" β’ {t}: {count} chunks")
# Embed + Store
print("\n[3/4] Initializing embedding model...")
embeddings = get_embeddings()
print("\n[4/4] Building FAISS vector store...")
vector_store = build_vector_store(documents, embeddings, index_path)
print("\nβ Ingestion complete!")
return vector_store
if __name__ == "__main__":
run_ingestion()
|