Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,104 @@
|
|
1 |
-
import
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
if __name__ == "__main__":
|
64 |
-
|
|
|
1 |
+
import os
|
2 |
+
import tempfile
|
3 |
+
import streamlit as st
|
4 |
+
from dotenv import load_dotenv
|
5 |
+
|
6 |
+
from langchain_community.document_loaders import PyPDFLoader
|
7 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
8 |
+
from langchain_community.vectorstores import Chroma
|
9 |
+
from langchain_community.embeddings import BedrockEmbeddings
|
10 |
+
from langchain_community.chat_models import BedrockChat
|
11 |
+
from langchain.chains import RetrievalQA
|
12 |
+
import boto3
|
13 |
+
|
14 |
+
# Load AWS credentials from .env if available
|
15 |
+
load_dotenv()
|
16 |
+
|
17 |
+
# Setup AWS Bedrock runtime
|
18 |
+
bedrock_runtime = boto3.client("bedrock-runtime", region_name="us-east-1")
|
19 |
+
|
20 |
+
# UI setup
|
21 |
+
st.set_page_config(page_title="PDF chatbot", layout="wide")
|
22 |
+
st.title("RAG Demo - PDF Q&A")
|
23 |
+
|
24 |
+
st.markdown("""
|
25 |
+
1. **Upload Your Documents**: You can upload multiple PDF files for processing.
|
26 |
+
|
27 |
+
2. **Ask a Question**: Then ask any question based on the documents' content.
|
28 |
+
""")
|
29 |
+
|
30 |
+
CHROMA_PATH = os.path.join(os.getcwd(), "chroma_db")
|
31 |
+
|
32 |
+
|
33 |
+
def main():
|
34 |
+
st.header("Ask a question")
|
35 |
+
|
36 |
+
# Initialize vector store with Amazon Titan Embeddings
|
37 |
+
embeddings = BedrockEmbeddings(
|
38 |
+
client=bedrock_runtime,
|
39 |
+
model_id="amazon.titan-embed-text-v1"
|
40 |
+
)
|
41 |
+
vectorstore = Chroma(
|
42 |
+
persist_directory=CHROMA_PATH,
|
43 |
+
embedding_function=embeddings
|
44 |
+
)
|
45 |
+
|
46 |
+
# Sidebar: Upload & Process PDFs
|
47 |
+
with st.sidebar:
|
48 |
+
st.title("Menu:")
|
49 |
+
uploaded_files = st.file_uploader(
|
50 |
+
"Upload PDF files and click Submit",
|
51 |
+
accept_multiple_files=True,
|
52 |
+
key="pdf_uploader"
|
53 |
+
)
|
54 |
+
if st.button("Submit & Process", key="process_button") and uploaded_files:
|
55 |
+
with st.spinner("Processing..."):
|
56 |
+
for uploaded_file in uploaded_files:
|
57 |
+
try:
|
58 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
|
59 |
+
tmp_file.write(uploaded_file.getvalue())
|
60 |
+
tmp_path = tmp_file.name
|
61 |
+
|
62 |
+
loader = PyPDFLoader(tmp_path)
|
63 |
+
pages = loader.load()
|
64 |
+
|
65 |
+
for page in pages:
|
66 |
+
page.metadata["page_number"] = pages.index(page) + 1
|
67 |
+
|
68 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
69 |
+
chunk_size=1000,
|
70 |
+
chunk_overlap=200,
|
71 |
+
separators=["\n\n", "\n", " ", ""]
|
72 |
+
)
|
73 |
+
chunks = text_splitter.split_documents(pages)
|
74 |
+
os.unlink(tmp_path)
|
75 |
+
|
76 |
+
vectorstore.add_documents(chunks)
|
77 |
+
vectorstore.persist()
|
78 |
+
|
79 |
+
except Exception as e:
|
80 |
+
st.error(f"Error processing {uploaded_file.name}: {str(e)}")
|
81 |
+
continue
|
82 |
+
|
83 |
+
st.success("Vector store updated with uploaded documents.")
|
84 |
+
|
85 |
+
# Main QA interface
|
86 |
+
user_question = st.text_input("Ask a Question from the PDF Files", key="user_question")
|
87 |
+
if user_question:
|
88 |
+
retriever = vectorstore.as_retriever(search_type='similarity', search_kwargs={'k': 5})
|
89 |
+
|
90 |
+
llm = BedrockChat(
|
91 |
+
client=bedrock_runtime,
|
92 |
+
model_id="anthropic.claude-v2", # or v2:1
|
93 |
+
model_kwargs={"temperature": 0.0}
|
94 |
+
)
|
95 |
+
|
96 |
+
chain = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever)
|
97 |
+
|
98 |
+
with st.spinner("Generating answer..."):
|
99 |
+
answer = chain.invoke({"query": user_question})
|
100 |
+
st.write("**Reply:**", answer["result"])
|
101 |
+
|
102 |
+
|
103 |
if __name__ == "__main__":
|
104 |
+
main()
|