Spaces:
Sleeping
Sleeping
File size: 5,543 Bytes
0841eca 8ccf632 db4478e bb18612 db4478e 06f0278 beb85d3 bb18612 06f0278 8ccf632 06f0278 8ccf632 b83a14e 6756bf5 1552b2e b83a14e bb18612 837a56e 54192f0 bb18612 837a56e ac67a14 db4478e ac67a14 8ccf632 ac3d055 8ccf632 b83a14e 8ccf632 0a779d1 8ccf632 2b62414 8ccf632 b45a5e9 |
1 2 3 4 5 6 7 8 9 10 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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 |
import os
import gradio as gr
import numpy as np
import random
import spaces
import torch
import tempfile
import os
import requests
import time
from io import BytesIO
from PIL import Image
token = os.environ["API_TOKEN"]
model = "black-forest-labs/FLUX.1-schnell"
dtype = torch.bfloat16
device = "cuda" if torch.cuda.is_available() else "cpu"
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 2048
custom_css = """
.built-with {
display: none !important;
}
.show-api {
display: none !important;
}
"""
def text_to_image(prompt, height, width, seed, num_inference_steps,
model=model,
token=token):
"""
Generate an image from a text prompt using the Hugging Face Inference API.
Returns a PIL Image (JPEG) if successful, otherwise returns None after retrying.
Parameters:
prompt (str): The text prompt describing the image.
height (int): Height of the generated image.
width (int): Width of the generated image.
seed (int): Random seed for generation reproducibility.
num_inference_steps (int): Number of inference steps.
model (str): Hugging Face model identifier.
token (str): Hugging Face API token.
Returns:
PIL.Image.Image or None: The generated image as a PIL Image object or None on failure.
"""
api_url = f"https://api-inference.huggingface.co/models/{model}"
headers = {
"Authorization": f"Bearer {token}"
}
payload = {
"inputs": prompt,
"parameters": {
"height": height,
"width": width,
"seed": seed,
"num_inference_steps": num_inference_steps
}
}
for attempt in range(1, 4):
response = requests.post(api_url, headers=headers, json=payload)
if response.status_code == 200:
try:
image = Image.open(BytesIO(response.content))
if image.format != 'JPEG':
with BytesIO() as output:
image.convert("RGB").save(output, format="JPEG")
output.seek(0)
image = Image.open(output)
return image
except Exception as e:
print(f"Error processing the image data: {e}")
else:
print(f"Attempt {attempt}: Request failed with status code {response.status_code}")
if attempt == 1:
print("Waiting for 3 seconds before retrying...")
time.sleep(3)
elif attempt == 2:
print("Waiting for 5 seconds before retrying...")
time.sleep(5)
return None
def infer(prompt, seed=42, randomize_seed=True, width=1024, height=1024, num_inference_steps=4, progress=gr.Progress(track_tqdm=True)):
if randomize_seed:
seed = random.randint(0, MAX_SEED)
image = text_to_image(
prompt,
height=height,
width=width,
seed=seed,
num_inference_steps=4
)
temp_dir = tempfile.gettempdir()
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg", dir=temp_dir)
image.save(temp_file, format="JPEG")
temp_file_path = temp_file.name
temp_file.close()
return temp_file_path, seed
examples = [
"A girl and a boy dancing in the forest",
"Tiny cat in a space suite in the moon",
"an anime illustration of girl holding book in her hand in a library",
]
with gr.Blocks(css=custom_css) as demo:
with gr.Column(elem_id="col-container"):
with gr.Row():
prompt = gr.Text(
label="Prompt",
show_label=False,
max_lines=1,
placeholder="Enter your prompt",
container=False,
)
run_button = gr.Button("Run", scale=0)
result = gr.Image(label="Result", show_label=False)
with gr.Accordion("Advanced Settings", open=False):
seed = gr.Slider(
label="Seed",
minimum=0,
maximum=MAX_SEED,
step=1,
value=0,
)
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
with gr.Row():
width = gr.Slider(
label="Width",
minimum=256,
maximum=MAX_IMAGE_SIZE,
step=32,
value=1024,
)
height = gr.Slider(
label="Height",
minimum=256,
maximum=MAX_IMAGE_SIZE,
step=32,
value=1024,
)
with gr.Row():
num_inference_steps = gr.Slider(
label="Number of inference steps",
minimum=1,
maximum=50,
step=1,
value=4,
)
gr.Examples(
examples = examples,
fn = infer,
inputs = [prompt],
outputs = [result, seed],
cache_examples="lazy"
)
gr.on(
triggers=[run_button.click, prompt.submit],
fn = infer,
inputs = [prompt, seed, randomize_seed, width, height, num_inference_steps],
outputs = [result, seed]
)
demo.launch()#show_api=False) |