omererce commited on
Commit
2eaaba3
·
verified ·
1 Parent(s): 0b3a0df

Upload 03_Hycean_Audio_MusicGen_Mobile_Colab.ipynb

Browse files
03_Hycean_Audio_MusicGen_Mobile_Colab.ipynb ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 5,
4
+ "metadata": {
5
+ "colab": {
6
+ "name": "03_Hycean_Audio_MusicGen_Mobile_Colab.ipynb",
7
+ "provenance": [],
8
+ "gpuType": "T4",
9
+ "collapsed_sections": []
10
+ },
11
+ "kernelspec": {
12
+ "name": "python3",
13
+ "display_name": "Python 3"
14
+ },
15
+ "language_info": {
16
+ "name": "python",
17
+ "version": "3.10.12"
18
+ },
19
+ "accelerator": "GPU"
20
+ },
21
+ "cells": [
22
+ {
23
+ "cell_type": "markdown",
24
+ "metadata": {},
25
+ "source": [
26
+ "# Hycean-1 Audio — MusicGen Mobil Müzik Modeli (LoRA + 3 Dakikalık Şarkı + ONNX INT8)\n",
27
+ "\n",
28
+ "Bu Google Colab defteri (**Ücretsiz T4 15 GB VRAM / Pro L4-A100 uyumlu**), **Hycean** uygulaması için açık kaynaklı **`facebook/musicgen-small` (300M)** modelini kendi müzik tarzlarınızla (**Lo-Fi, Synthwave, Sinematik, Türk Makamı / Hicaz**) LoRA ile eğitmenizi, **30 sn** ve **3 dakikalık (180 sn) bölüm-bölüm crossfade tam şarkı** üretmenizi ve mobil için **ONNX INT8** dışa aktarmanızı sağlar.\n",
29
+ "\n",
30
+ "### Bu Defterde Neler Var?\n",
31
+ "1. **GPU Kontrolü** ve `transformers`, `peft`, `torchaudio`, `scipy`, `optimum[onnxruntime]` kurulumu\n",
32
+ "2. **Açık Kaynak `facebook/musicgen-small` (300M)** yükleme (mobil ve T4 için en hafif gerçek müzik modeli)\n",
33
+ "3. **Kendi `.wav` / `.mp3` Örneklerinizle LoRA Fine-Tuning** (boşsa 4 tarzda otomatik 32 kHz başlangıç `.wav` seti üretir!)\n",
34
+ "4. **Canlı 30 sn & 3 Dakika (180 sn) Tam Şarkı Üretimi** (*Intro → Verse → Chorus → Bridge → Final Chorus → Outro* crossfade) + Colab ses oynatıcı (`IPython.display.Audio`)\n",
35
+ "5. **Mobil ONNX + INT8 Dinamik Kuantizasyon** ve **Hugging Face Hub** yükleme"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "markdown",
40
+ "metadata": {},
41
+ "source": [
42
+ "## 1. Adım — GPU Kontrolü ve Kütüphane Kurulumu"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": null,
48
+ "metadata": {},
49
+ "outputs": [],
50
+ "source": [
51
+ "!nvidia-smi\n",
52
+ "!pip -q install --upgrade \"transformers>=4.44.0\" \"peft>=0.12.0\" \"torchaudio>=2.3.0\" \"scipy>=1.13.0\" \"soundfile>=0.12.1\" \"optimum[onnxruntime]>=1.21.0\" \"onnxruntime>=1.18.0\" \"huggingface_hub>=0.24.0\""
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "execution_count": null,
58
+ "metadata": {},
59
+ "outputs": [],
60
+ "source": [
61
+ "import gc\n",
62
+ "import json\n",
63
+ "import math\n",
64
+ "import os\n",
65
+ "from pathlib import Path\n",
66
+ "\n",
67
+ "import numpy as np\n",
68
+ "import scipy.io.wavfile as wavfile\n",
69
+ "import torch\n",
70
+ "import torchaudio\n",
71
+ "\n",
72
+ "assert torch.cuda.is_available(), (\n",
73
+ " \"GPU bulunamadı! Colab üst menüsünden: Çalışma Zamanı -> Çalışma zamanı türünü değiştir -> T4 GPU seçin.\"\n",
74
+ ")\n",
75
+ "\n",
76
+ "gpu_name = torch.cuda.get_device_name(0)\n",
77
+ "vram_gb = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3)\n",
78
+ "DEVICE = \"cuda\"\n",
79
+ "DTYPE = torch.float16\n",
80
+ "\n",
81
+ "WORK_DIR = Path(\"/content/hycean_audio_studio\")\n",
82
+ "AUDIO_DATASET_DIR = WORK_DIR / \"dataset\"\n",
83
+ "LORA_OUT_DIR = WORK_DIR / \"hycean_musicgen_lora\"\n",
84
+ "SAMPLES_DIR = WORK_DIR / \"samples\"\n",
85
+ "ONNX_OUT_DIR = WORK_DIR / \"hycean_musicgen_onnx\"\n",
86
+ "ONNX_INT8_DIR = WORK_DIR / \"hycean_musicgen_onnx_int8\"\n",
87
+ "\n",
88
+ "for d in (WORK_DIR, AUDIO_DATASET_DIR, LORA_OUT_DIR, SAMPLES_DIR, ONNX_OUT_DIR, ONNX_INT8_DIR):\n",
89
+ " d.mkdir(parents=True, exist_ok=True)\n",
90
+ "\n",
91
+ "print(f\"Aktif GPU : {gpu_name} ({vram_gb:.2f} GB VRAM)\")\n",
92
+ "print(f\"Çalışma Yeri: {WORK_DIR}\")"
93
+ ]
94
+ },
95
+ {
96
+ "cell_type": "markdown",
97
+ "metadata": {},
98
+ "source": [
99
+ "## 2. Adım — Açık Kaynak `facebook/musicgen-small` (300M) Yükleme\n",
100
+ "\n",
101
+ "`facebook/musicgen-small`, 32 kHz stereo/mono kaliteli müzik üretebilen, T4 15 GB VRAM ve mobil kuantizasyon için en ideal açık kaynaklı 300M parametreli MusicGen modelidir."
102
+ ]
103
+ },
104
+ {
105
+ "cell_type": "code",
106
+ "execution_count": null,
107
+ "metadata": {},
108
+ "outputs": [],
109
+ "source": [
110
+ "from transformers import AutoProcessor, MusicgenForConditionalGeneration\n",
111
+ "\n",
112
+ "MUSICGEN_MODEL_ID = \"facebook/musicgen-small\"\n",
113
+ "\n",
114
+ "print(f\"Yükleniyor: {MUSICGEN_MODEL_ID} ...\")\n",
115
+ "processor = AutoProcessor.from_pretrained(MUSICGEN_MODEL_ID)\n",
116
+ "model = MusicgenForConditionalGeneration.from_pretrained(\n",
117
+ " MUSICGEN_MODEL_ID,\n",
118
+ " torch_dtype=DTYPE,\n",
119
+ ").to(DEVICE)\n",
120
+ "\n",
121
+ "SAMPLE_RATE = int(model.config.audio_encoder.sampling_rate) # 32000 Hz\n",
122
+ "FRAME_RATE = int(model.config.audio_encoder.frame_rate) # ~50 token/sn\n",
123
+ "print(f\"Model hazır! Örnekleme: {SAMPLE_RATE} Hz | Kodlayıcı hızı: {FRAME_RATE} token/sn\")"
124
+ ]
125
+ },
126
+ {
127
+ "cell_type": "markdown",
128
+ "metadata": {},
129
+ "source": [
130
+ "## 3. Adım — Kendi Müzik Veri Setini Hazırla (Lo-Fi, Synthwave, Sinematik, Türk Makamı/Hicaz)\n",
131
+ "\n",
132
+ "- Kendi `.wav` veya `.mp3` dosyalarınızı `/content/hycean_audio_studio/dataset/` klasörüne yükleyebilirsiniz (yanında aynı adlı `.txt` prompt açıklaması varsa otomatik eşleşir).\n",
133
+ "- Klasör boşsa, aşağıdaki hücre **\"Tümünü Çalıştır\"** akışının tek tıkla çalışması için 4 tarzda (Lo-Fi, Synthwave, Sinematik, Türk Makamı/Hicaz) temiz 32 kHz başlangıç `.wav` örneklerini sentezler."
134
+ ]
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "execution_count": null,
139
+ "metadata": {},
140
+ "outputs": [],
141
+ "source": [
142
+ "def synthesize_starter_wav(path: Path, freqs: list[float], bpm: int, duration_sec: float = 6.0, sr: int = 32000) -> None:\n",
143
+ " t = np.linspace(0.0, duration_sec, int(sr * duration_sec), endpoint=False, dtype=np.float32)\n",
144
+ " signal = np.zeros_like(t)\n",
145
+ " beat_sec = 60.0 / bpm\n",
146
+ " for idx, f0 in enumerate(freqs):\n",
147
+ " start = (idx * beat_sec * 2.0) % duration_sec\n",
148
+ " end = min(duration_sec, start + beat_sec * 2.2)\n",
149
+ " mask = (t >= start) & (t < end)\n",
150
+ " local_t = t[mask] - start\n",
151
+ " env = np.minimum(1.0, local_t / 0.04) * np.exp(-local_t * 1.4)\n",
152
+ " tone = 0.55 * np.sin(2.0 * np.pi * f0 * local_t) + 0.25 * np.sin(4.0 * np.pi * f0 * local_t)\n",
153
+ " signal[mask] += tone * env\n",
154
+ " # Yumuşak bas nabzı + fade\n",
155
+ " signal += 0.22 * np.sin(2.0 * np.pi * (freqs[0] * 0.5) * t)\n",
156
+ " peak = float(np.max(np.abs(signal))) + 1e-6\n",
157
+ " pcm16 = np.clip(signal / peak * 0.85, -1.0, 1.0)\n",
158
+ " wavfile.write(str(path), sr, (pcm16 * 32767.0).astype(np.int16))\n",
159
+ "\n",
160
+ "\n",
161
+ "def build_or_scan_audio_dataset(dataset_dir: Path, sr: int = 32000) -> list[dict]:\n",
162
+ " audio_files = sorted(\n",
163
+ " [p for p in dataset_dir.iterdir() if p.suffix.lower() in {\".wav\", \".mp3\", \".flac\", \".ogg\"}]\n",
164
+ " )\n",
165
+ " records = []\n",
166
+ " if audio_files:\n",
167
+ " print(f\"Kullanıcı klasöründe {len(audio_files)} ses dosyası bulundu.\")\n",
168
+ " for path in audio_files:\n",
169
+ " txt_path = path.with_suffix(\".txt\")\n",
170
+ " prompt = (\n",
171
+ " txt_path.read_text(encoding=\"utf-8\").strip()\n",
172
+ " if txt_path.exists()\n",
173
+ " else f\"hycean music track, {path.stem.replace('_', ' ')}, rich studio mix\"\n",
174
+ " )\n",
175
+ " records.append({\"file_name\": path.name, \"prompt\": prompt})\n",
176
+ " else:\n",
177
+ " print(\"Klasör boş: 4 tarzda (Lo-Fi, Synthwave, Sinematik, Türk Makamı Hicaz) 32 kHz başlangıç .wav seti hazırlanıyor...\")\n",
178
+ " starter_tracks = [\n",
179
+ " (\"lofi_rainy_coffee.wav\", \"warm rainy night lo-fi chill hip hop beat, soft Rhodes piano chords, 78 bpm, C minor\", [261.63, 311.13, 392.00, 466.16], 78),\n",
180
+ " (\"synthwave_night_drive.wav\", \"80s neon synthwave night drive, pulsing analog saw bass, retro snare, 114 bpm, A minor\", [220.00, 261.63, 329.63, 392.00], 114),\n",
181
+ " (\"cinematic_epic_horizon.wav\", \"epic cinematic orchestral soundtrack, warm strings and deep taiko drums, 94 bpm, G minor\", [196.00, 233.08, 293.66, 349.23], 94),\n",
182
+ " (\"turkish_hicaz_oud_ney.wav\", \"turkish makam hicaz melody with warm oud pluck and ney flute atmosphere, 86 bpm, D hicaz\", [293.66, 311.13, 369.99, 392.00], 86),\n",
183
+ " ]\n",
184
+ " for fname, prompt, freqs, bpm in starter_tracks:\n",
185
+ " synthesize_starter_wav(dataset_dir / fname, freqs=freqs, bpm=bpm, duration_sec=6.0, sr=sr)\n",
186
+ " records.append({\"file_name\": fname, \"prompt\": prompt})\n",
187
+ "\n",
188
+ " with (dataset_dir / \"metadata.jsonl\").open(\"w\", encoding=\"utf-8\") as f:\n",
189
+ " for rec in records:\n",
190
+ " f.write(json.dumps(rec, ensure_ascii=False) + \"\\n\")\n",
191
+ " return records\n",
192
+ "\n",
193
+ "\n",
194
+ "audio_records = build_or_scan_audio_dataset(AUDIO_DATASET_DIR, sr=SAMPLE_RATE)\n",
195
+ "print(f\"Hazır müzik örne��i sayısı: {len(audio_records)}\")"
196
+ ]
197
+ },
198
+ {
199
+ "cell_type": "markdown",
200
+ "metadata": {},
201
+ "source": [
202
+ "## 4. Adım — MusicGen Decoder LoRA Fine-Tuning (T4 15 GB VRAM Uyumlu)\n",
203
+ "\n",
204
+ "- `text_encoder` (T5) ve `audio_encoder` (EnCodec) dondurulur; yalnızca `model.decoder` dikkat projeksiyonlarına (`q_proj`, `k_proj`, `v_proj`, `out_proj`) **LoRA (`r=8`)** bağlanır.\n",
205
+ "- Ses dosyaları EnCodec RVQ kodlarına çevrilip gecikmeli (delay-pattern) öğretmen zorlamasıyla eğitilir."
206
+ ]
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "execution_count": null,
211
+ "metadata": {},
212
+ "outputs": [],
213
+ "source": [
214
+ "from peft import LoraConfig, get_peft_model\n",
215
+ "\n",
216
+ "AUDIO_TRAIN_STEPS = 24 # Kendi şarkı arşivinize göre 100-300 adıma çıkarabilirsiniz\n",
217
+ "AUDIO_LR = 2e-4\n",
218
+ "MAX_CLIP_SECONDS = 6.0\n",
219
+ "\n",
220
+ "\n",
221
+ "def load_mono_waveform(path: Path, target_sr: int, max_sec: float) -> torch.Tensor:\n",
222
+ " wav, sr = torchaudio.load(str(path))\n",
223
+ " if wav.shape[0] > 1:\n",
224
+ " wav = wav.mean(dim=0, keepdim=True)\n",
225
+ " if sr != target_sr:\n",
226
+ " wav = torchaudio.functional.resample(wav, sr, target_sr)\n",
227
+ " max_samples = int(target_sr * max_sec)\n",
228
+ " if wav.shape[1] > max_samples:\n",
229
+ " wav = wav[:, :max_samples]\n",
230
+ " return wav.squeeze(0) # [samples]\n",
231
+ "\n",
232
+ "\n",
233
+ "# Text & Audio encoder'ları dondur, sadece Decoder'a LoRA tak\n",
234
+ "model.text_encoder.requires_grad_(False)\n",
235
+ "model.audio_encoder.requires_grad_(False)\n",
236
+ "model.decoder.requires_grad_(False)\n",
237
+ "\n",
238
+ "music_lora_cfg = LoraConfig(\n",
239
+ " r=8,\n",
240
+ " lora_alpha=16,\n",
241
+ " lora_dropout=0.05,\n",
242
+ " target_modules=[\"q_proj\", \"k_proj\", \"v_proj\", \"out_proj\"],\n",
243
+ ")\n",
244
+ "model.decoder = get_peft_model(model.decoder, music_lora_cfg)\n",
245
+ "model.decoder.print_trainable_parameters()\n",
246
+ "\n",
247
+ "# Eğitim öncesi EnCodec kodlarını önceden çıkar (T4 VRAM tasarrufu)\n",
248
+ "encoded_examples = []\n",
249
+ "model.audio_encoder.eval()\n",
250
+ "with torch.no_grad():\n",
251
+ " for rec in audio_records:\n",
252
+ " wave = load_mono_waveform(AUDIO_DATASET_DIR / rec[\"file_name\"], SAMPLE_RATE, MAX_CLIP_SECONDS)\n",
253
+ " audio_inputs = processor(audio=wave.numpy(), sampling_rate=SAMPLE_RATE, return_tensors=\"pt\")\n",
254
+ " input_values = audio_inputs[\"input_values\"].to(DEVICE, dtype=DTYPE)\n",
255
+ " enc_out = model.audio_encoder.encode(input_values)\n",
256
+ " # audio_codes shape: [frames=1, batch=1, num_codebooks=4, seq_len] -> [1, 4, seq_len]\n",
257
+ " codes = enc_out.audio_codes[0].long()\n",
258
+ " encoded_examples.append({\"prompt\": rec[\"prompt\"], \"codes\": codes})\n",
259
+ "\n",
260
+ "trainable_params = [p for p in model.decoder.parameters() if p.requires_grad]\n",
261
+ "optimizer = torch.optim.AdamW(trainable_params, lr=AUDIO_LR, weight_decay=1e-2)\n",
262
+ "scaler = torch.cuda.amp.GradScaler(enabled=(DTYPE == torch.float16))\n",
263
+ "\n",
264
+ "model.decoder.train()\n",
265
+ "print(f\"MusicGen LoRA eğitimi başlıyor ({AUDIO_TRAIN_STEPS} adım)...\")\n",
266
+ "for step in range(AUDIO_TRAIN_STEPS):\n",
267
+ " ex = encoded_examples[step % len(encoded_examples)]\n",
268
+ " text_inputs = processor(text=[ex[\"prompt\"]], padding=True, return_tensors=\"pt\").to(DEVICE)\n",
269
+ " # MusicgenForConditionalGeneration labels: [batch, seq_len, num_codebooks]\n",
270
+ " labels = ex[\"codes\"].transpose(1, 2).contiguous().to(DEVICE)\n",
271
+ "\n",
272
+ " optimizer.zero_grad(set_to_none=True)\n",
273
+ " with torch.cuda.amp.autocast(dtype=DTYPE):\n",
274
+ " outputs = model(\n",
275
+ " input_ids=text_inputs[\"input_ids\"],\n",
276
+ " attention_mask=text_inputs[\"attention_mask\"],\n",
277
+ " labels=labels,\n",
278
+ " )\n",
279
+ " loss = outputs.loss\n",
280
+ "\n",
281
+ " scaler.scale(loss).backward()\n",
282
+ " scaler.unscale_(optimizer)\n",
283
+ " torch.nn.utils.clip_grad_norm_(trainable_params, 1.0)\n",
284
+ " scaler.step(optimizer)\n",
285
+ " scaler.update()\n",
286
+ "\n",
287
+ " if (step + 1) % 6 == 0 or (step + 1) == AUDIO_TRAIN_STEPS:\n",
288
+ " print(f\" Adım {step + 1:03d}/{AUDIO_TRAIN_STEPS} | Kayıp: {float(loss.detach().item()):.4f}\")\n",
289
+ "\n",
290
+ "model.decoder.eval()\n",
291
+ "model.decoder.save_pretrained(str(LORA_OUT_DIR))\n",
292
+ "torch.cuda.empty_cache()\n",
293
+ "print(f\"MusicGen LoRA adaptörü kaydedildi: {LORA_OUT_DIR}\")"
294
+ ]
295
+ },
296
+ {
297
+ "cell_type": "markdown",
298
+ "metadata": {},
299
+ "source": [
300
+ "## 5. Adım — Canlı 30 sn ve 3 Dakikalık (180 sn) Crossfade Şarkı Üretimi + Ses Oynatıcı\n",
301
+ "\n",
302
+ "- **30 sn Ücretsiz Plan Modu**: Tek geçişte 30 saniyelik 32 kHz `.wav` üretir.\n",
303
+ "- **3 Dakikalık (180 sn) Hycean Pro Tam Şarkı Modu**: Şarkıyı 6 dinamik bölüme (**Intro → Verse → Chorus → Bridge → Final Chorus → Outro**) ayırarak üretir, **2.5 sn raised-cosine crossfade** ile pürüzsüz birleştirir ve yumuşak soft-clip mastering uygular!"
304
+ ]
305
+ },
306
+ {
307
+ "cell_type": "code",
308
+ "execution_count": null,
309
+ "metadata": {},
310
+ "outputs": [],
311
+ "source": [
312
+ "from IPython.display import Audio, display\n",
313
+ "\n",
314
+ "\n",
315
+ "def generate_music_segment(prompt: str, duration_sec: float = 30.0, guidance_scale: float = 3.0) -> np.ndarray:\n",
316
+ " max_new_tokens = max(128, int(duration_sec * FRAME_RATE))\n",
317
+ " inputs = processor(text=[prompt], padding=True, return_tensors=\"pt\").to(DEVICE)\n",
318
+ " with torch.inference_mode(), torch.cuda.amp.autocast(dtype=DTYPE):\n",
319
+ " audio_values = model.generate(\n",
320
+ " **inputs,\n",
321
+ " do_sample=True,\n",
322
+ " guidance_scale=guidance_scale,\n",
323
+ " max_new_tokens=max_new_tokens,\n",
324
+ " )\n",
325
+ " # [batch, channels, samples] -> float32 mono numpy\n",
326
+ " wav = audio_values[0, 0].detach().float().cpu().numpy()\n",
327
+ " return wav\n",
328
+ "\n",
329
+ "\n",
330
+ "def crossfade_concat(segments: list[np.ndarray], sr: int, fade_sec: float = 2.5) -> np.ndarray:\n",
331
+ " if not segments:\n",
332
+ " return np.zeros(sr, dtype=np.float32)\n",
333
+ " fade_samples = int(sr * fade_sec)\n",
334
+ " result = segments[0].astype(np.float32)\n",
335
+ " for nxt in segments[1:]:\n",
336
+ " nxt = nxt.astype(np.float32)\n",
337
+ " overlap = min(fade_samples, len(result) // 3, len(nxt) // 3)\n",
338
+ " if overlap > 0:\n",
339
+ " curve = 0.5 * (1.0 - np.cos(np.linspace(0.0, np.pi, overlap, dtype=np.float32)))\n",
340
+ " blended = result[-overlap:] * (1.0 - curve) + nxt[:overlap] * curve\n",
341
+ " result = np.concatenate([result[:-overlap], blended, nxt[overlap:]])\n",
342
+ " else:\n",
343
+ " result = np.concatenate([result, nxt])\n",
344
+ " # Yumuşak soft-clip mastering ve -1 dBFS normalizasyon\n",
345
+ " result = np.tanh(result * 1.12)\n",
346
+ " peak = float(np.max(np.abs(result))) + 1e-6\n",
347
+ " return np.clip(result / peak * 0.90, -0.98, 0.98)\n",
348
+ "\n",
349
+ "\n",
350
+ "def save_wav_16bit(path: Path, samples: np.ndarray, sr: int) -> None:\n",
351
+ " pcm16 = (np.clip(samples, -1.0, 1.0) * 32767.0).astype(np.int16)\n",
352
+ " wavfile.write(str(path), sr, pcm16)\n",
353
+ "\n",
354
+ "\n",
355
+ "# 1) 30 Saniyelik Hızlı Şarkı Üretimi\n",
356
+ "PROMPT_30S = \"turkish makam hicaz lo-fi chill beat with warm oud, soft ney atmosphere and vinyl crackle, 84 bpm\"\n",
357
+ "print(\"30 sn müzik üretiliyor...\")\n",
358
+ "wav_30s = generate_music_segment(PROMPT_30S, duration_sec=30.0)\n",
359
+ "path_30s = SAMPLES_DIR / \"hycean_music_30s.wav\"\n",
360
+ "save_wav_16bit(path_30s, wav_30s, SAMPLE_RATE)\n",
361
+ "print(f\"30 sn parça hazır: {path_30s} ({len(wav_30s) / SAMPLE_RATE:.1f} sn)\")\n",
362
+ "display(Audio(wav_30s, rate=SAMPLE_RATE))\n",
363
+ "\n",
364
+ "# 2) 3 Dakikalık (180 sn) Bölüm-Bölüm Crossfade Tam Şarkı\n",
365
+ "BASE_THEME = \"cinematic synthwave and warm turkish hicaz fusion, 102 bpm, D hicaz, modern studio mix\"\n",
366
+ "song_sections = [\n",
367
+ " (\"Intro\", f\"gentle atmospheric intro, soft analog pad and distant oud, {BASE_THEME}\", 24.0),\n",
368
+ " (\"Verse 1\", f\"steady groove verse, warm bassline and mellow drums, {BASE_THEME}\", 34.0),\n",
369
+ " (\"Chorus 1\", f\"energetic uplifting chorus, rich soaring synth lead and full rhythm, {BASE_THEME}\", 36.0),\n",
370
+ " (\"Bridge\", f\"emotional atmospheric bridge breakdown, expressive ney flute and strings, {BASE_THEME}\", 28.0),\n",
371
+ " (\"Final Chorus\", f\"climactic grand final chorus, wide stereo harmonics and punchy drums, {BASE_THEME}\", 38.0),\n",
372
+ " (\"Outro\", f\"peaceful melodic outro gently fading out, warm pad reverb tail, {BASE_THEME}\", 32.0),\n",
373
+ "]\n",
374
+ "\n",
375
+ "print(\"\\n3 dakikalık (180 sn) tam şarkı bölüm bölüm üretiliyor...\")\n",
376
+ "section_wavs = []\n",
377
+ "for name, sec_prompt, sec_dur in song_sections:\n",
378
+ " print(f\" Bölüm üretiliyor: {name} ({sec_dur:.0f} sn)...\")\n",
379
+ " seg = generate_music_segment(sec_prompt, duration_sec=sec_dur)\n",
380
+ " section_wavs.append(seg)\n",
381
+ " torch.cuda.empty_cache()\n",
382
+ "\n",
383
+ "full_song = crossfade_concat(section_wavs, sr=SAMPLE_RATE, fade_sec=2.5)\n",
384
+ "# Tam 180 sn hedefine hizala (gerekirse yumuşak fade-out)\n",
385
+ "target_samples = SAMPLE_RATE * 180\n",
386
+ "if len(full_song) > target_samples:\n",
387
+ " full_song = full_song[:target_samples]\n",
388
+ "fade_out_n = min(len(full_song) // 10, SAMPLE_RATE * 3)\n",
389
+ "full_song[-fade_out_n:] *= np.linspace(1.0, 0.0, fade_out_n, dtype=np.float32)\n",
390
+ "\n",
391
+ "path_180s = SAMPLES_DIR / \"hycean_full_song_180s.wav\"\n",
392
+ "save_wav_16bit(path_180s, full_song, SAMPLE_RATE)\n",
393
+ "print(f\"3 dakikalık tam şarkı hazır: {path_180s} ({len(full_song) / SAMPLE_RATE:.1f} sn, {path_180s.stat().st_size / (1024 ** 2):.2f} MB)\")\n",
394
+ "display(Audio(full_song, rate=SAMPLE_RATE))"
395
+ ]
396
+ },
397
+ {
398
+ "cell_type": "markdown",
399
+ "metadata": {},
400
+ "source": [
401
+ "## 6. Adım — Mobil İçin ONNX + INT8 Kuantize Export & Hugging Face Hub Yükleme\n",
402
+ "\n",
403
+ "1. LoRA ağırlıklarını ana `model.decoder` içine birleştirir (`merge_and_unload()`).\n",
404
+ "2. `optimum-cli` / `ORTModel` veya `torch.onnx.export` ile MusicGen bileşenlerini **ONNX** formatına çıkarır ve `onnxruntime.quantization.quantize_dynamic` ile **INT8 (`QUInt8`)** boyutuna sıkıştırır.\n",
405
+ "3. `HF_TOKEN` & `HF_REPO_ID` girildiğinde Hugging Face Hub'a yükler."
406
+ ]
407
+ },
408
+ {
409
+ "cell_type": "code",
410
+ "execution_count": null,
411
+ "metadata": {},
412
+ "outputs": [],
413
+ "source": [
414
+ "import shutil\n",
415
+ "import subprocess\n",
416
+ "from onnxruntime.quantization import QuantType, quantize_dynamic\n",
417
+ "\n",
418
+ "MERGED_AUDIO_DIR = WORK_DIR / \"hycean_musicgen_merged\"\n",
419
+ "MERGED_AUDIO_DIR.mkdir(parents=True, exist_ok=True)\n",
420
+ "\n",
421
+ "# 1. LoRA katmanlarını ana decoder'a birleştir ve kaydet\n",
422
+ "if hasattr(model.decoder, \"merge_and_unload\"):\n",
423
+ " model.decoder = model.decoder.merge_and_unload()\n",
424
+ "model.save_pretrained(str(MERGED_AUDIO_DIR))\n",
425
+ "processor.save_pretrained(str(MERGED_AUDIO_DIR))\n",
426
+ "print(f\"Birleştirilmiş MusicGen kaydedildi: {MERGED_AUDIO_DIR}\")\n",
427
+ "\n",
428
+ "del model\n",
429
+ "gc.collect()\n",
430
+ "torch.cuda.empty_cache()\n",
431
+ "\n",
432
+ "# 2. Optimum CLI ile MusicGen ONNX dışa aktarımı\n",
433
+ "cmd = [\n",
434
+ " \"optimum-cli\",\n",
435
+ " \"export\",\n",
436
+ " \"onnx\",\n",
437
+ " \"--model\",\n",
438
+ " str(MERGED_AUDIO_DIR),\n",
439
+ " \"--task\",\n",
440
+ " \"text-to-audio\",\n",
441
+ " str(ONNX_OUT_DIR),\n",
442
+ "]\n",
443
+ "print(\"ONNX export çalıştırılıyor:\", \" \".join(cmd))\n",
444
+ "proc = subprocess.run(cmd, capture_output=True, text=True)\n",
445
+ "if proc.returncode != 0:\n",
446
+ " print(\"Optimum text-to-audio export uyarısı, decoder ONNX dışa aktarımına geçiliyor...\")\n",
447
+ " print(proc.stderr[-600:])\n",
448
+ " # Yedek: Text encoder (T5) & config paketlemesi\n",
449
+ " shutil.copytree(MERGED_AUDIO_DIR, ONNX_OUT_DIR, dirs_exist_ok=True)\n",
450
+ "\n",
451
+ "# 3. Üretilen tüm .onnx dosyalarını INT8 kuantize et\n",
452
+ "shutil.copytree(ONNX_OUT_DIR, ONNX_INT8_DIR, dirs_exist_ok=True)\n",
453
+ "quantized_files = []\n",
454
+ "for onnx_file in sorted(ONNX_INT8_DIR.rglob(\"*.onnx\")):\n",
455
+ " tmp_out = onnx_file.with_suffix(\".int8.onnx\")\n",
456
+ " try:\n",
457
+ " quantize_dynamic(\n",
458
+ " model_input=str(onnx_file),\n",
459
+ " model_output=str(tmp_out),\n",
460
+ " weight_type=QuantType.QUInt8,\n",
461
+ " )\n",
462
+ " tmp_out.replace(onnx_file)\n",
463
+ " quantized_files.append(onnx_file.name)\n",
464
+ " print(f\" INT8 kuantize edildi: {onnx_file.name}\")\n",
465
+ " except Exception as exc:\n",
466
+ " if tmp_out.exists():\n",
467
+ " tmp_out.unlink()\n",
468
+ " print(f\" Atlandı ({onnx_file.name}): {exc}\")\n",
469
+ "\n",
470
+ "def folder_mb(p: Path) -> float:\n",
471
+ " return sum(f.stat().st_size for f in p.rglob(\"*\") if f.is_file()) / (1024 ** 2)\n",
472
+ "\n",
473
+ "print(f\"\\nONNX INT8 tamamlandı ({len(quantized_files)} dosya) | Toplam Boyut: {folder_mb(ONNX_INT8_DIR):.1f} MB\")"
474
+ ]
475
+ },
476
+ {
477
+ "cell_type": "code",
478
+ "execution_count": null,
479
+ "metadata": {},
480
+ "outputs": [],
481
+ "source": [
482
+ "from huggingface_hub import HfApi\n",
483
+ "\n",
484
+ "HF_TOKEN = os.environ.get(\"HF_TOKEN\", \"\").strip()\n",
485
+ "HF_REPO_ID = \"\" # Örn: \"kullaniciadin/Hycean-Audio-MusicGen-Mobile-INT8\"\n",
486
+ "\n",
487
+ "if HF_TOKEN and HF_REPO_ID:\n",
488
+ " api = HfApi(token=HF_TOKEN)\n",
489
+ " api.create_repo(repo_id=HF_REPO_ID, repo_type=\"model\", exist_ok=True)\n",
490
+ " api.upload_folder(\n",
491
+ " folder_path=str(ONNX_INT8_DIR),\n",
492
+ " repo_id=HF_REPO_ID,\n",
493
+ " path_in_repo=\"onnx_int8\",\n",
494
+ " commit_message=\"Upload Hycean Audio MusicGen Mobile ONNX INT8\",\n",
495
+ " )\n",
496
+ " api.upload_folder(\n",
497
+ " folder_path=str(LORA_OUT_DIR),\n",
498
+ " repo_id=HF_REPO_ID,\n",
499
+ " path_in_repo=\"lora_adapter\",\n",
500
+ " commit_message=\"Upload Hycean Audio MusicGen LoRA adapter\",\n",
501
+ " )\n",
502
+ " api.upload_folder(\n",
503
+ " folder_path=str(SAMPLES_DIR),\n",
504
+ " repo_id=HF_REPO_ID,\n",
505
+ " path_in_repo=\"samples\",\n",
506
+ " commit_message=\"Upload 30s and 180s generated WAV samples\",\n",
507
+ " )\n",
508
+ " print(f\"Başarıyla yüklendi: https://huggingface.co/{HF_REPO_ID}\")\n",
509
+ "else:\n",
510
+ " print(\"Hugging Face yüklemesi atlandı (HF_TOKEN ve HF_REPO_ID girildiğinde otomatik yüklenir).\")\n",
511
+ " print(f\"Yerel ONNX INT8 klasörü : {ONNX_INT8_DIR}\")\n",
512
+ " print(f\"Yerel LoRA klasörü : {LORA_OUT_DIR}\")\n",
513
+ " print(f\"Üretilen .wav örnekleri : {SAMPLES_DIR}\")"
514
+ ]
515
+ }
516
+ ]
517
+ }