Spaces:
Running
Running
File size: 6,593 Bytes
9d8ec30 a8554ee 214739d 9d8ec30 dad94f5 bc32a3b dad94f5 38324f3 2aaf3ce 4138f63 a8554ee 4138f63 a8554ee 5a7e8e6 4757e3a dad94f5 2aaf3ce a8554ee 2aaf3ce a8554ee d5fb2f8 9d8ec30 9558517 214739d bc5bb26 214739d 9d8ec30 6933749 9d8ec30 8960fe5 9d8ec30 befd304 ed4bbdc 7c5299e bde82a9 da05edc 1169786 a8554ee 3a7cfe4 3911076 887d7a5 34db464 a8554ee 0866e35 04eb61d 8960fe5 04eb61d 9d8ec30 214739d 9d8ec30 8960fe5 0d985ab 8960fe5 aab4b76 7849b3b a18bbab 9d8ec30 fabfbf3 9d8ec30 20f19cf 9d8ec30 |
1 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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 |
import streamlit as st
from langchain_community.llms import HuggingFaceHub
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
from langchain.prompts import ChatPromptTemplate
from PyPDF2 import PdfReader
from langchain_text_splitters import RecursiveCharacterTextSplitter
import os
from langchain_community.vectorstores import Chroma
from langchain.chains.question_answering import load_qa_chain
from langchain.prompts import PromptTemplate
from langchain_community.document_loaders import PyPDFLoader
from langchain_chroma import Chroma
from langchain_community.embeddings import HuggingFaceEmbeddings
#from transformers import pipeline
# Load model directly
#from transformers import AutoModelForCausalLM
#from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline
#from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
#from llama_index.llms.huggingface import HuggingFaceInferenceAPI
#from llama_index.embeddings.huggingface import HuggingFaceEmbedding
#from llama_index.core import Settings
#access_token = os.getenv("HUGGINGFACE_API_KEY")
# Configure the Llama index settings
#llm = HuggingFaceInferenceAPI(
# model_name="meta-llama/Meta-Llama-3-8B-Instruct",
# tokenizer_name="meta-llama/Meta-Llama-3-8B-Instruct",
# context_window=3900,
# token=os.getenv("HUGGINGFACE_API_KEY"),
# max_new_tokens=1000,
# generate_kwargs={"temperature": 0.1},
#)
#st.set_page_config(page_title="Document Genie", layout="wide")
#st.markdown("""
### PDFChat: Get instant insights from your PDF
#This chatbot is built using the Retrieval-Augmented Generation (RAG) framework, leveraging Google's Generative AI model Gemini-PRO. It processes uploaded PDF documents by breaking them down into manageable chunks, creates a searchable vector store, and generates accurate answers to user queries. This advanced approach ensures high-quality, contextually relevant responses for an efficient and effective user experience.
#### How It Works
#Follow these simple steps to interact with the chatbot:
#1. **Upload Your Document**: The system accepts a PDF file at one time, analyzing the content to provide comprehensive insights.
#2. **Ask a Question**: After processing the document, ask any question related to the content of your uploaded document for a precise answer.
#""")
#def get_pdf(pdf_docs):
# loader = PyPDFLoader(pdf_docs)
# docs = loader.load()
# return docs
def get_pdf(pdf_docs):
docs=[]
for pdf in pdf_docs:
temp_file = "./temp.pdf"
# Delete the existing temp.pdf file if it exists
if os.path.exists(temp_file):
os.remove(temp_file)
with open(temp_file, "wb") as file:
file.write(pdf.getvalue())
file_name = pdf.name
loader = PyPDFLoader(temp_file)
docs.extend(loader.load())
return docs
def text_splitter(text):
text_splitter = RecursiveCharacterTextSplitter(
# Set a really small chunk size, just to show.
chunk_size=10000,
chunk_overlap=500,
separators=["\n\n","\n"," ",".",","])
chunks=text_splitter.split_documents(text)
return chunks
def get_conversational_chain(retriever):
prompt_template = """
Given the following extracted parts of a long document and a question, create a final answer.
Answer the question as detailed as possible from the provided context, make sure to provide all the details, if the answer is not in
provided context just say, "answer is not available in the context", and then ignore the context and add the answer from your knowledge like a simple llm prompt.
Try to give atleast the basic information.Donot return blank answer.\n\n
Make sure to understand the question and answer as per the question.
The answer should be a detailed one and try to incorporate examples for better understanding.
If the question involves terms like detailed or explained , give answer which involves complete detail about the question.\n\n
Context:\n {context}?\n
Question: \n{question}\n
Answer:
"""
#model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3, google_api_key=GOOGLE_API_KEY)
#repo_id='meta-llama/Meta-Llama-3-70B'
#repo_id = 'mistralai/Mixtral-8x7B-Instruct-v0.1'
#repo_id= 'nvidia/Llama3-ChatQA-1.5-8B'
#repo_id= 'google/gemma-1.1-2b-it'
llm = HuggingFaceHub(
#repo_id="HuggingFaceH4/zephyr-7b-beta",
#repo_id = "mistralai/Mistral-7B-v0.1",
#repo_id= "microsoft/Phi-3-mini-4k-instruct",
repo_id = "google/gemma-2b-it",
huggingfacehub_api_token=os.getenv("HUGGINGFACE_API_KEY2"),
task="text-generation",
)
pt = ChatPromptTemplate.from_template(prompt_template)
# Retrieve and generate using the relevant snippets of the blog.
#retriever = db.as_retriever()
rag_chain = (
{"context": retriever, "question": RunnablePassthrough()}
| pt
| llm
| StrOutputParser()
)
return rag_chain
def embedding(chunk,query):
#embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
#embeddings = CohereEmbeddings(model="embed-english-v3.0")
embeddings=HuggingFaceEmbeddings()
db = Chroma.from_documents(chunk,embeddings)
doc = db.similarity_search(query)
print(doc)
#Retrieve and generate using the relevant snippets of the blog.
retriever = db.as_retriever()
chain = get_conversational_chain(retriever)
response = chain.invoke(query)
response_answer=response.split("Answer:",-1)[-1]
return response_answer
#st.write("Reply: ", response["output_text"])
if 'messages' not in st.session_state:
st.session_state.messages = [{'role': 'assistant', "content": 'Hello! Upload a PDF and ask me anything about its content.'}]
st.header("Chat with your pdf💁")
with st.sidebar:
st.title("PDF FILE UPLOAD:")
pdf_docs = st.file_uploader("Upload your PDF File and Click on the Submit & Process Button", accept_multiple_files=True, key="pdf_uploader")
query = st.chat_input("Ask a Question from the PDF File")
if query:
raw_text = get_pdf(pdf_docs)
text_chunks = text_splitter(raw_text)
st.session_state.messages.append({'role': 'user', "content": query})
response = embedding(text_chunks,query)
st.session_state.messages.append({'role': 'assistant', "content": response})
for message in st.session_state.messages:
with st.chat_message(message['role']):
st.write(message['content']) |