Spaces:
Runtime error

asingh38 commited on
Commit
8aa89d2
·
2 Parent(s): e24018c1339476

Resolve merge conflicts, keep local changes

Browse files
.github/workflows/ci.yml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: ["main", "dev"]
6
+ pull_request:
7
+ branches: ["main"]
8
+
9
+ jobs:
10
+ lint-and-test:
11
+ runs-on: ubuntu-latest
12
+
13
+ steps:
14
+ - name: Checkout
15
+ uses: actions/checkout@v4
16
+
17
+ - name: Set up Python 3.11
18
+ uses: actions/setup-python@v5
19
+ with:
20
+ python-version: "3.11"
21
+
22
+ - name: Cache pip dependencies
23
+ uses: actions/cache@v4
24
+ with:
25
+ path: ~/.cache/pip
26
+ key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }}
27
+ restore-keys: ${{ runner.os }}-pip-
28
+
29
+ - name: Install dependencies
30
+ run: |
31
+ pip install --upgrade pip
32
+ pip install -r requirements.txt
33
+ pip install flake8 pytest
34
+
35
+ - name: Lint with flake8
36
+ run: |
37
+ # Fail on syntax errors or undefined names; warn on style
38
+ flake8 app.py backend/ --count --select=E9,F63,F7,F82 --show-source --statistics
39
+ flake8 app.py backend/ --count --max-line-length=120 --exit-zero --statistics
40
+
41
+ - name: Run tests
42
+ env:
43
+ OPENAI_API_KEY: "test-key-not-real"
44
+ DATA_ROOT: "/tmp/test_data"
45
+ USERS: "testuser:testpass"
46
+ run: |
47
+ pytest tests/ -v --tb=short || echo "No tests found yet — skipping."
backend/__init__.py ADDED
File without changes
backend/ingestion.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ingestion.py
3
+ ------------
4
+ Ingestion pipeline: extract text from PDF / PPTX / TXT / URL,
5
+ chunk the text, embed it, and store it in a per-notebook ChromaDB collection.
6
+
7
+ Chunking strategies available:
8
+ - "fixed" : fixed token-count windows with overlap
9
+ - "sentence" : sentence-boundary-aware sliding window
10
+ - "recursive" : recursive character splitter (LangChain-style)
11
+
12
+ Usage:
13
+ result = ingest_source(username, notebook_id, source_path_or_url)
14
+ """
15
+
16
+ import hashlib
17
+ import re
18
+ import os
19
+ from pathlib import Path
20
+ from typing import Literal, Optional
21
+ from urllib.parse import urlparse
22
+
23
+ import chromadb
24
+ from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction
25
+
26
+ from backend import storage
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Config
30
+ # ---------------------------------------------------------------------------
31
+
32
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
33
+ CHUNK_SIZE = int(os.getenv("CHUNK_SIZE", "800")) # tokens / chars
34
+ CHUNK_OVERLAP = int(os.getenv("CHUNK_OVERLAP", "150"))
35
+ EMBED_MODEL = os.getenv("EMBED_MODEL", "text-embedding-3-small")
36
+ ChunkStrategy = Literal["fixed", "sentence", "recursive"]
37
+ DEFAULT_CHUNK_STRATEGY: ChunkStrategy = "recursive"
38
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Embedding function
42
+ # ---------------------------------------------------------------------------
43
+
44
+ def _get_embedding_fn():
45
+ return OpenAIEmbeddingFunction(
46
+ api_key=OPENAI_API_KEY,
47
+ model_name=EMBED_MODEL,
48
+ )
49
+
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # ChromaDB helpers
53
+ # ---------------------------------------------------------------------------
54
+
55
+ def _get_collection(username: str, notebook_id: str):
56
+ chroma_path = storage.get_chroma_path(username, notebook_id)
57
+ client = chromadb.PersistentClient(path=chroma_path)
58
+ collection = client.get_or_create_collection(
59
+ name="sources",
60
+ embedding_function=_get_embedding_fn(),
61
+ metadata={"hnsw:space": "cosine"},
62
+ )
63
+ return collection
64
+
65
+
66
+ # ---------------------------------------------------------------------------
67
+ # Text extraction
68
+ # ---------------------------------------------------------------------------
69
+
70
+ def extract_text_from_pdf(file_path: str | Path) -> str:
71
+ """Extract text from a PDF using pdfplumber."""
72
+ import pdfplumber
73
+ texts = []
74
+ with pdfplumber.open(str(file_path)) as pdf:
75
+ for page in pdf.pages:
76
+ t = page.extract_text()
77
+ if t:
78
+ texts.append(t)
79
+ return "\n\n".join(texts)
80
+
81
+
82
+ def extract_text_from_pptx(file_path: str | Path) -> str:
83
+ """Extract text from a PowerPoint file."""
84
+ from pptx import Presentation
85
+ prs = Presentation(str(file_path))
86
+ texts = []
87
+ for slide_num, slide in enumerate(prs.slides, start=1):
88
+ slide_texts = [f"[Slide {slide_num}]"]
89
+ for shape in slide.shapes:
90
+ if shape.has_text_frame:
91
+ for para in shape.text_frame.paragraphs:
92
+ line = para.text.strip()
93
+ if line:
94
+ slide_texts.append(line)
95
+ texts.append("\n".join(slide_texts))
96
+ return "\n\n".join(texts)
97
+
98
+
99
+ def extract_text_from_url(url: str) -> str:
100
+ """Extract readable text from a web URL using trafilatura."""
101
+ import trafilatura
102
+ downloaded = trafilatura.fetch_url(url)
103
+ if downloaded is None:
104
+ raise ValueError(f"Could not fetch URL: {url}")
105
+ text = trafilatura.extract(downloaded, include_links=False, include_tables=True)
106
+ if not text:
107
+ raise ValueError(f"No readable text found at URL: {url}")
108
+ return text
109
+
110
+
111
+ def extract_text(source: str | Path) -> tuple[str, str]:
112
+ """
113
+ Dispatch extraction based on source type.
114
+ Returns (text, source_name).
115
+ """
116
+ src = str(source)
117
+ parsed = urlparse(src)
118
+ if parsed.scheme in ("http", "https"):
119
+ text = extract_text_from_url(src)
120
+ name = parsed.netloc + parsed.path.replace("/", "_")
121
+ return text, name
122
+
123
+ p = Path(src)
124
+ suffix = p.suffix.lower()
125
+ if suffix == ".pdf":
126
+ return extract_text_from_pdf(p), p.name
127
+ elif suffix in (".pptx", ".ppt"):
128
+ return extract_text_from_pptx(p), p.name
129
+ elif suffix in (".txt", ".md"):
130
+ return p.read_text(encoding="utf-8", errors="ignore"), p.name
131
+ else:
132
+ raise ValueError(f"Unsupported file type: {suffix}")
133
+
134
+
135
+ # ---------------------------------------------------------------------------
136
+ # Chunking strategies
137
+ # ---------------------------------------------------------------------------
138
+
139
+ def _fixed_chunks(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> list[str]:
140
+ """Split on character count with overlap."""
141
+ chunks, start = [], 0
142
+ while start < len(text):
143
+ end = start + size
144
+ chunks.append(text[start:end])
145
+ start += size - overlap
146
+ return [c.strip() for c in chunks if c.strip()]
147
+
148
+
149
+ def _sentence_chunks(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> list[str]:
150
+ """Split on sentence boundaries, then group into windows."""
151
+ sentences = re.split(r'(?<=[.!?])\s+', text)
152
+ chunks, current, current_len = [], [], 0
153
+ for sent in sentences:
154
+ slen = len(sent)
155
+ if current_len + slen > size and current:
156
+ chunks.append(" ".join(current))
157
+ # keep overlap sentences
158
+ overlap_sents = []
159
+ ol = 0
160
+ for s in reversed(current):
161
+ ol += len(s)
162
+ overlap_sents.insert(0, s)
163
+ if ol >= overlap:
164
+ break
165
+ current = overlap_sents
166
+ current_len = sum(len(s) for s in current)
167
+ current.append(sent)
168
+ current_len += slen
169
+ if current:
170
+ chunks.append(" ".join(current))
171
+ return [c.strip() for c in chunks if c.strip()]
172
+
173
+
174
+ def _recursive_chunks(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> list[str]:
175
+ """
176
+ Recursive character splitter — tries paragraph, then sentence,
177
+ then word boundaries before hard-splitting.
178
+ """
179
+ separators = ["\n\n", "\n", ". ", " ", ""]
180
+
181
+ def _split(t: str, seps: list[str]) -> list[str]:
182
+ if len(t) <= size:
183
+ return [t] if t.strip() else []
184
+ if not seps:
185
+ return _fixed_chunks(t, size, overlap)
186
+
187
+ sep = seps[0]
188
+ parts = t.split(sep)
189
+ chunks, current = [], ""
190
+ for part in parts:
191
+ candidate = current + (sep if current else "") + part
192
+ if len(candidate) <= size:
193
+ current = candidate
194
+ else:
195
+ if current:
196
+ chunks.extend(_split(current, seps[1:]))
197
+ current = part
198
+ if current:
199
+ chunks.extend(_split(current, seps[1:]))
200
+ return chunks
201
+
202
+ raw = _split(text, separators)
203
+ # Add overlap between adjacent chunks
204
+ result = []
205
+ for i, chunk in enumerate(raw):
206
+ if i > 0 and overlap > 0:
207
+ prev_tail = raw[i - 1][-overlap:]
208
+ chunk = prev_tail + " " + chunk
209
+ result.append(chunk.strip())
210
+ return [c for c in result if c]
211
+
212
+
213
+ def chunk_text(text: str, strategy: ChunkStrategy = DEFAULT_CHUNK_STRATEGY) -> list[str]:
214
+ if strategy == "fixed":
215
+ return _fixed_chunks(text)
216
+ elif strategy == "sentence":
217
+ return _sentence_chunks(text)
218
+ else:
219
+ return _recursive_chunks(text)
220
+
221
+
222
+ # ---------------------------------------------------------------------------
223
+ # Main ingest function
224
+ # ---------------------------------------------------------------------------
225
+
226
+ def ingest_source(
227
+ username: str,
228
+ notebook_id: str,
229
+ source: str | Path,
230
+ chunk_strategy: ChunkStrategy = DEFAULT_CHUNK_STRATEGY,
231
+ raw_bytes: Optional[bytes] = None,
232
+ ) -> dict:
233
+ """
234
+ Full ingestion pipeline for one source.
235
+ Returns a summary dict with stats.
236
+ """
237
+ # 1. Extract text
238
+ text, source_name = extract_text(source)
239
+
240
+ # 2. Persist raw file (if bytes provided, i.e. an upload)
241
+ if raw_bytes is not None:
242
+ storage.save_raw_file(username, notebook_id, source_name, raw_bytes)
243
+
244
+ # 3. Persist extracted text
245
+ storage.save_extracted_text(username, notebook_id, source_name, text)
246
+
247
+ # 4. Chunk
248
+ chunks = chunk_text(text, strategy=chunk_strategy)
249
+
250
+ # 5. Build IDs and metadata
251
+ ids, documents, metadatas = [], [], []
252
+ for i, chunk in enumerate(chunks):
253
+ chunk_id = hashlib.md5(f"{source_name}_{i}_{chunk[:40]}".encode()).hexdigest()
254
+ ids.append(chunk_id)
255
+ documents.append(chunk)
256
+ metadatas.append({
257
+ "source": source_name,
258
+ "chunk_index": i,
259
+ "total_chunks": len(chunks),
260
+ "strategy": chunk_strategy,
261
+ })
262
+
263
+ # 6. Upsert into ChromaDB
264
+ collection = _get_collection(username, notebook_id)
265
+ # Batch upsert in groups of 100 to avoid request-size limits
266
+ batch_size = 100
267
+ for start in range(0, len(ids), batch_size):
268
+ end = start + batch_size
269
+ collection.upsert(
270
+ ids=ids[start:end],
271
+ documents=documents[start:end],
272
+ metadatas=metadatas[start:end],
273
+ )
274
+
275
+ return {
276
+ "source_name": source_name,
277
+ "char_count": len(text),
278
+ "chunk_count": len(chunks),
279
+ "strategy": chunk_strategy,
280
+ }
281
+
282
+
283
+ def delete_source(username: str, notebook_id: str, source_name: str) -> int:
284
+ """Remove all chunks for a source from the vector store. Returns deleted count."""
285
+ collection = _get_collection(username, notebook_id)
286
+ results = collection.get(where={"source": source_name})
287
+ if results and results["ids"]:
288
+ collection.delete(ids=results["ids"])
289
+ return len(results["ids"])
290
+ return 0
291
+
292
+
293
+ def list_indexed_sources(username: str, notebook_id: str) -> list[str]:
294
+ """Return unique source names currently indexed in ChromaDB."""
295
+ collection = _get_collection(username, notebook_id)
296
+ results = collection.get(include=["metadatas"])
297
+ sources = {m["source"] for m in results["metadatas"]} if results["metadatas"] else set()
298
+ return sorted(sources)
data/.env.example DELETED
@@ -1,2 +0,0 @@
1
- # .env
2
- OPENAI_API_KEY=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