Spaces:
Sleeping
Sleeping
| import os | |
| import sys | |
| import gradio as gr | |
| from pinecone import Pinecone, ServerlessSpec | |
| from langchain_community.llms import Replicate | |
| from langchain_pinecone import PineconeVectorStore | |
| from langchain.text_splitter import CharacterTextSplitter | |
| from langchain_community.document_loaders import PyPDFLoader | |
| from langchain_huggingface.embeddings import HuggingFaceEmbeddings | |
| from langchain.chains import ConversationalRetrievalChain | |
| import time | |
| key1 = os.environ.get('REPLICATE_API_TOKEN') | |
| key2 = os.environ.get('PINECONE_API_KEY') | |
| os.environ['REPLICATE_API_TOKEN'] = key1 | |
| os.environ["PINECONE_API_KEY"] = key2 | |
| # Initialize Pinecone | |
| pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"]) | |
| # Function to process PDF and set up chatbot | |
| def process_pdf(pdf_doc): | |
| # Save uploaded file | |
| filename = pdf_doc.name | |
| pdf_doc.save(filename) | |
| # Load PDF and create index | |
| loader = PyPDFLoader(filename) | |
| documents = loader.load() | |
| text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) | |
| texts = text_splitter.split_documents(documents) | |
| embeddings = HuggingFaceEmbeddings() | |
| index_name = "pdfchatbot" | |
| existing_indexes = [index_info["name"] for index_info in pc.list_indexes()] | |
| if index_name in existing_indexes: | |
| pc.delete_index(index_name) | |
| while index_name in [index_info["name"] for index_info in pc.list_indexes()]: | |
| time.sleep(1) | |
| pc.create_index( | |
| name=index_name, | |
| dimension=768, | |
| metric="cosine", | |
| spec=ServerlessSpec(cloud="aws", region="us-east-1"), | |
| ) | |
| while not pc.describe_index(index_name).status["ready"]: | |
| time.sleep(1) | |
| index = pc.Index(index_name) | |
| vectordb = PineconeVectorStore.from_documents(texts, embeddings, index_name=index_name) | |
| llm = Replicate( | |
| model="a16z-infra/llama13b-v2-chat:df7690f1994d94e96ad9d568eac121aecf50684a0b0963b25a41cc40061269e5", | |
| input={"temperature": 0.75, "max_length": 3000} | |
| ) | |
| global qa_chain | |
| qa_chain = ConversationalRetrievalChain.from_llm( | |
| llm, | |
| vectordb.as_retriever(search_kwargs={'k': 2}), | |
| return_source_documents=True | |
| ) | |
| return "Ready" | |
| # Function to handle user queries | |
| def query(history, text): | |
| langchain_history = [(msg[1], history[i+1][1] if i+1 < len(history) else "") for i, msg in enumerate(history) if i % 2 == 0] | |
| result = qa_chain({"question": text, "chat_history": langchain_history}) | |
| new_history = history + [(text,result['answer'])] | |
| return new_history, "" | |
| # Define the Gradio interface | |
| css = """ | |
| #col-container {max-width: 700px; margin-left: auto; margin-right: auto;} | |
| """ | |
| title = """ | |
| <div style="text-align: center;max-width: 700px;"> | |
| <h1>Chat with PDF</h1> | |
| """ | |
| with gr.Blocks(css=css) as demo: | |
| with gr.Column(elem_id="col-container"): | |
| gr.HTML(title) | |
| with gr.Column(): | |
| pdf_doc = gr.File(label="Load a PDF", file_types=['.pdf'], type="filepath") | |
| load_pdf = gr.Button("Load PDF") | |
| langchain_status = gr.Textbox(label="Status", placeholder="", interactive=False) | |
| chatbot = gr.Chatbot([], elem_id="chatbot").style(height=350) | |
| question = gr.Textbox(label="Question", placeholder="Type your question and hit Enter ") | |
| submit_btn = gr.Button("Send message") | |
| load_pdf.click(pdf_changes, inputs=[pdf_doc], outputs=[langchain_status], queue=False) | |
| question.submit(query, [chatbot, question], [chatbot, question]) | |
| submit_btn.click(query, [chatbot, question], [chatbot, question]) | |
| demo.launch() | |