pysubzone 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.
pysubzone/__init__.py ADDED
@@ -0,0 +1,53 @@
1
+ """PySubZone - search and download subtitles from subzone.ir.
2
+
3
+ Python API, CLI and TUI for the Subf2m subtitle database engine running on
4
+ subzone.ir, in the spirit of PyAddic7 (addic7ed.com).
5
+
6
+ Quick start::
7
+
8
+ from pysubzone import SubZoneClient
9
+
10
+ client = SubZoneClient()
11
+ title = client.search_exact("Dexter Resurrection")
12
+ versions = client.title_versions(title.slug, "farsi_persian")
13
+ client.download(versions[0], dest_dir=".", save_mode="extract")
14
+ """
15
+
16
+ from .client import SubZoneClient
17
+ from .exceptions import (
18
+ DownloadError,
19
+ InvalidURLError,
20
+ NetworkError,
21
+ NoSubtitleFoundError,
22
+ ParseError,
23
+ SubZoneError,
24
+ TitleNotFoundError,
25
+ )
26
+ from .models import (
27
+ BrowseEntry,
28
+ DownloadResult,
29
+ SubtitleDetails,
30
+ SubtitleVersion,
31
+ TitlePage,
32
+ TitleResult,
33
+ )
34
+
35
+ __version__ = "0.1.0"
36
+
37
+ __all__ = [
38
+ "SubZoneClient",
39
+ "SubZoneError",
40
+ "NetworkError",
41
+ "ParseError",
42
+ "TitleNotFoundError",
43
+ "NoSubtitleFoundError",
44
+ "DownloadError",
45
+ "InvalidURLError",
46
+ "TitleResult",
47
+ "TitlePage",
48
+ "SubtitleVersion",
49
+ "SubtitleDetails",
50
+ "DownloadResult",
51
+ "BrowseEntry",
52
+ "__version__",
53
+ ]
pysubzone/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Allow ``python -m pysubzone`` to launch the CLI."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
pysubzone/cli.py ADDED
@@ -0,0 +1,624 @@
1
+ """Typer + Rich command line interface for PySubZone.
2
+
3
+ Command shape follows PyAddic7's contract so other programs can consume
4
+ results: every command accepts ``--json`` and uses stable exit codes
5
+ (0 success, 1 nothing found, 2 error).
6
+
7
+ subz search dexter --json
8
+ subz versions dexter-resurrection-season-2 -l fa
9
+ subz download dexter-resurrection-season-2/farsi_persian/3770171
10
+ subz url https://subzone.ir/subtitles/the-odyssey-2026 -n 2
11
+ subz filename Dexter.Resurrection.S02E01.1080p.AMZN.WEB-DL-NTb.mkv
12
+ subz auto /media/shows --dry-run
13
+ subz tui
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import sys
20
+ from pathlib import Path
21
+ from typing import Any, Dict, List, Optional
22
+
23
+ import typer
24
+ from rich import box
25
+ from rich.console import Console
26
+ from rich.progress import (
27
+ BarColumn,
28
+ MofNCompleteColumn,
29
+ Progress,
30
+ TextColumn,
31
+ TimeElapsedColumn,
32
+ )
33
+ from rich.table import Table
34
+
35
+ from .client import DEFAULT_BASE_URL, DEFAULT_USER_AGENT, SubZoneClient
36
+ from .exceptions import NoSubtitleFoundError, SubZoneError, TitleNotFoundError
37
+ from .languages import DEFAULT_LANGUAGE, display_name, resolve
38
+ from .models import DownloadResult, TitleResult
39
+ from .parsing import parse_subtitles_url
40
+ from .scoring import rank_versions
41
+
42
+ app = typer.Typer(
43
+ name="subz",
44
+ help="Search and download subtitles from subzone.ir (Subf2m database).",
45
+ add_completion=False,
46
+ no_args_is_help=True,
47
+ rich_markup_mode="rich",
48
+ )
49
+
50
+ EXIT_OK = 0
51
+ EXIT_NOT_FOUND = 1
52
+ EXIT_ERROR = 2
53
+
54
+ console = Console()
55
+ err_console = Console(stderr=True)
56
+
57
+ SECTION_STYLE = {
58
+ "exact": "bold green",
59
+ "tv_series": "bold cyan",
60
+ "close": "bold yellow",
61
+ "popular": "bold magenta",
62
+ }
63
+
64
+
65
+ class Settings:
66
+ """Global options collected by the app callback."""
67
+
68
+ def __init__(
69
+ self,
70
+ base_url: str,
71
+ user_agent: str,
72
+ timeout: float,
73
+ retries: int,
74
+ verbose: bool,
75
+ ) -> None:
76
+ self.base_url = base_url
77
+ self.user_agent = user_agent
78
+ self.timeout = timeout
79
+ self.retries = retries
80
+ self.verbose = verbose
81
+
82
+
83
+ def _client(settings: Settings) -> SubZoneClient:
84
+ return SubZoneClient(
85
+ base_url=settings.base_url,
86
+ user_agent=settings.user_agent,
87
+ timeout=settings.timeout,
88
+ max_retries=settings.retries,
89
+ verbose=settings.verbose,
90
+ )
91
+
92
+
93
+ def _emit(data: Any, as_json: bool) -> None:
94
+ if as_json:
95
+ console.print_json(json.dumps(data, ensure_ascii=False, default=str))
96
+
97
+
98
+ def _fail(message: str, code: int) -> int:
99
+ err_console.print(f"[red]{message}[/red]")
100
+ return code
101
+
102
+
103
+ def _is_slug_like(value: str) -> bool:
104
+ return bool(value) and all(c.isalnum() or c in "-_" for c in value) and " " not in value
105
+
106
+
107
+ def _resolve_title_arg(client: SubZoneClient, title: str) -> TitleResult:
108
+ """Accept a slug or a show/movie name; always return a TitleResult."""
109
+ if title.startswith("/subtitles"):
110
+ slug, _lang, _sub = parse_subtitles_url(title)
111
+ return TitleResult(name=slug, slug=slug, url=f"/subtitles/{slug}")
112
+ if _is_slug_like(title):
113
+ try:
114
+ page = client.title(title)
115
+ return TitleResult(
116
+ name=page.name, slug=page.slug, year=page.year, url=f"/subtitles/{page.slug}"
117
+ )
118
+ except (TitleNotFoundError, SubZoneError):
119
+ pass # fall through to search
120
+ return client.search_exact(title)
121
+
122
+
123
+ def _print_download_result(result: DownloadResult) -> None:
124
+ v = result.version
125
+ console.print(
126
+ f"[green]Saved[/green] {v.language or display_name(v.lang)} subtitle "
127
+ f"(by {v.author or '?'}) for [bold]{v.slug}[/bold]"
128
+ )
129
+ if result.zip_path:
130
+ console.print(f" zip: {result.zip_path} ({result.bytes_downloaded:,} bytes)")
131
+ for p in result.srt_paths:
132
+ console.print(f" saved: {p}")
133
+
134
+
135
+ # ---------------------------------------------------------------------------
136
+ # search
137
+ # ---------------------------------------------------------------------------
138
+
139
+ @app.command()
140
+ def search(
141
+ ctx: typer.Context,
142
+ query: str = typer.Argument(..., help="Show or movie title to look for."),
143
+ lang: Optional[str] = typer.Option(
144
+ None, "--lang", "-l", help="Only titles having subtitles in this language (fa, en, tr, ...)."
145
+ ),
146
+ json_out: bool = typer.Option(False, "--json", help="Emit JSON instead of a table."),
147
+ ) -> None:
148
+ """Search subzone.ir for movie/series titles."""
149
+ client = _client(ctx.obj)
150
+ try:
151
+ results = client.search(query, lang=lang)
152
+ except TitleNotFoundError:
153
+ if json_out:
154
+ _emit([], True)
155
+ raise typer.Exit(_fail(f"No title matches {query!r}.", EXIT_NOT_FOUND))
156
+ except SubZoneError as exc:
157
+ raise typer.Exit(_fail(str(exc), EXIT_ERROR))
158
+
159
+ if json_out:
160
+ _emit([r.as_dict() for r in results], True)
161
+ return
162
+
163
+ table = Table(title=f"Search results for {query!r}", box=box.SIMPLE_HEAVY)
164
+ table.add_column("section", style="dim")
165
+ table.add_column("title")
166
+ table.add_column("year", justify="right")
167
+ table.add_column("subs", justify="right")
168
+ table.add_column("slug", style="dim")
169
+ for r in results:
170
+ style = SECTION_STYLE.get(r.section, "dim")
171
+ table.add_row(
172
+ f"[{style}]{r.section}[/]",
173
+ r.name,
174
+ str(r.year or "-"),
175
+ str(r.subtitle_count if r.subtitle_count is not None else "-"),
176
+ r.slug,
177
+ )
178
+ console.print(table)
179
+ console.print("[dim]Next: subz versions <slug>[/dim]")
180
+
181
+
182
+ # ---------------------------------------------------------------------------
183
+ # versions
184
+ # ---------------------------------------------------------------------------
185
+
186
+ @app.command()
187
+ def versions(
188
+ ctx: typer.Context,
189
+ title: str = typer.Argument(..., help="Title slug (dexter-resurrection-season-2) or a show name."),
190
+ lang: Optional[str] = typer.Option(
191
+ None, "--lang", "-l", help="Only list versions in this language."
192
+ ),
193
+ json_out: bool = typer.Option(False, "--json", help="Emit JSON instead of a table."),
194
+ ) -> None:
195
+ """List subtitle versions available for a title."""
196
+ client = _client(ctx.obj)
197
+ try:
198
+ resolved = _resolve_title_arg(client, title)
199
+ version_list = client.title_versions(resolved.slug, lang)
200
+ except (TitleNotFoundError, NoSubtitleFoundError) as exc:
201
+ raise typer.Exit(_fail(str(exc), EXIT_NOT_FOUND))
202
+ except SubZoneError as exc:
203
+ raise typer.Exit(_fail(str(exc), EXIT_ERROR))
204
+
205
+ if json_out:
206
+ _emit([v.as_dict() for v in version_list], True)
207
+ return
208
+
209
+ heading = f"Subtitles for {resolved.name}"
210
+ if resolved.year:
211
+ heading += f" ({resolved.year})"
212
+ table = Table(title=heading, box=box.SIMPLE_HEAVY)
213
+ table.add_column("language")
214
+ table.add_column("rate")
215
+ table.add_column("author")
216
+ table.add_column("releases", overflow="fold")
217
+ table.add_column("ref", style="dim", overflow="fold")
218
+ for v in version_list:
219
+ rate = {"positive": "[green]good[/green]", "negative": "[red]bad[/red]"}.get(v.rate, "·")
220
+ releases = "; ".join(r[:42] for r in v.releases[:2])
221
+ if len(v.releases) > 2:
222
+ releases += f" (+{len(v.releases) - 2} more)"
223
+ table.add_row(v.language or display_name(v.lang), rate, v.author, releases, v.ref)
224
+ console.print(table)
225
+ console.print("[dim]Next: subz download <ref>[/dim]")
226
+
227
+
228
+ # ---------------------------------------------------------------------------
229
+ # download / url
230
+ # ---------------------------------------------------------------------------
231
+
232
+ def _download_impl(
233
+ client: SubZoneClient,
234
+ target: str,
235
+ lang: Optional[str],
236
+ limit: int,
237
+ out: Path,
238
+ save_zip: bool,
239
+ lang_suffix: Optional[str],
240
+ no_suffix: bool,
241
+ ) -> List[DownloadResult]:
242
+ """Shared logic for `download` and `url`: resolve target -> downloads."""
243
+ kwargs = dict(
244
+ dest_dir=out,
245
+ save_mode="zip" if save_zip else "extract",
246
+ lang_suffix=lang_suffix,
247
+ no_suffix=no_suffix,
248
+ )
249
+ stripped = target.strip().strip("/")
250
+ parts = stripped.split("/")
251
+
252
+ is_url = stripped.startswith(("http://", "https://", "/subtitles"))
253
+ if is_url:
254
+ slug, url_lang, sub_id = parse_subtitles_url(stripped)
255
+ elif len(parts) == 3 and parts[2].isdigit():
256
+ slug, url_lang, sub_id = parts[0], parts[1], parts[2]
257
+ elif len(parts) >= 1 and _is_slug_like(stripped):
258
+ slug, url_lang, sub_id = stripped, None, None
259
+ else:
260
+ raise ValueError(
261
+ "Target must be a '<slug>/<lang>/<id>' ref, a subzone.ir URL, "
262
+ "or a title slug."
263
+ )
264
+
265
+ if sub_id:
266
+ return [client.download(f"{slug}/{url_lang}/{sub_id}", **kwargs)]
267
+ # title-level target: grab the newest versions of one language
268
+ effective_lang = lang or url_lang or DEFAULT_LANGUAGE
269
+ return client.download_url(f"/subtitles/{slug}", lang=effective_lang, limit=limit, **kwargs)
270
+
271
+
272
+ def _shared_download_options(out: Path = None):
273
+ return {
274
+ "out": typer.Option(Path("."), "--out", "-o", help="Output directory (default: current directory)."),
275
+ "save_zip": typer.Option(False, "--zip", help="Keep the downloaded zip instead of extracting it."),
276
+ "lang_suffix": typer.Option(None, "--lang-suffix", help="Suffix for extracted files, e.g. 'fa' (default: derived from language)."),
277
+ "no_suffix": typer.Option(False, "--no-suffix", help="Name files 'Movie.srt' instead of 'Movie.fa.srt'."),
278
+ }
279
+
280
+
281
+ @app.command()
282
+ def download(
283
+ ctx: typer.Context,
284
+ target: str = typer.Argument(..., help="'<slug>/<lang>/<id>' ref, any subzone.ir URL, or a title slug."),
285
+ lang: Optional[str] = typer.Option(None, "--lang", "-l", help="Language for title slugs/URLs (default: farsi_persian)."),
286
+ limit: int = typer.Option(1, "--limit", "-n", help="How many versions to grab from title slugs/URLs (0 = all)."),
287
+ out: Path = typer.Option(Path("."), "--out", "-o", help="Output directory (default: current directory)."),
288
+ save_zip: bool = typer.Option(False, "--zip", help="Keep the downloaded zip instead of extracting it."),
289
+ lang_suffix: Optional[str] = typer.Option(None, "--lang-suffix", help="Suffix for extracted files, e.g. 'fa' (default: derived from language)."),
290
+ no_suffix: bool = typer.Option(False, "--no-suffix", help="Name files 'Movie.srt' instead of 'Movie.fa.srt'."),
291
+ json_out: bool = typer.Option(False, "--json", help="Emit JSON."),
292
+ ) -> None:
293
+ """Download a subtitle by ref, URL or title slug."""
294
+ client = _client(ctx.obj)
295
+ try:
296
+ results = _download_impl(client, target, lang, limit, out, save_zip, lang_suffix, no_suffix)
297
+ except (NoSubtitleFoundError, TitleNotFoundError) as exc:
298
+ raise typer.Exit(_fail(str(exc), EXIT_NOT_FOUND))
299
+ except (SubZoneError, ValueError) as exc:
300
+ raise typer.Exit(_fail(str(exc), EXIT_ERROR))
301
+
302
+ if json_out:
303
+ _emit([r.as_dict() for r in results], True)
304
+ return
305
+ for r in results:
306
+ _print_download_result(r)
307
+
308
+
309
+ @app.command()
310
+ def url(
311
+ ctx: typer.Context,
312
+ url_value: str = typer.Argument(..., help="Any subzone.ir subtitles URL (version or title page)."),
313
+ lang: Optional[str] = typer.Option(None, "--lang", "-l", help="Language for title URLs (default: farsi_persian)."),
314
+ limit: int = typer.Option(1, "--limit", "-n", help="How many versions to grab from title URLs (0 = all)."),
315
+ out: Path = typer.Option(Path("."), "--out", "-o", help="Output directory (default: current directory)."),
316
+ save_zip: bool = typer.Option(False, "--zip", help="Keep the downloaded zip instead of extracting it."),
317
+ lang_suffix: Optional[str] = typer.Option(None, "--lang-suffix", help="Suffix for extracted files, e.g. 'fa'."),
318
+ no_suffix: bool = typer.Option(False, "--no-suffix", help="Name files 'Movie.srt' instead of 'Movie.fa.srt'."),
319
+ json_out: bool = typer.Option(False, "--json", help="Emit JSON."),
320
+ ) -> None:
321
+ """'URL grab': paste any subzone.ir subtitles URL and download it."""
322
+ client = _client(ctx.obj)
323
+ try:
324
+ results = _download_impl(client, url_value, lang, limit, out, save_zip, lang_suffix, no_suffix)
325
+ except (NoSubtitleFoundError, TitleNotFoundError) as exc:
326
+ raise typer.Exit(_fail(str(exc), EXIT_NOT_FOUND))
327
+ except (SubZoneError, ValueError) as exc:
328
+ raise typer.Exit(_fail(str(exc), EXIT_ERROR))
329
+
330
+ if json_out:
331
+ _emit([r.as_dict() for r in results], True)
332
+ return
333
+ for r in results:
334
+ _print_download_result(r)
335
+
336
+
337
+ # ---------------------------------------------------------------------------
338
+ # filename
339
+ # ---------------------------------------------------------------------------
340
+
341
+ @app.command("filename")
342
+ def filename(
343
+ ctx: typer.Context,
344
+ file: str = typer.Argument(..., help="Video file path or release name."),
345
+ lang: Optional[str] = typer.Option(DEFAULT_LANGUAGE, "--lang", "-l", help="Subtitle language."),
346
+ out: Path = typer.Option(Path("."), "--out", "-o", help="Output directory when FILE is not a real file."),
347
+ save_zip: bool = typer.Option(False, "--zip", help="Keep the downloaded zip instead of extracting it."),
348
+ lang_suffix: Optional[str] = typer.Option(None, "--lang-suffix", help="Suffix for extracted files, e.g. 'fa'."),
349
+ no_suffix: bool = typer.Option(False, "--no-suffix", help="Name files 'Movie.srt' instead of 'Movie.fa.srt'."),
350
+ no_download: bool = typer.Option(False, "--no-download", help="Only show matching candidates."),
351
+ json_out: bool = typer.Option(False, "--json", help="Emit JSON."),
352
+ ) -> None:
353
+ """Find the best subtitle for one video file / release name."""
354
+ from .matcher import guess_season_episode, guess_title
355
+
356
+ client = _client(ctx.obj)
357
+ stem = Path(file).stem
358
+ query = guess_title(stem)
359
+ lang_slug = resolve(lang) or DEFAULT_LANGUAGE
360
+ if not json_out:
361
+ console.print(
362
+ f"[dim]query:[/dim] [bold]{query}[/bold] "
363
+ f"[dim]language:[/dim] {display_name(lang_slug)}"
364
+ )
365
+
366
+ try:
367
+ title, best, score = client.best_for_file(stem, lang=lang_slug)
368
+ page = client.title(f"{title.slug}/{lang_slug}")
369
+ ranked = rank_versions(stem, page.versions)[:5]
370
+ except (NoSubtitleFoundError, TitleNotFoundError) as exc:
371
+ raise typer.Exit(_fail(str(exc), EXIT_NOT_FOUND))
372
+ except SubZoneError as exc:
373
+ raise typer.Exit(_fail(str(exc), EXIT_ERROR))
374
+
375
+ if json_out:
376
+ payload: Dict[str, Any] = {
377
+ "query": query,
378
+ "title": title.as_dict(),
379
+ "best": {**best.as_dict(), "score": score},
380
+ "candidates": [{"score": s, **v.as_dict()} for s, v in ranked],
381
+ }
382
+ if not no_download:
383
+ result = client.download(
384
+ best,
385
+ dest_dir=out,
386
+ save_mode="zip" if save_zip else "extract",
387
+ lang_suffix=lang_suffix,
388
+ no_suffix=no_suffix,
389
+ target_video=file if Path(file).is_file() else None,
390
+ )
391
+ payload["download"] = result.as_dict()
392
+ _emit(payload, True)
393
+ return
394
+
395
+ table = Table(title="Top matching versions", box=box.SIMPLE_HEAVY)
396
+ table.add_column("score", justify="right", style="bold cyan")
397
+ table.add_column("language")
398
+ table.add_column("author")
399
+ table.add_column("releases", overflow="fold")
400
+ table.add_column("ref", style="dim")
401
+ for s, v in ranked:
402
+ mark = " [green]<- best[/green]" if v.ref == best.ref else ""
403
+ table.add_row(
404
+ str(s),
405
+ v.language or display_name(v.lang),
406
+ v.author,
407
+ ", ".join(v.releases[:2]) or "-",
408
+ f"{v.ref}{mark}",
409
+ )
410
+ console.print(table)
411
+
412
+ if no_download:
413
+ return
414
+ try:
415
+ result = client.download(
416
+ best,
417
+ dest_dir=out,
418
+ save_mode="zip" if save_zip else "extract",
419
+ lang_suffix=lang_suffix,
420
+ no_suffix=no_suffix,
421
+ target_video=file if Path(file).is_file() else None,
422
+ )
423
+ except (SubZoneError, ValueError) as exc:
424
+ raise typer.Exit(_fail(str(exc), EXIT_ERROR))
425
+ _print_download_result(result)
426
+
427
+
428
+ # ---------------------------------------------------------------------------
429
+ # auto
430
+ # ---------------------------------------------------------------------------
431
+
432
+ @app.command()
433
+ def auto(
434
+ ctx: typer.Context,
435
+ path: Path = typer.Argument(..., help="Video file or a folder containing videos."),
436
+ lang: Optional[str] = typer.Option(DEFAULT_LANGUAGE, "--lang", "-l", help="Subtitle language."),
437
+ out: Optional[Path] = typer.Option(None, "--out", "-o", help="Save subtitles here instead of next to each video."),
438
+ save_zip: bool = typer.Option(False, "--zip", help="Keep the downloaded zips instead of extracting them."),
439
+ lang_suffix: Optional[str] = typer.Option(None, "--lang-suffix", help="Suffix for extracted files, e.g. 'fa'."),
440
+ no_suffix: bool = typer.Option(False, "--no-suffix", help="Name files 'Movie.srt' instead of 'Movie.fa.srt'."),
441
+ dry_run: bool = typer.Option(False, "--dry-run", help="Only show the matches, download nothing."),
442
+ yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation prompt."),
443
+ json_out: bool = typer.Option(False, "--json", help="Emit JSON."),
444
+ ) -> None:
445
+ """Auto-match every video in PATH and download fitting subtitles."""
446
+ from .matcher import find_videos
447
+
448
+ lang_slug = resolve(lang) or DEFAULT_LANGUAGE
449
+ try:
450
+ videos = find_videos(path)
451
+ except (ValueError, FileNotFoundError) as exc:
452
+ raise typer.Exit(_fail(str(exc), EXIT_ERROR))
453
+ if not videos:
454
+ raise typer.Exit(_fail(f"No video files found under {path}", EXIT_NOT_FOUND))
455
+
456
+ if not json_out:
457
+ console.print(f"[bold]{len(videos)} video file(s)[/bold] under {path}")
458
+ for v in videos:
459
+ console.print(f" [dim]-[/dim] {v.name}")
460
+ note = " [dim](dry run)[/dim]" if dry_run else ""
461
+ console.print(f"[dim]language: {display_name(lang_slug)}{note}[/dim]")
462
+ if not dry_run and not yes and sys.stdin.isatty():
463
+ if not typer.confirm("Fetch and save subtitles for these files?"):
464
+ return
465
+
466
+ client = _client(ctx.obj)
467
+ rows: List[Dict[str, Any]] = []
468
+ saw_error = False
469
+ saw_missing = False
470
+
471
+ progress = Progress(
472
+ TextColumn("[progress.description]{task.description}"),
473
+ BarColumn(),
474
+ MofNCompleteColumn(),
475
+ TimeElapsedColumn(),
476
+ console=console,
477
+ disable=json_out,
478
+ )
479
+ with progress:
480
+ task = progress.add_task("matching", total=len(videos))
481
+ for video in videos:
482
+ progress.update(task, description=f"[cyan]{video.name[:40]}")
483
+ row: Dict[str, Any] = {"video": str(video), "title": None, "status": "ok"}
484
+ try:
485
+ title, best, score = client.best_for_file(video.stem, lang=lang_slug)
486
+ row.update({"title": title.name, "ref": best.ref, "score": score})
487
+ if dry_run:
488
+ row["status"] = "dry-run"
489
+ else:
490
+ dest = out if out else video.parent
491
+ result = client.download(
492
+ best,
493
+ dest_dir=dest,
494
+ save_mode="zip" if save_zip else "extract",
495
+ lang_suffix=lang_suffix,
496
+ no_suffix=no_suffix,
497
+ target_video=video,
498
+ )
499
+ row["saved"] = result.srt_paths or result.zip_path
500
+ except (NoSubtitleFoundError, TitleNotFoundError) as exc:
501
+ row["status"] = "not found"
502
+ row["error"] = str(exc)
503
+ saw_missing = True
504
+ except (SubZoneError, ValueError, OSError) as exc:
505
+ row["status"] = "error"
506
+ row["error"] = str(exc)
507
+ saw_error = True
508
+ rows.append(row)
509
+ progress.advance(task)
510
+
511
+ if json_out:
512
+ _emit(rows, True)
513
+ else:
514
+ summary = Table(title="Auto-match summary", box=box.SIMPLE_HEAVY)
515
+ summary.add_column("video")
516
+ summary.add_column("title")
517
+ summary.add_column("score", justify="right")
518
+ summary.add_column("status")
519
+ summary.add_column("saved", overflow="fold")
520
+ for row in rows:
521
+ style = {"ok": "green", "dry-run": "cyan", "not found": "yellow"}.get(
522
+ row["status"], "red"
523
+ )
524
+ saved = ", ".join(row.get("saved") or []) or row.get("error", "") or "-"
525
+ summary.add_row(
526
+ Path(row["video"]).name,
527
+ row.get("title") or "-",
528
+ str(row.get("score", "-")),
529
+ f"[{style}]{row['status']}[/{style}]",
530
+ saved,
531
+ )
532
+ console.print(summary)
533
+
534
+ if saw_error:
535
+ raise typer.Exit(EXIT_ERROR)
536
+ if saw_missing:
537
+ raise typer.Exit(EXIT_NOT_FOUND)
538
+
539
+
540
+ # ---------------------------------------------------------------------------
541
+ # popular / latest
542
+ # ---------------------------------------------------------------------------
543
+
544
+ @app.command()
545
+ def popular(
546
+ ctx: typer.Context,
547
+ mode: str = typer.Option("popular", "--mode", help="popular or latest."),
548
+ kind: str = typer.Option("all", "--type", "-t", help="all, film, series or music."),
549
+ page: int = typer.Option(1, "--page", "-p", help="Page number."),
550
+ lang: Optional[str] = typer.Option(None, "--lang", "-l", help="Only rows in this language."),
551
+ json_out: bool = typer.Option(False, "--json", help="Emit JSON instead of a table."),
552
+ ) -> None:
553
+ """Browse the popular/latest subtitle uploads."""
554
+ client = _client(ctx.obj)
555
+ try:
556
+ entries = client.browse(mode=mode, kind=kind, page=page, lang=lang)
557
+ except ValueError as exc:
558
+ raise typer.Exit(_fail(str(exc), EXIT_ERROR))
559
+ except SubZoneError as exc:
560
+ raise typer.Exit(_fail(str(exc), EXIT_ERROR))
561
+
562
+ if json_out:
563
+ _emit([e.as_dict() for e in entries], True)
564
+ return
565
+ table = Table(
566
+ title=f"{mode.title()} uploads ({kind}) - page {page}",
567
+ box=box.SIMPLE_HEAVY,
568
+ )
569
+ table.add_column("title")
570
+ table.add_column("language")
571
+ table.add_column("type")
572
+ table.add_column("owner", style="dim")
573
+ table.add_column("date", style="dim")
574
+ table.add_column("ref", style="dim")
575
+ for e in entries:
576
+ table.add_row(
577
+ e.title_name,
578
+ e.version.language,
579
+ e.media_type,
580
+ e.owner,
581
+ e.date,
582
+ e.version.ref,
583
+ )
584
+ console.print(table)
585
+ console.print("[dim]Next: subz download <ref>[/dim]")
586
+
587
+
588
+ # ---------------------------------------------------------------------------
589
+ # tui
590
+ # ---------------------------------------------------------------------------
591
+
592
+ @app.command()
593
+ def tui(ctx: typer.Context) -> None:
594
+ """Launch the interactive Textual interface."""
595
+ from .tui import SubZoneTUI
596
+
597
+ client = _client(ctx.obj)
598
+ SubZoneTUI(client).run()
599
+
600
+
601
+ # ---------------------------------------------------------------------------
602
+ # entry point
603
+ # ---------------------------------------------------------------------------
604
+
605
+ @app.callback()
606
+ def _callback(
607
+ ctx: typer.Context,
608
+ base_url: str = typer.Option(DEFAULT_BASE_URL, "--base-url", help="Site base URL."),
609
+ user_agent: str = typer.Option(DEFAULT_USER_AGENT, "--user-agent", help="User-Agent header."),
610
+ timeout: float = typer.Option(20.0, "--timeout", help="HTTP timeout in seconds."),
611
+ retries: int = typer.Option(3, "--retries", help="Retries per request."),
612
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Log HTTP requests."),
613
+ ) -> None:
614
+ """[bold]subz[/bold] - search and download subtitles from subzone.ir."""
615
+ ctx.obj = Settings(base_url, user_agent, timeout, retries, verbose)
616
+
617
+
618
+ def main() -> None:
619
+ """Console entry point."""
620
+ app()
621
+
622
+
623
+ if __name__ == "__main__":
624
+ main()