File size: 4,886 Bytes
cc93217
 
 
 
 
 
449fa63
cc93217
ffe7e6e
 
 
449fa63
 
 
 
 
1a34160
 
 
 
 
449fa63
 
 
 
1a34160
 
 
 
ff2dd67
 
1a34160
 
 
449fa63
8ae7246
9f266a1
8ae7246
 
cc93217
9f266a1
 
 
 
 
 
 
 
de4004c
 
 
 
 
 
 
 
 
cc93217
fe87044
 
1a34160
 
de4004c
1a34160
 
 
cc93217
 
 
 
 
8ae7246
1a34160
 
8ae7246
1a34160
 
65d65e8
cc93217
 
 
 
8ae7246
 
9f266a1
8ae7246
 
ff2dd67
8ae7246
 
 
 
 
 
 
 
 
 
1a34160
8ae7246
cc93217
8ae7246
1a34160
 
8ae7246
 
 
 
 
1a34160
 
8ae7246
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a34160
 
cc93217
 
 
 
 
 
 
de4004c
 
 
 
8ae7246
cc93217
de4004c
cc93217
 
8ae7246
1a34160
cc93217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ae7246
cc93217
 
65d65e8
8ae7246
cc93217
8ae7246
 
 
 
 
cc93217
 
8ae7246
 
 
 
 
cc93217
8ae7246
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc93217
 
179ea90
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import gradio as gr

from langchain.document_loaders import OnlinePDFLoader

from langchain.text_splitter import CharacterTextSplitter
from langchain.prompts import PromptTemplate
from langchain.llms import HuggingFaceHub

# from langhchain.llms import openai
from langchain.llms import OpenAI

from langchain.vectorstores import Chroma

from langchain.chains import RetrievalQA

from langchain.document_loaders import PyPDFLoader
from langchain.memory import VectorStoreRetrieverMemory

from langchain.chains import RetrievalQAWithSourcesChain
from langchain.memory import ConversationBufferMemory
from langchain.embeddings import CohereEmbeddings


from langchain.embeddings import HuggingFaceHubEmbeddings, OpenAIEmbeddings

import dotenv

import os

from prompt_template import template

dotenv.load_dotenv()



text_splitter = CharacterTextSplitter(
    chunk_size=350,
    chunk_overlap=0
    )

# flan_ul2 = HuggingFaceHub(
#     repo_id="HuggingFaceH4/zephyr-7b-beta", 
#     model_kwargs={
#         "temperature":0.1, 
#         "max_new_tokens":300
#         }
#         )

# flan_ul2 = OpenAI()
from langchain.chat_models import ChatOpenAI

flan_ul2 = chat = ChatOpenAI(
    model_name='gpt-3.5-turbo-16k',
    # temperature = self.config.llm.temperature,
    # openai_api_key = self.config.llm.openai_api_key,         
    # max_tokens=self.config.llm.max_tokens
)

global qa

COHERE_API_KEY = os.getenv("COHERE_API_KEY")
embeddings = CohereEmbeddings(
    model="embed-english-v3.0",
    cohere_api_key=COHERE_API_KEY
)
           


def loading_pdf():
    return "Loading..."
def pdf_changes(pdf_doc):

    embeddings = CohereEmbeddings(
    model="embed-english-light-v3.0",

)
    
    loader = PyPDFLoader(pdf_doc.name)
    documents = loader.load()
    texts = text_splitter.split_documents(documents)
    db = Chroma.from_documents(texts, embeddings)
    retriever = db.as_retriever()

    memory = ConversationBufferMemory(
        memory_key="chat_history",
        input_key="human_input"
        )


    prompt = PromptTemplate(
        input_variables=[
            "chat_history",
            "human_input", 
            "context"
            ], 
            template=template
            )

    chain_type_kwargs = {"prompt": prompt}

    global qa 


    prompt = PromptTemplate(
    input_variables=[
        "history", 
        "context", 
        "question"
        ],
    template=template,
)
    memory = ConversationBufferMemory(
        memory_key="history", 
        input_key="question"
        )

    qa = RetrievalQAWithSourcesChain.from_chain_type(
        llm=flan_ul2, 
        retriever=retriever, 
        return_source_documents=True, 
        verbose=True, 
        chain_type_kwargs={
            "verbose": True,
            "memory": memory,
            "prompt": prompt,
            "document_variable_name": "context"
            }
        )

    return "Ready"

def add_text(history, text):
    history = history + [(text, None)]
    return history, ""

def bot(history):
    response = infer(history[-1][0],"")
    history[-1][1] = response['answer']
    return history



def infer(question, history) -> dict:
    
    query = question

    result = qa({"query": query, "history": history, "question": question})

    return result

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>
    <p style="text-align: center;">Upload a .PDF from your computer, click the "Load PDF to LangChain" button, <br />
    when everything is ready, you can start asking questions about the pdf ;)</p>
</div>
"""


with gr.Blocks(css=css) as demo:
    with gr.Column(elem_id="col-container"):
        gr.HTML(title)

        
        with gr.Column():
            pdf_doc = gr.File()

            with gr.Row():
                langchain_status = gr.Textbox(
                    label="Status", 
                    placeholder="", 
                    interactive=False
                    )
                load_pdf = gr.Button("Load pdf to langchain")
        
        chatbot = gr.Chatbot(
            [], 
            elem_id="chatbot"
            ) #.style(height=350)
        
        with gr.Row():
            question = gr.Textbox(
                label="Question", 
                placeholder="Type your question and hit Enter "
                )

    load_pdf.click(
        loading_pdf, 
        None, 
        langchain_status, 
        queue=False
        )
    
    load_pdf.click(
        pdf_changes, 
        pdf_doc, 
        langchain_status, 
        queue=False
        )
    
    question.submit
    (add_text, 
     [
        chatbot, 
        question
      ], 
      [
          chatbot, 
          question]
          ).then(
        bot, 
        chatbot, 
        chatbot
    )

demo.launch()