Python
added kugel audio audio splitting
DeepBeepMeep1bb06d21356c
diff --git a/README.md b/README.mdindex 594d501..038ae4b 100644--- a/README.md+++ b/README.md@@ -33,7 +33,7 @@ WanGP supports the Wan (and derived models) but also Hunyuan Video, Flux, Qwen,## 🔥 Latest Updates :-### February 9rd 2026: WanGP v10.80, Easy Metal+### February 10th 2026: WanGP v10.82, Easy Metal- **Ace Step 1.5 Turbo Super Charged**: all the best features of *Ace Step 1.5* are now in *WanGP* and are *Fast* & *Easy* to use:* Manual Selection of *Bpm*, *Keyscale*, *Time Signature* & *Language*diff --git a/defaults/kugelaudio_0_open.json b/defaults/kugelaudio_0_open.jsonindex a2c3e92..aa0e491 100644--- a/defaults/kugelaudio_0_open.json+++ b/defaults/kugelaudio_0_open.json@@ -2,7 +2,7 @@"model": {"name": "TTS KugelAudio 0 Open 7B","architecture": "kugelaudio_0_open",- "description": "KugelAudio open-source text-to-speech with optional voice cloning, based on an AR + diffusion architecture. You can create a dialogue between two people by providing two audio sources and by starting lines alternatively with 'Speaker 0: ' or 'Speaker 1: '.",+ "description": "KugelAudio open-source text-to-speech with optional voice cloning. You can create a dialogue between two people by providing two audio sources and by starting lines alternatively with 'Speaker 0: ' or 'Speaker 1: '. You may observe Accelerated Speech with long speeches, use Manual Split (one empty line) or Auto Split to avoid this effect.","URLs": ["https://huggingface.co/DeepBeepMeep/TTS/resolve/main/kugelaudio_0_open_bf16.safetensors","https://huggingface.co/DeepBeepMeep/TTS/resolve/main/kugelaudio_0_open_quanto_bf16_int8.safetensors"diff --git a/docs/AMD-INSTALLATION.md b/docs/AMD-INSTALLATION.mdindex 8663cb0..79e14cd 100644--- a/docs/AMD-INSTALLATION.md+++ b/docs/AMD-INSTALLATION.md@@ -1,6 +1,6 @@# AMD Installation Guide for Windows (TheRock)-This guide covers installation for AMD GPUs and APUs running under Windows using TheRock's official PyTorch wheels.+This guide covers installation for AMD GPUs running under Windows using TheRock's official PyTorch wheels.## Supported GPUs@@ -206,7 +206,7 @@ set FLASH_ATTENTION_TRITON_AMD_ENABLE=TRUEset TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1```-MIOpen (AMD’s equivalent of NVIDIA’s cuDNN) is not yet fully stable on several architectures; it can cause out-of-memory errors (OOMs), crash the display driver, or significantly increase generation times. Currently, it is recommended to either use fast mode by setting:+MIOpen (AMD’s equivalent of NVIDIA’s cuDNN) is not yet fully stable on several architectures; it can cause out-of-memory errors (OOMs), crash the display driver, or significantly increase generation times. Currently, it is recommended to use fast mode by setting:```cmdset MIOPEN_FIND_MODE=FAST@@ -216,10 +216,12 @@ Alternatively, you can disable MIOpen entirely by editing `wgp.py` and adding th```cmd...-:: /Lines already in the file/+:: /lines already in the file/+:: ...:: import torchtorch.backends.cudnn.enabled = False # <-- Add this here:: import gc+:: ......```@@ -246,7 +248,6 @@ If `torch.cuda.is_available()` returns `False`:**"Could not find a version that satisfies the requirement":**- Double-check that you're using the correct `--index-url` for your GPU family. You can also try adding the `--pre` flag or replacing `/v2/` in the URL with `/v2/staging/`- Ensure you're using Python 3.11, and not 3.10-- Try adding `--pre` flag if not already present**"No matching distribution found":**- Your GPU architecture may not be supported@@ -271,4 +272,4 @@ Known issues are tracked at: https://github.com/ROCm/TheRock/issues/808- [Roadmap](https://github.com/ROCm/TheRock/blob/main/ROADMAP.md)- [ROCm Documentation](https://rocm.docs.amd.com/)-For additional troubleshooting guidance for Wan2GP, see [TROUBLESHOOTING.md](https://github.com/deepbeepmeep/Wan2GP/blob/main/docs/TROUBLESHOOTING.md).+For additional troubleshooting guidance for Wan2GP, see [TROUBLESHOOTING.md](https://github.com/deepbeepmeep/Wan2GP/blob/main/docs/TROUBLESHOOTING.md).\ No newline at end of filediff --git a/models/TTS/kugelaudio/pipeline.py b/models/TTS/kugelaudio/pipeline.pyindex 6eaae56..09f0ffa 100644--- a/models/TTS/kugelaudio/pipeline.py+++ b/models/TTS/kugelaudio/pipeline.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport jsonimport osimport random+import reimport timefrom pathlib import Pathfrom typing import Optional@@ -32,6 +33,7 @@ KUGELAUDIO_TOKENIZER_FILES = ["vocab.json",]KUGELAUDIO_DEBUG = os.getenv("KUGELAUDIO_DEBUG", "0") not in ("0", "", "false", "False")+KUGELAUDIO_AUTO_SPLIT_SETTING_ID = "auto_split_every_s"def _seed_everything(seed: int) -> None:@@ -203,6 +205,106 @@ class KugelAudioPipeline:except (TypeError, ValueError):return 2048+ def _resolve_auto_split_seconds(self, kwargs: dict) -> Optional[float]:+ custom_settings = kwargs.get("custom_settings", None)+ if not isinstance(custom_settings, dict):+ return None+ raw_value = custom_settings.get(KUGELAUDIO_AUTO_SPLIT_SETTING_ID, None)+ if raw_value is None:+ return None+ if isinstance(raw_value, str):+ raw_value = raw_value.strip()+ if len(raw_value) == 0:+ return None+ try:+ if isinstance(raw_value, bool):+ return None+ value = float(raw_value)+ except (TypeError, ValueError):+ return None+ return value if value > 0 else None++ def _resolve_cut_char_index(self, text: str, token_limit: Optional[int]) -> Optional[int]:+ if token_limit is None or token_limit <= 0 or len(text) == 0:+ return None+ tokenizer = getattr(self.processor, "tokenizer", None)+ if tokenizer is None:+ return None+ try:+ encoded = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True)+ offsets = encoded.get("offset_mapping", None) if isinstance(encoded, dict) else None+ if offsets is None and hasattr(encoded, "offset_mapping"):+ offsets = encoded.offset_mapping+ if offsets is None or len(offsets) <= token_limit:+ return None+ cut_char = offsets[token_limit][0]+ if isinstance(cut_char, (list, tuple)):+ cut_char = cut_char[0]+ cut_char = int(cut_char)+ return min(len(text), max(1, cut_char))+ except Exception:+ try:+ token_ids = tokenizer.encode(text, add_special_tokens=False)+ except Exception:+ return None+ if token_ids is None or len(token_ids) <= token_limit:+ return None+ try:+ prefix = tokenizer.decode(+ token_ids[:token_limit],+ skip_special_tokens=False,+ clean_up_tokenization_spaces=False,+ )+ except Exception:+ return None+ return min(len(text), max(1, len(prefix)))++ def _find_split_index_before_cut(self, text: str, cut_index: int) -> int:+ safe_cut = min(len(text), max(1, int(cut_index)))+ prefix = text[:safe_cut]+ dot_idx = prefix.rfind(".")+ newline_idx = prefix.rfind("\n")+ best_idx = max(dot_idx, newline_idx)+ if best_idx >= 0:+ return best_idx + 1+ space_idx = prefix.rfind(" ")+ if space_idx >= 0:+ return space_idx + 1+ return safe_cut++ def _split_text_sequence(self, text: str, auto_split_tokens: Optional[int]) -> list[str]:+ normalized = str(text or "").replace("\r\n", "\n").replace("\r", "\n")+ normalized = re.sub(r"\n(?:[ \t]*\n)+", "\n\n", normalized)+ manual_blocks = re.split(r"\n\s*\n", normalized)+ segments = []+ for block in manual_blocks:+ remaining = block.strip()+ if len(remaining) == 0:+ continue+ if auto_split_tokens is None or auto_split_tokens <= 0:+ segments.append(remaining)+ continue+ while len(remaining) > 0:+ cut_index = self._resolve_cut_char_index(remaining, auto_split_tokens)+ if cut_index is None:+ segments.append(remaining.strip())+ break+ split_index = self._find_split_index_before_cut(remaining, cut_index)+ if split_index <= 0:+ split_index = min(len(remaining), max(1, cut_index))+ piece = remaining[:split_index].strip()+ if len(piece) == 0:+ split_index = min(len(remaining), max(1, cut_index))+ piece = remaining[:split_index].strip()+ if len(piece) == 0:+ split_index = 1+ piece = remaining[:1]+ segments.append(piece)+ remaining = remaining[split_index:].lstrip()+ if len(segments) == 0 and len(normalized.strip()) > 0:+ segments.append(normalized.strip())+ return segments+def generate(self,input_prompt: str,@@ -218,6 +320,8 @@ class KugelAudioPipeline:text = _read_text_or_file(input_prompt, "Prompt")if not text.strip():raise ValueError("Prompt text cannot be empty for KugelAudio.")+ if "\\n" in text and "\n" not in text:+ text = text.replace("\\r\\n", "\n").replace("\\n", "\n")if KUGELAUDIO_DEBUG:print("[KugelAudio][debug] prompt repr:", repr(text))print("[KugelAudio][debug] contains 'Speaker':", "Speaker" in text)@@ -246,6 +350,19 @@ class KugelAudioPipeline:"max_new_tokens:",max_new_tokens,)+ auto_split_seconds = self._resolve_auto_split_seconds(kwargs)+ auto_split_tokens = (+ max(1, int(round(auto_split_seconds * self._tokens_per_second())))+ if auto_split_seconds is not None+ else None+ )+ if KUGELAUDIO_DEBUG:+ print(+ "[KugelAudio][debug] auto_split_seconds:",+ auto_split_seconds,+ "auto_split_tokens:",+ auto_split_tokens,+ )cfg_scale = kwargs.get("guide_scale", None)if cfg_scale is None:@@ -320,7 +437,7 @@ class KugelAudioPipeline:callback(step_idx=progress_seconds,override_num_inference_steps=int(round(total_seconds)),- denoising_extra=f"Line {int(completed_lines) + 1}/{total_lines}",+ denoising_extra=f"Segment {int(completed_lines) + 1}/{total_lines}",progress_unit="s",)active_callback = _line_callback@@ -350,12 +467,6 @@ class KugelAudioPipeline:# Multi-speaker mode: split by Speaker tags and run per segment (ComfyUI behavior)# Only do this when a reference voice is provided; otherwise let the native model handle speakers.if "Speaker" in text and (audio_guide is not None or audio_guide2 is not None):- import re-- # If the UI passed literal "\n", normalize to real line breaks for parsing.- if "\\n" in text and "\n" not in text:- text = text.replace("\\r\\n", "\n").replace("\\n", "\n")-tag_pattern = re.compile(r"Speaker\s*(\d+)\s*:\s*", re.IGNORECASE)matches = list(tag_pattern.finditer(text))if KUGELAUDIO_DEBUG:@@ -387,6 +498,19 @@ class KugelAudioPipeline:print("[KugelAudio][debug] seg", idx, "speaker", sid, "text:", repr(seg[:120]))if parsed:+ expanded = []+ for parsed_idx, (speaker_id, line_text) in enumerate(parsed):+ split_segments = self._split_text_sequence(line_text, auto_split_tokens)+ for split_idx, one_segment in enumerate(split_segments):+ expanded.append(+ (+ speaker_id,+ one_segment,+ split_idx == len(split_segments) - 1 and parsed_idx < len(parsed) - 1,+ )+ )+ if KUGELAUDIO_DEBUG:+ print("[KugelAudio][debug] expanded segments:", len(expanded))audio_segments = []pause_seconds = kwargs.get("pause_seconds", 0.2)try:@@ -404,7 +528,7 @@ class KugelAudioPipeline:elapsed_seconds = 0.0total_duration_seconds = duration_seconds if duration_seconds is not None and duration_seconds > 0 else Nonecompleted_lines = 0- for idx, (speaker_id, line_text) in enumerate(parsed):+ for speaker_id, line_text, append_pause_after in expanded:if self._abort_requested():return Noneduration_left = None@@ -422,7 +546,7 @@ class KugelAudioPipeline:extra_tail_tokens=extra_tail_tokens,segment_duration_seconds=duration_left,completed_lines=completed_lines,- total_lines=len(parsed),+ total_lines=len(expanded),cumulative_offset_seconds=elapsed_seconds,)if segment is None:@@ -434,7 +558,7 @@ class KugelAudioPipeline:completed_lines += 1# No extra callback here; per-line callback handles progress.elapsed_seconds += float(segment.shape[-1]) / float(self.sample_rate)- if silence is not None and idx < len(parsed) - 1:+ if silence is not None and append_pause_after:audio_segments.append(silence.to(segment))elapsed_seconds += float(pause_samples) / float(self.sample_rate)if self._early_stop_requested():@@ -443,8 +567,46 @@ class KugelAudioPipeline:audio = torch.cat(audio_segments, dim=-1)return {"x": audio, "audio_sampling_rate": int(self.sample_rate)}- # Default single-pass generationvoice_prompt = audio_guide+ single_segments = self._split_text_sequence(text, auto_split_tokens)+ if len(single_segments) > 1:+ audio_segments = []+ elapsed_seconds = 0.0+ total_duration_seconds = (+ duration_seconds if duration_seconds is not None and duration_seconds > 0 else None+ )+ for idx, one_segment in enumerate(single_segments):+ if self._abort_requested():+ return None+ duration_left = None+ if total_duration_seconds is not None:+ duration_left = max(0.0, total_duration_seconds - elapsed_seconds)+ if duration_left <= 0:+ break+ segment = _run_single(+ one_segment + " ",+ voice_prompt,+ extra_tail_tokens=3,+ segment_duration_seconds=duration_left,+ completed_lines=idx,+ total_lines=len(single_segments),+ cumulative_offset_seconds=elapsed_seconds,+ )+ if segment is None:+ if self._early_stop_requested() and audio_segments:+ audio = torch.cat(audio_segments, dim=-1)+ return {"x": audio, "audio_sampling_rate": int(self.sample_rate)}+ return None+ audio_segments.append(segment)+ elapsed_seconds += float(segment.shape[-1]) / float(self.sample_rate)+ if self._early_stop_requested():+ break+ if len(audio_segments) > 0:+ audio = torch.cat(audio_segments, dim=-1)+ return {"x": audio, "audio_sampling_rate": int(self.sample_rate)}+ return None++ # Default single-pass generationinputs = self.processor(text=text,voice_prompt=voice_prompt,diff --git a/models/TTS/kugelaudio_handler.py b/models/TTS/kugelaudio_handler.pyindex 9eddf34..fbb1c5c 100644--- a/models/TTS/kugelaudio_handler.py+++ b/models/TTS/kugelaudio_handler.py@@ -28,6 +28,17 @@ KUGELAUDIO_DURATION_SLIDER = {"increment": 1,"default": 20,}+KUGELAUDIO_AUTO_SPLIT_SETTING_ID = "auto_split_every_s"+KUGELAUDIO_AUTO_SPLIT_MIN_SECONDS = 5.0+KUGELAUDIO_AUTO_SPLIT_MAX_SECONDS = 90.0+KUGELAUDIO_CUSTOM_SETTINGS = [+ {+ "id": KUGELAUDIO_AUTO_SPLIT_SETTING_ID,+ "label": "Auto Split Every s (5-90, optional), to avoid Acceleration Effect. Empty Lines will force anyway Manual Splits.",+ "name": "Auto Split Every s",+ "type": "float",+ },+]def _get_kugelaudio_model_def():@@ -43,6 +54,8 @@ def _get_kugelaudio_model_def():"supports_early_stop": True,"profiles_dir": ["kugelaudio_0_open"],"duration_slider": dict(KUGELAUDIO_DURATION_SLIDER),+ "custom_settings": [one.copy() for one in KUGELAUDIO_CUSTOM_SETTINGS],+ "preserve_empty_prompt_lines": True,"pause_between_sentences": True,"any_audio_prompt": True,"audio_guide_label": "Reference voice (optional)",@@ -211,3 +224,44 @@ class family_handler:if "Speaker 1:" not in text and "speaker 1:" not in text:return "Two-voice cloning requires prompt lines with Speaker 0: and Speaker 1:."return None++ @staticmethod+ def validate_generative_settings(base_model_type, model_def, inputs):+ custom_settings = inputs.get("custom_settings", None)+ if custom_settings is None:+ return None+ if not isinstance(custom_settings, dict):+ return "Custom settings must be a dictionary."++ raw_value = custom_settings.get(KUGELAUDIO_AUTO_SPLIT_SETTING_ID, None)+ if raw_value is None:+ return None+ if isinstance(raw_value, str):+ raw_value = raw_value.strip()+ if len(raw_value) == 0:+ custom_settings.pop(KUGELAUDIO_AUTO_SPLIT_SETTING_ID, None)+ inputs["custom_settings"] = custom_settings if len(custom_settings) > 0 else None+ return None++ try:+ if isinstance(raw_value, bool):+ raise ValueError()+ auto_split_seconds = float(raw_value)+ except Exception:+ return (+ f"Auto Split Every s must be a number between "+ f"{int(KUGELAUDIO_AUTO_SPLIT_MIN_SECONDS)} and {int(KUGELAUDIO_AUTO_SPLIT_MAX_SECONDS)} seconds."+ )++ if (+ auto_split_seconds < KUGELAUDIO_AUTO_SPLIT_MIN_SECONDS+ or auto_split_seconds > KUGELAUDIO_AUTO_SPLIT_MAX_SECONDS+ ):+ return (+ f"Auto Split Every s must be between "+ f"{int(KUGELAUDIO_AUTO_SPLIT_MIN_SECONDS)} and {int(KUGELAUDIO_AUTO_SPLIT_MAX_SECONDS)} seconds."+ )++ custom_settings[KUGELAUDIO_AUTO_SPLIT_SETTING_ID] = auto_split_seconds+ inputs["custom_settings"] = custom_settings+ return Nonediff --git a/requirements.txt b/requirements.txtindex e223030..a42a9b4 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,3 +1,4 @@+--extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ort-cuda-13-nightly/pypi/simple/# Core AI stackdiffusers==0.36.0transformers==4.54.0 #4.53.1@@ -34,13 +35,15 @@ logurus3tokenizerconformer==0.3.2spacy_pkuseg-spacy==3.8.4+spacy+gradio_rangeslider# Vision & segmentationopencv-python>=4.12.0.88segment-anythingrembg[gpu]==2.0.65-onnxruntime-gpu==1.22+onnxruntime-gpu==1.22.0; python_version < "3.11"+onnxruntime-gpu==1.25.0.dev20260210001; python_version >= "3.11"decordtimminsightface @ https://github.com/deepbeepmeep/insightface/releases/download/insightface/insightface-0.7.3-cp310-cp310-win_amd64.whl ; sys_platform == "win32" and python_version == "3.10"diff --git a/shared/utils/prompt_parser.py b/shared/utils/prompt_parser.pyindex 46edec4..116a061 100644--- a/shared/utils/prompt_parser.py+++ b/shared/utils/prompt_parser.py@@ -1,6 +1,6 @@import re-def process_template(input_text, keep_comments = False):+def process_template(input_text, keep_comments=False, keep_empty_lines=False):"""Process a text template with macro instructions and variable substitution.Supports multiple values for variables to generate multiple output versions.@@ -14,7 +14,8 @@ def process_template(input_text, keep_comments = False):- output_text: Processed output with variables substituted, or empty string if error- error_message: Error description and problematic line, or empty string if no error"""- lines = input_text.strip().split('\n')+ normalized_input = str(input_text or "").replace("\r\n", "\n").replace("\r", "\n")+ lines = normalized_input.split("\n") if keep_empty_lines else normalized_input.strip().split("\n")current_variables = {}current_template_lines = []all_output_lines = []@@ -29,6 +30,8 @@ def process_template(input_text, keep_comments = False):# Skip empty lines or commentsif not line:+ if keep_empty_lines:+ current_template_lines.append("")continueif line.startswith('#') and not keep_comments:@@ -292,4 +295,4 @@ def generate_macro_line(variables_dict):sections.append(section)# Join sections with a colon and space for readability- return "! " + " : ".join(sections)\ No newline at end of file+ return "! " + " : ".join(sections)diff --git a/wgp.py b/wgp.pyindex 555bd64..582a5e0 100644--- a/wgp.py+++ b/wgp.py@@ -662,30 +662,24 @@ def validate_settings(state, model_type, single_prompt, inputs):gr.Info("Adaptive Progressive Guidance and Classifier Free Guidance Star can not be set at the same time")return ret()prompt = inputs["prompt"]- if len(prompt) ==0:- gr.Info("Prompt cannot be empty.")- gen = get_gen_info(state)- queue = gen.get("queue", [])- return ret()- prompt, errors = prompt_parser.process_template(prompt)+ prompt, errors = prompt_parser.process_template(prompt, keep_empty_lines=model_def.get("preserve_empty_prompt_lines", False))if len(errors) > 0:gr.Info("Error processing prompt template: " + errors)return ret()+ prompt = prompt.strip("\n").strip()- multi_prompts_gen_type = inputs["multi_prompts_gen_type"]-- prompts = prompt.replace("\r", "").split("\n")- prompts = [prompt.strip() for prompt in prompts if len(prompt.strip())>0 and not prompt.startswith("#")]-- if single_prompt or multi_prompts_gen_type == 2:- prompts = ["\n".join(prompts)]-- if len(prompts) == 0:+ if len(prompt) == 0:gr.Info("Prompt cannot be empty.")gen = get_gen_info(state)queue = gen.get("queue", [])return ret()+ multi_prompts_gen_type = inputs["multi_prompts_gen_type"]+ if single_prompt or multi_prompts_gen_type == 2:+ prompts = [prompt]+ else:+ prompts = [one_line.strip() for one_line in prompt.split("\n") if len(one_line.strip()) > 0]+parsed_custom_settings, custom_settings_error = collect_custom_settings_from_inputs(model_def, inputs, strict=True)if custom_settings_error is not None:gr.Info(custom_settings_error)@@ -7100,15 +7094,6 @@ def process_tasks(state):try:import inspectmodel_type = params.get('model_type')- known_defaults = {- 'image_refs_relative_size': 50,- 'custom_settings': None,- }-- for arg_name, default_value in known_defaults.items():- if arg_name not in params:- print(f"Warning: Missing argument '{arg_name}' in loaded task. Applying default value: {default_value}")- params[arg_name] = default_valueif model_type:default_settings = get_default_settings(model_type)expected_args = set(inspect.signature(generate_video).parameters.keys())