Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
import time
|
4 |
+
from datetime import datetime
|
5 |
+
from langchain_community.document_loaders import PyPDFLoader, TextLoader, Docx2txtLoader
|
6 |
+
from langchain_community.vectorstores import Chroma
|
7 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
8 |
+
from langchain_huggingface import HuggingFaceEndpoint, HuggingFaceEmbeddings
|
9 |
+
from langchain.chains import ConversationalRetrievalChain
|
10 |
+
from langchain.memory import ConversationBufferMemory
|
11 |
+
from pptx import Presentation
|
12 |
+
from io import BytesIO
|
13 |
+
|
14 |
+
# Environment setup for Hugging Face token
|
15 |
+
os.environ["HUGGINGFACEHUB_API_TOKEN"] = os.getenv("HUGGINGFACEHUB_API_TOKEN", "your-hf-token-here")
|
16 |
+
|
17 |
+
# Model and embedding options
|
18 |
+
LLM_MODELS = {
|
19 |
+
"Lightweight (Gemma-2B)": "google/gemma-2b-it",
|
20 |
+
"Balanced (Mixtral-8x7B)": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
21 |
+
"High Accuracy (Llama-3-8B)": "meta-llama/Llama-3-8b-hf"
|
22 |
+
}
|
23 |
+
|
24 |
+
EMBEDDING_MODELS = {
|
25 |
+
"Lightweight (MiniLM-L6)": "sentence-transformers/all-MiniLM-L6-v2",
|
26 |
+
"Balanced (MPNet-Base)": "sentence-transformers/all-mpnet-base-v2",
|
27 |
+
"High Accuracy (BGE-Large)": "BAAI/bge-large-en-v1.5"
|
28 |
+
}
|
29 |
+
|
30 |
+
# Global state
|
31 |
+
vector_store = None
|
32 |
+
qa_chain = None
|
33 |
+
chat_history = []
|
34 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
35 |
+
|
36 |
+
# Custom PPTX loader
|
37 |
+
class PPTXLoader:
|
38 |
+
def __init__(self, file_path):
|
39 |
+
self.file_path = file_path
|
40 |
+
|
41 |
+
def load(self):
|
42 |
+
docs = []
|
43 |
+
with open(self.file_path, "rb") as f:
|
44 |
+
prs = Presentation(BytesIO(f.read()))
|
45 |
+
for slide_num, slide in enumerate(prs.slides, 1):
|
46 |
+
text = ""
|
47 |
+
for shape in slide.shapes:
|
48 |
+
if hasattr(shape, "text"):
|
49 |
+
text += shape.text + "\n"
|
50 |
+
if text.strip():
|
51 |
+
docs.append({"page_content": text, "metadata": {"source": self.file_path, "slide": slide_num}})
|
52 |
+
return docs
|
53 |
+
|
54 |
+
# Function to load documents
|
55 |
+
def load_documents(files):
|
56 |
+
documents = []
|
57 |
+
for file in files:
|
58 |
+
file_path = file.name
|
59 |
+
if file_path.endswith(".pdf"):
|
60 |
+
loader = PyPDFLoader(file_path)
|
61 |
+
documents.extend(loader.load())
|
62 |
+
elif file_path.endswith(".txt"):
|
63 |
+
loader = TextLoader(file_path)
|
64 |
+
documents.extend(loader.load())
|
65 |
+
elif file_path.endswith(".docx"):
|
66 |
+
loader = Docx2txtLoader(file_path)
|
67 |
+
documents.extend(loader.load())
|
68 |
+
elif file_path.endswith(".pptx"):
|
69 |
+
loader = PPTXLoader(file_path)
|
70 |
+
documents.extend([{"page_content": doc["page_content"], "metadata": doc["metadata"]} for doc in loader.load()])
|
71 |
+
return documents
|
72 |
+
|
73 |
+
# Function to process documents and create vector store
|
74 |
+
def process_documents(files, chunk_size, chunk_overlap, embedding_model):
|
75 |
+
global vector_store, qa_chain
|
76 |
+
if not files:
|
77 |
+
return "Please upload at least one document.", None
|
78 |
+
|
79 |
+
# Load documents
|
80 |
+
documents = load_documents(files)
|
81 |
+
if not documents:
|
82 |
+
return "No valid documents loaded.", None
|
83 |
+
|
84 |
+
# Split documents
|
85 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
86 |
+
chunk_size=int(chunk_size),
|
87 |
+
chunk_overlap=int(chunk_overlap),
|
88 |
+
length_function=len
|
89 |
+
)
|
90 |
+
doc_splits = text_splitter.split_documents(documents)
|
91 |
+
|
92 |
+
# Create embeddings
|
93 |
+
embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODELS[embedding_model])
|
94 |
+
|
95 |
+
# Create vector store
|
96 |
+
try:
|
97 |
+
vector_store = Chroma.from_documents(doc_splits, embeddings, persist_directory="./chroma_db")
|
98 |
+
return f"Processed {len(documents)} documents into {len(doc_splits)} chunks.", None
|
99 |
+
except Exception as e:
|
100 |
+
return f"Error processing documents: {str(e)}", None
|
101 |
+
|
102 |
+
# Function to initialize QA chain
|
103 |
+
def initialize_qa_chain(llm_model, temperature):
|
104 |
+
global qa_chain
|
105 |
+
try:
|
106 |
+
llm = HuggingFaceEndpoint(
|
107 |
+
repo_id=LLM_MODELS[llm_model],
|
108 |
+
temperature=float(temperature),
|
109 |
+
max_length=512,
|
110 |
+
huggingfacehub_api_token=os.environ["HUGGINGFACEHUB_API_TOKEN"]
|
111 |
+
)
|
112 |
+
qa_chain = ConversationalRetrievalChain.from_llm(
|
113 |
+
llm=llm,
|
114 |
+
retriever=vector_store.as_retriever(search_kwargs={"k": 3}),
|
115 |
+
memory=memory
|
116 |
+
)
|
117 |
+
return "QA chain initialized successfully.", None
|
118 |
+
except Exception as e:
|
119 |
+
return f"Error initializing QA chain: {str(e)}", None
|
120 |
+
|
121 |
+
# Function to handle user query
|
122 |
+
def answer_question(question, llm_model, embedding_model, temperature, chunk_size, chunk_overlap):
|
123 |
+
global chat_history
|
124 |
+
if not vector_store or not qa_chain:
|
125 |
+
return "Please upload documents and initialize the QA chain.", chat_history
|
126 |
+
|
127 |
+
try:
|
128 |
+
response = qa_chain({"question": question})["answer"]
|
129 |
+
chat_history.append(("User", question))
|
130 |
+
chat_history.append(("Bot", response))
|
131 |
+
return response, chat_history
|
132 |
+
except Exception as e:
|
133 |
+
return f"Error answering question: {str(e)}", chat_history
|
134 |
+
|
135 |
+
# Function to export chat history
|
136 |
+
def export_chat():
|
137 |
+
if not chat_history:
|
138 |
+
return "No chat history to export.", None
|
139 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
140 |
+
filename = f"chat_history_{timestamp}.txt"
|
141 |
+
with open(filename, "w") as f:
|
142 |
+
for role, message in chat_history:
|
143 |
+
f.write(f"{role}: {message}\n\n")
|
144 |
+
return f"Chat history exported to {filename}.", filename
|
145 |
+
|
146 |
+
# Function to reset the app
|
147 |
+
def reset_app():
|
148 |
+
global vector_store, qa_chain, chat_history, memory
|
149 |
+
vector_store = None
|
150 |
+
qa_chain = None
|
151 |
+
chat_history = []
|
152 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
153 |
+
if os.path.exists("./chroma_db"):
|
154 |
+
import shutil
|
155 |
+
shutil.rmtree("./chroma_db")
|
156 |
+
return "App reset successfully.", None
|
157 |
+
|
158 |
+
# Gradio interface
|
159 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="DocTalk: Document Q&A Chatbot") as demo:
|
160 |
+
gr.Markdown("# DocTalk: Document Q&A Chatbot")
|
161 |
+
gr.Markdown("Upload documents (PDF, TXT, DOCX, PPTX), select models, tune parameters, and ask questions!")
|
162 |
+
|
163 |
+
with gr.Row():
|
164 |
+
with gr.Column(scale=2):
|
165 |
+
file_upload = gr.Files(label="Upload Documents", file_types=[".pdf", ".txt", ".docx", ".pptx"])
|
166 |
+
with gr.Row():
|
167 |
+
process_button = gr.Button("Process Documents")
|
168 |
+
reset_button = gr.Button("Reset App")
|
169 |
+
status = gr.Textbox(label="Status", interactive=False)
|
170 |
+
|
171 |
+
with gr.Column(scale=1):
|
172 |
+
llm_model = gr.Dropdown(choices=list(LLM_MODELS.keys()), label="Select LLM Model", value="Lightweight (Gemma-2B)")
|
173 |
+
embedding_model = gr.Dropdown(choices=list(EMBEDDING_MODELS.keys()), label="Select Embedding Model", value="Lightweight (MiniLM-L6)")
|
174 |
+
temperature = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0.7, label="Temperature")
|
175 |
+
chunk_size = gr.Slider(minimum=500, maximum=2000, step=100, value=1000, label="Chunk Size")
|
176 |
+
chunk_overlap = gr.Slider(minimum=0, maximum=500, step=50, value=100, label="Chunk Overlap")
|
177 |
+
init_button = gr.Button("Initialize QA Chain")
|
178 |
+
|
179 |
+
gr.Markdown("## Chat Interface")
|
180 |
+
question = gr.Textbox(label="Ask a Question", placeholder="Type your question here...")
|
181 |
+
answer = gr.Textbox(label="Answer", interactive=False)
|
182 |
+
chat_display = gr.Chatbot(label="Chat History")
|
183 |
+
export_button = gr.Button("Export Chat History")
|
184 |
+
export_file = gr.File(label="Exported Chat File")
|
185 |
+
|
186 |
+
# Event handlers
|
187 |
+
process_button.click(
|
188 |
+
fn=process_documents,
|
189 |
+
inputs=[file_upload, chunk_size, chunk_overlap, embedding_model],
|
190 |
+
outputs=[status, chat_display]
|
191 |
+
)
|
192 |
+
init_button.click(
|
193 |
+
fn=initialize_qa_chain,
|
194 |
+
inputs=[llm_model, temperature],
|
195 |
+
outputs=[status, chat_display]
|
196 |
+
)
|
197 |
+
question.submit(
|
198 |
+
fn=answer_question,
|
199 |
+
inputs=[question, llm_model, embedding_model, temperature, chunk_size, chunk_overlap],
|
200 |
+
outputs=[answer, chat_display]
|
201 |
+
)
|
202 |
+
export_button.click(
|
203 |
+
fn=export_chat,
|
204 |
+
outputs=[status, export_file]
|
205 |
+
)
|
206 |
+
reset_button.click(
|
207 |
+
fn=reset_app,
|
208 |
+
outputs=[status, chat_display]
|
209 |
+
)
|
210 |
+
|
211 |
+
demo.launch()
|