Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import groq
|
| 3 |
+
import os
|
| 4 |
+
import tempfile
|
| 5 |
+
import uuid
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
from langchain_community.document_loaders import PyPDFLoader
|
| 8 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 9 |
+
from langchain.vectorstores import FAISS
|
| 10 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
| 11 |
+
|
| 12 |
+
load_dotenv()
|
| 13 |
+
client = groq.Client(api_key=os.getenv("GROQ_FINANCE_API_KEY"))
|
| 14 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 15 |
+
|
| 16 |
+
FAISS_INDEX_DIR = "faiss_indexes_finance"
|
| 17 |
+
if not os.path.exists(FAISS_INDEX_DIR):
|
| 18 |
+
os.makedirs(FAISS_INDEX_DIR)
|
| 19 |
+
|
| 20 |
+
user_vectorstores = {}
|
| 21 |
+
|
| 22 |
+
custom_css = """
|
| 23 |
+
:root {
|
| 24 |
+
--primary-green: #10B981;
|
| 25 |
+
--dark-green: #047857;
|
| 26 |
+
--light-green: #D1FAE5;
|
| 27 |
+
--medium-grey: #6B7280;
|
| 28 |
+
--light-grey: #F3F4F6;
|
| 29 |
+
--white: #FFFFFF;
|
| 30 |
+
--border-grey: #E5E7EB;
|
| 31 |
+
}
|
| 32 |
+
body { background-color: var(--light-grey); font-family: 'Inter', sans-serif; }
|
| 33 |
+
.container { max-width: 900px !important; margin: 0 auto !important; }
|
| 34 |
+
.header { background-color: var(--white); border-bottom: 2px solid var(--border-grey); padding: 15px 0; margin-bottom: 20px; border-radius: 12px 12px 0 0; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
|
| 35 |
+
.header-title { color: var(--dark-green); font-size: 1.5rem; font-weight: 700; text-align: center; }
|
| 36 |
+
.header-subtitle { color: var(--medium-grey); font-size: 0.9rem; text-align: center; margin-top: 5px; }
|
| 37 |
+
.chat-container { border-radius: 12px !important; box-shadow: 0 4px 6px rgba(0,0,0,0.1) !important; background-color: var(--white) !important; border: 1px solid var(--border-grey) !important; }
|
| 38 |
+
.message-user { background-color: var(--primary-green) !important; color: var(--white) !important; border-radius: 18px 18px 4px 18px !important; padding: 12px 16px !important; margin-left: auto !important; max-width: 80% !important; }
|
| 39 |
+
.message-bot { background-color: var(--light-grey) !important; color: var(--medium-grey) !important; border-radius: 18px 18px 18px 4px !important; padding: 12px 16px !important; margin-right: auto !important; max-width: 80% !important; }
|
| 40 |
+
.input-area { background-color: var(--white) !important; border-top: 1px solid var(--border-grey) !important; padding: 12px !important; border-radius: 0 0 12px 12px !important; }
|
| 41 |
+
.input-box { border: 1px solid var(--border-grey) !important; border-radius: 24px !important; padding: 12px 16px !important; box-shadow: 0 2px 4px rgba(0,0,0,0.05) !important; }
|
| 42 |
+
.send-btn { background-color: var(--primary-green) !important; border-radius: 24px !important; color: var(--white) !important; padding: 10px 20px !important; font-weight: 500 !important; }
|
| 43 |
+
.clear-btn { background-color: var(--light-grey) !important; border: 1px solid var(--border-grey) !important; border-radius: 24px !important; color: var(--medium-grey) !important; padding: 8px 16px !important; font-weight: 500 !important; }
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def process_pdf(pdf_file):
|
| 47 |
+
if pdf_file is None:
|
| 48 |
+
return None, "No file uploaded"
|
| 49 |
+
try:
|
| 50 |
+
session_id = str(uuid.uuid4())
|
| 51 |
+
with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as temp_file:
|
| 52 |
+
temp_file.write(pdf_file)
|
| 53 |
+
pdf_path = temp_file.name
|
| 54 |
+
loader = PyPDFLoader(pdf_path)
|
| 55 |
+
documents = loader.load()
|
| 56 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
| 57 |
+
texts = text_splitter.split_documents(documents)
|
| 58 |
+
vectorstore = FAISS.from_documents(texts, embeddings)
|
| 59 |
+
index_path = os.path.join(FAISS_INDEX_DIR, session_id)
|
| 60 |
+
vectorstore.save_local(index_path)
|
| 61 |
+
user_vectorstores[session_id] = vectorstore
|
| 62 |
+
os.unlink(pdf_path)
|
| 63 |
+
return session_id, f"✅ Successfully processed {len(texts)} text chunks from your PDF"
|
| 64 |
+
except Exception as e:
|
| 65 |
+
if 'pdf_path' in locals() and os.path.exists(pdf_path):
|
| 66 |
+
os.unlink(pdf_path)
|
| 67 |
+
return None, f"Error processing PDF: {str(e)}"
|
| 68 |
+
|
| 69 |
+
def generate_response(message, session_id, model_name, history):
|
| 70 |
+
if not message:
|
| 71 |
+
return history
|
| 72 |
+
try:
|
| 73 |
+
context = ""
|
| 74 |
+
if session_id and session_id in user_vectorstores:
|
| 75 |
+
vectorstore = user_vectorstores[session_id]
|
| 76 |
+
docs = vectorstore.similarity_search(message, k=3)
|
| 77 |
+
if docs:
|
| 78 |
+
context = "\n\nRelevant information from uploaded PDF:\n" + "\n".join(f"- {doc.page_content}" for doc in docs)
|
| 79 |
+
system_prompt = "You are a financial analyst adept at summarizing reports and extracting key metrics."
|
| 80 |
+
if context:
|
| 81 |
+
system_prompt += " Use the following context to answer the question if relevant: " + context
|
| 82 |
+
completion = client.chat.completions.create(
|
| 83 |
+
model=model_name,
|
| 84 |
+
messages=[
|
| 85 |
+
{"role": "system", "content": system_prompt},
|
| 86 |
+
{"role": "user", "content": message}
|
| 87 |
+
],
|
| 88 |
+
temperature=0.7,
|
| 89 |
+
max_tokens=1024
|
| 90 |
+
)
|
| 91 |
+
response = completion.choices[0].message.content
|
| 92 |
+
history.append((message, response))
|
| 93 |
+
return history
|
| 94 |
+
except Exception as e:
|
| 95 |
+
history.append((message, f"Error generating response: {str(e)}"))
|
| 96 |
+
return history
|
| 97 |
+
|
| 98 |
+
with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
|
| 99 |
+
current_session_id = gr.State(None)
|
| 100 |
+
gr.HTML("""
|
| 101 |
+
<div class="header">
|
| 102 |
+
<div class="header-title">Financial Report Summarizer</div>
|
| 103 |
+
<div class="header-subtitle">Summarize financial data with Groq's LLM API</div>
|
| 104 |
+
</div>
|
| 105 |
+
""")
|
| 106 |
+
with gr.Row():
|
| 107 |
+
with gr.Column(scale=1):
|
| 108 |
+
pdf_file = gr.File(label="Upload PDF Document", file_types=[".pdf"], type="binary")
|
| 109 |
+
upload_button = gr.Button("Process PDF", variant="primary")
|
| 110 |
+
pdf_status = gr.Markdown("No PDF uploaded yet")
|
| 111 |
+
model_dropdown = gr.Dropdown(
|
| 112 |
+
choices=["llama3-70b-8192", "llama3-8b-8192", "mixtral-8x7b-32768", "gemma-7b-it"],
|
| 113 |
+
value="llama3-70b-8192",
|
| 114 |
+
label="Select Groq Model"
|
| 115 |
+
)
|
| 116 |
+
with gr.Column(scale=2):
|
| 117 |
+
chatbot = gr.Chatbot(height=500, bubble_full_width=False, show_copy_button=True, elem_classes="chat-container")
|
| 118 |
+
with gr.Row():
|
| 119 |
+
msg = gr.Textbox(show_label=False, placeholder="Ask about your financial report...", scale=5)
|
| 120 |
+
send_btn = gr.Button("Send", scale=1)
|
| 121 |
+
clear_btn = gr.Button("Clear Conversation")
|
| 122 |
+
|
| 123 |
+
upload_button.click(process_pdf, inputs=[pdf_file], outputs=[current_session_id, pdf_status])
|
| 124 |
+
msg.submit(generate_response, inputs=[msg, current_session_id, model_dropdown, chatbot], outputs=[chatbot]).then(lambda: "", None, [msg])
|
| 125 |
+
send_btn.click(generate_response, inputs=[msg, current_session_id, model_dropdown, chatbot], outputs=[chatbot]).then(lambda: "", None, [msg])
|
| 126 |
+
clear_btn.click(lambda: ([], None, "No PDF uploaded yet"), None, [chatbot, current_session_id, pdf_status])
|
| 127 |
+
|
| 128 |
+
if __name__ == "__main__":
|
| 129 |
+
demo.launch()
|