Hi, when generating thumbnail images with midjourney, there is a strange error. At first, my chatbot didn’t link images. Then when prompted, it provided URLs instead of the embedded image like in Pickaxe v1
Is there anything I need to change in my code for v2? Or is it a bug that needs to be updated for v2?
Here’s a video of the bug: Watch Recording #18 | Streamable
And my code:
import os
import requests
import time
import shutil
def midjourney_images_userapi_copy(prompt: str):
"""
Generate a 4-up Midjourney image, then upscale all 4 images (choices 1-4) individually. Save each upscaled image to your server and return their paths.
Args:
prompt (string): prompt for the image
Envs:
USERAPI_KEY (string): <a href='https://blog.userapi.ai/post/5' target='_blank'>UserAPI Documentation</a>
"""
# -------------------------------------------------------------------------
# 1. Get the API Key and Set Headers
# -------------------------------------------------------------------------
api_key = os.getenv('USERAPI_KEY')
if not api_key:
raise ValueError("USERAPI_KEY environment variable not set")
headers = {
"api-key": api_key,
"Content-Type": "application/json"
}
# -------------------------------------------------------------------------
# 2. Call /imagine to generate the 4-up grid
# -------------------------------------------------------------------------
imagine_url = "https://api.userapi.ai/midjourney/v2/imagine"
imagine_payload = {
"prompt": prompt,
"is_disable_prefilter": False
}
imagine_resp = requests.post(imagine_url, json=imagine_payload, headers=headers)
if imagine_resp.status_code != 200:
raise Exception(f"/imagine request failed: {imagine_resp.status_code} {imagine_resp.text}")
grid_hash = imagine_resp.json()["hash"]
print(f"<!--Grid Hash: {grid_hash} -->")
# Poll until the 4-up grid is done
for _ in range(90):
status_resp = requests.get(
f"https://api.userapi.ai/midjourney/v2/status?hash={grid_hash}",
headers=headers
)
status_data = status_resp.json()
if status_data.get("result") and status_data.get("status") == "done":
break
elif status_data.get("status") == "error":
raise Exception(f"Image generation failed: {status_data.get('status_reason')}")
time.sleep(1)
else:
raise Exception("4-up image generation timed out.")
# -------------------------------------------------------------------------
# 3. Upscale each of the 4 images separately
# -------------------------------------------------------------------------
upscaled_paths = {}
for choice_num in range(1, 5): # 1 through 4
# 3a. Request upscale for this particular choice
upscale_url = "https://api.userapi.ai/midjourney/v2/upscale"
upscale_payload = {
"hash": grid_hash,
"choice": choice_num
}
upscale_resp = requests.post(upscale_url, json=upscale_payload, headers=headers)
if upscale_resp.status_code != 200:
raise Exception(f"/upscale request failed: {upscale_resp.status_code} {upscale_resp.text}")
# 3b. Get the new or same hash for tracking this upscale
upscale_hash = upscale_resp.json().get("hash", grid_hash)
print(f"<!--Upscale Hash for choice {choice_num}: {upscale_hash} -->")
# 3c. Poll until this single upscaled image is done
upscaled_image_url = None
for _ in range(90):
upscale_status_resp = requests.get(
f"https://api.userapi.ai/midjourney/v2/status?hash={upscale_hash}",
headers=headers
)
upscale_status_data = upscale_status_resp.json()
if (upscale_status_data.get("result")
and upscale_status_data.get("status") == "done"):
upscaled_image_url = upscale_status_data["result"]["url"]
upscaled_image_url = upscaled_image_url.replace("\\u0026", "&")
break
elif upscale_status_data.get("status") == "error":
raise Exception(f"Upscale failed: {upscale_status_data.get('status_reason')}")
time.sleep(1)
else:
raise Exception(f"Upscale timed out for choice {choice_num}.")
# 3d. Download the single upscaled image
if upscaled_image_url:
filename = f"upscaled_image_{choice_num}.png"
image_resp = requests.get(upscaled_image_url, stream=True)
if image_resp.status_code == 200:
with open(filename, "wb") as f:
image_resp.raw.decode_content = True
shutil.copyfileobj(image_resp.raw, f)
print(f"Choice {choice_num} upscaled image downloaded: {filename}")
upscaled_paths[choice_num] = filename
else:
raise Exception(f"Failed to download the image for choice {choice_num}.")
else:
raise Exception(f"No URL found for upscaled choice {choice_num}.")
return upscaled_paths