Last active
October 12, 2023 10:42
-
-
Save notune/8c8e4ecb18f76432df5e9849538e9e5b to your computer and use it in GitHub Desktop.
Use Google Imagen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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