canturia 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
canturia/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Canturía — words into a song, rendered by your own ACE-Step server."""
2
+
3
+ __version__ = "0.1.0"
canturia/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from canturia.cli import app
2
+
3
+ if __name__ == "__main__":
4
+ app()
canturia/cli.py ADDED
@@ -0,0 +1,511 @@
1
+ """Canturía CLI: `canturia "lyrics"`, `canturia describe "a topic"`,
2
+ `canturia serve`, and `canturia health`."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ import secrets
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import typer
13
+ from rich.console import Console
14
+ from rich.table import Table
15
+ from typer.core import TyperGroup
16
+
17
+ from canturia import __version__
18
+ from canturia.config import (
19
+ ConfigurationError,
20
+ load_config,
21
+ resolve_serve_settings,
22
+ resolve_settings,
23
+ save_example_config,
24
+ )
25
+ from canturia.core import (
26
+ DURATION_MAX,
27
+ DURATION_MIN,
28
+ generate,
29
+ health,
30
+ save_song,
31
+ )
32
+ from canturia.providers import AceStepError
33
+
34
+ console = Console()
35
+ err_console = Console(stderr=True, style="bold red")
36
+
37
+
38
+ class DefaultCommandGroup(TyperGroup):
39
+ """Route bare invocations to `generate` so `canturia "lyrics"` works."""
40
+
41
+ default_command = "generate"
42
+ _root_tokens = {"-h", "--help", "-V", "--version"}
43
+
44
+ def parse_args(self, ctx: Any, args: list[str]) -> list[str]:
45
+ if args and args[0] not in self.commands and args[0] not in self._root_tokens:
46
+ args = [self.default_command, *args]
47
+ return super().parse_args(ctx, args)
48
+
49
+
50
+ app = typer.Typer(
51
+ cls=DefaultCommandGroup,
52
+ add_completion=False,
53
+ no_args_is_help=True,
54
+ context_settings={"help_option_names": ["-h", "--help"]},
55
+ )
56
+
57
+
58
+ def _version_callback(value: bool) -> None:
59
+ if value:
60
+ console.print(f"canturia {__version__}")
61
+ raise typer.Exit()
62
+
63
+
64
+ @app.callback()
65
+ def root(
66
+ version: bool = typer.Option(
67
+ False,
68
+ "--version",
69
+ "-V",
70
+ callback=_version_callback,
71
+ is_eager=True,
72
+ help="Print version and exit.",
73
+ ),
74
+ ) -> None:
75
+ """Canturía — words into a song, rendered by your own ACE-Step server."""
76
+ del version
77
+
78
+
79
+ def _read_lyrics(source: str) -> str:
80
+ if source == "-":
81
+ return sys.stdin.read()
82
+ path = Path(source).expanduser()
83
+ if not path.exists():
84
+ raise ValueError(f"Lyrics file not found: {source}")
85
+ return path.read_text(encoding="utf-8")
86
+
87
+
88
+ def _apply_overrides(
89
+ cfg: dict[str, Any],
90
+ *,
91
+ base_url: str | None,
92
+ api_key: str | None,
93
+ username: str | None,
94
+ password: str | None,
95
+ timeout: float | None,
96
+ ) -> None:
97
+ if base_url:
98
+ cfg["base_url"] = base_url
99
+ if api_key:
100
+ cfg["api_key"] = api_key
101
+ if username:
102
+ cfg["username"] = username
103
+ if password:
104
+ cfg["password"] = password
105
+ if timeout is not None:
106
+ cfg["timeout"] = timeout
107
+
108
+
109
+ def _connection_options(
110
+ *,
111
+ base_url: str | None,
112
+ api_key: str | None,
113
+ username: str | None,
114
+ password: str | None,
115
+ config: str | None,
116
+ timeout: float | None = None,
117
+ ) -> dict[str, Any]:
118
+ """Load config and apply the connection flags shared by commands."""
119
+ cfg = load_config(config)
120
+ _apply_overrides(
121
+ cfg,
122
+ base_url=base_url,
123
+ api_key=api_key,
124
+ username=username,
125
+ password=password,
126
+ timeout=timeout,
127
+ )
128
+ return cfg
129
+
130
+
131
+ def _run_generate(
132
+ mode: str,
133
+ text: str,
134
+ *,
135
+ genre: str | None,
136
+ style: str | None,
137
+ duration: float | None,
138
+ out: str | None,
139
+ config: str | None,
140
+ base_url: str | None,
141
+ api_key: str | None,
142
+ username: str | None,
143
+ password: str | None,
144
+ timeout: float | None,
145
+ ) -> None:
146
+ cfg = _connection_options(
147
+ base_url=base_url,
148
+ api_key=api_key,
149
+ username=username,
150
+ password=password,
151
+ config=config,
152
+ timeout=timeout,
153
+ )
154
+ settings = resolve_settings(cfg)
155
+
156
+ with console.status("Submitting to ACE-Step…", spinner="dots") as status:
157
+ generation = generate(
158
+ mode,
159
+ text,
160
+ settings,
161
+ genre=genre,
162
+ style=style,
163
+ duration=duration,
164
+ on_progress=lambda message: status.update(f"Generating… {message}"),
165
+ )
166
+
167
+ for song in generation.songs:
168
+ path, sidecar = save_song(generation, song, out)
169
+ console.print(f"Saved: [bold green]{path}[/bold green]")
170
+ console.print(f" metadata: [dim]{sidecar}[/dim]")
171
+
172
+
173
+ def generate_cmd(
174
+ text: str | None = typer.Argument(
175
+ None,
176
+ help="Lyrics to sing. Use [Verse]/[Chorus] tags for structure.",
177
+ show_default=False,
178
+ ),
179
+ lyrics_file: str | None = typer.Option(
180
+ None,
181
+ "--lyrics-file",
182
+ "-f",
183
+ help="Read lyrics from a file ('-' for stdin).",
184
+ show_default=False,
185
+ ),
186
+ genre: str | None = typer.Option(
187
+ None,
188
+ "--genre",
189
+ "-g",
190
+ help="Genre key (folk, pop, rock, indie, lofi, hiphop, …) or free text.",
191
+ show_default=False,
192
+ ),
193
+ style: str | None = typer.Option(
194
+ None,
195
+ "--style",
196
+ "-s",
197
+ help="Extra style details, e.g. 'warm female vocals, fingerpicked guitar'.",
198
+ show_default=False,
199
+ ),
200
+ duration: float | None = typer.Option(
201
+ None,
202
+ "--duration",
203
+ "-t",
204
+ min=DURATION_MIN,
205
+ max=DURATION_MAX,
206
+ help=f"Length in seconds ({int(DURATION_MIN)}–{int(DURATION_MAX)}).",
207
+ show_default=False,
208
+ ),
209
+ out: str | None = typer.Option(
210
+ None,
211
+ "--out",
212
+ "-o",
213
+ help="Output file (default: derived from the genre and words).",
214
+ show_default=False,
215
+ ),
216
+ config: str | None = typer.Option(
217
+ None, "--config", "-c", help="Config file (default: ./canturia.yaml).",
218
+ show_default=False,
219
+ ),
220
+ base_url: str | None = typer.Option(
221
+ None, "--base-url", help="ACE-Step URL (overrides config).",
222
+ show_default=False,
223
+ ),
224
+ api_key: str | None = typer.Option(
225
+ None, "--api-key", help="Bearer token for ACE-Step.",
226
+ show_default=False,
227
+ ),
228
+ username: str | None = typer.Option(
229
+ None, "--username", help="HTTP Basic username (reverse proxy).",
230
+ show_default=False,
231
+ ),
232
+ password: str | None = typer.Option(
233
+ None, "--password", help="HTTP Basic password (reverse proxy).",
234
+ show_default=False,
235
+ ),
236
+ timeout: float | None = typer.Option(
237
+ None, "--timeout", help="Overall generation timeout in seconds.",
238
+ show_default=False,
239
+ ),
240
+ init_config: bool = typer.Option(
241
+ False, "--init-config", help="Write an example ./canturia.yaml and exit."
242
+ ),
243
+ ) -> None:
244
+ """Turn lyrics into a song (the default command).
245
+
246
+ Configure once in ~/.canturia.yaml (server URL and optional auth), then:
247
+
248
+ canturia "[Verse]\\nMorning light...\\n[Chorus]\\nGrow a little every day" -g folk
249
+
250
+ For a topic, use `canturia describe "a song about growing up by the sea"`.
251
+ """
252
+ try:
253
+ if init_config:
254
+ path = save_example_config()
255
+ console.print(f"Wrote example config: [bold]{path}[/bold]")
256
+ raise typer.Exit()
257
+
258
+ if lyrics_file and text:
259
+ err_console.print("Give lyrics or --lyrics-file, not both.")
260
+ raise typer.Exit(code=2)
261
+ source = _read_lyrics(lyrics_file) if lyrics_file else (text or "")
262
+ if not source.strip():
263
+ err_console.print(
264
+ 'Give me lyrics, e.g.: canturia "[Verse]\\nA line..." -g folk'
265
+ )
266
+ raise typer.Exit(code=2)
267
+
268
+ _run_generate(
269
+ "lyrics",
270
+ source,
271
+ genre=genre,
272
+ style=style,
273
+ duration=duration,
274
+ out=out,
275
+ config=config,
276
+ base_url=base_url,
277
+ api_key=api_key,
278
+ username=username,
279
+ password=password,
280
+ timeout=timeout,
281
+ )
282
+ except (ConfigurationError, AceStepError, ValueError) as e:
283
+ err_console.print(str(e))
284
+ raise typer.Exit(code=1) from None
285
+
286
+
287
+ # Register the command under the name `generate` while keeping the function
288
+ # name usable in tests.
289
+ app.command(name="generate")(generate_cmd)
290
+
291
+
292
+ @app.command()
293
+ def describe(
294
+ topic: str = typer.Argument(
295
+ ...,
296
+ help="A topic, theme, or sentence; ACE-Step writes the lyrics.",
297
+ ),
298
+ genre: str | None = typer.Option(
299
+ None,
300
+ "--genre",
301
+ "-g",
302
+ help="Genre key (folk, pop, rock, indie, lofi, hiphop, …) or free text.",
303
+ show_default=False,
304
+ ),
305
+ style: str | None = typer.Option(
306
+ None,
307
+ "--style",
308
+ "-s",
309
+ help="Extra style details, e.g. 'warm female vocals, fingerpicked guitar'.",
310
+ show_default=False,
311
+ ),
312
+ duration: float | None = typer.Option(
313
+ None,
314
+ "--duration",
315
+ "-t",
316
+ min=DURATION_MIN,
317
+ max=DURATION_MAX,
318
+ help=f"Length in seconds ({int(DURATION_MIN)}–{int(DURATION_MAX)}).",
319
+ show_default=False,
320
+ ),
321
+ out: str | None = typer.Option(
322
+ None,
323
+ "--out",
324
+ "-o",
325
+ help="Output file (default: derived from the genre and topic).",
326
+ show_default=False,
327
+ ),
328
+ config: str | None = typer.Option(
329
+ None, "--config", "-c", help="Config file (default: ./canturia.yaml).",
330
+ show_default=False,
331
+ ),
332
+ base_url: str | None = typer.Option(
333
+ None, "--base-url", help="ACE-Step URL (overrides config).",
334
+ show_default=False,
335
+ ),
336
+ api_key: str | None = typer.Option(
337
+ None, "--api-key", help="Bearer token for ACE-Step.",
338
+ show_default=False,
339
+ ),
340
+ username: str | None = typer.Option(
341
+ None, "--username", help="HTTP Basic username (reverse proxy).",
342
+ show_default=False,
343
+ ),
344
+ password: str | None = typer.Option(
345
+ None, "--password", help="HTTP Basic password (reverse proxy).",
346
+ show_default=False,
347
+ ),
348
+ timeout: float | None = typer.Option(
349
+ None, "--timeout", help="Overall generation timeout in seconds.",
350
+ show_default=False,
351
+ ),
352
+ ) -> None:
353
+ """Let ACE-Step write the lyrics from a topic (requires its LM).
354
+
355
+ The server must have `resident: true` (its 5Hz LM enabled). If it is off,
356
+ this command fails with the server's explanation; use plain lyrics instead.
357
+ """
358
+ try:
359
+ _run_generate(
360
+ "describe",
361
+ topic,
362
+ genre=genre,
363
+ style=style,
364
+ duration=duration,
365
+ out=out,
366
+ config=config,
367
+ base_url=base_url,
368
+ api_key=api_key,
369
+ username=username,
370
+ password=password,
371
+ timeout=timeout,
372
+ )
373
+ except (ConfigurationError, AceStepError, ValueError) as e:
374
+ err_console.print(str(e))
375
+ raise typer.Exit(code=1) from None
376
+
377
+
378
+ def health_cmd(
379
+ config: str | None = typer.Option(
380
+ None, "--config", "-c", help="Config file (default: ./canturia.yaml).",
381
+ show_default=False,
382
+ ),
383
+ base_url: str | None = typer.Option(
384
+ None, "--base-url", help="ACE-Step URL (overrides config).",
385
+ show_default=False,
386
+ ),
387
+ api_key: str | None = typer.Option(
388
+ None, "--api-key", help="Bearer token for ACE-Step.",
389
+ show_default=False,
390
+ ),
391
+ username: str | None = typer.Option(
392
+ None, "--username", help="HTTP Basic username (reverse proxy).",
393
+ show_default=False,
394
+ ),
395
+ password: str | None = typer.Option(
396
+ None, "--password", help="HTTP Basic password (reverse proxy).",
397
+ show_default=False,
398
+ ),
399
+ ) -> None:
400
+ """Show the configured server's model and lyrics-writer status."""
401
+ try:
402
+ cfg = _connection_options(
403
+ base_url=base_url,
404
+ api_key=api_key,
405
+ username=username,
406
+ password=password,
407
+ config=config,
408
+ )
409
+ settings = resolve_settings(cfg)
410
+ data = health(settings)
411
+ model = data.get("loaded_model") or "—"
412
+ loaded = "loaded" if data.get("models_initialized") else "not loaded"
413
+ writer = "on" if data.get("llm_initialized") else "off"
414
+ table = Table(show_header=False, box=None)
415
+ table.add_row("Server", str(settings["base_url"]))
416
+ table.add_row("Status", str(data.get("status") or "unknown"))
417
+ table.add_row("Model", f"{model} ({loaded})")
418
+ table.add_row("Lyrics writer", writer)
419
+ console.print(table)
420
+ if not data.get("llm_initialized"):
421
+ console.print(
422
+ "[yellow]Lyrics writer is off; paste lyrics to generate. "
423
+ "Set resident: true in puente.yml to enable describe mode.[/yellow]"
424
+ )
425
+ except (ConfigurationError, AceStepError, ValueError) as e:
426
+ err_console.print(str(e))
427
+ raise typer.Exit(code=1) from None
428
+
429
+
430
+ app.command(name="health")(health_cmd)
431
+
432
+
433
+ @app.command()
434
+ def serve(
435
+ host: str | None = typer.Option(
436
+ None, "--host", help="Address to bind (127.0.0.1 = local only).",
437
+ show_default=False,
438
+ ),
439
+ port: int | None = typer.Option(
440
+ None, "--port", help="Port to listen on (default: 2268).",
441
+ show_default=False,
442
+ ),
443
+ password: str | None = typer.Option(
444
+ None,
445
+ "--password",
446
+ help="Shared password for the web UI; generated when binding non-locally.",
447
+ show_default=False,
448
+ ),
449
+ out_dir: str | None = typer.Option(
450
+ None, "--out-dir", help="Directory Save writes songs into.",
451
+ show_default=False,
452
+ ),
453
+ config: str | None = typer.Option(
454
+ None, "--config", "-c", help="Config file (default: ./canturia.yaml).",
455
+ show_default=False,
456
+ ),
457
+ no_browser: bool = typer.Option(
458
+ False, "--no-browser", help="Don't auto-open the browser."
459
+ ),
460
+ ) -> None:
461
+ r"""Run the local web UI (needs: pip install 'canturia\[serve]')."""
462
+ import threading
463
+ import webbrowser
464
+
465
+ try:
466
+ import uvicorn
467
+
468
+ from canturia.serve import create_app
469
+ except ImportError:
470
+ err_console.print(
471
+ "The web UI needs extra dependencies: pip install 'canturia[serve]'"
472
+ )
473
+ raise typer.Exit(code=1) from None
474
+
475
+ try:
476
+ cfg = load_config(config)
477
+ serve_cfg = resolve_serve_settings(cfg)
478
+ except ConfigurationError as e:
479
+ err_console.print(str(e))
480
+ raise typer.Exit(code=1) from None
481
+
482
+ chosen_host = host or str(serve_cfg["host"])
483
+ chosen_port = port or int(serve_cfg["port"])
484
+ chosen_out = out_dir or str(serve_cfg["out_dir"])
485
+ chosen_password = (
486
+ password
487
+ if password is not None
488
+ else os.getenv("CANTURIA_SERVE_PASSWORD") or serve_cfg.get("password")
489
+ )
490
+ if chosen_password is not None and str(chosen_password).strip() == "":
491
+ chosen_password = None
492
+
493
+ local = chosen_host in ("127.0.0.1", "localhost", "::1")
494
+ if not local and not chosen_password:
495
+ chosen_password = secrets.token_urlsafe(12)
496
+ console.print(f"Generated password: [bold]{chosen_password}[/bold]")
497
+
498
+ application = create_app(
499
+ cfg,
500
+ password=str(chosen_password) if chosen_password else None,
501
+ out_dir=Path(chosen_out).expanduser(),
502
+ )
503
+
504
+ url = f"http://{chosen_host}:{chosen_port}/"
505
+ console.print(f"Canturía web UI: [bold green]{url}[/bold green] (Ctrl+C to stop)")
506
+ if chosen_password:
507
+ console.print(f"Password: [bold]{chosen_password}[/bold]")
508
+ if not no_browser and local:
509
+ threading.Timer(0.8, webbrowser.open, args=[url]).start()
510
+
511
+ uvicorn.run(application, host=chosen_host, port=chosen_port, log_level="warning")