# Create a SEMANTIC-SEARCH version of the Hugging Face Space for Bejjup.ai – Polity Summarizer import os, zipfile, textwrap, json, re, pathlib base_dir = "/mnt/data/bejjup_polity_semantic_space" os.makedirs(base_dir, exist_ok=True) os.makedirs(os.path.join(base_dir, "data"), exist_ok=True) # empty data folder placeholder app_py = r'''# Bejjup.ai – Polity Summarizer (Semantic Search + PDFs) # ------------------------------------------------------ # How to deploy on Hugging Face Spaces (FREE): # 1) Create a new Space (SDK: Gradio). # 2) Upload: app.py, requirements.txt, README.md, and a folder "data/" with your PDFs. # 3) Click "Rebuild Index" once after uploading PDFs. # # What it does: # - Loads ALL PDFs from /data # - Extracts text, chunks it, builds embeddings (sentence-transformers) # - Chat: User asks question -> semantic retrieve top chunks -> summarizer answers # - Shows sources (filename + page) # # Notes: # - Uses CPU-friendly models: all-MiniLM-L6-v2 (embeddings) + BART CNN (summarizer) # - For scanned PDFs (images), text extraction won't work (needs OCR). Use text PDFs. # ------------------------------------------------------ import os import io import glob import re from dataclasses import dataclass from typing import List, Tuple, Dict import numpy as np import gradio as gr from transformers import pipeline import PyPDF2 from sentence_transformers import SentenceTransformer # ------------------- Config ------------------- EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2" SUMMARIZER_MODEL = "facebook/bart-large-cnn" CHUNK_SIZE = 1200 # characters CHUNK_OVERLAP = 250 # characters TOP_K = 6 # retrieved chunks per question MAX_CONTEXT_CHARS = 6000 # ------------------- Utilities ------------------- def clean_text(s: str) -> str: s = re.sub(r'\s+', ' ', s) return s.strip() def chunk_text(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> List[str]: text = clean_text(text) if not text: return [] chunks = [] start = 0 n = len(text) while start < n: end = min(start + size, n) chunk = text[start:end] chunks.append(chunk) start = end - overlap if start < 0: start = 0 return chunks def extract_text_from_pdf(path: str) -> List[Tuple[int, str]]: """Return list of (page_number, text) tuples (1-indexed).""" pages = [] try: with open(path, "rb") as f: reader = PyPDF2.PdfReader(f) for i, page in enumerate(reader.pages): txt = page.extract_text() or "" pages.append((i+1, clean_text(txt))) except Exception as e: print(f"[PDF ERROR] {path}: {e}") return pages @dataclass class Chunk: doc: str page: int text: str class KnowledgeIndex: def __init__(self, data_dir: str = "data"): self.data_dir = data_dir self.embedder = SentenceTransformer(EMBED_MODEL) self.summarizer = pipeline("summarization", model=SUMMARIZER_MODEL) self.chunks: List[Chunk] = [] self.embeddings: np.ndarray | None = None # shape (N, D) def build(self) -> str: """Load PDFs, create chunks, embed them.""" self.chunks.clear() self.embeddings = None pdfs = sorted(glob.glob(os.path.join(self.data_dir, "*.pdf"))) if not pdfs: return "⚠️ No PDFs found in /data. Upload your books/notes there." for pdf in pdfs: pages = extract_text_from_pdf(pdf) docname = os.path.basename(pdf) for page_num, ptext in pages: if not ptext: continue for ch in chunk_text(ptext): self.chunks.append(Chunk(doc=docname, page=page_num, text=ch)) if not self.chunks: return "⚠️ No extractable text found in PDFs (are they scanned images?)." texts = [c.text for c in self.chunks] embs = self.embedder.encode(texts, convert_to_numpy=True, normalize_embeddings=True, show_progress_bar=True) self.embeddings = embs.astype(np.float32) return f"✅ Indexed {len(pdfs)} PDFs → {len(self.chunks)} chunks." def search(self, query: str, top_k: int = TOP_K) -> List[Tuple[Chunk, float]]: if self.embeddings is None or not len(self.chunks): return [] q_emb = self.embedder.encode([query], convert_to_numpy=True, normalize_embeddings=True)[0].astype(np.float32) sims = (self.embeddings @ q_emb) # cosine since normalized idx = np.argsort(-sims)[:top_k] return [(self.chunks[i], float(sims[i])) for i in idx] def answer(self, query: str) -> Tuple[str, List[Tuple[str, int]]]: hits = self.search(query, top_k=TOP_K) if not hits: return ("⚠️ Index is empty or no relevant chunks found. Click 'Rebuild Index' after adding PDFs to /data.", []) # Build context from top chunks ctx_parts = [] sources = [] current_len = 0 for chunk, score in hits: if current_len >= MAX_CONTEXT_CHARS: break ctx_parts.append(chunk.text) current_len += len(chunk.text) sources.append((chunk.doc, chunk.page)) context = "\n\n".join(ctx_parts) prompt = f"Context:\n{context}\n\nQuestion: {query}\n\nProvide a crisp UPSC-ready summary (bullet points if suitable)." # Summarize answer max_len = 250 min_len = 80 output = self.summarizer(prompt, max_length=max_len, min_length=min_len, do_sample=False)[0]["summary_text"] return output.strip(), sources # Singleton index INDEX = KnowledgeIndex() # ------------------- Gradio UI ------------------- with gr.Blocks(title="Bejjup.ai – Polity Summarizer (Semantic)") as demo: gr.Markdown("# 🔵 Bejjup.ai – Polity Summarizer (Semantic Search)\nUpload your polity PDFs into `/data` (repository) → click **Rebuild Index** once → start asking!") with gr.Row(): build_btn = gr.Button("🔁 Rebuild Index", variant="secondary") build_status = gr.Markdown("*(Upload your PDFs to `/data/` then click Rebuild Index)*") with gr.Row(): chatbot = gr.Chatbot(height=420) query = gr.Textbox(placeholder="Ask anything from Indian Polity… e.g., 'Explain Fundamental Rights vs DPSP'", label="Your Question") def do_build(): msg = INDEX.build() return msg def respond(message, chat_history): if not message or not message.strip(): return "", chat_history answer, sources = INDEX.answer(message) # format sources if sources: unique = [] for s in sources: if s not in unique: unique.append(s) src_md = "\n".join([f"- {doc} (p.{pg})" for doc, pg in unique]) answer = f"### 📘 Answer\n{answer}\n\n**Sources:**\n{src_md}" chat_history.append((message, answer)) return "", chat_history build_btn.click(fn=do_build, inputs=None, outputs=build_status) query.submit(fn=respond, inputs=[query, chatbot], outputs=[query, chatbot]) if __name__ == "__main__": demo.launch() ''' requirements_txt = r'''gradio>=4.44.0 transformers>=4.44.0 torch>=2.2.0 PyPDF2>=3.0.0 sentence-transformers>=3.0.0 numpy>=1.24.0 ''' readme_md = r'''# Bejjup.ai – Polity Summarizer (Semantic Search, PDFs) **Zero-student-upload workflow**: You upload your polity PDFs once into `/data/`. The app builds a semantic index and answers students' questions from your notes. ## 🚀 Deploy (Free, Hugging Face Spaces) 1. Create a Space (SDK: **Gradio**). 2. Upload files: `app.py`, `requirements.txt`, `README.md`. 3. Create a folder **`data/`** in the Space and upload your **PDFs** there (e.g., `laxmikant.pdf`, `fr_dpsp.pdf`). 4. Click the **Rebuild Index** button in the live app once. Done. ## 🧠 How it works - Extracts text from all PDFs in `/data` (text PDFs, not scanned images). - Splits into overlapping chunks; embeds with **all-MiniLM-L6-v2**. - Retrieves top relevant chunks via cosine similarity. - Summarizes into an UPSC-ready answer using **BART CNN**. ## ⚠️ Notes - Scanned/image PDFs need OCR; this app does not perform OCR. - CPU-only; for very large books, first build may take a few minutes. - Add/remove PDFs any time → click **Rebuild Index** to refresh the knowledge base. ## 🧩 Future upgrades - GPU Space for faster builds (paid) - Citation highlighting with exact page snippets - CSV export of Q&A sessions for analytics ''' # write files with open(os.path.join(base_dir, "app.py"), "w", encoding="utf-8") as f: f.write(app_py) with open(os.path.join(base_dir, "requirements.txt"), "w", encoding="utf-8") as f: f.write(requirements_txt) with open(os.path.join(base_dir, "README.md"), "w", encoding="utf-8") as f: f.write(readme_md) # Create zip for download zip_path = "/mnt/data/bejjup_polity_semantic_space.zip" with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as z: z.write(os.path.join(base_dir, "app.py"), arcname="app.py") z.write(os.path.join(base_dir, "requirements.txt"), arcname="requirements.txt") z.write(os.path.join(base_dir, "README.md"), arcname="README.md") # include empty data/ placeholder z.writestr("data/README.txt", "Put your polity PDFs in this folder, then click 'Rebuild Index' in the app.") zip_path