PrajwalW commited on
Commit
dfb3884
·
verified ·
1 Parent(s): 002ca5c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -63
app.py CHANGED
@@ -1,64 +1,104 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
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()