Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -25,7 +25,7 @@ if not os.path.exists(FAISS_INDEX_DIR):
|
|
| 25 |
# Dictionary to store user-specific vectorstores
|
| 26 |
user_vectorstores = {}
|
| 27 |
|
| 28 |
-
# Custom CSS with
|
| 29 |
custom_css = """
|
| 30 |
:root {
|
| 31 |
--primary-green: #10B981;
|
|
@@ -80,16 +80,14 @@ body {
|
|
| 80 |
border-top: 1px solid var(--border-grey);
|
| 81 |
box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
|
| 82 |
padding: 10px;
|
| 83 |
-
height:
|
| 84 |
display: flex;
|
| 85 |
flex-direction: column;
|
| 86 |
z-index: 1000;
|
| 87 |
-
resize: vertical; /* Allows manual resizing */
|
| 88 |
-
overflow: hidden; /* Prevents overflow during resizing */
|
| 89 |
}
|
| 90 |
.chatbot {
|
| 91 |
flex-grow: 1;
|
| 92 |
-
overflow-y: auto;
|
| 93 |
padding: 10px;
|
| 94 |
}
|
| 95 |
.message-user {
|
|
@@ -165,14 +163,102 @@ body {
|
|
| 165 |
}
|
| 166 |
"""
|
| 167 |
|
| 168 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
# Gradio interface
|
| 171 |
with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
|
| 172 |
current_session_id = gr.State(None)
|
| 173 |
pdf_state = gr.State({"page_images": [], "total_pages": 0, "total_words": 0})
|
| 174 |
-
chat_height = gr.State(300) # Initial chatbot height in pixels
|
| 175 |
-
|
| 176 |
gr.HTML("""
|
| 177 |
<div class="header">
|
| 178 |
<div class="header-title">Fin-Vision</div>
|
|
@@ -191,8 +277,6 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
|
|
| 191 |
value="llama3-70b-8192",
|
| 192 |
label="Select Groq Model"
|
| 193 |
)
|
| 194 |
-
# Add a slider to adjust chatbot height
|
| 195 |
-
height_slider = gr.Slider(minimum=100, maximum=600, step=10, value=300, label="Chatbot Height (px)")
|
| 196 |
with gr.Column(scale=2, min_width=600):
|
| 197 |
with gr.Tabs():
|
| 198 |
with gr.TabItem("PDF Viewer"):
|
|
@@ -203,7 +287,7 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
|
|
| 203 |
|
| 204 |
# Chatbot at the bottom
|
| 205 |
with gr.Column(elem_classes="chat-container"):
|
| 206 |
-
chatbot = gr.Chatbot(elem_classes="chatbot", height=
|
| 207 |
with gr.Row(elem_classes="input-area"):
|
| 208 |
msg = gr.Textbox(show_label=False, placeholder="Ask about your financial report...", elem_classes="input-box")
|
| 209 |
send_btn = gr.Button("Send", elem_classes="send-btn")
|
|
@@ -243,13 +327,6 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
|
|
| 243 |
inputs=[page_slider, pdf_state],
|
| 244 |
outputs=[pdf_image]
|
| 245 |
)
|
| 246 |
-
|
| 247 |
-
# Update chatbot height dynamically with the slider
|
| 248 |
-
height_slider.change(
|
| 249 |
-
lambda height: gr.update(height=height),
|
| 250 |
-
inputs=[height_slider],
|
| 251 |
-
outputs=[chatbot]
|
| 252 |
-
)
|
| 253 |
|
| 254 |
# Launch the app
|
| 255 |
if __name__ == "__main__":
|
|
|
|
| 25 |
# Dictionary to store user-specific vectorstores
|
| 26 |
user_vectorstores = {}
|
| 27 |
|
| 28 |
+
# Custom CSS with green theme and modern chatbot
|
| 29 |
custom_css = """
|
| 30 |
:root {
|
| 31 |
--primary-green: #10B981;
|
|
|
|
| 80 |
border-top: 1px solid var(--border-grey);
|
| 81 |
box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
|
| 82 |
padding: 10px;
|
| 83 |
+
height: 40vh;
|
| 84 |
display: flex;
|
| 85 |
flex-direction: column;
|
| 86 |
z-index: 1000;
|
|
|
|
|
|
|
| 87 |
}
|
| 88 |
.chatbot {
|
| 89 |
flex-grow: 1;
|
| 90 |
+
overflow-y: auto;
|
| 91 |
padding: 10px;
|
| 92 |
}
|
| 93 |
.message-user {
|
|
|
|
| 163 |
}
|
| 164 |
"""
|
| 165 |
|
| 166 |
+
# Function to process PDF files
|
| 167 |
+
def process_pdf(pdf_file):
|
| 168 |
+
if pdf_file is None:
|
| 169 |
+
return None, "No file uploaded", {"page_images": [], "total_pages": 0, "total_words": 0}
|
| 170 |
+
try:
|
| 171 |
+
session_id = str(uuid.uuid4())
|
| 172 |
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as temp_file:
|
| 173 |
+
temp_file.write(pdf_file)
|
| 174 |
+
pdf_path = temp_file.name
|
| 175 |
+
|
| 176 |
+
doc = fitz.open(pdf_path)
|
| 177 |
+
texts = [page.get_text() for page in doc]
|
| 178 |
+
page_images = []
|
| 179 |
+
for page in doc:
|
| 180 |
+
pix = page.get_pixmap()
|
| 181 |
+
img_bytes = pix.tobytes("png")
|
| 182 |
+
img_base64 = base64.b64encode(img_bytes).decode("utf-8")
|
| 183 |
+
page_images.append(img_base64)
|
| 184 |
+
total_pages = len(doc)
|
| 185 |
+
total_words = sum(len(text.split()) for text in texts)
|
| 186 |
+
doc.close()
|
| 187 |
+
|
| 188 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
| 189 |
+
chunks = text_splitter.create_documents(texts)
|
| 190 |
+
|
| 191 |
+
vectorstore = FAISS.from_documents(chunks, embeddings)
|
| 192 |
+
index_path = os.path.join(FAISS_INDEX_DIR, session_id)
|
| 193 |
+
vectorstore.save_local(index_path)
|
| 194 |
+
user_vectorstores[session_id] = vectorstore
|
| 195 |
+
|
| 196 |
+
os.unlink(pdf_path)
|
| 197 |
+
pdf_state = {"page_images": page_images, "total_pages": total_pages, "total_words": total_words}
|
| 198 |
+
return session_id, f"✅ Successfully processed {len(chunks)} text chunks from your PDF", pdf_state
|
| 199 |
+
except Exception as e:
|
| 200 |
+
if "pdf_path" in locals() and os.path.exists(pdf_path):
|
| 201 |
+
os.unlink(pdf_path)
|
| 202 |
+
return None, f"Error processing PDF: {str(e)}", {"page_images": [], "total_pages": 0, "total_words": 0}
|
| 203 |
+
|
| 204 |
+
# Function to generate chatbot responses
|
| 205 |
+
def generate_response(message, session_id, model_name, history):
|
| 206 |
+
if not message:
|
| 207 |
+
return history
|
| 208 |
+
try:
|
| 209 |
+
context = ""
|
| 210 |
+
if session_id and session_id in user_vectorstores:
|
| 211 |
+
vectorstore = user_vectorstores[session_id]
|
| 212 |
+
docs = vectorstore.similarity_search(message, k=3)
|
| 213 |
+
if docs:
|
| 214 |
+
context = "\n\nRelevant information from uploaded PDF:\n" + "\n".join(f"- {doc.page_content}" for doc in docs)
|
| 215 |
+
system_prompt = "You are a financial analyst adept at summarizing reports and extracting key metrics."
|
| 216 |
+
if context:
|
| 217 |
+
system_prompt += " Use the following context to answer the question if relevant: " + context
|
| 218 |
+
completion = client.chat.completions.create(
|
| 219 |
+
model=model_name,
|
| 220 |
+
messages=[
|
| 221 |
+
{"role": "system", "content": system_prompt},
|
| 222 |
+
{"role": "user", "content": message}
|
| 223 |
+
],
|
| 224 |
+
temperature=0.7,
|
| 225 |
+
max_tokens=1024
|
| 226 |
+
)
|
| 227 |
+
response = completion.choices[0].message.content
|
| 228 |
+
history.append((message, response))
|
| 229 |
+
return history
|
| 230 |
+
except Exception as e:
|
| 231 |
+
history.append((message, f"Error generating response: {str(e)}"))
|
| 232 |
+
return history
|
| 233 |
+
|
| 234 |
+
# Function to update the PDF viewer with the first page
|
| 235 |
+
def update_pdf_viewer(pdf_state):
|
| 236 |
+
if not pdf_state["total_pages"]:
|
| 237 |
+
return 0, None, "No PDF uploaded yet"
|
| 238 |
+
try:
|
| 239 |
+
img_data = base64.b64decode(pdf_state["page_images"][0])
|
| 240 |
+
img = Image.open(io.BytesIO(img_data))
|
| 241 |
+
return pdf_state["total_pages"], img, f"**Total Pages:** {pdf_state['total_pages']}\n**Total Words:** {pdf_state['total_words']}"
|
| 242 |
+
except Exception as e:
|
| 243 |
+
print(f"Error decoding image: {e}")
|
| 244 |
+
return 0, None, "Error displaying PDF"
|
| 245 |
+
|
| 246 |
+
# Function to update the displayed PDF page based on the slider value
|
| 247 |
+
def update_image(page_num, pdf_state):
|
| 248 |
+
if not pdf_state["total_pages"] or page_num < 1 or page_num > pdf_state["total_pages"]:
|
| 249 |
+
return None
|
| 250 |
+
try:
|
| 251 |
+
img_data = base64.b64decode(pdf_state["page_images"][page_num - 1])
|
| 252 |
+
img = Image.open(io.BytesIO(img_data))
|
| 253 |
+
return img
|
| 254 |
+
except Exception as e:
|
| 255 |
+
print(f"Error decoding image: {e}")
|
| 256 |
+
return None
|
| 257 |
|
| 258 |
# Gradio interface
|
| 259 |
with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
|
| 260 |
current_session_id = gr.State(None)
|
| 261 |
pdf_state = gr.State({"page_images": [], "total_pages": 0, "total_words": 0})
|
|
|
|
|
|
|
| 262 |
gr.HTML("""
|
| 263 |
<div class="header">
|
| 264 |
<div class="header-title">Fin-Vision</div>
|
|
|
|
| 277 |
value="llama3-70b-8192",
|
| 278 |
label="Select Groq Model"
|
| 279 |
)
|
|
|
|
|
|
|
| 280 |
with gr.Column(scale=2, min_width=600):
|
| 281 |
with gr.Tabs():
|
| 282 |
with gr.TabItem("PDF Viewer"):
|
|
|
|
| 287 |
|
| 288 |
# Chatbot at the bottom
|
| 289 |
with gr.Column(elem_classes="chat-container"):
|
| 290 |
+
chatbot = gr.Chatbot(elem_classes="chatbot", height="100%", bubble_full_width=False, show_copy_button=True)
|
| 291 |
with gr.Row(elem_classes="input-area"):
|
| 292 |
msg = gr.Textbox(show_label=False, placeholder="Ask about your financial report...", elem_classes="input-box")
|
| 293 |
send_btn = gr.Button("Send", elem_classes="send-btn")
|
|
|
|
| 327 |
inputs=[page_slider, pdf_state],
|
| 328 |
outputs=[pdf_image]
|
| 329 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
|
| 331 |
# Launch the app
|
| 332 |
if __name__ == "__main__":
|