Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import streamlit as st
|
| 3 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
| 4 |
+
from langchain.vectorstores import FAISS
|
| 5 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 6 |
+
from langchain.llms import HuggingFaceHub
|
| 7 |
+
from langchain.schema import Document
|
| 8 |
+
import requests
|
| 9 |
+
from io import BytesIO
|
| 10 |
+
import fitz # PyMuPDF
|
| 11 |
+
from dotenv import load_dotenv
|
| 12 |
+
|
| 13 |
+
# Set device based on GPU availability
|
| 14 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 15 |
+
|
| 16 |
+
# Load environment variables from .env file
|
| 17 |
+
load_dotenv()
|
| 18 |
+
|
| 19 |
+
# Hugging Face API token should now be loaded from the .env file
|
| 20 |
+
# Explicitly set the Hugging Face API token from the environment variable
|
| 21 |
+
os.environ["HUGGINGFACEHUB_API_TOKEN"] = os.getenv("HUGGINGFACE_API_TOKEN")
|
| 22 |
+
|
| 23 |
+
# Load embeddings with Hugging Face API
|
| 24 |
+
embedding_model = "sentence-transformers/all-MiniLM-L6-v2"
|
| 25 |
+
embeddings = HuggingFaceEmbeddings(model_name=embedding_model) # Removed api_key parameter
|
| 26 |
+
|
| 27 |
+
# Set up the text generation model using Hugging Face Hub
|
| 28 |
+
model_name = "google/flan-t5-small" # Use a smaller model to reduce response time and cost
|
| 29 |
+
llm = HuggingFaceHub(repo_id=model_name, huggingfacehub_api_token=os.getenv("HUGGINGFACEHUB_API_TOKEN"), model_kwargs={"max_length": 256, "temperature": 0.7})
|
| 30 |
+
|
| 31 |
+
# Streamlit interface
|
| 32 |
+
def main():
|
| 33 |
+
st.title("Chat with Multiple PDFs")
|
| 34 |
+
st.write("Upload PDF files and chat with them.")
|
| 35 |
+
|
| 36 |
+
# File uploader
|
| 37 |
+
uploaded_files = st.file_uploader("Upload PDF Files", accept_multiple_files=True, type=["pdf"])
|
| 38 |
+
|
| 39 |
+
if uploaded_files:
|
| 40 |
+
# Load PDF documents
|
| 41 |
+
documents = []
|
| 42 |
+
for uploaded_file in uploaded_files:
|
| 43 |
+
pdf_content = BytesIO(uploaded_file.read())
|
| 44 |
+
doc = fitz.open(stream=pdf_content, filetype="pdf") # Open PDF with PyMuPDF
|
| 45 |
+
text = ""
|
| 46 |
+
for page in doc:
|
| 47 |
+
text += page.get_text() # Extract text from each page
|
| 48 |
+
doc.close()
|
| 49 |
+
|
| 50 |
+
# Create Document instance with page content
|
| 51 |
+
documents.append(Document(page_content=text, metadata={"file_name": uploaded_file.name}))
|
| 52 |
+
|
| 53 |
+
# Split documents into manageable chunks
|
| 54 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)
|
| 55 |
+
chunks = text_splitter.split_documents(documents)
|
| 56 |
+
|
| 57 |
+
# Embed document chunks into vector store
|
| 58 |
+
vector_store = FAISS.from_documents(chunks, embeddings)
|
| 59 |
+
|
| 60 |
+
# User query input
|
| 61 |
+
st.write("You can now start chatting with your PDFs!")
|
| 62 |
+
user_input = st.text_input("Ask a question:")
|
| 63 |
+
|
| 64 |
+
if user_input:
|
| 65 |
+
# Perform similarity search on the vector store
|
| 66 |
+
docs = vector_store.similarity_search(user_input, k=3)
|
| 67 |
+
|
| 68 |
+
# Concatenate retrieved docs into a single prompt
|
| 69 |
+
prompt = "\n".join([doc.page_content for doc in docs]) + "\n\n" + user_input
|
| 70 |
+
|
| 71 |
+
# Generate response using the Hugging Face API
|
| 72 |
+
try:
|
| 73 |
+
response = llm(prompt)
|
| 74 |
+
st.write(response)
|
| 75 |
+
except requests.exceptions.RequestException as e:
|
| 76 |
+
st.error(f"Error connecting to Hugging Face API: {e}")
|
| 77 |
+
|
| 78 |
+
if __name__ == "__main__":
|
| 79 |
+
main()
|