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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import os
|
| 3 |
+
from io import BytesIO
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
|
| 7 |
+
# Load .env explicitly from project folder
|
| 8 |
+
load_dotenv(dotenv_path=Path(__file__).parent / ".env", override=True)
|
| 9 |
+
|
| 10 |
+
from document_processor import extract_text, get_document_stats, chunk_text
|
| 11 |
+
from embedder import TarkaEmbedder
|
| 12 |
+
from llm_handler import ask_gemini, check_api_key
|
| 13 |
+
|
| 14 |
+
# ─── Page config ─────────────────────────────────────────────────────────────
|
| 15 |
+
st.set_page_config(
|
| 16 |
+
page_title="TarkaRAG",
|
| 17 |
+
page_icon="🔍",
|
| 18 |
+
layout="wide",
|
| 19 |
+
initial_sidebar_state="expanded",
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
# ─── Custom CSS ──────────────────────────────────────────────────────────────
|
| 23 |
+
st.markdown("""
|
| 24 |
+
<style>
|
| 25 |
+
@import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&family=DM+Sans:wght@300;400;500;600&display=swap');
|
| 26 |
+
|
| 27 |
+
html, body, [class*="css"] { font-family: 'DM Sans', sans-serif; }
|
| 28 |
+
|
| 29 |
+
.main-header {
|
| 30 |
+
background: linear-gradient(135deg, #0f0f23 0%, #1a1a3e 50%, #0d1b2a 100%);
|
| 31 |
+
border-radius: 16px;
|
| 32 |
+
padding: 2rem 2.5rem;
|
| 33 |
+
margin-bottom: 1.5rem;
|
| 34 |
+
border: 1px solid rgba(99, 102, 241, 0.3);
|
| 35 |
+
}
|
| 36 |
+
.main-title {
|
| 37 |
+
font-family: 'Space Mono', monospace;
|
| 38 |
+
font-size: 2.2rem;
|
| 39 |
+
font-weight: 700;
|
| 40 |
+
color: #a5b4fc;
|
| 41 |
+
margin: 0;
|
| 42 |
+
}
|
| 43 |
+
.main-subtitle { color: #94a3b8; font-size: 0.95rem; margin-top: 0.3rem; }
|
| 44 |
+
.model-badge {
|
| 45 |
+
display: inline-block;
|
| 46 |
+
background: rgba(99,102,241,0.15);
|
| 47 |
+
border: 1px solid rgba(99,102,241,0.4);
|
| 48 |
+
color: #a5b4fc;
|
| 49 |
+
padding: 3px 10px;
|
| 50 |
+
border-radius: 20px;
|
| 51 |
+
font-family: 'Space Mono', monospace;
|
| 52 |
+
font-size: 0.72rem;
|
| 53 |
+
margin-right: 6px;
|
| 54 |
+
}
|
| 55 |
+
.stat-card {
|
| 56 |
+
background: #0f172a;
|
| 57 |
+
border: 1px solid rgba(99,102,241,0.2);
|
| 58 |
+
border-radius: 12px;
|
| 59 |
+
padding: 1.2rem 1.4rem;
|
| 60 |
+
text-align: center;
|
| 61 |
+
}
|
| 62 |
+
.stat-value {
|
| 63 |
+
font-family: 'Space Mono', monospace;
|
| 64 |
+
font-size: 1.8rem;
|
| 65 |
+
font-weight: 700;
|
| 66 |
+
color: #a5b4fc;
|
| 67 |
+
line-height: 1;
|
| 68 |
+
}
|
| 69 |
+
.stat-label {
|
| 70 |
+
font-size: 0.75rem;
|
| 71 |
+
color: #64748b;
|
| 72 |
+
margin-top: 4px;
|
| 73 |
+
text-transform: uppercase;
|
| 74 |
+
letter-spacing: 0.08em;
|
| 75 |
+
}
|
| 76 |
+
.chat-bubble-user {
|
| 77 |
+
background: linear-gradient(135deg, #312e81, #1e1b4b);
|
| 78 |
+
border: 1px solid rgba(99,102,241,0.3);
|
| 79 |
+
border-radius: 12px 12px 4px 12px;
|
| 80 |
+
padding: 0.9rem 1.2rem;
|
| 81 |
+
margin: 0.5rem 0;
|
| 82 |
+
color: #e0e7ff;
|
| 83 |
+
}
|
| 84 |
+
.chat-bubble-ai {
|
| 85 |
+
background: #0f172a;
|
| 86 |
+
border: 1px solid rgba(99,102,241,0.15);
|
| 87 |
+
border-radius: 12px 12px 12px 4px;
|
| 88 |
+
padding: 0.9rem 1.2rem;
|
| 89 |
+
margin: 0.5rem 0;
|
| 90 |
+
color: #cbd5e1;
|
| 91 |
+
line-height: 1.7;
|
| 92 |
+
}
|
| 93 |
+
.chunk-card {
|
| 94 |
+
background: #0f172a;
|
| 95 |
+
border-left: 3px solid #6366f1;
|
| 96 |
+
border-radius: 0 8px 8px 0;
|
| 97 |
+
padding: 0.8rem 1rem;
|
| 98 |
+
margin: 0.4rem 0;
|
| 99 |
+
font-size: 0.83rem;
|
| 100 |
+
color: #94a3b8;
|
| 101 |
+
font-family: 'Space Mono', monospace;
|
| 102 |
+
}
|
| 103 |
+
.score-pill {
|
| 104 |
+
background: rgba(99,102,241,0.2);
|
| 105 |
+
color: #a5b4fc;
|
| 106 |
+
padding: 2px 8px;
|
| 107 |
+
border-radius: 10px;
|
| 108 |
+
font-size: 0.72rem;
|
| 109 |
+
font-family: 'Space Mono', monospace;
|
| 110 |
+
}
|
| 111 |
+
.status-ok { color: #34d399; font-size: 0.85rem; }
|
| 112 |
+
.status-err { color: #f87171; font-size: 0.85rem; }
|
| 113 |
+
.step-label {
|
| 114 |
+
font-family: 'Space Mono', monospace;
|
| 115 |
+
font-size: 0.75rem;
|
| 116 |
+
color: #6366f1;
|
| 117 |
+
text-transform: uppercase;
|
| 118 |
+
letter-spacing: 0.1em;
|
| 119 |
+
margin-bottom: 0.3rem;
|
| 120 |
+
}
|
| 121 |
+
.stButton > button {
|
| 122 |
+
background: linear-gradient(135deg, #6366f1, #4f46e5);
|
| 123 |
+
color: white;
|
| 124 |
+
border: none;
|
| 125 |
+
border-radius: 8px;
|
| 126 |
+
font-weight: 500;
|
| 127 |
+
padding: 0.5rem 1.5rem;
|
| 128 |
+
}
|
| 129 |
+
.stButton > button:hover {
|
| 130 |
+
background: linear-gradient(135deg, #818cf8, #6366f1);
|
| 131 |
+
transform: translateY(-1px);
|
| 132 |
+
}
|
| 133 |
+
</style>
|
| 134 |
+
""", unsafe_allow_html=True)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
# ─── Session state ────────────────────────────────────────────────────────────
|
| 138 |
+
def init_session():
|
| 139 |
+
defaults = {
|
| 140 |
+
"embedder": TarkaEmbedder(),
|
| 141 |
+
"doc_stats": None,
|
| 142 |
+
"doc_text": None,
|
| 143 |
+
"chunks": [],
|
| 144 |
+
"indexed": False,
|
| 145 |
+
"chat_history": [],
|
| 146 |
+
"current_file": None,
|
| 147 |
+
}
|
| 148 |
+
for key, val in defaults.items():
|
| 149 |
+
if key not in st.session_state:
|
| 150 |
+
st.session_state[key] = val
|
| 151 |
+
|
| 152 |
+
init_session()
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# ─── Header ──────────────────────────────────────────────────────────────────
|
| 156 |
+
st.markdown("""
|
| 157 |
+
<div class="main-header">
|
| 158 |
+
<div class="main-title">🔍 TarkaRAG</div>
|
| 159 |
+
<div class="main-subtitle">
|
| 160 |
+
Document Intelligence powered by
|
| 161 |
+
<span class="model-badge">Tarka-Embedding-150M</span>
|
| 162 |
+
<span class="model-badge">Gemini 2.5 Flash</span>
|
| 163 |
+
</div>
|
| 164 |
+
</div>
|
| 165 |
+
""", unsafe_allow_html=True)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# ─── Sidebar ─────────────────────────────────────────────────────────────────
|
| 169 |
+
with st.sidebar:
|
| 170 |
+
st.markdown("### ⚙️ Configuration")
|
| 171 |
+
|
| 172 |
+
api_ok, api_msg = check_api_key()
|
| 173 |
+
if api_ok:
|
| 174 |
+
st.markdown('<div class="status-ok">✅ Gemini API connected</div>', unsafe_allow_html=True)
|
| 175 |
+
else:
|
| 176 |
+
st.markdown(f'<div class="status-err">❌ {api_msg}</div>', unsafe_allow_html=True)
|
| 177 |
+
st.info("Add your GEMINI_API_KEY to the .env file and restart.")
|
| 178 |
+
|
| 179 |
+
# Show current API key status for debugging
|
| 180 |
+
current_key = os.getenv("GEMINI_API_KEY", "")
|
| 181 |
+
if current_key and current_key != "your_gemini_api_key_here":
|
| 182 |
+
st.caption(f"Key loaded: {current_key[:8]}...{current_key[-4:]}")
|
| 183 |
+
else:
|
| 184 |
+
st.caption("No key detected in environment")
|
| 185 |
+
|
| 186 |
+
st.divider()
|
| 187 |
+
st.markdown("### 🧩 Chunking Settings")
|
| 188 |
+
chunk_size = st.slider("Chunk size (words)", 200, 1000, 500, 50)
|
| 189 |
+
chunk_overlap = st.slider("Overlap (words)", 0, 200, 50, 10)
|
| 190 |
+
top_k = st.slider("Top-K chunks for retrieval", 1, 10, 5)
|
| 191 |
+
|
| 192 |
+
st.divider()
|
| 193 |
+
st.markdown("### 📋 About")
|
| 194 |
+
st.markdown("""
|
| 195 |
+
<small style='color:#64748b;'>
|
| 196 |
+
<b>Embedding:</b> Tarka-150M (768-dim)<br>
|
| 197 |
+
<b>Vector DB:</b> FAISS (cosine similarity)<br>
|
| 198 |
+
<b>LLM:</b> Gemini 2.5 Flash<br>
|
| 199 |
+
<b>Supported:</b> PDF, DOCX, TXT
|
| 200 |
+
</small>
|
| 201 |
+
""", unsafe_allow_html=True)
|
| 202 |
+
|
| 203 |
+
if st.session_state.indexed:
|
| 204 |
+
st.divider()
|
| 205 |
+
if st.button("🗑️ Reset & Upload New Doc"):
|
| 206 |
+
st.session_state.embedder.reset()
|
| 207 |
+
st.session_state.doc_stats = None
|
| 208 |
+
st.session_state.doc_text = None
|
| 209 |
+
st.session_state.chunks = []
|
| 210 |
+
st.session_state.indexed = False
|
| 211 |
+
st.session_state.chat_history = []
|
| 212 |
+
st.session_state.current_file = None
|
| 213 |
+
st.rerun()
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
# ─── Main layout ──────────────────────────────────────────────────────────────
|
| 217 |
+
col_left, col_right = st.columns([1, 1.3], gap="large")
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
# ─── LEFT: Upload + Stats + Embed ────────────────────────────────────────────
|
| 221 |
+
with col_left:
|
| 222 |
+
|
| 223 |
+
st.markdown('<div class="step-label">Step 01 — Upload Document</div>', unsafe_allow_html=True)
|
| 224 |
+
uploaded_file = st.file_uploader(
|
| 225 |
+
"Drop your document here",
|
| 226 |
+
type=["pdf", "docx", "txt"],
|
| 227 |
+
label_visibility="collapsed",
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
if uploaded_file and uploaded_file.name != st.session_state.current_file:
|
| 231 |
+
with st.spinner("Analysing document..."):
|
| 232 |
+
try:
|
| 233 |
+
file_bytes = BytesIO(uploaded_file.read())
|
| 234 |
+
text, pages = extract_text(file_bytes, uploaded_file.name)
|
| 235 |
+
stats = get_document_stats(text, pages, uploaded_file.name)
|
| 236 |
+
st.session_state.doc_text = text
|
| 237 |
+
st.session_state.doc_stats = stats
|
| 238 |
+
st.session_state.indexed = False
|
| 239 |
+
st.session_state.current_file = uploaded_file.name
|
| 240 |
+
st.session_state.chat_history = []
|
| 241 |
+
st.session_state.embedder.reset()
|
| 242 |
+
except Exception as e:
|
| 243 |
+
st.error(f"Error reading file: {e}")
|
| 244 |
+
|
| 245 |
+
if st.session_state.doc_stats:
|
| 246 |
+
stats = st.session_state.doc_stats
|
| 247 |
+
st.markdown('<div class="step-label" style="margin-top:1.5rem;">Step 02 — Document Analysis</div>', unsafe_allow_html=True)
|
| 248 |
+
|
| 249 |
+
c1, c2, c3 = st.columns(3)
|
| 250 |
+
with c1:
|
| 251 |
+
st.markdown(f'<div class="stat-card"><div class="stat-value">{stats["pages"]}</div><div class="stat-label">Pages</div></div>', unsafe_allow_html=True)
|
| 252 |
+
with c2:
|
| 253 |
+
st.markdown(f'<div class="stat-card"><div class="stat-value">{stats["words"]:,}</div><div class="stat-label">Words</div></div>', unsafe_allow_html=True)
|
| 254 |
+
with c3:
|
| 255 |
+
st.markdown(f'<div class="stat-card"><div class="stat-value">{stats["tokens"]:,}</div><div class="stat-label">Tokens</div></div>', unsafe_allow_html=True)
|
| 256 |
+
|
| 257 |
+
c4, c5, c6 = st.columns(3)
|
| 258 |
+
with c4:
|
| 259 |
+
st.markdown(f'<div class="stat-card"><div class="stat-value">{stats["sentences"]}</div><div class="stat-label">Sentences</div></div>', unsafe_allow_html=True)
|
| 260 |
+
with c5:
|
| 261 |
+
st.markdown(f'<div class="stat-card"><div class="stat-value">{stats["estimated_read_time_min"]}m</div><div class="stat-label">Read Time</div></div>', unsafe_allow_html=True)
|
| 262 |
+
with c6:
|
| 263 |
+
st.markdown(f'<div class="stat-card"><div class="stat-value">{stats["avg_words_per_page"]}</div><div class="stat-label">Words/Page</div></div>', unsafe_allow_html=True)
|
| 264 |
+
|
| 265 |
+
st.markdown('<div class="step-label" style="margin-top:1.5rem;">Step 03 — Embed with Tarka-150M</div>', unsafe_allow_html=True)
|
| 266 |
+
|
| 267 |
+
if not st.session_state.indexed:
|
| 268 |
+
if st.button("🚀 Embed Document", use_container_width=True):
|
| 269 |
+
status_box = st.empty()
|
| 270 |
+
progress = st.progress(0)
|
| 271 |
+
|
| 272 |
+
def update_status(msg):
|
| 273 |
+
status_box.info(msg)
|
| 274 |
+
|
| 275 |
+
with st.spinner(""):
|
| 276 |
+
try:
|
| 277 |
+
update_status("Chunking document...")
|
| 278 |
+
progress.progress(15)
|
| 279 |
+
chunks = chunk_text(
|
| 280 |
+
st.session_state.doc_text,
|
| 281 |
+
chunk_size=chunk_size,
|
| 282 |
+
overlap=chunk_overlap,
|
| 283 |
+
)
|
| 284 |
+
st.session_state.chunks = chunks
|
| 285 |
+
progress.progress(30)
|
| 286 |
+
|
| 287 |
+
update_status("Loading Tarka-Embedding-150M-V1 model...")
|
| 288 |
+
progress.progress(45)
|
| 289 |
+
st.session_state.embedder.load_model(update_status)
|
| 290 |
+
progress.progress(65)
|
| 291 |
+
|
| 292 |
+
update_status(f"Embedding {len(chunks)} chunks...")
|
| 293 |
+
st.session_state.embedder.build_index(chunks, update_status)
|
| 294 |
+
progress.progress(90)
|
| 295 |
+
|
| 296 |
+
st.session_state.indexed = True
|
| 297 |
+
progress.progress(100)
|
| 298 |
+
status_box.success(f"✅ Indexed {len(chunks)} chunks! Ready to chat.")
|
| 299 |
+
|
| 300 |
+
except Exception as e:
|
| 301 |
+
status_box.error(f"Embedding failed: {e}")
|
| 302 |
+
progress.empty()
|
| 303 |
+
else:
|
| 304 |
+
st.success(f"✅ {len(st.session_state.chunks)} chunks indexed — Ready!")
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
# ─── RIGHT: Chat ──────────────────────────────────────────────────────────────
|
| 308 |
+
with col_right:
|
| 309 |
+
st.markdown('<div class="step-label">Step 04 — Ask Questions</div>', unsafe_allow_html=True)
|
| 310 |
+
|
| 311 |
+
if not st.session_state.indexed:
|
| 312 |
+
st.markdown("""
|
| 313 |
+
<div style="background:#0f172a;border:1px dashed rgba(99,102,241,0.3);
|
| 314 |
+
border-radius:12px;padding:2rem;text-align:center;color:#475569;">
|
| 315 |
+
<div style="font-size:2.5rem;margin-bottom:0.5rem;">💬</div>
|
| 316 |
+
<div style="font-family:'Space Mono',monospace;font-size:0.85rem;">
|
| 317 |
+
Upload & embed a document first<br>to start asking questions
|
| 318 |
+
</div>
|
| 319 |
+
</div>
|
| 320 |
+
""", unsafe_allow_html=True)
|
| 321 |
+
|
| 322 |
+
else:
|
| 323 |
+
# Chat history
|
| 324 |
+
for msg in st.session_state.chat_history:
|
| 325 |
+
if msg["role"] == "user":
|
| 326 |
+
st.markdown(f'<div class="chat-bubble-user">🧑 {msg["content"]}</div>', unsafe_allow_html=True)
|
| 327 |
+
else:
|
| 328 |
+
st.markdown(f'<div class="chat-bubble-ai">🤖 {msg["content"]}</div>', unsafe_allow_html=True)
|
| 329 |
+
if msg.get("chunks"):
|
| 330 |
+
with st.expander("📎 Retrieved context chunks", expanded=False):
|
| 331 |
+
for i, chunk in enumerate(msg["chunks"]):
|
| 332 |
+
st.markdown(
|
| 333 |
+
f'<div class="chunk-card">'
|
| 334 |
+
f'<span class="score-pill">score {chunk["score"]:.3f}</span> '
|
| 335 |
+
f'chunk #{chunk["index"]+1}<br><br>'
|
| 336 |
+
f'{chunk["chunk"][:300]}{"..." if len(chunk["chunk"]) > 300 else ""}'
|
| 337 |
+
f'</div>',
|
| 338 |
+
unsafe_allow_html=True,
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
st.divider()
|
| 342 |
+
with st.form("chat_form", clear_on_submit=True):
|
| 343 |
+
user_input = st.text_input(
|
| 344 |
+
"Ask a question",
|
| 345 |
+
placeholder="e.g. What is the main topic? Summarize key findings...",
|
| 346 |
+
label_visibility="collapsed",
|
| 347 |
+
)
|
| 348 |
+
col_btn1, col_btn2 = st.columns([3, 1])
|
| 349 |
+
with col_btn1:
|
| 350 |
+
submitted = st.form_submit_button("Send ↗", use_container_width=True)
|
| 351 |
+
with col_btn2:
|
| 352 |
+
clear = st.form_submit_button("Clear", use_container_width=True)
|
| 353 |
+
|
| 354 |
+
if clear:
|
| 355 |
+
st.session_state.chat_history = []
|
| 356 |
+
st.rerun()
|
| 357 |
+
|
| 358 |
+
if submitted and user_input.strip():
|
| 359 |
+
if not api_ok:
|
| 360 |
+
st.error("❌ Gemini API key not working. Check your .env file.")
|
| 361 |
+
else:
|
| 362 |
+
with st.spinner("Searching document & generating answer..."):
|
| 363 |
+
try:
|
| 364 |
+
results = st.session_state.embedder.search(user_input, top_k=top_k)
|
| 365 |
+
answer = ask_gemini(user_input, results)
|
| 366 |
+
st.session_state.chat_history.append({"role": "user", "content": user_input})
|
| 367 |
+
st.session_state.chat_history.append({
|
| 368 |
+
"role": "assistant",
|
| 369 |
+
"content": answer,
|
| 370 |
+
"chunks": results,
|
| 371 |
+
})
|
| 372 |
+
st.rerun()
|
| 373 |
+
except Exception as e:
|
| 374 |
+
st.error(f"Error: {e}")
|
| 375 |
+
|
| 376 |
+
# Suggestions
|
| 377 |
+
if not st.session_state.chat_history:
|
| 378 |
+
st.markdown('<div style="color:#475569;font-size:0.8rem;margin-top:0.5rem;">💡 Try asking:</div>', unsafe_allow_html=True)
|
| 379 |
+
suggestions = ["Summarize this document", "What are the key points?", "What is the main conclusion?"]
|
| 380 |
+
cols = st.columns(3)
|
| 381 |
+
for i, sug in enumerate(suggestions):
|
| 382 |
+
with cols[i]:
|
| 383 |
+
if st.button(sug, key=f"sug_{i}", use_container_width=True):
|
| 384 |
+
with st.spinner("Generating answer..."):
|
| 385 |
+
try:
|
| 386 |
+
results = st.session_state.embedder.search(sug, top_k=top_k)
|
| 387 |
+
answer = ask_gemini(sug, results)
|
| 388 |
+
st.session_state.chat_history.append({"role": "user", "content": sug})
|
| 389 |
+
st.session_state.chat_history.append({
|
| 390 |
+
"role": "assistant",
|
| 391 |
+
"content": answer,
|
| 392 |
+
"chunks": results,
|
| 393 |
+
})
|
| 394 |
+
st.rerun()
|
| 395 |
+
except Exception as e:
|
| 396 |
+
st.error(str(e))
|
document_processor.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import PyPDF2
|
| 3 |
+
import docx
|
| 4 |
+
import tiktoken
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def extract_text_from_pdf(file) -> tuple[str, int]:
|
| 8 |
+
"""Extract text from PDF and return (text, page_count)."""
|
| 9 |
+
reader = PyPDF2.PdfReader(file)
|
| 10 |
+
page_count = len(reader.pages)
|
| 11 |
+
text = ""
|
| 12 |
+
for page in reader.pages:
|
| 13 |
+
extracted = page.extract_text()
|
| 14 |
+
if extracted:
|
| 15 |
+
text += extracted + "\n"
|
| 16 |
+
return text.strip(), page_count
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def extract_text_from_docx(file) -> tuple[str, int]:
|
| 20 |
+
"""Extract text from DOCX and return (text, estimated_pages)."""
|
| 21 |
+
doc = docx.Document(file)
|
| 22 |
+
full_text = []
|
| 23 |
+
for para in doc.paragraphs:
|
| 24 |
+
if para.text.strip():
|
| 25 |
+
full_text.append(para.text)
|
| 26 |
+
text = "\n".join(full_text)
|
| 27 |
+
# Estimate pages: ~250 words per page
|
| 28 |
+
word_count = len(text.split())
|
| 29 |
+
estimated_pages = max(1, round(word_count / 250))
|
| 30 |
+
return text.strip(), estimated_pages
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def extract_text_from_txt(file) -> tuple[str, int]:
|
| 34 |
+
"""Extract text from TXT and return (text, estimated_pages)."""
|
| 35 |
+
text = file.read().decode("utf-8", errors="ignore")
|
| 36 |
+
word_count = len(text.split())
|
| 37 |
+
estimated_pages = max(1, round(word_count / 250))
|
| 38 |
+
return text.strip(), estimated_pages
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def extract_text(file, filename: str) -> tuple[str, int]:
|
| 42 |
+
"""Extract text from uploaded file based on extension."""
|
| 43 |
+
ext = os.path.splitext(filename)[1].lower()
|
| 44 |
+
if ext == ".pdf":
|
| 45 |
+
return extract_text_from_pdf(file)
|
| 46 |
+
elif ext == ".docx":
|
| 47 |
+
return extract_text_from_docx(file)
|
| 48 |
+
elif ext == ".txt":
|
| 49 |
+
return extract_text_from_txt(file)
|
| 50 |
+
else:
|
| 51 |
+
raise ValueError(f"Unsupported file type: {ext}. Supported: PDF, DOCX, TXT")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def count_tokens(text: str) -> int:
|
| 55 |
+
"""Count tokens using tiktoken (cl100k_base encoding)."""
|
| 56 |
+
try:
|
| 57 |
+
enc = tiktoken.get_encoding("cl100k_base")
|
| 58 |
+
return len(enc.encode(text))
|
| 59 |
+
except Exception:
|
| 60 |
+
# Fallback: approximate 1 token per 4 characters
|
| 61 |
+
return len(text) // 4
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def chunk_text(text: str, chunk_size: int = 500, overlap: int = 50) -> list[str]:
|
| 65 |
+
"""Split text into overlapping chunks by word count."""
|
| 66 |
+
words = text.split()
|
| 67 |
+
chunks = []
|
| 68 |
+
start = 0
|
| 69 |
+
while start < len(words):
|
| 70 |
+
end = start + chunk_size
|
| 71 |
+
chunk = " ".join(words[start:end])
|
| 72 |
+
chunks.append(chunk)
|
| 73 |
+
start += chunk_size - overlap
|
| 74 |
+
return [c for c in chunks if c.strip()]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def get_document_stats(text: str, page_count: int, filename: str) -> dict:
|
| 78 |
+
"""Return a stats dictionary for the uploaded document."""
|
| 79 |
+
word_count = len(text.split())
|
| 80 |
+
char_count = len(text)
|
| 81 |
+
token_count = count_tokens(text)
|
| 82 |
+
sentence_count = text.count(".") + text.count("!") + text.count("?")
|
| 83 |
+
avg_words_per_page = round(word_count / max(page_count, 1))
|
| 84 |
+
|
| 85 |
+
return {
|
| 86 |
+
"filename": filename,
|
| 87 |
+
"pages": page_count,
|
| 88 |
+
"words": word_count,
|
| 89 |
+
"characters": char_count,
|
| 90 |
+
"tokens": token_count,
|
| 91 |
+
"sentences": sentence_count,
|
| 92 |
+
"avg_words_per_page": avg_words_per_page,
|
| 93 |
+
"estimated_read_time_min": max(1, round(word_count / 200)),
|
| 94 |
+
}
|
embedder.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import faiss
|
| 3 |
+
from sentence_transformers import SentenceTransformer
|
| 4 |
+
from typing import List
|
| 5 |
+
|
| 6 |
+
MODEL_NAME = "Tarka-AIR/Tarka-Embedding-150M-V1"
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TarkaEmbedder:
|
| 10 |
+
"""Handles embedding with Tarka-Embedding-150M-V1 and FAISS vector store."""
|
| 11 |
+
|
| 12 |
+
def __init__(self):
|
| 13 |
+
self.model = None
|
| 14 |
+
self.index = None
|
| 15 |
+
self.chunks: List[str] = []
|
| 16 |
+
self.dimension = 768 # Tarka-150M output dimension
|
| 17 |
+
|
| 18 |
+
def load_model(self, status_callback=None):
|
| 19 |
+
"""Load the Tarka embedding model."""
|
| 20 |
+
if self.model is None:
|
| 21 |
+
if status_callback:
|
| 22 |
+
status_callback("Loading Tarka-Embedding-150M-V1... (first run downloads model)")
|
| 23 |
+
self.model = SentenceTransformer(
|
| 24 |
+
MODEL_NAME,
|
| 25 |
+
trust_remote_code=True,
|
| 26 |
+
tokenizer_kwargs={"padding_side": "left"},
|
| 27 |
+
)
|
| 28 |
+
if status_callback:
|
| 29 |
+
status_callback("Model loaded successfully!")
|
| 30 |
+
return self.model
|
| 31 |
+
|
| 32 |
+
def embed_chunks(self, chunks: List[str], status_callback=None) -> np.ndarray:
|
| 33 |
+
"""Embed a list of text chunks and return numpy array."""
|
| 34 |
+
if self.model is None:
|
| 35 |
+
self.load_model(status_callback)
|
| 36 |
+
|
| 37 |
+
if status_callback:
|
| 38 |
+
status_callback(f"Embedding {len(chunks)} chunks with Tarka-150M...")
|
| 39 |
+
|
| 40 |
+
embeddings = self.model.encode(
|
| 41 |
+
chunks,
|
| 42 |
+
batch_size=16,
|
| 43 |
+
show_progress_bar=False,
|
| 44 |
+
normalize_embeddings=True,
|
| 45 |
+
)
|
| 46 |
+
return np.array(embeddings, dtype=np.float32)
|
| 47 |
+
|
| 48 |
+
def build_index(self, chunks: List[str], status_callback=None):
|
| 49 |
+
"""Build FAISS index from chunks."""
|
| 50 |
+
self.chunks = chunks
|
| 51 |
+
embeddings = self.embed_chunks(chunks, status_callback)
|
| 52 |
+
|
| 53 |
+
self.index = faiss.IndexFlatIP(self.dimension)
|
| 54 |
+
self.index.add(embeddings)
|
| 55 |
+
|
| 56 |
+
if status_callback:
|
| 57 |
+
status_callback(f"FAISS index built with {self.index.ntotal} vectors.")
|
| 58 |
+
|
| 59 |
+
return self.index
|
| 60 |
+
|
| 61 |
+
def search(self, query: str, top_k: int = 5) -> List[dict]:
|
| 62 |
+
"""Search the FAISS index for the most relevant chunks."""
|
| 63 |
+
if self.index is None or not self.chunks:
|
| 64 |
+
raise ValueError("Index not built. Please embed documents first.")
|
| 65 |
+
|
| 66 |
+
query_embedding = self.model.encode(
|
| 67 |
+
[query],
|
| 68 |
+
normalize_embeddings=True,
|
| 69 |
+
)
|
| 70 |
+
query_embedding = np.array(query_embedding, dtype=np.float32)
|
| 71 |
+
|
| 72 |
+
scores, indices = self.index.search(query_embedding, min(top_k, len(self.chunks)))
|
| 73 |
+
|
| 74 |
+
results = []
|
| 75 |
+
for score, idx in zip(scores[0], indices[0]):
|
| 76 |
+
if idx != -1:
|
| 77 |
+
results.append({
|
| 78 |
+
"chunk": self.chunks[idx],
|
| 79 |
+
"score": float(score),
|
| 80 |
+
"index": int(idx),
|
| 81 |
+
})
|
| 82 |
+
return results
|
| 83 |
+
|
| 84 |
+
def reset(self):
|
| 85 |
+
"""Clear index and chunks."""
|
| 86 |
+
self.index = None
|
| 87 |
+
self.chunks = []
|
llm_handler.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import google.generativeai as genai
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
# Load .env from same folder as this file — works always
|
| 7 |
+
load_dotenv(dotenv_path=Path(__file__).parent / ".env", override=True)
|
| 8 |
+
|
| 9 |
+
MODEL_NAME = "gemini-2.5-flash"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def get_api_key() -> str:
|
| 13 |
+
"""Get API key from .env or environment."""
|
| 14 |
+
load_dotenv(dotenv_path=Path(__file__).parent / ".env", override=True)
|
| 15 |
+
key = os.getenv("GEMINI_API_KEY", "").strip()
|
| 16 |
+
return key
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def get_gemini_client():
|
| 20 |
+
"""Initialize and return Gemini client."""
|
| 21 |
+
api_key = get_api_key()
|
| 22 |
+
if not api_key or api_key == "your_gemini_api_key_here":
|
| 23 |
+
raise ValueError(
|
| 24 |
+
"GEMINI_API_KEY not set. Please add your API key to the .env file."
|
| 25 |
+
)
|
| 26 |
+
genai.configure(api_key=api_key)
|
| 27 |
+
return genai.GenerativeModel(MODEL_NAME)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def build_prompt(question: str, context_chunks: list) -> str:
|
| 31 |
+
"""Build a RAG prompt from question and retrieved context chunks."""
|
| 32 |
+
context_text = "\n\n---\n\n".join(
|
| 33 |
+
[f"[Chunk {i+1} | Relevance: {c['score']:.2f}]\n{c['chunk']}"
|
| 34 |
+
for i, c in enumerate(context_chunks)]
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
prompt = f"""You are a precise and helpful document assistant. Answer the user's question strictly based on the provided document context.
|
| 38 |
+
|
| 39 |
+
RULES:
|
| 40 |
+
- Answer ONLY from the context provided below.
|
| 41 |
+
- If the answer is not in the context, say: "I couldn't find relevant information in the document for this question."
|
| 42 |
+
- Be concise yet thorough. Use bullet points when listing multiple items.
|
| 43 |
+
- Quote directly from the document when it helps the answer.
|
| 44 |
+
- Do NOT make up information.
|
| 45 |
+
|
| 46 |
+
DOCUMENT CONTEXT:
|
| 47 |
+
{context_text}
|
| 48 |
+
|
| 49 |
+
USER QUESTION:
|
| 50 |
+
{question}
|
| 51 |
+
|
| 52 |
+
ANSWER:"""
|
| 53 |
+
return prompt
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def ask_gemini(question: str, context_chunks: list) -> str:
|
| 57 |
+
"""Send question + context to Gemini and return the answer."""
|
| 58 |
+
client = get_gemini_client()
|
| 59 |
+
prompt = build_prompt(question, context_chunks)
|
| 60 |
+
|
| 61 |
+
response = client.generate_content(
|
| 62 |
+
prompt,
|
| 63 |
+
generation_config=genai.types.GenerationConfig(
|
| 64 |
+
temperature=0.2,
|
| 65 |
+
max_output_tokens=2048,
|
| 66 |
+
),
|
| 67 |
+
)
|
| 68 |
+
return response.text
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def check_api_key() -> tuple:
|
| 72 |
+
"""Check if API key is valid."""
|
| 73 |
+
try:
|
| 74 |
+
api_key = get_api_key()
|
| 75 |
+
if not api_key or api_key == "your_gemini_api_key_here":
|
| 76 |
+
return False, "GEMINI_API_KEY not set in .env file"
|
| 77 |
+
genai.configure(api_key=api_key)
|
| 78 |
+
model = genai.GenerativeModel(MODEL_NAME)
|
| 79 |
+
response = model.generate_content(
|
| 80 |
+
"Say OK",
|
| 81 |
+
generation_config=genai.types.GenerationConfig(max_output_tokens=5),
|
| 82 |
+
)
|
| 83 |
+
return True, "API key is valid."
|
| 84 |
+
except ValueError as e:
|
| 85 |
+
return False, str(e)
|
| 86 |
+
except Exception as e:
|
| 87 |
+
return False, f"API error: {str(e)}"
|