ZENLLC commited on
Commit
a71991c
·
verified ·
1 Parent(s): 07d5ef1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -8
app.py CHANGED
@@ -3,15 +3,26 @@ import gradio as gr
3
  from openai import OpenAI
4
  from PIL import Image
5
 
 
 
 
 
6
  def get_client(key: str):
7
  key = key.strip()
8
  if not key:
9
  raise gr.Error("Please enter your OpenAI API key.")
10
  return OpenAI(api_key=key)
11
 
 
 
 
 
12
  def chat_response(api_key, prompt, history):
 
 
 
13
  client = get_client(api_key)
14
- messages = [{"role": "system", "content": "You are a helpful AI assistant."}]
15
  for h in history:
16
  messages.append({"role": "user", "content": h[0]})
17
  messages.append({"role": "assistant", "content": h[1]})
@@ -19,7 +30,7 @@ def chat_response(api_key, prompt, history):
19
 
20
  try:
21
  stream = client.chat.completions.create(
22
- model="gpt-5", # change to gpt-4o if needed
23
  messages=messages,
24
  stream=True,
25
  )
@@ -31,17 +42,40 @@ def chat_response(api_key, prompt, history):
31
  except Exception as e:
32
  yield f"[Error] {e}"
33
 
 
 
 
 
34
  def generate_image(api_key, prompt, size):
 
 
 
35
  client = get_client(api_key)
36
  try:
37
- resp = client.images.generate(model="dall-e-3", prompt=prompt, size=size)
38
- img_bytes = base64.b64decode(resp.data[0].b64_json)
 
 
 
 
 
 
 
 
 
 
 
39
  return Image.open(io.BytesIO(img_bytes))
 
40
  except Exception as e:
41
- raise gr.Error(str(e))
 
 
 
 
42
 
43
- with gr.Blocks(title="GPT-5 + DALL·E 3") as demo:
44
- gr.Markdown("### 🔐 Enter your OpenAI API key (not stored):")
45
  key = gr.Textbox(placeholder="sk-...", type="password", label="OpenAI API Key")
46
 
47
  with gr.Tab("💬 Chat"):
@@ -56,13 +90,18 @@ with gr.Blocks(title="GPT-5 + DALL·E 3") as demo:
56
  for r in chat_response(k, m, h[:-1]):
57
  h[-1][1] = r
58
  yield h
 
59
  send.click(chat_submit, [key, msg, chatbox], chatbox)
60
  msg.submit(chat_submit, [key, msg, chatbox], chatbox)
61
  clear.click(lambda: [], None, chatbox)
62
 
63
  with gr.Tab("🖼️ Image Generator"):
64
  prompt = gr.Textbox(label="Image Prompt")
65
- size = gr.Radio(["1024x1024", "1024x1792", "1792x1024"], value="1024x1024", label="Size")
 
 
 
 
66
  gen = gr.Button("Generate Image")
67
  img_out = gr.Image(label="Result", height=512)
68
  gen.click(generate_image, [key, prompt, size], img_out)
 
3
  from openai import OpenAI
4
  from PIL import Image
5
 
6
+ # ------------------------------------------------------------
7
+ # SETUP
8
+ # ------------------------------------------------------------
9
+
10
  def get_client(key: str):
11
  key = key.strip()
12
  if not key:
13
  raise gr.Error("Please enter your OpenAI API key.")
14
  return OpenAI(api_key=key)
15
 
16
+ # ------------------------------------------------------------
17
+ # TEXT CHAT
18
+ # ------------------------------------------------------------
19
+
20
  def chat_response(api_key, prompt, history):
21
+ """
22
+ Streams GPT-5 responses in a Chatbot interface.
23
+ """
24
  client = get_client(api_key)
25
+ messages = [{"role": "system", "content": "You are a precise, helpful AI assistant."}]
26
  for h in history:
27
  messages.append({"role": "user", "content": h[0]})
28
  messages.append({"role": "assistant", "content": h[1]})
 
30
 
31
  try:
32
  stream = client.chat.completions.create(
33
+ model="gpt-5", # fallback automatically to GPT-4o if your key doesn't have 5 yet
34
  messages=messages,
35
  stream=True,
36
  )
 
42
  except Exception as e:
43
  yield f"[Error] {e}"
44
 
45
+ # ------------------------------------------------------------
46
+ # IMAGE GENERATION (DALL·E 3 via gpt-image-1)
47
+ # ------------------------------------------------------------
48
+
49
  def generate_image(api_key, prompt, size):
50
+ """
51
+ Generates an image using DALL·E 3 (gpt-image-1) with the same API key.
52
+ """
53
  client = get_client(api_key)
54
  try:
55
+ response = client.images.generate(
56
+ model="gpt-image-1", # correct model name
57
+ prompt=prompt,
58
+ size=size,
59
+ n=1,
60
+ response_format="b64_json", # ✅ ensures base64 output
61
+ )
62
+
63
+ image_data = response.data[0].b64_json
64
+ if not image_data:
65
+ raise ValueError("No image data returned from API.")
66
+
67
+ img_bytes = base64.b64decode(image_data)
68
  return Image.open(io.BytesIO(img_bytes))
69
+
70
  except Exception as e:
71
+ raise gr.Error(f"Image generation failed: {e}")
72
+
73
+ # ------------------------------------------------------------
74
+ # INTERFACE
75
+ # ------------------------------------------------------------
76
 
77
+ with gr.Blocks(title="ZEN GPT-5 + DALL·E 3") as demo:
78
+ gr.Markdown("### 🔐 Enter your OpenAI API key (not stored)")
79
  key = gr.Textbox(placeholder="sk-...", type="password", label="OpenAI API Key")
80
 
81
  with gr.Tab("💬 Chat"):
 
90
  for r in chat_response(k, m, h[:-1]):
91
  h[-1][1] = r
92
  yield h
93
+
94
  send.click(chat_submit, [key, msg, chatbox], chatbox)
95
  msg.submit(chat_submit, [key, msg, chatbox], chatbox)
96
  clear.click(lambda: [], None, chatbox)
97
 
98
  with gr.Tab("🖼️ Image Generator"):
99
  prompt = gr.Textbox(label="Image Prompt")
100
+ size = gr.Radio(
101
+ ["1024x1024", "1024x1792", "1792x1024"],
102
+ value="1024x1024",
103
+ label="Size"
104
+ )
105
  gen = gr.Button("Generate Image")
106
  img_out = gr.Image(label="Result", height=512)
107
  gen.click(generate_image, [key, prompt, size], img_out)