castforge 0.1.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,228 @@
1
+ """Reusable NotebookLM audio publishing helpers for CastForge pipelines."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import anyio
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ _DEFAULT_INSTRUCTIONS_ZH = """请用简体中文录制本期播客,语速偏快、节奏紧凑。
15
+
16
+ 【开场格式】
17
+ 不要介绍论坛或资料来源是什么。直接用一句话说明本期内容,然后快速抛出2-3个关键词作为 hook,吸引听众继续听。
18
+
19
+ 【事实优先】
20
+ 逐个讨论来源文档中的话题。每个话题先讲清楚 What Happened、Essential Context 和 Evidence From Source,再进入社区反应或主持人观点。听众应该在没看过原帖的情况下也能明白前因后果。
21
+
22
+ 【回复使用】
23
+ 如果来源文档中有 Informative Replies、精选回复或社区讨论,只引用其中提供事实、数据点、修正、约束、亲身经验或实质分歧的内容。不要把低信息量玩笑、吐槽或高赞短评当成事实主线。
24
+
25
+ 【不确定性】
26
+ 遇到 Caveats / Unknowns、YMMV、争议点或来源没有交代清楚的背景时,要明确说出来。不要编造缺失事实,不要不懂装懂。
27
+
28
+ 【语气】
29
+ 像两个熟悉主题的人聊天,不要播音腔,不要过度客套。可以有轻微调侃和个人倾向,但必须服从来源文档中的 Editorial Voice 和事实边界。"""
30
+
31
+ _DEFAULT_INSTRUCTIONS_EN = """Record a concise English briefing with a brisk, conversational pace.
32
+
33
+ Open with one sentence explaining what matters today, then cover each story in the source document. For every story, establish what happened, the essential context, and the cited evidence before adding interpretation. Treat uncertainty and disagreement explicitly. Do not invent missing facts, sources, quotes, or causal claims.
34
+
35
+ Sound like two informed builders comparing notes rather than broadcast announcers. Keep the discussion focused on practical implications and use only information contained in the source document."""
36
+
37
+ _INTEGRATION_HINT = (
38
+ "Install optional deps: pip install -r requirements-integrations.txt && "
39
+ "playwright install chromium && notebooklm login"
40
+ )
41
+
42
+
43
+ def _ensure_notebooklm_imported() -> Any:
44
+ try:
45
+ from notebooklm import AudioFormat, AudioLength, NotebookLMClient
46
+
47
+ return NotebookLMClient, AudioFormat, AudioLength
48
+ except ImportError as e:
49
+ raise RuntimeError(
50
+ f"notebooklm-py is not installed ({e}). {_INTEGRATION_HINT}"
51
+ ) from e
52
+
53
+
54
+ def _parse_audio_format(name: str | None, AudioFormat: Any) -> Any:
55
+ if not name or not str(name).strip():
56
+ return None
57
+ key = str(name).strip().lower().replace("-", "_")
58
+ mapping = {
59
+ "deep_dive": AudioFormat.DEEP_DIVE,
60
+ "brief": AudioFormat.BRIEF,
61
+ "critique": AudioFormat.CRITIQUE,
62
+ "debate": AudioFormat.DEBATE,
63
+ }
64
+ if key not in mapping:
65
+ raise ValueError(
66
+ f"NOTEBOOKLM_AUDIO_FORMAT must be one of {list(mapping.keys())}, got {name!r}"
67
+ )
68
+ return mapping[key]
69
+
70
+
71
+ def _parse_audio_length(name: str | None, AudioLength: Any) -> Any:
72
+ if not name or not str(name).strip():
73
+ return None
74
+ key = str(name).strip().lower()
75
+ mapping = {
76
+ "short": AudioLength.SHORT,
77
+ "default": AudioLength.DEFAULT,
78
+ "long": AudioLength.LONG,
79
+ }
80
+ if key not in mapping:
81
+ raise ValueError(
82
+ f"NOTEBOOKLM_AUDIO_LENGTH must be one of {list(mapping.keys())}, got {name!r}"
83
+ )
84
+ return mapping[key]
85
+
86
+
87
+ def _config_from_env() -> dict[str, Any]:
88
+ notebook_id = os.environ.get("NOTEBOOKLM_NOTEBOOK_ID", "").strip()
89
+ if not notebook_id:
90
+ raise RuntimeError(
91
+ "NOTEBOOKLM_NOTEBOOK_ID is required for programmatic publish "
92
+ "(create a notebook in the UI, copy its id from the URL or metadata)."
93
+ )
94
+ language = os.environ.get("NOTEBOOKLM_AUDIO_LANGUAGE", "en").strip() or "en"
95
+ default_instructions = _DEFAULT_INSTRUCTIONS_ZH if language.lower().startswith("zh") else _DEFAULT_INSTRUCTIONS_EN
96
+ instructions = os.environ.get("NOTEBOOKLM_AUDIO_INSTRUCTIONS", "").strip() or default_instructions
97
+ gen_timeout = float(os.environ.get("NOTEBOOKLM_GENERATION_TIMEOUT", "600"))
98
+ source_wait = float(os.environ.get("NOTEBOOKLM_SOURCE_WAIT_TIMEOUT", "180"))
99
+ storage_path = os.environ.get("NOTEBOOKLM_STORAGE_PATH", "").strip() or None
100
+ http_timeout = float(os.environ.get("NOTEBOOKLM_HTTP_TIMEOUT", "60"))
101
+ audio_fmt = os.environ.get("NOTEBOOKLM_AUDIO_FORMAT", "").strip() or None
102
+ audio_len = os.environ.get("NOTEBOOKLM_AUDIO_LENGTH", "").strip() or None
103
+ return {
104
+ "notebook_id": notebook_id,
105
+ "instructions": instructions,
106
+ "language": language,
107
+ "generation_timeout": gen_timeout,
108
+ "source_wait_timeout": source_wait,
109
+ "storage_path": storage_path,
110
+ "http_timeout": http_timeout,
111
+ "audio_format_name": audio_fmt,
112
+ "audio_length_name": audio_len,
113
+ }
114
+
115
+
116
+ async def publish_audio_async(
117
+ markdown_path: Path,
118
+ *,
119
+ output_audio: Path,
120
+ notebook_id: str | None = None,
121
+ instructions: str | None = None,
122
+ language: str | None = None,
123
+ generation_timeout: float | None = None,
124
+ source_wait_timeout: float | None = None,
125
+ storage_path: str | None = None,
126
+ http_timeout: float | None = None,
127
+ audio_format: Any | None = None,
128
+ audio_length: Any | None = None,
129
+ audio_length_name: str | None = None,
130
+ ) -> Path:
131
+ """Upload markdown, generate audio for that source, and download it."""
132
+ NotebookLMClient, AudioFormat, AudioLength = _ensure_notebooklm_imported()
133
+ cfg = _config_from_env()
134
+ nb = notebook_id or cfg["notebook_id"]
135
+ instr = instructions if instructions is not None else cfg["instructions"]
136
+ lang = language if language is not None else cfg["language"]
137
+ gen_to = generation_timeout if generation_timeout is not None else cfg["generation_timeout"]
138
+ src_to = source_wait_timeout if source_wait_timeout is not None else cfg["source_wait_timeout"]
139
+ store = storage_path if storage_path is not None else cfg["storage_path"]
140
+ http_to = http_timeout if http_timeout is not None else cfg["http_timeout"]
141
+ af = audio_format
142
+ al = audio_length
143
+ if af is None and cfg["audio_format_name"]:
144
+ af = _parse_audio_format(cfg["audio_format_name"], AudioFormat)
145
+ configured_length = audio_length_name or cfg["audio_length_name"]
146
+ if al is None and configured_length:
147
+ al = _parse_audio_length(configured_length, AudioLength)
148
+
149
+ md = Path(markdown_path).resolve()
150
+ if not md.is_file():
151
+ raise FileNotFoundError(f"Markdown export not found: {md}")
152
+
153
+ out = Path(output_audio).resolve()
154
+ out.parent.mkdir(parents=True, exist_ok=True)
155
+
156
+ client_ctx = await NotebookLMClient.from_storage(store, timeout=http_to)
157
+ async with client_ctx as client:
158
+ source_id = None
159
+ try:
160
+ logger.info("NotebookLM: adding file source %s", md)
161
+ source = await client.sources.add_file(nb, md, wait=True, wait_timeout=src_to)
162
+ if source.is_error:
163
+ raise RuntimeError(f"NotebookLM source failed to index: {source!r}")
164
+ source_id = source.id
165
+ logger.info(
166
+ "NotebookLM: source ready id=%s, generating audio (language=%r)",
167
+ source_id,
168
+ lang,
169
+ )
170
+
171
+ status = await client.artifacts.generate_audio(
172
+ nb,
173
+ source_ids=[source_id],
174
+ language=lang,
175
+ instructions=instr,
176
+ audio_format=af,
177
+ audio_length=al,
178
+ )
179
+ final = await client.artifacts.wait_for_completion(
180
+ nb,
181
+ status.task_id,
182
+ timeout=gen_to,
183
+ )
184
+ if final.is_failed:
185
+ raise RuntimeError(
186
+ f"NotebookLM audio generation failed: status={final.status!r} "
187
+ f"error={final.error!r}"
188
+ )
189
+ if not final.is_complete:
190
+ raise RuntimeError(f"NotebookLM audio generation ended incomplete: {final!r}")
191
+
192
+ logger.info("NotebookLM: downloading audio to %s", out)
193
+ await client.artifacts.download_audio(nb, str(out), artifact_id=final.task_id)
194
+ finally:
195
+ if source_id:
196
+ try:
197
+ await client.sources.delete(nb, source_id)
198
+ logger.info("NotebookLM: deleted temporary source id=%s", source_id)
199
+ except Exception:
200
+ # The downloaded MP3 remains valid even if provider-side cleanup fails.
201
+ # Preserve the primary pipeline result and make the leak visible in logs.
202
+ logger.warning(
203
+ "NotebookLM: failed to delete temporary source id=%s",
204
+ source_id,
205
+ exc_info=True,
206
+ )
207
+ return out
208
+
209
+
210
+ def publish_audio(
211
+ markdown_path: Path,
212
+ output_audio: Path,
213
+ **kwargs: Any,
214
+ ) -> Path:
215
+ """Sync wrapper for jobs and CLI."""
216
+
217
+ async def _runner() -> Path:
218
+ return await publish_audio_async(
219
+ markdown_path, output_audio=output_audio, **kwargs
220
+ )
221
+
222
+ return anyio.run(_runner)
223
+
224
+
225
+ # Backward-compatible aliases for the production Nitan show while it migrates
226
+ # to the schedule-neutral names.
227
+ publish_weekly_audio_async = publish_audio_async
228
+ publish_weekly_audio = publish_audio
castforge/pipeline.py ADDED
@@ -0,0 +1,227 @@
1
+ """Reusable CLI pipeline orchestration for show repositories."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import logging
8
+ import os
9
+ import sys
10
+ from dataclasses import dataclass
11
+ from datetime import date
12
+ from pathlib import Path
13
+ from typing import Any, Callable
14
+
15
+ from dotenv import load_dotenv
16
+
17
+ from castforge.briefing import write_briefing_markdown
18
+ from castforge.export import DEFAULT_EXPORT_DIR, DEFAULT_MARKDOWN_NAME, export_for_notebooklm
19
+ from castforge.notebooklm_audio import publish_audio
20
+
21
+ DEFAULT_RELEASES_DIR = Path("releases")
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class PipelineHooks:
26
+ extract_weekly_key_info: Callable[[], list[dict[str, Any]]]
27
+ fetch_thread_details: Callable[[list[dict[str, Any]]], list[dict[str, Any]]]
28
+ list_mcp_tools: Callable[[], list[Any]]
29
+ select_threads: Callable[[list[dict[str, Any]]], list[dict[str, Any]]]
30
+ threads_to_source_markdown: Callable[[list[dict[str, Any]]], str]
31
+ write_forum_post: Callable[..., Path]
32
+ generate_rss_feed: Callable[..., Path]
33
+ episode_file_prefix: str
34
+ week_episode_filename: Callable[[int, int], str]
35
+ week_episode_url: Callable[[int, int], str]
36
+
37
+
38
+ def _week_filename(prefix: str, ext: str = ".md") -> str:
39
+ iso = date.today().isocalendar()
40
+ return f"{prefix}_{iso.year}-W{iso.week:02d}{ext}"
41
+
42
+
43
+ def _default_audio_out(dated: bool, hooks: PipelineHooks) -> Path:
44
+ iso = date.today().isocalendar()
45
+ name = hooks.week_episode_filename(iso.year, iso.week) if dated else f"{hooks.episode_file_prefix}_podcast.mp3"
46
+ return (DEFAULT_RELEASES_DIR / name).resolve()
47
+
48
+
49
+ def _setup_logging(level: str) -> None:
50
+ logging.basicConfig(
51
+ level=getattr(logging, level.upper(), logging.INFO),
52
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",
53
+ datefmt="%Y-%m-%dT%H:%M:%S",
54
+ stream=sys.stderr,
55
+ )
56
+
57
+
58
+ def build_parser(*, episode_file_prefix: str) -> argparse.ArgumentParser:
59
+ parser = argparse.ArgumentParser(description="Source -> NotebookLM Markdown export pipeline")
60
+ parser.add_argument("--env-file", type=Path, default=Path(".env"), help="Dotenv path (default: .env)")
61
+ parser.add_argument("--skip-briefing", action="store_true", help="Skip Gemini; export structured Markdown from extraction only")
62
+ parser.add_argument("--export-dir", type=Path, default=None, help=f"Export directory (default: {DEFAULT_EXPORT_DIR})")
63
+ parser.add_argument(
64
+ "--output-filename",
65
+ default=None,
66
+ help=f"Output filename (default: {DEFAULT_MARKDOWN_NAME} or ISO-week name if --dated)",
67
+ )
68
+ parser.add_argument("--dated", action="store_true", help=f"Use ISO week filename {episode_file_prefix}_YYYY-Www.md")
69
+ parser.add_argument("--log-level", default="INFO", help="Logging level (DEBUG, INFO, WARNING, ERROR)")
70
+ parser.add_argument(
71
+ "--list-mcp-tools",
72
+ action="store_true",
73
+ help="Connect to MCP server, print tool names/schemas as JSON, exit",
74
+ )
75
+ parser.add_argument(
76
+ "--skip-details",
77
+ action="store_true",
78
+ help="Skip fetching thread replies/details (faster, uses only OP-level data)",
79
+ )
80
+ parser.add_argument(
81
+ "--markdown-input",
82
+ type=Path,
83
+ default=None,
84
+ help="Skip extraction; use this existing Markdown file as input (for reuse across pipeline phases)",
85
+ )
86
+ parser.add_argument(
87
+ "--publish-notebooklm",
88
+ action="store_true",
89
+ help="After export: upload Markdown to NotebookLM, generate Audio Overview, download MP3",
90
+ )
91
+ parser.add_argument(
92
+ "--notebooklm-audio-out",
93
+ type=Path,
94
+ default=None,
95
+ help=f"Path for downloaded audio (default: releases/{episode_file_prefix}_YYYY-Www.mp3 if --dated else releases/{episode_file_prefix}_podcast.mp3)",
96
+ )
97
+ parser.add_argument("--generate-post", action="store_true", help="Generate a forum/community post alongside the export")
98
+ parser.add_argument("--audio-url", default=None, help="Podcast episode URL to embed in post and RSS")
99
+ parser.add_argument("--generate-rss", action="store_true", help="Generate/update podcast RSS feed")
100
+ parser.add_argument("--rss-output", type=Path, default=None, help="Path for RSS feed file")
101
+ parser.add_argument("--episode-duration", default="00:06:00", help="Episode duration as HH:MM:SS for RSS feed")
102
+ parser.add_argument("--mp3-path", type=Path, default=None, help="Path to local MP3 file for RSS enclosure size detection")
103
+ return parser
104
+
105
+
106
+ def main(argv: list[str] | None, *, hooks: PipelineHooks) -> int:
107
+ parser = build_parser(episode_file_prefix=hooks.episode_file_prefix)
108
+ args = parser.parse_args(argv)
109
+
110
+ _setup_logging(args.log_level)
111
+ log = logging.getLogger("castforge.pipeline")
112
+
113
+ if args.env_file.is_file():
114
+ load_dotenv(args.env_file, override=False)
115
+ else:
116
+ load_dotenv(override=False)
117
+
118
+ if args.list_mcp_tools:
119
+ try:
120
+ tools = hooks.list_mcp_tools()
121
+ out = [
122
+ {
123
+ "name": t.name,
124
+ "description": getattr(t, "description", None),
125
+ "inputSchema": getattr(t, "inputSchema", None),
126
+ }
127
+ for t in tools
128
+ ]
129
+ json.dump(out, sys.stdout, ensure_ascii=False, indent=2)
130
+ sys.stdout.write("\n")
131
+ return 0
132
+ except Exception:
133
+ log.exception("Failed to list MCP tools")
134
+ return 1
135
+
136
+ export_dir = args.export_dir if args.export_dir is not None else DEFAULT_EXPORT_DIR
137
+ if args.output_filename:
138
+ filename = args.output_filename
139
+ elif args.dated:
140
+ filename = _week_filename(hooks.episode_file_prefix)
141
+ else:
142
+ filename = DEFAULT_MARKDOWN_NAME
143
+
144
+ try:
145
+ if args.markdown_input:
146
+ md_input = Path(args.markdown_input).resolve()
147
+ if not md_input.is_file():
148
+ log.error("Markdown input not found: %s", md_input)
149
+ return 1
150
+ body = md_input.read_text(encoding="utf-8")
151
+ path = md_input
152
+ threads = None
153
+ log.info("Using existing Markdown: %s", path)
154
+ else:
155
+ threads = hooks.extract_weekly_key_info()
156
+ if not threads:
157
+ log.error("Extraction returned no threads")
158
+ return 1
159
+
160
+ if len(threads) > 7:
161
+ threads = hooks.select_threads(threads)
162
+ log.info("Selected %d threads after scoring", len(threads))
163
+
164
+ if not args.skip_details:
165
+ log.info("Fetching thread details (replies) for %d threads", len(threads))
166
+ threads = hooks.fetch_thread_details(threads)
167
+
168
+ raw_md = hooks.threads_to_source_markdown(threads)
169
+
170
+ if args.skip_briefing:
171
+ body = raw_md
172
+ log.info("Skipping Gemini briefing")
173
+ else:
174
+ body = write_briefing_markdown(raw_md)
175
+
176
+ path = export_for_notebooklm(body, export_dir=export_dir, filename=filename)
177
+ log.info("Wrote NotebookLM source: %s", path)
178
+
179
+ audio_path = None
180
+
181
+ if args.publish_notebooklm:
182
+ audio_path = args.notebooklm_audio_out
183
+ if audio_path is None:
184
+ audio_path = _default_audio_out(args.dated, hooks)
185
+ else:
186
+ audio_path = audio_path.resolve()
187
+ log.info("Publishing to NotebookLM; audio output: %s", audio_path)
188
+ publish_audio(path, audio_path)
189
+ log.info("Downloaded Audio Overview: %s", audio_path)
190
+
191
+ if args.generate_post:
192
+ platform_links = None
193
+ raw_links = os.environ.get("PODCAST_PLATFORM_LINKS", "").strip()
194
+ if raw_links:
195
+ try:
196
+ platform_links = json.loads(raw_links)
197
+ except json.JSONDecodeError:
198
+ log.warning("PODCAST_PLATFORM_LINKS is not valid JSON; ignoring")
199
+ post_path = hooks.write_forum_post(
200
+ path, audio_url=args.audio_url, extra_links=platform_links, threads=threads,
201
+ )
202
+ log.info("Wrote forum post: %s", post_path)
203
+
204
+ if args.generate_rss:
205
+ rss_audio_url = args.audio_url
206
+ if not rss_audio_url:
207
+ iso = date.today().isocalendar()
208
+ rss_audio_url = hooks.week_episode_url(iso.year, iso.week)
209
+ rss_mp3 = args.mp3_path or audio_path
210
+ feed_path = hooks.generate_rss_feed(
211
+ path,
212
+ args.rss_output,
213
+ audio_url=rss_audio_url,
214
+ duration=args.episode_duration,
215
+ threads=threads,
216
+ mp3_path=rss_mp3,
217
+ )
218
+ log.info("Updated RSS feed: %s", feed_path)
219
+
220
+ if audio_path and audio_path.is_file():
221
+ print(str(audio_path), file=sys.stdout)
222
+ else:
223
+ print(str(path), file=sys.stdout)
224
+ return 0
225
+ except Exception:
226
+ log.exception("Pipeline failed")
227
+ return 1
@@ -0,0 +1,5 @@
1
+ """Publication integrations supplied by CastForge."""
2
+
3
+ from castforge.publishers.r2 import R2Publisher, validate_public_audio
4
+
5
+ __all__ = ["R2Publisher", "validate_public_audio"]
@@ -0,0 +1,136 @@
1
+ """Cloudflare R2 publication through its S3-compatible API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+ from typing import Any, Callable
8
+ from urllib.request import Request, urlopen
9
+
10
+
11
+ def validate_public_audio(
12
+ url: str,
13
+ *,
14
+ expected_length: int | None = None,
15
+ opener: Callable[..., Any] = urlopen,
16
+ timeout: float = 60,
17
+ ) -> None:
18
+ request = Request(url, method="HEAD", headers={"User-Agent": "CastForge/0.1"})
19
+ with opener(request, timeout=timeout) as response:
20
+ status = getattr(response, "status", response.getcode())
21
+ content_type = response.headers.get("Content-Type", "").split(";", 1)[0].lower()
22
+ content_length = int(response.headers.get("Content-Length", "0") or 0)
23
+ if status != 200:
24
+ raise RuntimeError(f"public audio returned HTTP {status}: {url}")
25
+ if content_type != "audio/mpeg":
26
+ raise RuntimeError(f"public audio has wrong content type {content_type!r}: {url}")
27
+ if content_length < 1:
28
+ raise RuntimeError(f"public audio has no content length: {url}")
29
+ if expected_length is not None and content_length != expected_length:
30
+ raise RuntimeError(
31
+ f"public audio length mismatch: expected {expected_length}, got {content_length}"
32
+ )
33
+
34
+
35
+ class R2Publisher:
36
+ def __init__(
37
+ self,
38
+ *,
39
+ client: Any,
40
+ bucket: str,
41
+ public_base_url: str,
42
+ max_bucket_bytes: int = 0,
43
+ opener: Callable[..., Any] = urlopen,
44
+ ) -> None:
45
+ self.client = client
46
+ self.bucket = bucket
47
+ self.public_base_url = public_base_url.rstrip("/")
48
+ self.max_bucket_bytes = max_bucket_bytes
49
+ self.opener = opener
50
+
51
+ @classmethod
52
+ def from_env(
53
+ cls,
54
+ *,
55
+ bucket: str,
56
+ endpoint_url: str,
57
+ public_base_url: str,
58
+ access_key_env: str = "R2_ACCESS_KEY_ID",
59
+ secret_key_env: str = "R2_SECRET_ACCESS_KEY",
60
+ max_bucket_bytes: int = 0,
61
+ ) -> "R2Publisher":
62
+ access_key = os.environ.get(access_key_env, "").strip()
63
+ secret_key = os.environ.get(secret_key_env, "").strip()
64
+ if not access_key or not secret_key:
65
+ raise RuntimeError(f"R2 credentials are required in {access_key_env} and {secret_key_env}")
66
+ try:
67
+ import boto3
68
+ except ImportError as error:
69
+ raise RuntimeError('Install the R2 integration with: pip install "castforge[r2]"') from error
70
+ client = boto3.client(
71
+ "s3",
72
+ endpoint_url=endpoint_url,
73
+ aws_access_key_id=access_key,
74
+ aws_secret_access_key=secret_key,
75
+ region_name="auto",
76
+ )
77
+ return cls(
78
+ client=client,
79
+ bucket=bucket,
80
+ public_base_url=public_base_url,
81
+ max_bucket_bytes=max_bucket_bytes,
82
+ )
83
+
84
+ def _bucket_usage(self, object_key: str) -> tuple[int, int]:
85
+ total = 0
86
+ replaced_size = 0
87
+ continuation_token: str | None = None
88
+ while True:
89
+ request = {"Bucket": self.bucket}
90
+ if continuation_token:
91
+ request["ContinuationToken"] = continuation_token
92
+ page = self.client.list_objects_v2(**request)
93
+ for item in page.get("Contents", []):
94
+ size = int(item.get("Size", 0))
95
+ total += size
96
+ if item.get("Key") == object_key:
97
+ replaced_size = size
98
+ if not page.get("IsTruncated"):
99
+ return total, replaced_size
100
+ continuation_token = page.get("NextContinuationToken")
101
+ if not continuation_token:
102
+ raise RuntimeError("R2 bucket listing was truncated without a continuation token")
103
+
104
+ def publish(self, local_audio: Path, object_key: str) -> str:
105
+ audio = Path(local_audio)
106
+ if not audio.is_file():
107
+ raise FileNotFoundError(f"audio file not found: {audio}")
108
+ size = audio.stat().st_size
109
+ if size < 1:
110
+ raise ValueError("audio file is empty")
111
+ if audio.suffix.lower() != ".mp3":
112
+ raise ValueError("R2 publisher currently accepts MP3 audio only")
113
+ normalized_key = object_key.lstrip("/")
114
+ if self.max_bucket_bytes:
115
+ bucket_size, replaced_size = self._bucket_usage(normalized_key)
116
+ projected_size = bucket_size - replaced_size + size
117
+ if projected_size > self.max_bucket_bytes:
118
+ raise RuntimeError(
119
+ "R2 bucket limit would be exceeded: "
120
+ f"projected {projected_size} bytes > {self.max_bucket_bytes} bytes"
121
+ )
122
+ with audio.open("rb") as handle:
123
+ self.client.put_object(
124
+ Bucket=self.bucket,
125
+ Key=normalized_key,
126
+ Body=handle,
127
+ ContentType="audio/mpeg",
128
+ CacheControl="public, max-age=31536000, immutable",
129
+ )
130
+ public_url = f"{self.public_base_url}/{normalized_key}"
131
+ validate_public_audio(
132
+ public_url,
133
+ expected_length=size,
134
+ opener=self.opener,
135
+ )
136
+ return public_url