-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapp.py
More file actions
1318 lines (1161 loc) · 58.6 KB
/
app.py
File metadata and controls
1318 lines (1161 loc) · 58.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import logging
import os
import time
import html as html_mod
import gradio as gr
from config import (
DEFAULT_GENERATION_PARAMS, DEFAULT_OLLAMA_URL, DEFAULT_OLLAMA_MODEL,
DEFAULT_OPENAI_MODEL, DEFAULT_OPENAI_URL, DEFAULT_OPENAI_KEY,
DEFAULT_OPENAI_MODELS, DEFAULT_LLM_BACKEND, DEFAULT_LLM_TEMPERATURE,
DEFAULT_LLM_TIMEOUT, OUTPUT_DIR,
DEFAULT_LAZY_LOAD, DEFAULT_MODEL_VARIANT, MODEL_VARIANT_LABELS,
DEFAULT_NUM_VARIANTS, STYLE_TRANSFER_ENABLED, TRANSCRIPTION_ENABLED,
)
from model_manager import is_ready_for_generation
from lyrics_llm import generate_checked_fields, unload_ollama_model, list_ollama_models
from generator import generate_music, unload_pipeline, cancel_generation, GenerationCancelled, is_generation_cancelled, ensure_pipeline_loaded
from history import generate_output_path, save_generation, load_history, delete_generation, filter_history
logger = logging.getLogger(__name__)
HISTORY_PAGE_SIZE = 10
_SORT_MAP = {"Newest": "newest", "Oldest": "oldest", "Title A-Z": "title_az", "Title Z-A": "title_za"}
_JS_SWITCH_TO_GENERATE = "() => document.querySelector('button[role=\"tab\"]').click()"
# Map display labels to internal variant names
_VARIANT_CHOICES = list(MODEL_VARIANT_LABELS.values())
_VARIANT_LABEL_TO_NAME = {v: k for k, v in MODEL_VARIANT_LABELS.items()}
def _variant_name_from_label(label):
"""Convert dropdown label to internal variant name."""
return _VARIANT_LABEL_TO_NAME.get(label, "hny")
def _variant_label_from_name(name):
"""Convert internal variant name to dropdown label."""
return MODEL_VARIANT_LABELS.get(name, "HeartMuLa 3B HNY (Recommended)")
def on_list_ollama(ollama_url):
models = list_ollama_models(base_url=ollama_url)
if not models:
return gr.update(choices=[], value=None)
return gr.update(choices=models, value=models[0])
def _llm_kwargs(backend, ollama_url, ollama_model, openai_url, openai_model, openai_key, temperature, timeout):
if backend == "Ollama":
return {"base_url": ollama_url, "model": ollama_model, "temperature": temperature, "timeout": timeout}
else:
return {"api_key": openai_key, "base_url": openai_url, "model": openai_model, "temperature": temperature, "timeout": timeout}
def _maybe_unload_ollama(backend, ollama_url, ollama_model, auto_unload):
if auto_unload and backend == "Ollama":
try:
unload_ollama_model(base_url=ollama_url, model=ollama_model)
except Exception as e:
logger.warning("Failed to unload Ollama model: %s", e)
def _btns_disabled():
return gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=True)
def _btns_enabled():
return gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=False)
def _status_html(message, style="info", stats_html=""):
"""Return styled HTML for status messages with optional progress bar and stats."""
message = html_mod.escape(str(message))
colors = {
"info": ("#1a3a5c", "#3b82f6", "#e0f2fe"),
"success": ("#14532d", "#22c55e", "#dcfce7"),
"error": ("#7f1d1d", "#ef4444", "#fee2e2"),
"progress": ("#1a3a5c", "#3b82f6", "#e0f2fe"),
}
bg, border, text_bg = colors.get(style, colors["info"])
progress_bar = ""
if style == "progress":
progress_bar = """
<div style="width:100%;height:4px;background:#1e293b;border-radius:2px;overflow:hidden;margin-top:8px;">
<div style="width:30%;height:100%;background:linear-gradient(90deg,#3b82f6,#60a5fa);border-radius:2px;animation:progress-slide 1.5s ease-in-out infinite;"></div>
</div>
<style>
@keyframes progress-slide {
0% { margin-left: 0%; width: 30%; }
50% { margin-left: 35%; width: 40%; }
100% { margin-left: 70%; width: 30%; }
}
</style>"""
return f"""<div style="padding:12px 16px;border-left:4px solid {border};background:{bg};border-radius:8px;font-size:1.05em;color:#e2e8f0;">
{message}{progress_bar}{stats_html}
</div>"""
def _build_variants_html(variants, autoplay=False):
"""Build HTML for one or more audio variant players.
Args:
variants: list of (abs_path, filename) tuples
autoplay: if True, autoplay the last audio element
"""
if not variants:
return ""
if len(variants) == 1:
path, fname = variants[0]
autoplay_attr = " autoplay" if autoplay else ""
return f'<audio controls{autoplay_attr} src="/gradio_api/file={path}" style="width:100%;margin:10px 0;"></audio>'
parts = []
for idx, (path, fname) in enumerate(variants, 1):
is_last = idx == len(variants)
autoplay_attr = " autoplay" if (autoplay and is_last) else ""
parts.append(
f'<div style="margin:8px 0;">'
f'<span style="color:#a0aec0;font-size:0.9em;font-weight:600;">Variant {idx}</span>'
f'<span style="color:#666;font-size:0.8em;margin-left:8px;">{html_mod.escape(fname)}</span>'
f'<audio controls{autoplay_attr} src="/gradio_api/file={path}" style="width:100%;margin:4px 0;"></audio>'
f'</div>'
)
return f'<div>{"".join(parts)}</div>'
def _get_ram_usage_mb():
"""Return (used_mb, total_mb) for system RAM, or None if unavailable.
Supports Linux (/proc/meminfo) and Windows (kernel32.GlobalMemoryStatusEx).
"""
# Linux
try:
with open("/proc/meminfo") as f:
info = {}
for line in f:
tokens = line.split()
if len(tokens) >= 2 and tokens[0].rstrip(":") in ("MemTotal", "MemAvailable"):
info[tokens[0].rstrip(":")] = int(tokens[1]) # kB
if "MemTotal" in info and "MemAvailable" in info:
total = info["MemTotal"] / 1024
used = (info["MemTotal"] - info["MemAvailable"]) / 1024
return used, total
except (OSError, ValueError):
pass
# Windows
try:
import ctypes
class MEMORYSTATUSEX(ctypes.Structure):
_fields_ = [
("dwLength", ctypes.c_ulong),
("dwMemoryLoad", ctypes.c_ulong),
("ullTotalPhys", ctypes.c_ulonglong),
("ullAvailPhys", ctypes.c_ulonglong),
("ullTotalPageFile", ctypes.c_ulonglong),
("ullAvailPageFile", ctypes.c_ulonglong),
("ullTotalVirtual", ctypes.c_ulonglong),
("ullAvailVirtual", ctypes.c_ulonglong),
("ullAvailExtendedVirtual", ctypes.c_ulonglong),
]
stat = MEMORYSTATUSEX(dwLength=ctypes.sizeof(MEMORYSTATUSEX))
if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)):
total = stat.ullTotalPhys / (1024 ** 2)
used = (stat.ullTotalPhys - stat.ullAvailPhys) / (1024 ** 2)
return used, total
except (OSError, AttributeError):
pass
return None
def _read_memory_stats():
"""Collect current VRAM and RAM usage. Returns dict with available fields."""
stats = {}
try:
import torch
if torch.cuda.is_available():
device = torch.cuda.current_device()
props = torch.cuda.get_device_properties(device)
stats["gpu_name"] = props.name
stats["gpu_total_mb"] = props.total_memory / (1024 ** 2)
stats["gpu_allocated_mb"] = torch.cuda.memory_allocated(device) / (1024 ** 2)
stats["gpu_peak_mb"] = torch.cuda.max_memory_allocated(device) / (1024 ** 2)
except Exception:
pass
ram = _get_ram_usage_mb()
if ram:
stats["ram_used_mb"], stats["ram_total_mb"] = ram
return stats
def _get_gpu_utilization():
"""Return GPU utilization percentage via nvidia-smi, or None."""
try:
import subprocess
result = subprocess.run(
["nvidia-smi", "--query-gpu=utilization.gpu", "--format=csv,noheader,nounits"],
capture_output=True, text=True, timeout=5,
)
if result.returncode == 0:
return int(result.stdout.strip().split("\n")[0])
except (OSError, ValueError, subprocess.TimeoutExpired):
pass
return None
def _get_live_memory_html():
"""Return compact HTML bar showing current GPU, VRAM and RAM usage."""
parts = []
try:
import torch
if torch.cuda.is_available():
free, total = torch.cuda.mem_get_info()
used_mb = (total - free) / (1024 ** 2)
total_mb = total / (1024 ** 2)
pct = used_mb / total_mb * 100 if total_mb else 0
gpu_util = _get_gpu_utilization()
gpu_str = f"GPU: {gpu_util}% | " if gpu_util is not None else ""
parts.append(f"{gpu_str}VRAM: {used_mb:,.0f} / {total_mb:,.0f} MB ({pct:.0f}%)")
except Exception:
pass
ram = _get_ram_usage_mb()
if ram:
used_mb, total_mb = ram
pct = used_mb / total_mb * 100 if total_mb else 0
parts.append(f"RAM: {used_mb:,.0f} / {total_mb:,.0f} MB ({pct:.0f}%)")
if not parts:
return ""
text = html_mod.escape(" | ".join(parts))
return (
f'<div style="padding:6px 12px;background:#0f172a;border:1px solid #1e293b;'
f'border-radius:6px;font-family:monospace;font-size:0.82em;color:#64748b;'
f'text-align:center;">{text}</div>'
)
def _format_stats_html(timings=None, mem_stats=None, extra_info=None):
"""Format generation statistics as a collapsible HTML details block."""
rows = []
if timings:
rows.append("<b>Timing</b>")
for label, seconds in timings:
rows.append(f" {html_mod.escape(label)}: {seconds:.1f}s")
if mem_stats:
rows.append("<b>Memory</b>")
if "gpu_name" in mem_stats:
rows.append(f" GPU: {html_mod.escape(mem_stats['gpu_name'])}")
if "gpu_peak_mb" in mem_stats:
peak = mem_stats["gpu_peak_mb"]
total = mem_stats.get("gpu_total_mb", 0)
rows.append(f" VRAM Peak: {peak:,.0f} / {total:,.0f} MB")
if extra_info:
rows.append("<b>Details</b>")
for label, value in extra_info:
rows.append(f" {html_mod.escape(label)}: {html_mod.escape(str(value))}")
if not rows:
return ""
content = "\n".join(rows)
return (
f'<details style="margin-top:10px;font-size:0.85em;">'
f'<summary style="cursor:pointer;color:#7b8cde;">Generation Statistics</summary>'
f'<pre style="margin-top:6px;padding:8px;background:rgba(0,0,0,0.2);'
f'border-radius:6px;white-space:pre-wrap;color:#a0aec0;">{content}</pre>'
f'</details>'
)
def on_generate_text(description, title, lyrics, tags, edit_instructions,
gen_desc, gen_title, gen_lyrics, gen_tags,
backend, ollama_url, ollama_model,
openai_url, openai_model, openai_key,
llm_temp, llm_timeout, auto_unload, max_length_sec):
"""Generate checked text fields using LLM. Can generate from scratch if nothing is provided."""
if not gen_desc and not gen_title and not gen_lyrics and not gen_tags:
yield description, title, lyrics, tags, _status_html("Nothing selected for generation.", "error"), *_btns_enabled()
return
yield description, title, lyrics, tags, _status_html("Generating text...", "progress"), *_btns_disabled()
try:
kwargs = _llm_kwargs(backend, ollama_url, ollama_model, openai_url, openai_model, openai_key, llm_temp, llm_timeout)
t_start = time.monotonic()
result = generate_checked_fields(
description=description,
title=title,
lyrics=lyrics,
tags=tags,
gen_desc=gen_desc,
gen_title=gen_title,
gen_lyrics=gen_lyrics,
gen_tags=gen_tags,
backend=backend.lower(),
max_length_sec=max_length_sec,
edit_instructions=edit_instructions,
**kwargs,
)
t_text = time.monotonic() - t_start
_maybe_unload_ollama(backend, ollama_url, ollama_model, auto_unload)
# Build status message reporting what actually succeeded vs failed
requested = [f for f, checked in [("description", gen_desc), ("title", gen_title), ("lyrics", gen_lyrics), ("tags", gen_tags)] if checked]
failed = result.get("failed_fields", [])
succeeded = [f for f in requested if f not in failed]
stats = _format_stats_html(
timings=[("Text generation", t_text)],
extra_info=[("Backend", backend), ("Model", ollama_model if backend == "Ollama" else openai_model)],
)
if failed and succeeded:
status = _status_html(f"Generated: {', '.join(succeeded)}. Failed to parse: {', '.join(failed)}", "info", stats_html=stats)
elif failed and not succeeded:
status = _status_html(f"LLM did not return expected format for: {', '.join(failed)}", "error", stats_html=stats)
else:
status = _status_html(f"Generated: {', '.join(succeeded)}", "success", stats_html=stats)
yield result["description"], result["title"], result["lyrics"], result["tags"], status, *_btns_enabled()
except Exception as e:
logger.error("Text generation failed: %s", e)
yield description, title, lyrics, tags, _status_html(f"Error: {e}", "error"), *_btns_enabled()
def on_generate_music_only(song_title, description, lyrics, tags,
temperature, cfg_scale, topk, max_length_sec,
lazy_load, model_variant_label, autoplay, num_variants,
style_audio, style_enabled, style_strength, seed):
"""Generate music only from current fields (no LLM). Supports batch variants."""
if not lyrics.strip():
yield gr.skip(), _status_html("Please enter lyrics.", "error"), *_btns_enabled()
return
if not tags.strip() and not (style_enabled and style_audio):
yield gr.skip(), _status_html("Please enter tags or provide a style reference audio.", "error"), *_btns_enabled()
return
num_variants = int(num_variants)
variant_name = _variant_name_from_label(model_variant_label)
seed_val = None if seed is None or seed < 0 else int(seed)
style_embedding = None
t_total_start = time.monotonic()
t_style = None
t_pipeline = 0
was_cold = False
variant_timings = []
yield gr.skip(), _status_html("Checking models...", "progress"), *_btns_disabled()
try:
from generator import ensure_models_downloaded
from model_manager import is_ready_for_generation
if not is_ready_for_generation(variant_name):
yield gr.skip(), _status_html("Downloading required models (this may take a while)...", "progress"), *_btns_disabled()
ensure_models_downloaded(variant_name)
if not is_ready_for_generation(variant_name):
yield gr.skip(), _status_html("Model download failed. Check your internet connection and disk space.", "error"), *_btns_enabled()
return
# Extract style embedding from reference audio if enabled
if style_enabled and style_audio:
yield gr.skip(), _status_html("Extracting style from reference audio...", "progress"), *_btns_disabled()
try:
from style_transfer import extract_style_embedding
t_style_start = time.monotonic()
style_embedding = extract_style_embedding(style_audio)
t_style = time.monotonic() - t_style_start
if style_strength != 1.0:
style_embedding = style_embedding * style_strength
except Exception as e:
logger.error("Style extraction failed: %s", e)
yield gr.skip(), _status_html(f"Style extraction failed: {e}", "error"), *_btns_enabled()
return
# Pre-load pipeline so we can show distinct status and time it
yield gr.skip(), _status_html("Loading music pipeline...", "progress"), *_btns_disabled()
t_pipeline_start = time.monotonic()
was_cold = ensure_pipeline_loaded(lazy_load=lazy_load, model_variant=variant_name)
t_pipeline = time.monotonic() - t_pipeline_start
title = song_title.strip() or "Untitled"
completed = [] # list of (abs_path, filename) tuples
# Reset peak memory tracking before generation loop
try:
import torch
if torch.cuda.is_available():
torch.cuda.reset_peak_memory_stats()
except Exception:
pass
for i in range(num_variants):
# Check cancellation between variants
if i > 0 and is_generation_cancelled():
yield _build_variants_html(completed, autoplay), \
_status_html(f"Cancelled after {len(completed)} of {num_variants} variants.", "info"), \
*_btns_enabled()
return
if num_variants > 1:
status_msg = f"Generating audio — variant {i + 1} of {num_variants} (this may take a while)..."
else:
status_msg = "Generating audio (this may take a while)..."
audio_update = _build_variants_html(completed, autoplay=False) if completed else gr.skip()
yield audio_update, _status_html(status_msg, "progress"), *_btns_disabled()
output_path = generate_output_path(title)
variant_seed = (seed_val + i) if seed_val is not None else None
t_var_start = time.monotonic()
path, used_seed = generate_music(
lyrics=lyrics,
tags=tags,
temperature=temperature,
cfg_scale=cfg_scale,
topk=topk,
max_audio_length_ms=int(max_length_sec * 1000),
output_path=output_path,
lazy_load=lazy_load,
model_variant=variant_name,
style_embedding=style_embedding,
seed=variant_seed,
)
variant_timings.append(time.monotonic() - t_var_start)
params = {
"temperature": temperature,
"cfg_scale": cfg_scale,
"topk": topk,
"max_length_sec": max_length_sec,
"lazy_load": lazy_load,
"model_variant": variant_name,
"style_reference": bool(style_embedding is not None),
"style_strength": style_strength if style_embedding is not None else None,
"seed": used_seed,
}
if num_variants > 1:
params["batch_total"] = num_variants
params["batch_variant"] = i + 1
save_generation(
song_title=title if num_variants == 1 else f"{title} (Variant {i + 1})",
description=description,
lyrics=lyrics,
tags=tags,
params=params,
audio_path=path,
)
completed.append((path, os.path.basename(path)))
is_last = i == num_variants - 1
if is_last:
t_total = time.monotonic() - t_total_start
# Build stats
timings = []
if was_cold and t_pipeline > 1.0:
timings.append(("Pipeline loading", t_pipeline))
if t_style is not None:
timings.append(("Style extraction", t_style))
for vi, vt in enumerate(variant_timings):
label = f"Audio generation (variant {vi + 1})" if num_variants > 1 else "Audio generation"
timings.append((label, vt))
timings.append(("Total", t_total))
mem_stats = _read_memory_stats()
try:
import torch
device_str = "CUDA" if torch.cuda.is_available() else "CPU"
except Exception:
device_str = "CPU"
extra = [("Model", variant_name), ("Device", device_str), ("Seed", str(used_seed))]
stats = _format_stats_html(timings=timings, mem_stats=mem_stats, extra_info=extra)
if num_variants > 1:
msg = f"All {num_variants} variants generated."
else:
msg = f"Music saved as {os.path.basename(path)}"
yield _build_variants_html(completed, autoplay), \
_status_html(msg, "success", stats_html=stats), *_btns_enabled()
else:
yield _build_variants_html(completed, autoplay=False), \
_status_html(f"Variant {i + 1} of {num_variants} complete.", "info"), \
*_btns_disabled()
except GenerationCancelled:
if completed:
yield _build_variants_html(completed, autoplay), \
_status_html(f"Cancelled after {len(completed)} of {num_variants} variants.", "info"), \
*_btns_enabled()
else:
yield gr.skip(), _status_html("Generation cancelled.", "info"), *_btns_enabled()
except Exception as e:
logger.error("Music generation failed: %s", e)
e.__traceback__ = None # release stack frame refs to GPU tensors
if completed:
yield _build_variants_html(completed, autoplay), \
_status_html(f"Error on variant {len(completed) + 1}: {e}", "error"), \
*_btns_enabled()
else:
yield gr.skip(), _status_html(f"Error: {e}", "error"), *_btns_enabled()
finally:
if style_embedding is not None:
from style_transfer import unload_muq
unload_muq()
def on_unload():
unload_pipeline()
return _status_html("Pipeline unloaded, GPU memory freed.", "success")
def on_clear_all(gen_desc, gen_title, gen_lyrics, gen_tags, desc, title, lyrics, tags):
"""Clear text fields that have their checkboxes checked."""
new_desc = "" if gen_desc else desc
new_title = "" if gen_title else title
new_lyrics = "" if gen_lyrics else lyrics
new_tags = "" if gen_tags else tags
cleared = [name for name, checked in [("description", gen_desc), ("title", gen_title), ("lyrics", gen_lyrics), ("tags", gen_tags)] if checked]
msg = f"Cleared: {', '.join(cleared)}" if cleared else "Nothing selected to clear."
return new_desc, new_title, new_lyrics, new_tags, _status_html(msg, "info")
def on_transcribe(audio_path, auto_unload):
"""Transcribe lyrics from uploaded audio file."""
if not audio_path:
yield "", _status_html("Please upload an audio file.", "error"), gr.update(interactive=True)
return
yield "", _status_html("Checking transcriptor model...", "progress"), gr.update(interactive=False)
from model_manager import is_transcriptor_downloaded, download_transcriptor
if not is_transcriptor_downloaded():
yield "", _status_html("Downloading HeartTranscriptor model (first time only, this may take a while)...", "progress"), gr.update(interactive=False)
download_transcriptor()
if not is_transcriptor_downloaded():
yield "", _status_html("Failed to download transcriptor model. Check internet connection.", "error"), gr.update(interactive=True)
return
yield "", _status_html("Transcribing lyrics (this may take a moment)...", "progress"), gr.update(interactive=False)
try:
from transcriptor import transcribe_audio
text = transcribe_audio(audio_path)
if not text or not text.strip():
yield "", _status_html("Transcription completed but no lyrics were detected.", "info"), gr.update(interactive=True)
else:
yield text, _status_html("Transcription complete.", "success"), gr.update(interactive=True)
except Exception as e:
logger.error("Transcription failed: %s", e)
yield "", _status_html(f"Transcription failed: {e}", "error"), gr.update(interactive=True)
finally:
if auto_unload:
from transcriptor import unload_transcriptor
unload_transcriptor()
def on_unload_transcriptor():
from transcriptor import unload_transcriptor
unload_transcriptor()
return _status_html("HeartTranscriptor unloaded.", "success")
def _build_card_html(e):
"""Build HTML for a single history card (display only, no interactive elements)."""
audio_file = e.get("audio_file", "")
audio_path = os.path.realpath(os.path.join(OUTPUT_DIR, audio_file))
# Prevent path traversal
if not audio_path.startswith(os.path.realpath(OUTPUT_DIR) + os.sep):
audio_path = ""
title = html_mod.escape(e.get("song_title", "Untitled"))
ts = e.get("timestamp", "")[:16].replace("T", " ")
desc = html_mod.escape(e.get("description", ""))
tags = html_mod.escape(e.get("tags", ""))
lyrics = html_mod.escape(e.get("lyrics", ""))
p = e.get("parameters", {})
audio_html = ""
if os.path.isfile(audio_path):
audio_html = f'<audio controls src="/gradio_api/file={audio_path}" style="width:100%;margin:10px 0;"></audio>'
tag_pills = ""
if e.get("tags", ""):
pills = [f'<span style="display:inline-block;background:#2d3748;color:#a0aec0;padding:2px 8px;border-radius:12px;font-size:0.75em;margin:2px;">{html_mod.escape(t.strip())}</span>'
for t in e.get("tags", "").split(",")[:8] if t.strip()]
tag_pills = f'<div style="margin:6px 0;">{" ".join(pills)}</div>'
param_badges = ""
if p:
badges = []
if p.get("style_reference"):
strength = p.get("style_strength", 1.0)
strength_label = f"Style: {strength}x" if strength != 1.0 else "Style Ref"
badges.append(f'<span style="display:inline-block;background:#553c9a;color:#d6bcfa;padding:2px 8px;border-radius:8px;font-size:0.75em;margin:2px;">{strength_label}</span>')
if p.get("seed") is not None:
badges.append(f'<span style="display:inline-block;background:#1a365d;color:#63b3ed;padding:2px 8px;border-radius:8px;font-size:0.75em;margin:2px;">Seed: {p["seed"]}</span>')
for label, key in [("Temp", "temperature"), ("CFG", "cfg_scale"), ("Top-K", "topk"), ("Length", "max_length_sec")]:
val = p.get(key, "?")
suffix = "s" if key == "max_length_sec" else ""
badges.append(f'<span style="display:inline-block;background:#1a365d;color:#63b3ed;padding:2px 8px;border-radius:8px;font-size:0.75em;margin:2px;">{label}: {val}{suffix}</span>')
param_badges = f'<div style="margin:6px 0;">{" ".join(badges)}</div>'
return f"""<div style="border:1px solid #444;border-radius:12px;padding:16px;background:rgba(255,255,255,0.02);">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px;">
<h3 style="margin:0;font-size:1.1em;">{title}</h3>
<span style="color:#888;font-size:0.8em;white-space:nowrap;margin-left:12px;">{ts}</span>
</div>
{f'<p style="color:#aaa;font-size:0.85em;margin:4px 0;">{desc}</p>' if desc else ''}
{tag_pills}
{audio_html}
{param_badges}
<details style="margin-top:10px;">
<summary style="cursor:pointer;color:#7b8cde;font-size:0.85em;">Show full details</summary>
<div style="margin-top:8px;font-size:0.83em;padding:10px;background:rgba(0,0,0,0.15);border-radius:8px;">
<p style="margin:4px 0;"><b>Tags:</b> {tags}</p>
<p style="margin:8px 0 4px;"><b>Lyrics:</b></p>
<pre style="white-space:pre-wrap;max-height:250px;overflow-y:auto;padding:8px;border-radius:6px;background:rgba(0,0,0,0.25);">{lyrics}</pre>
</div>
</details>
</div>"""
def _build_playlist_html(entries):
"""Build HTML-only playlist player. JS is injected via app.launch(js=...)."""
tracks = []
real_output = os.path.realpath(OUTPUT_DIR) + os.sep
for e in entries:
audio_file = e.get("audio_file", "")
audio_path = os.path.realpath(os.path.join(OUTPUT_DIR, audio_file))
if not audio_path.startswith(real_output):
continue
if os.path.isfile(audio_path):
tracks.append({
"title": e.get("song_title", "Untitled"),
"ts": e.get("timestamp", "")[:16].replace("T", " "),
"src": f"/gradio_api/file={audio_path}",
})
if not tracks:
return ""
tracks_attr = html_mod.escape(json.dumps(tracks))
return f'''<div id="hm-playlist-player" data-tracks="{tracks_attr}" style="border:1px solid #444;border-radius:12px;padding:16px;background:#1a1a2e;margin-bottom:16px;">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
<div style="display:flex;align-items:center;gap:8px;min-width:0;flex:1;">
<span style="font-size:1.2em;">♫</span>
<span id="hm-pl-title" style="color:#e2e8f0;font-weight:600;font-size:1.05em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">—</span>
</div>
<span id="hm-pl-ts" style="color:#888;font-size:0.8em;white-space:nowrap;margin-left:12px;"></span>
</div>
<div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;">
<button id="hm-pl-prev" title="Previous" style="background:#2d3748;color:#e2e8f0;border:1px solid #555;border-radius:8px;padding:6px 12px;cursor:pointer;font-size:0.9em;">◀◀</button>
<button id="hm-pl-play" title="Play" style="background:#3b82f6;color:#fff;border:none;border-radius:8px;padding:8px 16px;cursor:pointer;font-size:1.1em;min-width:44px;">▶</button>
<button id="hm-pl-next" title="Next" style="background:#2d3748;color:#e2e8f0;border:1px solid #555;border-radius:8px;padding:6px 12px;cursor:pointer;font-size:0.9em;">▶▶</button>
<span style="flex:1;"></span>
<button id="hm-pl-mode" title="Toggle shuffle" style="background:#2d3748;color:#e2e8f0;border:1px solid #555;border-radius:8px;padding:6px 12px;cursor:pointer;font-size:0.8em;">Sequential</button>
</div>
<div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
<span id="hm-pl-time" style="color:#888;font-size:0.8em;min-width:36px;">0:00</span>
<div id="hm-pl-bar" style="flex:1;height:6px;background:#2d3748;border-radius:3px;cursor:pointer;position:relative;">
<div id="hm-pl-fill" style="height:100%;background:linear-gradient(90deg,#3b82f6,#60a5fa);border-radius:3px;width:0%;transition:width 0.1s linear;"></div>
</div>
<span id="hm-pl-dur" style="color:#888;font-size:0.8em;min-width:36px;text-align:right;">0:00</span>
</div>
<div id="hm-pl-counter" style="text-align:center;color:#666;font-size:0.75em;"></div>
<audio id="hm-pl-audio" preload="auto"></audio>
</div>'''
# ─── UI ───
CUSTOM_CSS = """
#song-desc-group {
border: 2px solid #3b82f6;
border-radius: 12px;
padding: 12px;
background: linear-gradient(135deg, rgba(59,130,246,0.08), rgba(59,130,246,0.02));
}
"""
PLAYLIST_JS = """
(function() {
var SK = '__hmPlState';
var lastHash = '';
var audio = null;
function init() {
var el = document.getElementById('hm-playlist-player');
if (!el) return;
var raw = el.getAttribute('data-tracks');
if (!raw) return;
// Skip if tracks haven't changed
var hash = raw.length + ':' + raw.slice(0, 100);
if (hash === lastHash && audio && document.contains(audio)) return;
lastHash = hash;
var tracks;
try { tracks = JSON.parse(raw); } catch(e) { return; }
if (!tracks.length) return;
var prev = window[SK] || {};
var ci = (typeof prev.ci === 'number' && prev.ci < tracks.length) ? prev.ci : 0;
var shuf = prev.shuf || false;
var shufOrd = prev.shufOrd || [];
var wasPlay = prev.wasPlay || false;
var savedT = prev.savedT || 0;
var savedSrc = prev.savedSrc || '';
// Create persistent audio element (survives Gradio re-renders)
if (!audio) {
audio = document.createElement('audio');
audio.preload = 'auto';
audio.style.display = 'none';
document.body.appendChild(audio);
}
var playBtn = document.getElementById('hm-pl-play');
var prevBtn = document.getElementById('hm-pl-prev');
var nextBtn = document.getElementById('hm-pl-next');
var modeBtn = document.getElementById('hm-pl-mode');
var titleEl = document.getElementById('hm-pl-title');
var tsEl = document.getElementById('hm-pl-ts');
var fill = document.getElementById('hm-pl-fill');
var timeEl = document.getElementById('hm-pl-time');
var durEl = document.getElementById('hm-pl-dur');
var ctrEl = document.getElementById('hm-pl-counter');
var bar = document.getElementById('hm-pl-bar');
if (!playBtn || !bar) return;
function fmt(s) {
if (isNaN(s)) return '0:00';
var m = Math.floor(s/60), sec = Math.floor(s%60);
return m + ':' + (sec < 10 ? '0' : '') + sec;
}
function genShuf() {
shufOrd = [];
for (var i = 0; i < tracks.length; i++) shufOrd.push(i);
for (var i = shufOrd.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var t = shufOrd[i]; shufOrd[i] = shufOrd[j]; shufOrd[j] = t;
}
}
function ri(idx) { return shuf ? (shufOrd[idx] || 0) : idx; }
function loadTrack(idx) {
ci = idx;
var t = tracks[ri(idx)];
audio.src = t.src;
titleEl.textContent = t.title;
tsEl.textContent = t.ts;
ctrEl.textContent = 'Track ' + (idx + 1) + ' of ' + tracks.length;
fill.style.width = '0%';
timeEl.textContent = '0:00';
durEl.textContent = '0:00';
}
function playTrack(idx) {
loadTrack(idx);
audio.play().catch(function(){});
playBtn.innerHTML = '\\u23F8';
}
function save() {
window[SK] = {
ci: ci, shuf: shuf, shufOrd: shufOrd,
wasPlay: !audio.paused, savedT: audio.currentTime || 0, savedSrc: audio.src || ''
};
}
// Sync play button with audio state
function syncBtn() {
playBtn.innerHTML = audio.paused ? '\\u25B6' : '\\u23F8';
}
playBtn.onclick = function() {
if (audio.paused) {
if (!audio.src) loadTrack(0);
audio.play().catch(function(){});
} else {
audio.pause();
}
syncBtn();
};
nextBtn.onclick = function() { playTrack((ci + 1) % tracks.length); };
prevBtn.onclick = function() {
if (audio.currentTime > 3) audio.currentTime = 0;
else playTrack((ci - 1 + tracks.length) % tracks.length);
};
modeBtn.onclick = function() {
shuf = !shuf;
modeBtn.textContent = shuf ? 'Shuffle' : 'Sequential';
modeBtn.style.background = shuf ? '#3b82f6' : '#2d3748';
if (shuf) genShuf();
save();
};
// Remove old listeners to avoid duplicates
audio.onended = function() {
var nx = ci + 1;
if (nx < tracks.length) playTrack(nx);
else { if (shuf) genShuf(); playTrack(0); }
};
audio.ontimeupdate = function() {
var f = document.getElementById('hm-pl-fill');
var te = document.getElementById('hm-pl-time');
var de = document.getElementById('hm-pl-dur');
if (f && audio.duration) {
f.style.width = (audio.currentTime / audio.duration * 100) + '%';
te.textContent = fmt(audio.currentTime);
de.textContent = fmt(audio.duration);
}
save();
};
bar.onclick = function(e) {
if (audio.duration) {
var r = bar.getBoundingClientRect();
audio.currentTime = ((e.clientX - r.left) / r.width) * audio.duration;
}
};
// Mutual exclusion with card players
audio.onplay = function() {
document.querySelectorAll('audio[controls]').forEach(function(x) {
if (!x.paused) x.pause();
});
};
if (!window.__hmPlCapture) {
window.__hmPlCapture = true;
document.addEventListener('play', function(e) {
if (audio && e.target !== audio && e.target.tagName === 'AUDIO') {
audio.pause();
var pb = document.getElementById('hm-pl-play');
if (pb) pb.innerHTML = '\\u25B6';
save();
}
}, true);
}
// Restore state
if (shuf) {
modeBtn.textContent = 'Shuffle';
modeBtn.style.background = '#3b82f6';
if (!shufOrd.length || shufOrd.length !== tracks.length) genShuf();
}
// If audio is already playing (persistent element), just sync UI
if (!audio.paused && audio.src) {
// Find which track matches current src
for (var i = 0; i < tracks.length; i++) {
if (audio.src.indexOf(tracks[i].src) !== -1) {
ci = shuf ? shufOrd.indexOf(i) : i;
if (ci < 0) ci = 0;
break;
}
}
var t = tracks[ri(ci)];
titleEl.textContent = t.title;
tsEl.textContent = t.ts;
ctrEl.textContent = 'Track ' + (ci + 1) + ' of ' + tracks.length;
syncBtn();
} else {
loadTrack(ci);
if (wasPlay && savedSrc) {
var expected = tracks[ri(ci)] ? tracks[ri(ci)].src : '';
if (expected && savedSrc.indexOf(expected) !== -1) {
audio.currentTime = savedT;
audio.play().catch(function(){});
syncBtn();
}
}
}
}
// Run init now and observe DOM for Gradio updates
init();
new MutationObserver(function() { setTimeout(init, 50); })
.observe(document.body, { childList: true, subtree: true });
})();
"""
with gr.Blocks(title="HeartMuse Music Generator", css=CUSTOM_CSS) as app:
gr.Markdown("# HeartMuse Music Generator")
with gr.Tab("Generate"):
with gr.Row():
# ── LEFT COLUMN: Text Composition ──
with gr.Column(scale=3):
gr.Markdown("### Describe your song")
with gr.Group(elem_id="song-desc-group"):
song_desc = gr.Textbox(
label="Song Description",
placeholder="A romantic ballad about summer love with piano and strings... (or leave empty to generate randomly)",
lines=3,
max_lines=10,
)
gen_desc_cb = gr.Checkbox(value=False, label="Auto-generate")
gr.Markdown("### Song details")
with gr.Row():
song_title_box = gr.Textbox(label="Song Title", placeholder="Enter or leave empty to generate...", scale=4)
gen_title_cb = gr.Checkbox(value=True, label="Auto-generate", scale=1)
with gr.Row():
lyrics_box = gr.Textbox(
label="Lyrics",
placeholder="[verse]\nYour lyrics here...\n\n[chorus]\n...",
lines=10,
max_lines=10,
scale=4,
)
gen_lyrics_cb = gr.Checkbox(value=True, label="Auto-generate", scale=1)
edit_instructions = gr.Textbox(
label="Edit Instructions (optional)",
placeholder='e.g., "Change the name Eva to Ela", "Add two verses", "Rework the chorus"',
lines=2,
max_lines=4,
)
with gr.Row():
tags_box = gr.Textbox(
label="Tags (comma-separated, 4-8 tags)",
placeholder="electronic,warm,female,energetic,synthesizer,dance",
info="Genre (required) + optional: timbre, gender, mood, instrument, scene, region, topic",
scale=4,
)
gen_tags_cb = gr.Checkbox(value=True, label="Auto-generate", scale=1)
with gr.Row():
clear_btn = gr.Button("Clear All", size="sm", variant="secondary")
gen_text_btn = gr.Button("Generate Text", variant="primary", size="lg")
with gr.Accordion("LLM Settings", open=False):
llm_backend = gr.Radio(["Ollama", "OpenAI"], value=DEFAULT_LLM_BACKEND, label="Backend")
with gr.Group(visible=DEFAULT_LLM_BACKEND == "Ollama") as ollama_group:
ollama_url = gr.Textbox(label="Ollama URL", value=DEFAULT_OLLAMA_URL)
with gr.Row():
ollama_model = gr.Dropdown(
label="Ollama Model", value=DEFAULT_OLLAMA_MODEL,
choices=[DEFAULT_OLLAMA_MODEL], allow_custom_value=True,
)
refresh_ollama_btn = gr.Button("Refresh Models", size="sm")
refresh_ollama_btn.click(on_list_ollama, [ollama_url], [ollama_model])
with gr.Group(visible=DEFAULT_LLM_BACKEND == "OpenAI") as openai_group:
openai_url = gr.Textbox(label="API Base URL", value=DEFAULT_OPENAI_URL)
openai_model = gr.Dropdown(
label="Model", value=DEFAULT_OPENAI_MODEL,
choices=DEFAULT_OPENAI_MODELS, allow_custom_value=True,
)
openai_key = gr.Textbox(label="API Key", value=DEFAULT_OPENAI_KEY, type="password")
def toggle_backend(choice):
return (
gr.update(visible=choice == "Ollama"),
gr.update(visible=choice == "OpenAI"),
)
llm_backend.change(toggle_backend, [llm_backend], [ollama_group, openai_group])
llm_temp = gr.Slider(0.0, 2.0, value=DEFAULT_LLM_TEMPERATURE, step=0.1, label="LLM Temperature")
llm_timeout = gr.Slider(10, 600, value=DEFAULT_LLM_TIMEOUT, step=10, label="LLM Timeout (seconds)")
# ── RIGHT COLUMN: Music Generation & Output ──
with gr.Column(scale=2):
gr.Markdown("### Generate music")
with gr.Row():
gen_music_btn = gr.Button("Generate Music", variant="primary", size="lg")
cancel_btn = gr.Button("Cancel", variant="stop", size="lg", interactive=False)
with gr.Row():
num_variants = gr.Slider(
1, 10, value=DEFAULT_NUM_VARIANTS, step=1,
label="Number of Variants",
info="Generate multiple audio variations from the same lyrics/tags.",
)
autoplay_cb = gr.Checkbox(label="Autoplay", value=True)
status_box = gr.HTML(value="", label="Status")
audio_out = gr.HTML(value="")
# Style Reference
if STYLE_TRANSFER_ENABLED:
with gr.Accordion("Style Reference (experimental)", open=False):
gr.Markdown("Upload a reference audio to guide the musical style. "
"The model will extract style characteristics and use them during generation.")
style_audio = gr.Audio(
label="Reference Audio",
type="filepath",
sources=["upload"],
)
style_enabled_cb = gr.Checkbox(
label="Use style reference",
value=False,
info="When enabled, the uploaded audio will guide the style of generated music.",
)
style_strength_sl = gr.Slider(
minimum=0.0, maximum=10.0, value=1.0, step=0.1,
label="Style Strength",
info="0 = no effect, 1 = normal, >1 = amplified style influence",
)
else:
style_audio = gr.State(value=None)
style_enabled_cb = gr.State(value=False)
style_strength_sl = gr.State(value=1.0)
with gr.Accordion("Music Generation Settings", open=False):
temperature = gr.Slider(0.1, 2.0, value=DEFAULT_GENERATION_PARAMS["temperature"], label="Temperature")