File size: 13,047 Bytes
d3c3946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be6dbc5
d3c3946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be6dbc5
d3c3946
 
 
 
 
 
 
 
 
 
be6dbc5
d3c3946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be6dbc5
d3c3946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be6dbc5
d3c3946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
386
387
388
389
390
391
392
393
394
395
396
# %%
import os
import json
import urllib.parse
from tempfile import _TemporaryFileWrapper

import pandas as pd
import requests
import streamlit as st
from streamlit_chat import message
from streamlit_extras.add_vertical_space import add_vertical_space
from streamlit_extras.colored_header import colored_header

st.set_page_config(
    layout="wide",
    page_title="pdfGPT-chat. Ask your PDF!",
    page_icon=":robot_face:",
)


def main():
    @st.cache_data
    def convert_df(df):
        return df.to_csv(index=False).encode("utf-8")
  
    def pdf_change():
        st.session_state["pdf_change"] = True

    def check_api(api_key):
        return api_key.startswith("sk-") and len(api_key) == 51

    def check_url(url):
        parsed_url = urllib.parse.urlparse(url)
        return all([parsed_url.scheme, parsed_url.netloc])

    def result_to_dict(r, start):
        result = r.json()["result"]
        result = result.split("###")[start:]
        keys = ["prompt", "answer", "token_used", "gpt_model"]
        # Error in OpenAI server also gives status_code 200
        if len(result) >= 0:
            result.extend([result, 0, gpt_model])
        return dict(zip(keys, result))

    def load_pdf():
        if file is None and len(pdf_url) == 0:
            return st.error("Both URL and PDF is empty. Provide at least one.")
        elif len(pdf_url) > 0:
            if not check_url(pdf_url):
                return st.error("Please enter valid URL.")
            elif file is not None:
                return st.error(
                    "Both URL and PDF is provided. Please provide only one (either URL or PDF)."
                )
            # load pdf from url
            else:
                r = requests.post(
                    f"{LCSERVE_HOST}/load_url",
                    json={
                        "url": pdf_url,
                        "rebuild_embedding": st.session_state["pdf_change"],
                        "embedding_model": embedding_model,
                        "gpt_model": gpt_model,
                        "envs": {
                            "OPENAI_API_KEY": OPENAI_API_KEY,
                        }
                    },
                )
        # load file
        else:
            _data = {
                "rebuild_embedding": st.session_state["pdf_change"],
                "embedding_model": embedding_model,
                "gpt_model": gpt_model,
                "envs": {
                    "OPENAI_API_KEY": OPENAI_API_KEY,
                }
            }

            r = requests.post(
                f"{LCSERVE_HOST}/load_file",
                params={"input_data": json.dumps(_data)},
                files={"file": file},
            )
        if r.status_code != 200:
            if "error" in r.json():
                if "message" in r.json()["error"]:
                    return st.error(r.json()["error"]["message"])
            else:
                return str(r.json())
        elif r.json()["result"].startswith("Corpus Loaded."):
            st.session_state["loaded"] = True
            st.session_state["pdf_change"] = False
            # extract result
            result = result_to_dict(r, 1)

            # concatenate reply
            reply_summary = "Hello there. I'm **pdfGPT-chat**.\nHere is a **summary** of your PDF:\n\n"
            reply_summary += result["answer"]
            reply_summary += "\n\nDo you have any **question** about your PDF?"

            if len(st.session_state["past"]) == 1:
                st.session_state["generated"][0] = reply_summary
            else:
                st.session_state["past"].append("Hi")
                st.session_state["generated"].append(reply_summary)

            # calculate cost
            calculate_cost(result["token_used"], result["gpt_model"])
            return st.success("The PDF file has been loaded.")
        else:
            return st.info(r.json()["result"])

    def generate_response(
        lcserve_host: str,
        url: str,
        file: _TemporaryFileWrapper,
        question: str,
    ) -> dict:
        if question.strip() == "":
            return "[ERROR]: Question field is empty"

        _data = {
            "question": question,
            "rebuild_embedding": st.session_state["pdf_change"],
            "embedding_model": embedding_model,
            "gpt_model": gpt_model,
            "envs": {
                "OPENAI_API_KEY": OPENAI_API_KEY,
            },
        }

        if url.strip() != "":
            r = requests.post(
                f"{LCSERVE_HOST}/ask_url",
                json={"url": url, **_data},
            )

        else:
            r = requests.post(
                f"{LCSERVE_HOST}/ask_file",
                params={"input_data": json.dumps(_data)},
                files={"file": file},
            )

        if r.status_code != 200:
            content = r.content.decode()  # Convert bytes to string
            with open("langchainlog.txt", "w") as file:
                file.write(content)
            return f"[ERROR]: {r.text}"

        result_dict = result_to_dict(r, 0)
        return result_dict

    def calculate_cost(token_used, gpt_model):
        st.session_state["total_token"] += int(token_used)
        if "gpt-3" in gpt_model:
            current_cost = st.session_state["total_token"] * 0.002 / 1000
        else:
            current_cost = st.session_state["total_token"] * 0.06 / 1000
        st.session_state["total_cost"] += current_cost

    # %%
    # main page layout
    header = st.container()
    welcome_page = st.container()
    response_container = st.container()
    input_container = st.container()
    cost_container = st.container()
    load_pdf_popup = st.container()

    # sidebar layout
    input_details = st.sidebar.container()
    preferences = st.sidebar.container()
    chat_download = st.sidebar.container()
    # %%
    # instantiate session states
    if "api_key" not in st.session_state:
        st.session_state["api_key"] = False

    if "generated" not in st.session_state:
        st.session_state["generated"] = ["Hello there. I'm pdfGPT-chat. Do you have any question about your PDF?"]

    if "loaded" not in st.session_state:
        st.session_state["loaded"] = False

    if "past" not in st.session_state:
        st.session_state["past"] = ["Hi"]

    if "pdf_change" not in st.session_state:
        st.session_state["pdf_change"] = True

    if "total_cost" not in st.session_state:
        st.session_state["total_cost"] = 0

    if "total_token" not in st.session_state:
        st.session_state["total_token"] = 0

    # %%
    # constants
    E5_URL = "https://github.com/microsoft/unilm/tree/master/e5"
    EMBEDDING_CHOICES = {
        "multilingual-e5-base": "Multilingual-E5 (default)",
        "e5-small-v2": "English-E5-small (faster)",
    }
    GPT_CHOICES = {
        "gpt-3.5-turbo": "GPT-3.5-turbo (default)",
        "gpt-4": "GPT-4 (smarter, costlier)",
    }
    LCSERVE_HOST = "http://localhost:8080"
    OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
    PDFGPT_URL = "https://github.com/bhaskatripathi/pdfGPT"
    SIGNATURE = """<style>
.footer {
position: static;
left: 0;
bottom: 0;
width: 100%;
background: rgba(0,0,0,0);
text-align: center;
}
</style>

<div class="footer">
<p style='display: block;
text-align: center;
font-size:14px;
color:darkgray'>Developed with ❤ by asyafiqe</p>
</div>
"""

    with header:
        st.title(":page_facing_up: pdfGPT-chat")
        with st.expander(
            "A fork of [pdfGPT](%s) with several improvements. With pdfGPT-chat, you can chat with your PDF files using [**Microsoft E5 Multilingual Text Embeddings**](%s) and **OpenAI**."
            % (PDFGPT_URL, E5_URL)
        ):
            st.markdown(
                "Compared to other tools, pdfGPT-chat provides **hallucinations-free** response, thanks to its superior embeddings and tailored prompt.<br />The generated responses from pdfGPT-chat include **citations** in square brackets ([]), indicating the **page numbers** where the relevant information is found.<br />This feature not only enhances the credibility of the responses but also aids in swiftly locating the pertinent information within the PDF file.",
                unsafe_allow_html=True,
            )

        colored_header(
            label="",
            description="",
            color_name="blue-40",
        )

    with preferences:
        colored_header(
            label="",
            description="",
            color_name="blue-40",
        )
        st.write("**Preferences**")
        embedding_model = st.selectbox(
            "Embedding",
            EMBEDDING_CHOICES.keys(),
            help="""[Multilingual-E5](%s) supports 100 languages. 
            E5-small is much faster and suitable for PC without GPU."""
            % E5_URL,
            on_change=pdf_change,
            format_func=lambda x: EMBEDDING_CHOICES[x],
        )
        gpt_model = st.selectbox(
            "GPT Model",
            GPT_CHOICES.keys(),
            help="For GPT-4 you might have to join the waitlist: https://openai.com/waitlist/gpt-4-api",
            format_func=lambda x: GPT_CHOICES[x],
        )

    # %%
    # sidebar
    with input_details:
        # sidebar
        pdf_url = st.text_input(
            ":globe_with_meridians: Enter PDF URL here", on_change=pdf_change
        )

        st.markdown(
            "<h2 style='text-align: center; color: black;'>OR</h2>",
            unsafe_allow_html=True,
        )

        file = st.file_uploader(
            ":page_facing_up: Upload your PDF/ Research Paper / Book here",
            type=["pdf"],
            on_change=pdf_change,
        )

        if st.button("Load PDF"):
            st.session_state["loaded"] = True
            with st.spinner("Loading PDF"):
                with load_pdf_popup:
                    load_pdf()

    # %%

    # main tab
    if st.session_state["loaded"]:
        with input_container:
            with st.form(key="input_form", clear_on_submit=True):
                user_input = st.text_area("Question:", key="input", height=100)
                submit_button = st.form_submit_button(label="Send")

            if user_input and submit_button:
                with st.spinner("Processing your question"):
                    response = generate_response(
                        LCSERVE_HOST,
                        pdf_url,
                        file,
                        user_input,
                    )
                    st.session_state.past.append(user_input)
                    st.session_state.generated.append(response["answer"])

                    # calculate cost
                    calculate_cost(response["token_used"], response["gpt_model"])

            if not user_input and submit_button:
                st.error("Please write your question.")

        with response_container:
            if st.session_state["generated"]:
                for i in range(len(st.session_state["generated"])):
                    message(
                        st.session_state["past"][i], is_user=True, key=str(i) + "_user"
                    )
                    message(st.session_state["generated"][i], key=str(i))

        cost_container.caption(
            f"Estimated cost: $ {st.session_state['total_cost']:.4f}"
        )

    else:
        with welcome_page:
            st.write("")
            st.subheader(
                """:arrow_left: To start please fill input details in the sidebar and click **Load PDF**"""
            )
    # %%
    # placed in the end to include the last conversation
    with chat_download:
        chat_history = pd.DataFrame(
            {
                "Question": st.session_state["past"],
                "Answer": st.session_state["generated"],
            }
        )

        csv = convert_df(chat_history)

        st.download_button(
            label="Download chat history",
            data=csv,
            file_name="chat history.csv",
            mime="text/csv",
        )
        add_vertical_space(2)
        st.markdown(SIGNATURE, unsafe_allow_html=True)

    # %%
    # # javascript
    #
    # # scroll halfway through the page
    js = f"""
    <script>
    function scroll() {{
    var textAreas = parent.document.querySelectorAll('section.main');
    var halfwayScroll = 0.4 * textAreas[0].scrollHeight; // Calculate halfway scroll position

    for (let index = 0; index < textAreas.length; index++) {{
    textAreas[index].scrollTop = halfwayScroll; // Set scroll position to halfway
    }}
    }}

    scroll(); // Call the scroll function
    </script>
    """
    st.components.v1.html(js)

    # reduce main top padding
    st.markdown(
        "<style>div.block-container{padding-top:1.5em;}</style>",
        unsafe_allow_html=True,
    )
    # reduce sidebar top padding
    st.markdown(
        "<style>.css-ysnqb2.e1g8pov64 {margin-top: -90px;}</style>",
        unsafe_allow_html=True,
    )


if __name__ == "__main__":
    main()