ZENLLC commited on
Commit
04b65d7
·
verified ·
1 Parent(s): fb09d6f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -40
app.py CHANGED
@@ -1,7 +1,5 @@
1
- import os, base64, io
2
  import gradio as gr
3
  from openai import OpenAI
4
- from PIL import Image
5
 
6
  # ------------------------------------------------------------
7
  # CLIENT SETUP
@@ -13,7 +11,7 @@ def get_client(key: str):
13
  return OpenAI(api_key=key)
14
 
15
  # ------------------------------------------------------------
16
- # TEXT CHAT (GPT-5)
17
  # ------------------------------------------------------------
18
  def chat_response(api_key, prompt, history):
19
  client = get_client(api_key)
@@ -25,7 +23,7 @@ def chat_response(api_key, prompt, history):
25
 
26
  try:
27
  stream = client.chat.completions.create(
28
- model="gpt-5", # fallback to gpt-4o if your account doesn’t yet support 5
29
  messages=messages,
30
  stream=True,
31
  )
@@ -38,38 +36,33 @@ def chat_response(api_key, prompt, history):
38
  yield f"[Error] {e}"
39
 
40
  # ------------------------------------------------------------
41
- # IMAGE GENERATION (DALL·E 3 / gpt-image-1)
42
  # ------------------------------------------------------------
43
- def generate_image(api_key, prompt, size):
44
  client = get_client(api_key)
45
- try:
46
- response = client.images.generate(
47
- model="gpt-image-1",
48
- prompt=prompt,
49
- size=size,
50
- n=1,
51
- )
52
 
53
- # Defensive extraction: OpenAI may return base64 or URL depending on account
54
- data = response.data[0]
55
- if hasattr(data, "b64_json") and data.b64_json:
56
- img_bytes = base64.b64decode(data.b64_json)
57
- return Image.open(io.BytesIO(img_bytes))
58
- elif hasattr(data, "url") and data.url:
59
- # fallback if only URL provided
60
- import requests
61
- img_bytes = requests.get(data.url).content
62
- return Image.open(io.BytesIO(img_bytes))
63
- else:
64
- raise ValueError("No valid image data returned from API.")
65
 
 
 
 
 
 
 
 
66
  except Exception as e:
67
- raise gr.Error(f"Image generation failed: {e}")
68
 
69
  # ------------------------------------------------------------
70
  # INTERFACE
71
  # ------------------------------------------------------------
72
- with gr.Blocks(title="ZEN GPT-5 + DALL·E 3") as demo:
73
  gr.Markdown("### 🔐 Enter your OpenAI API key (not stored)")
74
  key = gr.Textbox(placeholder="sk-...", type="password", label="OpenAI API Key")
75
 
@@ -81,24 +74,28 @@ with gr.Blocks(title="ZEN GPT-5 + DALL·E 3") as demo:
81
 
82
  def chat_submit(k, m, h):
83
  h = h or []
84
- h.append({"role": "user", "content": m})
85
- for r in chat_response(k, m, [(x["content"], y["content"]) for x, y in zip(h, h)]):
86
- h.append({"role": "assistant", "content": r})
87
  yield h
88
 
89
  send.click(chat_submit, [key, msg, chatbox], chatbox)
90
  msg.submit(chat_submit, [key, msg, chatbox], chatbox)
91
  clear.click(lambda: [], None, chatbox)
92
 
93
- with gr.Tab("🖼️ Image Generator"):
94
- prompt = gr.Textbox(label="Image Prompt")
95
- size = gr.Radio(
96
- ["1024x1024", "1024x1792", "1792x1024"],
97
- value="1024x1024",
98
- label="Size"
99
- )
100
- gen = gr.Button("Generate Image")
101
- img_out = gr.Image(label="Result", height=512)
102
- gen.click(generate_image, [key, prompt, size], img_out)
 
 
 
 
103
 
104
  demo.launch()
 
 
1
  import gradio as gr
2
  from openai import OpenAI
 
3
 
4
  # ------------------------------------------------------------
5
  # CLIENT SETUP
 
11
  return OpenAI(api_key=key)
12
 
13
  # ------------------------------------------------------------
14
+ # GPT-5 CHAT
15
  # ------------------------------------------------------------
16
  def chat_response(api_key, prompt, history):
17
  client = get_client(api_key)
 
23
 
24
  try:
25
  stream = client.chat.completions.create(
26
+ model="gpt-5",
27
  messages=messages,
28
  stream=True,
29
  )
 
36
  yield f"[Error] {e}"
37
 
38
  # ------------------------------------------------------------
39
+ # CODE EXPLAINER / REFACTOR
40
  # ------------------------------------------------------------
41
+ def analyze_code(api_key, code_snippet, mode):
42
  client = get_client(api_key)
43
+ if not code_snippet.strip():
44
+ raise gr.Error("Paste some code first.")
 
 
 
 
 
45
 
46
+ prompt = (
47
+ "Explain this code clearly and suggest improvements:\n\n" + code_snippet
48
+ if mode == "Explain & Improve"
49
+ else "Refactor this code for clarity, efficiency, and style:\n\n" + code_snippet
50
+ )
 
 
 
 
 
 
 
51
 
52
+ try:
53
+ completion = client.chat.completions.create(
54
+ model="gpt-5",
55
+ messages=[{"role": "system", "content": "You are an expert software engineer."},
56
+ {"role": "user", "content": prompt}],
57
+ )
58
+ return completion.choices[0].message.content
59
  except Exception as e:
60
+ raise gr.Error(f"Code analysis failed: {e}")
61
 
62
  # ------------------------------------------------------------
63
  # INTERFACE
64
  # ------------------------------------------------------------
65
+ with gr.Blocks(title="ZEN GPT-5 Production SDK") as demo:
66
  gr.Markdown("### 🔐 Enter your OpenAI API key (not stored)")
67
  key = gr.Textbox(placeholder="sk-...", type="password", label="OpenAI API Key")
68
 
 
74
 
75
  def chat_submit(k, m, h):
76
  h = h or []
77
+ h.append([m, ""])
78
+ for r in chat_response(k, m, h[:-1]):
79
+ h[-1][1] = r
80
  yield h
81
 
82
  send.click(chat_submit, [key, msg, chatbox], chatbox)
83
  msg.submit(chat_submit, [key, msg, chatbox], chatbox)
84
  clear.click(lambda: [], None, chatbox)
85
 
86
+ with gr.Tab("💻 Code Assistant"):
87
+ gr.Markdown("Use GPT-5 to **explain or refactor** any code.")
88
+ code_input = gr.Code(label="Paste your code here", language="python", lines=18)
89
+ mode = gr.Radio(["Explain & Improve", "Refactor Only"], value="Explain & Improve", label="Mode")
90
+ run_btn = gr.Button("Analyze Code", variant="primary")
91
+ result = gr.Textbox(label="Result", lines=18)
92
+ run_btn.click(analyze_code, [key, code_input, mode], result)
93
+
94
+ # footer / watermark
95
+ gr.HTML(
96
+ "<div style='text-align:right; font-size:12px; opacity:0.5; margin-top:12px;'>"
97
+ "Module 3 – ZEN SDK Production"
98
+ "</div>"
99
+ )
100
 
101
  demo.launch()