Yashikaysn29 commited on
Commit
18f908a
·
verified ·
1 Parent(s): 6888757

Upload folder using huggingface_hub

Browse files
Files changed (7) hide show
  1. Dockerfile +10 -0
  2. README.md +22 -4
  3. app.py +466 -0
  4. requirements.txt +10 -0
  5. static/index.html +203 -0
  6. static/script.js +292 -0
  7. static/style.css +164 -0
Dockerfile ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+ WORKDIR /app
3
+ RUN apt-get update && apt-get install -y --no-install-recommends \
4
+ libglib2.0-0 libsm6 libxext6 libxrender1 libgl1 git \
5
+ && rm -rf /var/lib/apt/lists/*
6
+ COPY requirements.txt .
7
+ RUN pip install --no-cache-dir -r requirements.txt
8
+ COPY . .
9
+ EXPOSE 7860
10
+ CMD ["python", "app.py"]
README.md CHANGED
@@ -1,10 +1,28 @@
1
  ---
2
  title: Cortex
3
- emoji: 🐢
4
- colorFrom: blue
5
- colorTo: purple
6
  sdk: docker
 
7
  pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Cortex
3
+ emoji: 🧠
4
+ colorFrom: yellow
5
+ colorTo: red
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
  ---
10
 
11
+ # Cortex Multimodal Knowledge Intelligence
12
+
13
+ Upload PDFs, images, videos, and text files — ask questions across all of them.
14
+
15
+ ## Features
16
+ - **Multimodal ingestion** — PDF, images, video frames, plain text
17
+ - **Semantic search** — sentence-transformers + FAISS vector index
18
+ - **Q&A with citations** — Claude API answers with source + page references
19
+ - **Auto summaries** — per-file summaries and entity extraction on upload
20
+ - **Cross-document connections** — Claude finds relationships between files
21
+
22
+ ## Stack
23
+ - Backend: FastAPI + sentence-transformers + FAISS + PyMuPDF + OpenCV
24
+ - LLM: Claude API (claude-sonnet-4-6)
25
+ - Frontend: Custom HTML/CSS/JS (earthy professional design)
26
+ - Deployment: Docker Space on Hugging Face
27
+
28
+ Built by Yashika Saxena · B.Tech AI & ML · ITM Gwalior · 2023–2027
app.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, io, base64, time, json, re
2
+ from pathlib import Path
3
+ from typing import List, Optional
4
+ import numpy as np
5
+
6
+ from fastapi import FastAPI, UploadFile, File, Form, HTTPException
7
+ from fastapi.staticfiles import StaticFiles
8
+ from fastapi.responses import FileResponse, JSONResponse
9
+ from groq import Groq
10
+
11
+ # ── Optional heavy deps (graceful fallback) ───────────────────────
12
+ try:
13
+ import fitz # PyMuPDF
14
+ HAS_FITZ = True
15
+ except ImportError:
16
+ HAS_FITZ = False
17
+
18
+ try:
19
+ from sentence_transformers import SentenceTransformer
20
+ import faiss
21
+ embedder = SentenceTransformer("all-MiniLM-L6-v2")
22
+ HAS_EMBEDDER = True
23
+ except ImportError:
24
+ HAS_EMBEDDER = False
25
+
26
+ try:
27
+ import cv2
28
+ HAS_CV2 = True
29
+ except ImportError:
30
+ HAS_CV2 = False
31
+
32
+ from PIL import Image
33
+
34
+ # ── In-memory knowledge base ──────────────────────────────────────
35
+ KB = {
36
+ "files": {}, # filename -> {type, summary, entities, chunks, thumb_b64}
37
+ "chunks": [], # [{text, source, page, embedding}]
38
+ "index": None, # FAISS index
39
+ }
40
+
41
+ CHUNK_SIZE = 600 # words per chunk
42
+ CHUNK_OVERLAP = 80
43
+
44
+ # ── Helpers ───────────────────────────────────────────────────────
45
+ def chunk_text(text: str, source: str, page: int = 0) -> List[dict]:
46
+ words = text.split()
47
+ chunks = []
48
+ for i in range(0, len(words), CHUNK_SIZE - CHUNK_OVERLAP):
49
+ chunk = " ".join(words[i:i + CHUNK_SIZE])
50
+ if chunk.strip():
51
+ chunks.append({"text": chunk, "source": source, "page": page})
52
+ return chunks
53
+
54
+ def embed_chunks(chunks: List[dict]) -> np.ndarray:
55
+ if not HAS_EMBEDDER:
56
+ return np.random.rand(len(chunks), 384).astype("float32")
57
+ texts = [c["text"] for c in chunks]
58
+ return embedder.encode(texts, convert_to_numpy=True).astype("float32")
59
+
60
+ def rebuild_index():
61
+ if not KB["chunks"]:
62
+ KB["index"] = None
63
+ return
64
+ vecs = np.array([c["embedding"] for c in KB["chunks"]], dtype="float32")
65
+ dim = vecs.shape[1]
66
+ if HAS_EMBEDDER:
67
+ index = faiss.IndexFlatIP(dim)
68
+ faiss.normalize_L2(vecs)
69
+ index.add(vecs)
70
+ KB["index"] = index
71
+ else:
72
+ KB["index"] = None
73
+
74
+ def retrieve(query: str, top_k: int = 8) -> List[dict]:
75
+ if not KB["chunks"]:
76
+ return []
77
+
78
+ # Vector search if available
79
+ vector_results = []
80
+ if KB["index"] is not None and HAS_EMBEDDER:
81
+ q_vec = embedder.encode([query], convert_to_numpy=True).astype("float32")
82
+ faiss.normalize_L2(q_vec)
83
+ _, indices = KB["index"].search(q_vec, min(top_k, len(KB["chunks"])))
84
+ vector_results = [KB["chunks"][i] for i in indices[0] if i < len(KB["chunks"])]
85
+
86
+ # Keyword fallback — always run to catch what vector search misses
87
+ query_words = set(query.lower().split())
88
+ keyword_results = []
89
+ for chunk in KB["chunks"]:
90
+ chunk_lower = chunk["text"].lower()
91
+ # score by how many query words appear in chunk
92
+ score = sum(1 for w in query_words if len(w) > 3 and w in chunk_lower)
93
+ if score > 0:
94
+ keyword_results.append((score, chunk))
95
+ keyword_results.sort(key=lambda x: x[0], reverse=True)
96
+ keyword_chunks = [c for _, c in keyword_results[:top_k]]
97
+
98
+ # Merge — deduplicate by text, prioritize vector results
99
+ seen = set()
100
+ merged = []
101
+ for chunk in vector_results + keyword_chunks:
102
+ key = chunk["text"][:100]
103
+ if key not in seen:
104
+ seen.add(key)
105
+ merged.append(chunk)
106
+
107
+ return merged[:top_k + 4] # return a few extra for better coverage
108
+
109
+ def pil_to_b64(pil_img, max_size=1024) -> str:
110
+ img = pil_img.copy()
111
+ img.thumbnail((max_size, max_size), Image.LANCZOS)
112
+ buf = io.BytesIO()
113
+ img.save(buf, format="JPEG", quality=85)
114
+ return base64.b64encode(buf.getvalue()).decode()
115
+
116
+ def claude_client(api_key: str):
117
+ return Groq(api_key=api_key)
118
+
119
+ def claude_vision(client, b64_img: str, prompt: str) -> str:
120
+ msg = client.chat.completions.create(
121
+ model="meta-llama/llama-4-scout-17b-16e-instruct",
122
+ max_tokens=1000,
123
+ messages=[{"role": "user", "content": [
124
+ {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_img}"}},
125
+ {"type": "text", "text": prompt}
126
+ ]}]
127
+ )
128
+ return msg.choices[0].message.content
129
+
130
+ def claude_text(client, prompt: str) -> str:
131
+ msg = client.chat.completions.create(
132
+ model="llama-3.3-70b-versatile",
133
+ max_tokens=1500,
134
+ messages=[{"role": "user", "content": prompt}]
135
+ )
136
+ return msg.choices[0].message.content
137
+
138
+ # ── File processors ───────────────────────────────────────────────
139
+ def process_pdf(raw: bytes, filename: str, client) -> dict:
140
+ chunks = []
141
+ thumb_b64 = None
142
+ if not HAS_FITZ:
143
+ return {"chunks": [{"text": "PDF processing unavailable (PyMuPDF not installed)", "source": filename, "page": 0}], "thumb_b64": None, "raw_text": ""}
144
+ doc = fitz.open(stream=raw, filetype="pdf")
145
+ full_text = ""
146
+ for page_num, page in enumerate(doc):
147
+ # extract text with better layout preservation
148
+ text = page.get_text("text")
149
+ if not text.strip():
150
+ # try blocks mode for scanned/structured PDFs
151
+ text = page.get_text("blocks")
152
+ if isinstance(text, list):
153
+ text = "\n".join([b[4] for b in text if len(b) > 4 and isinstance(b[4], str)])
154
+ full_text += f"\n[Page {page_num + 1}]\n{text}"
155
+ page_chunks = chunk_text(text, filename, page_num + 1)
156
+ chunks.extend(page_chunks)
157
+ if page_num == 0:
158
+ pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
159
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
160
+ thumb_b64 = pil_to_b64(img, 300)
161
+ # store up to 80000 chars for large multi-section documents
162
+ return {"chunks": chunks, "thumb_b64": thumb_b64, "raw_text": full_text[:80000]}
163
+
164
+ def process_image(raw: bytes, filename: str, client) -> dict:
165
+ pil_img = Image.open(io.BytesIO(raw)).convert("RGB")
166
+ b64 = pil_to_b64(pil_img)
167
+ thumb_b64 = pil_to_b64(pil_img, 300)
168
+ description = claude_vision(client, b64, "Describe this image in detail. Extract any text visible. Note objects, people, scenes, data, charts, or diagrams present.")
169
+ chunks = chunk_text(description, filename, 0)
170
+ return {"chunks": chunks, "thumb_b64": thumb_b64, "raw_text": description[:5000]}
171
+
172
+ def process_video(raw: bytes, filename: str, client) -> dict:
173
+ if not HAS_CV2:
174
+ return {"chunks": [{"text": "Video processing unavailable", "source": filename, "page": 0}], "thumb_b64": None, "raw_text": ""}
175
+ import tempfile
176
+ suffix = Path(filename).suffix or ".mp4"
177
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
178
+ tmp.write(raw)
179
+ tmp_path = tmp.name
180
+ try:
181
+ cap = cv2.VideoCapture(tmp_path)
182
+ total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
183
+ sample_at = np.linspace(0, max(total - 1, 0), min(6, total), dtype=int)
184
+ descriptions = []
185
+ thumb_b64 = None
186
+ for i, idx in enumerate(sample_at):
187
+ cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
188
+ ret, frame = cap.read()
189
+ if not ret:
190
+ continue
191
+ pil_img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
192
+ b64 = pil_to_b64(pil_img)
193
+ if i == 0:
194
+ thumb_b64 = pil_to_b64(pil_img, 300)
195
+ desc = claude_vision(client, b64, f"Frame {i+1} of a video. Describe what's happening. Note any text, people, objects, or key events.")
196
+ descriptions.append(f"[Frame {i+1}] {desc}")
197
+ cap.release()
198
+ os.unlink(tmp_path)
199
+ full_text = "\n\n".join(descriptions)
200
+ chunks = chunk_text(full_text, filename, 0)
201
+ return {"chunks": chunks, "thumb_b64": thumb_b64, "raw_text": full_text[:5000]}
202
+ except Exception as e:
203
+ os.unlink(tmp_path)
204
+ raise e
205
+
206
+ def process_text(raw: bytes, filename: str) -> dict:
207
+ text = raw.decode("utf-8", errors="ignore")
208
+ chunks = chunk_text(text, filename, 0)
209
+ return {"chunks": chunks, "thumb_b64": None, "raw_text": text[:5000]}
210
+
211
+ def summarize_section(client, section_text: str, section_label: str) -> str:
212
+ """Summarize a single section/batch of text."""
213
+ prompt = f"""Summarize this section of a document ({section_label}) in 3-4 sentences.
214
+ Capture all distinct topics, subjects, or subsections mentioned. Be specific, not generic.
215
+
216
+ Text:
217
+ {section_text}"""
218
+ try:
219
+ return claude_text(client, prompt)
220
+ except Exception as e:
221
+ return f"[Could not summarize this section: {e}]"
222
+
223
+ def generate_summary_and_entities(client, raw_text: str, filename: str) -> dict:
224
+ BATCH_SIZE = 15000 # chars per batch, safely under token limits
225
+
226
+ if len(raw_text) <= BATCH_SIZE:
227
+ # Short document — single pass
228
+ content = raw_text
229
+ combined_summary_input = content
230
+ else:
231
+ # Long document — map-reduce: summarize each batch, then combine
232
+ batches = [raw_text[i:i + BATCH_SIZE] for i in range(0, len(raw_text), BATCH_SIZE)]
233
+ section_summaries = []
234
+ for idx, batch in enumerate(batches):
235
+ label = f"part {idx + 1} of {len(batches)}"
236
+ s = summarize_section(client, batch, label)
237
+ section_summaries.append(f"[{label}]: {s}")
238
+ combined_summary_input = "\n\n".join(section_summaries)
239
+
240
+ prompt = f"""Based on the following content (or section summaries) from "{filename}", produce a complete analysis.
241
+ This document may cover MULTIPLE topics/sections/subjects — make sure your output covers ALL of them, not just the first part.
242
+
243
+ Respond in JSON only (no markdown):
244
+ {{
245
+ "summary": "Detailed 5-8 sentence summary that covers ALL major sections/subjects/topics found in the document",
246
+ "key_entities": ["entity1", "entity2", ...up to 20 entities, covering the whole document],
247
+ "topics": ["topic1", "topic2", ...up to 10 topics covering the full scope],
248
+ "file_type_detected": "what kind of document this is",
249
+ "key_sections": ["list ALL section/chapter/subject titles found in the document"],
250
+ "important_facts": ["fact1", "fact2", ...up to 10 specific facts, drawn from across the ENTIRE document"]
251
+ }}
252
+
253
+ Content:
254
+ {combined_summary_input[:14000]}"""
255
+ try:
256
+ result = claude_text(client, prompt)
257
+ clean = result.strip()
258
+ if clean.startswith("```"):
259
+ clean = re.sub(r"```(?:json)?", "", clean).strip().rstrip("`").strip()
260
+ return json.loads(clean)
261
+ except Exception:
262
+ return {"summary": "Could not generate summary.", "key_entities": [], "topics": [], "file_type_detected": "unknown"}
263
+
264
+ def find_connections(client) -> List[dict]:
265
+ if len(KB["files"]) < 2:
266
+ return []
267
+ summaries = "\n".join([f"- {name}: {info.get('summary','')}" for name, info in KB["files"].items()])
268
+ prompt = f"""Given these documents in a knowledge base, find meaningful connections between them.
269
+ Respond in JSON only (no markdown):
270
+ [{{"doc1": "filename1", "doc2": "filename2", "connection": "brief description of how they relate"}}]
271
+
272
+ Documents:
273
+ {summaries}"""
274
+ try:
275
+ result = claude_text(client, prompt)
276
+ clean = result.strip()
277
+ if clean.startswith("```"):
278
+ clean = re.sub(r"```(?:json)?", "", clean).strip().rstrip("`").strip()
279
+ return json.loads(clean)
280
+ except Exception:
281
+ return []
282
+
283
+ # ── FastAPI ───────────────────────────────────────────────────────
284
+ app = FastAPI(title="Cortex API")
285
+
286
+ @app.post("/api/upload")
287
+ async def upload(
288
+ file: UploadFile = File(...),
289
+ api_key: str = Form(...)
290
+ ):
291
+ if not api_key.strip():
292
+ raise HTTPException(400, "API key required")
293
+ raw = await file.read()
294
+ filename = file.filename or "upload"
295
+ ext = Path(filename).suffix.lower()
296
+ client = claude_client(api_key)
297
+
298
+ try:
299
+ if ext == ".pdf":
300
+ result = process_pdf(raw, filename, client)
301
+ ftype = "pdf"
302
+ elif ext in {".jpg", ".jpeg", ".png", ".webp", ".gif"}:
303
+ result = process_image(raw, filename, client)
304
+ ftype = "image"
305
+ elif ext in {".mp4", ".mov", ".avi", ".mkv", ".webm"}:
306
+ result = process_video(raw, filename, client)
307
+ ftype = "video"
308
+ else:
309
+ result = process_text(raw, filename)
310
+ ftype = "text"
311
+
312
+ meta = generate_summary_and_entities(client, result["raw_text"], filename)
313
+ chunks = result["chunks"]
314
+ if chunks and HAS_EMBEDDER:
315
+ vecs = embed_chunks(chunks)
316
+ for i, c in enumerate(chunks):
317
+ c["embedding"] = vecs[i].tolist()
318
+ else:
319
+ for c in chunks:
320
+ c["embedding"] = [0.0] * 384
321
+
322
+ KB["files"][filename] = {
323
+ "type": ftype,
324
+ "summary": meta.get("summary", ""),
325
+ "entities": meta.get("key_entities", []),
326
+ "topics": meta.get("topics", []),
327
+ "key_sections": meta.get("key_sections", []),
328
+ "important_facts": meta.get("important_facts", []),
329
+ "file_type_detected": meta.get("file_type_detected", ""),
330
+ "chunk_count": len(chunks),
331
+ "thumb_b64": result.get("thumb_b64"),
332
+ "preview": result.get("raw_text", "")[:5000],
333
+ }
334
+ old_chunks = [c for c in KB["chunks"] if c["source"] != filename]
335
+ for c in chunks:
336
+ c["embedding"] = np.array(c["embedding"], dtype="float32")
337
+ KB["chunks"] = old_chunks + chunks
338
+ rebuild_index()
339
+
340
+ connections = find_connections(client)
341
+
342
+ return JSONResponse({
343
+ "filename": filename,
344
+ "type": ftype,
345
+ "summary": meta.get("summary", ""),
346
+ "entities": meta.get("key_entities", []),
347
+ "topics": meta.get("topics", []),
348
+ "key_sections": meta.get("key_sections", []),
349
+ "important_facts": meta.get("important_facts", []),
350
+ "chunk_count": len(chunks),
351
+ "total_chunks": len(KB["chunks"]),
352
+ "connections": connections,
353
+ "thumb_b64": result.get("thumb_b64"),
354
+ "preview": result.get("raw_text", "")[:5000],
355
+ })
356
+ except Exception as e:
357
+ err = str(e)
358
+ if "401" in err or "invalid_api_key" in err or "auth" in err.lower():
359
+ raise HTTPException(401, "Invalid API key")
360
+ raise HTTPException(500, err)
361
+
362
+
363
+ @app.post("/api/ask")
364
+ async def ask(query: str = Form(...), api_key: str = Form(...)):
365
+ if not api_key.strip():
366
+ raise HTTPException(400, "API key required")
367
+ if not KB["chunks"]:
368
+ raise HTTPException(400, "No documents indexed yet")
369
+ client = claude_client(api_key)
370
+
371
+ # Detect broad "list all / summarize everything" queries
372
+ broad_keywords = ["list all", "all subjects", "all topics", "all courses", "all codes",
373
+ "all units", "every subject", "complete list", "full list", "what are all",
374
+ "how many", "entire", "overview", "syllabus contains", "subjects in"]
375
+ query_lower = query.lower()
376
+ is_broad = any(kw in query_lower for kw in broad_keywords)
377
+
378
+ if is_broad:
379
+ # For broad queries: use file summaries + first chunk of each page
380
+ # This gives a document-wide view without blowing token limits
381
+ summary_context = []
382
+ for fname, finfo in KB["files"].items():
383
+ summary_context.append(
384
+ f"[FILE: {fname}]\n"
385
+ f"Summary: {finfo.get('summary','')}\n"
386
+ f"Key Sections: {', '.join(finfo.get('key_sections', []))}\n"
387
+ f"Topics: {', '.join(finfo.get('topics', []))}\n"
388
+ f"Entities: {', '.join(finfo.get('key_entities', finfo.get('entities', [])))}"
389
+ )
390
+ # Also grab first chunk from every unique page for full coverage
391
+ seen_pages = set()
392
+ page_chunks = []
393
+ for c in KB["chunks"]:
394
+ key = (c["source"], c.get("page", 0))
395
+ if key not in seen_pages:
396
+ seen_pages.add(key)
397
+ page_chunks.append(f"[{c['source']} p.{c.get('page',0)}] {c['text'][:300]}")
398
+ context = "\n\n".join(summary_context) + "\n\nPER-PAGE EXCERPTS:\n" + "\n".join(page_chunks[:30])
399
+ source_file = list(KB["files"].keys())[0] if KB["files"] else "document"
400
+ source_hint = [{"file": source_file, "page": 0}]
401
+ else:
402
+ # For specific queries: use hybrid vector + keyword retrieval
403
+ relevant = retrieve(query, top_k=10)
404
+ context_parts = []
405
+ for c in relevant[:10]:
406
+ text = c["text"][:800]
407
+ context_parts.append(f"[Source: {c['source']}, Page: {c.get('page',0)}]\n{text}")
408
+ context = "\n\n".join(context_parts)
409
+ source_hint = [{"file": c["source"], "page": c.get("page", 0)} for c in relevant[:3]]
410
+
411
+ prompt = f"""You are Cortex, an intelligent document assistant. Answer the question using the provided context.
412
+ Be specific, complete and detailed. If the question asks to "list all" something, make sure you include EVERY item found across ALL pages.
413
+ Extract exact names, codes, titles from the context — do not summarize or omit items.
414
+ Only say "not found" if truly absent after checking all context.
415
+
416
+ Context:
417
+ {context[:6000]}
418
+
419
+ Question: {query}
420
+
421
+ Respond in JSON only (no markdown backticks):
422
+ {{"answer": "complete detailed answer here", "sources": [{{"file": "filename", "page": 0}}], "confidence": "high/medium/low"}}"""
423
+ try:
424
+ result = claude_text(client, prompt)
425
+ clean = result.strip()
426
+ if clean.startswith("```"):
427
+ clean = re.sub(r"```(?:json)?", "", clean).strip().rstrip("`").strip()
428
+ data = json.loads(clean)
429
+ return JSONResponse(data)
430
+ except Exception as e:
431
+ return JSONResponse({"answer": f"Error: {str(e)}", "sources": [], "confidence": "low"})
432
+
433
+ @app.get("/api/status")
434
+ async def status():
435
+ return JSONResponse({
436
+ "files": {k: {**v, "thumb_b64": None} for k, v in KB["files"].items()},
437
+ "total_chunks": len(KB["chunks"]),
438
+ "file_count": len(KB["files"]),
439
+ })
440
+
441
+ @app.post("/api/connections")
442
+ async def connections(api_key: str = Form(...)):
443
+ if not api_key.strip():
444
+ raise HTTPException(400, "API key required")
445
+ client = claude_client(api_key)
446
+ result = find_connections(client)
447
+ return JSONResponse({"connections": result})
448
+
449
+ @app.delete("/api/file/{filename}")
450
+ async def delete_file(filename: str):
451
+ if filename in KB["files"]:
452
+ del KB["files"][filename]
453
+ KB["chunks"] = [c for c in KB["chunks"] if c["source"] != filename]
454
+ rebuild_index()
455
+ return JSONResponse({"ok": True})
456
+
457
+ STATIC_DIR = Path(__file__).parent / "static"
458
+ app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
459
+
460
+ @app.get("/")
461
+ async def root():
462
+ return FileResponse(str(STATIC_DIR / "index.html"))
463
+
464
+ if __name__ == "__main__":
465
+ import uvicorn
466
+ uvicorn.run(app, host="0.0.0.0", port=7860)
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn[standard]
3
+ python-multipart
4
+ groq
5
+ sentence-transformers
6
+ faiss-cpu
7
+ pymupdf
8
+ opencv-python-headless
9
+ numpy
10
+ pillow
static/index.html ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8"/>
5
+ <meta name="viewport" content="width=device-width,initial-scale=1.0"/>
6
+ <title>Cortex — Multimodal Knowledge Intelligence</title>
7
+ <link rel="stylesheet" href="/static/style.css"/>
8
+ </head>
9
+ <body>
10
+ <div class="app">
11
+
12
+ <aside class="sidebar">
13
+ <div class="logo">Cor<span>tex</span></div>
14
+
15
+ <div class="nav-label">Workspace</div>
16
+ <div class="nav-item active" data-page="knowledge"><i class="ti ti-brain" aria-hidden="true"></i>Knowledge Base</div>
17
+ <div class="nav-item" data-page="ask"><i class="ti ti-message-question" aria-hidden="true"></i>Ask Anything</div>
18
+ <div class="nav-item" data-page="summaries"><i class="ti ti-file-text" aria-hidden="true"></i>Summaries</div>
19
+ <div class="nav-item" data-page="connections"><i class="ti ti-topology-star" aria-hidden="true"></i>Connections</div>
20
+
21
+ <div class="nav-label">Files</div>
22
+ <div id="sidebar-files"></div>
23
+
24
+ <div class="sidebar-footer">
25
+ <div class="api-key-box">
26
+ <div class="api-key-label">Groq API Key</div>
27
+ <input class="api-key-input" type="password" id="apiKeyInput" placeholder="gsk_..."/>
28
+ </div>
29
+ </div>
30
+ </aside>
31
+
32
+ <main class="main">
33
+
34
+ <!-- KNOWLEDGE BASE -->
35
+ <div class="page active" id="page-knowledge">
36
+ <div class="page-header">
37
+ <h1>Knowledge Base</h1>
38
+ <p>Upload files across any format — Cortex reads, indexes and connects them intelligently</p>
39
+ </div>
40
+
41
+ <div class="stats-row">
42
+ <div class="stat-card">
43
+ <div class="stat-label">Documents</div>
44
+ <div class="stat-value" id="stat-docs">0</div>
45
+ <div class="stat-sub">indexed & ready</div>
46
+ </div>
47
+ <div class="stat-card">
48
+ <div class="stat-label">Chunks</div>
49
+ <div class="stat-value" id="stat-chunks">0</div>
50
+ <div class="stat-sub">vector embeddings</div>
51
+ </div>
52
+ <div class="stat-card">
53
+ <div class="stat-label">File Types</div>
54
+ <div class="stat-value" id="stat-types">—</div>
55
+ <div class="stat-sub">in knowledge base</div>
56
+ </div>
57
+ </div>
58
+
59
+ <div class="card">
60
+ <div class="upload-zone" id="uploadZone">
61
+ <div class="upload-icon"><i class="ti ti-cloud-upload" aria-hidden="true"></i></div>
62
+ <h3>Drop files to expand your knowledge base</h3>
63
+ <div class="hint">Cortex understands all of these natively</div>
64
+ <div class="file-types">
65
+ <span class="badge">PDF</span>
66
+ <span class="badge">Images</span>
67
+ <span class="badge">Video</span>
68
+ <span class="badge">TXT</span>
69
+ <span class="badge">MD</span>
70
+ </div>
71
+ <input type="file" id="fileInput" accept=".pdf,.jpg,.jpeg,.png,.webp,.gif,.mp4,.mov,.avi,.mkv,.webm,.txt,.md"/>
72
+ </div>
73
+ <div class="status-bar" id="uploadStatus"></div>
74
+ </div>
75
+
76
+ <div id="files-grid-wrap">
77
+ <div class="card-label" style="margin-bottom:10px;">Indexed Files</div>
78
+ <div class="files-grid" id="filesGrid">
79
+ <div class="empty-state" style="grid-column:1/-1;">
80
+ <i class="ti ti-inbox" aria-hidden="true"></i>
81
+ <p>No files yet — upload something to get started</p>
82
+ </div>
83
+ </div>
84
+ </div>
85
+ </div>
86
+
87
+ <!-- ASK ANYTHING -->
88
+ <div class="page" id="page-ask">
89
+ <div class="page-header">
90
+ <h1>Ask Anything</h1>
91
+ <p>Ask questions across all your documents — Cortex finds the answer and cites its sources</p>
92
+ </div>
93
+
94
+ <div class="card">
95
+ <div class="card-label">Question</div>
96
+ <div class="query-row">
97
+ <input class="query-input" type="text" id="queryInput" placeholder="What are the key findings? Summarize the main argument. Compare the two documents..."/>
98
+ <button class="btn btn-dark" id="askBtn" disabled><i class="ti ti-arrow-right" aria-hidden="true"></i>Ask</button>
99
+ </div>
100
+ <div class="chat-history" id="chatHistory" style="margin-top:16px;display:none;"></div>
101
+ </div>
102
+
103
+ <div class="card" id="suggestionsCard">
104
+ <div class="card-label">Try asking</div>
105
+ <div style="display:flex;flex-wrap:wrap;gap:7px;">
106
+ <button class="btn btn-outline btn-sm" onclick="setQuery(this)">What are the main topics covered?</button>
107
+ <button class="btn btn-outline btn-sm" onclick="setQuery(this)">Summarize the key findings</button>
108
+ <button class="btn btn-outline btn-sm" onclick="setQuery(this)">What entities are mentioned most?</button>
109
+ <button class="btn btn-outline btn-sm" onclick="setQuery(this)">What connections exist between documents?</button>
110
+ <button class="btn btn-outline btn-sm" onclick="setQuery(this)">What are the action items?</button>
111
+ </div>
112
+ </div>
113
+ </div>
114
+
115
+ <!-- SUMMARIES -->
116
+ <div class="page" id="page-summaries">
117
+ <div class="page-header">
118
+ <h1>Summaries</h1>
119
+ <p>Auto-generated intelligence for each file in your knowledge base</p>
120
+ </div>
121
+ <div class="summary-list" id="summaryList">
122
+ <div class="empty-state">
123
+ <i class="ti ti-file-text" aria-hidden="true"></i>
124
+ <p>Upload files to see auto-generated summaries and entities</p>
125
+ </div>
126
+ </div>
127
+ </div>
128
+
129
+ <!-- CONNECTIONS -->
130
+ <div class="page" id="page-connections">
131
+ <div class="page-header">
132
+ <h1>Connections</h1>
133
+ <p>Cross-document links and relationships discovered by Cortex</p>
134
+ </div>
135
+ <div class="conn-list" id="connList">
136
+ <div class="empty-state">
137
+ <i class="ti ti-topology-star" aria-hidden="true"></i>
138
+ <p>Upload at least two files to discover cross-document connections</p>
139
+ </div>
140
+ </div>
141
+ </div>
142
+
143
+ </main>
144
+ </div>
145
+
146
+ <footer>CORTEX · MULTIMODAL KNOWLEDGE INTELLIGENCE · BUILT BY YASHIKA SAXENA</footer>
147
+
148
+ <!-- FILE DETAIL MODAL -->
149
+ <div id="fileModal" style="display:none; position:fixed; inset:0; z-index:200; background:rgba(0,0,0,0.4); backdrop-filter:blur(4px); padding:24px; overflow-y:auto;">
150
+ <div style="max-width:720px; margin:0 auto; background:#f5f0e8; border-radius:18px; border:0.5px solid #ddd0be; overflow:hidden;">
151
+ <div style="padding:20px 24px; border-bottom:0.5px solid #ecdecb; display:flex; align-items:center; justify-content:space-between;">
152
+ <div>
153
+ <div id="modal-type" style="font-family:'JetBrains Mono',monospace; font-size:9px; letter-spacing:0.2em; color:#c17a4a; text-transform:uppercase; margin-bottom:4px;"></div>
154
+ <div id="modal-filename" style="font-family:'Playfair Display',serif; font-size:20px; font-weight:500; color:#1a1209;"></div>
155
+ </div>
156
+ <button onclick="closeModal()" style="background:none; border:0.5px solid #ddd0be; border-radius:8px; padding:8px 14px; cursor:pointer; font-family:'DM Sans',sans-serif; font-size:13px; color:#5a4a38;">Close</button>
157
+ </div>
158
+
159
+ <div id="modal-thumb-wrap" style="display:none;">
160
+ <img id="modal-thumb" style="width:100%; max-height:220px; object-fit:cover; display:block;"/>
161
+ </div>
162
+
163
+ <div style="padding:20px 24px; display:flex; flex-direction:column; gap:18px;">
164
+ <div>
165
+ <div style="font-family:'JetBrains Mono',monospace; font-size:9px; letter-spacing:0.2em; color:#a89a88; text-transform:uppercase; margin-bottom:8px;">Summary</div>
166
+ <div id="modal-summary" style="font-family:'DM Sans',sans-serif; font-size:14px; color:#3d2e1f; line-height:1.8;"></div>
167
+ </div>
168
+
169
+ <div id="modal-facts-wrap">
170
+ <div style="font-family:'JetBrains Mono',monospace; font-size:9px; letter-spacing:0.2em; color:#a89a88; text-transform:uppercase; margin-bottom:8px;">Key Facts</div>
171
+ <div id="modal-facts" style="display:flex; flex-direction:column; gap:6px;"></div>
172
+ </div>
173
+
174
+ <div id="modal-sections-wrap">
175
+ <div style="font-family:'JetBrains Mono',monospace; font-size:9px; letter-spacing:0.2em; color:#a89a88; text-transform:uppercase; margin-bottom:8px;">Sections</div>
176
+ <div id="modal-sections" style="display:flex; flex-wrap:wrap; gap:6px;"></div>
177
+ </div>
178
+
179
+ <div>
180
+ <div style="font-family:'JetBrains Mono',monospace; font-size:9px; letter-spacing:0.2em; color:#a89a88; text-transform:uppercase; margin-bottom:8px;">Entities</div>
181
+ <div id="modal-entities" style="display:flex; flex-wrap:wrap; gap:5px;"></div>
182
+ </div>
183
+
184
+ <div>
185
+ <div style="font-family:'JetBrains Mono',monospace; font-size:9px; letter-spacing:0.2em; color:#a89a88; text-transform:uppercase; margin-bottom:8px;">Topics</div>
186
+ <div id="modal-topics" style="display:flex; flex-wrap:wrap; gap:5px;"></div>
187
+ </div>
188
+
189
+ <div>
190
+ <div style="font-family:'JetBrains Mono',monospace; font-size:9px; letter-spacing:0.2em; color:#a89a88; text-transform:uppercase; margin-bottom:8px;">Content Preview</div>
191
+ <div id="modal-preview" style="font-family:'JetBrains Mono',monospace; font-size:11px; color:#7a6a58; line-height:1.7; background:#fff; border:0.5px solid #ddd0be; border-radius:8px; padding:14px; max-height:200px; overflow-y:auto; white-space:pre-wrap;"></div>
192
+ </div>
193
+
194
+ <div style="display:flex; gap:8px;">
195
+ <button class="btn btn-dark" onclick="askAboutFile(currentModalFile)"><i class="ti ti-message-question" aria-hidden="true"></i> Ask about this file</button>
196
+ <button class="btn btn-outline" onclick="closeModal()">Close</button>
197
+ </div>
198
+ </div>
199
+ </div>
200
+ </div>
201
+ <script src="/static/script.js"></script>
202
+ </body>
203
+ </html>
static/script.js ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ── State ─────────────────────────────────────────────────────────
2
+ const state = { files: {}, connections: [], chatHistory: [] };
3
+
4
+ // ── Navigation ────────────────────────────────────────────────────
5
+ function showPage(name) {
6
+ document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
7
+ document.querySelectorAll('.nav-item[data-page]').forEach(n => n.classList.remove('active'));
8
+ document.getElementById('page-' + name).classList.add('active');
9
+ document.querySelector(`.nav-item[data-page="${name}"]`)?.classList.add('active');
10
+ window.scrollTo({ top: 0, behavior: 'smooth' });
11
+ }
12
+ document.querySelectorAll('.nav-item[data-page]').forEach(item => {
13
+ item.addEventListener('click', () => showPage(item.dataset.page));
14
+ });
15
+
16
+ // ── API key ───────────────────────────────────────────────────────
17
+ function getKey() { return document.getElementById('apiKeyInput').value.trim(); }
18
+
19
+ // ── Upload ────────────────────────────────────────────────────────
20
+ const uploadZone = document.getElementById('uploadZone');
21
+ const fileInput = document.getElementById('fileInput');
22
+ const uploadStatus = document.getElementById('uploadStatus');
23
+
24
+ uploadZone.addEventListener('click', () => fileInput.click());
25
+ uploadZone.addEventListener('dragover', e => { e.preventDefault(); uploadZone.classList.add('dragover'); });
26
+ uploadZone.addEventListener('dragleave', () => uploadZone.classList.remove('dragover'));
27
+ uploadZone.addEventListener('drop', e => {
28
+ e.preventDefault(); uploadZone.classList.remove('dragover');
29
+ if (e.dataTransfer.files[0]) handleUpload(e.dataTransfer.files[0]);
30
+ });
31
+ fileInput.addEventListener('change', () => { if (fileInput.files[0]) handleUpload(fileInput.files[0]); });
32
+
33
+ function showStatus(msg, show = true) {
34
+ uploadStatus.style.display = show ? 'block' : 'none';
35
+ uploadStatus.textContent = msg;
36
+ }
37
+
38
+ async function handleUpload(file) {
39
+ const key = getKey();
40
+ if (!key) { alert('Please enter your Claude API key in the sidebar first.'); return; }
41
+ showStatus(`⏳ Processing ${file.name} — this may take 20-60 seconds...`);
42
+ const fd = new FormData();
43
+ fd.append('file', file);
44
+ fd.append('api_key', key);
45
+ try {
46
+ const res = await fetch('/api/upload', { method: 'POST', body: fd });
47
+ const data = await res.json();
48
+ if (!res.ok) { showStatus(`Error: ${data.detail || 'Upload failed'}`); return; }
49
+ state.files[data.filename] = data;
50
+ if (data.connections) state.connections = data.connections;
51
+ showStatus(`✓ ${data.filename} indexed — ${data.chunk_count} chunks, summary generated`);
52
+ updateAll();
53
+ document.getElementById('askBtn').disabled = false;
54
+ } catch (e) {
55
+ showStatus('Upload failed: ' + e.message);
56
+ } finally {
57
+ fileInput.value = '';
58
+ }
59
+ }
60
+
61
+ // ── Update UI ─────────────────────────────────────────────────────
62
+ function updateAll() {
63
+ updateStats();
64
+ updateSidebarFiles();
65
+ updateFilesGrid();
66
+ updateSummaries();
67
+ updateConnections();
68
+ }
69
+
70
+ function updateStats() {
71
+ const files = Object.values(state.files);
72
+ document.getElementById('stat-docs').textContent = files.length;
73
+ const totalChunks = files.reduce((s, f) => s + (f.chunk_count || 0), 0);
74
+ document.getElementById('stat-chunks').textContent = totalChunks;
75
+ const types = [...new Set(files.map(f => f.type?.toUpperCase()))];
76
+ document.getElementById('stat-types').textContent = types.length ? types.join(', ') : '—';
77
+ }
78
+
79
+ function fileIcon(type) {
80
+ const icons = { pdf: 'ti-file-type-pdf', image: 'ti-photo', video: 'ti-video', text: 'ti-file-text' };
81
+ return icons[type] || 'ti-file';
82
+ }
83
+
84
+ function updateSidebarFiles() {
85
+ const container = document.getElementById('sidebar-files');
86
+ const files = Object.entries(state.files);
87
+ if (!files.length) { container.innerHTML = ''; return; }
88
+ container.innerHTML = files.map(([name, f]) => `
89
+ <div class="nav-item" onclick="showPage('summaries')">
90
+ <i class="ti ${fileIcon(f.type)}" aria-hidden="true"></i>
91
+ <span class="file-name">${name}</span>
92
+ <button class="del-btn" onclick="event.stopPropagation();deleteFile('${name}')" title="Remove">✕</button>
93
+ </div>
94
+ `).join('');
95
+ }
96
+
97
+ function updateFilesGrid() {
98
+ const grid = document.getElementById('filesGrid');
99
+ const files = Object.entries(state.files);
100
+ if (!files.length) {
101
+ grid.innerHTML = `<div class="empty-state" style="grid-column:1/-1;"><i class="ti ti-inbox" aria-hidden="true"></i><p>No files yet — upload something to get started</p></div>`;
102
+ return;
103
+ }
104
+ grid.innerHTML = files.map(([name, f]) => `
105
+ <div class="file-card" onclick="openModal('${name.replace(/'/g, "\\'")}')" style="cursor:pointer;">
106
+ <div class="file-thumb">
107
+ ${f.thumb_b64 ? `<img src="data:image/jpeg;base64,${f.thumb_b64}" alt="${name}"/>` : `<i class="ti ${fileIcon(f.type)}" aria-hidden="true"></i>`}
108
+ </div>
109
+ <div class="file-info">
110
+ <div class="file-name">${name}</div>
111
+ <div class="file-type">${f.type || 'file'}</div>
112
+ <div class="file-meta">${f.chunk_count || 0} chunks · click to explore</div>
113
+ </div>
114
+ </div>
115
+ `).join('');
116
+ }
117
+
118
+ function updateSummaries() {
119
+ const list = document.getElementById('summaryList');
120
+ const files = Object.entries(state.files);
121
+ if (!files.length) {
122
+ list.innerHTML = `<div class="empty-state"><i class="ti ti-file-text" aria-hidden="true"></i><p>Upload files to see auto-generated summaries and entities</p></div>`;
123
+ return;
124
+ }
125
+ list.innerHTML = files.map(([name, f]) => `
126
+ <div class="summary-item">
127
+ <div class="summary-filename"><i class="ti ${fileIcon(f.type)}" aria-hidden="true"></i>${name}</div>
128
+ <div class="summary-text">${f.summary || 'No summary available.'}</div>
129
+ ${f.entities?.length ? `<div class="entity-row">${f.entities.map(e => `<span class="entity-chip">${e}</span>`).join('')}</div>` : ''}
130
+ ${f.topics?.length ? `<div class="entity-row" style="margin-top:6px;">${f.topics.map(t => `<span class="entity-chip" style="background:#eef4f0;border-color:#c4d8ca;color:#4a7a5a;">${t}</span>`).join('')}</div>` : ''}
131
+ </div>
132
+ `).join('');
133
+ }
134
+
135
+ function updateConnections() {
136
+ const list = document.getElementById('connList');
137
+ if (!state.connections.length) {
138
+ list.innerHTML = `<div class="empty-state"><i class="ti ti-topology-star" aria-hidden="true"></i><p>Upload at least two files to discover cross-document connections</p></div>`;
139
+ return;
140
+ }
141
+ list.innerHTML = state.connections.map(c => `
142
+ <div class="conn-item">
143
+ <div class="conn-icon"><i class="ti ti-link" aria-hidden="true"></i></div>
144
+ <div>
145
+ <div class="conn-docs">${c.doc1} ↔ ${c.doc2}</div>
146
+ <div class="conn-text">${c.connection}</div>
147
+ </div>
148
+ </div>
149
+ `).join('');
150
+ }
151
+
152
+ // ── Ask ───────────────────────────────────────────────────────────
153
+ const askBtn = document.getElementById('askBtn');
154
+ const queryInput = document.getElementById('queryInput');
155
+ const chatHistory = document.getElementById('chatHistory');
156
+
157
+ askBtn.addEventListener('click', runAsk);
158
+ queryInput.addEventListener('keydown', e => { if (e.key === 'Enter' && !askBtn.disabled) runAsk(); });
159
+
160
+ async function runAsk() {
161
+ const query = queryInput.value.trim();
162
+ if (!query) return;
163
+ const key = getKey();
164
+ if (!key) { alert('Please enter your Claude API key first.'); return; }
165
+ askBtn.disabled = true;
166
+ askBtn.innerHTML = '<i class="ti ti-loader" aria-hidden="true"></i> Thinking...';
167
+ chatHistory.style.display = 'flex';
168
+ document.getElementById('suggestionsCard').style.display = 'none';
169
+ chatHistory.innerHTML += `<div class="chat-q">${query}</div>`;
170
+ chatHistory.scrollTop = chatHistory.scrollHeight;
171
+
172
+ const fd = new FormData();
173
+ fd.append('query', query);
174
+ fd.append('api_key', key);
175
+
176
+ try {
177
+ const res = await fetch('/api/ask', { method: 'POST', body: fd });
178
+ const data = await res.json();
179
+ const confClass = { high: 'conf-high', medium: 'conf-medium', low: 'conf-low' }[data.confidence] || 'conf-medium';
180
+ const sources = (data.sources || []).map(s => `<span class="source-chip"><i class="ti ${fileIcon(s.file?.split('.').pop())} " aria-hidden="true"></i>${s.file}${s.page ? ` p.${s.page}` : ''}</span>`).join('');
181
+ chatHistory.innerHTML += `
182
+ <div class="chat-a">
183
+ <span class="confidence-badge ${confClass}">${data.confidence || 'medium'}</span>
184
+ <div style="margin-top:8px;">${data.answer || 'No answer found.'}</div>
185
+ ${sources ? `<div class="src">${sources}</div>` : ''}
186
+ </div>`;
187
+ chatHistory.scrollTop = chatHistory.scrollHeight;
188
+ queryInput.value = '';
189
+ } catch (e) {
190
+ chatHistory.innerHTML += `<div class="chat-a" style="color:var(--danger);">Error: ${e.message}</div>`;
191
+ } finally {
192
+ askBtn.disabled = false;
193
+ askBtn.innerHTML = '<i class="ti ti-arrow-right" aria-hidden="true"></i>Ask';
194
+ }
195
+ }
196
+
197
+ function setQuery(el) { queryInput.value = el.textContent; queryInput.focus(); }
198
+
199
+ // ── Delete file ───────────────────────────────────────────────────
200
+ async function deleteFile(name) {
201
+ await fetch(`/api/file/${encodeURIComponent(name)}`, { method: 'DELETE' });
202
+ delete state.files[name];
203
+ updateAll();
204
+ if (!Object.keys(state.files).length) document.getElementById('askBtn').disabled = true;
205
+ }
206
+
207
+ // ── File detail modal ──��──────────────────────────────────────────
208
+ let currentModalFile = null;
209
+
210
+ function openModal(name) {
211
+ const f = state.files[name];
212
+ if (!f) return;
213
+ currentModalFile = name;
214
+
215
+ document.getElementById('modal-filename').textContent = name;
216
+ document.getElementById('modal-type').textContent = (f.type || 'file').toUpperCase() + ' · ' + (f.file_type_detected || '');
217
+ document.getElementById('modal-summary').textContent = f.summary || 'No summary available.';
218
+
219
+ // thumb
220
+ const thumbWrap = document.getElementById('modal-thumb-wrap');
221
+ const thumbImg = document.getElementById('modal-thumb');
222
+ if (f.thumb_b64) {
223
+ thumbImg.src = `data:image/jpeg;base64,${f.thumb_b64}`;
224
+ thumbWrap.style.display = 'block';
225
+ } else {
226
+ thumbWrap.style.display = 'none';
227
+ }
228
+
229
+ // facts
230
+ const facts = f.important_facts || [];
231
+ const factsWrap = document.getElementById('modal-facts-wrap');
232
+ const factsEl = document.getElementById('modal-facts');
233
+ if (facts.length) {
234
+ factsEl.innerHTML = facts.map(fact => `<div style="display:flex;gap:8px;align-items:flex-start;"><span style="color:#c17a4a;flex-shrink:0;">→</span><span style="font-family:'DM Sans',sans-serif;font-size:13px;color:#3d2e1f;line-height:1.6;">${fact}</span></div>`).join('');
235
+ factsWrap.style.display = 'block';
236
+ } else {
237
+ factsWrap.style.display = 'none';
238
+ }
239
+
240
+ // sections
241
+ const sections = f.key_sections || [];
242
+ const sectionsWrap = document.getElementById('modal-sections-wrap');
243
+ const sectionsEl = document.getElementById('modal-sections');
244
+ if (sections.length) {
245
+ sectionsEl.innerHTML = sections.map(s => `<span class="badge" style="font-size:11px;">${s}</span>`).join('');
246
+ sectionsWrap.style.display = 'block';
247
+ } else {
248
+ sectionsWrap.style.display = 'none';
249
+ }
250
+
251
+ // entities
252
+ document.getElementById('modal-entities').innerHTML = (f.entities || []).map(e => `<span class="entity-chip">${e}</span>`).join('') || '<span style="font-size:12px;color:#a89a88;">None extracted</span>';
253
+
254
+ // topics
255
+ document.getElementById('modal-topics').innerHTML = (f.topics || []).map(t => `<span class="entity-chip" style="background:#eef4f0;border-color:#c4d8ca;color:#4a7a5a;">${t}</span>`).join('') || '<span style="font-size:12px;color:#a89a88;">None extracted</span>';
256
+
257
+ // preview
258
+ document.getElementById('modal-preview').textContent = f.preview || 'No content preview available.';
259
+
260
+ document.getElementById('fileModal').style.display = 'block';
261
+ document.body.style.overflow = 'hidden';
262
+ }
263
+
264
+ function closeModal() {
265
+ document.getElementById('fileModal').style.display = 'none';
266
+ document.body.style.overflow = '';
267
+ currentModalFile = null;
268
+ }
269
+
270
+ function askAboutFile(name) {
271
+ closeModal();
272
+ showPage('ask');
273
+ document.getElementById('queryInput').value = `Tell me everything important about ${name}`;
274
+ document.getElementById('queryInput').focus();
275
+ }
276
+
277
+ // close modal on backdrop click
278
+ document.getElementById('fileModal')?.addEventListener('click', function(e) {
279
+ if (e.target === this) closeModal();
280
+ });
281
+ async function loadStatus() {
282
+ try {
283
+ const res = await fetch('/api/status');
284
+ const data = await res.json();
285
+ for (const [name, info] of Object.entries(data.files || {})) {
286
+ if (!state.files[name]) state.files[name] = info;
287
+ }
288
+ updateAll();
289
+ if (Object.keys(state.files).length) document.getElementById('askBtn').disabled = false;
290
+ } catch (e) {}
291
+ }
292
+ loadStatus();
static/style.css ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;500;600&family=DM+Sans:wght@300;400;500&family=JetBrains+Mono:wght@400;500&display=swap');
2
+
3
+ *{margin:0;padding:0;box-sizing:border-box;}
4
+
5
+ :root{
6
+ --bg:#f5f0e8;
7
+ --sidebar:#2c1f14;
8
+ --sidebar-hover:rgba(255,255,255,0.05);
9
+ --sidebar-active:rgba(193,122,74,0.15);
10
+ --sidebar-active-border:rgba(193,122,74,0.3);
11
+ --sidebar-text:#a89a88;
12
+ --sidebar-text-active:#e8c9a8;
13
+ --sidebar-label:#7a6a58;
14
+ --accent:#c17a4a;
15
+ --accent-light:#f0e8d8;
16
+ --card:#ffffff;
17
+ --card-border:#ddd0be;
18
+ --text:#1a1209;
19
+ --text-2:#5a4a38;
20
+ --text-3:#a89a88;
21
+ --input-bg:#f5f0e8;
22
+ --tag-bg:#f0e8d8;
23
+ --tag-border:#d4c4ae;
24
+ --tag-text:#7a6a58;
25
+ --divider:#ecdecb;
26
+ --danger:#c0392b;
27
+ --danger-bg:#fdf0ee;
28
+ }
29
+
30
+ body{font-family:'DM Sans',sans-serif;background:var(--bg);color:var(--text);min-height:100vh;overflow-x:hidden;}
31
+
32
+ .app{display:flex;min-height:100vh;}
33
+
34
+ /* SIDEBAR */
35
+ .sidebar{width:230px;flex-shrink:0;background:var(--sidebar);padding:24px 14px;display:flex;flex-direction:column;gap:2px;position:sticky;top:0;height:100vh;overflow-y:auto;}
36
+ .logo{font-family:'Playfair Display',serif;font-size:22px;color:#f5f0e8;letter-spacing:0.02em;margin-bottom:32px;padding-left:8px;}
37
+ .logo span{color:var(--accent);}
38
+ .nav-label{font-family:'JetBrains Mono',monospace;font-size:9px;letter-spacing:0.2em;color:var(--sidebar-label);text-transform:uppercase;padding:0 8px;margin:18px 0 6px;}
39
+ .nav-item{display:flex;align-items:center;gap:9px;padding:9px 10px;border-radius:8px;font-size:13px;color:var(--sidebar-text);cursor:pointer;border:0.5px solid transparent;transition:all 0.15s;margin-bottom:1px;}
40
+ .nav-item i{font-size:15px;width:16px;flex-shrink:0;}
41
+ .nav-item:hover{background:var(--sidebar-hover);color:#d4c4b0;}
42
+ .nav-item.active{background:var(--sidebar-active);border-color:var(--sidebar-active-border);color:var(--sidebar-text-active);}
43
+ .nav-item .file-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;}
44
+ .nav-item .del-btn{opacity:0;font-size:12px;color:var(--sidebar-label);background:none;border:none;cursor:pointer;padding:0 2px;line-height:1;}
45
+ .nav-item:hover .del-btn{opacity:1;}
46
+ .nav-item .del-btn:hover{color:#e87a6a;}
47
+
48
+ .sidebar-footer{margin-top:auto;padding-top:16px;border-top:0.5px solid rgba(255,255,255,0.08);}
49
+ .api-key-box{background:rgba(255,255,255,0.05);border:0.5px solid rgba(255,255,255,0.1);border-radius:10px;padding:12px 14px;}
50
+ .api-key-label{font-family:'JetBrains Mono',monospace;font-size:9px;letter-spacing:0.18em;color:var(--sidebar-label);text-transform:uppercase;margin-bottom:6px;}
51
+ .api-key-input{width:100%;background:rgba(255,255,255,0.06);border:0.5px solid rgba(255,255,255,0.12);border-radius:6px;padding:7px 9px;font-family:'JetBrains Mono',monospace;font-size:11px;color:#d4c4b0;outline:none;transition:border-color 0.15s;}
52
+ .api-key-input:focus{border-color:rgba(193,122,74,0.5);}
53
+ .api-key-input::placeholder{color:var(--sidebar-label);}
54
+
55
+ /* MAIN */
56
+ .main{flex:1;padding:36px 32px;min-width:0;display:flex;flex-direction:column;}
57
+ .page{display:none;flex-direction:column;gap:20px;}
58
+ .page.active{display:flex;}
59
+
60
+ .page-header{margin-bottom:4px;}
61
+ .page-header h1{font-family:'Playfair Display',serif;font-size:26px;font-weight:500;color:var(--text);letter-spacing:-0.01em;margin-bottom:6px;}
62
+ .page-header p{font-size:13px;color:var(--text-3);}
63
+
64
+ /* CARDS */
65
+ .card{background:var(--card);border:0.5px solid var(--card-border);border-radius:14px;padding:20px 22px;}
66
+ .card-label{font-family:'JetBrains Mono',monospace;font-size:9px;letter-spacing:0.2em;color:var(--text-3);text-transform:uppercase;margin-bottom:12px;}
67
+
68
+ /* STATS */
69
+ .stats-row{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;}
70
+ .stat-card{background:var(--card);border:0.5px solid var(--card-border);border-radius:12px;padding:18px 20px;}
71
+ .stat-label{font-family:'JetBrains Mono',monospace;font-size:9px;letter-spacing:0.2em;color:var(--text-3);text-transform:uppercase;margin-bottom:10px;}
72
+ .stat-value{font-family:'Playfair Display',serif;font-size:28px;color:var(--text);line-height:1;}
73
+ .stat-sub{font-size:11px;color:var(--text-3);margin-top:5px;}
74
+
75
+ /* UPLOAD */
76
+ .upload-zone{border:1.5px dashed var(--card-border);border-radius:12px;padding:32px;text-align:center;cursor:pointer;background:rgba(255,255,255,0.5);transition:all 0.2s;margin-bottom:14px;}
77
+ .upload-zone:hover,.upload-zone.dragover{border-color:var(--accent);background:#fffcf8;}
78
+ .upload-zone input{display:none;}
79
+ .upload-icon{font-size:28px;color:var(--text-3);margin-bottom:12px;}
80
+ .upload-zone h3{font-family:'Playfair Display',serif;font-size:16px;font-weight:500;color:var(--text);margin-bottom:4px;}
81
+ .upload-zone .hint{font-size:12px;color:var(--text-3);margin-bottom:14px;}
82
+ .file-types{display:flex;gap:6px;justify-content:center;flex-wrap:wrap;}
83
+ .badge{font-family:'JetBrains Mono',monospace;font-size:10px;background:var(--tag-bg);border:0.5px solid var(--tag-border);border-radius:5px;padding:3px 9px;color:var(--tag-text);}
84
+
85
+ /* STATUS BAR */
86
+ .status-bar{display:none;padding:10px 14px;border-radius:8px;font-family:'JetBrains Mono',monospace;font-size:11px;background:var(--accent-light);border:0.5px solid var(--tag-border);color:var(--text-2);margin-top:10px;}
87
+
88
+ /* BUTTONS */
89
+ .btn{font-family:'DM Sans',sans-serif;font-size:13px;font-weight:500;padding:10px 18px;border-radius:9px;cursor:pointer;transition:all 0.15s;display:inline-flex;align-items:center;gap:7px;border:none;}
90
+ .btn-dark{background:var(--sidebar);color:#f5f0e8;}
91
+ .btn-dark:hover{background:#3d2e1f;}
92
+ .btn-dark:disabled{opacity:0.4;cursor:not-allowed;}
93
+ .btn-outline{background:transparent;color:var(--text-2);border:0.5px solid var(--card-border);}
94
+ .btn-outline:hover{background:var(--accent-light);}
95
+ .btn-full{width:100%;justify-content:center;}
96
+ .btn-sm{padding:6px 12px;font-size:12px;}
97
+
98
+ /* SEARCH/QUERY */
99
+ .query-row{display:flex;gap:8px;align-items:stretch;}
100
+ .query-input{flex:1;background:var(--input-bg);border:0.5px solid var(--card-border);border-radius:9px;padding:10px 14px;font-family:'DM Sans',sans-serif;font-size:14px;color:var(--text);outline:none;transition:border-color 0.15s;}
101
+ .query-input:focus{border-color:var(--accent);}
102
+ .query-input::placeholder{color:var(--text-3);}
103
+
104
+ /* ANSWER */
105
+ .answer-block{margin-top:16px;padding-top:16px;border-top:0.5px solid var(--divider);}
106
+ .answer-text{font-size:14px;color:var(--text-2);line-height:1.8;margin-bottom:12px;}
107
+ .sources-row{display:flex;flex-wrap:wrap;gap:6px;}
108
+ .source-chip{display:inline-flex;align-items:center;gap:5px;background:var(--tag-bg);border:0.5px solid var(--tag-border);border-radius:6px;padding:4px 10px;font-family:'JetBrains Mono',monospace;font-size:10px;color:var(--tag-text);}
109
+ .source-chip i{font-size:12px;}
110
+ .confidence-badge{font-family:'JetBrains Mono',monospace;font-size:10px;padding:2px 8px;border-radius:4px;margin-left:8px;}
111
+ .conf-high{background:#eaf6ee;color:#2a7a4a;}
112
+ .conf-medium{background:#fef6e4;color:#8a6010;}
113
+ .conf-low{background:#fdf0ee;color:#c0392b;}
114
+
115
+ /* FILE CARDS */
116
+ .files-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:14px;}
117
+ .file-card{background:var(--card);border:0.5px solid var(--card-border);border-radius:12px;overflow:hidden;transition:border-color 0.15s;}
118
+ .file-card:hover{border-color:var(--accent);}
119
+ .file-thumb{width:100%;height:100px;object-fit:cover;background:var(--accent-light);display:flex;align-items:center;justify-content:center;font-size:32px;color:var(--text-3);}
120
+ .file-thumb img{width:100%;height:100%;object-fit:cover;}
121
+ .file-info{padding:12px 14px;}
122
+ .file-name{font-size:12px;font-weight:500;color:var(--text);margin-bottom:4px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
123
+ .file-type{font-family:'JetBrains Mono',monospace;font-size:10px;color:var(--text-3);text-transform:uppercase;letter-spacing:0.1em;}
124
+ .file-meta{font-size:11px;color:var(--text-3);margin-top:6px;}
125
+
126
+ /* SUMMARY */
127
+ .summary-list{display:flex;flex-direction:column;gap:14px;}
128
+ .summary-item{background:var(--card);border:0.5px solid var(--card-border);border-radius:12px;padding:18px 20px;}
129
+ .summary-filename{font-family:'JetBrains Mono',monospace;font-size:10px;letter-spacing:0.1em;color:var(--accent);text-transform:uppercase;margin-bottom:8px;display:flex;align-items:center;gap:6px;}
130
+ .summary-text{font-size:13px;color:var(--text-2);line-height:1.75;margin-bottom:12px;}
131
+ .entity-row{display:flex;flex-wrap:wrap;gap:5px;}
132
+ .entity-chip{font-family:'JetBrains Mono',monospace;font-size:10px;background:var(--tag-bg);border:0.5px solid var(--tag-border);border-radius:4px;padding:2px 8px;color:var(--tag-text);}
133
+
134
+ /* CONNECTIONS */
135
+ .conn-list{display:flex;flex-direction:column;gap:12px;}
136
+ .conn-item{background:var(--card);border:0.5px solid var(--card-border);border-radius:12px;padding:16px 18px;display:flex;gap:14px;align-items:flex-start;}
137
+ .conn-icon{width:36px;height:36px;border-radius:50%;background:var(--accent-light);display:flex;align-items:center;justify-content:center;flex-shrink:0;color:var(--accent);font-size:16px;}
138
+ .conn-docs{font-family:'JetBrains Mono',monospace;font-size:10px;color:var(--accent);margin-bottom:5px;}
139
+ .conn-text{font-size:13px;color:var(--text-2);line-height:1.6;}
140
+
141
+ /* EMPTY STATE */
142
+ .empty-state{text-align:center;padding:48px 20px;color:var(--text-3);}
143
+ .empty-state i{font-size:36px;display:block;margin-bottom:12px;opacity:0.4;}
144
+ .empty-state p{font-size:13px;}
145
+
146
+ /* CHAT HISTORY */
147
+ .chat-history{display:flex;flex-direction:column;gap:12px;max-height:420px;overflow-y:auto;margin-bottom:14px;padding-right:4px;}
148
+ .chat-q{background:var(--accent-light);border-radius:10px;padding:10px 14px;font-size:13px;color:var(--text-2);align-self:flex-end;max-width:80%;border:0.5px solid var(--tag-border);}
149
+ .chat-a{background:var(--card);border:0.5px solid var(--card-border);border-radius:10px;padding:12px 16px;font-size:13px;color:var(--text-2);line-height:1.75;}
150
+ .chat-a .src{margin-top:8px;display:flex;flex-wrap:wrap;gap:4px;}
151
+
152
+ /* DIVIDER */
153
+ .or-divider{text-align:center;position:relative;margin:12px 0;}
154
+ .or-divider::before{content:'';position:absolute;top:50%;left:0;right:0;height:0.5px;background:var(--card-border);}
155
+ .or-divider span{background:var(--bg);position:relative;padding:0 10px;font-size:11px;color:var(--text-3);font-family:'JetBrains Mono',monospace;}
156
+
157
+ footer{text-align:center;padding:20px;font-family:'JetBrains Mono',monospace;font-size:10px;color:var(--text-3);letter-spacing:0.12em;border-top:0.5px solid var(--card-border);margin-top:auto;}
158
+
159
+ @media(max-width:768px){
160
+ .sidebar{display:none;}
161
+ .main{padding:16px;}
162
+ .stats-row{grid-template-columns:1fr 1fr;}
163
+ .files-grid{grid-template-columns:1fr 1fr;}
164
+ }