Spaces:
Running
Running
File size: 9,652 Bytes
c8ab95e defb0f0 c8ab95e defb0f0 7df82ea c8ab95e 7df82ea dead93e d9732be dead93e d9732be dead93e d9732be dead93e d9732be dead93e d9732be dead93e d9732be dead93e d9732be dead93e d9732be dead93e d9732be dead93e d9732be dead93e 780e6e0 dead93e d9732be dead93e d9732be dead93e d9732be dead93e d9732be dead93e d9732be dead93e d9732be dead93e d9732be dead93e d9732be dead93e d9732be dead93e d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f c2b7f46 f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be a7c5b0d d9732be a7c5b0d d9732be a7c5b0d d9732be a7c5b0d d9732be a7c5b0d d9732be a7c5b0d f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be f8d698f d9732be c2b7f46 f8d698f d9732be f8d698f d9732be f8d698f d9732be | 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 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 | ---
title: "distill-rag"
emoji: "π§°"
colorFrom: "indigo"
colorTo: "blue"
sdk: "static"
pinned: false
tags:
- tool
- rag
- dataset
- nlp
- text-processing
- search
- embeddings
---
# Distill RAG
A lightweight pipeline for extraction, chunking, embeddings, and search.
---
## π§ What Is This? (Plain-Language Overview)
**distill_rag** is a small but powerful toolkit that helps you transform messy text sources (HTML pages, transcripts, articles, archives) into **clean, structured data** that AI models can learn from.
Itβs designed for people who want to build:
* **domain-specific AI assistants**
* **high-quality expert models**
* **distillation pipelines** where a stronger model teaches a smaller one
If youβve ever tried to fine-tune a model and realised the hardest part is actually preparing the dataset β this toolkit is for that problem.
---
## π Why This Exists
Training or distilling a specialised AI model requires **clean, coherent, well-structured data**.
But most text online is:
* full of ads, scripts, headers
* chopped into small fragments
* badly formatted
* missing metadata
* hard to chunk in meaningful ways
Before you can train a model, you need a **pipeline that turns raw text into polished, training-ready data**.
`distill_rag` gives you that pipeline. It helps you:
1. pull content from raw HTML
2. clean and structure it
3. break it into long coherent chunks
4. embed it locally
5. index it with Elasticsearch
6. perform high-quality semantic search
This structure mirrors the data format most distillation workflows expect.
**Goal:**
Make it easy for researchers and builders to create **high-quality domain-specific AI models**.
---
### β‘ Key Benefits: Speed, Simplicity, and Efficiency
Built entirely in Node.js, `distill_rag` leverages async promises and lightweight concurrency to deliver blazing-fast performanceβoften 5β10Γ faster than equivalent Python-based tools like LlamaIndex, LangChain, or Haystack. This makes it ideal for local workflows on consumer hardware, where you can process thousands of chunks in minutes without heavy dependencies or complex setups.
- **GPU-Bound Efficiency**: Embeddings (via Ollama) are the bottleneck, but everything else (extraction, chunking, indexing) is lightning-fast, with sustained rates of 30+ chunks/second on a single RTX 3090.
- **No Overhead Bloat**: Direct HTTP calls to embedding APIs and seamless parallelism mean low CPU/RAM usage and no GIL-like bottlenecks.
- **Hackable for JS Devs**: If you're in the Node ecosystem (e.g., integrating with web apps or CLIs), this fits like a gloveβzero language switching required.
- **Benchmark Example**: On an RTX 3090 with 1531 sessions (~3565 chunks, 5000β9000 chars each), a full index rebuild takes just 1m48s (33 chunks/s). Comparable Python tools often take 8β40 minutes for similar workloads due to wrapper latencies and inefficient batching.
If speed and developer joy matter in your RAG/distillation pipeline, this toolkit shines.
---
## π§ How It Works (At a Glance)
### 1. Extract & Clean
Feed it a folder of HTML (scraped, archived, downloaded).
It removes noise and produces structured JSON sessions.
### 2. Chunk & Embed
Text is broken into long, context-rich chunks (ideal for distillation).
Each chunk is embedded using a local model like `mxbai-embed-large`.
### 3. Index & Search
Chunks are stored in Elasticsearch as vectors + metadata.
You can then run semantic search to retrieve relevant material.
---
## π Who Should Use This?
* AI researchers building **aligned distilled models**
* Developers training **expert assistants**
* Archivists handling large text collections
* Anyone building **custom RAG systems**
* Anyone who wants a clean, open, hackable indexing pipeline
---
## π Features
* β HTML extraction using Cheerio
* β Robust cleaning (scripts, ads, headers removed)
* β Long-chunker tuned for distillation
* β Async embedding + indexing
* β Elasticsearch v8 dense vector support
* β Ollama embedding API support
* β CLI tools for extraction, indexing, search
* β Test suite included
* β Apache 2.0 licensed
---
## π§± Project Structure
```text
distill_rag/
βββ data_extraction/
β βββ clean_html.js # strip noise safely
β βββ extractor.js # extract Q/A style turns
β βββ convert_raw_to_sessions.js # HTML β structured JSON
β βββ walk_and_extract.js # CLI to batch-convert directories
β
βββ indexing/
β βββ index_distill_chunks.js # long-chunk indexer
β βββ rebuild_distill_index.sh # wipe + rebuild helper
β
βββ search/
β βββ search_distill_chunks.js # BM25 / vector / hybrid search
β βββ search_cli.js # CLI search tool
β
βββ tests/ # jest-based automated test suite
β
βββ prompts/ # optional prompt templates
βββ shared/ # shared utilities
βββ cleanup.sh # remove build artefacts
βββ jest.config.js
βββ package.json
βββ README.md
```
---
## π¦ Installation
Requirements:
* Node **18+**
* Elasticsearch **8.x**
* Embedding API (e.g., **Ollama** running `mxbai-embed-large`)
Install:
```bash
npm install
```
---
## π§Ό 1. Extracting Data from Raw HTML
Convert a directory:
```bash
node data_extraction/walk_and_extract.js raw_html/ extracted_sessions/
```
Output example:
```json
{
"title": "example.html",
"turns": [
{ "role": "user", "content": "Q: What is service?" },
{ "role": "assistant", "content": "Service begins with kindness." }
]
}
```
Behind the scenes it:
* strips scripts, ads, headers, nav bars
* extracts paragraphs and headings
* assigns roles (`user` = first block, rest `assistant`)
* normalises whitespace
---
## π§± 2. Chunking + Indexing into Elasticsearch
Rebuild the full index:
```bash
bash rebuild_distill_index.sh
```
Manual index build:
```bash
ES_DISTILL_INDEX=quo_distill_index \
JSON_DIR=./extracted_sessions \
ELASTICSEARCH_NODE=http://localhost:9200 \
node indexing/index_distill_chunks.js
```
The indexer:
* creates long semantic chunks (5000β9000 characters)
* calls your embedding API (`/api/embeddings`)
* indexes all chunks with metadata:
* `title`
* `session_date`
* `source`
* `chunk_index`
* `embedding` (vector)
---
## π Advanced Retrieval Modes
`distill_rag` supports **three complementary search strategies** via `search/search_distill_chunks.js`:
### 1. BM25 (Keyword Search)
Classic lexical search.
Good for names, citations, exact phrases.
```js
const { searchBM25 } = require("./search/search_distill_chunks");
const results = await searchBM25("service to others", 5);
console.log(results);
```
---
### 2. Vector Search (Dense Embeddings)
Semantic similarity using your local embedding model.
```js
const { searchVector } = require("./search/search_distill_chunks");
const results = await searchVector("how to grow spiritually", 5);
console.log(results);
```
---
### 3. Hybrid Search (RRF Fusion) β Recommended
State-of-the-art fusion of:
* BM25 lexical relevance
* Dense vector KNN
This gives robust results even on noisy or varied datasets.
```js
const { searchHybrid } = require("./search/search_distill_chunks");
const results = await searchHybrid("balance love and wisdom", 5);
console.log(results);
```
---
## π₯ Search CLI Tool
You can run searches directly from the terminal:
```bash
node search/search_cli.js "service to others"
```
Specify mode (`bm25`, `vector`, `hybrid`) and `k`:
```bash
node search/search_cli.js "healing catalyst" hybrid 8
node search/search_cli.js "unity" bm25 5
node search/search_cli.js "wisdom" vector 10
```
This prints:
* source file
* chunk index
* score
* preview of the retrieved chunk
---
## π§ͺ Tests
Run all tests:
```bash
npm test
```
Covers:
* HTML cleaning
* extractor correctness
* session conversion
* chunker behaviour
* embedding API live test
* Elasticsearch index live test
* hybrid retrieval
* end-to-end smoke test
---
## π§½ Cleanup
```bash
npm run clean
```
or:
```bash
bash cleanup.sh
```
---
## π Configuration
Config is handled via environment variables:
| Variable | Default | Purpose |
| -------------------- | --------------------------------------- | ------------------------------- |
| `ELASTICSEARCH_NODE` | `http://localhost:9200` | ES cluster URL |
| `ES_DISTILL_INDEX` | `quo_distill_index` | Target index |
| `EMBED_URL` | `http://localhost:11434/api/embeddings` | Embedding API |
| `EMBED_MODEL` | `mxbai-embed-large` | Embedding model |
| `CHUNK_MIN` | `5000` | Minimum chunk size (characters) |
| `CHUNK_MAX` | `9000` | Maximum chunk size (characters) |
| `JSON_DIR` | *(required)* | Directory of session JSON |
---
## π License
Apache 2.0 (see `LICENSE`).
---
## π€ Contributing
Contributions are welcome β bug fixes, new extractors, support for other embedding backends, indexing strategies, documentation.
---
## βοΈ Final Thoughts
This project is meant to empower people building truth-aligned, service-oriented models.
If it helps someone create a clearer dataset or a kinder AI, itβs doing its job.
---
|