
    i                    *   S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKJ	r	J
r
JrJrJrJr  SSKJrJrJr  SSKJr  SSKrSSKrSSKJrJrJrJrJr  SSKJrJ r J!r!J"r"J#r#  \RH                  RK                  S5      SLr&S@S
 jr'\ " S S5      5       r(\ " S S5      5       r)\" SS9 " S S5      5       r*\ " S S5      5       r+\ " S S5      5       r,S\\-\4   S\	\.   S\-S\-S\	\/   S\-S\-S\-S\\	\.   \-\-\	\/   \-\-\-4   4S  jr0S!\-S\\-   4S" jr1S#\S\	\.   4S$ jr2S%\\.   S&\	\.   S\\.   4S' jr3S!\	\-   S\	\*   4S( jr4S!\	\-   S\	\Rj                     4S) jr6\'" S	S*9  SAS+\(S,\)S-\	\-   S\+4S. jj5       r7      SBS/\-S0\/S1\	\.   S2\	\/   S3\/S4\8S5\8S\,4S6 jjr9\ " S7 S85      5       r:        SCS9\-S:\8S\	\-   S0\/S1\	\.   S2\	\/   S3\/S4\8S5\8S\:4S; jjr;\ " S< S=5      5       r<       SDS\-S\-S>\	\\-\4      S0\/S1\	\.   S2\	\/   S3\/S4\8S5\8S\<4S? jjr=g)Ez
ACE-Step Inference API Module

This module provides a standardized inference interface for music generation,
designed for third-party integration. It offers both a simplified API and
backward-compatible Gradio UI support.
    N)OptionalUnionListDictAnyTuple)	dataclassfieldasdict)logger)
AudioSaver
apply_fadegenerate_uuid_from_paramsnormalize_audioget_lora_weights_hash)BPM_MINBPM_MAXDURATION_MAX
TASK_TYPESVALID_TIME_SIGNATURESSPACE_ID   c                     [         (       a   SSKnUR                  U S9$ S $ ! [         a    [        R
                  " S5        S s $ f = f)z
Get the @spaces.GPU decorator if running in HuggingFace Space environment.
Returns identity decorator if not in Space environment.
r   Ndurationz0spaces package not found, GPU decorator disabledc                     U $ N funcs    0/mnt/workspace/ACE-Step-1.5/acestep/inference.py<lambda>+_get_spaces_gpu_decorator.<locals>.<lambda>(   s        c                     U $ r   r   r   s    r!   r"   r#   )   s    r$   )IS_HUGGINGFACE_SPACEspacesGPUImportErrorr   warning)r   r'   s     r!   _get_spaces_gpu_decoratorr+      sO    
 	%::x:00   	%NNMN$$	%s   # #A	A	c                   b   \ rS rSr% SrSr\\S'   Sr\\S'   Sr	\
\   \S'   Sr\
\   \S	'   S
r\\S'   S
r\\S'   S
r\\S'   S
r\\S'   Sr\\S'   Sr\\S'   Sr\
\   \S'   S
r\\S'   S
r\\S'   Sr\\S'   Sr\\S'   Sr\\S'   Sr\\S'   Sr\\S'   Sr\\S'   Sr\\S '   S!r\\S"'   S#r \\S$'   S%r!\\S&'   Sr"\\S''   Sr#\\S('   Sr$\\S)'   Sr%\\S*'   S+r&\\S,'   S-r'\\S.'   Sr(\\S/'   Sr)\\S0'   Sr*\\S1'   S2r+\\S3'   S4r,\\S5'   S6r-\\S7'   S8r.\\S9'   Sr/\
\0\      \S:'   Sr1\\S;'   S#r2\\S<'   S=r3\\S>'   S?r4\\S@'   Sr5\\SA'   SBr6\\SC'   SDr7\\SE'   Sr8\
\9\\4      \SF'   Sr:\\SG'   Sr;\\SH'   S
r<\\SI'   S
r=\\SJ'   Sr>\\SK'   Sr?\\SL'   SMr@\\SN'   SrA\\SO'   SrB\\SP'   SrC\\SQ'   SRrD\\SS'   STrE\\SU'   SVrF\\SW'   SXrG\\SY'   SZrH\\S['   SrI\\S\'   SrJ\\S]'   SrK\\S^'   SrL\\S_'   SrM\\S`'   SrN\
\   \Sa'   S
rO\\Sb'   S
rP\\Sc'   SrQ\
\   \Sd'   SrR\\Se'   S
rS\\Sf'   S
rT\\Sg'   Sh rUSi\V\\W4   4Sj jrXSkrYg)lGenerationParams,   u+  Configuration for music generation parameters.

Attributes:
    # Text Inputs
    caption: A short text prompt describing the desired music (main prompt). < 512 characters
    lyrics: Lyrics for the music. Use "[Instrumental]" for instrumental songs. < 4096 characters
    instrumental: If True, generate instrumental music regardless of lyrics.
    
    # Music Metadata
    bpm: BPM (beats per minute), e.g., 120. Set to None for automatic estimation. 30 ~ 300
    keyscale: Musical key (e.g., "C Major", "Am"). Leave empty for auto-detection. A-G, #/♭, major/minor
    timesignature: Time signature (2 for '2/4', 3 for '3/4', 4 for '4/4', 6 for '6/8'). Leave empty for auto-detection.
    vocal_language: Language code for vocals, e.g., "en", "zh", "ja", or "unknown". see acestep/constants.py:VALID_LANGUAGES
    duration: Target audio length in seconds. If <0 or None, model chooses automatically. 10 ~ 600
    
    # Audio Post-Processing
    enable_normalization: Whether to apply loudness normalization to the output audio.
    normalization_db: Target loudness in dB for normalization (e.g., -1.0 for -1 dBFS peak).
    latent_shift: Additive shift applied to DiT latents before VAE decode (default 0, no shift).
    latent_rescale: Multiplicative rescale applied to DiT latents before VAE decode (default 1.0, no rescale).
    
    # Generation Parameters
    inference_steps: Number of diffusion steps (e.g., 8 for turbo, 32–100 for base model).
    guidance_scale: CFG (classifier-free guidance) strength. Higher means following the prompt more strictly. Only support for non-turbo model.
    seed: Integer seed for reproducibility. -1 means use random seed each time.
    
    # Advanced DiT Parameters
    use_adg: Whether to use Adaptive Dual Guidance (only works for base model).
    cfg_interval_start: Start ratio (0.0–1.0) to apply CFG.
    cfg_interval_end: End ratio (0.0–1.0) to apply CFG.
    shift: Timestep shift factor (default 1.0). When != 1.0, applies t = shift * t / (1 + (shift - 1) * t) to timesteps.
    
    # Task-Specific Parameters
    task_type: Type of generation task. One of: "text2music", "cover", "repaint", "lego", "extract", "complete".
    reference_audio: Path to a reference audio file for style transfer or cover tasks.
    src_audio: Path to a source audio file for audio-to-audio tasks.
    audio_codes: Audio semantic codes as a string (advanced use, for code-control generation).
    repainting_start: For repaint/lego tasks: start time in seconds for region to repaint.
    repainting_end: For repaint/lego tasks: end time in seconds for region to repaint (-1 for until end).
    audio_cover_strength: Strength of reference audio/codes influence (range 0.0–1.0). set smaller (0.2) for style transfer tasks.
    instruction: Optional task instruction prompt. If empty, auto-generated by system.
    
    # 5Hz Language Model Parameters for CoT reasoning
    thinking: If True, enable 5Hz Language Model "Chain-of-Thought" reasoning for semantic/music metadata and codes.
    lm_temperature: Sampling temperature for the LLM (0.0–2.0). Higher = more creative/varied results.
    lm_cfg_scale: Classifier-free guidance scale for the LLM.
    lm_top_k: LLM top-k sampling (0 = disabled).
    lm_top_p: LLM top-p nucleus sampling (1.0 = disabled).
    lm_negative_prompt: Negative prompt to use for LLM (for control).
    use_cot_metas: Whether to let LLM generate music metadata via CoT reasoning.
    use_cot_caption: Whether to let LLM rewrite or format the input caption via CoT reasoning.
    use_cot_language: Whether to let LLM detect vocal language via CoT.

text2music	task_typez;Fill the audio semantic mask based on the given conditions:instructionNreference_audio	src_audio audio_codescaptionglobal_captionlyricsFinstrumentalunknownvocal_languagebpmkeyscaletimesignatureg      r   Tenable_normalizationnormalization_db        fade_in_durationfade_out_durationlatent_shift      ?latent_rescale   inference_stepsseedg      @guidance_scaleuse_adgcfg_interval_startcfg_interval_endshiftodeinfer_methodeulersampler_modevelocity_norm_thresholdvelocity_ema_factordcw_enableddoubledcw_modeg?
dcw_scalerg{Gz?dcw_high_scalerhaardcw_wavelet	timestepsrepainting_startrepainting_endautochunk_mask_mode
   repaint_latent_crossfade_framesrepaint_wav_crossfade_secbalancedrepaint_modeg      ?repaint_strengthretake_seedretake_varianceflow_edit_morphflow_edit_source_captionflow_edit_source_lyricsflow_edit_n_minflow_edit_n_max   flow_edit_n_avgaudio_cover_strengthcover_noise_strengththinking333333?lm_temperatureg       @lm_cfg_scaler   lm_top_kg?lm_top_pNO USER INPUTlm_negative_promptuse_cot_metasuse_cot_captionuse_cot_lyricsuse_cot_languageuse_constrained_decodingcot_bpmcot_keyscalecot_timesignaturecot_durationcot_vocal_languagecot_caption
cot_lyricsc                     U R                   b  U R                   S::  a  SU l         U R                  b  U R                  S:  a  SU l        g g g )Nr   rE   ro   )rO   rH   selfs    r!   __post_init__GenerationParams.__post_init__   sG    ::!djjAoDJ+0D0Dq0H#$D  1I+r$   returnc                     [        U 5      $ z4Convert config to dictionary for JSON serialization.r   r   s    r!   to_dictGenerationParams.to_dict       d|r$   )rH   rO   )Z__name__
__module____qualname____firstlineno____doc__r0   str__annotations__r1   r2   r   r3   r5   r6   r7   r8   r9   boolr;   r<   intr=   r>   r   floatr?   r@   rB   rC   rD   rF   rH   rJ   rK   rL   rM   rN   rO   rQ   rS   rT   rU   rV   rX   rY   rZ   r\   r]   r   r^   r_   ra   rc   rd   rf   rg   rh   r   ri   rj   rk   rl   rm   rn   rp   rq   rr   rs   ru   rv   rw   rx   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   r   r   r   r   r   __static_attributes__r   r$   r!   r-   r-   ,   sK   4l "Is!TKT &*OXc])#Ix}# K GSNCFCL$ $NC#C#HcM3He "&$%"e"!e!"u" L%NE OSD#NNEGT ##!e!E5L#L#%(U(!$$ K
 HcJ!OU!K (,IxU$+!e!NE!OS!+-#S-'*u*"L#"!e! .2K%S/*1 OU  "OT!$&c&#%S% OU  OU OS"%%%"%%% Hd NE L%HcHe--M4 OT  ND !d!%)d)!GXc]!L#s$(L(5/(''KJ%c3h r$   r-   c                       \ rS rSr% SrSr\\S'   Sr\	\S'   Sr
\	\S'   S	r\\\      \S
'   Sr\\S'   Sr\	\S'   Sr\\S'   Sr\\S'   Sr\\S'   S\\\4   4S jrSrg	)GenerationConfig   a  Configuration for music generation.

Attributes:
    batch_size: Number of audio samples to generate
    allow_lm_batch: Whether to allow batch processing in LM
    use_random_seed: Whether to use random seed
    seeds: Seed(s) for batch generation. Can be:
        - None: Use random seeds (when use_random_seed=True) or params.seed (when use_random_seed=False)
        - List[int]: List of seeds, will be padded with random seeds if fewer than batch_size
        - int: Single seed value (will be converted to list and padded)
    lm_batch_chunk_size: Batch chunk size for LM processing
    constrained_decoding_debug: Whether to enable constrained decoding debug
    audio_format: Output audio format, one of "mp3", "wav", "flac", "wav32", "opus", "aac". Default: "flac"
    mp3_bitrate: MP3 bitrate used when audio_format="mp3". Default: "128k"
    mp3_sample_rate: MP3 output sample rate used when audio_format="mp3". Default: 48000
   
batch_sizeFallow_lm_batchTuse_random_seedNseedsrG   lm_batch_chunk_sizeconstrained_decoding_debugflacaudio_format128kmp3_bitrate逻  mp3_sample_rater   c                     [        U 5      $ r   r   r   s    r!   r   GenerationConfig.to_dict   r   r$   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r$   r!   r   r      s      J ND  OT !%E8DI%  ',,L#K OS c3h r$   r   T)frozenc                   R    \ rS rSr% Sr\R                  \S'   \\	   \S'   \
\S'   Srg)CachedRepaintSourcei  z<Generated-source repaint cache loaded from an audio sidecar.latentssource_seedlatent_pathr   N)r   r   r   r   r   torchTensorr   r   r   r   r   r   r$   r!   r   r     s    F\\#r$   r   c                       \ rS rSr% Sr\" \S9r\\	\
\4      \S'   Sr\
\S'   \" \S9r\	\
\4   \S'   Sr\\S	'   S
r\\
   \S'   S\	\
\4   4S jrSrg
)GenerationResulti  aF  Result of music generation.

Attributes:
    # Audio Outputs
    audios: List of audio dictionaries with paths, keys, params
    status_message: Status message from generation
    extra_outputs: Extra outputs from generation
    success: Whether generation completed successfully
    error: Error message if generation failed
)default_factoryaudiosr4   status_messageextra_outputsTsuccessNerrorr   c                     [        U 5      $ z4Convert result to dictionary for JSON serialization.r   r   s    r!   r   GenerationResult.to_dict!  r   r$   r   )r   r   r   r   r   r
   listr   r   r   r   r   r   r   dictr   r   r   r   r   r   r   r   r$   r!   r   r     sr    	 $)#>FDc3h >NC$)$$?M4S>?GTE8C=c3h r$   r   c                       \ rS rSr% SrSr\\S'   Sr\\S'   Sr	\
\   \S'   Sr\
\   \S'   Sr\\S	'   Sr\\S
'   Sr\\S'   Sr\\S'   Sr\\S'   Sr\
\   \S'   S\\\4   4S jrSrg)UnderstandResulti&  a_  Result of music understanding from audio codes.

Attributes:
    # Metadata Fields
    caption: Generated caption describing the music
    lyrics: Generated or extracted lyrics
    bpm: Beats per minute (None if not detected)
    duration: Duration in seconds (None if not detected)
    keyscale: Musical key (e.g., "C Major")
    language: Vocal language code (e.g., "en", "zh")
    timesignature: Time signature (e.g., "4/4")
    
    # Status
    status_message: Status message from understanding
    success: Whether understanding completed successfully
    error: Error message if understanding failed
r4   r6   r8   Nr<   r   r=   languager>   r   Tr   r   r   c                     [        U 5      $ r   r   r   s    r!   r   UnderstandResult.to_dictG  r   r$   r   r   r   r   r   r   r6   r   r   r8   r<   r   r   r   r   r=   r   r>   r   r   r   r   r   r   r   r   r   r$   r!   r   r   &  s    $ GSFCC# $Hhuo$HcHcM3 NCGTE8C=c3h r$   r   metadatar<   	key_scaletime_signatureaudio_durationr;   r6   r8   r   c                 j   Uc9  U R                  S5      (       a#  U R                  S5      nUS;  a   [        U5      nU(       d@  U R                  S5      (       a*  U R                  SU R                  SS5      5      n	U	S:w  a  U	nU(       d@  U R                  S5      (       a*  U R                  SU R                  SS5      5      n
U
S:w  a  U
nUb  US	::  a$  U R                  S
S5      nUS;  a   [	        U5      nU(       d'  U R                  S5      (       a  U R                  S5      nU(       d'  U R                  S5      (       a  U R                  S5      nU(       d'  U R                  S5      (       a  U R                  S5      nXX4XVU4$ ! [        [        4 a     GN^f = f! [        [        4 a     Nf = f)z>Update metadata fields from LM output if not provided by user.r<   )N/Ar4   r=   r   r4   r   r>   r   r   r   rI   r;   r6   r8   )getr   
ValueError	TypeErrorr   )r   r<   r   r   r   r;   r6   r8   	bpm_valuekey_scale_valuetime_signature_valueaudio_duration_values               r!   _update_metadata_from_lmr   L  s    {x||E**LL'	K')n j11",,z8<<R3PQe#'Ihll?;;'||OX\\JZ\^=_`5(1N1!4'||J;{2!&';!< hll+;<<!&67x||I..,,y)hll8,,h'>>TZZZ7 	* $ 	* s#   F -F FFF21F2r3   c           	      8   [         R                  R                  U 5      n[         R                  R                  U5      S   S-   /n[         R                  R                  [         R                  R	                  U5      5      S   nU(       a  [         R                  R                  [         R                  " 5       S5      n[        R                  " [         R                  R                  US[        R                  " U5       S35      5      nUR                  [        U[         R                  R                  SS95        [        5       n/ nU HK  n[         R                  R                  U5      n	X;  d  M)  UR                  U	5        UR                  U	5        MM     U$ )zHReturn possible generated sidecar paths for a repaint source audio path.r   z.jsongradio_outputszbatch_*T)keyreverse)ospath
expandusersplitextbasenamejoingetcwdglobescapeextendsortedgetmtimesetabspathaddappend)
r3   expanded_audio
candidatesr   results_rootsidecarsseenunique_candidates	candidate
normalizeds
             r!   _candidate_repaint_sidecarsr   {  s$   WW''	2N''"">215?@Jww 0 0 @A!DHww||BIIK1AB99GGLLyT[[5J4K52QR
 	&rww/?/?NO5D	WW__Y/
!HHZ $$Z0	  
 r$   valuec                 2   U c  g[        U [        5      (       a  U (       a  U S   OSn U c  g [        U 5      R                  S5      S   R	                  5       nU(       d  g[        [        U5      5      nUS:  a  U$ S$ ! [        [        [        4 a     gf = f)z9Convert a sidecar seed value to an integer when possible.Nr   ,)

isinstancer   r   splitstripr   r   r   r   OverflowError)r   textrJ   s      r!   _coerce_seed_valuer     s    }%!at}5z$Q'--/5; 194&$& z=1 s   2A>  A> >BBr   r   c                    Uc  U $ [        U 5      n[        U5       Hb  u  p4XA:w  a  M  [        R                  " SS5      nXQ:X  a  [        R                  " SS5      nXQ:X  a  M  [        R
                  " SUU5        XRU'   Md     U$ )zAReturn seeds that do not reuse the cached source generation seed.r   l    zN[repaint_cache] Replacing repaint seed {} with {} to avoid reusing source seed)r   	enumeraterandomrandintr   info)r   r   resolvedindexrJ   replacements         r!   _resample_matching_source_seedsr    s    
 E{H *nnQ	2( ..I6K (\	

 & + Or$   c                 `   U (       d  g [         R                  " U 5      n[        U5      n[	        S U 5       S5      nUc  [
        R                  " SUU5        g [        USS9 n[        R                  " U5      nSSS5        [        W[        5      (       d  g[        UR                  S5      =(       d    S5      R!                  5       nU(       d  gUn[         R"                  R%                  U5      (       d=  [         R"                  R'                  [         R"                  R)                  U5      U5      n[         R"                  R+                  U5      n[         R"                  R-                  U5      (       d  [
        R.                  " SU5        g [0        R                  " U5      R3                  [0        R4                  5      nUR8                  S
:w  a  [
        R.                  " S5        g[
        R                  " SU5        [;        [<        R>                  " U5      [A        UR                  S5      5      US9$ ! [         a     gf = f! , (       d  f       GN= f! [        [        R                  4 a     gf = f! [        [6        4 a!  n	[
        R.                  " S	U	5         Sn	A	gSn	A	ff = f)zLoad cached repaint source state from a generated audio sidecar.

The cache is an optimization for ACE-generated Gradio outputs. Missing or
malformed sidecars return ``None`` so uploaded audio keeps the normal
repaint path.
Nc              3   r   #    U  H-  n[         R                  R                  U5      (       d  M)  Uv   M/     g 7fr   )r   r   exists).0r   s     r!   	<genexpr>._load_cached_repaint_source.<locals>.<genexpr>  s!     Hxt277>>$3Gddxs   (7	7zM[repaint_cache] No cached source latents found for src_audio={} candidates={}zutf-8)encodingrepaint_source_latents_filer4   z2[repaint_cache] Cached repaint latents missing: {}z9[repaint_cache] Could not load cached repaint latents: {}r   z<[repaint_cache] Cached repaint latents must be shaped [T, C]z<[repaint_cache] Loaded cached repaint source latents from {}rJ   )r   r   r   )!r   fspathr   r   nextr   r  openjsonloadOSErrorJSONDecodeErrorr   r   r   r   r   r   isabsr   dirnamer   r
  r*   npastypefloat32r   ndimr   r   
from_numpyr   )
r3   
audio_pathr   	json_pathfile_objparamslatent_filer   r   excs
             r!   _load_cached_repaint_sourcer$    s    YYy)
 +:6HHxH$OI[	

 )g.(YYx(F / fd##fjj!>?E2FLLNKK77==%%ggll277??9#={K''$$[1K77>>+&&K[Y''+&--bjj9 ||qUV
KKNP[\  )&vzz&'9: K   /.T))*   Z  RTWXsY   H: 
I %I
<I 3I< :
II

II I I98I9<J-J((J-c                 :    [        U 5      nUb  UR                  $ S$ )zBLoad cached repaint source latents from a generated audio sidecar.N)r$  r   )r3   cached_sources     r!   #_load_cached_repaint_source_latentsr'    s"    /	:M$1$==  G4Gr$   r   r!  configsave_dirc                 (    UR                   S:X  a  UR                  (       a  SnOUR                  nSn/ nSSSS.n	UR                  n
UR                  nUR
                  nUR                  nUR                  nUR                  nUR                  nUR                   S:X  a  [        UR                  5      OSnUb  UR                  OSn[        UR                  =(       a#    [        UR                  5      R                  5       5      nU(       + nUR                   b  UR                   OSnSnUR"                  b  [%        UR"                  [&        5      (       a<  [)        UR"                  5      S:  a#  S	R+                  S
 UR"                   5       5      nO4[%        UR"                  [,        5      (       a  [        UR"                  5      nU R/                  UUUR0                  5      u  nnUR0                  nUb0  [3        UUR4                  5      nS	R+                  S U 5       5      nSn1 SknUR                   S:H  =(       a    UR                  nUR6                  =(       d    UR8                  =(       d    UR:                  nUR                   U;   =(       d    UnUR<                  =(       d    U=(       a%    USL=(       a    UR>                  =(       a    U(       + n/ nU(       aE  UR                   U;   a  UR                   OUR                    S3n [@        RB                  " SU  S35        [@        RB                  " SUR<                   SUR6                   SUR8                   SUR:                   SU SU(       a  UR>                  OS SU 35        U(       Ga  URD                  (       a  URD                  S:X  a  SO[-        URD                  5      n!URF                  (       a  URF                  S:  a  SOURF                  n"0 n#U
b    [I        U
5      n$U$S:  a  [-        U$5      U#S'   U(       a>  UR                  5       (       a)  UR                  5       n%U%RO                  5       S;  a  U%U#S'   U(       a>  UR                  5       (       a)  UR                  5       n&U&RO                  5       S;  a  U&U#S'   Ub    [I        U5      n'U'S:  a  [-        U'5      U#S'   U#(       a  U#OSn(U(       a  UR<                  (       a  SOSn)URP                  S:  a  [-        URP                  5      OUn*[R        RT                  " UU*-  5      n+/ n,/ n-[W        U+5       GHy  n.U.U*-  n/[Y        U/U*-   U5      n0U0U/-
  n1U/[)        U5      :  a  UU/U0 OSn2[@        RB                  " S U.S-    S!U+ S"U) S#U1 S$U2 S%35        UR[                  UR                  =(       d    SUR                  =(       d    SU)UR\                  UR^                  UR`                  U!U"UU(UR6                  UR8                  UR:                  URb                  URd                  U1U2US&9n3U3Rg                  S'S5      (       d8  U3Rg                  S(S)5      n4URi                  S*U4 35        [k        / S+U4 30 SU4S,9s  $ U1S:  aG  U3Rg                  S-/ 5      n5U3Rg                  S./ 5      n6U,Rm                  U55        U-Rm                  U65        OFU3Rg                  S-0 5      n7U3Rg                  S.S5      n8U,Ri                  U75        U-Ri                  U85        U3Rg                  S/0 5      n9U9Rg                  S00 5      n:U:(       d  GM  S H  n;U;U:;   d  M  U	U;==   U:U;   -  ss'   M     S1R+                  U:Ro                  5        V<V=s/ s H  u  n<n=U< S2U=S3 S43PM     sn=n<5      n>URi                  S5U.S-    S2U> 35        GM|     U,(       a  U,S   OSnU-nU)S:X  a  US:  a  U-nOU-(       a  U-S   OSnOUR                  nU(       Ga  [q        UU
UUUUUUS69u  ppn?n@nAUR                  (       a  UR                  S::  a  U
(       a  [-        U
5      S:  a  Xl9        UR                  (       d  Xl:        UR
                  (       d  Xl;        UR                  (       a  UR                  S::  a  U(       a  [I        U5      S:  a  Xl<        UR                  (       d  U?Ul=        UR                  (       d  W@Ul>        UR                  (       d  WAUl?        UR6                  (       a  URg                  S7U5      nUR8                  (       a  URg                  S8U5      nUR                   S9;   a  UR                  =(       d    UnUR                  b  UR                  OUn[@        RB                  " S:UR                    S;UR                   S<UR                   S=35        [@        RB                  " S>U S?U S=35        UR                   S@;   a  Sn0 SAU_SBUR                  _SCU_SU
_SDU_SEU_S8U_SFUR                  _SGUR                  _SHU_SIU_SJUR                  _SKU_SLUR                   b  UR                   OS_SMUR                   S:w  d  UR                  (       a  UR                  OS_SNU_SOUR                  _0 SPUR                  _SQUR                  _SRUR                  _SSUR                  _STUR                  _SUUR                  _SVU_SWUR                  _SXUR                  _SYUR                  _SZUR                  _S[UR                  _S\UR                  _S]UR                  _S^UR                  _S_UR                  _S`UR                  _E0 SaUR                  _SbUR                   _ScUR                  _SdUR                  _SeUR                  _SfUR                  _SgUR                  _ShUR                  _SiUR                  _SjUR                  _SkUR                  _SlUR                  _SmUR                  _SnUR                  _SoUR                  _SpUR                  _SqUR                  _EUR                  USr.EnB[        [        R                  " U R                  5      R                  R                  5       5      nCUBRo                  5        V;VDs0 s H  u  n;nDU;WC;   d  M  U;WD_M     nEn;nD[        [        WBR                  5       5      WC-
  5      nFUF(       a  [@        R                  " SsWF 35        U R                  " S0 WED6n3U3Rg                  S'S5      (       d,  [k        / U3Rg                  StS5      0 SU3Rg                  S(5      S,9$ U3Rg                  Su/ 5      nGU3Rg                  StS5      nHU3Rg                  S/0 5      nIUnJUR                  5       nKUR                  (       a1  [        UR                  5      R                  5       RO                  5       OSvnL[        ULSw9nMUb  [        R                  " USxSy9  WI=(       d    0 Rg                  SzS5      =(       d    SnNUN(       aG  WNR                  S	5       VOs/ s H*  nOUOR                  5       (       d  M  WOR                  5       PM,     snOO/ nP/ nQ[        WG5       GH  u  nRnSWKR                  5       nTUR[)        WJ5      :  a  WJWR   OSWTSI'   WP(       a  WR[)        WP5      :  a  WPWR   OWPS   WTSW'   U(       a>  WR[)        U5      :  a/  UWR   nUUU(       a#  [        WU5      R                  5       (       a  WUWTS.'   U R                  WTS{'   U R                  UTS|'   U R                  UTS}'   [        U 5      UTS~'   WLUTS'   ULS:X  a   [        USS5      WTS'   [        USS5      UTS'   WSRg                  S5      nVUSRg                  SS5      nWUR                  (       a  UR                  S::  a   [        R                  " [        R                  " WV5      5      R                  5       nX[@        RB                  " SWR SUXS SUR                   S35        G[        UVUR                  5      nV[        R                  " [        R                  " UV5      5      R                  5       nY[@        RB                  " SUR SUYS 35        UGR                  S:  d  UGR                  S:  a   G[        UGR                  WW-  5      n[G[        UGR                  UW-  5      n\G[        WVU[U\5      nV[@        RB                  " SWR SUGR                  S3 SU[ SUGR                  S3 SU\ S35        WR[)        WJ5      :  a  WJWR   OWJ(       a  WJS   OSn]U(       a  WR[)        U5      :  a  UWR   OUn^[%        U^[&        5      (       a  WR[)        W^5      :  a  W^WR   OSn^G[        WT5      n_Sn`WVb`  Ub]   WLS:X  a  SOWLna[        GR                  R+                  UW_ SUa 35      nbWMGR                  WVUbWWWLSx[        USS5      [        USS5      S9n`W`=(       d    SWVW_WWWTS.ncWQRi                  Uc5        GM     WIR                  5       ndUUdS'   0 neU(       a)  U	(       a"  U	Ro                  5        H  u  n;nDUDWeSU; 3'   M     WIRg                  S00 5      nfUf(       a"  WfRo                  5        H  u  n;nDUDWeSU; 3'   M     We(       a,  WeRg                  SS5      ngUeRg                  SS5      nhUgUh-   UeS'   WeWdS0'   U(       a  SR+                  U5      S-   WH-   nH[k        WQWHWdSxSS,9$ ! [J        [L        4 a     GN2f = f! [J        [L        4 a     GNf = fs  sn=n<f s  snDn;f s  snOf ! G[         a%  nZ[@        GR                  " SUZ 35         SnZAZGNSnZAZff = f! G[         a%  nZ[@        GR                  " SUZ 35         SnZAZGNSnZAZff = f! G[         a'  nZ[@        GR                  " SUZ 35        Sn` SnZAZGNSnZAZff = f! G[         aC  nZ[@        GR                  " S5        [k        / S[        UZ5       30 S[        UZ5      S,9s SnZAZ$ SnZAZff = f)a  Generate music using ACE-Step model with optional LM reasoning.

Args:
    dit_handler: Initialized DiT model handler (AceStepHandler instance)
    llm_handler: Initialized LLM handler (LLMHandler instance)
    params: Generation parameters (GenerationParams instance)
    config: Generation configuration (GenerationConfig instance)
    
Returns:
    GenerationResult with generated audio files and metadata
r/   r4   NrA   )phase1_timephase2_time
total_timerepaintro   r   r   c              3   8   #    U  H  n[        U5      v   M     g 7fr   r   )r  ss     r!   r  !generate_music.<locals>.<genexpr>M  s     .L|!s1vv|   c              3   8   #    U  H  n[        U5      v   M     g 7fr   r0  )r  rJ   s     r!   r  r2  \  s     *RAQ3t99AQr3  F>   coverextractr.  cover-nofsqz+flow_edit_morphzSkipping LM for task_type='z' - using DiT directlyz.[generate_music] LLM usage decision: thinking=z, use_cot_caption=z, use_cot_language=z, use_cot_metas=z, need_lm_for_cot=z, llm_initialized=z	, use_lm=rE   r<   )zn/ar4   r=   r>   r   llm_ditditz	LM chunk /z (infer_type=z	) (size: z	, seeds: ))r6   r8   
infer_typetemperature	cfg_scalenegative_prompttop_ktop_ptarget_durationuser_metadatar|   r~   r{   r   r   r   r   progressr   r   zUnknown LM erroru   ❌ LM Error: u   ❌ LM generation failed: )r   r   r   r   r   r   r5   r   
time_costsz, z: z.2fr1  u   ✅ LM chunk )r   r<   r   r   r   r;   r6   r8   r6   r;   )r.  r5  r7  r6  z[generate_music] z task: using params.caption='z', params.lyrics=''z2[generate_music] Final inputs: dit_input_caption='z', dit_input_lyrics=')r5  r7  r.  legor6  captionsr7   r8   r   r   rH   rK   r   rJ   r2   r   r   r3   audio_code_stringr^   r_   ra   rc   rd   rf   rg   source_repaint_latentsrh   ri   rj   rk   rl   rm   rn   rp   r1   rq   rr   r0   rL   rM   rN   rO   rQ   rS   rT   rU   rV   rX   rY   rZ   r\   r]   rD   )rF   rD  z=[generate_music] Skipping unsupported generate_music kwargs: r   r   r   )default_formatT)exist_okretake_seed_valuelora_loadeduse_lora
lora_scalelora_weights_hashr   mp3r   r   r   r   tensorsample_ratez[Normalization] Audio z BEFORE: Peak=z.4fz	, Target=dBz AFTER: Peak=zNormalization failed: z[Fade] Audio z
: fade_in=zs (z samples), fade_out=z	 samples)zFade application failed: rI   wav32wav.)rT  formatchannels_firstr   r   z,[generate_music] Failed to save audio file: )r   rS  r   rT  r!  lm_metadatalm_dit_lm_total_timedit_total_time_costpipeline_total_time
zMusic generation failedError: r   )r0   rj   r5   r<   r=   r>   r   r6   r;   r8   r$  r3   r   r   r   r   r   r   r   r   lenr   r   prepare_seedsr   r  r   r|   r~   r{   rs   llm_initializedr   r  rw   rx   r   r   r   lowerr   mathceilrangemingenerate_with_stop_conditionru   rv   rz   r   r   r   r   r   r   itemsr   r   r   r   r   r   r   r   r7   rH   rK   r2   r^   r_   ra   rc   rd   rf   rg   rh   ri   rk   rl   rm   rn   rp   r1   rq   rr   rL   rM   rN   rO   rQ   rS   rT   rU   rV   rX   rY   rZ   r\   r]   rD   rF   r   inspect	signaturegenerate_music
parameterskeysr   r*   r   r   r   r   makedirsr   r   copyrN  rO  rP  r   getattrr?   r@   r   maxabsitemr   	Exceptionr   rB   rC   roundr   r   r   
save_audio	exception)idit_handlerllm_handlerr!  r(  r)  rD  audio_code_string_to_uselm_generated_metadatalm_generated_audio_codes_listlm_total_time_costsr<   r   r   r   dit_input_captiondit_input_vocal_languagedit_input_lyricscached_repaint_sourcerJ  user_provided_audio_codesneed_audio_codesactual_batch_sizeseed_for_generationactual_seed_list_use_random_seed_for_ditskip_lm_tasksmorph_on_text2musicneed_lm_for_cotskip_lmuse_lm	lm_statusreasontop_k_valuetop_p_valuerC  r   key_scale_cleantime_sig_cleanduration_valueuser_metadata_to_passr<  max_inference_batch_size
num_chunksall_metadata_listall_audio_codes_list	chunk_idxchunk_start	chunk_end
chunk_sizechunk_seedsresult	error_msgmetadata_listaudio_codes_listr   r5   lm_extralm_chunk_time_costsr   kvtime_strr;   r6   r8   dit_generate_kwargssupported_generate_keysr   filtered_generate_kwargsdropped_generate_keys
dit_audiosr   dit_extra_outputs	seed_listbase_params_dictr   audio_saverretake_seed_value_strr1  retake_seeds_resolvedr   idx	dit_audioaudio_paramslm_codeaudio_tensorrT  peak_before
peak_afterefade_in_samplesfade_out_samples
batch_seedaudio_code_str	audio_keyr  file_ext
audio_file
audio_dictr   unified_time_costsdit_time_costslm_total	dit_totalsi                                                                                                            r!   ro  ro    s   (|
 |+0F0F')$'-'9'9$ $(*%
 jjOO	--"NN#)#8#8 !== 9, ((8(89 	 .C-N!))TX 	 %)););)_FDVDV@W@]@]@_$`!  98 281B1B1NF--TU
 ! <<#&,,--#fll2Ca2G&)hh.Lv||.L&L#FLL#.. '*&,,&7# *778IK^`f`v`vw!"("8"8 ,> %11  #&((*RAQ*R"R&+# G ,G1G1G 	 !00cF4K4KcvOcOc""m3J7J//4_  B+T:Q  BVaVqVq  B  {B  wB	)/)9)9])JV%%SYScScRddtPuFKK5fX=STUDV__DU V&&,&<&<%==PQWQhQhPi j$$*$8$8#99KOK\ ]&EPk&A&AV[%\\eflemo 	p
 &,ooA9M$SVW]WfWfSgK&,ooC9O$U[UdUdK M %c
I 1}/29~e, Y__.."+//"3"((*+=0?M*-."6"6"8"8!/!5!5!7!'')<5CM/2)%*>%:N%)474Gj1 6CM!
 '76??PUJ KQJdJdghJhs6+E+E'Fn$#47O#OPJ "#% ":.	'*BB.F FHYZ	&4
ITWZ[kWlIl.{9Ervi	!}Aj\zl [&&0\;-qJ K %AA"NN0b!==.B) & 5 5$11$*$=$=%%$2"7$*$:$:%+%<%<"("6"6-3-L-L/5/P/P)%%% B , zz)U33 &

74F GI$$~i[%AB+!)CI;'O&( %'  >$*JJz2$>M'-zz-'D$%,,];(//0@A%zz*b9H"(**]B"?K%,,X6(//< "::or:&.ll<&D#&&K"55/48KC8PP4  L  $yyGZG`G`Gb)cGbtq!QCr!C*:Gb)cdH$$}Yq[MH:%NOI /L =N$5a$8SW!,@) Y&$q(/C,J^/CA/Fdf, ,2+=+=( %bz2'#1#1#;-+c-_PWY_ 

fjjAo33s8a<%(N*3'++/=,6??a+?^X]^lXmpqXq*8',,0>F-~~)0F&}}(.F% %%$9$=$=iIZ$[!&&+@+D+DEUWo+p( MM & C2C060Iv}}O_KK+F,<,<+==Z[a[i[iZjj|  ~D  ~K  ~K  }L  LM  N  OKKLM^L__t  vF  uG  GH  I  J
 UU!N=
)=
f33=
 &=
 3	=

 =
 n=
 6=
 v55=
 f33=
 6=
 '=
 v55=
 n=
 v/@/@/L&++RS=
$ ##|3v7M7M   +=
.  !9/=
0  7 71=
2 f333=
4 v555=
6 .v/U/U7=
8 ()I)I9=
: F//;=
<  7 7==
> %&<?=
@ 6--A=
B v55C=
D v55E=
F '(G(GG=
H &v'E'EI=
J v55K=
L v55M=
N v55O=
P 6--Q=
R #F$?$?S=
T #F$?$?U=
V ))W=
X v~~Y=
Z !&";";[=
\  7 7]=
^ V\\_=
` F//a=
b F//c=
d &v'E'Ee=
f "6#=#=g=
h 6--i=
j k=
l &++m=
n v55o=
p 6--q=
r ))s=
t F//u=
v %33 y=
| #&g&7&78R8R&S&^&^&c&c&e"f)<)B)B)D$
)D:3OfHfJCJ)D 	! $
 !'s+>+C+C+E'FI`'` a NNOPeOfg ++G.FG zz)U++#%zz*:B? jj)  ZZ"-
$4b9"JJ; %	 ">>+ DJCVCVs6../557==?\b = KK40 "3!8b = =>QSU V \Z\ % !6 ; ;C @N @1AGGIYQWWY @N 	 '
3NC+002L 693y>5I9S>tL $ S!677 *#..q1 ]+ -s;X7Y1Y7<s7|113329L/ +6*A*AL''2';';L$)4)?)?L&0Ek0RL,-+7L(u$.5fmV.T]+29&BSUZ2[./ %==2L#--u=K **v/F/F#/M@#(99UYY|-D#E#J#J#L[[[#9#n[Y\L]]fgmg~g~f  @B  "C  D$3L&BYBY$Z\"'))EIIl,C"D"I"I"KZ[[#9#mJWZK[!\] &&,0H0H30N
B&+F,C,Ck,Q&RO',V-E-E-S'T$#-lOM]#^LKK'uJv7N7Ns6S T+,,@AYAYZ]@^ _,-Y8 ,/Y+?3U^Yq\dfJ .#<Y8Z2Z ;3?ay .$//8;c.>Q8Q!4WY1,?I J'H,@$(4(?u\H!#h9+Qxj8Q!RJ!,!7!78BDO?KGKDKFTaciDjHOPVXikpHq "8 "sJ #(b& *&J MM*%O 4T *..0'<m$   )1779
U27"S;/ : +..|R@,224
U38"T#<0 5 )--osCH*../DcJI8@98L45 '9l#!YYy1D8>IN)'
 	
I #I. $ #I. h *d~$
` On " @\\$:1#">??@ ! BLL#<QC!@AAB: ! $LL#OPQs!ST!#J$h  
23$SVH-a&
 	

s  O=AP  AL> BAP -AM F6AP B<AP 	AP 2AP AM,T&AP ?AM2AM2BAP 4C+AP AM8<AM8EAP %CAM=B4"AP CB AN0EA>AP GAAO#H2DAP L>AMMAP MAMMAP MAM)M%AP M(AM)M)AP M=AN-NAN(N"AP N(AN-N-AP N0AO N;AOOAP OAO O AP O#APO.APP
AP PAPPAP PAQ&P#8AQ!QAQ&Q!AQ&r5   r=  r@  rA  repetition_penaltyr   r   c                    U R                   (       d  [        SSSS9$ U(       a  UR                  5       (       d  Sn U R                  UUUUUUUS9u  pU(       d  [        U	=(       d    SSU	=(       d    SS9$ UR	                  S	S
5      n
UR	                  SS
5      nUR	                  SS
5      nUR	                  SUR	                  SS
5      5      nUR	                  SS
5      nSnUR	                  S5      nUb  US:w  a  US
:w  a   [        U5      nSnUR	                  S5      nUb  US:w  a  US
:w  a   [        U5      nUS:X  a  S
nUS:X  a  S
nUS:X  a  S
n[        U
UUUUUUU	SSS9
$ ! [        [        4 a     Njf = f! [        [        4 a     NRf = f! [         a@  n[        R                  " S5        [        S[        U5       3S[        U5      S9s SnA$ SnAff = f)a  Understand music from audio codes using the 5Hz Language Model.

This function analyzes audio semantic codes and generates metadata about the music,
including caption, lyrics, BPM, duration, key scale, language, and time signature.

If audio_codes is empty or "NO USER INPUT", the LM will generate a sample example
instead of analyzing existing codes.

Note: cfg_scale and negative_prompt are not supported in understand mode.

Args:
    llm_handler: Initialized LLM handler (LLMHandler instance)
    audio_codes: String of audio code tokens (e.g., "<|audio_code_123|><|audio_code_456|>...")
                 Use empty string or "NO USER INPUT" to generate a sample example.
    temperature: Sampling temperature for generation (0.0-2.0). Higher = more creative.
    top_k: Top-K sampling (None or 0 = disabled)
    top_p: Top-P (nucleus) sampling (None or 1.0 = disabled)
    repetition_penalty: Repetition penalty (1.0 = no penalty)
    use_constrained_decoding: Whether to use FSM-based constrained decoding for metadata
    constrained_decoding_debug: Whether to enable debug logging for constrained decoding
    
Returns:
    UnderstandResult with parsed metadata fields and status
    
Example:
    >>> result = understand_music(llm_handler, audio_codes="<|audio_code_123|>...")
    >>> if result.success:
    ...     print(f"Caption: {result.caption}")
    ...     print(f"BPM: {result.bpm}")
    ...     print(f"Lyrics: {result.lyrics}")
35Hz LM not initialized. Please initialize it first.FLLM not initializedr   r   r   ry   )r5   r=  r@  rA  r  r   r   z Failed to understand audio codesEmpty metadata returnedr6   r4   r8   r=   r   r;   r>   Nr<   r   r   T
r6   r8   r<   r   r=   r   r>   r   r   r   zMusic understanding failedrb  )re  r   r   understand_audio_from_codesr   r   r   r   r   rx  r   r{  r   )r}  r5   r=  r@  rA  r  r   r   r   statusr6   r8   r=   r   r>   r<   r   r   r  r  s                       r!   understand_musicr  I  s.   T &&P'
 	
 k//11%H
&BB##1%='A C 
 #%K)K9 9  ,,y"-h+<<
B/<<
HLL9I2,NO _b9 LL'	 Y%%7IO)n
 !j1%.E*AnXZFZ 0
 uHuHE!M'!
 	
) 	*  	* 0  
56$SVH-a&
 	

sl   :F 7BF E' "F 2E= =)F 'E:7F 9E::F =FF FF 
G5GGGc                       \ rS rSr% SrSr\\S'   Sr\\S'   Sr	\
\   \S'   Sr\
\   \S'   Sr\\S	'   Sr\\S
'   Sr\\S'   Sr\\S'   Sr\\S'   Sr\\S'   Sr\
\   \S'   S\\\4   4S jrSrg)CreateSampleResulti  a  Result of creating a music sample from a natural language query.

This is used by the "Simple Mode" / "Inspiration Mode" feature where users
provide a natural language description and the LLM generates a complete
sample with caption, lyrics, and metadata.

Attributes:
    # Metadata Fields
    caption: Generated detailed music description/caption
    lyrics: Generated lyrics (or "[Instrumental]" for instrumental music)
    bpm: Beats per minute (None if not generated)
    duration: Duration in seconds (None if not generated)
    keyscale: Musical key (e.g., "C Major")
    language: Vocal language code (e.g., "en", "zh")
    timesignature: Time signature (e.g., "4")
    instrumental: Whether this is an instrumental piece
    
    # Status
    status_message: Status message from sample creation
    success: Whether sample creation completed successfully
    error: Error message if sample creation failed
r4   r6   r8   Nr<   r   r=   r   r>   Fr9   r   Tr   r   r   c                     [        U 5      $ r   r   r   s    r!   r   CreateSampleResult.to_dict  r   r$   r   )r   r   r   r   r   r6   r   r   r8   r<   r   r   r   r   r=   r   r>   r9   r   r   r   r   r   r   r   r   r   r$   r!   r  r    s    . GSFCC# $Hhuo$HcHcM3L$ NCGTE8C=c3h r$   r  queryr9   c
                    U R                   (       d  [        SSSS9$  U R                  UUUUUUUUU	S9	u  pU
(       d  [        U=(       d    SSU=(       d    SS9$ U
R                  SS	5      nU
R                  S
S	5      nU
R                  SS	5      nU
R                  SU
R                  SS	5      5      nU
R                  SS	5      nU
R                  SU5      nSnU
R                  S5      nUb  US:w  a  US	:w  a   [	        U5      nSnU
R                  S5      nUb  US:w  a  US	:w  a   [        U5      nUS:X  a  S	nUS:X  a  S	nUS:X  a  S	n[        UUUUUUUUUSSS9$ ! [
        [        4 a     Nkf = f! [
        [        4 a     NSf = f! [         a@  n[        R                  " S5        [        S[        U5       3S[        U5      S9s SnA$ SnAff = f)a  Create a music sample from a natural language query using the 5Hz Language Model.

This is the "Simple Mode" / "Inspiration Mode" feature that takes a user's natural
language description of music and generates a complete sample including:
- Detailed caption/description
- Lyrics (unless instrumental)
- Metadata (BPM, duration, key, language, time signature)

Note: cfg_scale and negative_prompt are not supported in create_sample mode.

Args:
    llm_handler: Initialized LLM handler (LLMHandler instance)
    query: User's natural language music description (e.g., "a soft Bengali love song")
    instrumental: Whether to generate instrumental music (no vocals)
    vocal_language: Allowed vocal language for constrained decoding (e.g., "en", "zh").
                   If provided, the model will be constrained to generate lyrics in this language.
                   If None or "unknown", no language constraint is applied.
    temperature: Sampling temperature for generation (0.0-2.0). Higher = more creative.
    top_k: Top-K sampling (None or 0 = disabled)
    top_p: Top-P (nucleus) sampling (None or 1.0 = disabled)
    repetition_penalty: Repetition penalty (1.0 = no penalty)
    use_constrained_decoding: Whether to use FSM-based constrained decoding
    constrained_decoding_debug: Whether to enable debug logging
    
Returns:
    CreateSampleResult with generated sample fields and status
    
Example:
    >>> result = create_sample(llm_handler, "a soft Bengali love song for a quiet evening", vocal_language="bn")
    >>> if result.success:
    ...     print(f"Caption: {result.caption}")
    ...     print(f"Lyrics: {result.lyrics}")
    ...     print(f"BPM: {result.bpm}")
r  Fr  r  )	r  r9   r;   r=  r@  rA  r  r   r   zFailed to create sampler  r6   r4   r8   r=   r   r;   r>   r9   Nr<   r   r   T)r6   r8   r<   r   r=   r   r>   r9   r   r   r   zSample creation failedrb  )re  r  create_sample_from_queryr   r   r   r   r   rx  r   r{  r   )r}  r  r9   r;   r=  r@  rA  r  r   r   r   r  r6   r8   r=   r   r>   is_instrumentalr<   r   r   r  r  s                          r!   create_sampler    s/   ^ &&!P'
 	
L
&??%)#1%='A @ 

 %%B)B9 9  ,,y"-h+<<
B/<<
HLL9I2,NO _b9",,~|D LL'	 Y%%7IO)n
 !j1%.E*AnXZFZ 0
 uHuHE!M!'(!
 	
) 	*  	* 2  
12!$SVH-a&
 	

sl   <F
 BF
 :E "F
 (E4 3*F
 E1.F
 0E11F
 4FF
 FF
 

G5G	GGc                       \ rS rSr% SrSr\\S'   Sr\\S'   Sr	\
\   \S'   Sr\
\   \S'   Sr\\S	'   Sr\\S
'   Sr\\S'   Sr\\S'   Sr\\S'   Sr\
\   \S'   S\\\4   4S jrSrg)FormatSampleResultiz  a  Result of formatting user-provided caption and lyrics.

This is used by the "Format" feature where users provide caption and lyrics,
and the LLM formats them into structured music metadata and an enhanced description.

Attributes:
    # Metadata Fields
    caption: Enhanced/formatted music description/caption
    lyrics: Formatted lyrics (may be same as input or reformatted)
    bpm: Beats per minute (None if not detected)
    duration: Duration in seconds (None if not detected)
    keyscale: Musical key (e.g., "C Major")
    language: Vocal language code (e.g., "en", "zh")
    timesignature: Time signature (e.g., "4")
    
    # Status
    status_message: Status message from formatting
    success: Whether formatting completed successfully
    error: Error message if formatting failed
r4   r6   r8   Nr<   r   r=   r   r>   r   Tr   r   r   c                     [        U 5      $ r   r   r   s    r!   r   FormatSampleResult.to_dict  r   r$   r   r   r   r$   r!   r  r  z  s    * GSFCC# $Hhuo$HcHcM3 NCGTE8C=c3h r$   r  rC  c
                    U R                   (       d  [        SSSS9$  U R                  UUUUUUUUU	S9	u  pU
(       d  [        U=(       d    SSU=(       d    SS9$ U
R                  SS	5      nU
R                  S
U5      nU
R                  SS	5      nU
R                  SU
R                  SS	5      5      nU
R                  SS	5      nSnU
R                  S5      nUb  US:w  a  US	:w  a   [	        U5      nSnU
R                  S5      nUb  US:w  a  US	:w  a   [        U5      nUS:X  a  S	nUS:X  a  S	nUS:X  a  S	n[        UUUUUUUUSSS9
$ ! [
        [        4 a     Njf = f! [
        [        4 a     NRf = f! [         a@  n[        R                  " S5        [        S[        U5       3S[        U5      S9s SnA$ SnAff = f)a8  Format user-provided caption and lyrics using the 5Hz Language Model.

This function takes user input (caption and lyrics) and generates structured
music metadata including an enhanced caption, BPM, duration, key, language,
and time signature.

If user_metadata is provided, those values will be used to constrain the
decoding, ensuring the output matches user-specified values.

Note: cfg_scale and negative_prompt are not supported in format mode.

Args:
    llm_handler: Initialized LLM handler (LLMHandler instance)
    caption: User's caption/description (e.g., "Latin pop, reggaeton")
    lyrics: User's lyrics with structure tags
    user_metadata: Optional dict with user-provided metadata to constrain decoding.
                  Supported keys: bpm, duration, keyscale, timesignature, language
    temperature: Sampling temperature for generation (0.0-2.0). Higher = more creative.
    top_k: Top-K sampling (None or 0 = disabled)
    top_p: Top-P (nucleus) sampling (None or 1.0 = disabled)
    repetition_penalty: Repetition penalty (1.0 = no penalty)
    use_constrained_decoding: Whether to use FSM-based constrained decoding for metadata
    constrained_decoding_debug: Whether to enable debug logging for constrained decoding
    
Returns:
    FormatSampleResult with formatted metadata fields and status
    
Example:
    >>> result = format_sample(llm_handler, "Latin pop, reggaeton", "[Verse 1]\nHola mundo...")
    >>> if result.success:
    ...     print(f"Caption: {result.caption}")
    ...     print(f"BPM: {result.bpm}")
    ...     print(f"Lyrics: {result.lyrics}")
r  Fr  r  )	r6   r8   rC  r=  r@  rA  r  r   r   zFailed to format inputr  r6   r4   r8   r=   r   r;   r>   Nr<   r   r   Tr  zFormat sample failedrb  )re  r  format_sample_from_inputr   r   r   r   r   rx  r   r{  r   )r}  r6   r8   rC  r=  r@  rA  r  r   r   r   r  result_captionresult_lyricsr=   r   r>   r<   r   r   r  r  s                         r!   format_sampler    s   ^ &&!P'
 	
J
&??'#1%='A @ 

 %%A)A9 9  "i4 Xv6<<
B/<<
HLL9I2,NO _b9 LL'	 Y%%7IO)n
 !j1%.E*AnXZFZ 0
 uHuHE!M!" '!
 	
) 	*  	* 0  
/0!$SVH-a&
 	

sl   <E7 BE7 (E 3"E7 E! !)E7 EE7 EE7 !E41E7 3E44E7 7
G5F<6G<G)r   )NN)rt   NNrE   TF)FNrt   NNrE   TF)Nrt   NNrE   TF)>r   r   rm  r  rg  r   r  tempfiletypingr   r   r   r   r   r   dataclassesr	   r
   r   logurur   numpyr  r   acestep.audio_utilsr   r   r   r   r   acestep.constantsr   r   r   r   r   environr   r&   r+   r-   r   r   r   r   r   r   r   r   r   r   r  r$  r   r'  ro  r   r  r  r  r  r  r   r$   r!   <module>r     sP       	   : : 0 0    z y _ _ zz~~j1=  q q qh   @ $     4 " " "J,[38n,[	#,[ ,[ 	,[
 UO,[ ,[ ,[ ,[ 8C=#sHUOS#sBC,[^3 49 *'c 'hsm '$9# 
#Y.48C= 4XFY=Z 4nH8C= HXellE[ H C( #O	
 O	
 	O	

 smO	
 O	
 )O	
j ! #%)',}
}
 }
 C=	}

 E?}
 }
 #}
 !%}
 }
@ ( ( (\ $(! #%)',B
B
 B
 SM	B

 B
 C=B
 E?B
 B
 #B
 !%B
 B
J % % %X /3! #%)',@
@
 @
 DcN+	@

 @
 C=@
 E?@
 @
 #@
 !%@
 @
r$   