ZENLLC commited on
Commit
acddccd
·
verified ·
1 Parent(s): d15e3b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -39
app.py CHANGED
@@ -1,67 +1,102 @@
 
 
 
1
  import gradio as gr
2
- import openai, os, asyncio
 
 
 
3
 
4
- TITLE = "ZEN AI Playground — Ask, Learn, Create"
5
- TAGLINE = "A simple way to chat with GPT-5 and get an instant image suggestion."
6
 
7
- def check_key(key):
8
- if not key or not key.startswith("sk-"):
9
- raise gr.Error("Please paste a valid OpenAI API key starting with 'sk-'.")
10
- return key.strip()
 
11
 
12
- async def ask_ai(api_key, question):
13
- check_key(api_key)
14
- openai.api_key = api_key
 
 
15
  try:
16
- # --- Text reply ---
17
- text_resp = await asyncio.to_thread(
18
- openai.ChatCompletion.create,
19
- model="gpt-5", # works if your account has access; fallback below otherwise
20
- messages=[{"role": "user", "content": question}],
21
  temperature=0.7,
22
  )
23
- answer = text_resp["choices"][0]["message"]["content"]
24
-
25
  except Exception as e:
26
- # Fallback to gpt-4o if gpt-5 unavailable
27
- try:
28
- text_resp = await asyncio.to_thread(
29
- openai.ChatCompletion.create,
30
  model="gpt-4o",
31
- messages=[{"role": "user", "content": question}],
32
  temperature=0.7,
33
  )
34
- answer = text_resp["choices"][0]["message"]["content"]
35
- except Exception as ee:
36
- raise gr.Error(f"OpenAI error: {ee}")
37
 
38
- # --- Optional Image generation ---
 
 
 
39
  try:
40
- img_resp = await asyncio.to_thread(
41
- openai.Image.create,
42
- model="dall-e-3",
43
- prompt=question,
44
- n=1,
45
  size="512x512",
 
46
  )
47
- image_url = img_resp["data"][0]["url"]
 
 
48
  except Exception:
49
- image_url = None
 
 
 
 
 
 
50
 
51
- return answer, image_url
 
 
 
 
 
 
 
 
52
 
53
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
54
  gr.Markdown(f"## {TITLE}\n{TAGLINE}")
55
 
56
- api_key = gr.Textbox(label="OpenAI API Key", type="password", placeholder="sk-...")
57
- question = gr.Textbox(label="Ask anything about AI, science, or creativity", lines=3)
58
- run_btn = gr.Button("Generate Response", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  with gr.Row():
61
  text_out = gr.Markdown(label="AI Response")
62
- img_out = gr.Image(label="Suggested Image", show_label=True)
63
 
64
- run_btn.click(fn=ask_ai, inputs=[api_key, question], outputs=[text_out, img_out])
65
 
66
  if __name__ == "__main__":
67
  demo.queue().launch()
 
1
+ import base64, io
2
+ from typing import Optional
3
+
4
  import gradio as gr
5
+ from PIL import Image
6
+
7
+ # OpenAI SDK v1 style
8
+ from openai import OpenAI
9
 
10
+ TITLE = "ZEN AI Playground — Beginner Edition"
11
+ TAGLINE = "Paste one key. Pick a model. Get an answer (and an optional image)."
12
 
13
+ def ensure_key(key: str) -> str:
14
+ key = (key or "").strip()
15
+ if not key.startswith("sk-") or len(key) < 20:
16
+ raise gr.Error("Please paste a valid OpenAI API key (starts with 'sk-').")
17
+ return key
18
 
19
+ def try_text(client: OpenAI, model: str, prompt: str) -> str:
20
+ """
21
+ Try a chat completion on the given model.
22
+ If that fails (e.g., model not available), fallback to gpt-4o.
23
+ """
24
  try:
25
+ r = client.chat.completions.create(
26
+ model=model,
27
+ messages=[{"role": "user", "content": prompt}],
 
 
28
  temperature=0.7,
29
  )
30
+ return r.choices[0].message.content
 
31
  except Exception as e:
32
+ # fallback if the selected model isn't available for the account
33
+ if model != "gpt-4o":
34
+ r = client.chat.completions.create(
 
35
  model="gpt-4o",
36
+ messages=[{"role": "user", "content": prompt}],
37
  temperature=0.7,
38
  )
39
+ return r.choices[0].message.content
40
+ raise gr.Error(f"OpenAI text error: {e}")
 
41
 
42
+ def try_image(client: OpenAI, prompt: str) -> Optional[Image.Image]:
43
+ """
44
+ Generate an image with gpt-image-1. If not permitted, return None.
45
+ """
46
  try:
47
+ img = client.images.generate(
48
+ model="gpt-image-1",
49
+ prompt=prompt,
 
 
50
  size="512x512",
51
+ n=1,
52
  )
53
+ b64 = img.data[0].b64_json
54
+ raw = base64.b64decode(b64)
55
+ return Image.open(io.BytesIO(raw)).convert("RGB")
56
  except Exception:
57
+ return None
58
+
59
+ def run(api_key: str, model_choice: str, prompt: str):
60
+ api_key = ensure_key(api_key)
61
+ prompt = (prompt or "").strip()
62
+ if not prompt:
63
+ raise gr.Error("Please enter a prompt/question.")
64
 
65
+ client = OpenAI(api_key=api_key)
66
+
67
+ # 1) Text
68
+ answer = try_text(client, model_choice, prompt)
69
+
70
+ # 2) Image (best-effort)
71
+ image = try_image(client, prompt)
72
+
73
+ return answer, image
74
 
75
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
76
  gr.Markdown(f"## {TITLE}\n{TAGLINE}")
77
 
78
+ with gr.Row():
79
+ with gr.Column(scale=1):
80
+ key = gr.Textbox(label="OpenAI API Key", type="password", placeholder="sk-...")
81
+ model = gr.Dropdown(
82
+ label="Model",
83
+ choices=["gpt-4o", "gpt-4o-mini", "gpt-5"],
84
+ value="gpt-4o",
85
+ info="Use gpt-4o for widest access. Pick gpt-5 only if your account has it."
86
+ )
87
+ with gr.Column(scale=2):
88
+ prompt = gr.Textbox(
89
+ label="Ask anything",
90
+ placeholder="Explain how transformers work like I’m new to AI…",
91
+ lines=4
92
+ )
93
+ go = gr.Button("Generate", variant="primary")
94
 
95
  with gr.Row():
96
  text_out = gr.Markdown(label="AI Response")
97
+ image_out = gr.Image(label="Generated Image (optional)", type="pil")
98
 
99
+ go.click(run, inputs=[key, model, prompt], outputs=[text_out, image_out])
100
 
101
  if __name__ == "__main__":
102
  demo.queue().launch()