castforge 0.1.1__tar.gz

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CastForge contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,176 @@
1
+ Metadata-Version: 2.4
2
+ Name: castforge
3
+ Version: 0.1.1
4
+ Summary: Open-source framework for automated podcast pipelines
5
+ Author: CastForge contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/lifan-builds/castforge
8
+ Project-URL: Repository, https://github.com/lifan-builds/castforge
9
+ Project-URL: Documentation, https://github.com/lifan-builds/castforge#readme
10
+ Project-URL: Issues, https://github.com/lifan-builds/castforge/issues
11
+ Keywords: podcast,automation,notebooklm,rss,gemini
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Multimedia :: Sound/Audio
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: anyio>=4
23
+ Requires-Dist: python-dotenv>=1
24
+ Requires-Dist: PyYAML>=6
25
+ Provides-Extra: gemini
26
+ Requires-Dist: google-genai>=1.69; extra == "gemini"
27
+ Provides-Extra: notebooklm
28
+ Requires-Dist: notebooklm-py[browser]>=0.3.4; extra == "notebooklm"
29
+ Provides-Extra: r2
30
+ Requires-Dist: boto3>=1.35; extra == "r2"
31
+ Provides-Extra: test
32
+ Requires-Dist: pytest>=8; extra == "test"
33
+ Dynamic: license-file
34
+
35
+ # CastForge
36
+
37
+ Open-source Python framework for repeatable, source-transparent podcast pipelines.
38
+
39
+ CastForge separates reusable production mechanics from show-owned editorial policy. It can normalize cited sources, record an auditable episode manifest, generate NotebookLM audio, publish MP3s to Cloudflare R2, update RSS atomically, and validate the result. Each show keeps its own sources, prompts, identity, schedule, and feed.
40
+
41
+ CastForge powers [Nitan Podcast](https://github.com/lifan-builds/nitan-podcast), a production Chinese podcast generated from USCardForum discussions.
42
+
43
+ ## Install
44
+
45
+ The `v0.1.1` wheel is attached to the [GitHub release](https://github.com/lifan-builds/castforge/releases/tag/v0.1.1). Until the first PyPI upload is authorized, install the immutable release tag:
46
+
47
+ ```bash
48
+ pip install "castforge @ git+https://github.com/lifan-builds/castforge.git@v0.1.1"
49
+
50
+ # Optional production integrations
51
+ pip install "castforge[notebooklm,r2] @ git+https://github.com/lifan-builds/castforge.git@v0.1.1"
52
+ ```
53
+
54
+ Python 3.10 or newer is supported. Gemini, NotebookLM, and R2 dependencies remain optional.
55
+
56
+ ## First episode in under 20 minutes
57
+
58
+ ```bash
59
+ mkdir my-show && cd my-show
60
+ castforge init
61
+ castforge run --config podcast.yaml --date 2026-08-11
62
+ castforge validate --config podcast.yaml --date 2026-08-11
63
+ ```
64
+
65
+ The fixture-backed starter creates:
66
+
67
+ - a cited NotebookLM source document;
68
+ - a deterministic episode manifest;
69
+ - an RSS feed with a positive audio enclosure contract.
70
+
71
+ Fixture mode does not call an LLM, audio service, or public endpoint. Replace the example sources and public values before production use.
72
+
73
+ ## Core contracts
74
+
75
+ ```python
76
+ from castforge import EpisodeManifest, SourceItem, StoryCluster
77
+ from castforge.contracts import AudioProvider, Publisher, SourceAdapter
78
+ ```
79
+
80
+ - `SourceItem` normalizes one primary, independent, or trend-signal source.
81
+ - `StoryCluster` groups duplicate coverage and qualifies only a primary source or two independent reports.
82
+ - `EpisodeManifest` preserves the selected stories, citations, source document, pipeline version, and public audio identity.
83
+ - `SourceAdapter`, `AudioProvider`, and `Publisher` are intentionally small protocols implemented by show repositories or integrations.
84
+
85
+ The generic CLI consumes `podcast.yaml`; show-specific collectors and ranking remain in the show repository.
86
+
87
+ ## Commands
88
+
89
+ ```bash
90
+ castforge init [directory]
91
+ castforge run --config podcast.yaml --date YYYY-MM-DD [--shadow]
92
+ castforge validate --config podcast.yaml [--date YYYY-MM-DD] [--check-public]
93
+ ```
94
+
95
+ `--shadow` creates the source and manifest artifacts but does not mutate RSS or R2. Same-date production reruns replace the date-keyed RSS item instead of duplicating it.
96
+
97
+ ## Production configuration
98
+
99
+ See [`examples/podcast.yaml`](examples/podcast.yaml) for the complete schema.
100
+
101
+ For NotebookLM:
102
+
103
+ ```yaml
104
+ audio:
105
+ provider: notebooklm
106
+ output_dir: build/audio
107
+ duration: 00:06:00
108
+ public_url_template: https://audio.example.com/episodes/{filename}
109
+ language: en
110
+ audio_length: short
111
+ ```
112
+
113
+ Install and authenticate the integration once on the runner:
114
+
115
+ ```bash
116
+ pip install "castforge[notebooklm]"
117
+ playwright install chromium
118
+ notebooklm login
119
+ ```
120
+
121
+ Set `NOTEBOOKLM_NOTEBOOK_ID`. Authentication state and notebook ownership stay outside the show repository.
122
+
123
+ For Cloudflare R2:
124
+
125
+ ```yaml
126
+ publication:
127
+ provider: r2
128
+ bucket: podcast-audio
129
+ endpoint_url: https://ACCOUNT_ID.r2.cloudflarestorage.com
130
+ public_base_url: https://audio.example.com
131
+ access_key_env: R2_ACCESS_KEY_ID
132
+ secret_key_env: R2_SECRET_ACCESS_KEY
133
+ download_url_prefix: https://op3.dev/e/
134
+ max_bucket_bytes: 9000000000
135
+ ```
136
+
137
+ CastForge totals the bucket before each upload and refuses a projected size above `max_bucket_bytes`; overwrites subtract the prior object and listings paginate safely. It then uploads MP3s as `audio/mpeg` and sends a public `HEAD` request to verify status, MIME type, and byte length before updating RSS. A show may apply a privacy-respecting download redirect such as OP3 after the R2 origin passes validation. A failed capacity check, generation, upload, or public check leaves the feed unchanged.
138
+
139
+ ## Existing hook pipeline
140
+
141
+ Production shows can continue wiring show-specific extraction and publishing through `PipelineHooks` while migrating to config-driven artifacts:
142
+
143
+ ```python
144
+ from castforge.pipeline import PipelineHooks, main as castforge_main
145
+
146
+ def main(argv=None):
147
+ hooks = PipelineHooks(
148
+ extract_weekly_key_info=extract,
149
+ fetch_thread_details=fetch_details,
150
+ list_mcp_tools=list_tools,
151
+ select_threads=select,
152
+ threads_to_source_markdown=to_markdown,
153
+ write_forum_post=write_post,
154
+ generate_rss_feed=generate_feed,
155
+ episode_file_prefix="weekly_episode",
156
+ week_episode_filename=episode_filename,
157
+ week_episode_url=episode_url,
158
+ )
159
+ return castforge_main(argv, hooks=hooks)
160
+ ```
161
+
162
+ CastForge owns execution and provider integrations. The show owns sources, editorial policy, branding, secrets, scheduling, feeds, episodes, and public compatibility.
163
+
164
+ ## Development
165
+
166
+ ```bash
167
+ python -m pip install -e ".[test]"
168
+ python -m pytest
169
+ python -m build
170
+ ```
171
+
172
+ Tests are offline and use fake provider clients. Live NotebookLM and R2 checks require explicit credentials and are not part of the ordinary suite.
173
+
174
+ ## License
175
+
176
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,142 @@
1
+ # CastForge
2
+
3
+ Open-source Python framework for repeatable, source-transparent podcast pipelines.
4
+
5
+ CastForge separates reusable production mechanics from show-owned editorial policy. It can normalize cited sources, record an auditable episode manifest, generate NotebookLM audio, publish MP3s to Cloudflare R2, update RSS atomically, and validate the result. Each show keeps its own sources, prompts, identity, schedule, and feed.
6
+
7
+ CastForge powers [Nitan Podcast](https://github.com/lifan-builds/nitan-podcast), a production Chinese podcast generated from USCardForum discussions.
8
+
9
+ ## Install
10
+
11
+ The `v0.1.1` wheel is attached to the [GitHub release](https://github.com/lifan-builds/castforge/releases/tag/v0.1.1). Until the first PyPI upload is authorized, install the immutable release tag:
12
+
13
+ ```bash
14
+ pip install "castforge @ git+https://github.com/lifan-builds/castforge.git@v0.1.1"
15
+
16
+ # Optional production integrations
17
+ pip install "castforge[notebooklm,r2] @ git+https://github.com/lifan-builds/castforge.git@v0.1.1"
18
+ ```
19
+
20
+ Python 3.10 or newer is supported. Gemini, NotebookLM, and R2 dependencies remain optional.
21
+
22
+ ## First episode in under 20 minutes
23
+
24
+ ```bash
25
+ mkdir my-show && cd my-show
26
+ castforge init
27
+ castforge run --config podcast.yaml --date 2026-08-11
28
+ castforge validate --config podcast.yaml --date 2026-08-11
29
+ ```
30
+
31
+ The fixture-backed starter creates:
32
+
33
+ - a cited NotebookLM source document;
34
+ - a deterministic episode manifest;
35
+ - an RSS feed with a positive audio enclosure contract.
36
+
37
+ Fixture mode does not call an LLM, audio service, or public endpoint. Replace the example sources and public values before production use.
38
+
39
+ ## Core contracts
40
+
41
+ ```python
42
+ from castforge import EpisodeManifest, SourceItem, StoryCluster
43
+ from castforge.contracts import AudioProvider, Publisher, SourceAdapter
44
+ ```
45
+
46
+ - `SourceItem` normalizes one primary, independent, or trend-signal source.
47
+ - `StoryCluster` groups duplicate coverage and qualifies only a primary source or two independent reports.
48
+ - `EpisodeManifest` preserves the selected stories, citations, source document, pipeline version, and public audio identity.
49
+ - `SourceAdapter`, `AudioProvider`, and `Publisher` are intentionally small protocols implemented by show repositories or integrations.
50
+
51
+ The generic CLI consumes `podcast.yaml`; show-specific collectors and ranking remain in the show repository.
52
+
53
+ ## Commands
54
+
55
+ ```bash
56
+ castforge init [directory]
57
+ castforge run --config podcast.yaml --date YYYY-MM-DD [--shadow]
58
+ castforge validate --config podcast.yaml [--date YYYY-MM-DD] [--check-public]
59
+ ```
60
+
61
+ `--shadow` creates the source and manifest artifacts but does not mutate RSS or R2. Same-date production reruns replace the date-keyed RSS item instead of duplicating it.
62
+
63
+ ## Production configuration
64
+
65
+ See [`examples/podcast.yaml`](examples/podcast.yaml) for the complete schema.
66
+
67
+ For NotebookLM:
68
+
69
+ ```yaml
70
+ audio:
71
+ provider: notebooklm
72
+ output_dir: build/audio
73
+ duration: 00:06:00
74
+ public_url_template: https://audio.example.com/episodes/{filename}
75
+ language: en
76
+ audio_length: short
77
+ ```
78
+
79
+ Install and authenticate the integration once on the runner:
80
+
81
+ ```bash
82
+ pip install "castforge[notebooklm]"
83
+ playwright install chromium
84
+ notebooklm login
85
+ ```
86
+
87
+ Set `NOTEBOOKLM_NOTEBOOK_ID`. Authentication state and notebook ownership stay outside the show repository.
88
+
89
+ For Cloudflare R2:
90
+
91
+ ```yaml
92
+ publication:
93
+ provider: r2
94
+ bucket: podcast-audio
95
+ endpoint_url: https://ACCOUNT_ID.r2.cloudflarestorage.com
96
+ public_base_url: https://audio.example.com
97
+ access_key_env: R2_ACCESS_KEY_ID
98
+ secret_key_env: R2_SECRET_ACCESS_KEY
99
+ download_url_prefix: https://op3.dev/e/
100
+ max_bucket_bytes: 9000000000
101
+ ```
102
+
103
+ CastForge totals the bucket before each upload and refuses a projected size above `max_bucket_bytes`; overwrites subtract the prior object and listings paginate safely. It then uploads MP3s as `audio/mpeg` and sends a public `HEAD` request to verify status, MIME type, and byte length before updating RSS. A show may apply a privacy-respecting download redirect such as OP3 after the R2 origin passes validation. A failed capacity check, generation, upload, or public check leaves the feed unchanged.
104
+
105
+ ## Existing hook pipeline
106
+
107
+ Production shows can continue wiring show-specific extraction and publishing through `PipelineHooks` while migrating to config-driven artifacts:
108
+
109
+ ```python
110
+ from castforge.pipeline import PipelineHooks, main as castforge_main
111
+
112
+ def main(argv=None):
113
+ hooks = PipelineHooks(
114
+ extract_weekly_key_info=extract,
115
+ fetch_thread_details=fetch_details,
116
+ list_mcp_tools=list_tools,
117
+ select_threads=select,
118
+ threads_to_source_markdown=to_markdown,
119
+ write_forum_post=write_post,
120
+ generate_rss_feed=generate_feed,
121
+ episode_file_prefix="weekly_episode",
122
+ week_episode_filename=episode_filename,
123
+ week_episode_url=episode_url,
124
+ )
125
+ return castforge_main(argv, hooks=hooks)
126
+ ```
127
+
128
+ CastForge owns execution and provider integrations. The show owns sources, editorial policy, branding, secrets, scheduling, feeds, episodes, and public compatibility.
129
+
130
+ ## Development
131
+
132
+ ```bash
133
+ python -m pip install -e ".[test]"
134
+ python -m pytest
135
+ python -m build
136
+ ```
137
+
138
+ Tests are offline and use fake provider clients. Live NotebookLM and R2 checks require explicit credentials and are not part of the ordinary suite.
139
+
140
+ ## License
141
+
142
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,7 @@
1
+ """Reusable contracts and orchestration for automated podcast shows."""
2
+
3
+ from castforge.models import EpisodeManifest, SourceItem, StoryCluster
4
+
5
+ __all__ = ["EpisodeManifest", "SourceItem", "StoryCluster", "__version__"]
6
+
7
+ __version__ = "0.1.1"
@@ -0,0 +1,9 @@
1
+ """Module entry point for ``python -m castforge``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from castforge.cli import main
6
+
7
+
8
+ if __name__ == "__main__":
9
+ raise SystemExit(main())
@@ -0,0 +1,45 @@
1
+ """Reusable Gemini briefing step for CastForge pipelines."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ SYSTEM_PROMPT = """你是播客来源文档编辑,正在把抓取到的论坛素材整理成供音频生成工具使用的中文 Markdown。
11
+
12
+ 请输出**事实优先、来源约束清晰**的结构化 Markdown。要求:
13
+ - 如果输入已经包含 Story Brief、What Happened、Evidence From Source、Informative Replies、Caveats / Unknowns、Editorial Voice 等结构,保留并强化这些结构,不要改写成纯评论稿。
14
+ - 每个话题先讲清楚事实:发生了什么、必要背景、来源里明确给出的数字/日期/限制/项目名/具体说法。
15
+ - 社区回复只能作为信息、修正、数据点或分歧使用;不要让玩笑、情绪化短评或高赞吐槽盖过事实。
16
+ - 对缺失背景、YMMV、争议点、未经验证的说法要明确标注,不要替来源补全不存在的因果。
17
+ - 保留论坛常用术语与梗(如 5/24、杀全家、史高、冥币)的原样表述,但先解释必要上下文。
18
+ - 语气可以生动,但不要为了戏剧性牺牲准确性;不要写双人对话脚本,不要分配主持人台词。
19
+
20
+ 直接输出 Markdown 正文,不要外层代码块标记。"""
21
+
22
+
23
+ def write_briefing_markdown(raw_extraction_text: str) -> str:
24
+ """Call Gemini with UTF-8; return a single Markdown document for upload."""
25
+ api_key = os.environ.get("GEMINI_API_KEY", "").strip()
26
+ if not api_key:
27
+ raise RuntimeError("GEMINI_API_KEY is required when briefing is enabled")
28
+
29
+ from google import genai
30
+
31
+ model_id = os.environ.get("GEMINI_MODEL", "gemini-2.0-flash").strip()
32
+ client = genai.Client(api_key=api_key)
33
+
34
+ user_part = f"以下是需要整理的原始素材(可为结构化列表或长文本):\n\n{raw_extraction_text}"
35
+ logger.info("Calling Gemini model=%r for briefing", model_id)
36
+ response = client.models.generate_content(
37
+ model=model_id,
38
+ contents=[SYSTEM_PROMPT, user_part],
39
+ config=genai.types.GenerateContentConfig(temperature=0.5),
40
+ )
41
+
42
+ text = response.text or ""
43
+ if not text.strip():
44
+ raise RuntimeError("Gemini returned empty briefing text")
45
+ return text.strip()
@@ -0,0 +1,63 @@
1
+ """Command-line interface for config-driven CastForge shows."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import logging
7
+ import sys
8
+ from datetime import date
9
+ from pathlib import Path
10
+
11
+ from castforge.config import load_config
12
+ from castforge.runner import run_episode
13
+ from castforge.scaffold import initialize_show
14
+ from castforge.validation import validate_project
15
+
16
+
17
+ def build_parser() -> argparse.ArgumentParser:
18
+ parser = argparse.ArgumentParser(prog="castforge", description="Build source-transparent podcast pipelines")
19
+ subparsers = parser.add_subparsers(dest="command", required=True)
20
+
21
+ init_parser = subparsers.add_parser("init", help="create a minimal show repository")
22
+ init_parser.add_argument("directory", nargs="?", type=Path, default=Path.cwd())
23
+
24
+ run_parser = subparsers.add_parser("run", help="run one date-keyed episode")
25
+ run_parser.add_argument("--config", type=Path, default=Path("podcast.yaml"))
26
+ run_parser.add_argument("--date", dest="episode_date", type=date.fromisoformat, default=date.today())
27
+ run_parser.add_argument("--shadow", action="store_true", help="generate artifacts without publishing RSS or R2")
28
+
29
+ validate_parser = subparsers.add_parser("validate", help="validate manifests, RSS, and optional public audio")
30
+ validate_parser.add_argument("--config", type=Path, default=Path("podcast.yaml"))
31
+ validate_parser.add_argument("--date", dest="episode_date", default=None)
32
+ validate_parser.add_argument("--check-public", action="store_true")
33
+ return parser
34
+
35
+
36
+ def main(argv: list[str] | None = None) -> int:
37
+ args = build_parser().parse_args(argv)
38
+ try:
39
+ if args.command == "init":
40
+ for path in initialize_show(args.directory):
41
+ print(path)
42
+ return 0
43
+ config = load_config(args.config)
44
+ if args.command == "run":
45
+ manifest = run_episode(config, args.episode_date, shadow=args.shadow)
46
+ print(config.outputs.manifests / f"{manifest.episode_date}.json")
47
+ return 0
48
+ if args.command == "validate":
49
+ errors = validate_project(
50
+ config,
51
+ episode_date=args.episode_date,
52
+ check_public=args.check_public,
53
+ )
54
+ if errors:
55
+ for error in errors:
56
+ print(f"ERROR: {error}", file=sys.stderr)
57
+ return 1
58
+ print("CastForge validation passed")
59
+ return 0
60
+ except Exception as error:
61
+ logging.getLogger("castforge").error("%s", error)
62
+ return 1
63
+ raise AssertionError(f"unhandled command: {args.command}")
@@ -0,0 +1,210 @@
1
+ """Configuration loading for generic CastForge show repositories."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Any
8
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
9
+
10
+ import yaml
11
+
12
+
13
+ def _mapping(raw: Any, name: str) -> dict[str, Any]:
14
+ if not isinstance(raw, dict):
15
+ raise ValueError(f"{name} must be a mapping")
16
+ return raw
17
+
18
+
19
+ def _text(raw: dict[str, Any], key: str, section: str) -> str:
20
+ value = str(raw.get(key, "") or "").strip()
21
+ if not value:
22
+ raise ValueError(f"{section}.{key} is required")
23
+ return value
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class ShowConfig:
28
+ slug: str
29
+ title: str
30
+ description: str
31
+ language: str
32
+ author: str
33
+ site_url: str
34
+ feed_url: str
35
+ cover_art_url: str
36
+ episode_guid_prefix: str
37
+ episode_file_prefix: str
38
+ cadence: str
39
+ timezone: str
40
+ publication_hour: int
41
+
42
+
43
+ @dataclass(frozen=True, slots=True)
44
+ class SourceConfig:
45
+ fixture: Path
46
+
47
+
48
+ @dataclass(frozen=True, slots=True)
49
+ class SelectionConfig:
50
+ max_stories: int = 5
51
+ max_per_organization: int = 1
52
+ max_per_category: int = 1
53
+ recent_days: int = 7
54
+
55
+
56
+ @dataclass(frozen=True, slots=True)
57
+ class AudioConfig:
58
+ provider: str
59
+ output_dir: Path
60
+ duration: str
61
+ public_url_template: str
62
+ fixture_length_bytes: int = 0
63
+ language: str = "en"
64
+ instructions: str = ""
65
+ audio_length: str = "short"
66
+
67
+
68
+ @dataclass(frozen=True, slots=True)
69
+ class PublicationConfig:
70
+ provider: str
71
+ bucket: str = ""
72
+ endpoint_url: str = ""
73
+ public_base_url: str = ""
74
+ access_key_env: str = "R2_ACCESS_KEY_ID"
75
+ secret_key_env: str = "R2_SECRET_ACCESS_KEY"
76
+ download_url_prefix: str = ""
77
+ max_bucket_bytes: int = 0
78
+
79
+
80
+ @dataclass(frozen=True, slots=True)
81
+ class OutputConfig:
82
+ root: Path
83
+ feed: Path
84
+ manifests: Path
85
+ sources: Path
86
+
87
+
88
+ @dataclass(frozen=True, slots=True)
89
+ class PodcastConfig:
90
+ path: Path
91
+ show: ShowConfig
92
+ source: SourceConfig
93
+ selection: SelectionConfig
94
+ audio: AudioConfig
95
+ publication: PublicationConfig
96
+ outputs: OutputConfig
97
+
98
+
99
+ def _resolve(base: Path, value: Any, default: str) -> Path:
100
+ candidate = Path(str(value or default))
101
+ return candidate if candidate.is_absolute() else (base / candidate).resolve()
102
+
103
+
104
+ def load_config(path: Path) -> PodcastConfig:
105
+ config_path = Path(path).resolve()
106
+ raw = yaml.safe_load(config_path.read_text(encoding="utf-8"))
107
+ root = _mapping(raw, "config")
108
+ if int(root.get("version", 0)) != 1:
109
+ raise ValueError("version must be 1")
110
+
111
+ base = config_path.parent
112
+ show_raw = _mapping(root.get("show"), "show")
113
+ timezone = _text(show_raw, "timezone", "show")
114
+ try:
115
+ ZoneInfo(timezone)
116
+ except ZoneInfoNotFoundError as error:
117
+ raise ValueError(f"unknown timezone: {timezone}") from error
118
+ cadence = str(show_raw.get("cadence", "daily")).strip()
119
+ if cadence not in {"daily", "weekly"}:
120
+ raise ValueError("show.cadence must be daily or weekly")
121
+ show = ShowConfig(
122
+ slug=_text(show_raw, "slug", "show"),
123
+ title=_text(show_raw, "title", "show"),
124
+ description=_text(show_raw, "description", "show"),
125
+ language=_text(show_raw, "language", "show"),
126
+ author=_text(show_raw, "author", "show"),
127
+ site_url=_text(show_raw, "site_url", "show"),
128
+ feed_url=_text(show_raw, "feed_url", "show"),
129
+ cover_art_url=_text(show_raw, "cover_art_url", "show"),
130
+ episode_guid_prefix=_text(show_raw, "episode_guid_prefix", "show"),
131
+ episode_file_prefix=_text(show_raw, "episode_file_prefix", "show"),
132
+ cadence=cadence,
133
+ timezone=timezone,
134
+ publication_hour=int(show_raw.get("publication_hour", 6)),
135
+ )
136
+ if show.publication_hour < 0 or show.publication_hour > 23:
137
+ raise ValueError("show.publication_hour must be between 0 and 23")
138
+
139
+ source_raw = _mapping(root.get("source"), "source")
140
+ source = SourceConfig(fixture=_resolve(base, source_raw.get("fixture"), "fixtures/sources.json"))
141
+
142
+ selection_raw = _mapping(root.get("selection", {}), "selection")
143
+ selection = SelectionConfig(
144
+ max_stories=int(selection_raw.get("max_stories", 5)),
145
+ max_per_organization=int(selection_raw.get("max_per_organization", 1)),
146
+ max_per_category=int(selection_raw.get("max_per_category", 1)),
147
+ recent_days=int(selection_raw.get("recent_days", 7)),
148
+ )
149
+ if min(
150
+ selection.max_stories,
151
+ selection.max_per_organization,
152
+ selection.max_per_category,
153
+ ) < 1:
154
+ raise ValueError("selection limits must be positive")
155
+
156
+ audio_raw = _mapping(root.get("audio"), "audio")
157
+ audio = AudioConfig(
158
+ provider=_text(audio_raw, "provider", "audio"),
159
+ output_dir=_resolve(base, audio_raw.get("output_dir"), "build/audio"),
160
+ duration=str(audio_raw.get("duration", "00:06:00")),
161
+ public_url_template=_text(audio_raw, "public_url_template", "audio"),
162
+ fixture_length_bytes=int(audio_raw.get("fixture_length_bytes", 0)),
163
+ language=str(audio_raw.get("language", show.language)),
164
+ instructions=str(audio_raw.get("instructions", "") or ""),
165
+ audio_length=str(audio_raw.get("audio_length", "short") or "short"),
166
+ )
167
+ if audio.provider not in {"fixture", "notebooklm"}:
168
+ raise ValueError("audio.provider must be fixture or notebooklm")
169
+ if audio.provider == "fixture" and audio.fixture_length_bytes < 1:
170
+ raise ValueError("audio.fixture_length_bytes must be positive for fixture audio")
171
+
172
+ publication_raw = _mapping(root.get("publication", {"provider": "fixture"}), "publication")
173
+ publication = PublicationConfig(
174
+ provider=str(publication_raw.get("provider", "fixture") or "fixture"),
175
+ bucket=str(publication_raw.get("bucket", "") or ""),
176
+ endpoint_url=str(publication_raw.get("endpoint_url", "") or ""),
177
+ public_base_url=str(publication_raw.get("public_base_url", "") or ""),
178
+ access_key_env=str(publication_raw.get("access_key_env", "R2_ACCESS_KEY_ID")),
179
+ secret_key_env=str(publication_raw.get("secret_key_env", "R2_SECRET_ACCESS_KEY")),
180
+ download_url_prefix=str(publication_raw.get("download_url_prefix", "") or ""),
181
+ max_bucket_bytes=int(publication_raw.get("max_bucket_bytes", 0)),
182
+ )
183
+ if publication.provider not in {"fixture", "r2"}:
184
+ raise ValueError("publication.provider must be fixture or r2")
185
+ if publication.provider == "r2" and not all(
186
+ (publication.bucket, publication.endpoint_url, publication.public_base_url)
187
+ ):
188
+ raise ValueError("R2 publication requires bucket, endpoint_url, and public_base_url")
189
+ if publication.provider == "r2" and audio.provider == "fixture":
190
+ raise ValueError("R2 publication requires non-fixture audio")
191
+ if publication.max_bucket_bytes < 0:
192
+ raise ValueError("publication.max_bucket_bytes must not be negative")
193
+
194
+ output_raw = _mapping(root.get("outputs", {}), "outputs")
195
+ output_root = _resolve(base, output_raw.get("root"), "build")
196
+ outputs = OutputConfig(
197
+ root=output_root,
198
+ feed=_resolve(base, output_raw.get("feed"), "build/feed.xml"),
199
+ manifests=_resolve(base, output_raw.get("manifests"), "build/manifests"),
200
+ sources=_resolve(base, output_raw.get("sources"), "build/sources"),
201
+ )
202
+ return PodcastConfig(
203
+ path=config_path,
204
+ show=show,
205
+ source=source,
206
+ selection=selection,
207
+ audio=audio,
208
+ publication=publication,
209
+ outputs=outputs,
210
+ )