Skip to content

Instantly share code, notes, and snippets.

@radames
Created February 1, 2023 20:16
Show Gist options
  • Save radames/3785cd653fc11bad1dbe76f397b11b39 to your computer and use it in GitHub Desktop.
Save radames/3785cd653fc11bad1dbe76f397b11b39 to your computer and use it in GitHub Desktop.
Save Image from API inference Stable Diffusion on Hugging Face in Python
import json
import requests
from PIL import Image
import io
import re
from time import time
API_TOKEN = "" # token in case you want to use private API
headers = {
# "Authorization": f"Bearer {API_TOKEN}",
"X-Wait-For-Model": "true",
"X-Use-Cache": "false"
}
API_URL = "https://api-inference.huggingface.co/models/runwayml/stable-diffusion-v1-5"
def query(payload):
data = json.dumps(payload)
response = requests.request("POST", API_URL, headers=headers, data=data)
return Image.open(io.BytesIO(response.content))
def slugify(text):
# remove non-word characters and foreign characters
text = re.sub(r"[^\w\s]", "", text)
text = re.sub(r"\s+", "-", text)
return text
prompt = "A photo of a a flyiing cat"
image = query({"inputs": prompt})
image.save(f"{slugify(prompt)}-{time():.0f}.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment