Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import PyPDF2
|
| 3 |
+
import openai
|
| 4 |
+
from config import OPENAI_API_KEY
|
| 5 |
+
import os
|
| 6 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 7 |
+
|
| 8 |
+
def extract_text_from_pdf(pdf_file):
|
| 9 |
+
text = ""
|
| 10 |
+
with open(pdf_file.name, "rb") as file:
|
| 11 |
+
reader = PyPDF2.PdfReader(file)
|
| 12 |
+
for page in reader.pages:
|
| 13 |
+
text += page.extract_text() + "\n"
|
| 14 |
+
return text
|
| 15 |
+
|
| 16 |
+
def answer_question(pdf_file, question):
|
| 17 |
+
# Extract text from the PDF
|
| 18 |
+
text = extract_text_from_pdf(pdf_file)
|
| 19 |
+
|
| 20 |
+
# Define the assistant's behavior
|
| 21 |
+
assistant_prompt = f"""
|
| 22 |
+
You are a helpful assistant that answers questions based on the content of the PDF provided.
|
| 23 |
+
Here is the content of the PDF:
|
| 24 |
+
{text}
|
| 25 |
+
|
| 26 |
+
User question: {question}
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
# Call OpenAI API to get the answer using GPT-4 Turbo
|
| 30 |
+
response = openai.ChatCompletion.create(
|
| 31 |
+
model="gpt-4-turbo",
|
| 32 |
+
messages=[
|
| 33 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
| 34 |
+
{"role": "user", "content": assistant_prompt}
|
| 35 |
+
]
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
answer = response.choices[0].message['content']
|
| 39 |
+
return answer
|
| 40 |
+
|
| 41 |
+
# Create Gradio interface using the updated input/output classes
|
| 42 |
+
iface = gr.Interface(
|
| 43 |
+
fn=answer_question,
|
| 44 |
+
inputs=[
|
| 45 |
+
gr.File(label="Upload PDF"),
|
| 46 |
+
gr.Textbox(label="Ask a question about the PDF", placeholder="What do you want to know?")
|
| 47 |
+
],
|
| 48 |
+
outputs="text",
|
| 49 |
+
title="PDF Q&A with OpenAI Assistant",
|
| 50 |
+
description="Upload a PDF document and ask questions about its content. The assistant will provide answers based on the PDF.",
|
| 51 |
+
examples=[
|
| 52 |
+
["renesas-ra6m1-group-datasheet.pdf", "Which Renesas products are mentioned in this PDF?"]
|
| 53 |
+
]
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# Launch the interface
|
| 57 |
+
iface.launch()
|