File size: 1,739 Bytes
c6c1ce5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import PyPDF2
import openai
from config import OPENAI_API_KEY
import os
openai.api_key = os.getenv("OPENAI_API_KEY")

def extract_text_from_pdf(pdf_file):
    text = ""
    with open(pdf_file.name, "rb") as file:
        reader = PyPDF2.PdfReader(file)
        for page in reader.pages:
            text += page.extract_text() + "\n"
    return text

def answer_question(pdf_file, question):
    # Extract text from the PDF
    text = extract_text_from_pdf(pdf_file)
    
    # Define the assistant's behavior
    assistant_prompt = f"""
    You are a helpful assistant that answers questions based on the content of the PDF provided.
    Here is the content of the PDF:
    {text}

    User question: {question}
    """

    # Call OpenAI API to get the answer using GPT-4 Turbo
    response = openai.ChatCompletion.create(
        model="gpt-4-turbo",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": assistant_prompt}
        ]
    )
    
    answer = response.choices[0].message['content']
    return answer

# Create Gradio interface using the updated input/output classes
iface = gr.Interface(
    fn=answer_question,
    inputs=[
        gr.File(label="Upload PDF"),
        gr.Textbox(label="Ask a question about the PDF", placeholder="What do you want to know?")
    ],
    outputs="text",
    title="PDF Q&A with OpenAI Assistant",
    description="Upload a PDF document and ask questions about its content. The assistant will provide answers based on the PDF.",
    examples=[
        ["renesas-ra6m1-group-datasheet.pdf", "Which Renesas products are mentioned in this PDF?"]
    ]
)

# Launch the interface
iface.launch()