koby commited on
Commit
aa4ca52
·
1 Parent(s): 5f0dc39

simple layout per yue2_app.py + community link at bottom

Browse files
Files changed (1) hide show
  1. app.py +47 -595
app.py CHANGED
@@ -1,26 +1,19 @@
1
- import html
2
  import json
3
  import os
4
  import random
5
  import secrets
6
  import subprocess
7
- import time
8
- from concurrent.futures import ThreadPoolExecutor
9
  from datetime import datetime, timezone
10
- import spaces
11
  import gradio as gr
 
12
  import torch
13
 
14
- # נתיב שמירה תואם לסביבת Hugging Face Spaces
15
- OUT = "/tmp/yue2_out"
16
- os.makedirs(OUT, exist_ok=True)
17
-
18
- REPO = "m-a-p/YuE2-3B"
19
  COMMUNITY_REPO = "directedbykobyperez/YuE2-community"
20
 
21
- # Community feed cache (avoid hammering the Hub on every click)
22
- _FEED_CACHE = {"ts": 0.0, "songs": []}
23
- FEED_TTL = 30 # seconds
24
 
25
  pipe = None
26
 
@@ -38,7 +31,6 @@ def _ensure_yue2():
38
  return
39
  except ImportError:
40
  pass
41
- import subprocess
42
  import sys
43
  whl = os.path.join(os.path.dirname(os.path.abspath(__file__)), "yue2_infer-0.1.5-py3-none-any.whl")
44
  print(f"[yue2] installing vendored wheel: {whl}")
@@ -54,11 +46,8 @@ def get_pipeline():
54
  if pipe is None:
55
  _ensure_yue2()
56
  from yue2 import YuE2Pipeline
57
- print("Loading YuE2-3B pipeline on GPU...")
58
- pipe = YuE2Pipeline.from_pretrained(
59
- REPO,
60
- device="cuda" if torch.cuda.is_available() else "cpu",
61
- )
62
  print("Pipeline loaded.")
63
  return pipe
64
 
@@ -80,11 +69,9 @@ def flac_to_wav(flac_path, wav_path):
80
 
81
 
82
  def get_duration_seconds(audio_path):
83
- """Best-effort duration probe: soundfile -> ffprobe -> 0."""
84
  try:
85
  import soundfile as sf
86
- info = sf.info(audio_path)
87
- return float(info.duration)
88
  except Exception:
89
  pass
90
  try:
@@ -98,640 +85,105 @@ def get_duration_seconds(audio_path):
98
  return 0.0
99
 
100
 
101
- def derive_title(style, title_input, song_id):
102
- t = (title_input or "").strip()
103
- if t:
104
- return t[:120]
105
- s = (style or "").strip().replace("\n", " ")
106
- if s:
107
- words = s.split()[:8]
108
- title = " ".join(words)[:80]
109
- return title.title() if title else f"YuE2 Song {song_id[:6]}"
110
- return f"YuE2 Song {song_id[:6]}"
111
-
112
-
113
- def upload_to_community(wav_path, meta_dict, song_id):
114
- """Upload songs/<id>/<id>.wav + meta.json to the dataset repo.
115
- Returns (ok: bool, message: str). Never raises."""
116
  token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
117
  if not token:
118
- return False, "skipped upload (HF_TOKEN secret not set in Space)"
119
  try:
120
  from huggingface_hub import HfApi
121
  api = HfApi(token=token)
122
- wav_in_repo = f"songs/{song_id}/{song_id}.wav"
123
- meta_in_repo = f"songs/{song_id}/meta.json"
124
-
125
  meta_local = os.path.join(OUT, f"{song_id}_meta.json")
126
  with open(meta_local, "w", encoding="utf-8") as f:
127
  json.dump(meta_dict, f, ensure_ascii=False, indent=2)
128
-
129
  api.upload_file(
130
  path_or_fileobj=wav_path,
131
- path_in_repo=wav_in_repo,
132
- repo_id=COMMUNITY_REPO,
133
- repo_type="dataset",
134
  commit_message=f"add song {song_id}",
135
  )
136
  api.upload_file(
137
  path_or_fileobj=meta_local,
138
- path_in_repo=meta_in_repo,
139
- repo_id=COMMUNITY_REPO,
140
- repo_type="dataset",
141
  commit_message=f"add meta {song_id}",
142
  )
143
- url = f"https://huggingface.co/datasets/{COMMUNITY_REPO}/tree/main/songs/{song_id}"
144
- # invalidate feed cache so the new song appears fast
145
- _FEED_CACHE["ts"] = 0.0
146
- return True, f"uploaded to community ✅ {url}"
147
  except Exception as e:
148
- print(f"[community-upload] failed: {e}")
149
- return False, f"upload failed: {e}"
150
 
151
 
152
  @spaces.GPU(duration=120)
153
- def generate(style, lyrics, cot, seed, cfg_scale, title_input, bpm_input, lang_input, tags_input):
154
  pipeline = get_pipeline()
155
-
156
  if seed is None or seed < 1:
157
  try:
158
  seed = int(seed) if seed else random.randint(1, 10**6)
159
  except Exception:
160
  seed = random.randint(1, 10**6)
161
  seed = int(seed)
162
-
163
  gen_kwargs = dict(style=style, lyrics=lyrics, cot=cot, seed=seed)
164
  if cfg_scale and float(cfg_scale) != 1.0:
165
  gen_kwargs["cfg_scale"] = float(cfg_scale)
166
-
167
  song = pipeline(**gen_kwargs)
168
 
169
- # 12-hex-char id like 98152b6c67cb
170
  song_id = secrets.token_hex(6)
171
-
172
  flac_path = os.path.join(OUT, f"song_{song_id}.flac")
173
  mp3_path = os.path.join(OUT, f"song_{song_id}.mp3")
174
  wav_path = os.path.join(OUT, f"{song_id}.wav")
175
-
176
  song.save(flac_path)
177
  flac_to_mp3(flac_path, mp3_path)
178
  flac_to_wav(flac_path, wav_path)
179
 
180
- duration = get_duration_seconds(wav_path)
181
- try:
182
- bpm = int(bpm_input) if bpm_input else 120
183
- except Exception:
184
- bpm = 120
185
- language = (lang_input or "en").strip() or "en"
186
- title = derive_title(style, title_input, song_id)
187
- created_at = datetime.now(timezone.utc).isoformat()
188
- tags = (tags_input or "").strip()
189
-
190
- meta = {
191
  "id": song_id,
192
  "title": title,
193
  "description": (style or "").strip(),
194
- "tags": tags,
195
  "lyrics": lyrics or "",
196
  "caption": (style or "").strip(),
197
- "bpm": bpm,
198
- "language": language,
199
- "duration": duration,
200
  "seed": seed,
201
  "generation_mode": cot or "auto",
202
  "audio_file": f"{song_id}.wav",
203
- "created_at": created_at,
204
- }
205
-
206
- ok, upload_msg = upload_to_community(wav_path, meta, song_id)
207
-
208
- size_kb = os.path.getsize(mp3_path) // 1024
209
- info = (
210
- f"ID: {song_id} | Seed: {seed} | Size: {size_kb} KB (MP3 320kbps) | "
211
- f"Duration: {duration:.1f}s\n{upload_msg}"
212
- )
213
- return flac_path, mp3_path, info
214
-
215
 
216
- # ---------------- Community feed ----------------
217
 
218
- def _fetch_one_meta(path, token):
219
- """Download + parse one meta.json. Returns dict or None."""
220
- try:
221
- from huggingface_hub import hf_hub_download
222
- local = hf_hub_download(
223
- repo_id=COMMUNITY_REPO, repo_type="dataset",
224
- filename=path, token=token,
225
- )
226
- with open(local, "r", encoding="utf-8") as f:
227
- m = json.load(f)
228
- if isinstance(m, dict) and m.get("id"):
229
- return m
230
- except Exception as e:
231
- print(f"[feed] skip {path}: {e}")
232
- return None
233
-
234
-
235
- def _load_feed_songs():
236
- """List all songs/*/meta.json, download, sort newest first. Cached."""
237
- now = time.time()
238
- if now - _FEED_CACHE["ts"] < FEED_TTL and _FEED_CACHE["songs"]:
239
- return _FEED_CACHE["songs"], True
240
-
241
- token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
242
- try:
243
- from huggingface_hub import HfApi
244
- api = HfApi(token=token) if token else HfApi()
245
- files = api.list_repo_files(repo_id=COMMUNITY_REPO, repo_type="dataset")
246
- meta_paths = [f for f in files if f.startswith("songs/") and f.endswith("/meta.json")]
247
- except Exception as e:
248
- print(f"[feed] list failed: {e}")
249
- # serve stale cache if we have it
250
- if _FEED_CACHE["songs"]:
251
- return _FEED_CACHE["songs"], True
252
- return [], False
253
-
254
- # cap to keep the tab fast (newest unknown until we read created_at,
255
- # so take a slice; 300 metas ≈ a few MB max)
256
- meta_paths = sorted(meta_paths)[-300:]
257
-
258
- songs = []
259
- with ThreadPoolExecutor(max_workers=8) as ex:
260
- for m in ex.map(lambda p: _fetch_one_meta(p, token), meta_paths):
261
- if m:
262
- songs.append(m)
263
-
264
- def _key(m):
265
- try:
266
- return m.get("created_at", "")
267
- except Exception:
268
- return ""
269
- songs.sort(key=_key, reverse=True)
270
-
271
- _FEED_CACHE["ts"] = time.time()
272
- _FEED_CACHE["songs"] = songs
273
- return songs, False
274
-
275
-
276
- def _tags_html(tags_raw):
277
- tags_raw = (tags_raw or "").strip()
278
- if not tags_raw:
279
- return '<span class="no-tags">no tags</span>'
280
- parts = [t.strip() for t in tags_raw.replace(";", ",").split(",") if t.strip()][:10]
281
- if not parts:
282
- return '<span class="no-tags">no tags</span>'
283
- return "".join(f'<span class="tag-pill">{html.escape(t)}</span>' for t in parts)
284
-
285
-
286
- def _fmt_dur(s):
287
- try:
288
- s = float(s or 0)
289
- except Exception:
290
- return "0:00"
291
- return f"{int(s // 60)}:{int(s % 60):02d}"
292
 
293
-
294
- def _ago(iso):
295
- try:
296
- dt = datetime.fromisoformat(str(iso).replace("Z", "+00:00"))
297
- if dt.tzinfo is None:
298
- dt = dt.replace(tzinfo=timezone.utc)
299
- secs = int((datetime.now(timezone.utc) - dt).total_seconds())
300
- if secs < 90:
301
- return "just now"
302
- if secs < 3600:
303
- return f"{secs // 60}m ago"
304
- if secs < 86400:
305
- return f"{secs // 3600}h ago"
306
- d = secs // 86400
307
- return "1 day ago" if d == 1 else f"{d} days ago"
308
- except Exception:
309
- return ""
310
-
311
-
312
- def _is_new(iso):
313
- try:
314
- dt = datetime.fromisoformat(str(iso).replace("Z", "+00:00"))
315
- if dt.tzinfo is None:
316
- dt = dt.replace(tzinfo=timezone.utc)
317
- return (datetime.now(timezone.utc) - dt).total_seconds() < 86400
318
- except Exception:
319
- return False
320
-
321
-
322
- def _song_audio_url(song_id):
323
- return f"https://huggingface.co/datasets/{COMMUNITY_REPO}/resolve/main/songs/{song_id}/{song_id}.wav"
324
-
325
-
326
- def _wave_html(sid, bars=72):
327
- import hashlib
328
- h = int(hashlib.md5(str(sid).encode()).hexdigest(), 16)
329
- out = []
330
- for _ in range(bars):
331
- h = (h * 1103515245 + 12345) & 0x7FFFFFFF
332
- out.append(f'<i style="height:{8 + h % 92}%"></i>')
333
- return '<div class="wave">' + "".join(out) + "</div>"
334
-
335
-
336
- def _filter_songs(songs, search):
337
- q = (search or "").strip().lower()
338
- if not q:
339
- return songs
340
- def _match(m):
341
- blob = " ".join([
342
- str(m.get("title", "")), str(m.get("caption", "")),
343
- str(m.get("description", "")), str(m.get("lyrics", "")),
344
- str(m.get("tags", "")), str(m.get("id", "")),
345
- ]).lower()
346
- return q in blob
347
- return [m for m in songs if _match(m)]
348
-
349
-
350
- def render_list_html(songs, selected_id=None):
351
- """Middle column: track rows with gradient play buttons."""
352
- if not songs:
353
- return """
354
- <div class="empty-feed">
355
- <p style="font-size:1.2rem;">🎶 No songs yet — be the first!</p>
356
- <p style="color:#8e8e99;">Hit Generate on the left and your track lands here.</p>
357
- </div>
358
- """
359
- rows = []
360
- for m in songs:
361
- sid = str(m.get("id", "?"))
362
- title = html.escape(str(m.get("title", sid)))
363
- tags = str(m.get("tags", "")).strip()
364
- tag_list = [t.strip() for t in tags.replace(";", ",").split(",") if t.strip()][:4]
365
- sub = html.escape(", ".join(tag_list) if tag_list else str(m.get("caption", ""))[:70])
366
- dur = _fmt_dur(m.get("duration", 0))
367
- au = html.escape(_song_audio_url(sid), quote=True)
368
- sel = " sel" if sid == selected_id else ""
369
- new = ' <span class="r-new">New</span>' if _is_new(m.get("created_at", "")) else ""
370
- rows.append(
371
- f"""<div class="r-row{sel}">
372
- <button class="r-play" onclick="document.querySelectorAll('.rau').forEach(function(x){{x.pause()}});document.getElementById('au_{sid}').play()">▶</button>
373
- <div class="r-meta"><div class="r-title">{title}{new}</div><div class="r-sub">{sub or "—"}</div></div>
374
- <div class="r-dur">{dur}</div>
375
- <audio class="rau" id="au_{sid}" src="{au}" preload="none" style="display:none"></audio>
376
- </div>"""
377
- )
378
- return "\n".join(rows)
379
-
380
-
381
- def _detail_parts(m):
382
- """Returns (title_html, tags_html, lyrics_html, audio_url_or_None, wave_html, meta_html)."""
383
- if not m:
384
- return (
385
- "<div class='d-title'>🎶 No song yet</div><div class='d-ago'>Generate your first track on the left</div>",
386
- '<span class="no-tags">no tags</span>',
387
- "<div class='d-lyrics'>Lyrics will appear here…</div>",
388
- None,
389
- _wave_html("empty"),
390
- "<div class='d-meta'>—</div>",
391
- )
392
- sid = str(m.get("id", "?"))
393
- title = html.escape(str(m.get("title", sid)))
394
- ago = html.escape(_ago(m.get("created_at", "")))
395
- lyrics = html.escape(str(m.get("lyrics", ""))[:3000]) or "—"
396
- bpm = html.escape(str(m.get("bpm", "?")))
397
- lang = html.escape(str(m.get("language", "?")))
398
- seed = html.escape(str(m.get("seed", "?")))
399
- dur = _fmt_dur(m.get("duration", 0))
400
- au = _song_audio_url(sid)
401
- au_e = html.escape(au, quote=True)
402
- title_html = f"<div class='d-title'>{title}</div><div class='d-ago'>{ago}</div>"
403
- lyrics_html = f"<div class='d-lyrics'>{lyrics}</div>"
404
- meta_html = (
405
- f"<div class='d-meta'>BPM {bpm} · {lang} · ⏱ {dur} · seed {seed}</div>"
406
- f"<div class='d-links'><a href='{au_e}' target='_blank'>⬇ Download WAV</a>"
407
- f"<a href='https://huggingface.co/datasets/{COMMUNITY_REPO}/tree/main/songs/{sid}' target='_blank'>Dataset ↗</a></div>"
408
- )
409
- return title_html, _tags_html(m.get("tags", "")), lyrics_html, au, _wave_html(sid), meta_html
410
-
411
-
412
- def _dd_choices(songs):
413
- return [(f"{str(m.get('title', m.get('id')))} — {str(m.get('id'))[:6]}", str(m.get("id"))) for m in songs]
414
-
415
-
416
- def refresh_all(search, limit):
417
- """Full refresh: list + status + dropdown + detail (newest selected). Never raises."""
418
- try:
419
- limit = int(limit) if limit else 20
420
- except Exception:
421
- limit = 20
422
- limit = max(1, min(int(limit), 60))
423
- try:
424
- songs, cached = _load_feed_songs()
425
- total = len(songs)
426
- shown = _filter_songs(songs, search)[:limit]
427
- sel = str(shown[0].get("id")) if shown else None
428
- d = _detail_parts(shown[0] if shown else None)
429
- status = f"Showing {len(shown)}/{total} songs" + (" • cached" if cached else " • live")
430
- if (search or "").strip():
431
- status += f" • filter: '{search}'"
432
- return (
433
- render_list_html(shown, sel), status, gr.update(choices=_dd_choices(shown), value=sel),
434
- d[0], d[1], d[2], d[3], d[4], d[5],
435
- )
436
- except Exception as e:
437
- print(f"[feed] refresh failed: {e}")
438
- d = _detail_parts(None)
439
- return (render_list_html([]), f"Failed to load feed: {e}", gr.update(choices=[], value=None),
440
- d[0], d[1], d[2], d[3], d[4], d[5])
441
-
442
-
443
- def show_detail(song_id, search, limit):
444
- """Right-panel focus view when the user picks a song. Never raises."""
445
- try:
446
- limit = int(limit) if limit else 20
447
- except Exception:
448
- limit = 20
449
- limit = max(1, min(int(limit), 60))
450
- try:
451
- songs, _ = _load_feed_songs()
452
- shown = _filter_songs(songs, search)[:limit]
453
- song = next((m for m in songs if str(m.get("id")) == str(song_id)), None)
454
- d = _detail_parts(song)
455
- return (render_list_html(shown, str(song_id)), d[0], d[1], d[2], d[3], d[4], d[5])
456
- except Exception as e:
457
- print(f"[feed] detail failed: {e}")
458
- d = _detail_parts(None)
459
- return (render_list_html([]), d[0], d[1], d[2], d[3], d[4], d[5])
460
-
461
-
462
- # CSS לעיצוב יוקרתי בסגנון Dark Theme
463
  custom_css = """
464
  :root { color-scheme: dark; }
465
- body, .gradio-container {
466
- background-color: #0e0e0f !important;
467
- color: #ffffff !important;
468
- }
469
- h1, h2, h3, label, p, .prose, .gradio-container span, .gradio-container div { color: #ffffff; }
470
  input, textarea, select { color: #ffffff !important; }
471
  input::placeholder, textarea::placeholder { color: #9a9aa3 !important; }
472
- .gradio-container {
473
- max-width: 1100px !important;
474
- margin: 0 auto !important;
475
- }
476
- .main-title {
477
- text-align: center;
478
- margin-bottom: 20px;
479
- }
480
- .main-title h1 {
481
- font-size: 2.5rem;
482
- font-weight: 800;
483
- background: linear-gradient(90deg, #ff4b4b, #6b21a8);
484
- -webkit-background-clip: text;
485
- -webkit-text-fill-color: transparent;
486
- }
487
- .generate-btn {
488
- background: linear-gradient(135deg, #ff4b4b 0%, #a855f7 100%) !important;
489
- border: none !important;
490
- color: white !important;
491
- font-size: 1.1rem !important;
492
- font-weight: bold !important;
493
- border-radius: 12px !important;
494
- padding: 12px !important;
495
- box-shadow: 0 4px 15px rgba(255, 75, 75, 0.3) !important;
496
- transition: all 0.3s ease !important;
497
- }
498
- .generate-btn:hover {
499
- transform: translateY(-2px);
500
- box-shadow: 0 6px 20px rgba(255, 75, 75, 0.5) !important;
501
- }
502
- .song-card {
503
- background: #111827;
504
- border: 1px solid #1f2937;
505
- border-radius: 14px;
506
- padding: 16px;
507
- margin-bottom: 14px;
508
- }
509
- .song-title { font-size: 1.15rem; font-weight: 700; color: #f1f5f9; }
510
- .song-sub { font-size: 0.78rem; color: #64748b; margin-top: 2px; }
511
- .song-sub code { color: #a855f7; }
512
- .song-tags { margin: 6px 0; display: flex; flex-wrap: wrap; gap: 6px; }
513
- .tag-pill {
514
- background: #1e1b4b; color: #c4b5fd; border: 1px solid #4c1d95;
515
- font-size: 0.75rem; padding: 2px 10px; border-radius: 999px;
516
- }
517
- .no-tags { color: #475569; font-size: 0.78rem; }
518
- .song-prompt { font-size: 0.88rem; color: #cbd5e1; margin: 6px 0; }
519
- .song-lyrics { margin-top: 6px; }
520
- .song-lyrics summary { cursor: pointer; color: #94a3b8; font-size: 0.85rem; }
521
- .song-lyrics pre {
522
- white-space: pre-wrap; font-size: 0.82rem; color: #94a3b8;
523
- background: #0b0f19; padding: 10px; border-radius: 8px; max-height: 220px; overflow: auto;
524
- }
525
- .song-links { margin-top: 8px; font-size: 0.82rem; }
526
- .song-links a { color: #a855f7; text-decoration: none; margin-right: 8px; }
527
- .empty-feed { text-align: center; padding: 40px 10px; color: #94a3b8; }
528
- audio::-webkit-media-controls-panel { background: #1f2937; }
529
- /* hide Gradio footer: Use via API · Built with Gradio · Settings */
530
  footer { display: none !important; }
531
- /* ===== studio layout (dark 3-column) ===== */
532
- .gradio-container { max-width: 1500px !important; }
533
- .panel { background: #121218 !important; border: 1px solid #232330 !important; border-radius: 14px !important; padding: 14px !important; }
534
- .r-row { display: flex; align-items: center; gap: 12px; background: #15151d; border: 1px solid #262633; border-radius: 12px; padding: 10px 12px; margin-bottom: 10px; }
535
- .r-row.sel { border-color: #ff2d55; box-shadow: 0 0 0 1px #ff2d55; }
536
- .r-play { width: 44px; height: 44px; border-radius: 50%; border: none; cursor: pointer; flex-shrink: 0; font-size: 15px; color: #fff; background: linear-gradient(135deg, #ff9f43, #ff2d55); }
537
- .r-play:hover { filter: brightness(1.12); }
538
- .r-meta { min-width: 0; flex: 1; }
539
- .r-title { font-weight: 700; color: #f5f5f7; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
540
- .r-sub { font-size: 0.76rem; color: #8e8e99; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
541
- .r-dur { margin-left: auto; color: #c7c7d1; font-size: 0.8rem; flex-shrink: 0; }
542
- .r-new { background: #ff2d55; color: #fff; font-size: 0.65rem; border-radius: 6px; padding: 1px 7px; margin-left: 8px; vertical-align: middle; }
543
- .generate-btn { width: 100% !important; }
544
- .detail-panel { background: linear-gradient(165deg, #e5383b 0%, #f3722c 55%, #f5a524 100%) !important; border-radius: 16px !important; padding: 18px !important; color: #fff !important; border: none !important; }
545
- .detail-panel .prose, .detail-panel h3 { color: #fff !important; }
546
- .d-title { font-size: 1.5rem; font-weight: 800; color: #fff; }
547
- .d-ago { opacity: 0.85; font-size: 0.8rem; margin-bottom: 10px; color: #fff; }
548
- .detail-panel .tag-pill { background: rgba(0,0,0,0.35); border: 1px solid transparent; color: #fff; }
549
- .detail-panel .no-tags { color: rgba(255,255,255,0.7); }
550
- .d-lyrics { font-size: 1.02rem; line-height: 1.9; color: #fff; white-space: pre-wrap; max-height: 360px; overflow-y: auto; margin: 10px 0; }
551
- .wave { display: flex; align-items: flex-end; gap: 2px; height: 60px; margin: 12px 0 4px; }
552
- .wave i { flex: 1; background: rgba(255,255,255,0.9); border-radius: 2px; min-height: 3px; }
553
- .d-meta { font-size: 0.8rem; color: rgba(255,255,255,0.9); margin-top: 8px; }
554
- .d-links { margin-top: 6px; font-size: 0.85rem; }
555
- .d-links a { color: #fff; font-weight: 700; margin-right: 12px; }
556
  """
557
 
558
- with gr.Blocks(title="YuE2-3B Music Generator") as demo:
559
- gr.HTML(
560
- """
561
- <div class="main-title">
562
- <img src="https://huggingface.co/spaces/directedbykobyperez/YuE2-Create/resolve/main/logo.svg" alt="YuE2 logo" style="width:88px;height:88px;margin-bottom:8px;" />
563
- <h1>🎵 YuE2-3B Music Studio</h1>
564
- <p style="font-size: 0.95rem;">
565
- <a href="https://map-yue2.github.io/" target="_blank" style="color:#a855f7;">🌐 Model Website</a>
566
- <span style="color:#475569;"> · </span>
567
- <a href="https://huggingface.co/datasets/directedbykobyperez/YuE2-community" target="_blank" style="color:#a855f7;">🤗 Community Dataset</a>
568
- </p>
569
- </div>
570
- """
571
- )
572
-
573
  with gr.Row():
574
- # LEFT: studio controls
575
- with gr.Column(scale=4, elem_classes=["panel"]):
576
- gr.Markdown("### 🎛️ Create")
577
- title_input = gr.Textbox(
578
- label="🏷️ Title (optional — auto from style if empty)",
579
- value="",
580
- placeholder="e.g. Reggaeton Latin Spanish Old",
581
- lines=1,
582
- )
583
- style = gr.Textbox(
584
- label="🎨 Style Prompt",
585
- value="Old School Reggaeton, Perreo, Heavy Bass, 2000s Style, Deep Male Vocal, piano orchestral, malianteo, Daddy Yankee",
586
- lines=3
587
- )
588
- tags_input = gr.Textbox(
589
- label="🏷️ Tags (comma separated, shown in community feed)",
590
- value="",
591
- placeholder="e.g. pop, melodic, cinematic",
592
- lines=1,
593
- )
594
- lyrics = gr.Textbox(
595
- label="📜 Lyrics ([verse] / [chorus] structure)",
596
- value="""[Verse 1]
597
- Me dijiste baby ven que te espero
598
- Y yo llegué corriendo sin dudar
599
- Tú me tenías en tu juego entero
600
- Y no quería nunca despertar
601
-
602
- Tus ojos me hablaban de otro lado
603
- Tu boca me prometía el mar
604
- Pero el tiempo siempre dice claro
605
- Lo que el corazón no quiere ver jamás
606
-
607
- [Pre-Chorus]
608
- Y ahora dime quién te va a tratar así
609
- Quién va a escribir tu nombre sobre mí
610
-
611
- [Chorus]
612
- Déjame quererte aunque tú no quieras
613
- Déjame abrazarte aunque sea en la espera
614
- Sé que tú me miras pero no lo dices
615
- Aquí en mi pecho tú eres mi cicatriz
616
-
617
- Tu recuerdo vive y no se muere
618
- Tu cariño quema aunque tú no quiere'
619
- Déjame quererte aunque sea mentira
620
- Porque contigo yo perdí la vida
621
-
622
- [Verse 2]
623
- Sé que andas conmigo en otro cuarto
624
- Que tu corazón me tiene en replay
625
- Pero yo sigo aquí esperando el rato
626
- Donde me mires como ayer
627
-
628
- Las calles hablan de tu nombre
629
- Los vecinos cuentan que te vi
630
- Con otro beso y otro hombre
631
- Pero el mío siempre pega aquí
632
-
633
- [Pre-Chorus]
634
- Y ahora dime quién te va a tratar así
635
- Quién va a escribir tu nombre sobre mí
636
-
637
- [Chorus]
638
- Déjame quererte aunque tú no quieras
639
- Déjame abrazarte aunque sea en la espera
640
- Sé que tú me miras pero no lo dices
641
- Aquí en mi pecho tú eres mi cicatriz
642
-
643
- Tu recuerdo vive y no se muere
644
- Tu cariño quema aunque tú no quiere'
645
- Déjame quererte aunque sea mentira
646
- Porque contigo yo perdí la vida
647
-
648
- [Bridge]
649
- No me importa el qué dirán
650
- Ni los cuentos que se van
651
- Yo te busco en la ciudad
652
- Y te encuentro en la verdad
653
-
654
- [Chorus]
655
- Déjame quererte aunque tú no quieras
656
- Déjame abrazarte aunque sea en la espera
657
- Sé que tú me miras pero no lo dices
658
- Aquí en mi pecho tú eres mi cicatriz
659
-
660
- Tu recuerdo vive y no se muere
661
- Tu cariño quema aunque tú no quiere'
662
- Déjame quererte aunque sea mentira
663
- Porque contigo yo perdí la vida""",
664
- lines=12
665
- )
666
- with gr.Row():
667
- cot = gr.Radio(["full", "melody", "off"], value="full", label="CoT Mode")
668
- seed = gr.Number(label="Seed (0 for Random)", value=0, precision=0)
669
- cfg = gr.Number(label="CFG Scale", value=1.0, precision=2)
670
  with gr.Row():
671
- bpm_input = gr.Number(label="BPM", value=120, precision=0)
672
- lang_input = gr.Textbox(label="Language", value="es", lines=1)
673
-
674
- btn = gr.Button("✨ Generate", elem_classes=["generate-btn"])
675
- audio = gr.Audio(label="🎧 Preview", type="filepath")
676
- mp3_file = gr.File(label="📥 MP3 (320kbps)")
677
- info = gr.Textbox(label="ℹ️ Generation Info", interactive=False)
678
-
679
- # MIDDLE: track list
680
- with gr.Column(scale=5, elem_classes=["panel"]):
681
- gr.Markdown("### 🎵 Tracks")
682
- with gr.Row():
683
- search_box = gr.Textbox(label="🔍 Search", value="", placeholder="type anything: title, prompt, lyrics, tags, id...", lines=1, scale=4)
684
- limit_slider = gr.Slider(5, 60, value=20, step=5, label="How many")
685
- refresh_btn = gr.Button("🔄 Refresh", scale=1)
686
- feed_status = gr.Textbox(label="Status", interactive=False, value="Loading songs...")
687
- feed_html = gr.HTML("<div class='empty-feed'>Loading latest community songs...</div>")
688
-
689
- # RIGHT: now-showing detail
690
- with gr.Column(scale=4, elem_classes=["detail-panel"]):
691
- gr.Markdown("### ✨ Now Showing")
692
- song_select = gr.Dropdown(label="🎵 Pick a song", choices=[], interactive=True)
693
- d_title = gr.HTML("<div class='d-title'>🎶 No song yet</div><div class='d-ago'>Generate your first track</div>")
694
- d_tags = gr.HTML('<span class="no-tags">no tags</span>')
695
- d_lyrics = gr.HTML("<div class='d-lyrics'>Lyrics will appear here…</div>")
696
- d_wave = gr.HTML("")
697
- d_audio = gr.Audio(label="▶ Player", interactive=False)
698
- d_meta = gr.HTML("<div class='d-meta'>—</div>")
699
-
700
- gen_event = btn.click(
701
- fn=generate,
702
- inputs=[style, lyrics, cot, seed, cfg, title_input, bpm_input, lang_input, tags_input],
703
- outputs=[audio, mp3_file, info],
704
- queue=True
705
- )
706
-
707
- _refresh_out = [feed_html, feed_status, song_select, d_title, d_tags, d_lyrics, d_audio, d_wave, d_meta]
708
- _detail_out = [feed_html, d_title, d_tags, d_lyrics, d_audio, d_wave, d_meta]
709
-
710
- refresh_btn.click(
711
- fn=refresh_all,
712
- inputs=[search_box, limit_slider],
713
- outputs=_refresh_out,
714
- )
715
-
716
- # auto-refresh everything right after each generation (CPU-only, no extra GPU time)
717
- gen_event.then(
718
- fn=refresh_all,
719
- inputs=[search_box, limit_slider],
720
- outputs=_refresh_out,
721
- )
722
-
723
- # picking a song focuses it in the red detail panel (+ highlights the row)
724
- song_select.change(
725
- fn=show_detail,
726
- inputs=[song_select, search_box, limit_slider],
727
- outputs=_detail_out,
728
- )
729
-
730
- # auto-load feed on page open so users see songs without pressing Refresh
731
- demo.load(
732
- fn=refresh_all,
733
- inputs=[search_box, limit_slider],
734
- outputs=_refresh_out,
735
  )
736
 
737
  demo.queue().launch(css=custom_css, footer_links=[], favicon_path="favicon.png")
 
 
1
  import json
2
  import os
3
  import random
4
  import secrets
5
  import subprocess
 
 
6
  from datetime import datetime, timezone
7
+
8
  import gradio as gr
9
+ import spaces
10
  import torch
11
 
 
 
 
 
 
12
  COMMUNITY_REPO = "directedbykobyperez/YuE2-community"
13
 
14
+ REPO = "m-a-p/YuE2-3B"
15
+ OUT = "/tmp/yue2_out"
16
+ os.makedirs(OUT, exist_ok=True)
17
 
18
  pipe = None
19
 
 
31
  return
32
  except ImportError:
33
  pass
 
34
  import sys
35
  whl = os.path.join(os.path.dirname(os.path.abspath(__file__)), "yue2_infer-0.1.5-py3-none-any.whl")
36
  print(f"[yue2] installing vendored wheel: {whl}")
 
46
  if pipe is None:
47
  _ensure_yue2()
48
  from yue2 import YuE2Pipeline
49
+ print("Loading YuE2-3B pipeline (first run downloads weights)...")
50
+ pipe = YuE2Pipeline.from_pretrained(REPO, device="cuda" if torch.cuda.is_available() else "cpu")
 
 
 
51
  print("Pipeline loaded.")
52
  return pipe
53
 
 
69
 
70
 
71
  def get_duration_seconds(audio_path):
 
72
  try:
73
  import soundfile as sf
74
+ return float(sf.info(audio_path).duration)
 
75
  except Exception:
76
  pass
77
  try:
 
85
  return 0.0
86
 
87
 
88
+ def _upload_to_community(wav_path, meta_dict, song_id):
89
+ """Silently share songs/<id>/<id>.wav + meta.json to the dataset repo. Never raises."""
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
91
  if not token:
92
+ return
93
  try:
94
  from huggingface_hub import HfApi
95
  api = HfApi(token=token)
 
 
 
96
  meta_local = os.path.join(OUT, f"{song_id}_meta.json")
97
  with open(meta_local, "w", encoding="utf-8") as f:
98
  json.dump(meta_dict, f, ensure_ascii=False, indent=2)
 
99
  api.upload_file(
100
  path_or_fileobj=wav_path,
101
+ path_in_repo=f"songs/{song_id}/{song_id}.wav",
102
+ repo_id=COMMUNITY_REPO, repo_type="dataset",
 
103
  commit_message=f"add song {song_id}",
104
  )
105
  api.upload_file(
106
  path_or_fileobj=meta_local,
107
+ path_in_repo=f"songs/{song_id}/meta.json",
108
+ repo_id=COMMUNITY_REPO, repo_type="dataset",
 
109
  commit_message=f"add meta {song_id}",
110
  )
111
+ print(f"[community] uploaded {song_id}")
 
 
 
112
  except Exception as e:
113
+ print(f"[community] upload failed: {e}")
 
114
 
115
 
116
  @spaces.GPU(duration=120)
117
+ def generate(style, lyrics, cot, seed, cfg_scale):
118
  pipeline = get_pipeline()
 
119
  if seed is None or seed < 1:
120
  try:
121
  seed = int(seed) if seed else random.randint(1, 10**6)
122
  except Exception:
123
  seed = random.randint(1, 10**6)
124
  seed = int(seed)
 
125
  gen_kwargs = dict(style=style, lyrics=lyrics, cot=cot, seed=seed)
126
  if cfg_scale and float(cfg_scale) != 1.0:
127
  gen_kwargs["cfg_scale"] = float(cfg_scale)
 
128
  song = pipeline(**gen_kwargs)
129
 
 
130
  song_id = secrets.token_hex(6)
 
131
  flac_path = os.path.join(OUT, f"song_{song_id}.flac")
132
  mp3_path = os.path.join(OUT, f"song_{song_id}.mp3")
133
  wav_path = os.path.join(OUT, f"{song_id}.wav")
 
134
  song.save(flac_path)
135
  flac_to_mp3(flac_path, mp3_path)
136
  flac_to_wav(flac_path, wav_path)
137
 
138
+ words = (style or "").strip().replace("\n", " ").split()[:8]
139
+ title = " ".join(words).title()[:80] if words else f"YuE2 Song {song_id[:6]}"
140
+ _upload_to_community(wav_path, {
 
 
 
 
 
 
 
 
141
  "id": song_id,
142
  "title": title,
143
  "description": (style or "").strip(),
 
144
  "lyrics": lyrics or "",
145
  "caption": (style or "").strip(),
146
+ "bpm": 120,
147
+ "language": "",
148
+ "duration": get_duration_seconds(wav_path),
149
  "seed": seed,
150
  "generation_mode": cot or "auto",
151
  "audio_file": f"{song_id}.wav",
152
+ "created_at": datetime.now(timezone.utc).isoformat(),
153
+ }, song_id)
 
 
 
 
 
 
 
 
 
 
154
 
155
+ return flac_path, mp3_path, f"seed={seed} | {os.path.getsize(mp3_path) // 1024}KB MP3 320kbps"
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  custom_css = """
159
  :root { color-scheme: dark; }
160
+ body, .gradio-container { background-color: #0e0e0f !important; color: #ffffff !important; }
161
+ h1, h2, h3, label, p, .prose { color: #ffffff !important; }
 
 
 
162
  input, textarea, select { color: #ffffff !important; }
163
  input::placeholder, textarea::placeholder { color: #9a9aa3 !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  footer { display: none !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  """
166
 
167
+ with gr.Blocks(title="YuE2-3B Music") as demo:
168
+ gr.Markdown("# YuE2-3B Music Generator\nFull song (vocals + accompaniment) from a style prompt and lyrics.")
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  with gr.Row():
170
+ with gr.Column():
171
+ style = gr.Textbox(label="Style prompt", value="Cyber metal, English, aggressive male vocals, distorted guitars, double-kick drums", lines=3)
172
+ lyrics = gr.Textbox(label="Lyrics ([verse]/[chorus] etc.)", value="[verse]\nnothing here but static skies\nwe ride the current till it dies", lines=8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  with gr.Row():
174
+ cot = gr.Radio(["full", "melody", "off"], value="full", label="CoT mode")
175
+ seed = gr.Number(label="Seed", value=0, precision=0)
176
+ cfg = gr.Number(label="CFG scale (1.0 = default)", value=1.0, precision=2)
177
+ btn = gr.Button("Generate song", variant="primary")
178
+ with gr.Column():
179
+ audio = gr.Audio(label="Play song", type="filepath")
180
+ flac_file = gr.File(label="Download FLAC")
181
+ mp3_file = gr.File(label="Download MP3 320kbps")
182
+ info = gr.Textbox(label="Info")
183
+ btn.click(fn=generate, inputs=[style, lyrics, cot, seed, cfg], outputs=[audio, mp3_file, info], queue=True)
184
+ gr.Markdown(
185
+ "---\n🎶 **Community songs:** every generation is auto-shared to the "
186
+ "[YuE2-community dataset](https://huggingface.co/datasets/directedbykobyperez/YuE2-community)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  )
188
 
189
  demo.queue().launch(css=custom_css, footer_links=[], favicon_path="favicon.png")