-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunklab_cli.py
More file actions
513 lines (450 loc) · 18.4 KB
/
funklab_cli.py
File metadata and controls
513 lines (450 loc) · 18.4 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
#!/usr/bin/env python3
"""
FunkLab CLI - Interface de linha de comando.
Comandos: new, analyze, bassline, batch, organize-samples.
"""
from __future__ import annotations
import itertools
import json
import sys
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
import click
# Adiciona raiz do projeto ao path
PROJECT_ROOT = Path(__file__).parent
sys.path.insert(0, str(PROJECT_ROOT))
@dataclass
class ProjectManifestEntry:
project_name: str
bpm: float
style: str
groove_used: str
bass_pattern_used: str
created_at: str
def _build_project_structure(
groove_name: str,
bass_pattern: str,
structure_override: list[dict] | None = None,
) -> list:
"""Constrói estrutura de seções. Usa structure_override se fornecido."""
from core.template_builder import SongSection
if structure_override:
sections = []
for s in structure_override:
name = s.get("name", "section")
bars = s.get("bars", 4)
has_groove = s.get("groove", False)
has_bass = s.get("bass", False)
sections.append(SongSection(
name=name,
bars=bars,
groove_name=groove_name if has_groove else None,
bass_pattern=bass_pattern if has_bass else None,
))
return sections
return [
SongSection("intro", 4),
SongSection("groove", 8, groove_name=groove_name, bass_pattern=bass_pattern),
SongSection("build", 4, groove_name=groove_name),
SongSection("drop", 8, groove_name=groove_name, bass_pattern=bass_pattern),
SongSection("break", 4),
SongSection("outro", 4),
]
def _create_single_project(
bpm: float,
style: str,
project_name: str,
output_dir: Path,
groove_name: str,
bass_pattern: str,
structure_override: list[dict] | None = None,
musicality_params: "MusicalityParams | None" = None, # noqa: F821
) -> Path:
"""Cria um único projeto. Reutilizado por new e batch."""
from core.template_builder import TemplateBuilder
from core.bass_generator import BassGenerator
from core.musicality import MusicalityParams
structure = _build_project_structure(
groove_name, bass_pattern, structure_override=structure_override
)
musicality = musicality_params or MusicalityParams.default(preset_name=style)
tb = TemplateBuilder(bpm=bpm)
project_dir = tb.build_template(
structure=structure,
output_dir=output_dir,
project_name=project_name,
groove_lib_path=PROJECT_ROOT / "library" / "grooves.json",
musicality=musicality,
)
bg = BassGenerator(bpm=bpm, musicality=musicality)
pm = bg.generate_from_pattern(key="C", pattern_name=bass_pattern, length=16)
bg.export_midi(pm, project_dir / "bassline.mid")
return project_dir
@click.group()
@click.version_option(version="0.2.0", prog_name="funklab")
def cli():
"""FunkLab - Ferramenta de automação para produção de beats e grooves."""
pass
@cli.command()
@click.option("--bpm", default=None, type=float, help="BPM (usa preset se omitido)")
@click.option("--style", default="mandelao", help="Estilo/preset (mandelao, funk130, funk-techhouse, phonk, etc.)")
@click.option("--name", default=None, help="Nome do projeto (gera automaticamente se omitido)")
@click.option("--no-humanize", is_flag=True, help="Desativa humanização de timing/velocity")
@click.option("--no-ghost-notes", is_flag=True, help="Desativa ghost notes")
@click.option("--velocity-variation", type=click.Choice(["off", "light", "medium"]), default=None, help="Variação de velocity")
@click.option("--slide-intensity", type=click.Choice(["off", "light", "medium"]), default=None, help="Intensidade de slides no bass")
def new(
bpm: float | None,
style: str,
name: str | None,
no_humanize: bool,
no_ghost_notes: bool,
velocity_variation: str | None,
slide_intensity: str | None,
):
"""Gera novo projeto em projects/ com grooves e arranjo. Usa presets quando style corresponde."""
try:
from core.musicality import MusicalityParams
from library.presets_util import resolve_preset_params
preset_bpm, structure, groove_names, bass_names, musicality = resolve_preset_params(
style, bpm_override=bpm
)
if no_humanize or no_ghost_notes or velocity_variation is not None or slide_intensity is not None:
musicality = MusicalityParams(
humanize=not no_humanize,
ghost_notes=not no_ghost_notes,
velocity_variation="off" if no_humanize else (velocity_variation or musicality.velocity_variation),
slide_intensity=slide_intensity or musicality.slide_intensity,
preset_name=style,
)
groove_name = groove_names[0]
bass_pattern = bass_names[0]
if name is None:
name = f"project_{style}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
project_dir = _create_single_project(
bpm=preset_bpm,
style=style,
project_name=name,
output_dir=PROJECT_ROOT / "projects",
groove_name=groove_name,
bass_pattern=bass_pattern,
structure_override=structure,
musicality_params=musicality,
)
click.echo(f"✓ Projeto criado em: {project_dir}")
click.echo(f"✓ Bassline gerada: {project_dir / 'bassline.mid'}")
except ImportError as e:
click.echo(f"Erro de dependência: {e}. Execute: pip install -r requirements.txt", err=True)
raise click.Abort()
except Exception as e:
click.echo(f"Erro: {e}", err=True)
raise click.Abort()
@cli.command()
@click.argument("audio_file", type=click.Path(exists=True))
@click.option("--name", default=None, help="Nome do groove (usa sugestão automática se omitido)")
@click.option("--save/--no-save", default=True, help="Salvar em library/grooves.json")
@click.option("--aubio/--librosa", default=False, help="Usar aubio para detecção de BPM")
@click.option("--json-output", "json_output", is_flag=True, help="Saída em JSON estruturado")
@click.option("--no-hits", is_flag=True, help="Omitir estimativa de hits (kick/clap/hat)")
def analyze(
audio_file: str,
name: str | None,
save: bool,
aubio: bool,
json_output: bool,
no_hits: bool,
):
"""Analisa groove de referência. Saída simples ou JSON estruturado para a biblioteca."""
try:
from core.groove_analyzer import GrooveAnalyzer
from library.patterns_util import load_grooves, save_grooves
analyzer = GrooveAnalyzer()
result = analyzer.analyze_detailed(
audio_file,
name=name,
use_aubio_bpm=aubio,
include_hits=not no_hits,
)
if name:
result["name"] = name
if json_output:
output = {k: v for k, v in result.items() if v is not None}
click.echo(json.dumps(output, indent=2, ensure_ascii=False))
else:
click.echo(f"BPM: {result['bpm']}")
click.echo(f"Swing: {result['swing']:.3f}")
click.echo(f"Densidade: {result['density']}")
click.echo(f"Padrão: {result['pattern']}")
click.echo(f"Sugestão de nome: {result['name']}")
if "hits" in result:
click.echo(f"Hits (steps): kick={result['hits']['kick']} clap={result['hits']['clap']} hat={result['hits']['hat']}")
if save:
data = load_grooves()
groove_entry: dict = {
"pattern": result["pattern"],
"tags": [],
"description": f"Extraído de {audio_file}",
"bpm": result["bpm"],
"swing": result["swing"],
"density": result["density"],
}
if "hits" in result:
groove_entry["hits"] = result["hits"]
data.setdefault("grooves", {})[result["name"]] = groove_entry
save_grooves(data)
msg = f"✓ Salvo em library/grooves.json como '{result['name']}'"
click.echo(msg, err=json_output)
except ImportError as e:
click.echo(f"Erro de dependência: {e}. Execute: pip install -r requirements.txt", err=True)
raise click.Abort()
except Exception as e:
click.echo(f"Erro: {e}", err=True)
raise click.Abort()
@cli.command()
@click.option("--key", default="C", help="Tonalidade (C, D, E, F, G, A, B)")
@click.option("--length", default=16, type=int, help="Comprimento em steps (16 = 1 barra)")
@click.option("--pattern", default="mandelao_root", help="Padrão da biblioteca")
@click.option("--output", "-o", default=None, help="Arquivo de saída MIDI")
@click.option("--bpm", default=120, type=float, help="BPM")
@click.option("--no-humanize", is_flag=True, help="Desativa humanização")
@click.option("--slide-intensity", type=click.Choice(["off", "light", "medium"]), default="light", help="Intensidade de slides")
def bassline(
key: str,
length: int,
pattern: str,
output: str | None,
bpm: float,
no_humanize: bool,
slide_intensity: str,
):
"""Gera linha de baixo MIDI com humanização e slides opcionais."""
try:
from core.bass_generator import BassGenerator
from core.musicality import MusicalityParams
musicality = MusicalityParams.off() if no_humanize else MusicalityParams(
humanize=True, ghost_notes=True, velocity_variation="light",
slide_intensity=slide_intensity, preset_name="",
)
bg = BassGenerator(bpm=bpm, musicality=musicality)
pm = bg.generate_from_pattern(key=key, pattern_name=pattern, length=length)
out_path = Path(output) if output else PROJECT_ROOT / "projects" / "bassline.mid"
out_path.parent.mkdir(parents=True, exist_ok=True)
bg.export_midi(pm, out_path)
click.echo(f"✓ Bassline gerada: {out_path}")
except ImportError as e:
click.echo(f"Erro de dependência: {e}. Execute: pip install -r requirements.txt", err=True)
raise click.Abort()
except Exception as e:
click.echo(f"Erro: {e}", err=True)
raise click.Abort()
@cli.command()
@click.option("--style", default="mandelao", help="Estilo/preset (mandelao, funk130, funk-techhouse, phonk, etc.)")
@click.option("--bpm", default=None, type=float, help="BPM (usa preset se omitido)")
@click.option("--count", default=10, type=int, help="Número de projetos a gerar")
def batch(style: str, bpm: float | None, count: int):
"""Gera múltiplos projetos em lote. Usa presets quando style corresponde."""
try:
from library.presets_util import resolve_preset_params
preset_bpm, structure, groove_names, bass_names, musicality = resolve_preset_params(
style, bpm_override=bpm
)
bpm_val = preset_bpm
batch_name = f"batch_{style}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
batch_dir = PROJECT_ROOT / "projects" / batch_name
batch_dir.mkdir(parents=True, exist_ok=True)
manifest_entries, manifest_path = _run_batch_generation(
style=style,
bpm=bpm_val,
count=count,
output_dir=batch_dir,
musicality=musicality,
structure=structure,
groove_names=groove_names,
bass_names=bass_names,
extra_manifest={"batch_name": batch_name},
)
click.echo(f"\n✓ Batch gerado: {batch_dir}")
click.echo(f"✓ Manifest: {manifest_path}")
except ImportError as e:
click.echo(f"Erro de dependência: {e}. Execute: pip install -r requirements.txt", err=True)
raise click.Abort()
except Exception as e:
click.echo(f"Erro: {e}", err=True)
raise click.Abort()
def _run_batch_generation(
style: str,
bpm: float,
count: int,
output_dir: Path,
musicality: "MusicalityParams",
structure: list[dict],
groove_names: list[str],
bass_names: list[str],
extra_manifest: dict | None = None,
) -> tuple[list[ProjectManifestEntry], Path]:
"""Gera projetos em lote. Retorna (manifest_entries, manifest_path)."""
groove_cycle = itertools.cycle(groove_names)
bass_cycle = itertools.cycle(bass_names)
manifest_entries: list[ProjectManifestEntry] = []
for i in range(1, count + 1):
project_name = f"project_{i:03d}"
groove_name = next(groove_cycle)
bass_pattern = next(bass_cycle)
created_at = datetime.now().isoformat()
_create_single_project(
bpm=bpm,
style=style,
project_name=project_name,
output_dir=output_dir,
groove_name=groove_name,
bass_pattern=bass_pattern,
structure_override=structure,
musicality_params=musicality,
)
manifest_entries.append(ProjectManifestEntry(
project_name=project_name,
bpm=bpm,
style=style,
groove_used=groove_name,
bass_pattern_used=bass_pattern,
created_at=created_at,
))
click.echo(f" ✓ {project_name} (groove={groove_name}, bass={bass_pattern})")
manifest_path = output_dir / "manifest.json"
manifest_data = {
"style": style,
"bpm": bpm,
"count": count,
**(extra_manifest or {}),
"projects": [
{
"project_name": e.project_name,
"bpm": e.bpm,
"style": e.style,
"groove_used": e.groove_used,
"bass_pattern_used": e.bass_pattern_used,
"created_at": e.created_at,
}
for e in manifest_entries
],
}
with open(manifest_path, "w", encoding="utf-8") as f:
json.dump(manifest_data, f, indent=2, ensure_ascii=False)
return manifest_entries, manifest_path
def _build_session_markdown(
session_name: str,
style: str,
bpm: float,
count: int,
manifest_entries: list[ProjectManifestEntry],
grooves_used: list[str],
bass_used: list[str],
) -> str:
"""Constrói resumo markdown da sessão para seleção posterior."""
lines = [
f"# Sessão: {session_name}",
"",
"## Resumo",
"",
f"- **Estilo:** {style}",
f"- **BPM:** {bpm}",
f"- **Projetos gerados:** {count}",
"",
"## Grooves utilizados",
"",
]
for g in grooves_used:
lines.append(f"- {g}")
lines.extend(["", "## Basslines utilizadas", ""])
for b in bass_used:
lines.append(f"- {b}")
lines.extend([
"",
"## Projetos",
"",
"Marque com `[x]` os que deseja trabalhar depois:",
"",
])
for e in manifest_entries:
lines.append(f"- [ ] **{e.project_name}** — groove: `{e.groove_used}` | bass: `{e.bass_pattern_used}`")
lines.extend(["", "---", "_Gerado pelo FunkLab_"])
return "\n".join(lines)
@cli.command()
@click.option("--style", default="mandelao", help="Estilo/preset (mandelao, funk130, funk-techhouse, phonk, etc.)")
@click.option("--bpm", default=None, type=float, help="BPM (usa preset se omitido)")
@click.option("--count", default=8, type=int, help="Número de projetos a gerar")
def session(style: str, bpm: float | None, count: int):
"""Cria sessão com múltiplos projetos e resumo markdown para seleção posterior."""
try:
from library.presets_util import resolve_preset_params
preset_bpm, structure, groove_names, bass_names, musicality = resolve_preset_params(
style, bpm_override=bpm
)
bpm_val = preset_bpm
session_name = f"session_{style}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
session_dir = PROJECT_ROOT / "projects" / session_name
session_dir.mkdir(parents=True, exist_ok=True)
manifest_entries, manifest_path = _run_batch_generation(
style=style,
bpm=bpm_val,
count=count,
output_dir=session_dir,
musicality=musicality,
structure=structure,
groove_names=groove_names,
bass_names=bass_names,
extra_manifest={
"session_name": session_name,
"created_at": datetime.now().isoformat(),
},
)
# Resumo markdown
grooves_used = sorted({e.groove_used for e in manifest_entries})
bass_used = sorted({e.bass_pattern_used for e in manifest_entries})
session_md = _build_session_markdown(
session_name=session_name,
style=style,
bpm=bpm_val,
count=count,
manifest_entries=manifest_entries,
grooves_used=grooves_used,
bass_used=bass_used,
)
session_md_path = session_dir / "SESSION.md"
session_md_path.write_text(session_md, encoding="utf-8")
click.echo(f"\n✓ Sessão criada: {session_dir}")
click.echo(f"✓ Manifest: {manifest_path}")
click.echo(f"✓ Resumo: {session_md_path}")
except ImportError as e:
click.echo(f"Erro de dependência: {e}. Execute: pip install -r requirements.txt", err=True)
raise click.Abort()
except Exception as e:
click.echo(f"Erro: {e}", err=True)
raise click.Abort()
@cli.command("organize-samples")
@click.option("--src", default="samples_raw", help="Pasta de origem")
@click.option("--dst", default="samples", help="Pasta de destino")
@click.option("--dry-run", is_flag=True, help="Apenas mostrar o que seria feito")
def organize_samples(src: str, dst: str, dry_run: bool):
"""Organiza samples: normaliza volume, renomeia e agrupa por categoria."""
try:
from sample_organizer import SampleOrganizer
src_path = PROJECT_ROOT / src
dst_path = PROJECT_ROOT / dst
if not src_path.exists():
click.echo(f"Pasta de origem não existe: {src_path}. Crie e adicione samples.", err=True)
raise click.Abort()
org = SampleOrganizer(src_path, dst_path)
result = org.organize(dry_run=dry_run)
click.echo(f"✓ {result['processed']} arquivos processados")
if dry_run:
click.echo("(dry-run - nada foi alterado)")
except ImportError as e:
click.echo(f"Erro: {e}. Verifique se sample_organizer.py existe.", err=True)
raise click.Abort()
except Exception as e:
click.echo(f"Erro: {e}", err=True)
raise click.Abort()
if __name__ == "__main__":
cli()