Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,49 +1,13 @@
|
|
|
|
|
| 1 |
import subprocess
|
| 2 |
import sys
|
| 3 |
|
| 4 |
-
#
|
| 5 |
-
def install_packages():
|
| 6 |
-
packages = [
|
| 7 |
-
"transformers>=4.46.0",
|
| 8 |
-
"diffusers>=0.31.0",
|
| 9 |
-
"accelerate>=0.26.0",
|
| 10 |
-
"huggingface-hub>=0.23.0",
|
| 11 |
-
"timm", # Required for Florence-2
|
| 12 |
-
]
|
| 13 |
-
|
| 14 |
-
for package in packages:
|
| 15 |
-
try:
|
| 16 |
-
subprocess.run([sys.executable, "-m", "pip", "install", "--upgrade", package], check=True)
|
| 17 |
-
except Exception as e:
|
| 18 |
-
print(f"Warning: Could not install {package}: {e}")
|
| 19 |
-
|
| 20 |
-
# Run installation before other imports
|
| 21 |
-
try:
|
| 22 |
-
install_packages()
|
| 23 |
-
except Exception as e:
|
| 24 |
-
print(f"Warning: Could not auto-install packages: {e}")
|
| 25 |
-
|
| 26 |
-
# Try to install flash-attn with a timeout
|
| 27 |
try:
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
shell=True,
|
| 33 |
-
timeout=120, # 2 minute timeout
|
| 34 |
-
capture_output=True,
|
| 35 |
-
text=True
|
| 36 |
-
)
|
| 37 |
-
if result.returncode == 0:
|
| 38 |
-
print("Flash-attn installed successfully")
|
| 39 |
-
else:
|
| 40 |
-
print(f"Flash-attn installation failed: {result.stderr}")
|
| 41 |
-
print("Continuing without flash-attn...")
|
| 42 |
-
except subprocess.TimeoutExpired:
|
| 43 |
-
print("Flash-attn installation timed out - continuing without it")
|
| 44 |
-
except Exception as e:
|
| 45 |
-
print(f"Flash-attn installation error: {e}")
|
| 46 |
-
print("Continuing without flash-attn...")
|
| 47 |
|
| 48 |
import spaces
|
| 49 |
import argparse
|
|
@@ -61,20 +25,7 @@ from diffusers.pipelines.stable_diffusion import safety_checker
|
|
| 61 |
from PIL import Image
|
| 62 |
from transformers import AutoProcessor, AutoModelForCausalLM
|
| 63 |
|
| 64 |
-
#
|
| 65 |
-
ATTN_METHOD = None
|
| 66 |
-
try:
|
| 67 |
-
import xformers
|
| 68 |
-
print("Using xformers for efficient attention")
|
| 69 |
-
ATTN_METHOD = "xformers"
|
| 70 |
-
except ImportError:
|
| 71 |
-
try:
|
| 72 |
-
import flash_attn
|
| 73 |
-
print("Using flash attention")
|
| 74 |
-
ATTN_METHOD = "flash_attn"
|
| 75 |
-
except ImportError:
|
| 76 |
-
print("No efficient attention method available, using default")
|
| 77 |
-
ATTN_METHOD = "default"
|
| 78 |
|
| 79 |
# Setup and initialization code
|
| 80 |
cache_path = path.join(path.dirname(path.abspath(__file__)), "models")
|
|
@@ -91,53 +42,52 @@ print("Initializing Florence models...")
|
|
| 91 |
florence_models = {}
|
| 92 |
florence_processors = {}
|
| 93 |
|
|
|
|
| 94 |
try:
|
| 95 |
-
# Try importing timm to verify it's available
|
| 96 |
import timm
|
| 97 |
-
print("timm library available")
|
| 98 |
except ImportError:
|
| 99 |
-
print("
|
| 100 |
subprocess.run([sys.executable, "-m", "pip", "install", "timm"], check=True)
|
| 101 |
import timm
|
|
|
|
| 102 |
|
| 103 |
-
# Initialize Florence models with error handling
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
-
for model_name in
|
| 107 |
try:
|
| 108 |
print(f"Loading {model_name}...")
|
| 109 |
florence_models[model_name] = AutoModelForCausalLM.from_pretrained(
|
| 110 |
model_name,
|
| 111 |
-
trust_remote_code=True
|
|
|
|
| 112 |
).eval()
|
|
|
|
| 113 |
florence_processors[model_name] = AutoProcessor.from_pretrained(
|
| 114 |
model_name,
|
| 115 |
trust_remote_code=True
|
| 116 |
)
|
| 117 |
print(f"Successfully loaded {model_name}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
except Exception as e:
|
| 119 |
print(f"Warning: Could not load {model_name}: {e}")
|
| 120 |
-
|
| 121 |
-
if model_name == 'gokaygokay/Florence-2-Flux-Large' and len(florence_models) == 0:
|
| 122 |
print("Attempting to load fallback model...")
|
| 123 |
-
|
| 124 |
-
fallback_model = 'gokaygokay/Florence-2-Flux'
|
| 125 |
-
florence_models[model_name] = AutoModelForCausalLM.from_pretrained(
|
| 126 |
-
fallback_model,
|
| 127 |
-
trust_remote_code=True
|
| 128 |
-
).eval()
|
| 129 |
-
florence_processors[model_name] = AutoProcessor.from_pretrained(
|
| 130 |
-
fallback_model,
|
| 131 |
-
trust_remote_code=True
|
| 132 |
-
)
|
| 133 |
-
print(f"Using {fallback_model} as fallback")
|
| 134 |
-
except Exception as e2:
|
| 135 |
-
print(f"Error loading fallback model: {e2}")
|
| 136 |
|
| 137 |
if not florence_models:
|
| 138 |
-
print("
|
|
|
|
| 139 |
else:
|
| 140 |
-
print(f"
|
| 141 |
|
| 142 |
def filter_prompt(prompt):
|
| 143 |
inappropriate_keywords = [
|
|
@@ -172,18 +122,6 @@ pipe = FluxPipeline.from_pretrained(
|
|
| 172 |
torch_dtype=torch.bfloat16
|
| 173 |
)
|
| 174 |
|
| 175 |
-
# Configure attention mechanism
|
| 176 |
-
if ATTN_METHOD == "xformers":
|
| 177 |
-
try:
|
| 178 |
-
pipe.enable_xformers_memory_efficient_attention()
|
| 179 |
-
print("Enabled xformers memory efficient attention")
|
| 180 |
-
except Exception as e:
|
| 181 |
-
print(f"Could not enable xformers: {e}")
|
| 182 |
-
elif ATTN_METHOD == "flash_attn":
|
| 183 |
-
print("Flash attention available")
|
| 184 |
-
else:
|
| 185 |
-
print("Using standard attention")
|
| 186 |
-
|
| 187 |
print("Loading LoRA weights...")
|
| 188 |
pipe.load_lora_weights(
|
| 189 |
hf_hub_download(
|
|
@@ -408,10 +346,18 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
|
|
| 408 |
visible=False
|
| 409 |
)
|
| 410 |
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
|
| 416 |
# 구분선
|
| 417 |
gr.HTML('<hr style="margin: 20px 0;">')
|
|
@@ -480,11 +426,12 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
|
|
| 480 |
)
|
| 481 |
|
| 482 |
# Event handlers
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
|
|
|
| 488 |
|
| 489 |
generate_btn.click(
|
| 490 |
process_and_save_image,
|
|
|
|
| 1 |
+
# No need for dynamic package installation since we're using requirements.txt
|
| 2 |
import subprocess
|
| 3 |
import sys
|
| 4 |
|
| 5 |
+
# Optional: Try to install flash-attn if not present (but don't fail if it doesn't work)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
try:
|
| 7 |
+
import flash_attn
|
| 8 |
+
print("Flash attention is available")
|
| 9 |
+
except ImportError:
|
| 10 |
+
print("Flash attention not available - using standard attention (this is fine)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
import spaces
|
| 13 |
import argparse
|
|
|
|
| 25 |
from PIL import Image
|
| 26 |
from transformers import AutoProcessor, AutoModelForCausalLM
|
| 27 |
|
| 28 |
+
# No special attention mechanisms needed - the model will work fine without them
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
# Setup and initialization code
|
| 31 |
cache_path = path.join(path.dirname(path.abspath(__file__)), "models")
|
|
|
|
| 42 |
florence_models = {}
|
| 43 |
florence_processors = {}
|
| 44 |
|
| 45 |
+
# Check if timm is available
|
| 46 |
try:
|
|
|
|
| 47 |
import timm
|
| 48 |
+
print("timm library is available")
|
| 49 |
except ImportError:
|
| 50 |
+
print("ERROR: timm library not found. Installing...")
|
| 51 |
subprocess.run([sys.executable, "-m", "pip", "install", "timm"], check=True)
|
| 52 |
import timm
|
| 53 |
+
print("timm installed successfully")
|
| 54 |
|
| 55 |
+
# Initialize Florence models with better error handling
|
| 56 |
+
model_configs = [
|
| 57 |
+
('gokaygokay/Florence-2-Flux-Large', True), # Primary model
|
| 58 |
+
('gokaygokay/Florence-2-Flux', False), # Fallback model
|
| 59 |
+
]
|
| 60 |
|
| 61 |
+
for model_name, is_primary in model_configs:
|
| 62 |
try:
|
| 63 |
print(f"Loading {model_name}...")
|
| 64 |
florence_models[model_name] = AutoModelForCausalLM.from_pretrained(
|
| 65 |
model_name,
|
| 66 |
+
trust_remote_code=True,
|
| 67 |
+
low_cpu_mem_usage=True, # Add memory optimization
|
| 68 |
).eval()
|
| 69 |
+
|
| 70 |
florence_processors[model_name] = AutoProcessor.from_pretrained(
|
| 71 |
model_name,
|
| 72 |
trust_remote_code=True
|
| 73 |
)
|
| 74 |
print(f"Successfully loaded {model_name}")
|
| 75 |
+
|
| 76 |
+
# If we successfully loaded the primary model, we can skip the fallback
|
| 77 |
+
if is_primary:
|
| 78 |
+
break
|
| 79 |
+
|
| 80 |
except Exception as e:
|
| 81 |
print(f"Warning: Could not load {model_name}: {e}")
|
| 82 |
+
if is_primary:
|
|
|
|
| 83 |
print("Attempting to load fallback model...")
|
| 84 |
+
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
if not florence_models:
|
| 87 |
+
print("WARNING: No Florence models could be loaded. Caption generation will not be available.")
|
| 88 |
+
print("Users will need to manually enter image descriptions.")
|
| 89 |
else:
|
| 90 |
+
print(f"Successfully loaded {len(florence_models)} Florence model(s)")
|
| 91 |
|
| 92 |
def filter_prompt(prompt):
|
| 93 |
inappropriate_keywords = [
|
|
|
|
| 122 |
torch_dtype=torch.bfloat16
|
| 123 |
)
|
| 124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
print("Loading LoRA weights...")
|
| 126 |
pipe.load_lora_weights(
|
| 127 |
hf_hub_download(
|
|
|
|
| 346 |
visible=False
|
| 347 |
)
|
| 348 |
|
| 349 |
+
# Caption button - only show if models are available
|
| 350 |
+
if florence_models:
|
| 351 |
+
caption_button = gr.Button(
|
| 352 |
+
"🔍 Generate Caption from Image",
|
| 353 |
+
elem_classes=["generate-btn"]
|
| 354 |
+
)
|
| 355 |
+
else:
|
| 356 |
+
caption_button = gr.Button(
|
| 357 |
+
"⚠️ Caption Generation Unavailable - Enter Description Manually",
|
| 358 |
+
elem_classes=["generate-btn"],
|
| 359 |
+
interactive=False
|
| 360 |
+
)
|
| 361 |
|
| 362 |
# 구분선
|
| 363 |
gr.HTML('<hr style="margin: 20px 0;">')
|
|
|
|
| 426 |
)
|
| 427 |
|
| 428 |
# Event handlers
|
| 429 |
+
if florence_models:
|
| 430 |
+
caption_button.click(
|
| 431 |
+
generate_caption,
|
| 432 |
+
inputs=[input_image, florence_model],
|
| 433 |
+
outputs=[prompt]
|
| 434 |
+
)
|
| 435 |
|
| 436 |
generate_btn.click(
|
| 437 |
process_and_save_image,
|