Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,10 @@
|
|
| 1 |
-
import spaces
|
| 2 |
|
| 3 |
import subprocess
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
| 6 |
@spaces.GPU(required=True)
|
| 7 |
def install_dependencies():
|
| 8 |
subprocess.run(['sh', './flashattn.sh'])
|
|
@@ -48,7 +50,6 @@ from PIL import Image
|
|
| 48 |
# For HDR
|
| 49 |
import pillow_avif
|
| 50 |
import cv2
|
| 51 |
-
|
| 52 |
from google.oauth2 import service_account
|
| 53 |
from google.cloud import storage
|
| 54 |
|
|
@@ -80,7 +81,7 @@ if GCS_SA_KEY and GCS_BUCKET_NAME:
|
|
| 80 |
gcs_client = storage.Client(credentials=credentials)
|
| 81 |
print("✅ GCS Client initialized successfully.")
|
| 82 |
except Exception as e:
|
| 83 |
-
print(f"❌ Failed to initialize GCS client: ")
|
| 84 |
|
| 85 |
def upload_to_gcs(image_bytes, filename):
|
| 86 |
if not gcs_client:
|
|
@@ -90,13 +91,49 @@ def upload_to_gcs(image_bytes, filename):
|
|
| 90 |
print(f"--> Starting GCS upload for {filename}...")
|
| 91 |
bucket = gcs_client.bucket(GCS_BUCKET_NAME)
|
| 92 |
blob = bucket.blob(f"stablediff/{filename}")
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
print(f"✅ Successfully uploaded {filename} to GCS.")
|
| 96 |
except Exception as e:
|
| 97 |
print(f"❌ An error occurred during GCS upload for {filename}: {e}")
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 101 |
|
| 102 |
from diffusers.models.attention_processor import AttnProcessor2_0
|
|
@@ -142,7 +179,7 @@ class FlashAttentionProcessor(AttnProcessor2_0):
|
|
| 142 |
out = out_reshaped.permute(0, 2, 1, 3).reshape(b, t, c)
|
| 143 |
out = attn.to_out(out)
|
| 144 |
return out
|
| 145 |
-
|
| 146 |
@spaces.GPU(duration=120)
|
| 147 |
def compile_transformer():
|
| 148 |
with spaces.aoti_capture(pipe.transformer) as call:
|
|
@@ -153,7 +190,7 @@ def compile_transformer():
|
|
| 153 |
kwargs=call.kwargs,
|
| 154 |
)
|
| 155 |
return spaces.aoti_compile(exported)
|
| 156 |
-
|
| 157 |
def load_model():
|
| 158 |
pipe = StableDiffusion3Pipeline.from_pretrained(
|
| 159 |
"ford442/stable-diffusion-3.5-large-bf16",
|
|
@@ -168,45 +205,6 @@ def load_model():
|
|
| 168 |
upscaler_2 = UpscaleWithModel.from_pretrained("Kim2091/ClearRealityV1").to(device)
|
| 169 |
return pipe, upscaler_2
|
| 170 |
|
| 171 |
-
def srgb_to_linear(img_tensor):
|
| 172 |
-
"""Converts a batched sRGB tensor [0, 1] to a linear tensor."""
|
| 173 |
-
# Using the standard sRGB to linear conversion formula
|
| 174 |
-
return torch.where(
|
| 175 |
-
img_tensor <= 0.04045,
|
| 176 |
-
img_tensor / 12.92,
|
| 177 |
-
((img_tensor + 0.055) / 1.055).pow(2.4)
|
| 178 |
-
)
|
| 179 |
-
|
| 180 |
-
def create_hdr_avif_bytes(sdr_pil_image):
|
| 181 |
-
"""Converts an SDR PIL image to a 10-bit HDR AVIF byte buffer."""
|
| 182 |
-
# 1. Convert SDR PIL image to a float tensor [0, 1]
|
| 183 |
-
srgb_tensor = torch.from_numpy(np.array(sdr_pil_image)).float().to(device) / 255.0
|
| 184 |
-
srgb_tensor = srgb_tensor.permute(2, 0, 1).unsqueeze(0) # HWC to BCHW
|
| 185 |
-
|
| 186 |
-
# 2. Convert sRGB tensor to linear space
|
| 187 |
-
linear_tensor = srgb_to_linear(srgb_tensor)
|
| 188 |
-
|
| 189 |
-
# 3. Convert to 16-bit NumPy array for high-bit-depth processing
|
| 190 |
-
linear_numpy_float = linear_tensor.squeeze(0).permute(1, 2, 0).cpu().numpy()
|
| 191 |
-
hdr_16bit_array = (np.clip(linear_numpy_float, 0, 1) * 65535).astype(np.uint16)
|
| 192 |
-
|
| 193 |
-
# 4. Create a PIL image that holds the 16-bit data
|
| 194 |
-
hdr_pil_image = Image.fromarray(hdr_16bit_array)
|
| 195 |
-
|
| 196 |
-
# 5. Save to a bytes buffer as 10-bit AVIF with HDR10 metadata
|
| 197 |
-
buffer = io.BytesIO()
|
| 198 |
-
hdr_pil_image.save(
|
| 199 |
-
buffer,
|
| 200 |
-
format="AVIF",
|
| 201 |
-
quality=90,
|
| 202 |
-
depth=10, # Specify 10-bit depth
|
| 203 |
-
subsampling="4:4:4",
|
| 204 |
-
color_primaries=9, # BT.2020
|
| 205 |
-
transfer_characteristics=16, # PQ (Perceptual Quantizer)
|
| 206 |
-
matrix_coefficients=9, # BT.2020 non-constant luminance
|
| 207 |
-
)
|
| 208 |
-
return buffer.getvalue()
|
| 209 |
-
|
| 210 |
pipe, upscaler_2 = load_model()
|
| 211 |
|
| 212 |
fa_processor = FlashAttentionProcessor()
|
|
@@ -221,66 +219,126 @@ spaces.aoti_apply(compiled_transformer, pipe.transformer)
|
|
| 221 |
MAX_SEED = np.iinfo(np.int32).max
|
| 222 |
MAX_IMAGE_SIZE = 4096
|
| 223 |
|
| 224 |
-
|
| 225 |
-
def
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
output_type="pil" # Get PIL for display and easy upscaling
|
| 242 |
-
).images[0]
|
| 243 |
-
|
| 244 |
-
# Convert the sRGB tensor [0,1] to a PIL Image for display and upscaling
|
| 245 |
-
sd_image_pil_srgb = Image.fromarray((sd_image_tensor_srgb.squeeze(0).permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8))
|
| 246 |
-
print('-- got image, creating HDR AVIF version --')
|
| 247 |
-
sd_avif_bytes = create_hdr_avif_bytes(sd_image_srgb_pil)
|
| 248 |
-
|
| 249 |
-
print('-- upscaling image --')
|
| 250 |
with torch.no_grad():
|
| 251 |
-
upscale = upscaler_2(
|
| 252 |
upscale2 = upscaler_2(upscale, tiling=True, tile_width=256, tile_height=256)
|
| 253 |
-
print('-- got upscaled image
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
return
|
| 257 |
-
|
| 258 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
-
|
| 261 |
-
def
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
)
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
if save_consent:
|
| 268 |
print("✅ User consented to save. Preparing uploads...")
|
| 269 |
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 270 |
-
sd_filename = f"sd35ll_{timestamp}.
|
| 271 |
-
upscale_filename = f"sd35ll_upscale_{timestamp}.
|
| 272 |
-
|
| 273 |
-
#
|
| 274 |
-
sd_thread = threading.Thread(target=upload_to_gcs, args=(sd_hdr_bytes, sd_filename))
|
| 275 |
-
upscale_thread = threading.Thread(target=upload_to_gcs, args=(upscaled_hdr_bytes, upscale_filename))
|
| 276 |
sd_thread.start()
|
| 277 |
-
upscale_thread.start()
|
| 278 |
else:
|
| 279 |
print("ℹ️ User did not consent to save. Skipping upload.")
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
css = """
|
| 285 |
#col-container {margin: 0 auto;max-width: 640px;}
|
| 286 |
body{background-color: blue;}
|
|
@@ -297,12 +355,11 @@ with gr.Blocks(theme=gr.themes.Origin(), css=css) as demo:
|
|
| 297 |
)
|
| 298 |
run_button_30 = gr.Button("Run30", scale=0, variant="primary")
|
| 299 |
run_button_60 = gr.Button("Run60", scale=0, variant="primary")
|
| 300 |
-
run_button_110 = gr.Button("
|
| 301 |
-
|
| 302 |
-
result = gr.Image(label="Result (SDR Preview)", show_label=False, type="pil")
|
| 303 |
save_consent_checkbox = gr.Checkbox(
|
| 304 |
-
label="✅ Anonymously upload result to a public gallery
|
| 305 |
-
value=True,
|
| 306 |
info="Check this box to help us by contributing your image."
|
| 307 |
)
|
| 308 |
with gr.Accordion("Advanced Settings", open=True):
|
|
@@ -316,30 +373,50 @@ with gr.Blocks(theme=gr.themes.Origin(), css=css) as demo:
|
|
| 316 |
guidance_scale = gr.Slider(label="Guidance scale", minimum=0.0, maximum=30.0, step=0.1, value=4.2)
|
| 317 |
num_inference_steps = gr.Slider(label="Inference steps", minimum=1, maximum=150, step=1, value=60)
|
| 318 |
|
| 319 |
-
# Clicks now call the same function with a different duration parameter
|
| 320 |
run_button_30.click(
|
| 321 |
-
fn=
|
| 322 |
inputs=[
|
| 323 |
-
prompt,
|
| 324 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
],
|
| 326 |
outputs=[result, expanded_prompt_output],
|
| 327 |
)
|
| 328 |
|
| 329 |
run_button_60.click(
|
| 330 |
-
fn=
|
| 331 |
inputs=[
|
| 332 |
-
prompt,
|
| 333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
],
|
| 335 |
outputs=[result, expanded_prompt_output],
|
| 336 |
)
|
| 337 |
|
| 338 |
run_button_110.click(
|
| 339 |
-
fn=
|
| 340 |
inputs=[
|
| 341 |
-
prompt,
|
| 342 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
],
|
| 344 |
outputs=[result, expanded_prompt_output],
|
| 345 |
)
|
|
|
|
|
|
|
| 1 |
|
| 2 |
import subprocess
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
subprocess.run(['sh', './spaces.sh'])
|
| 6 |
+
import spaces
|
| 7 |
+
|
| 8 |
@spaces.GPU(required=True)
|
| 9 |
def install_dependencies():
|
| 10 |
subprocess.run(['sh', './flashattn.sh'])
|
|
|
|
| 50 |
# For HDR
|
| 51 |
import pillow_avif
|
| 52 |
import cv2
|
|
|
|
| 53 |
from google.oauth2 import service_account
|
| 54 |
from google.cloud import storage
|
| 55 |
|
|
|
|
| 81 |
gcs_client = storage.Client(credentials=credentials)
|
| 82 |
print("✅ GCS Client initialized successfully.")
|
| 83 |
except Exception as e:
|
| 84 |
+
print(f"❌ Failed to initialize GCS client: {e}")
|
| 85 |
|
| 86 |
def upload_to_gcs(image_bytes, filename):
|
| 87 |
if not gcs_client:
|
|
|
|
| 91 |
print(f"--> Starting GCS upload for {filename}...")
|
| 92 |
bucket = gcs_client.bucket(GCS_BUCKET_NAME)
|
| 93 |
blob = bucket.blob(f"stablediff/{filename}")
|
| 94 |
+
blob.upload_from_string(image_bytes, content_type='image/avif')
|
| 95 |
+
print(f"✅ Successfully uploaded {} to GCS.")
|
|
|
|
| 96 |
except Exception as e:
|
| 97 |
print(f"❌ An error occurred during GCS upload for {filename}: {e}")
|
| 98 |
|
| 99 |
+
def srgb_to_linear(tensor_srgb):
|
| 100 |
+
"""Converts a batched sRGB PyTorch tensor [0, 1] to a linear tensor."""
|
| 101 |
+
return torch.where(
|
| 102 |
+
tensor_srgb <= 0.04045,
|
| 103 |
+
tensor_srgb / 12.92,
|
| 104 |
+
((tensor_srgb + 0.055) / 1.055).pow(2.4)
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
def create_hdr_avif_bytes(sdr_pil_image):
|
| 108 |
+
"""Converts an SDR PIL image to a 10-bit HDR AVIF byte buffer."""
|
| 109 |
+
# 1. Convert SDR PIL image to a float tensor [0, 1]
|
| 110 |
+
srgb_tensor = torch.from_numpy(np.array(sdr_pil_image)).float().to(device) / 255.0
|
| 111 |
+
srgb_tensor = srgb_tensor.permute(2, 0, 1).unsqueeze(0) # HWC to BCHW
|
| 112 |
+
|
| 113 |
+
# 2. Convert sRGB tensor to linear space
|
| 114 |
+
linear_tensor = srgb_to_linear(srgb_tensor)
|
| 115 |
|
| 116 |
+
# 3. Convert to 16-bit NumPy array for high-bit-depth processing
|
| 117 |
+
linear_numpy_float = linear_tensor.squeeze(0).permute(1, 2, 0).cpu().numpy()
|
| 118 |
+
hdr_16bit_array = (np.clip(linear_numpy_float, 0, 1) * 65535).astype(np.uint16)
|
| 119 |
+
|
| 120 |
+
# 4. Create a PIL image that holds the 16-bit data
|
| 121 |
+
hdr_pil_image = Image.fromarray(hdr_16bit_array)
|
| 122 |
+
|
| 123 |
+
# 5. Save to a bytes buffer as 10-bit AVIF with HDR10 metadata
|
| 124 |
+
buffer = io.BytesIO()
|
| 125 |
+
hdr_pil_image.save(
|
| 126 |
+
buffer,
|
| 127 |
+
format="AVIF",
|
| 128 |
+
quality=90,
|
| 129 |
+
depth=10, # Specify 10-bit depth
|
| 130 |
+
subsampling="4:4:4",
|
| 131 |
+
color_primaries=9, # BT.2020
|
| 132 |
+
transfer_characteristics=16, # PQ (Perceptual Quantizer)
|
| 133 |
+
matrix_coefficients=9, # BT.2020 non-constant luminance
|
| 134 |
+
)
|
| 135 |
+
return buffer.getvalue()
|
| 136 |
+
|
| 137 |
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 138 |
|
| 139 |
from diffusers.models.attention_processor import AttnProcessor2_0
|
|
|
|
| 179 |
out = out_reshaped.permute(0, 2, 1, 3).reshape(b, t, c)
|
| 180 |
out = attn.to_out(out)
|
| 181 |
return out
|
| 182 |
+
|
| 183 |
@spaces.GPU(duration=120)
|
| 184 |
def compile_transformer():
|
| 185 |
with spaces.aoti_capture(pipe.transformer) as call:
|
|
|
|
| 190 |
kwargs=call.kwargs,
|
| 191 |
)
|
| 192 |
return spaces.aoti_compile(exported)
|
| 193 |
+
|
| 194 |
def load_model():
|
| 195 |
pipe = StableDiffusion3Pipeline.from_pretrained(
|
| 196 |
"ford442/stable-diffusion-3.5-large-bf16",
|
|
|
|
| 205 |
upscaler_2 = UpscaleWithModel.from_pretrained("Kim2091/ClearRealityV1").to(device)
|
| 206 |
return pipe, upscaler_2
|
| 207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
pipe, upscaler_2 = load_model()
|
| 209 |
|
| 210 |
fa_processor = FlashAttentionProcessor()
|
|
|
|
| 219 |
MAX_SEED = np.iinfo(np.int32).max
|
| 220 |
MAX_IMAGE_SIZE = 4096
|
| 221 |
|
| 222 |
+
@spaces.GPU(duration=45)
|
| 223 |
+
def generate_images_30(prompt, neg_prompt_1, neg_prompt_2, neg_prompt_3, width, height, guidance, steps, progress=gr.Progress(track_tqdm=True)):
|
| 224 |
+
seed = random.randint(0, MAX_SEED)
|
| 225 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 226 |
+
print('-- generating image --')
|
| 227 |
+
torch.cuda.empty_cache()
|
| 228 |
+
torch.cuda.reset_peak_memory_stats()
|
| 229 |
+
sd_image = pipe(
|
| 230 |
+
prompt=prompt, prompt_2=prompt, prompt_3=prompt,
|
| 231 |
+
negative_prompt=neg_prompt_1, negative_prompt_2=neg_prompt_2, negative_prompt_3=neg_prompt_3,
|
| 232 |
+
guidance_scale=guidance, num_inference_steps=steps,
|
| 233 |
+
width=width, height=height, generator=generator,
|
| 234 |
+
max_sequence_length=384
|
| 235 |
+
).images[0]
|
| 236 |
+
print('-- got image --')
|
| 237 |
+
torch.cuda.empty_cache()
|
| 238 |
+
torch.cuda.reset_peak_memory_stats()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
with torch.no_grad():
|
| 240 |
+
upscale = upscaler_2(sd_image, tiling=True, tile_width=256, tile_height=256)
|
| 241 |
upscale2 = upscaler_2(upscale, tiling=True, tile_width=256, tile_height=256)
|
| 242 |
+
print('-- got upscaled image --')
|
| 243 |
+
downscaled_upscale = upscale2.resize((upscale2.width // 16, upscale2.height // 16), Image.LANCZOS)
|
| 244 |
+
sd_avif_bytes = create_hdr_avif_bytes(downscaled_upscale)
|
| 245 |
+
return sd_avif_bytes, sd_avif_bytes, prompt
|
| 246 |
+
|
| 247 |
+
@spaces.GPU(duration=70)
|
| 248 |
+
def generate_images_60(prompt, neg_prompt_1, neg_prompt_2, neg_prompt_3, width, height, guidance, steps, progress=gr.Progress(track_tqdm=True)):
|
| 249 |
+
seed = random.randint(0, MAX_SEED)
|
| 250 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 251 |
+
print('-- generating image --')
|
| 252 |
+
torch.cuda.empty_cache()
|
| 253 |
+
torch.cuda.reset_peak_memory_stats()
|
| 254 |
+
sd_image = pipe(
|
| 255 |
+
prompt=prompt, prompt_2=prompt, prompt_3=prompt,
|
| 256 |
+
negative_prompt=neg_prompt_1, negative_prompt_2=neg_prompt_2, negative_prompt_3=neg_prompt_3,
|
| 257 |
+
guidance_scale=guidance, num_inference_steps=steps,
|
| 258 |
+
width=width, height=height, generator=generator,
|
| 259 |
+
max_sequence_length=384
|
| 260 |
+
).images[0]
|
| 261 |
+
print('-- got image --')
|
| 262 |
+
torch.cuda.empty_cache()
|
| 263 |
+
torch.cuda.reset_peak_memory_stats()
|
| 264 |
+
with torch.no_grad():
|
| 265 |
+
upscale = upscaler_2(sd_image, tiling=True, tile_width=256, tile_height=256)
|
| 266 |
+
upscale2 = upscaler_2(upscale, tiling=True, tile_width=256, tile_height=256)
|
| 267 |
+
print('-- got upscaled image --')
|
| 268 |
+
downscaled_upscale = upscale2.resize((upscale2.width // 16, upscale2.height // 16), Image.LANCZOS)
|
| 269 |
+
sd_avif_bytes = create_hdr_avif_bytes(downscaled_upscale)
|
| 270 |
+
return sd_avif_bytes, sd_avif_bytes, prompt
|
| 271 |
|
| 272 |
+
@spaces.GPU(duration=120)
|
| 273 |
+
def generate_images_110(prompt, neg_prompt_1, neg_prompt_2, neg_prompt_3, width, height, guidance, steps, progress=gr.Progress(track_tqdm=True)):
|
| 274 |
+
seed = random.randint(0, MAX_SEED)
|
| 275 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 276 |
+
print('-- generating image --')
|
| 277 |
+
torch.cuda.empty_cache()
|
| 278 |
+
torch.cuda.reset_peak_memory_stats()
|
| 279 |
+
sd_image = pipe(
|
| 280 |
+
prompt=prompt, prompt_2=prompt, prompt_3=prompt,
|
| 281 |
+
negative_prompt=neg_prompt_1, negative_prompt_2=neg_prompt_2, negative_prompt_3=neg_prompt_3,
|
| 282 |
+
guidance_scale=guidance, num_inference_steps=steps,
|
| 283 |
+
width=width, height=height, generator=generator,
|
| 284 |
+
max_sequence_length=384
|
| 285 |
+
).images[0]
|
| 286 |
+
print('-- got image --')
|
| 287 |
+
torch.cuda.empty_cache()
|
| 288 |
+
torch.cuda.reset_peak_memory_stats()
|
| 289 |
+
with torch.no_grad():
|
| 290 |
+
upscale = upscaler_2(sd_image, tiling=True, tile_width=256, tile_height=256)
|
| 291 |
+
upscale2 = upscaler_2(upscale, tiling=True, tile_width=256, tile_height=256)
|
| 292 |
+
print('-- got upscaled image --')
|
| 293 |
+
downscaled_upscale = upscale2.resize((upscale2.width // 16, upscale2.height // 16), Image.LANCZOS)
|
| 294 |
+
sd_avif_bytes = create_hdr_avif_bytes(downscaled_upscale)
|
| 295 |
+
return sd_avif_bytes, sd_avif_bytes, prompt
|
| 296 |
+
|
| 297 |
+
def run_inference_and_upload_30(prompt, neg_prompt_1, neg_prompt_2, neg_prompt_3, width, height, guidance, steps, save_consent, progress=gr.Progress(track_tqdm=True)):
|
| 298 |
+
sd_image, upscaled_image, expanded_prompt = generate_images_30(prompt, neg_prompt_1, neg_prompt_2, neg_prompt_3, width, height, guidance, steps, progress)
|
| 299 |
if save_consent:
|
| 300 |
print("✅ User consented to save. Preparing uploads...")
|
| 301 |
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 302 |
+
sd_filename = f"sd35ll_{timestamp}.png"
|
| 303 |
+
upscale_filename = f"sd35ll_upscale_{timestamp}.png"
|
| 304 |
+
sd_thread = threading.Thread(target=upload_to_gcs, args=(sd_image, sd_filename))
|
| 305 |
+
#upscale_thread = threading.Thread(target=upload_to_gcs, args=(upscaled_image, upscale_filename))
|
|
|
|
|
|
|
| 306 |
sd_thread.start()
|
| 307 |
+
#upscale_thread.start()
|
| 308 |
else:
|
| 309 |
print("ℹ️ User did not consent to save. Skipping upload.")
|
| 310 |
+
return sd_image, expanded_prompt
|
| 311 |
+
|
| 312 |
+
def run_inference_and_upload_60(prompt, neg_prompt_1, neg_prompt_2, neg_prompt_3, width, height, guidance, steps, save_consent, progress=gr.Progress(track_tqdm=True)):
|
| 313 |
+
sd_image, upscaled_image, expanded_prompt = generate_images_60(prompt, neg_prompt_1, neg_prompt_2, neg_prompt_3, width, height, guidance, steps, progress)
|
| 314 |
+
if save_consent:
|
| 315 |
+
print("✅ User consented to save. Preparing uploads...")
|
| 316 |
+
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 317 |
+
sd_filename = f"sd35ll_{timestamp}.png"
|
| 318 |
+
upscale_filename = f"sd35ll_upscale_{timestamp}.png"
|
| 319 |
+
sd_thread = threading.Thread(target=upload_to_gcs, args=(sd_image, sd_filename))
|
| 320 |
+
#upscale_thread = threading.Thread(target=upload_to_gcs, args=(upscaled_image, upscale_filename))
|
| 321 |
+
sd_thread.start()
|
| 322 |
+
#upscale_thread.start()
|
| 323 |
+
else:
|
| 324 |
+
print("ℹ️ User did not consent to save. Skipping upload.")
|
| 325 |
+
return sd_image, expanded_prompt
|
| 326 |
|
| 327 |
+
def run_inference_and_upload_110(prompt, neg_prompt_1, neg_prompt_2, neg_prompt_3, width, height, guidance, steps, save_consent, progress=gr.Progress(track_tqdm=True)):
|
| 328 |
+
sd_image, upscaled_image, expanded_prompt = generate_images_110(prompt, neg_prompt_1, neg_prompt_2, neg_prompt_3, width, height, guidance, steps, progress)
|
| 329 |
+
if save_consent:
|
| 330 |
+
print("✅ User consented to save. Preparing uploads...")
|
| 331 |
+
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 332 |
+
sd_filename = f"sd35ll_{timestamp}.png"
|
| 333 |
+
upscale_filename = f"sd35ll_upscale_{timestamp}.png"
|
| 334 |
+
sd_thread = threading.Thread(target=upload_to_gcs, args=(sd_image, sd_filename))
|
| 335 |
+
#upscale_thread = threading.Thread(target=upload_to_gcs, args=(upscaled_image, upscale_filename))
|
| 336 |
+
sd_thread.start()
|
| 337 |
+
#upscale_thread.start()
|
| 338 |
+
else:
|
| 339 |
+
print("ℹ️ User did not consent to save. Skipping upload.")
|
| 340 |
+
return sd_image, expanded_prompt
|
| 341 |
+
|
| 342 |
css = """
|
| 343 |
#col-container {margin: 0 auto;max-width: 640px;}
|
| 344 |
body{background-color: blue;}
|
|
|
|
| 355 |
)
|
| 356 |
run_button_30 = gr.Button("Run30", scale=0, variant="primary")
|
| 357 |
run_button_60 = gr.Button("Run60", scale=0, variant="primary")
|
| 358 |
+
run_button_110 = gr.Button("Run100", scale=0, variant="primary")
|
| 359 |
+
result = gr.Image(label="Result", show_label=False, type="pil")
|
|
|
|
| 360 |
save_consent_checkbox = gr.Checkbox(
|
| 361 |
+
label="✅ Anonymously upload result to a public gallery",
|
| 362 |
+
value=True, # Default to not uploading
|
| 363 |
info="Check this box to help us by contributing your image."
|
| 364 |
)
|
| 365 |
with gr.Accordion("Advanced Settings", open=True):
|
|
|
|
| 373 |
guidance_scale = gr.Slider(label="Guidance scale", minimum=0.0, maximum=30.0, step=0.1, value=4.2)
|
| 374 |
num_inference_steps = gr.Slider(label="Inference steps", minimum=1, maximum=150, step=1, value=60)
|
| 375 |
|
|
|
|
| 376 |
run_button_30.click(
|
| 377 |
+
fn=run_inference_and_upload_30,
|
| 378 |
inputs=[
|
| 379 |
+
prompt,
|
| 380 |
+
negative_prompt_1,
|
| 381 |
+
negative_prompt_2,
|
| 382 |
+
negative_prompt_3,
|
| 383 |
+
width,
|
| 384 |
+
height,
|
| 385 |
+
guidance_scale,
|
| 386 |
+
num_inference_steps,
|
| 387 |
+
save_consent_checkbox # Pass the checkbox value
|
| 388 |
],
|
| 389 |
outputs=[result, expanded_prompt_output],
|
| 390 |
)
|
| 391 |
|
| 392 |
run_button_60.click(
|
| 393 |
+
fn=run_inference_and_upload_60,
|
| 394 |
inputs=[
|
| 395 |
+
prompt,
|
| 396 |
+
negative_prompt_1,
|
| 397 |
+
negative_prompt_2,
|
| 398 |
+
negative_prompt_3,
|
| 399 |
+
width,
|
| 400 |
+
height,
|
| 401 |
+
guidance_scale,
|
| 402 |
+
num_inference_steps,
|
| 403 |
+
save_consent_checkbox # Pass the checkbox value
|
| 404 |
],
|
| 405 |
outputs=[result, expanded_prompt_output],
|
| 406 |
)
|
| 407 |
|
| 408 |
run_button_110.click(
|
| 409 |
+
fn=run_inference_and_upload_110,
|
| 410 |
inputs=[
|
| 411 |
+
prompt,
|
| 412 |
+
negative_prompt_1,
|
| 413 |
+
negative_prompt_2,
|
| 414 |
+
negative_prompt_3,
|
| 415 |
+
width,
|
| 416 |
+
height,
|
| 417 |
+
guidance_scale,
|
| 418 |
+
num_inference_steps,
|
| 419 |
+
save_consent_checkbox # Pass the checkbox value
|
| 420 |
],
|
| 421 |
outputs=[result, expanded_prompt_output],
|
| 422 |
)
|