PDF_QnA / app.py
Vihang28's picture
Update app.py
d348c8d verified
import gradio as gr
import requests
import PyPDF2
import openai
import os
import tempfile
import fitz
prompt = "Type and press Enter"
def read_pdf(pdf_path):
doc = fitz.open(pdf_path)
text = ""
for page in doc:
text+=page.get_text()
return(text)
# with tempfile.TemporaryFile(mode='w+b') as temp_file:
# reader = PyPDF2.PdfReader(temp_file)
# text_pdf = ''
# # pdf_len = len(pdfReader.pages)
# for i in range(len(reader.pages)):
# pageObj = reader.pages[i]
# text_pdf = text_pdf + pageObj.extract_text() + ' '
# return text_pdf
def api_calling(pdf_input, prompt, api_key):
text_pdf = read_pdf(pdf_input)
if len(prompt) == 0:
prompt = "What this paragrapgh is about?"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
payload = {
"model": "gpt-4-vision-preview",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
},
{
"type": "text",
"text": text_pdf
}
]
}
],
"max_tokens": 1000
}
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
img_preview = response.json()
return img_preview["choices"][0]["message"]["content"]
def message_and_history(pdf_input, input, history, api_key):
history = history or []
s = list(sum(history, ()))
s.append(input)
inp = ' '.join(s)
output = api_calling(pdf_input,inp, api_key)
if len(input) == 0:
input = "Brief description of the pdf."
history.append((input, output))
else:
history.append((input, output))
return history, history
title = "Chat/QnA with PDF"
with gr.Blocks(theme=gr.themes.Soft(primary_hue=gr.themes.colors.slate)) as demo:
gr.Markdown(f'<h1 style="text-align: center;">{title}</h1>')
with gr.Row():
with gr.Column():
pdf_input = gr.File(type="file", label="Upload .pdf File")
api_input = gr.Textbox(label= "Enter Api-key")
upload_button = gr.Button(value="Upload & Start Chat", interactive=True, variant="primary")
with gr.Column():
chatbot = gr.Chatbot(label="Chatbot")
message = gr.Textbox(label="User", placeholder=prompt)
state = gr.State()
upload_button.click(message_and_history, inputs=[pdf_input, message, state, api_input], outputs=[chatbot, state])
message.submit(message_and_history, inputs=[pdf_input, message, state, api_input], outputs=[chatbot, state])
message.submit(lambda: None, None, message, queue=False)
demo.launch()