Spaces:
Sleeping
Sleeping
added diffusion model name
Browse files- TextToImage_StableDiffusion.py +49 -47
TextToImage_StableDiffusion.py
CHANGED
|
@@ -1,48 +1,50 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import io
|
| 3 |
-
import IPython.display
|
| 4 |
-
from PIL import Image
|
| 5 |
-
import base64
|
| 6 |
-
import re
|
| 7 |
-
|
| 8 |
-
from dotenv import load_dotenv, find_dotenv
|
| 9 |
-
_ = load_dotenv(find_dotenv()) # read local .env file
|
| 10 |
-
hf_api_key = os.environ['HF_API_KEY']
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
| 48 |
return pil_image
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
import IPython.display
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import base64
|
| 6 |
+
import re
|
| 7 |
+
|
| 8 |
+
from dotenv import load_dotenv, find_dotenv
|
| 9 |
+
_ = load_dotenv(find_dotenv()) # read local .env file
|
| 10 |
+
# hf_api_key = os.environ['HF_API_KEY']
|
| 11 |
+
hf_api_key = os.getenv('HF_API_KEY')
|
| 12 |
+
HF_API_TTI_BASE='https://api-inference.huggingface.co/models/runwayml/stable-diffusion-v1-5'
|
| 13 |
+
|
| 14 |
+
# Helper function
|
| 15 |
+
import requests, json
|
| 16 |
+
|
| 17 |
+
#Text-to-image endpoint
|
| 18 |
+
def get_completion(inputs, parameters=None, ENDPOINT_URL=HF_API_TTI_BASE):
|
| 19 |
+
headers = {
|
| 20 |
+
"Authorization": f"Bearer {hf_api_key}",
|
| 21 |
+
"Content-Type": "application/json"
|
| 22 |
+
}
|
| 23 |
+
data = { "inputs": inputs }
|
| 24 |
+
if parameters is not None:
|
| 25 |
+
data.update({"parameters": parameters})
|
| 26 |
+
response = requests.request("POST",
|
| 27 |
+
ENDPOINT_URL,
|
| 28 |
+
headers=headers,
|
| 29 |
+
data=json.dumps(data))
|
| 30 |
+
image_bytes = response.content
|
| 31 |
+
return image_bytes
|
| 32 |
+
|
| 33 |
+
def base64_to_pil(image_bytes):
|
| 34 |
+
# base64_decoded = base64.b64decode(img_base64)
|
| 35 |
+
byte_stream = io.BytesIO(image_bytes)
|
| 36 |
+
byte_stream.seek(0)
|
| 37 |
+
try:
|
| 38 |
+
pil_image = Image.open(byte_stream)
|
| 39 |
+
pil_image.verify()
|
| 40 |
+
except (IOError, SyntaxError) as e:
|
| 41 |
+
print("Error: ", e)
|
| 42 |
+
pil_image = Image.open(byte_stream)
|
| 43 |
+
return pil_image
|
| 44 |
+
|
| 45 |
+
def generate(prompt):
|
| 46 |
+
prompt = re.sub(' +', ' ', prompt)
|
| 47 |
+
prompt = re.sub('[^A-Za-z0-9., ]+', '', prompt)
|
| 48 |
+
output = get_completion(prompt)
|
| 49 |
+
pil_image = base64_to_pil(output)
|
| 50 |
return pil_image
|