Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,9 +1,8 @@
|
|
| 1 |
import os
|
| 2 |
import shutil
|
| 3 |
-
|
| 4 |
import gradio as gr
|
| 5 |
-
from transformers import pipeline
|
| 6 |
|
|
|
|
| 7 |
from langchain_community.vectorstores import Chroma
|
| 8 |
from langchain_community.embeddings import SentenceTransformerEmbeddings
|
| 9 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
|
@@ -13,49 +12,55 @@ from langchain_core.documents import Document
|
|
| 13 |
# Global State
|
| 14 |
# =========================
|
| 15 |
retriever = None
|
| 16 |
-
|
| 17 |
|
| 18 |
# =========================
|
| 19 |
-
#
|
| 20 |
# =========================
|
| 21 |
embeddings = SentenceTransformerEmbeddings(
|
| 22 |
model_name="sentence-transformers/all-MiniLM-L6-v2",
|
| 23 |
model_kwargs={"device": "cpu"}
|
| 24 |
)
|
| 25 |
|
|
|
|
|
|
|
|
|
|
| 26 |
generator = pipeline(
|
| 27 |
-
"text2text-generation",
|
| 28 |
model="google/flan-t5-small",
|
| 29 |
-
device=-1
|
| 30 |
)
|
| 31 |
|
| 32 |
# =========================
|
| 33 |
-
# Load
|
| 34 |
# =========================
|
| 35 |
-
def load_hidden_file(
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
# =========================
|
| 44 |
-
# Build Vector
|
| 45 |
# =========================
|
| 46 |
-
def build_vector_db(
|
| 47 |
global retriever
|
| 48 |
|
| 49 |
-
if not content.strip():
|
| 50 |
-
print("β οΈ Empty document. Vector DB not created.")
|
| 51 |
-
return
|
| 52 |
-
|
| 53 |
splitter = RecursiveCharacterTextSplitter(
|
| 54 |
-
chunk_size=
|
| 55 |
chunk_overlap=100
|
| 56 |
)
|
| 57 |
|
| 58 |
-
chunks = splitter.split_text(
|
|
|
|
|
|
|
| 59 |
|
| 60 |
docs = [
|
| 61 |
Document(
|
|
@@ -65,98 +70,81 @@ def build_vector_db(content):
|
|
| 65 |
for i, chunk in enumerate(chunks)
|
| 66 |
]
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
shutil.rmtree(db_path)
|
| 71 |
|
| 72 |
db = Chroma.from_documents(
|
| 73 |
docs,
|
| 74 |
embeddings,
|
| 75 |
-
persist_directory=
|
| 76 |
)
|
| 77 |
|
| 78 |
-
retriever = db.as_retriever(search_kwargs={"k":
|
| 79 |
-
print(
|
| 80 |
|
| 81 |
# =========================
|
| 82 |
-
# RAG Answer
|
| 83 |
# =========================
|
| 84 |
def smart_answer(question):
|
| 85 |
if retriever is None:
|
| 86 |
-
return "β οΈ
|
| 87 |
|
| 88 |
-
|
| 89 |
-
docs = retriever.get_relevant_documents(question)
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
)
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
QUESTION:
|
| 105 |
-
{question}
|
| 106 |
-
|
| 107 |
-
ANSWER:
|
| 108 |
-
"""
|
| 109 |
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
|
| 117 |
-
|
| 118 |
-
answer = answer.split("ANSWER:")[-1].strip()
|
| 119 |
|
| 120 |
-
|
|
|
|
| 121 |
|
| 122 |
-
|
| 123 |
-
print(f"β οΈ Answer error: {e}")
|
| 124 |
-
return "β οΈ Error generating answer."
|
| 125 |
|
| 126 |
# =========================
|
| 127 |
# Gradio UI
|
| 128 |
# =========================
|
| 129 |
-
with gr.Blocks(title="
|
| 130 |
-
gr.Markdown(
|
| 131 |
-
"## π€ **RAG Chatbot**\n"
|
| 132 |
-
"*Ask questions about your hidden document.*"
|
| 133 |
-
)
|
| 134 |
|
| 135 |
chatbot = gr.Chatbot(height=500)
|
| 136 |
|
| 137 |
with gr.Row():
|
| 138 |
-
|
| 139 |
-
placeholder="
|
| 140 |
show_label=False
|
| 141 |
)
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
def respond(message, chat_history):
|
| 145 |
-
reply = smart_answer(message)
|
| 146 |
-
chat_history.append((message, reply))
|
| 147 |
-
return "", chat_history
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
|
|
|
|
|
|
| 151 |
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
# =========================
|
| 155 |
-
hidden_content = load_hidden_file()
|
| 156 |
-
build_vector_db(hidden_content)
|
| 157 |
|
| 158 |
# =========================
|
| 159 |
-
#
|
| 160 |
# =========================
|
| 161 |
if __name__ == "__main__":
|
|
|
|
|
|
|
| 162 |
demo.launch()
|
|
|
|
| 1 |
import os
|
| 2 |
import shutil
|
|
|
|
| 3 |
import gradio as gr
|
|
|
|
| 4 |
|
| 5 |
+
from transformers import pipeline
|
| 6 |
from langchain_community.vectorstores import Chroma
|
| 7 |
from langchain_community.embeddings import SentenceTransformerEmbeddings
|
| 8 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
|
|
|
| 12 |
# Global State
|
| 13 |
# =========================
|
| 14 |
retriever = None
|
| 15 |
+
DB_PATH = "./chromadb"
|
| 16 |
|
| 17 |
# =========================
|
| 18 |
+
# Embeddings (CPU)
|
| 19 |
# =========================
|
| 20 |
embeddings = SentenceTransformerEmbeddings(
|
| 21 |
model_name="sentence-transformers/all-MiniLM-L6-v2",
|
| 22 |
model_kwargs={"device": "cpu"}
|
| 23 |
)
|
| 24 |
|
| 25 |
+
# =========================
|
| 26 |
+
# Generator (FLAN-T5)
|
| 27 |
+
# =========================
|
| 28 |
generator = pipeline(
|
| 29 |
+
task="text2text-generation",
|
| 30 |
model="google/flan-t5-small",
|
| 31 |
+
device=-1
|
| 32 |
)
|
| 33 |
|
| 34 |
# =========================
|
| 35 |
+
# Load TXT Document
|
| 36 |
# =========================
|
| 37 |
+
def load_hidden_file(path="ai-geoth.txt"):
|
| 38 |
+
if not os.path.exists(path):
|
| 39 |
+
raise FileNotFoundError("β ai-geoth.txt NOT FOUND")
|
| 40 |
+
|
| 41 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 42 |
+
text = f.read()
|
| 43 |
+
|
| 44 |
+
if not text.strip():
|
| 45 |
+
raise ValueError("β ai-geoth.txt is EMPTY")
|
| 46 |
+
|
| 47 |
+
print(f"β
Loaded document ({len(text)} characters)")
|
| 48 |
+
return text
|
| 49 |
|
| 50 |
# =========================
|
| 51 |
+
# Build Vector DB
|
| 52 |
# =========================
|
| 53 |
+
def build_vector_db(text):
|
| 54 |
global retriever
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
splitter = RecursiveCharacterTextSplitter(
|
| 57 |
+
chunk_size=700,
|
| 58 |
chunk_overlap=100
|
| 59 |
)
|
| 60 |
|
| 61 |
+
chunks = splitter.split_text(text)
|
| 62 |
+
|
| 63 |
+
print(f"β
Split into {len(chunks)} chunks")
|
| 64 |
|
| 65 |
docs = [
|
| 66 |
Document(
|
|
|
|
| 70 |
for i, chunk in enumerate(chunks)
|
| 71 |
]
|
| 72 |
|
| 73 |
+
if os.path.exists(DB_PATH):
|
| 74 |
+
shutil.rmtree(DB_PATH)
|
|
|
|
| 75 |
|
| 76 |
db = Chroma.from_documents(
|
| 77 |
docs,
|
| 78 |
embeddings,
|
| 79 |
+
persist_directory=DB_PATH
|
| 80 |
)
|
| 81 |
|
| 82 |
+
retriever = db.as_retriever(search_kwargs={"k": 3})
|
| 83 |
+
print("β
Vector DB ready")
|
| 84 |
|
| 85 |
# =========================
|
| 86 |
+
# RAG Answer (NO SILENT FAILURES)
|
| 87 |
# =========================
|
| 88 |
def smart_answer(question):
|
| 89 |
if retriever is None:
|
| 90 |
+
return "β οΈ Vector database not initialized."
|
| 91 |
|
| 92 |
+
docs = retriever.get_relevant_documents(question)
|
|
|
|
| 93 |
|
| 94 |
+
if not docs:
|
| 95 |
+
return "β No relevant text found in document."
|
| 96 |
|
| 97 |
+
# π DEBUG: confirm text retrieval
|
| 98 |
+
context = "\n".join(d.page_content for d in docs)
|
|
|
|
| 99 |
|
| 100 |
+
prompt = (
|
| 101 |
+
"Answer the question using ONLY the context below.\n\n"
|
| 102 |
+
f"Context:\n{context}\n\n"
|
| 103 |
+
f"Question:\n{question}\n\n"
|
| 104 |
+
"Answer:"
|
| 105 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
# β NO try/except β show real errors
|
| 108 |
+
result = generator(
|
| 109 |
+
prompt,
|
| 110 |
+
max_new_tokens=150,
|
| 111 |
+
do_sample=False
|
| 112 |
+
)
|
| 113 |
|
| 114 |
+
answer = result[0]["generated_text"].strip()
|
|
|
|
| 115 |
|
| 116 |
+
if not answer:
|
| 117 |
+
return "β οΈ Model returned empty response."
|
| 118 |
|
| 119 |
+
return answer
|
|
|
|
|
|
|
| 120 |
|
| 121 |
# =========================
|
| 122 |
# Gradio UI
|
| 123 |
# =========================
|
| 124 |
+
with gr.Blocks(title="RAG Chatbot") as demo:
|
| 125 |
+
gr.Markdown("## π€ RAG Chatbot (TXT-based)")
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
chatbot = gr.Chatbot(height=500)
|
| 128 |
|
| 129 |
with gr.Row():
|
| 130 |
+
textbox = gr.Textbox(
|
| 131 |
+
placeholder="Ask about ai-geoth.txt...",
|
| 132 |
show_label=False
|
| 133 |
)
|
| 134 |
+
send = gr.Button("Send")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
+
def respond(msg, history):
|
| 137 |
+
reply = smart_answer(msg)
|
| 138 |
+
history.append((msg, reply))
|
| 139 |
+
return "", history
|
| 140 |
|
| 141 |
+
textbox.submit(respond, [textbox, chatbot], [textbox, chatbot])
|
| 142 |
+
send.click(respond, [textbox, chatbot], [textbox, chatbot])
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
# =========================
|
| 145 |
+
# Startup
|
| 146 |
# =========================
|
| 147 |
if __name__ == "__main__":
|
| 148 |
+
text = load_hidden_file()
|
| 149 |
+
build_vector_db(text)
|
| 150 |
demo.launch()
|