File size: 2,393 Bytes
fa67bc8
3e36891
 
 
 
 
 
 
fa67bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from langchain_community.llms import GooglePalm
from langchain_community.embeddings import HuggingFaceInstructEmbeddings
from langchain_community.text_splitter import CharacterTextSplitter
from langchain_community.embeddings import GooglePalmEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_community.document_loaders import PyPDFLoader
from langchain_community.chains import RetrievalQA
from secret1 import GOOGLE_API as google_api
import PyPDF2
def chatbot_response(user_input, history):
    # This is a placeholder function. Replace with your actual chatbot logic.
    bot_response = "You said: " + user_input
    history.append((user_input, bot_response))
    return history, history

def text_splitter_function(text):
    text_splitter = CharacterTextSplitter(
        separator = '\n',
        chunk_size = 1000,
        chunk_overlap = 40,
        length_function = len,
    )
    texts = text_splitter.split_text(text)
    return texts;

def text_extract(file):
    pdf_reader = PyPDF2.PdfReader(file.name)
    # Get the number of pages
    num_pages = len(pdf_reader.pages)
    # Extract text from each page
    text = ""
    for page_num in range(num_pages):
        page = pdf_reader.pages[page_num]
        text += page.extract_text()
    text_splitter=text_splitter_function(text);
    db = FAISS.from_texts(text_splitter, embeddings);
    retriever = db.as_retriever(search_type="similarity", search_kwargs={"k": 2})
    llm=GooglePalm(google_api_key=google_api)
    qa = RetrievalQA.from_chain_type(
        llm=llm, chain_type="stuff", retriever=retriever, return_source_documents=True
    )
    print(db)
    return text
    

with gr.Blocks() as demo:
    gr.Markdown("# Chat with ChatGPT-like Interface")

    chatbot = gr.Chatbot()
    state = gr.State([])

    with gr.Row():
        with gr.Column():
            user_input = gr.Textbox(show_label=False, placeholder="Type your message here...")
            send_btn = gr.Button("Send")
        with gr.Column():
            input_file=gr.File(label="Upload PDF", file_count="single")
            submit_btn=gr.Button("Submit")
    submit_btn.click(text_extract, [input_file], [user_input])
    send_btn.click(chatbot_response,[user_input,state],[chatbot, state])

if __name__ == "__main__":
    embeddings=GooglePalmEmbeddings(google_api_key=google_api)
    demo.launch()