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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from diffusers import StableDiffusionPipeline, StableDiffusionXLImg2ImgPipeline, AutoPipelineForText2Image
|
| 4 |
+
from diffusers.utils import load_image
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import time
|
| 7 |
+
import random
|
| 8 |
+
import os
|
| 9 |
+
import gc # Garbage collector
|
| 10 |
+
import logging
|
| 11 |
+
|
| 12 |
+
# --- Configuration ---
|
| 13 |
+
|
| 14 |
+
# Setup basic logging
|
| 15 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
# Ensure CPU is used
|
| 19 |
+
DEVICE = "cpu"
|
| 20 |
+
TORCH_DTYPE = torch.float32 # float16/bfloat16 not practical on CPU
|
| 21 |
+
|
| 22 |
+
# Model definitions
|
| 23 |
+
# We need to know the base model for LoRAs and compatible IP-Adapters
|
| 24 |
+
MODEL_CONFIG = {
|
| 25 |
+
"BlaireSilver13/youtube-thumbnail": {
|
| 26 |
+
"repo_id": "BlaireSilver13/youtube-thumbnail",
|
| 27 |
+
"is_lora": False,
|
| 28 |
+
"base_model": None, # It's a full model
|
| 29 |
+
"pipeline_class": StableDiffusionPipeline,
|
| 30 |
+
"ip_adapter_repo": "h94/IP-Adapter", # Standard SD 1.5 IP-Adapter
|
| 31 |
+
"ip_adapter_weights": "ip-adapter_sd15.bin",
|
| 32 |
+
"ip_adapter_image_encoder": "laion/CLIP-ViT-H-14-laion2B-s32B-b79K"
|
| 33 |
+
},
|
| 34 |
+
"itzzdeep/youtube-thumbnails-sdxl-lora": {
|
| 35 |
+
"repo_id": "itzzdeep/youtube-thumbnails-sdxl-lora",
|
| 36 |
+
"is_lora": True,
|
| 37 |
+
"lora_filename": "pytorch_lora_weights.safetensors", # Check repo for actual filename if different
|
| 38 |
+
"base_model": "stabilityai/stable-diffusion-xl-base-1.0",
|
| 39 |
+
"pipeline_class": AutoPipelineForText2Image, # Handles SDXL loading better
|
| 40 |
+
"ip_adapter_repo": "h94/IP-Adapter", # SDXL IP-Adapter repo
|
| 41 |
+
"ip_adapter_weights": "ip-adapter-plus_sdxl_vit-h.bin", # SDXL weights
|
| 42 |
+
"ip_adapter_image_encoder": "laion/CLIP-ViT-H-14-laion2B-s32B-b79K" # Usually the same encoder repo
|
| 43 |
+
},
|
| 44 |
+
"justmalhar/flux-thumbnails-v3": {
|
| 45 |
+
"repo_id": "justmalhar/flux-thumbnails-v3",
|
| 46 |
+
"is_lora": False, # Assuming this is a full SD 1.5 fine-tune based on common practice
|
| 47 |
+
"base_model": None,
|
| 48 |
+
"pipeline_class": StableDiffusionPipeline,
|
| 49 |
+
"ip_adapter_repo": "h94/IP-Adapter",
|
| 50 |
+
"ip_adapter_weights": "ip-adapter_sd15.bin",
|
| 51 |
+
"ip_adapter_image_encoder": "laion/CLIP-ViT-H-14-laion2B-s32B-b79K"
|
| 52 |
+
},
|
| 53 |
+
"saq1b/mrbeast-thumbnail-style": {
|
| 54 |
+
"repo_id": "saq1b/mrbeast-thumbnail-style",
|
| 55 |
+
"is_lora": True, # This is typically a LoRA
|
| 56 |
+
"lora_filename": None, # Auto-detect or specify e.g., "pytorch_lora_weights.safetensors"
|
| 57 |
+
"base_model": "runwayml/stable-diffusion-v1-5", # Common base for SD 1.5 LoRAs
|
| 58 |
+
"pipeline_class": StableDiffusionPipeline,
|
| 59 |
+
"ip_adapter_repo": "h94/IP-Adapter",
|
| 60 |
+
"ip_adapter_weights": "ip-adapter_sd15.bin",
|
| 61 |
+
"ip_adapter_image_encoder": "laion/CLIP-ViT-H-14-laion2B-s32B-b79K"
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
AVAILABLE_MODELS = list(MODEL_CONFIG.keys())
|
| 66 |
+
|
| 67 |
+
# Global variable to potentially hold the pipeline to avoid reloading *if memory allows*
|
| 68 |
+
# NOTE: On restricted CPU environments, it's SAFER to load inside the function.
|
| 69 |
+
# Set to None initially. Let's load dynamically inside the function for safety.
|
| 70 |
+
# current_pipeline = None
|
| 71 |
+
# current_model_key = None
|
| 72 |
+
|
| 73 |
+
# --- Helper Functions ---
|
| 74 |
+
|
| 75 |
+
def cleanup_memory():
|
| 76 |
+
"""Attempts to free GPU memory (less relevant for CPU but good practice)."""
|
| 77 |
+
logger.info("Attempting to clean up memory...")
|
| 78 |
+
try:
|
| 79 |
+
# If a pipeline exists globally (if we change strategy), unload it
|
| 80 |
+
# global current_pipeline, current_model_key
|
| 81 |
+
# if current_pipeline is not None:
|
| 82 |
+
# logger.info(f"Unloading model {current_model_key} from memory.")
|
| 83 |
+
# del current_pipeline
|
| 84 |
+
# current_pipeline = None
|
| 85 |
+
# current_model_key = None
|
| 86 |
+
|
| 87 |
+
gc.collect()
|
| 88 |
+
if torch.cuda.is_available(): # Only run cuda cache empty if cuda is present
|
| 89 |
+
torch.cuda.empty_cache()
|
| 90 |
+
logger.info("Memory cleanup potentially done.")
|
| 91 |
+
except Exception as e:
|
| 92 |
+
logger.error(f"Error during memory cleanup: {e}")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# --- Main Generation Function ---
|
| 96 |
+
|
| 97 |
+
def generate_thumbnail(
|
| 98 |
+
model_key: str,
|
| 99 |
+
prompt: str,
|
| 100 |
+
negative_prompt: str,
|
| 101 |
+
reference_image_pil: Image.Image | None, # Gradio provides PIL image
|
| 102 |
+
num_inference_steps: int,
|
| 103 |
+
guidance_scale: float,
|
| 104 |
+
seed: int,
|
| 105 |
+
ip_adapter_scale: float,
|
| 106 |
+
progress=gr.Progress(track_ τότε=True)
|
| 107 |
+
):
|
| 108 |
+
"""Generates an image using the selected model, IP-Adapter, and settings."""
|
| 109 |
+
start_time = time.time()
|
| 110 |
+
debug_log = f"--- Generation Log ({time.strftime('%Y-%m-%d %H:%M:%S')}) ---\n"
|
| 111 |
+
debug_log += f"Selected Model Key: {model_key}\n"
|
| 112 |
+
debug_log += f"Prompt: {prompt}\n"
|
| 113 |
+
debug_log += f"Negative Prompt: {negative_prompt}\n"
|
| 114 |
+
debug_log += f"Steps: {num_inference_steps}, CFG Scale: {guidance_scale}\n"
|
| 115 |
+
debug_log += f"Seed: {seed}\n"
|
| 116 |
+
debug_log += f"Reference Image Provided: {'Yes' if reference_image_pil else 'No'}\n"
|
| 117 |
+
debug_log += f"IP Adapter Scale: {ip_adapter_scale}\n"
|
| 118 |
+
debug_log += f"Device: {DEVICE}, Dtype: {TORCH_DTYPE}\n\n"
|
| 119 |
+
|
| 120 |
+
pipeline = None # Ensure pipeline is defined in this scope
|
| 121 |
+
|
| 122 |
+
try:
|
| 123 |
+
if not model_key:
|
| 124 |
+
raise ValueError("No model selected.")
|
| 125 |
+
|
| 126 |
+
config = MODEL_CONFIG[model_key]
|
| 127 |
+
repo_id = config["repo_id"]
|
| 128 |
+
is_lora = config["is_lora"]
|
| 129 |
+
base_model = config["base_model"]
|
| 130 |
+
pipeline_class = config["pipeline_class"]
|
| 131 |
+
ip_adapter_repo = config["ip_adapter_repo"]
|
| 132 |
+
ip_adapter_weights = config["ip_adapter_weights"]
|
| 133 |
+
# ip_adapter_image_encoder = config["ip_adapter_image_encoder"] # Encoder loaded via IP-Adapter itself usually
|
| 134 |
+
|
| 135 |
+
# --- Model Loading ---
|
| 136 |
+
load_start_time = time.time()
|
| 137 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Cleaning up memory before loading...\n"
|
| 138 |
+
progress(0.1, desc="Cleaning up memory...")
|
| 139 |
+
cleanup_memory() # Attempt cleanup before loading new model
|
| 140 |
+
|
| 141 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Loading model: {'LoRA ' + repo_id if is_lora else repo_id}...\n"
|
| 142 |
+
progress(0.2, desc=f"Loading {'LoRA ' + repo_id if is_lora else repo_id}...")
|
| 143 |
+
|
| 144 |
+
model_load_id = base_model if is_lora else repo_id
|
| 145 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Base/Model ID for pipeline: {model_load_id}\n"
|
| 146 |
+
|
| 147 |
+
pipeline = pipeline_class.from_pretrained(
|
| 148 |
+
model_load_id,
|
| 149 |
+
torch_dtype=TORCH_DTYPE,
|
| 150 |
+
# Add any specific args needed for the pipeline class if necessary
|
| 151 |
+
# safety_checker=None, # Disable safety checker if needed/causes issues on CPU
|
| 152 |
+
# requires_safety_checker=False,
|
| 153 |
+
)
|
| 154 |
+
pipeline.to(DEVICE)
|
| 155 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Base pipeline loaded onto {DEVICE}.\n"
|
| 156 |
+
|
| 157 |
+
if is_lora:
|
| 158 |
+
lora_load_start = time.time()
|
| 159 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Loading LoRA weights from {repo_id}...\n"
|
| 160 |
+
progress(0.4, desc=f"Loading LoRA {repo_id}...")
|
| 161 |
+
try:
|
| 162 |
+
lora_filename = config.get("lora_filename") # Get specific filename if provided
|
| 163 |
+
if lora_filename:
|
| 164 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Using specified LoRA filename: {lora_filename}\n"
|
| 165 |
+
pipeline.load_lora_weights(repo_id, weight_name=lora_filename, torch_dtype=TORCH_DTYPE)
|
| 166 |
+
else:
|
| 167 |
+
# Let diffusers try to auto-detect standard names like .safetensors or .bin
|
| 168 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Attempting auto-detection of LoRA filename.\n"
|
| 169 |
+
pipeline.load_lora_weights(repo_id, torch_dtype=TORCH_DTYPE)
|
| 170 |
+
|
| 171 |
+
# When using LoRA with diffusers >= 0.22, explicitly fuse *or* set adapters
|
| 172 |
+
# pipeline.fuse_lora() # Fuse creates a new pipeline state (might use more memory)
|
| 173 |
+
pipeline.set_adapters(pipeline.get_active_adapters(), adapter_weights=1.0) # Recommended for flexibility
|
| 174 |
+
debug_log += f"[{time.time() - start_time:.2f}s] LoRA weights loaded and adapters set in {time.time() - lora_load_start:.2f}s.\n"
|
| 175 |
+
|
| 176 |
+
except Exception as e:
|
| 177 |
+
debug_log += f"[{time.time() - start_time:.2f}s] ERROR loading LoRA: {e}. Check LoRA repo structure/filename.\n"
|
| 178 |
+
# Decide whether to continue without LoRA or raise error
|
| 179 |
+
raise ValueError(f"Failed to load LoRA weights for {repo_id}: {e}")
|
| 180 |
+
|
| 181 |
+
# --- IP Adapter Loading ---
|
| 182 |
+
if reference_image_pil and ip_adapter_scale > 0:
|
| 183 |
+
ip_load_start = time.time()
|
| 184 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Loading IP-Adapter: {ip_adapter_repo} ({ip_adapter_weights})...\n"
|
| 185 |
+
progress(0.6, desc="Loading IP-Adapter...")
|
| 186 |
+
try:
|
| 187 |
+
# Ensure the pipeline has the load_ip_adapter method
|
| 188 |
+
if not hasattr(pipeline, "load_ip_adapter"):
|
| 189 |
+
raise AttributeError("The current pipeline class does not support load_ip_adapter. Check diffusers version or pipeline type.")
|
| 190 |
+
|
| 191 |
+
pipeline.load_ip_adapter(
|
| 192 |
+
ip_adapter_repo,
|
| 193 |
+
subfolder="models", # Common subfolder, adjust if needed
|
| 194 |
+
weight_name=ip_adapter_weights,
|
| 195 |
+
# image_encoder_folder=ip_adapter_image_encoder # Let diffusers handle encoder loading usually
|
| 196 |
+
)
|
| 197 |
+
pipeline.set_ip_adapter_scale(ip_adapter_scale)
|
| 198 |
+
debug_log += f"[{time.time() - start_time:.2f}s] IP-Adapter loaded and scale set ({ip_adapter_scale}) in {time.time() - ip_load_start:.2f}s.\n"
|
| 199 |
+
# Prepare the image for IP-Adapter (often just needs to be a PIL image)
|
| 200 |
+
ip_image = reference_image_pil.convert("RGB")
|
| 201 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Reference image prepared for IP-Adapter.\n"
|
| 202 |
+
|
| 203 |
+
except Exception as e:
|
| 204 |
+
debug_log += f"[{time.time() - start_time:.2f}s] WARNING: Failed to load IP-Adapter: {e}. Proceeding without image guidance.\n"
|
| 205 |
+
ip_image = None
|
| 206 |
+
ip_adapter_scale = 0 # Effectively disable it if loading failed
|
| 207 |
+
pipeline.set_ip_adapter_scale(0) # Ensure scale is 0
|
| 208 |
+
else:
|
| 209 |
+
ip_image = None
|
| 210 |
+
if hasattr(pipeline, "set_ip_adapter_scale"):
|
| 211 |
+
pipeline.set_ip_adapter_scale(0) # Ensure scale is 0 if no image/scale=0
|
| 212 |
+
debug_log += f"[{time.time() - start_time:.2f}s] No reference image provided or IP Adapter scale is 0. Skipping IP-Adapter loading.\n"
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Total Model & IP-Adapter Loading time: {time.time() - load_start_time:.2f}s\n"
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# --- Generation ---
|
| 219 |
+
gen_start_time = time.time()
|
| 220 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Starting generation...\n"
|
| 221 |
+
progress(0.7, desc="Generating image...")
|
| 222 |
+
|
| 223 |
+
# Handle seed
|
| 224 |
+
if seed == -1:
|
| 225 |
+
seed = random.randint(0, 2**32 - 1)
|
| 226 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Using random seed: {seed}\n"
|
| 227 |
+
generator = torch.Generator(device=DEVICE).manual_seed(seed)
|
| 228 |
+
|
| 229 |
+
# Prepare arguments for pipeline call
|
| 230 |
+
pipeline_args = {
|
| 231 |
+
"prompt": prompt,
|
| 232 |
+
"negative_prompt": negative_prompt,
|
| 233 |
+
"num_inference_steps": num_inference_steps,
|
| 234 |
+
"guidance_scale": guidance_scale,
|
| 235 |
+
"generator": generator,
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
# Add IP-Adapter image if it's loaded and ready
|
| 239 |
+
if ip_image is not None and hasattr(pipeline, "set_ip_adapter_scale") and ip_adapter_scale > 0:
|
| 240 |
+
pipeline_args["ip_adapter_image"] = ip_image
|
| 241 |
+
# Scale was set earlier with set_ip_adapter_scale
|
| 242 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Passing reference image to pipeline with IP scale {ip_adapter_scale}.\n"
|
| 243 |
+
else:
|
| 244 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Not passing reference image to pipeline.\n"
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
# Run inference
|
| 248 |
+
with torch.inference_mode(): # More modern than no_grad for inference
|
| 249 |
+
output_image = pipeline(**pipeline_args).images[0]
|
| 250 |
+
|
| 251 |
+
gen_end_time = time.time()
|
| 252 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Generation finished in {gen_end_time - gen_start_time:.2f}s.\n"
|
| 253 |
+
|
| 254 |
+
# --- Cleanup ---
|
| 255 |
+
debug_log += f"[{time.time() - start_time:.2f}s] Unloading model from memory (CPU strategy)...\n"
|
| 256 |
+
progress(0.95, desc="Cleaning up...")
|
| 257 |
+
del pipeline # Explicitly delete pipeline
|
| 258 |
+
cleanup_memory() # Call garbage collection
|
| 259 |
+
|
| 260 |
+
total_time = time.time() - start_time
|
| 261 |
+
debug_log += f"\n--- Total time: {total_time:.2f} seconds ---\n"
|
| 262 |
+
|
| 263 |
+
return output_image, debug_log
|
| 264 |
+
|
| 265 |
+
except Exception as e:
|
| 266 |
+
logger.exception(f"Error during generation for model {model_key}") # Log full traceback
|
| 267 |
+
error_time = time.time() - start_time
|
| 268 |
+
debug_log += f"\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
|
| 269 |
+
debug_log += f"ERROR occurred after {error_time:.2f}s:\n{e}\n"
|
| 270 |
+
debug_log += f"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
|
| 271 |
+
# Try cleanup even on error
|
| 272 |
+
if 'pipeline' in locals() and pipeline is not None:
|
| 273 |
+
del pipeline
|
| 274 |
+
cleanup_memory()
|
| 275 |
+
# Return None for image, and the log containing the error
|
| 276 |
+
return None, debug_log
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
# --- Gradio Interface ---
|
| 280 |
+
|
| 281 |
+
css = """
|
| 282 |
+
#warning {
|
| 283 |
+
background-color: #FFCCCB; /* Light red */
|
| 284 |
+
padding: 10px;
|
| 285 |
+
border-radius: 5px;
|
| 286 |
+
text-align: center;
|
| 287 |
+
font-weight: bold;
|
| 288 |
+
}
|
| 289 |
+
#debug_log_area textarea {
|
| 290 |
+
font-family: monospace;
|
| 291 |
+
font-size: 10px; /* Smaller font for logs */
|
| 292 |
+
white-space: pre-wrap; /* Wrap long lines */
|
| 293 |
+
word-wrap: break-word; /* Break words if necessary */
|
| 294 |
+
}
|
| 295 |
+
"""
|
| 296 |
+
|
| 297 |
+
with gr.Blocks(css=css) as demo:
|
| 298 |
+
gr.Markdown("# YouTube Thumbnail Generator with IP-Adapter")
|
| 299 |
+
gr.Markdown(
|
| 300 |
+
"Select a thumbnail model, provide a text prompt, and optionally upload a reference image "
|
| 301 |
+
"to guide the generation using IP-Adapter."
|
| 302 |
+
)
|
| 303 |
+
gr.HTML("<div id='warning'>⚠️ Warning: Inference on CPU is VERY SLOW (minutes per image, especially SDXL models). Please be patient.</div>")
|
| 304 |
+
|
| 305 |
+
with gr.Row():
|
| 306 |
+
with gr.Column(scale=1):
|
| 307 |
+
model_dropdown = gr.Dropdown(
|
| 308 |
+
label="Select Thumbnail Model",
|
| 309 |
+
choices=AVAILABLE_MODELS,
|
| 310 |
+
value=AVAILABLE_MODELS[0] if AVAILABLE_MODELS else None,
|
| 311 |
+
)
|
| 312 |
+
prompt_input = gr.Textbox(label="Prompt", lines=3, placeholder="e.g., Epic landscape, dramatic lighting, YouTube thumbnail style")
|
| 313 |
+
negative_prompt_input = gr.Textbox(label="Negative Prompt", lines=2, placeholder="e.g., blurry, low quality, text, signature, watermark")
|
| 314 |
+
reference_image_input = gr.Image(label="Reference Image (for IP-Adapter)", type="pil", source="upload")
|
| 315 |
+
|
| 316 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 317 |
+
steps_slider = gr.Slider(label="Inference Steps", minimum=10, maximum=100, value=30, step=1)
|
| 318 |
+
cfg_slider = gr.Slider(label="Guidance Scale (CFG)", minimum=1.0, maximum=20.0, value=7.0, step=0.5)
|
| 319 |
+
ip_adapter_scale_slider = gr.Slider(label="IP-Adapter Scale", minimum=0.0, maximum=1.5, value=0.6, step=0.05,
|
| 320 |
+
info="Strength of the reference image influence (0 = disabled).")
|
| 321 |
+
seed_input = gr.Number(label="Seed", value=-1, precision=0, info="-1 for random seed")
|
| 322 |
+
|
| 323 |
+
generate_button = gr.Button("Generate Thumbnail", variant="primary")
|
| 324 |
+
|
| 325 |
+
with gr.Column(scale=1):
|
| 326 |
+
output_image = gr.Image(label="Generated Thumbnail", type="pil")
|
| 327 |
+
debug_output = gr.Textbox(label="Debug Log", lines=20, interactive=False, elem_id="debug_log_area")
|
| 328 |
+
|
| 329 |
+
generate_button.click(
|
| 330 |
+
fn=generate_thumbnail,
|
| 331 |
+
inputs=[
|
| 332 |
+
model_dropdown,
|
| 333 |
+
prompt_input,
|
| 334 |
+
negative_prompt_input,
|
| 335 |
+
reference_image_input,
|
| 336 |
+
steps_slider,
|
| 337 |
+
cfg_slider,
|
| 338 |
+
seed_input,
|
| 339 |
+
ip_adapter_scale_slider
|
| 340 |
+
],
|
| 341 |
+
outputs=[output_image, debug_output]
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
# --- Launch ---
|
| 345 |
+
if __name__ == "__main__":
|
| 346 |
+
logger.info("Starting Gradio App...")
|
| 347 |
+
# Queueing is important for handling multiple users on Spaces, even if slow
|
| 348 |
+
demo.queue().launch(debug=True) # debug=True provides Gradio debug info in console
|