cambridge-dictionary-audio 0.2.1__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.
@@ -0,0 +1 @@
1
+ """Cambridge Dictionary pronunciation downloader."""
@@ -0,0 +1,6 @@
1
+ """Run the CLI with python -m cambridge_audio."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
@@ -0,0 +1,153 @@
1
+ """Phrase synthesis and playback through system audio tools."""
2
+
3
+ import os
4
+ import shutil
5
+ import subprocess
6
+ import sys
7
+ from collections.abc import Callable
8
+ from pathlib import Path
9
+ from tempfile import TemporaryDirectory
10
+ from threading import Event
11
+
12
+ from .dictionary import CambridgeClient, CambridgeError, normalize_word, save_mp3
13
+ from .i18n import translate
14
+
15
+ _MACOS_FFMPEG_DIRS = (Path("/opt/homebrew/bin"), Path("/usr/local/bin"))
16
+
17
+
18
+ def ffmpeg_executable() -> str | None:
19
+ if getattr(sys, "frozen", False):
20
+ root = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parents[1]))
21
+ bundled = root / "tools" / ("ffmpeg.exe" if sys.platform == "win32" else "ffmpeg")
22
+ if bundled.is_file() and os.access(bundled, os.X_OK):
23
+ return str(bundled)
24
+ executable = shutil.which("ffmpeg")
25
+ if executable or sys.platform != "darwin":
26
+ return executable
27
+ # Finder launches do not inherit the shell's Homebrew PATH.
28
+ for directory in _MACOS_FFMPEG_DIRS:
29
+ candidate = directory / "ffmpeg"
30
+ if candidate.is_file() and os.access(candidate, os.X_OK):
31
+ return str(candidate)
32
+ return None
33
+
34
+
35
+ def combine_phrase(
36
+ client: CambridgeClient,
37
+ phrase: str,
38
+ accent: str,
39
+ destination: Path,
40
+ *,
41
+ overwrite: bool = False,
42
+ check_cancelled: Callable[[], None] | None = None,
43
+ ) -> Path:
44
+ words = normalize_word(phrase, client.language).split()
45
+ if len(words) < 2:
46
+ raise CambridgeError(
47
+ translate("Combining requires a phrase with at least two words.", client.language)
48
+ )
49
+ ffmpeg = ffmpeg_executable()
50
+ if ffmpeg is None:
51
+ raise CambridgeError(
52
+ translate("Install FFmpeg and add it to PATH to combine a phrase.", client.language)
53
+ )
54
+ if destination.exists() and not overwrite:
55
+ raise FileExistsError(
56
+ translate(
57
+ "File already exists: {path}. Use --overwrite to replace it.",
58
+ client.language,
59
+ path=destination,
60
+ )
61
+ )
62
+ with TemporaryDirectory(prefix="cambridge-audio-") as directory:
63
+ temporary = Path(directory)
64
+ for index, word in enumerate(words):
65
+ if check_cancelled:
66
+ check_cancelled()
67
+ client.download(client.lookup(word), accent, temporary / f"{index}.mp3")
68
+ manifest = temporary / "inputs.txt"
69
+ manifest.write_text(
70
+ "".join(f"file '{index}.mp3'\n" for index in range(len(words))), encoding="utf-8"
71
+ )
72
+ output = temporary / "combined.mp3"
73
+ if check_cancelled:
74
+ check_cancelled()
75
+ try:
76
+ subprocess.run(
77
+ [
78
+ ffmpeg,
79
+ "-nostdin",
80
+ "-loglevel",
81
+ "error",
82
+ "-f",
83
+ "concat",
84
+ "-safe",
85
+ "1",
86
+ "-i",
87
+ str(manifest),
88
+ "-af",
89
+ "loudnorm",
90
+ "-c:a",
91
+ "libmp3lame",
92
+ str(output),
93
+ ],
94
+ check=True,
95
+ capture_output=True,
96
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)
97
+ if sys.platform == "win32"
98
+ else 0,
99
+ )
100
+ except subprocess.CalledProcessError as exc:
101
+ raise CambridgeError(f"FFmpeg: {exc.stderr.decode(errors='replace').strip()}") from exc
102
+ return save_mp3(
103
+ output.read_bytes(), destination, overwrite=overwrite, language=client.language
104
+ )
105
+
106
+
107
+ def play_audio(path: Path, language: str = "en", *, stop: Event | None = None) -> None:
108
+ path = path.resolve()
109
+ if sys.platform == "win32":
110
+ os.startfile(str(path))
111
+ return
112
+ player = shutil.which("afplay" if sys.platform == "darwin" else "ffplay")
113
+ if player is None:
114
+ raise CambridgeError(
115
+ translate(
116
+ "Audio player not found: afplay (macOS) or ffplay (Linux) is required.", language
117
+ )
118
+ )
119
+ command = [player, str(path)]
120
+ if sys.platform != "darwin":
121
+ command = [player, "-nodisp", "-autoexit", "-loglevel", "error", str(path)]
122
+ if stop is not None:
123
+ if stop.is_set():
124
+ return
125
+ # A terminal workspace owns its player so it can stop it on request or quit.
126
+ # Keep child output away from the terminal's alternate screen.
127
+ with subprocess.Popen(
128
+ command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
129
+ ) as process:
130
+ try:
131
+ while not stop.is_set():
132
+ try:
133
+ code = process.wait(timeout=0.1)
134
+ except subprocess.TimeoutExpired:
135
+ continue
136
+ if code:
137
+ raise CambridgeError(
138
+ translate("Could not play {path}.", language, path=path)
139
+ )
140
+ return
141
+ finally:
142
+ if process.poll() is None:
143
+ process.terminate()
144
+ try:
145
+ process.wait(timeout=2)
146
+ except subprocess.TimeoutExpired:
147
+ process.kill()
148
+ process.wait()
149
+ return
150
+ try:
151
+ subprocess.run(command, check=True)
152
+ except subprocess.CalledProcessError as exc:
153
+ raise CambridgeError(translate("Could not play {path}.", language, path=path)) from exc
cambridge_audio/cli.py ADDED
@@ -0,0 +1,276 @@
1
+ """Command-line and interactive Cambridge Dictionary audio downloader."""
2
+
3
+ import argparse
4
+ import math
5
+ import sys
6
+ from importlib.metadata import version
7
+ from pathlib import Path
8
+
9
+ from .audio import play_audio
10
+ from .console import Output, is_terminal
11
+ from .dictionary import (
12
+ CambridgeClient,
13
+ CambridgeError,
14
+ )
15
+ from .i18n import translate
16
+ from .library import save_metadata
17
+ from .service import Recording, download_recordings
18
+
19
+
20
+ class HelpFormatter(argparse.HelpFormatter):
21
+ def __init__(self, prog: str, language: str):
22
+ super().__init__(prog)
23
+ self.language = language
24
+
25
+ def add_usage(self, usage, actions, groups, prefix=None):
26
+ super().add_usage(usage, actions, groups, prefix or translate("usage: ", self.language))
27
+
28
+
29
+ class ArgumentParser(argparse.ArgumentParser):
30
+ def __init__(self, language: str, **kwargs):
31
+ self.language = language
32
+ super().__init__(
33
+ formatter_class=lambda prog: HelpFormatter(prog, language),
34
+ add_help=False,
35
+ allow_abbrev=False,
36
+ **kwargs,
37
+ )
38
+
39
+ def error(self, message):
40
+ self.print_usage(sys.stderr)
41
+ self.exit(
42
+ 2, translate("{prog}: error: {error}\n", self.language, prog=self.prog, error=message)
43
+ )
44
+
45
+
46
+ def positive_timeout(value: str, language: str = "en") -> float:
47
+ try:
48
+ timeout = float(value)
49
+ except ValueError as exc:
50
+ raise argparse.ArgumentTypeError(
51
+ translate("Timeout must be a positive finite number.", language)
52
+ ) from exc
53
+ if not math.isfinite(timeout) or timeout <= 0:
54
+ raise argparse.ArgumentTypeError(
55
+ translate("Timeout must be a positive finite number.", language)
56
+ )
57
+ return timeout
58
+
59
+
60
+ def download_word(client: CambridgeClient, word: str, args, downloaded: set[Path]) -> None:
61
+ output = Output(args.lang, plain=args.plain)
62
+
63
+ def saved(recording: Recording) -> None:
64
+ downloaded.add(recording.path)
65
+ if recording.combined:
66
+ output.message(
67
+ translate(
68
+ "{accent}: combined from individual word recordings",
69
+ args.lang,
70
+ accent=recording.accent.upper(),
71
+ )
72
+ )
73
+ else:
74
+ output.message(f"{recording.accent.upper()}: /{recording.ipa}/", style="bold cyan")
75
+ output.message(translate("Saved: {path}", args.lang, path=recording.path), style="dim")
76
+ store_details(recording)
77
+ if args.play:
78
+ try:
79
+ play_audio(recording.path, args.lang)
80
+ except (CambridgeError, OSError) as exc:
81
+ print(translate("Playback: {error}", args.lang, error=exc), file=sys.stderr)
82
+
83
+ def store_details(recording, translations=()):
84
+ try:
85
+ save_metadata(recording, translations, args.translation)
86
+ except OSError as exc:
87
+ print(
88
+ translate("Audio saved. Details could not be saved: {error}", args.lang, error=exc),
89
+ file=sys.stderr,
90
+ )
91
+
92
+ with output.working():
93
+ result = download_recordings(
94
+ client,
95
+ word,
96
+ args.output_dir,
97
+ args.accent,
98
+ overwrite=args.overwrite,
99
+ combine=args.combine,
100
+ translation=args.translation,
101
+ on_recording=saved,
102
+ )
103
+ for recording in result.recordings:
104
+ store_details(recording, result.translations)
105
+ output.details(result.recordings[0].word, result.recordings[0].definition, result.translations)
106
+ if result.translation_error:
107
+ print(
108
+ translate("Translation: {error}", args.lang, error=result.translation_error),
109
+ file=sys.stderr,
110
+ )
111
+
112
+
113
+ def interactive(client: CambridgeClient, args) -> int:
114
+ downloaded: set[Path] = set()
115
+ print(
116
+ translate(
117
+ "Enter a word or phrase. /m: playback, /r: delete this session's files, /q: quit.",
118
+ args.lang,
119
+ )
120
+ )
121
+ while True:
122
+ try:
123
+ word = input("> ").strip()
124
+ if not word:
125
+ continue
126
+ if word == "/q":
127
+ return 0
128
+ if word == "/m":
129
+ args.play = not args.play
130
+ print(
131
+ translate("Playback enabled." if args.play else "Playback disabled.", args.lang)
132
+ )
133
+ continue
134
+ if word == "/r":
135
+ for path in tuple(downloaded):
136
+ path.unlink(missing_ok=True)
137
+ path.with_suffix(".json").unlink(missing_ok=True)
138
+ downloaded.remove(path)
139
+ print(translate("Files downloaded in this session have been deleted.", args.lang))
140
+ continue
141
+ download_word(client, word, args, downloaded)
142
+ except (CambridgeError, OSError, ValueError) as exc:
143
+ print(translate("Error: {error}", args.lang, error=exc), file=sys.stderr)
144
+ except (EOFError, KeyboardInterrupt):
145
+ print()
146
+ return 0
147
+
148
+
149
+ def main(argv: list[str] | None = None) -> int:
150
+ if sys.platform == "win32":
151
+ # Preserve IPA and Russian text when Windows output is redirected as well.
152
+ for stream in (sys.stdout, sys.stderr):
153
+ if hasattr(stream, "reconfigure"):
154
+ stream.reconfigure(encoding="utf-8")
155
+ language_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)
156
+ language_parser.add_argument("--lang", choices=("en", "ru"), default="en")
157
+ language = language_parser.parse_known_args(argv)[0].lang
158
+ parser = ArgumentParser(
159
+ language,
160
+ description=translate(
161
+ "Download US or UK pronunciation audio from Cambridge Dictionary.", language
162
+ ),
163
+ )
164
+ arguments = parser.add_argument_group(translate("Arguments", language))
165
+ options = parser.add_argument_group(translate("Options", language))
166
+ arguments.add_argument(
167
+ "word",
168
+ nargs="*",
169
+ help=translate("Word or phrase; omit to start interactive mode.", language),
170
+ )
171
+ options.add_argument(
172
+ "-h", "--help", action="help", help=translate("Show this help message and exit.", language)
173
+ )
174
+ options.add_argument(
175
+ "--version",
176
+ action="version",
177
+ version=version("cambridge-dictionary-audio"),
178
+ help=translate("Show version and exit.", language),
179
+ )
180
+ modes = options.add_mutually_exclusive_group()
181
+ modes.add_argument(
182
+ "--plain",
183
+ action="store_true",
184
+ help=translate("Use plain output and the line-based interactive prompt.", language),
185
+ )
186
+ modes.add_argument(
187
+ "--tui",
188
+ action="store_true",
189
+ help=translate("Open the terminal workspace (requires an interactive terminal).", language),
190
+ )
191
+ options.add_argument(
192
+ "--lang",
193
+ choices=("en", "ru"),
194
+ default=language,
195
+ help=translate(
196
+ "Interface language (default: en); does not change dictionary translations.", language
197
+ ),
198
+ )
199
+ options.add_argument(
200
+ "--accent",
201
+ choices=("us", "uk", "both"),
202
+ default="us",
203
+ help=translate("Pronunciation accent (default: us).", language),
204
+ )
205
+ options.add_argument(
206
+ "--output-dir",
207
+ type=Path,
208
+ default=Path.cwd() / "downloads",
209
+ help=translate(
210
+ "Destination directory (default: downloads/ in the current directory).", language
211
+ ),
212
+ )
213
+ options.add_argument(
214
+ "--timeout",
215
+ type=lambda value: positive_timeout(value, language),
216
+ default=15.0,
217
+ help=translate("HTTP timeout in seconds (default: 15).", language),
218
+ )
219
+ options.add_argument(
220
+ "--play",
221
+ action=argparse.BooleanOptionalAction,
222
+ default=None,
223
+ help=translate("Play downloaded audio (enabled by default in interactive mode).", language),
224
+ )
225
+ options.add_argument(
226
+ "--overwrite", action="store_true", help=translate("Replace existing MP3 files.", language)
227
+ )
228
+ options.add_argument(
229
+ "--combine",
230
+ action=argparse.BooleanOptionalAction,
231
+ default=None,
232
+ help=translate(
233
+ "Combine missing phrases (enabled by default in interactive mode).", language
234
+ ),
235
+ )
236
+ options.add_argument(
237
+ "--translation",
238
+ help=translate(
239
+ "Cambridge translation language, e.g. russian; disabled by default.", language
240
+ ),
241
+ )
242
+ args = parser.parse_args(argv)
243
+ if args.tui and (args.word or not is_terminal()):
244
+ parser.error(translate("--tui requires a terminal and no word argument.", language))
245
+ if args.play is None:
246
+ args.play = not args.word
247
+ if args.combine is None:
248
+ args.combine = not args.word
249
+ if not args.word and not args.plain and is_terminal():
250
+ # Import lazily: scripts and desktop packaging do not initialize a TUI.
251
+ from .terminal import CambridgeApp, Options
252
+
253
+ CambridgeApp(
254
+ Options(
255
+ args.output_dir,
256
+ language=args.lang,
257
+ accent=args.accent,
258
+ play=args.play,
259
+ combine=args.combine,
260
+ translation=args.translation,
261
+ timeout=args.timeout,
262
+ overwrite=args.overwrite,
263
+ )
264
+ ).run()
265
+ return 0
266
+ with CambridgeClient(args.timeout, language=args.lang) as client:
267
+ if not args.word:
268
+ return interactive(client, args)
269
+ try:
270
+ download_word(client, " ".join(args.word), args, set())
271
+ except (CambridgeError, OSError, ValueError) as exc:
272
+ print(translate("Error: {error}", args.lang, error=exc), file=sys.stderr)
273
+ return 1
274
+ except KeyboardInterrupt:
275
+ return 130
276
+ return 0
@@ -0,0 +1,42 @@
1
+ """Readable terminal output with a plain fallback for pipes and older terminals."""
2
+
3
+ import os
4
+ import sys
5
+ from contextlib import nullcontext
6
+
7
+ from rich.console import Console
8
+ from rich.panel import Panel
9
+ from rich.text import Text
10
+
11
+ from .i18n import translate
12
+
13
+
14
+ def is_terminal() -> bool:
15
+ return sys.stdin.isatty() and sys.stdout.isatty() and os.environ.get("TERM") != "dumb"
16
+
17
+
18
+ class Output:
19
+ def __init__(self, language: str, *, plain: bool = False):
20
+ self.language = language
21
+ self.pretty = is_terminal() and not plain
22
+ self.console = Console(highlight=False)
23
+
24
+ def message(self, message: str, *, style: str = "") -> None:
25
+ if self.pretty:
26
+ self.console.print(Text(message, style=style))
27
+ else:
28
+ print(message)
29
+
30
+ def working(self):
31
+ if self.pretty:
32
+ return self.console.status(translate("Downloading...", self.language), spinner="dots")
33
+ return nullcontext()
34
+
35
+ def details(self, word: str, definition: str, translations: tuple[str, ...]) -> None:
36
+ content = "\n\n".join(value for value in (definition, "\n".join(translations)) if value)
37
+ if self.pretty and content:
38
+ self.console.print(
39
+ Panel(Text(content), title=Text(word), border_style="cyan", padding=1)
40
+ )
41
+ elif content:
42
+ print("\n".join(value for value in (definition, "\n".join(translations)) if value))