namelessai commited on
Commit
09e37fb
·
verified ·
1 Parent(s): 58a4da0

Add better error handling

Browse files
Files changed (1) hide show
  1. app.py +26 -14
app.py CHANGED
@@ -9,7 +9,6 @@ import gradio as gr
9
  # Make sure you export your API token before running this script:
10
  # export CHUTES_API_TOKEN="your_real_token_here"
11
  # ------------------------------------------------------------------------------
12
-
13
  API_TOKEN = os.getenv("CHUTES_API_TOKEN")
14
  if API_TOKEN is None:
15
  raise ValueError("Please set the environment variable CHUTES_API_TOKEN before running.")
@@ -21,7 +20,8 @@ def generate_image(prompt: str,
21
  shift: int) -> Image.Image:
22
  """
23
  Calls the HiDream (Chutes) API to generate an image from the given prompt
24
- and parameters. Returns a PIL.Image.
 
25
  """
26
  headers = {
27
  "Authorization": f"Bearer {API_TOKEN}",
@@ -42,32 +42,45 @@ def generate_image(prompt: str,
42
  json=payload
43
  )
44
 
 
45
  if response.status_code != 200:
46
- # you can customize error handling as needed
47
- raise RuntimeError(f"API returned {response.status_code}: {response.text}")
 
 
 
 
 
48
 
49
- data = response.json()
50
- # Typically, the API returns a base64‐encoded image under the key "image".
51
- # If yours returns a URL (e.g. under "url"), you can fetch that instead.
52
  b64_img = data.get("image")
53
  if b64_img:
54
- decoded = base64.b64decode(b64_img)
55
- img = Image.open(io.BytesIO(decoded)).convert("RGB")
56
- return img
 
 
 
57
 
58
- # Fallback: if the API returns a direct URL
59
  img_url = data.get("url") or data.get("image_url")
60
  if img_url:
61
  img_response = requests.get(img_url)
 
 
62
  img = Image.open(io.BytesIO(img_response.content)).convert("RGB")
63
  return img
64
 
65
- raise RuntimeError("No image field found in API response.")
 
66
 
67
 
68
  # Build the Gradio interface
69
  with gr.Blocks(title="HiDream Unlimited") as demo:
70
- gr.Markdown("## HiDream Unlimited\nGenerate unlimited AI‐driven images powered by HiDream/Chutes.\n\nEnter your prompt and tweak the parameters, then click **Generate**.")
 
 
 
 
71
 
72
  with gr.Row():
73
  with gr.Column(scale=1):
@@ -98,7 +111,6 @@ with gr.Blocks(title="HiDream Unlimited") as demo:
98
  with gr.Column(scale=1):
99
  output_img = gr.Image(label="Generated Image", interactive=False)
100
 
101
- # Wire up the button
102
  generate_btn.click(
103
  fn=generate_image,
104
  inputs=[prompt_in, resolution_in, guidance_in, steps_in, shift_in],
 
9
  # Make sure you export your API token before running this script:
10
  # export CHUTES_API_TOKEN="your_real_token_here"
11
  # ------------------------------------------------------------------------------
 
12
  API_TOKEN = os.getenv("CHUTES_API_TOKEN")
13
  if API_TOKEN is None:
14
  raise ValueError("Please set the environment variable CHUTES_API_TOKEN before running.")
 
20
  shift: int) -> Image.Image:
21
  """
22
  Calls the HiDream (Chutes) API to generate an image from the given prompt
23
+ and parameters. Returns a PIL.Image on success. Raises a RuntimeError on failure,
24
+ including if the API returns a non‐JSON response.
25
  """
26
  headers = {
27
  "Authorization": f"Bearer {API_TOKEN}",
 
42
  json=payload
43
  )
44
 
45
+ # If the status code isn’t 200, raise immediately
46
  if response.status_code != 200:
47
+ raise RuntimeError(f"API returned HTTP {response.status_code}:\n{response.text}")
48
+
49
+ # Try to parse JSON; if that fails, surface raw text
50
+ try:
51
+ data = response.json()
52
+ except Exception as e:
53
+ raise RuntimeError(f"Failed to parse JSON (status {response.status_code}):\n{response.text}") from e
54
 
55
+ # The API may return base64 under "image", or a URL under "url"/"image_url"
 
 
56
  b64_img = data.get("image")
57
  if b64_img:
58
+ try:
59
+ decoded = base64.b64decode(b64_img)
60
+ img = Image.open(io.BytesIO(decoded)).convert("RGB")
61
+ return img
62
+ except Exception as e:
63
+ raise RuntimeError(f"Error decoding base64 image:\n{str(e)}")
64
 
 
65
  img_url = data.get("url") or data.get("image_url")
66
  if img_url:
67
  img_response = requests.get(img_url)
68
+ if img_response.status_code != 200:
69
+ raise RuntimeError(f"Failed to fetch image URL ({img_url}): HTTP {img_response.status_code}")
70
  img = Image.open(io.BytesIO(img_response.content)).convert("RGB")
71
  return img
72
 
73
+ # If neither field is present, raise an error
74
+ raise RuntimeError(f"No 'image' or 'url' field found in API response JSON:\n{data}")
75
 
76
 
77
  # Build the Gradio interface
78
  with gr.Blocks(title="HiDream Unlimited") as demo:
79
+ gr.Markdown(
80
+ "## HiDream Unlimited\n\n"
81
+ "Generate unlimited AI‐driven images powered by HiDream/Chutes.\n\n"
82
+ "Enter your prompt and tweak the parameters, then click **Generate**."
83
+ )
84
 
85
  with gr.Row():
86
  with gr.Column(scale=1):
 
111
  with gr.Column(scale=1):
112
  output_img = gr.Image(label="Generated Image", interactive=False)
113
 
 
114
  generate_btn.click(
115
  fn=generate_image,
116
  inputs=[prompt_in, resolution_in, guidance_in, steps_in, shift_in],