Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
import fitz # PyMuPDF
|
4 |
+
from sentence_transformers import SentenceTransformer
|
5 |
+
import numpy as np
|
6 |
+
import faiss
|
7 |
+
from typing import List, Tuple, Dict
|
8 |
+
from google.generativeai import GenerativeModel, configure, types
|
9 |
+
|
10 |
+
# Set up the Google API for the Gemini model
|
11 |
+
GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
|
12 |
+
configure(api_key=GOOGLE_API_KEY)
|
13 |
+
|
14 |
+
# Placeholder for the app's state
|
15 |
+
class MyApp:
|
16 |
+
def __init__(self) -> None:
|
17 |
+
self.documents = []
|
18 |
+
self.embeddings = None
|
19 |
+
self.index = None
|
20 |
+
self.model = SentenceTransformer('all-MiniLM-L6-v2')
|
21 |
+
|
22 |
+
def load_pdfs(self, files: List[gr.File]) -> str:
|
23 |
+
"""Extracts text from multiple PDF files and stores them."""
|
24 |
+
self.documents = []
|
25 |
+
for file in files:
|
26 |
+
doc = fitz.open(stream=file.read(), filetype="pdf")
|
27 |
+
for page_num in range(len(doc)):
|
28 |
+
page = doc[page_num]
|
29 |
+
text = page.get_text()
|
30 |
+
self.documents.append({
|
31 |
+
"file_name": file.name,
|
32 |
+
"page": page_num + 1,
|
33 |
+
"content": text
|
34 |
+
})
|
35 |
+
return f"Processed {len(files)} PDFs successfully!"
|
36 |
+
|
37 |
+
def build_vector_db(self) -> str:
|
38 |
+
"""Builds a vector database using the content of the PDFs."""
|
39 |
+
if not self.documents:
|
40 |
+
return "No documents to process."
|
41 |
+
contents = [doc["content"] for doc in self.documents]
|
42 |
+
self.embeddings = self.model.encode(contents, show_progress_bar=True)
|
43 |
+
self.index = faiss.IndexFlatL2(self.embeddings.shape[1])
|
44 |
+
self.index.add(np.array(self.embeddings))
|
45 |
+
return "Vector database built successfully!"
|
46 |
+
|
47 |
+
def search_documents(self, query: str, k: int = 3) -> List[Dict]:
|
48 |
+
"""Searches for relevant document snippets using vector similarity."""
|
49 |
+
if not self.index:
|
50 |
+
return [{"content": "Vector database is not built."}]
|
51 |
+
query_embedding = self.model.encode([query], show_progress_bar=False)
|
52 |
+
D, I = self.index.search(np.array(query_embedding), k)
|
53 |
+
results = [self.documents[i] for i in I[0]]
|
54 |
+
return results if results else [{"content": "No relevant documents found."}]
|
55 |
+
|
56 |
+
app = MyApp()
|
57 |
+
|
58 |
+
def upload_files(files: List[gr.File]) -> str:
|
59 |
+
return app.load_pdfs(files)
|
60 |
+
|
61 |
+
def build_vector_db() -> str:
|
62 |
+
return app.build_vector_db()
|
63 |
+
|
64 |
+
def respond(message: str, history: List[Tuple[str, str]]) -> Tuple[List[Tuple[str, str]], str]:
|
65 |
+
system_message = (
|
66 |
+
"You are a helpful assistant designed to assist with studying and learning. "
|
67 |
+
"You analyze uploaded PDF documents and provide clear, concise responses "
|
68 |
+
"to any questions based on the content. You strive to be accurate, detailed, "
|
69 |
+
"and educational in your responses."
|
70 |
+
)
|
71 |
+
messages = [{"role": "system", "content": system_message}]
|
72 |
+
|
73 |
+
for user_msg, assistant_msg in history:
|
74 |
+
if user_msg:
|
75 |
+
messages.append({"role": "user", "content": user_msg})
|
76 |
+
if assistant_msg:
|
77 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
78 |
+
|
79 |
+
messages.append({"role": "user", "content": message})
|
80 |
+
|
81 |
+
# Retrieve relevant documents
|
82 |
+
retrieved_docs = app.search_documents(message)
|
83 |
+
context = "\n".join(
|
84 |
+
[f"File: {doc['file_name']}, Page: {doc['page']}\n{doc['content'][:200]}..." for doc in retrieved_docs]
|
85 |
+
)
|
86 |
+
|
87 |
+
# Generate response using the generative model
|
88 |
+
model = GenerativeModel("gemini-1.5-pro-latest")
|
89 |
+
generation_config = types.GenerationConfig(
|
90 |
+
temperature=0.7,
|
91 |
+
max_output_tokens=1024,
|
92 |
+
)
|
93 |
+
|
94 |
+
try:
|
95 |
+
response = model.generate_content([context + "\nQuestion: " + message], generation_config=generation_config)
|
96 |
+
response_content = response.text if hasattr(response, "text") else "No response generated."
|
97 |
+
except Exception as e:
|
98 |
+
response_content = f"An error occurred while generating the response: {str(e)}"
|
99 |
+
|
100 |
+
# Append the message and generated response to the chat history
|
101 |
+
history.append((message, response_content))
|
102 |
+
return history, ""
|
103 |
+
|
104 |
+
with gr.Blocks() as demo:
|
105 |
+
gr.Markdown("# Study Assistant Chatbot")
|
106 |
+
gr.Markdown("Upload your PDFs, build a vector database, and ask questions to learn efficiently.")
|
107 |
+
|
108 |
+
with gr.Row():
|
109 |
+
with gr.Column():
|
110 |
+
upload_btn = gr.File(label="Upload PDFs", file_types=[".pdf"], file_count="multiple")
|
111 |
+
upload_message = gr.Textbox(label="Upload Status", lines=2)
|
112 |
+
build_db_btn = gr.Button("Build Vector Database")
|
113 |
+
db_message = gr.Textbox(label="DB Build Status", lines=2)
|
114 |
+
|
115 |
+
upload_btn.change(upload_files, inputs=[upload_btn], outputs=[upload_message])
|
116 |
+
build_db_btn.click(build_vector_db, inputs=[], outputs=[db_message])
|
117 |
+
|
118 |
+
with gr.Column():
|
119 |
+
chatbot = gr.Chatbot(label="Chat Responses")
|
120 |
+
query_input = gr.Textbox(label="Enter your query here")
|
121 |
+
submit_btn = gr.Button("Submit")
|
122 |
+
submit_btn.click(respond, inputs=[query_input, chatbot], outputs=[chatbot, query_input])
|
123 |
+
|
124 |
+
demo.launch()
|