File size: 13,544 Bytes
f8ea069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
715fe48
 
f8ea069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
715fe48
 
 
f8ea069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a90f0b
f8ea069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a90f0b
 
 
 
 
f8ea069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a90f0b
 
 
 
 
f8ea069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a90f0b
 
 
 
 
f8ea069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df8f70f
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import os
import pickle
import urllib
import requests
import io
from collections import Counter
from pathlib import Path
import pdfplumber
from bs4 import BeautifulSoup
import faiss

from langchain.llms import OpenAI
from langchain.chains import LLMChain, ConstitutionalChain
from langchain.chains.constitutional_ai.models import ConstitutionalPrinciple
from langchain import PromptTemplate
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import FAISS
from langchain.docstore.document import Document
from langchain.embeddings import OpenAIEmbeddings
from langchain.chains.qa_with_sources import load_qa_with_sources_chain
from langchain.document_loaders import PyPDFLoader


BING_API_KEY = os.environ.get("BING_API_KEY")


def scrape_article(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, "html.parser")
    paragraphs = soup.find_all("p")
    return " ".join([p.get_text() for p in paragraphs])


def is_not_pdf(url):
    return not url.lower().endswith(".pdf")


def extract_text_from_pdf_url(pdf_url):
    response = requests.get(pdf_url)
    pdf_data = io.BytesIO(response.content)

    font_stats = []

    with pdfplumber.open(pdf_data) as pdf:
        for page in pdf.pages:
            chars = page.chars
            for char in chars:
                font_stats.append((char['size'], char['fontname']))

    most_common_font = Counter(font_stats).most_common(1)[0][0]

    text = []
    with pdfplumber.open(pdf_data) as pdf:
        for page in pdf.pages:
            chars = page.chars
            page_text = []
            for char in chars:
                if (char['size'], char['fontname']) == most_common_font:
                    page_text.append(char['text'])
            text.append("".join(page_text))

    return "\n".join(text)


def scrape_bing_results(url, n=3):
    headers = {
        "Ocp-Apim-Subscription-Key": BING_API_KEY
    }
    response = requests.get(url, headers=headers)
    results = response.json()
    links = []

    if 'webPages' in results and 'value' in results['webPages']:
        search_results = results['webPages']['value']
        for result in search_results[:n]:
            link = result['url']
            links.append(link)

    return links


def get_search_url_bing(query):
    return f"https://api.bing.microsoft.com/v7.0/search?q={urllib.parse.quote_plus(query)}"


class ChatbotAssistant:
    def __init__(self):
        self.temperature = 0.7

        self.BING_API_KEY = os.environ.get("BING_API_KEY")
        self.openai_api_key = os.environ.get("OPENAI_API_KEY")
        self.chain = load_qa_with_sources_chain(
            OpenAI(temperature=self.temperature, openai_api_key=self.openai_api_key))
        self.search_index = None
        self.articles = []
        self.source_urls = []
        self.sources = [
            "https://home.kpmg/",
            "https://www.ibisworld.com",
            "https://www.bcg.com/",
            "https://www.mckinsey.com/",
            "https://www2.deloitte.com/",
            "https://www.pwc.co.uk/",
            "https://www.ey.com/en_gl"
        ]

        if os.path.exists("search_index.pickle"):
            with open("search_index.pickle", "rb") as f:
                self.search_index = pickle.load(f)

        self.qa_prompt = PromptTemplate(
            template="Q: {question} A:",
            input_variables=["question"],
        )
        self.qa_chain = LLMChain(llm=OpenAI(temperature=self.temperature, openai_api_key=self.openai_api_key, max_tokens=300), prompt=self.qa_prompt)

        self.constitutional_chain = ConstitutionalChain.from_llm(
            llm=OpenAI(openai_api_key=self.openai_api_key),
            chain=self.qa_chain,
            constitutional_principles=[
                ConstitutionalPrinciple(
                    critique_request="Rate the quality of this answer on a scale of 1 (bad) to 10 (good). If the answer is'I don't know' or similar return a 0.",
                    revision_request="Return the rating as a single integer from 1 (bad) to 10 (good). Only return the number. For example, this would be a valid rating: 10. This would be an invalid rating: The answer is 10."
                )
            ],
        )


    def get_search_url(self, query, site=None):
        if site:
            query = f"site:{site} {query}"
        return f"https://api.bing.microsoft.com/v7.0/search?q={urllib.parse.quote_plus(query)}"

    def update_search_index(self):
        source_docs = self.articles
        source_chunks = []
        splitter = CharacterTextSplitter(separator=" ", chunk_size=1024, chunk_overlap=0)
        source_counter = 0

        for source, url in zip(source_docs, self.source_urls):
            for chunk in splitter.split_text(source):
                source_chunks.append(Document(page_content=chunk, metadata={"source": url}))
            source_counter = source_counter + 1

        with open("search_index.pickle", "wb") as f:
            pickle.dump(FAISS.from_documents(source_chunks, OpenAIEmbeddings(openai_api_key=self.openai_api_key)), f)

        with open("search_index.pickle", "rb") as f:
            self.search_index = pickle.load(f)

    def retrieve_articles(self, question):
        self.articles = []
        self.source_urls = []

        for source in self.sources:
            search_url = self.get_search_url(question, source)
            urls = scrape_bing_results(search_url, 1)
            for url in urls:
                if is_not_pdf(url):
                    self.articles.append(scrape_article(url))
                else:
                    self.articles.append(extract_text_from_pdf_url(url))
                self.source_urls.append(url)

        self.update_search_index()

    def retrieve_alternative_articles(self, question):
        self.articles = []
        self.source_urls = []

        search_url = get_search_url_bing(question)
        urls = scrape_bing_results(search_url, 5)
        for url in urls:
            if is_not_pdf(url):
                self.articles.append(scrape_article(url))
            else:
                self.articles.append(extract_text_from_pdf_url(url))
            self.source_urls.append(url)

        self.update_search_index()


    def chatbot_assistant(self, question, custom_sources=None, rating_threshold=6):
        # Update the assistant's sources with the provided custom sources
        if custom_sources:
            self.sources = custom_sources
            print(custom_sources)


        if self.search_index:
            input_documents = self.search_index.similarity_search(question, k=4)
            answers = self.chain(
                {
                    "input_documents": input_documents,
                    "question": question,
                },
                return_only_outputs=True,
            )
            answer = answers["output_text"]

            evaluation = self.constitutional_chain.run(question=answer)

            try:
                rating = int(evaluation.strip().split()[-1])  # Extract the rating from the returned text
            except ValueError:
                rating = 0  # Set a default rating if the output is not a number string

            if rating < rating_threshold or "I don't know" in answer:
                print("Launching a new Bing search.")
                self.retrieve_articles(question)
                answers = self.chain(
                    {
                        "input_documents": input_documents,
                        "question": question,
                    },
                    return_only_outputs=True,
                )
                answer = answers["output_text"]

                # Check again after retrieving from the original sources
                evaluation = self.constitutional_chain.run(question=answer)

                try:
                    rating = int(evaluation.strip().split()[-1])  # Extract the rating from the returned text
                except ValueError:
                    rating = 0  # Set a default rating if the output is not a number string
                
                if rating < rating_threshold or "I don't know" in answer:
                    self.retrieve_alternative_articles(question)
                    answers = self.chain(
                        {
                            "input_documents": input_documents,
                            "question": question,
                        },
                        return_only_outputs=True,
                    )
                    answer = answers["output_text"]
            else:
                pass
        else:
            print("Launching a new Bing search.")
            self.retrieve_articles(question)
            input_documents = self.search_index.similarity_search(question, k=4)
            answers = self.chain(
                {
                    "input_documents": input_documents,
                    "question": question,
                },
                return_only_outputs=True,
            )
            answer = answers["output_text"]

            # Check again after retrieving from the original sources
            evaluation = self.constitutional_chain.run(question=answer)
            
            try:
                rating = int(evaluation.strip().split()[-1])  # Extract the rating from the returned text
            except ValueError:
                rating = 0  # Set a default rating if the output is not a number string

            if rating < rating_threshold or "I don't know" in answer:
                self.retrieve_alternative_articles(question)
                answers = self.chain(
                    {
                        "input_documents": input_documents,
                        "question": question,
                    },
                    return_only_outputs=True,
                )
                answer = answers["output_text"]
            else:
                pass

        self.search_index = None
        self.articles = []
        self.source_urls = []

        if os.path.exists("search_index.pickle"):
            with open("search_index.pickle", "rb") as f:
                self.search_index = pickle.load(f)

        input_documents = self.search_index.similarity_search(question, k=4)

        answers = self.chain(
            {
                "input_documents": input_documents,
                "question": question,
            },
            return_only_outputs=True,
        )
        answer = answers["output_text"]

        return answer

      

    def add_pdf_source(self, pdf_text, pdf_filename):

        self.search_index = None
        self.articles = []
        self.source_urls = []

        self.articles.append(pdf_text)
        print(pdf_text)
        self.source_urls.append(pdf_filename)
        print(pdf_filename)
        self.update_search_index()


import gradio as gr
import time
import tempfile
import PyPDF2

# Create an instance of the ChatbotAssistant class
assistant = ChatbotAssistant()

def process_pdf(file_obj):
    pdf_reader = PyPDF2.PdfReader(file_obj.name)
    num_pages = len(pdf_reader.pages)
    text = ""

    for page in range(num_pages):
        pdf_page = pdf_reader.pages[page]
        text += pdf_page.extract_text()

    return text

def user(user_message, custom_sources, history, pdf_upload):
    # Update the assistant's sources with the provided custom sources
    if custom_sources:
        assistant.sources = custom_sources.split(', ')

    # Process the uploaded PDF file and add it to the assistant's sources
    if pdf_upload:
        print("PDF upload is triggered")
        pdf_file_name = os.path.basename(pdf_upload.name)
        pdf_text = process_pdf(pdf_upload)
        assistant.add_pdf_source(pdf_text, pdf_file_name)


    return "", custom_sources, history + [(user_message, None)]


def bot(history):
    question = history[-1][0]
    answer = assistant.chatbot_assistant(question)
    history[-1] = (question, answer)
    time.sleep(1)
    return history

def copy_last_response(history, saved_responses):
    if history:
        last_response = history[-1][1]
        if saved_responses:
            saved_responses += "\n\n" + last_response
        else:
            saved_responses = last_response
    return saved_responses

default_sources = "https://home.kpmg/, https://www.ibisworld.com, https://www.bcg.com/, https://www.mckinsey.com/, https://www2.deloitte.com/, https://www.pwc.co.uk/, https://www.ey.com/en_gl"

with gr.Blocks() as demo:
    fn = process_pdf

    with gr.Row():
        with gr.Column(scale=1, min_width=200):
            custom_sources = gr.Textbox(label="Custom Sources (comma-separated URLs)", value=default_sources, lines=5)
            pdf_upload = gr.File(file_types=[".pdf"], label="Upload PDF")

        with gr.Column(scale=2, min_width=400):
          chatbot = gr.Chatbot(label="AI Consultant")
          msg = gr.Textbox(label="Your Question")
          submit = gr.Button("Submit")
          clear = gr.Button("Clear History")
        with gr.Column(scale=1, min_width=200):
          copy_button = gr.Button("Copy Last Response")
          saved_responses = gr.Textbox(label="Saved Responses", lines=10)

    submit.click(user, [msg, custom_sources, chatbot, pdf_upload], [msg, custom_sources, chatbot], queue=False).then(bot, chatbot, chatbot) 
    clear.click(lambda: None, None, chatbot, queue=False)
    copy_button.click(copy_last_response, [chatbot, saved_responses], saved_responses, queue=False)

demo.launch(debug=True)