Update app.py
Browse files
app.py
CHANGED
|
@@ -1,108 +1,172 @@
|
|
| 1 |
-
# =======================================
|
| 2 |
-
# π RAG App β Gemini +
|
| 3 |
-
# =======================================
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
import
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
import
|
| 12 |
-
import
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
# ======================
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
"""
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
# ======================
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =======================================
|
| 2 |
+
# π RAG App Pro β Gemini + Smart Embeddings (Multi-User Safe)
|
| 3 |
+
# =======================================
|
| 4 |
+
|
| 5 |
+
import os, re, shutil, textwrap, requests, uuid
|
| 6 |
+
from bs4 import BeautifulSoup
|
| 7 |
+
import google.generativeai as genai
|
| 8 |
+
from sentence_transformers import SentenceTransformer
|
| 9 |
+
import chromadb
|
| 10 |
+
import gradio as gr
|
| 11 |
+
from langchain_community.document_loaders import UnstructuredPDFLoader
|
| 12 |
+
import camelot
|
| 13 |
+
|
| 14 |
+
# ======================
|
| 15 |
+
# πΉ Gemini + Local Setup
|
| 16 |
+
# ======================
|
| 17 |
+
genai.configure(api_key="AIzaSyDr2X5N-hHt9EqUNy7JCm58aG1FpeGVpgs") # π apni Gemini key
|
| 18 |
+
MODEL = "gemini-2.5-flash"
|
| 19 |
+
|
| 20 |
+
embedder = SentenceTransformer("all-MiniLM-L6-v2")
|
| 21 |
+
chroma_client = chromadb.Client()
|
| 22 |
+
|
| 23 |
+
# ======================
|
| 24 |
+
# πΉ Utils
|
| 25 |
+
# ======================
|
| 26 |
+
def clean_text(text):
|
| 27 |
+
return re.sub(r"\s+", " ", text).strip()
|
| 28 |
+
|
| 29 |
+
def adaptive_chunk_text(text):
|
| 30 |
+
length = len(text)
|
| 31 |
+
if length < 3000:
|
| 32 |
+
size = 500
|
| 33 |
+
elif length < 10000:
|
| 34 |
+
size = 1000
|
| 35 |
+
else:
|
| 36 |
+
size = 1500
|
| 37 |
+
chunks = []
|
| 38 |
+
for i in range(0, len(text), size - 150):
|
| 39 |
+
chunks.append(text[i:i + size])
|
| 40 |
+
return chunks
|
| 41 |
+
|
| 42 |
+
def extract_pdf_text(pdf_path):
|
| 43 |
+
"""Smart PDF extractor (tables + text)"""
|
| 44 |
+
full_text = ""
|
| 45 |
+
try:
|
| 46 |
+
tables = camelot.read_pdf(pdf_path, pages="all")
|
| 47 |
+
for i, table in enumerate(tables):
|
| 48 |
+
full_text += f"\n\n[Table {i+1}]\n" + table.df.to_string(index=False)
|
| 49 |
+
except Exception:
|
| 50 |
+
pass
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
loader = UnstructuredPDFLoader(pdf_path)
|
| 54 |
+
docs = loader.load()
|
| 55 |
+
full_text += "\n\n".join([doc.page_content for doc in docs])
|
| 56 |
+
except Exception as e:
|
| 57 |
+
full_text += f"\n\n[Error extracting text: {e}]"
|
| 58 |
+
|
| 59 |
+
return clean_text(full_text)
|
| 60 |
+
|
| 61 |
+
# ======================
|
| 62 |
+
# πΉ Session Handling
|
| 63 |
+
# ======================
|
| 64 |
+
def create_user_collection():
|
| 65 |
+
"""Each user/session gets unique collection"""
|
| 66 |
+
session_id = f"user_{str(uuid.uuid4())[:8]}"
|
| 67 |
+
collection = chroma_client.create_collection(name=session_id)
|
| 68 |
+
return session_id, collection
|
| 69 |
+
|
| 70 |
+
def reset_collection(collection_name):
|
| 71 |
+
"""Delete previous data for same user"""
|
| 72 |
+
try:
|
| 73 |
+
chroma_client.delete_collection(name=collection_name)
|
| 74 |
+
except Exception:
|
| 75 |
+
pass
|
| 76 |
+
return chroma_client.create_collection(name=collection_name)
|
| 77 |
+
|
| 78 |
+
# ======================
|
| 79 |
+
# πΉ Ingestion Logic
|
| 80 |
+
# ======================
|
| 81 |
+
def ingest_source(source, from_url, collection_name):
|
| 82 |
+
# Delete previous user data
|
| 83 |
+
collection = reset_collection(collection_name)
|
| 84 |
+
|
| 85 |
+
if from_url:
|
| 86 |
+
html = requests.get(source, timeout=15).text
|
| 87 |
+
soup = BeautifulSoup(html, "html.parser")
|
| 88 |
+
text = clean_text(soup.get_text())
|
| 89 |
+
else:
|
| 90 |
+
text = extract_pdf_text(source)
|
| 91 |
+
|
| 92 |
+
if not text.strip():
|
| 93 |
+
return "β οΈ No readable text found (maybe image-only PDF)."
|
| 94 |
+
|
| 95 |
+
chunks = adaptive_chunk_text(text)
|
| 96 |
+
embeddings = embedder.encode(chunks).tolist()
|
| 97 |
+
|
| 98 |
+
for i, emb in enumerate(embeddings):
|
| 99 |
+
collection.add(ids=[f"{collection_name}_{i}"], embeddings=[emb], documents=[chunks[i]])
|
| 100 |
+
|
| 101 |
+
return f"β
[{collection_name}] Ingested {len(chunks)} chunks successfully!"
|
| 102 |
+
|
| 103 |
+
# ======================
|
| 104 |
+
# πΉ Query Logic
|
| 105 |
+
# ======================
|
| 106 |
+
def rag_query(query, collection_name):
|
| 107 |
+
try:
|
| 108 |
+
collection = chroma_client.get_collection(name=collection_name)
|
| 109 |
+
q_emb = embedder.encode([query]).tolist()
|
| 110 |
+
results = collection.query(query_embeddings=q_emb, n_results=4)
|
| 111 |
+
if not results["documents"]:
|
| 112 |
+
return "β οΈ No context found. Try ingesting data first."
|
| 113 |
+
|
| 114 |
+
context = "\n\n".join(results["documents"][0])
|
| 115 |
+
prompt = f"""
|
| 116 |
+
You are a knowledgeable AI assistant.
|
| 117 |
+
Use the context below to answer clearly and in multiple lines.
|
| 118 |
+
|
| 119 |
+
Context:
|
| 120 |
+
{context}
|
| 121 |
+
|
| 122 |
+
Question: {query}
|
| 123 |
+
Answer:
|
| 124 |
+
"""
|
| 125 |
+
response = genai.GenerativeModel(MODEL).generate_content(prompt)
|
| 126 |
+
ans = response.text.replace(". ", ".\n")
|
| 127 |
+
return ans
|
| 128 |
+
except Exception as e:
|
| 129 |
+
return f"β οΈ Error: {e}"
|
| 130 |
+
|
| 131 |
+
# ======================
|
| 132 |
+
# πΉ Gradio UI
|
| 133 |
+
# ======================
|
| 134 |
+
def start_new_session():
|
| 135 |
+
session_id, _ = create_user_collection()
|
| 136 |
+
return session_id
|
| 137 |
+
|
| 138 |
+
session_id = start_new_session()
|
| 139 |
+
|
| 140 |
+
def ingest_website(url):
|
| 141 |
+
return ingest_source(url, True, session_id)
|
| 142 |
+
|
| 143 |
+
def ingest_pdf(file):
|
| 144 |
+
return ingest_source(file.name, False, session_id)
|
| 145 |
+
|
| 146 |
+
def query_ask(q):
|
| 147 |
+
return rag_query(q, session_id)
|
| 148 |
+
|
| 149 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="emerald")) as demo:
|
| 150 |
+
gr.Markdown("# π€ Smart RAG App Pro (Gemini + Adaptive PDF + Multi-User Mode)")
|
| 151 |
+
|
| 152 |
+
gr.Markdown(f"π **Private Session ID:** `{session_id}` β Your data is isolated and auto-clears on refresh.")
|
| 153 |
+
|
| 154 |
+
with gr.Tab("π Ingest Website"):
|
| 155 |
+
url_in = gr.Textbox(label="Enter Website URL")
|
| 156 |
+
url_btn = gr.Button("Ingest Website")
|
| 157 |
+
url_out = gr.Textbox(label="Status")
|
| 158 |
+
url_btn.click(fn=ingest_website, inputs=url_in, outputs=url_out)
|
| 159 |
+
|
| 160 |
+
with gr.Tab("π Ingest PDF"):
|
| 161 |
+
pdf_in = gr.File(label="Upload PDF")
|
| 162 |
+
pdf_btn = gr.Button("Ingest PDF")
|
| 163 |
+
pdf_out = gr.Textbox(label="Status")
|
| 164 |
+
pdf_btn.click(fn=ingest_pdf, inputs=pdf_in, outputs=pdf_out)
|
| 165 |
+
|
| 166 |
+
with gr.Tab("π¬ Ask Questions"):
|
| 167 |
+
q_in = gr.Textbox(label="Ask anything from ingested data")
|
| 168 |
+
q_btn = gr.Button("Ask Gemini")
|
| 169 |
+
q_out = gr.Markdown(label="Answer")
|
| 170 |
+
q_btn.click(fn=query_ask, inputs=q_in, outputs=q_out)
|
| 171 |
+
|
| 172 |
+
demo.launch()
|