Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files
app.py
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
from dotenv import load_dotenv
|
4 |
+
from transformers import pipeline
|
5 |
+
from io import BytesIO
|
6 |
+
from pypdf import PdfReader
|
7 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
8 |
+
from langchain_community.vectorstores import FAISS
|
9 |
+
from main import get_index_for_pdf # Assuming 'main.py' contains this function
|
10 |
+
|
11 |
+
# Initialize session state for the app
|
12 |
+
if "vectordb" not in st.session_state:
|
13 |
+
st.session_state["vectordb"] = None
|
14 |
+
if "prompt" not in st.session_state:
|
15 |
+
st.session_state["prompt"] = [{"role": "system", "content": "none"}]
|
16 |
+
|
17 |
+
# Set the title for the Streamlit app
|
18 |
+
st.title("RAG Enhance Chatbot")
|
19 |
+
|
20 |
+
# Hugging Face API Key (avoid hardcoding for production)
|
21 |
+
load_dotenv()
|
22 |
+
HUGGINGFACE_API_KEY = os.getenv("HUGGINGFACE_API_KEY")
|
23 |
+
|
24 |
+
|
25 |
+
# st.title('Model Configuration')
|
26 |
+
# model_name = st.sidebar.selectbox(
|
27 |
+
# "Choose a Hugging Face Model",
|
28 |
+
# [
|
29 |
+
# "sentence-transformers/all-mpnet-base-v2",
|
30 |
+
# "sentence-transformers/all-MiniLM-L6-v2",
|
31 |
+
# "msmarco-distilbert-base-tas-b",
|
32 |
+
# "deepset/roberta-large-squad2",
|
33 |
+
# "facebook/dpr-ctx_encoder-single-nq-base"
|
34 |
+
# ],
|
35 |
+
# index=0 # Default model
|
36 |
+
# )
|
37 |
+
|
38 |
+
# Define the QA pipeline
|
39 |
+
qa_pipeline = pipeline(
|
40 |
+
"question-answering",
|
41 |
+
model="deepset/roberta-base-squad2", # Replace with your desired model
|
42 |
+
use_auth_token=HUGGINGFACE_API_KEY
|
43 |
+
)
|
44 |
+
|
45 |
+
# Define a prompt template for the assistant
|
46 |
+
prompt_template = """
|
47 |
+
You are a helpful Assistant who answers users' questions based on PDF extracts.
|
48 |
+
|
49 |
+
Keep your answer lengthy and if long make points.
|
50 |
+
|
51 |
+
Context information includes 'filename' and 'page'. Always reference these in your responses.
|
52 |
+
|
53 |
+
If the text is irrelevant or insufficient to answer, respond with "Not applicable."
|
54 |
+
|
55 |
+
The provided PDF content is:
|
56 |
+
{pdf_extract}
|
57 |
+
"""
|
58 |
+
|
59 |
+
# Cached function to create a vector database for the provided PDF files
|
60 |
+
@st.cache_data
|
61 |
+
def create_vectordb(files, filenames, huggingface_model_name):
|
62 |
+
# Show a spinner while creating the vector database
|
63 |
+
with st.spinner("Creating Vector Database..."):
|
64 |
+
vectordb = get_index_for_pdf(
|
65 |
+
[file.getvalue() for file in files], filenames, huggingface_model_name
|
66 |
+
)
|
67 |
+
return vectordb
|
68 |
+
|
69 |
+
# Upload PDF files using Streamlit file uploader
|
70 |
+
pdf_files = st.file_uploader("Upload your PDFs", type="pdf", accept_multiple_files=True)
|
71 |
+
|
72 |
+
# If PDF files are uploaded, create the vector database and store it in the session state
|
73 |
+
if pdf_files:
|
74 |
+
pdf_file_names = [file.name for file in pdf_files]
|
75 |
+
huggingface_model_name = "sentence-transformers/all-MiniLM-L6-v2" # Correct model name
|
76 |
+
st.session_state["vectordb"] = create_vectordb(pdf_files, pdf_file_names, huggingface_model_name)
|
77 |
+
|
78 |
+
# Display previous chat messages
|
79 |
+
for message in st.session_state["prompt"]:
|
80 |
+
if message["role"] != "system":
|
81 |
+
with st.chat_message(message["role"]):
|
82 |
+
st.write(message["content"])
|
83 |
+
|
84 |
+
# Get the user's question using Streamlit chat input
|
85 |
+
question = st.chat_input("Ask anything")
|
86 |
+
|
87 |
+
# Handle the user's question
|
88 |
+
if question:
|
89 |
+
vectordb = st.session_state.get("vectordb", None)
|
90 |
+
if not vectordb:
|
91 |
+
with st.chat_message("assistant"):
|
92 |
+
st.write("You need to upload a PDF first.")
|
93 |
+
st.stop()
|
94 |
+
|
95 |
+
# Search the vector database for similar content to the user's question
|
96 |
+
search_results = vectordb.similarity_search(question, k=3)
|
97 |
+
pdf_extract = "\n".join(
|
98 |
+
[
|
99 |
+
f"{result.page_content} (Filename: {result.metadata['filename']}, Page: {result.metadata['page']})"
|
100 |
+
for result in search_results
|
101 |
+
]
|
102 |
+
)
|
103 |
+
|
104 |
+
# Use the QA pipeline with the context
|
105 |
+
response = qa_pipeline(question=question, context=pdf_extract)
|
106 |
+
|
107 |
+
# Update the assistant's response
|
108 |
+
with st.chat_message("assistant"):
|
109 |
+
st.write(response["answer"])
|
110 |
+
|
111 |
+
# Update the session state prompt
|
112 |
+
st.session_state["prompt"].append({"role": "user", "content": question})
|
113 |
+
st.session_state["prompt"].append({"role": "assistant", "content": response["answer"]})
|
main.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
from io import BytesIO
|
3 |
+
from typing import Tuple, List
|
4 |
+
import pickle
|
5 |
+
|
6 |
+
from langchain.docstore.document import Document
|
7 |
+
from langchain.embeddings.huggingface import HuggingFaceEmbeddings
|
8 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
9 |
+
from langchain.vectorstores.faiss import FAISS
|
10 |
+
from pypdf import PdfReader
|
11 |
+
import faiss
|
12 |
+
|
13 |
+
|
14 |
+
def parse_pdf(file: BytesIO, filename: str) -> Tuple[List[str], str]:
|
15 |
+
pdf = PdfReader(file)
|
16 |
+
output = []
|
17 |
+
for page in pdf.pages:
|
18 |
+
text = page.extract_text()
|
19 |
+
text = re.sub(r"(\w+)-\n(\w+)", r"\1\2", text)
|
20 |
+
text = re.sub(r"(?<!\n\s)\n(?!\s\n)", " ", text.strip())
|
21 |
+
text = re.sub(r"\n\s*\n", "\n\n", text)
|
22 |
+
output.append(text)
|
23 |
+
return output, filename
|
24 |
+
|
25 |
+
|
26 |
+
def text_to_docs(text: List[str], filename: str) -> List[Document]:
|
27 |
+
if isinstance(text, str):
|
28 |
+
text = [text]
|
29 |
+
page_docs = [Document(page_content=page) for page in text]
|
30 |
+
for i, doc in enumerate(page_docs):
|
31 |
+
doc.metadata["page"] = i + 1
|
32 |
+
|
33 |
+
doc_chunks = []
|
34 |
+
for doc in page_docs:
|
35 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
36 |
+
chunk_size=4000,
|
37 |
+
separators=["\n\n", "\n", ".", "!", "?", ",", " ", ""],
|
38 |
+
chunk_overlap=0,
|
39 |
+
)
|
40 |
+
chunks = text_splitter.split_text(doc.page_content)
|
41 |
+
for i, chunk in enumerate(chunks):
|
42 |
+
doc = Document(
|
43 |
+
page_content=chunk, metadata={"page": doc.metadata["page"], "chunk": i}
|
44 |
+
)
|
45 |
+
doc.metadata["source"] = f"{doc.metadata['page']}-{doc.metadata['chunk']}"
|
46 |
+
doc.metadata["filename"] = filename # Add filename to metadata
|
47 |
+
doc_chunks.append(doc)
|
48 |
+
return doc_chunks
|
49 |
+
|
50 |
+
|
51 |
+
def docs_to_index(docs, huggingface_model_name):
|
52 |
+
# Using Hugging Face embeddings
|
53 |
+
embedding_model = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
|
54 |
+
index = FAISS.from_documents(docs, embedding_model)
|
55 |
+
return index
|
56 |
+
|
57 |
+
|
58 |
+
def get_index_for_pdf(pdf_files, pdf_names, huggingface_model_name):
|
59 |
+
documents = []
|
60 |
+
for pdf_file, pdf_name in zip(pdf_files, pdf_names):
|
61 |
+
text, filename = parse_pdf(BytesIO(pdf_file), pdf_name)
|
62 |
+
documents = documents + text_to_docs(text, filename)
|
63 |
+
index = docs_to_index(documents, huggingface_model_name)
|
64 |
+
return index
|