Skip to content

Instantly share code, notes, and snippets.

@notune
Last active October 12, 2023 10:42
Show Gist options
  • Save notune/8c8e4ecb18f76432df5e9849538e9e5b to your computer and use it in GitHub Desktop.
Save notune/8c8e4ecb18f76432df5e9849538e9e5b to your computer and use it in GitHub Desktop.
Use Google Imagen
import re
import requests
import json
import base64
# SET THESE VALUES
PROJECT_ID = "<REPLACE_WITH_YOUR_PROJECT_ID_HERE>"
TOKEN = "<REPLACE_WITH_YOUR_TOKEN_HERE>"
PROMPT = "futuristic portrait of mona lisa, canon eos 5d mark iii, 50mm f/1.4 usm lens"
# Optionally change these values
SAMPLE_COUNT = 4
GUIDANCE_SCALE = "high" # "low", "medium" or "high"
MODEL_VERSION = "002" # "001" or "002"
def generate_image(prompt, token):
url = f"https://us-central1-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/us-central1/publishers/google/models/imagegeneration@{MODEL_VERSION}:predict"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json; charset=utf-8"
}
data = {
"instances": [
{
"prompt": prompt
}
],
"parameters": {
"sampleCount": SAMPLE_COUNT,
"guidanceScale": GUIDANCE_SCALE
}
}
response = requests.post(url, headers=headers, data=json.dumps(data))
return response.json()
def save_images(response_json, prompt):
prompt = re.sub(r'\W+', '', prompt)
for i, prediction in enumerate(response_json['predictions']):
img_data = base64.b64decode(prediction['bytesBase64Encoded'])
# Name the images as prompt_i.png
with open(f'{prompt}_{i}.png', 'wb') as f:
f.write(img_data)
if __name__ == "__main__":
response = generate_image(PROMPT, TOKEN)
save_images(response, PROMPT)
@notune
Copy link
Author

notune commented Jul 20, 2023

Usage

Login to Google Cloud Console - Imagen and click on the cloud shell in the top left corner
grafik

Then enter gcloud auth print-access-token press ENTER and click on Authorize. Copy the Access-Token and paste it into line 8.

In the top left corner click on "My Project" (or similar)
grafik
and copy the project id to paste it into line 7 of the python script.
grafik
Then before using the script install requests by executing pip install requests and finally execute the script with python imagen.py.

You can change the prompt and more settings at the top of the script.

@notune
Copy link
Author

notune commented Jul 20, 2023

apparently you have to gain access via https://cloud.google.com/ai/earlyaccess/join?hl=en which is weird because I never got an invite mail, only news from the trusted tester newsletter, but can still use the api

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment