File size: 1,694 Bytes
72058bd
4f21220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b3d449
4f21220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import openai
import os
import PyPDF2

# Read the API key from environment variable (you'll store it on Hugging Face Spaces)
openai.api_key = os.getenv("OPENAI_API_KEY")

def read_pdf(file):
    if file is None:
        return ""
    reader = PyPDF2.PdfReader(file)
    text = ""
    for page in reader.pages:
        text += page.extract_text()
    return text

def chat_with_openai(user_input, model_name, uploaded_pdf):
    pdf_text = read_pdf(uploaded_pdf) if uploaded_pdf else ""
    prompt = f"{pdf_text}\n\nUser Query: {user_input}" if pdf_text else user_input

    try:
        response = openai.ChatCompletion.create(
            model=model_name,
            messages=[{"role": "user", "content": prompt}]
        )
        return response['choices'][0]['message']['content']
    except Exception as e:
        return f"Error: {str(e)}"

with gr.Blocks() as app:
    gr.Markdown("# 🔥 OpenAI Chat + PDF Analysis Tool")
    with gr.Row():
        model_selector = gr.Dropdown(
            choices=["gpt-3.5-turbo", "gpt-4", "gpt-4-turbo"],
            label="Select OpenAI Model",
            value="gpt-3.5-turbo"
        )
    with gr.Row():
        uploaded_pdf = gr.File(label="Upload a PDF (optional)", file_types=[".pdf"])
    with gr.Row():
        user_input = gr.Textbox(label="Your Prompt", placeholder="Ask anything...")
    with gr.Row():
        submit_btn = gr.Button("Submit")
    with gr.Row():
        response_output = gr.Textbox(label="OpenAI Response", lines=10, interactive=True)

    submit_btn.click(
        fn=chat_with_openai,
        inputs=[user_input, model_selector, uploaded_pdf],
        outputs=response_output
    )

app.launch()