Python
added headless mode
DeepBeepMeepa9a82b8b269e
diff --git a/README.md b/README.mdindex 4fb12e1..8febf87 100644--- a/README.md+++ b/README.md@@ -37,6 +37,20 @@ WanGP supports the Wan (and derived models), Hunyuan Video and LTV Video models## 🔥 Latest Updates :+### December 5 2025: WanGP v9.8, Simple Pleasures...++These two features are going to change the life of many people:+- **Pause Button**: ever had a urge to use your GPU for a very important task that can't wait (a game for instance ?), here comes your new friend the *Pause* button. Not only it will suspend the current gen in progress but it will free most of the VRAM used by WanGP (please note that the RAM by WanGP used wont be released). When you are done just click the *Resume* button++- **WanGP Headless**: trouble running remotely WanGP or having some stability issues with Gradio or your Web Browser. This is all past thanks to *WanGP Headless* mode. Here is how it works : first make you shopping list of Video Gen using the classic WanGP gradio interface. When you are done, click the *Save Queue* button and quit WanGP.++Then in your terminal window just write this:+```bash+python wgp.py --process my_queue.zip+```+++### December 4 2025: WanGP v9.74, The Alpha & the Omega ... and the Dancer- **Flux 2**: the best ever open source *Image Generator* has just landed. It does everything very well: generate an *Image* based a *Text Prompt* or combine up to 10 *Images References*@@ -260,6 +274,15 @@ conda activate wan2gppip install -r requirements.txt```+**Run headless (batch processing):**++Process saved queues without launching the web UI:+```bash+# Process a saved queue+python wgp.py --process my_queue.zip+```+Create your queue in the web UI, save it with "Save Queue", then process it headless. See [CLI Documentation](docs/CLI.md) for details.+## 🐳 Docker:**For Debian-based systems (Ubuntu, Debian, etc.):**diff --git a/docs/CLI.md b/docs/CLI.mdindex 38538b3..d7065b1 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -1,21 +1,89 @@---vace-1-3B--vace-1-3B# Command Line Reference+# Command Line ReferenceThis document covers all available command line options for WanGP.## Basic Usage```bash-# Default launch+# Default launchpython wgp.py-# Specific model modes-python wgp.py --i2v # Image-to-video-python wgp.py --t2v # Text-to-video (default)-python wgp.py --t2v-14B # 14B text-to-video model-python wgp.py --t2v-1-3B # 1.3B text-to-video model-python wgp.py --i2v-14B # 14B image-to-video model-python wgp.py --i2v-1-3B # Fun InP 1.3B image-to-video model-python wgp.py --vace-1-3B # VACE ControlNet 1.3B model+```++## CLI Queue Processing (Headless Mode)++Process saved queues without launching the web UI. Useful for batch processing or automated workflows.++### Quick Start+```bash+# Process a saved queue+python wgp.py --process my_queue.zip++# Validate queue without generating (dry-run)+python wgp.py --process my_queue.zip --dry-run++# Process with custom output directory+python wgp.py --process my_queue.zip --output-dir ./batch_outputs+```++### Workflow+1. **Create your queue** in the web UI using the normal interface+2. **Save the queue** using the "Save Queue" button (creates a .zip file)+3. **Close the web UI** if desired+4. **Process the queue** via command line:+ ```bash+ python wgp.py --process saved_queue.zip --output-dir ./my_outputs+ ```++### CLI Queue Options+```bash+--process PATH # Path to saved queue .zip file (enables headless mode)+--dry-run # Validate queue without generating (use with --process)+--output-dir PATH # Override output directory (use with --process)+--verbose LEVEL # Verbosity level 0-2 for detailed logging+```++### Console Output+The CLI mode provides real-time feedback:+```+WanGP CLI Mode - Processing queue: my_queue.zip+Output directory: ./batch_outputs+Loaded 3 task(s)++[Task 1/3] A beautiful sunset over the ocean...+ [12/30] Prompt 1/3 - Denoising | Phase 2/2 Low Noise+ Video saved+ Task 1 completed++[Task 2/3] A cat playing with yarn...+ [30/30] Prompt 2/3 - VAE Decoding+ Video saved+ Task 2 completed++==================================================+Queue completed: 3/3 tasks in 5m 23s+```++### Exit Codes+| Code | Meaning |+|------|---------|+| 0 | Success (all tasks completed) |+| 1 | Error (file not found, invalid queue, or task failures) |+| 130 | Interrupted by user (Ctrl+C) |++### Examples+```bash+# Overnight batch processing+python wgp.py --process overnight_jobs.zip --output-dir ./renders++# Quick validation before long run+python wgp.py --process big_queue.zip --dry-run++# Verbose mode for debugging+python wgp.py --process my_queue.zip --verbose 2++# Combined with other options+python wgp.py --process queue.zip --output-dir ./out --attention sage2```## Model and Performance Options@@ -36,6 +104,7 @@ python wgp.py --vace-1-3B # VACE ControlNet 1.3B model- **Profile 2**: Load model parts as needed, keep all unused models in reserved RAM for fast VRAM tranfers- **Profile 3**: Load entire current model in VRAM (requires 24GB for 14B model)- **Profile 4**: Default and recommended, load model parts as needed, most flexible option+- **Profile 4+** (4.5): Profile 4 variation, can save up to 1 GB of VRAM, but will be slighlty slower on some configs- **Profile 5**: Minimum RAM usage### Memory Management@@ -99,16 +168,13 @@ python wgp.py --vace-1-3B # VACE ControlNet 1.3B model### Basic Usage Examples```bash# Launch with specific model and loras-python wgp.py --t2v-14B --lora-preset mystyle.lset+python wgp.py ----lora-preset mystyle.lset# High-performance setup with compilationpython wgp.py --compile --attention sage2 --profile 3# Low VRAM setup-python wgp.py --t2v-1-3B --profile 4 --attention sdpa--# Multiple images with custom lora directory-python wgp.py --i2v --multiple-images --lora-dir /path/to/shared/loras+python wgp.py --profile 4 --attention sdpa```### Server Configuration Examplesdiff --git a/wgp.py b/wgp.pyindex f83b74e..83a17cb 100644--- a/wgp.py+++ b/wgp.py@@ -83,7 +83,7 @@ global_queue_ref = []AUTOSAVE_FILENAME = "queue.zip"PROMPT_VARS_MAX = 10target_mmgp_version = "3.6.9"-WanGP_version = "9.74"+WanGP_version = "9.8"settings_version = 2.41max_source_video_frames = 3000prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None@@ -1208,100 +1208,75 @@ def save_queue_action(state):finally:zip_buffer.close()-def load_queue_action(filepath, state, evt:gr.EventData):+def _parse_queue_zip(filename, state):+ """Parse queue ZIP file. Returns (queue_list, error_msg or None).+ Core parsing logic used by both load_queue_action() and CLI mode.+ """global task_id-- gen = get_gen_info(state)- original_queue = gen.get("queue", [])- if len(original_queue):- gr.Info("Queue must be empty before loading a new queue")- return update_queue_data(original_queue)- delete_autoqueue_file = False- if evt.target == None:-- if original_queue or not Path(AUTOSAVE_FILENAME).is_file():- return- print(f"Autoloading queue from {AUTOSAVE_FILENAME}...")- filename = AUTOSAVE_FILENAME- delete_autoqueue_file = True- else:- if not filepath or not hasattr(filepath, 'name') or not Path(filepath.name).is_file():- print("[load_queue_action] Warning: No valid file selected or file not found.")- return update_queue_data(original_queue)- filename = filepath.name--save_path_base = server_config.get("save_path", "outputs")loaded_cache_dir = os.path.join(save_path_base, "_loaded_queue_cache")--newly_loaded_queue = []- max_id_in_file = 0- error_message = ""- local_queue_copy_for_global_ref = Nonetry:- print(f"[load_queue_action] Attempting to load queue from: {filename}")+ print(f"[load_queue] Attempting to load queue from: {filename}")os.makedirs(loaded_cache_dir, exist_ok=True)- print(f"[load_queue_action] Using cache directory: {loaded_cache_dir}")+ print(f"[load_queue] Using cache directory: {loaded_cache_dir}")with tempfile.TemporaryDirectory() as tmpdir:with zipfile.ZipFile(filename, 'r') as zf:- if "queue.json" not in zf.namelist(): raise ValueError("queue.json not found in zip file")- print(f"[load_queue_action] Extracting {filename} to {tmpdir}")+ if "queue.json" not in zf.namelist():+ return None, "queue.json not found in zip file"+ print(f"[load_queue] Extracting {filename} to {tmpdir}")zf.extractall(tmpdir)- print(f"[load_queue_action] Extraction complete.")+ print(f"[load_queue] Extraction complete.")manifest_path = os.path.join(tmpdir, "queue.json")- print(f"[load_queue_action] Reading manifest: {manifest_path}")+ print(f"[load_queue] Reading manifest: {manifest_path}")with open(manifest_path, 'r', encoding='utf-8') as f:loaded_manifest = json.load(f)- print(f"[load_queue_action] Manifest loaded. Processing {len(loaded_manifest)} tasks.")+ print(f"[load_queue] Manifest loaded. Processing {len(loaded_manifest)} tasks.")for task_index, task_data in enumerate(loaded_manifest):if task_data is None or not isinstance(task_data, dict):- print(f"[load_queue_action] Skipping invalid task data at index {task_index}")+ print(f"[load_queue] Skipping invalid task data at index {task_index}")continueparams = task_data.get('params', {})task_id_loaded = task_data.get('id', 0)- max_id_in_file = max(max_id_in_file, task_id_loaded)params['state'] = stateimage_keys = ["image_start", "image_end", "image_refs", "image_guide", "image_mask"]video_keys = ["video_guide", "video_mask", "video_source", "audio_guide", "audio_guide2", "audio_source"]- loaded_pil_images = {}- loaded_video_paths = {}-for key in image_keys:image_filenames = params.get(key)- if image_filenames is None: continue+ if image_filenames is None:+ continueis_list = isinstance(image_filenames, list)- if not is_list: image_filenames = [image_filenames]+ if not is_list:+ image_filenames = [image_filenames]loaded_pils = []for img_filename_in_zip in image_filenames:- if not isinstance(img_filename_in_zip, str):- print(f"[load_queue_action] Warning: Non-string filename found for image key '{key}'. Skipping.")- continue- img_load_path = os.path.join(tmpdir, img_filename_in_zip)- if not os.path.exists(img_load_path):- print(f"[load_queue_action] Image file not found in extracted data: {img_load_path}. Skipping.")- continue- try:- pil_image = Image.open(img_load_path)- pil_image.load()- converted_image = convert_image(pil_image)- loaded_pils.append(converted_image)- pil_image.close()- print(f"Loaded image: {img_filename_in_zip} for key {key}")- except Exception as img_e:- print(f"[load_queue_action] Error loading image {img_filename_in_zip}: {img_e}")+ if not isinstance(img_filename_in_zip, str):+ print(f"[load_queue] Warning: Non-string filename found for image key '{key}'. Skipping.")+ continue+ img_load_path = os.path.join(tmpdir, img_filename_in_zip)+ if not os.path.exists(img_load_path):+ print(f"[load_queue] Image file not found in extracted data: {img_load_path}. Skipping.")+ continue+ try:+ pil_image = Image.open(img_load_path)+ pil_image.load()+ converted_image = convert_image(pil_image)+ loaded_pils.append(converted_image)+ pil_image.close()+ print(f"Loaded image: {img_filename_in_zip} for key {key}")+ except Exception as img_e:+ print(f"[load_queue] Error loading image {img_filename_in_zip}: {img_e}")if loaded_pils:params[key] = loaded_pils if is_list else loaded_pils[0]- loaded_pil_images[key] = params[key]else:params.pop(key, None)@@ -1312,7 +1287,7 @@ def load_queue_action(filepath, state, evt:gr.EventData):video_load_path = os.path.join(tmpdir, video_filename_in_zip)if not os.path.exists(video_load_path):- print(f"[load_queue_action] Video file not found in extracted data: {video_load_path}. Skipping.")+ print(f"[load_queue] Video file not found in extracted data: {video_load_path}. Skipping.")params.pop(key, None)continue@@ -1320,13 +1295,12 @@ def load_queue_action(filepath, state, evt:gr.EventData):try:shutil.copy2(video_load_path, persistent_video_path)params[key] = persistent_video_path- loaded_video_paths[key] = persistent_video_pathprint(f"Loaded video: {video_filename_in_zip} -> {persistent_video_path}")except Exception as vid_e:- print(f"[load_queue_action] Error copying video {video_filename_in_zip} to cache: {vid_e}")+ print(f"[load_queue] Error copying video {video_filename_in_zip} to cache: {vid_e}")params.pop(key, None)- primary_preview_pil_list, secondary_preview_pil_list, primary_preview_pil_labels, secondary_preview_pil_labels = get_preview_images(params)+ primary_preview_pil_list, secondary_preview_pil_list, primary_preview_pil_labels, secondary_preview_pil_labels = get_preview_images(params)start_b64 = [pil_to_base64_uri(primary_preview_pil_list[0], format="jpeg", quality=70)] if isinstance(primary_preview_pil_list, list) and primary_preview_pil_list else Noneend_b64 = [pil_to_base64_uri(secondary_preview_pil_list[0], format="jpeg", quality=70)] if isinstance(secondary_preview_pil_list, list) and secondary_preview_pil_list else None@@ -1337,6 +1311,7 @@ def load_queue_action(filepath, state, evt:gr.EventData):runtime_task = {"id": task_id_loaded,"params": params.copy(),+ "plugin_data": task_data.get('plugin_data', {}),"repeats": params.get('repeat_generation', 1),"length": params.get('video_length'),"steps": params.get('num_inference_steps'),@@ -1349,41 +1324,66 @@ def load_queue_action(filepath, state, evt:gr.EventData):"end_image_data_base64": end_b64,}newly_loaded_queue.append(runtime_task)- print(f"[load_queue_action] Reconstructed task {task_index+1}/{len(loaded_manifest)}, ID: {task_id_loaded}")+ print(f"[load_queue] Reconstructed task {task_index+1}/{len(loaded_manifest)}, ID: {task_id_loaded}")- with lock:- print("[load_queue_action] Acquiring lock to update state...")- gen["queue"] = newly_loaded_queue[:]- local_queue_copy_for_global_ref = gen["queue"][:]+ # Update global task_id+ current_max_id = max([t['id'] for t in newly_loaded_queue if 'id' in t] + [0])+ if current_max_id >= task_id:+ new_task_id = current_max_id + 1+ print(f"[load_queue] Updating global task_id from {task_id} to {new_task_id}")+ task_id = new_task_id- current_max_id_in_new_queue = max([t['id'] for t in newly_loaded_queue if 'id' in t] + [0])- if current_max_id_in_new_queue >= task_id:- new_task_id = current_max_id_in_new_queue + 1- print(f"[load_queue_action] Updating global task_id from {task_id} to {new_task_id}")- task_id = new_task_id- else:- print(f"[load_queue_action] Global task_id ({task_id}) is > max in file ({current_max_id_in_new_queue}). Not changing task_id.")+ return newly_loaded_queue, None- gen["prompts_max"] = len(newly_loaded_queue)- print("[load_queue_action] State update complete. Releasing lock.")+ except Exception as e:+ traceback.print_exc()+ return None, str(e)- if local_queue_copy_for_global_ref is not None:- print("[load_queue_action] Updating global queue reference...")- update_global_queue_ref(local_queue_copy_for_global_ref)- else:- print("[load_queue_action] Warning: Skipping global ref update as local copy is None.")+def load_queue_action(filepath, state, evt:gr.EventData):+ """Load queue from ZIP file (Gradio UI wrapper for _parse_queue_zip)."""+ gen = get_gen_info(state)+ original_queue = gen.get("queue", [])+ if len(original_queue):+ gr.Info("Queue must be empty before loading a new queue")+ return update_queue_data(original_queue)++ # Determine filename (autoload vs user upload)+ delete_autoqueue_file = False+ if evt.target == None:+ if original_queue or not Path(AUTOSAVE_FILENAME).is_file():+ return+ print(f"Autoloading queue from {AUTOSAVE_FILENAME}...")+ filename = AUTOSAVE_FILENAME+ delete_autoqueue_file = True+ else:+ if not filepath or not hasattr(filepath, 'name') or not Path(filepath.name).is_file():+ print("[load_queue_action] Warning: No valid file selected or file not found.")+ return update_queue_data(original_queue)+ filename = filepath.name++ try:+ # Use shared parser+ newly_loaded_queue, error = _parse_queue_zip(filename, state)+ if error:+ gr.Warning(f"Failed to load queue: {error[:200]}")+ return update_queue_data(original_queue)- print(f"[load_queue_action] Queue load successful. Returning DataFrame update for {len(newly_loaded_queue)} tasks.")+ # Update state (Gradio-specific)+ with lock:+ gen["queue"] = newly_loaded_queue[:]+ gen["prompts_max"] = len(newly_loaded_queue)+ update_global_queue_ref(newly_loaded_queue)++ print(f"[load_queue_action] Queue load successful. {len(newly_loaded_queue)} tasks.")return update_queue_data(newly_loaded_queue)- except (ValueError, zipfile.BadZipFile, FileNotFoundError, Exception) as e:+ except Exception as e:error_message = f"Error during queue load: {e}"print(f"[load_queue_action] Caught error: {error_message}")traceback.print_exc()gr.Warning(f"Failed to load queue: {error_message[:200]}")-- print("[load_queue_action] Load failed. Returning DataFrame update for original queue.")return update_queue_data(original_queue)+finally:if delete_autoqueue_file:if os.path.isfile(filename):@@ -1391,14 +1391,14 @@ def load_queue_action(filepath, state, evt:gr.EventData):print(f"Clear Queue: Deleted autosave file '{filename}'.")if filepath and hasattr(filepath, 'name') and filepath.name and os.path.exists(filepath.name):- if tempfile.gettempdir() in os.path.abspath(filepath.name):- try:- os.remove(filepath.name)- print(f"[load_queue_action] Removed temporary upload file: {filepath.name}")- except OSError as e:- print(f"[load_queue_action] Info: Could not remove temp file {filepath.name}: {e}")- else:- print(f"[load_queue_action] Info: Did not remove non-temporary file: {filepath.name}")+ if tempfile.gettempdir() in os.path.abspath(filepath.name):+ try:+ os.remove(filepath.name)+ print(f"[load_queue_action] Removed temporary upload file: {filepath.name}")+ except OSError as e:+ print(f"[load_queue_action] Info: Could not remove temp file {filepath.name}: {e}")+ else:+ print(f"[load_queue_action] Info: Did not remove non-temporary file: {filepath.name}")def clear_queue_action(state):gen = get_gen_info(state)@@ -2018,7 +2018,25 @@ def _parse_args():type=str,default="",help="vae config mode"- )+ )++ parser.add_argument(+ "--process",+ type=str,+ default="",+ help="Process a saved queue file without launching the web UI"+ )+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="Validate queue file without generating (use with --process)"+ )+ parser.add_argument(+ "--output-dir",+ type=str,+ default="",+ help="Override output directory for CLI processing (use with --process)"+ )args = parser.parse_args()@@ -6318,6 +6336,100 @@ def process_tasks(state):release_gen()+def process_tasks_cli(queue, state):+ """Process queue tasks with console output for CLI mode. Returns True on success."""+ from shared.utils.thread_utils import AsyncStream, async_run+ import inspect++ gen = get_gen_info(state)+ total_tasks = len(queue)+ completed = 0+ start_time = time.time()++ for task_idx, task in enumerate(queue):+ task_no = task_idx + 1+ prompt_preview = (task.get('prompt', '') or '')[:60]+ print(f"\n[Task {task_no}/{total_tasks}] {prompt_preview}...")++ # Update gen state for this task+ gen["prompt_no"] = task_no+ gen["prompts_max"] = total_tasks++ params = task['params'].copy()+ params['state'] = state++ com_stream = AsyncStream()+ send_cmd = com_stream.output_queue.push++ def make_error_handler(task, params, send_cmd):+ def error_handler():+ try:+ model_type = params.get('model_type')+ known_defaults = {'image_refs_relative_size': 50}++ for arg_name, default_value in known_defaults.items():+ if arg_name not in params:+ params[arg_name] = default_value++ if model_type:+ default_settings = get_default_settings(model_type)+ expected_args = inspect.signature(generate_video).parameters.keys()+ for arg_name in expected_args:+ if arg_name not in params and arg_name in default_settings:+ params[arg_name] = default_settings[arg_name]++ plugin_data = task.get('plugin_data', {})+ generate_video(task, send_cmd, plugin_data=plugin_data, **params)+ except Exception as e:+ print(f"\n [ERROR] {e}")+ traceback.print_exc()+ send_cmd("error", str(e))+ finally:+ send_cmd("exit", None)+ return error_handler++ async_run(make_error_handler(task, params, send_cmd))++ # Process output stream+ task_error = False+ last_msg_len = 0+ while True:+ cmd, data = com_stream.output_queue.next()+ if cmd == "exit":+ break+ elif cmd == "error":+ print(f"\n [ERROR] {data}")+ task_error = True+ elif cmd == "progress":+ if isinstance(data, list) and len(data) >= 2:+ if isinstance(data[0], tuple):+ step, total = data[0]+ msg = data[1] if len(data) > 1 else ""+ else:+ step, msg = 0, data[1] if len(data) > 1 else str(data[0])+ total = 1+ status_line = f"\r [{step}/{total}] {msg}"+ # Pad to clear previous longer messages+ print(status_line.ljust(max(last_msg_len, len(status_line))), end="", flush=True)+ last_msg_len = len(status_line)+ elif cmd == "status":+ status_line = f"\r {data}"+ print(status_line.ljust(max(last_msg_len, len(status_line))), end="", flush=True)+ last_msg_len = len(status_line)+ elif cmd == "output":+ print(f"\n Video saved")+ elif cmd == "info":+ print(f"\n [INFO] {data}")++ if not task_error:+ completed += 1+ print(f"\n Task {task_no} completed")++ elapsed = time.time() - start_time+ print(f"\n{'='*50}")+ print(f"Queue completed: {completed}/{total_tasks} tasks in {format_time(elapsed)}")+ return completed == total_tasks+def get_generation_status(prompt_no, prompts_max, repeat_no, repeat_max, window_no, total_windows):if prompts_max == 1:@@ -10735,6 +10847,98 @@ def create_ui():if __name__ == "__main__":app = WAN2GPApplication()++ # CLI Queue Processing Mode+ if len(args.process) > 0:+ download_ffmpeg() # Still needed for video encoding+ print(f"WanGP CLI Mode - Processing queue: {args.process}")++ if not os.path.isfile(args.process):+ print(f"[ERROR] File not found: {args.process}")+ sys.exit(1)++ # Override output directory if specified+ if len(args.output_dir) > 0:+ if not os.path.isdir(args.output_dir):+ os.makedirs(args.output_dir, exist_ok=True)+ server_config["save_path"] = args.output_dir+ server_config["image_save_path"] = args.output_dir+ # Update the module-level variables that generate_video() uses+ globals()["save_path"] = args.output_dir+ globals()["image_save_path"] = args.output_dir+ print(f"Output directory: {args.output_dir}")++ # Create minimal state with all required fields+ state = {+ "gen": {+ "queue": [],+ "in_progress": False,+ "file_list": [],+ "file_settings_list": [],+ "audio_file_list": [],+ "audio_file_settings_list": [],+ "selected": 0,+ "audio_selected": 0,+ "prompt_no": 0,+ "prompts_max": 0,+ "repeat_no": 0,+ "total_generation": 1,+ "window_no": 0,+ "total_windows": 0,+ "progress_status": "",+ "process_status": "process:main",+ },+ "loras": [],+ }++ # Use shared queue parser+ queue, error = _parse_queue_zip(args.process, state)+ if error:+ print(f"[ERROR] {error}")+ sys.exit(1)++ if len(queue) == 0:+ print("Queue is empty, nothing to process")+ sys.exit(0)++ print(f"Loaded {len(queue)} task(s)")++ # Dry-run mode: validate and exit+ if args.dry_run:+ print("\n[DRY-RUN] Queue validation:")+ for i, task in enumerate(queue, 1):+ prompt = (task.get('prompt', '') or '')[:50]+ model = task.get('params', {}).get('model_type', 'unknown')+ steps = task.get('steps', '?')+ length = task.get('length', '?')+ print(f" Task {i}: model={model}, steps={steps}, frames={length}")+ print(f" prompt: {prompt}...")+ print(f"\n[DRY-RUN] Validation complete. {len(queue)} task(s) ready.")+ # Clean up cache folder created during parsing+ dry_run_cache = os.path.join(server_config.get("save_path", "outputs"), "_loaded_queue_cache")+ if os.path.isdir(dry_run_cache):+ shutil.rmtree(dry_run_cache, ignore_errors=True)+ sys.exit(0)++ state["gen"]["queue"] = queue++ # Determine cache dir location for cleanup+ cli_save_path = args.output_dir if len(args.output_dir) > 0 else server_config.get("save_path", "outputs")+ cli_cache_dir = os.path.join(cli_save_path, "_loaded_queue_cache")++ try:+ success = process_tasks_cli(queue, state)+ # Clean up cache folder+ if os.path.isdir(cli_cache_dir):+ shutil.rmtree(cli_cache_dir, ignore_errors=True)+ sys.exit(0 if success else 1)+ except KeyboardInterrupt:+ print("\n\nAborted by user")+ if os.path.isdir(cli_cache_dir):+ shutil.rmtree(cli_cache_dir, ignore_errors=True)+ sys.exit(130)++ # Normal Gradio mode continues below...atexit.register(autosave_queue)download_ffmpeg()# threading.Thread(target=runner, daemon=True).start()@@ -10746,13 +10950,13 @@ if __name__ == "__main__":if args.listen:server_name = "0.0.0.0"if len(server_name) == 0:- server_name = os.getenv("SERVER_NAME", "localhost")+ server_name = os.getenv("SERVER_NAME", "localhost")demo = create_ui()if args.open_browser:- import webbrowser+ import webbrowserif server_name.startswith("http"):- url = server_name+ url = server_nameelse:- url = "http://" + server_name+ url = "http://" + server_namewebbrowser.open(url + ":" + str(server_port), new = 0, autoraise = True)demo.launch(favicon_path="favicon.png", server_name=server_name, server_port=server_port, share=args.share, allowed_paths=list({save_path, image_save_path, "icons"}))