Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,134 +1,81 @@
|
|
1 |
-
we want to build RAG base application in which 3 to 4 different PDF documents will be placed at github . Application will be deployed on hugging face using streamlit interface. our objective is user will inquire the query and our application will give pin point answer and very short but comprehensive summary upto maximum 250 words about that particular question. i already developed an application but it asks to upload document on run time means on user interface and then extract information. similarly we need only query block and it should extract required info from different Pdfs and give pin point answer. Sample of code is given below nad amend its as per requirement:
|
2 |
-
|
3 |
from PyPDF2 import PdfReader
|
4 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
5 |
-
from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
|
6 |
from langchain.vectorstores import FAISS
|
7 |
-
from
|
8 |
-
from langchain.prompts import PromptTemplate
|
9 |
-
import google.generativeai as genai
|
10 |
import streamlit as st
|
|
|
|
|
11 |
|
12 |
-
#
|
13 |
-
|
14 |
-
genai.configure(api_key=GOOGLE_API_KEY)
|
15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
-
|
18 |
-
def get_pdf_text(pdf_docs):
|
19 |
text = ""
|
20 |
-
for
|
21 |
-
|
22 |
-
if
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
text += page_text
|
32 |
return text
|
33 |
|
34 |
-
|
35 |
@st.cache_data
|
36 |
def get_text_chunks(text):
|
37 |
text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
|
38 |
chunks = text_splitter.split_text(text)
|
39 |
return chunks
|
40 |
|
41 |
-
|
42 |
@st.cache_resource
|
43 |
def load_or_create_vector_store(text_chunks):
|
44 |
-
|
45 |
-
raise ValueError("Text chunks are empty. Cannot create vector store.")
|
46 |
-
|
47 |
-
embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=GOOGLE_API_KEY)
|
48 |
vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
|
49 |
-
vector_store.save_local("faiss_index")
|
50 |
return vector_store
|
51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
52 |
|
53 |
-
def
|
54 |
-
prompt_template = """
|
55 |
-
Answer the question as detailed as possible from the provided context. If the answer is not in the provided context, say "answer is not available in the context".
|
56 |
-
|
57 |
-
Context:\n {context}?\n
|
58 |
-
Question: \n{question}\n
|
59 |
-
|
60 |
-
Answer:
|
61 |
-
"""
|
62 |
-
model = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0.3, google_api_key=GOOGLE_API_KEY)
|
63 |
-
prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
|
64 |
-
chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
|
65 |
-
return chain
|
66 |
-
|
67 |
-
|
68 |
-
def user_input(user_question, chain, vector_store):
|
69 |
docs = vector_store.similarity_search(user_question)
|
70 |
-
|
71 |
-
|
72 |
-
return_only_outputs=True
|
73 |
-
)
|
74 |
-
return response['output_text']
|
75 |
-
|
76 |
|
77 |
def main():
|
78 |
-
st.set_page_config(page_title="
|
79 |
-
st.title("π
|
80 |
-
|
81 |
-
# Initialize chat history and vector store in session state
|
82 |
-
if 'chat_history' not in st.session_state:
|
83 |
-
st.session_state.chat_history = []
|
84 |
-
if 'vector_store' not in st.session_state:
|
85 |
-
st.session_state.vector_store = None
|
86 |
-
|
87 |
-
# Sidebar for PDF upload
|
88 |
-
st.sidebar.title("Upload PDF")
|
89 |
-
pdf_docs = st.sidebar.file_uploader("Upload your PDF Files", type=["pdf"], accept_multiple_files=True)
|
90 |
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
text_chunks = get_text_chunks(raw_text)
|
96 |
-
|
97 |
-
if not text_chunks:
|
98 |
-
st.error("No text extracted from the PDFs. Please check the content.")
|
99 |
-
else:
|
100 |
-
st.session_state.vector_store = load_or_create_vector_store(text_chunks)
|
101 |
-
st.success("PDF processed successfully!")
|
102 |
-
|
103 |
-
st.sidebar.markdown("---")
|
104 |
-
st.sidebar.markdown(
|
105 |
-
"<footer style='text-align: center;'>Created by <span style='font-weight: 600;'>Ghulam Mahiyudin</span></footer>",
|
106 |
-
unsafe_allow_html=True)
|
107 |
-
|
108 |
-
# Create conversational chain
|
109 |
-
chain = get_conversational_chain()
|
110 |
|
111 |
# User question input
|
112 |
user_question = st.text_input("Ask a Question:", placeholder="Type your question here...")
|
113 |
|
114 |
if st.button("Get Response"):
|
115 |
-
# Validate user input
|
116 |
if not user_question:
|
117 |
st.warning("Please enter a question before submitting.")
|
118 |
-
elif st.session_state.vector_store is None:
|
119 |
-
st.warning("Please upload and process a PDF document before asking a question.")
|
120 |
else:
|
121 |
with st.spinner("Generating response..."):
|
122 |
-
answer = user_input(user_question,
|
123 |
-
|
124 |
-
st.session_state.chat_history.insert(0, (user_question, answer)) # Insert at the top
|
125 |
-
|
126 |
-
# Display chat history with styling
|
127 |
-
if st.session_state.chat_history:
|
128 |
-
for question, answer in st.session_state.chat_history:
|
129 |
-
st.write("---")
|
130 |
-
st.markdown(f"**π€ You:** _{question}_")
|
131 |
-
st.markdown(f"**π€ AI:** {answer}")
|
132 |
|
133 |
if __name__ == "__main__":
|
134 |
-
main()
|
|
|
|
|
|
|
1 |
from PyPDF2 import PdfReader
|
2 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
|
3 |
from langchain.vectorstores import FAISS
|
4 |
+
from transformers import pipeline
|
|
|
|
|
5 |
import streamlit as st
|
6 |
+
import requests
|
7 |
+
from io import BytesIO
|
8 |
|
9 |
+
# Set up Hugging Face model pipeline for text generation
|
10 |
+
pipe = pipeline("text-generation", model="meta-llama/Llama-Guard-3-8B-INT8")
|
|
|
11 |
|
12 |
+
# List of GitHub PDF URLs
|
13 |
+
PDF_URLS = [
|
14 |
+
"https://github.com/TahirSher/GenAI_Lawyers_Guide/blob/main/bi%20pat%20graphs.pdf",
|
15 |
+
"https://github.com/TahirSher/GenAI_Lawyers_Guide/blob/main/bi-partite.pdf",
|
16 |
+
# Add more document links as needed
|
17 |
+
]
|
18 |
|
19 |
+
def fetch_pdf_text_from_github(urls):
|
|
|
20 |
text = ""
|
21 |
+
for url in urls:
|
22 |
+
response = requests.get(url)
|
23 |
+
if response.status_code == 200:
|
24 |
+
pdf_file = BytesIO(response.content)
|
25 |
+
pdf_reader = PdfReader(pdf_file)
|
26 |
+
for page in pdf_reader.pages:
|
27 |
+
page_text = page.extract_text()
|
28 |
+
if page_text:
|
29 |
+
text += page_text
|
30 |
+
else:
|
31 |
+
st.error(f"Failed to fetch PDF from URL: {url}")
|
|
|
32 |
return text
|
33 |
|
|
|
34 |
@st.cache_data
|
35 |
def get_text_chunks(text):
|
36 |
text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
|
37 |
chunks = text_splitter.split_text(text)
|
38 |
return chunks
|
39 |
|
|
|
40 |
@st.cache_resource
|
41 |
def load_or_create_vector_store(text_chunks):
|
42 |
+
embeddings = FAISS.get_default_embeddings()
|
|
|
|
|
|
|
43 |
vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
|
|
|
44 |
return vector_store
|
45 |
|
46 |
+
def generate_answer(user_question, context_text):
|
47 |
+
# Format the input message for the pipeline
|
48 |
+
messages = [
|
49 |
+
{"role": "user", "content": f"Context: {context_text}\nQuestion: {user_question}"}
|
50 |
+
]
|
51 |
+
# Generate response using the pipeline
|
52 |
+
response = pipe(messages, max_length=250, do_sample=True)
|
53 |
+
return response[0]['generated_text'][:250] # Limit response to 250 characters
|
54 |
|
55 |
+
def user_input(user_question, vector_store):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
docs = vector_store.similarity_search(user_question)
|
57 |
+
context_text = " ".join([doc.page_content for doc in docs])
|
58 |
+
return generate_answer(user_question, context_text)
|
|
|
|
|
|
|
|
|
59 |
|
60 |
def main():
|
61 |
+
st.set_page_config(page_title="RAG-based PDF Chat", layout="centered", page_icon="π")
|
62 |
+
st.title("π Query PDF Documents on GitHub")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
64 |
+
# Load documents from GitHub
|
65 |
+
raw_text = fetch_pdf_text_from_github(PDF_URLS)
|
66 |
+
text_chunks = get_text_chunks(raw_text)
|
67 |
+
vector_store = load_or_create_vector_store(text_chunks)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
# User question input
|
70 |
user_question = st.text_input("Ask a Question:", placeholder="Type your question here...")
|
71 |
|
72 |
if st.button("Get Response"):
|
|
|
73 |
if not user_question:
|
74 |
st.warning("Please enter a question before submitting.")
|
|
|
|
|
75 |
else:
|
76 |
with st.spinner("Generating response..."):
|
77 |
+
answer = user_input(user_question, vector_store)
|
78 |
+
st.markdown(f"**π€ AI:** {answer}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
|
80 |
if __name__ == "__main__":
|
81 |
+
main()
|