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.
- castforge/__init__.py +7 -0
- castforge/__main__.py +9 -0
- castforge/briefing.py +45 -0
- castforge/cli.py +63 -0
- castforge/config.py +210 -0
- castforge/contracts.py +24 -0
- castforge/export.py +21 -0
- castforge/models.py +194 -0
- castforge/notebooklm_audio.py +228 -0
- castforge/pipeline.py +227 -0
- castforge/publishers/__init__.py +5 -0
- castforge/publishers/r2.py +136 -0
- castforge/rss.py +120 -0
- castforge/runner.py +193 -0
- castforge/scaffold.py +93 -0
- castforge/validation.py +66 -0
- castforge-0.1.1.dist-info/METADATA +176 -0
- castforge-0.1.1.dist-info/RECORD +22 -0
- castforge-0.1.1.dist-info/WHEEL +5 -0
- castforge-0.1.1.dist-info/entry_points.txt +2 -0
- castforge-0.1.1.dist-info/licenses/LICENSE +21 -0
- castforge-0.1.1.dist-info/top_level.txt +1 -0
castforge/__init__.py
ADDED
castforge/__main__.py
ADDED
castforge/briefing.py
ADDED
|
@@ -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()
|
castforge/cli.py
ADDED
|
@@ -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}")
|
castforge/config.py
ADDED
|
@@ -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
|
+
)
|
castforge/contracts.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Small extension contracts for show-owned CastForge integrations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Protocol, runtime_checkable
|
|
8
|
+
|
|
9
|
+
from castforge.models import SourceItem
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@runtime_checkable
|
|
13
|
+
class SourceAdapter(Protocol):
|
|
14
|
+
def collect(self, start: datetime, end: datetime) -> list[SourceItem]: ...
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@runtime_checkable
|
|
18
|
+
class AudioProvider(Protocol):
|
|
19
|
+
def generate(self, source_document: Path, output_audio: Path) -> Path: ...
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@runtime_checkable
|
|
23
|
+
class Publisher(Protocol):
|
|
24
|
+
def publish(self, local_audio: Path, object_key: str) -> str: ...
|
castforge/export.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""NotebookLM-facing export helpers for CastForge pipelines."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
DEFAULT_EXPORT_DIR = Path("exports")
|
|
8
|
+
DEFAULT_MARKDOWN_NAME = "weekly_meika_notebooklm.md"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def export_for_notebooklm(
|
|
12
|
+
markdown_body: str,
|
|
13
|
+
export_dir: Path | None = None,
|
|
14
|
+
filename: str = DEFAULT_MARKDOWN_NAME,
|
|
15
|
+
) -> Path:
|
|
16
|
+
"""Create export_dir if needed, write markdown_body as UTF-8, return absolute path."""
|
|
17
|
+
out_dir = export_dir if export_dir is not None else DEFAULT_EXPORT_DIR
|
|
18
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
19
|
+
path = (out_dir / filename).resolve()
|
|
20
|
+
path.write_text(markdown_body, encoding="utf-8", newline="\n")
|
|
21
|
+
return path
|
castforge/models.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Serializable contracts shared by CastForge shows and pipeline stages."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import asdict, dataclass, field
|
|
7
|
+
from datetime import date, datetime
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Literal
|
|
10
|
+
|
|
11
|
+
SourceAuthority = Literal["primary", "independent", "signal"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _required_text(value: Any, field_name: str) -> str:
|
|
15
|
+
text = str(value or "").strip()
|
|
16
|
+
if not text:
|
|
17
|
+
raise ValueError(f"{field_name} is required")
|
|
18
|
+
return text
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, slots=True)
|
|
22
|
+
class SourceItem:
|
|
23
|
+
"""One normalized source discovered by a show-owned adapter."""
|
|
24
|
+
|
|
25
|
+
id: str
|
|
26
|
+
title: str
|
|
27
|
+
url: str
|
|
28
|
+
source: str
|
|
29
|
+
published_at: str
|
|
30
|
+
summary: str
|
|
31
|
+
authority: SourceAuthority = "signal"
|
|
32
|
+
organization: str = ""
|
|
33
|
+
category: str = ""
|
|
34
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
35
|
+
|
|
36
|
+
def __post_init__(self) -> None:
|
|
37
|
+
for name in ("id", "title", "url", "source", "published_at", "summary"):
|
|
38
|
+
object.__setattr__(self, name, _required_text(getattr(self, name), name))
|
|
39
|
+
if self.authority not in {"primary", "independent", "signal"}:
|
|
40
|
+
raise ValueError("authority must be primary, independent, or signal")
|
|
41
|
+
try:
|
|
42
|
+
datetime.fromisoformat(self.published_at.replace("Z", "+00:00"))
|
|
43
|
+
except ValueError as error:
|
|
44
|
+
raise ValueError("published_at must be ISO 8601") from error
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def from_dict(cls, raw: dict[str, Any]) -> "SourceItem":
|
|
48
|
+
return cls(
|
|
49
|
+
id=raw.get("id", ""),
|
|
50
|
+
title=raw.get("title", ""),
|
|
51
|
+
url=raw.get("url", ""),
|
|
52
|
+
source=raw.get("source", ""),
|
|
53
|
+
published_at=raw.get("published_at", ""),
|
|
54
|
+
summary=raw.get("summary", ""),
|
|
55
|
+
authority=raw.get("authority", "signal"),
|
|
56
|
+
organization=str(raw.get("organization", "") or ""),
|
|
57
|
+
category=str(raw.get("category", "") or ""),
|
|
58
|
+
metadata=dict(raw.get("metadata") or {}),
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
def to_dict(self) -> dict[str, Any]:
|
|
62
|
+
return asdict(self)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True, slots=True)
|
|
66
|
+
class StoryCluster:
|
|
67
|
+
"""Deduplicated, qualified sources describing one episode story."""
|
|
68
|
+
|
|
69
|
+
id: str
|
|
70
|
+
title: str
|
|
71
|
+
summary: str
|
|
72
|
+
category: str
|
|
73
|
+
organization: str
|
|
74
|
+
sources: tuple[SourceItem, ...]
|
|
75
|
+
selection_reason: str
|
|
76
|
+
|
|
77
|
+
def __post_init__(self) -> None:
|
|
78
|
+
for name in ("id", "title", "summary", "selection_reason"):
|
|
79
|
+
object.__setattr__(self, name, _required_text(getattr(self, name), name))
|
|
80
|
+
if not self.sources:
|
|
81
|
+
raise ValueError("sources must not be empty")
|
|
82
|
+
|
|
83
|
+
@classmethod
|
|
84
|
+
def from_dict(cls, raw: dict[str, Any]) -> "StoryCluster":
|
|
85
|
+
return cls(
|
|
86
|
+
id=raw.get("id", ""),
|
|
87
|
+
title=raw.get("title", ""),
|
|
88
|
+
summary=raw.get("summary", ""),
|
|
89
|
+
category=str(raw.get("category", "") or ""),
|
|
90
|
+
organization=str(raw.get("organization", "") or ""),
|
|
91
|
+
sources=tuple(SourceItem.from_dict(item) for item in raw.get("sources", [])),
|
|
92
|
+
selection_reason=raw.get("selection_reason", ""),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
def is_qualified(self) -> bool:
|
|
96
|
+
if any(item.authority == "primary" for item in self.sources):
|
|
97
|
+
return True
|
|
98
|
+
independent = {item.source.casefold() for item in self.sources if item.authority == "independent"}
|
|
99
|
+
return len(independent) >= 2
|
|
100
|
+
|
|
101
|
+
def to_dict(self) -> dict[str, Any]:
|
|
102
|
+
return {
|
|
103
|
+
"id": self.id,
|
|
104
|
+
"title": self.title,
|
|
105
|
+
"summary": self.summary,
|
|
106
|
+
"category": self.category,
|
|
107
|
+
"organization": self.organization,
|
|
108
|
+
"sources": [item.to_dict() for item in self.sources],
|
|
109
|
+
"selection_reason": self.selection_reason,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass(frozen=True, slots=True)
|
|
114
|
+
class EpisodeManifest:
|
|
115
|
+
"""Auditable record of one generated episode."""
|
|
116
|
+
|
|
117
|
+
show_slug: str
|
|
118
|
+
episode_id: str
|
|
119
|
+
episode_date: str
|
|
120
|
+
title: str
|
|
121
|
+
created_at: str
|
|
122
|
+
stories: tuple[StoryCluster, ...]
|
|
123
|
+
source_document: str
|
|
124
|
+
pipeline_version: str
|
|
125
|
+
audio_url: str = ""
|
|
126
|
+
duration: str = ""
|
|
127
|
+
transcript_url: str = ""
|
|
128
|
+
chapters_url: str = ""
|
|
129
|
+
schema_version: int = 1
|
|
130
|
+
|
|
131
|
+
def __post_init__(self) -> None:
|
|
132
|
+
for name in (
|
|
133
|
+
"show_slug",
|
|
134
|
+
"episode_id",
|
|
135
|
+
"episode_date",
|
|
136
|
+
"title",
|
|
137
|
+
"created_at",
|
|
138
|
+
"source_document",
|
|
139
|
+
"pipeline_version",
|
|
140
|
+
):
|
|
141
|
+
object.__setattr__(self, name, _required_text(getattr(self, name), name))
|
|
142
|
+
date.fromisoformat(self.episode_date)
|
|
143
|
+
datetime.fromisoformat(self.created_at.replace("Z", "+00:00"))
|
|
144
|
+
if not self.stories:
|
|
145
|
+
raise ValueError("stories must not be empty")
|
|
146
|
+
if any(not story.is_qualified() for story in self.stories):
|
|
147
|
+
raise ValueError("every story must have a primary source or two independent sources")
|
|
148
|
+
|
|
149
|
+
@classmethod
|
|
150
|
+
def from_dict(cls, raw: dict[str, Any]) -> "EpisodeManifest":
|
|
151
|
+
return cls(
|
|
152
|
+
show_slug=raw.get("show_slug", ""),
|
|
153
|
+
episode_id=raw.get("episode_id", ""),
|
|
154
|
+
episode_date=raw.get("episode_date", ""),
|
|
155
|
+
title=raw.get("title", ""),
|
|
156
|
+
created_at=raw.get("created_at", ""),
|
|
157
|
+
stories=tuple(StoryCluster.from_dict(story) for story in raw.get("stories", [])),
|
|
158
|
+
source_document=raw.get("source_document", ""),
|
|
159
|
+
pipeline_version=raw.get("pipeline_version", ""),
|
|
160
|
+
audio_url=str(raw.get("audio_url", "") or ""),
|
|
161
|
+
duration=str(raw.get("duration", "") or ""),
|
|
162
|
+
transcript_url=str(raw.get("transcript_url", "") or ""),
|
|
163
|
+
chapters_url=str(raw.get("chapters_url", "") or ""),
|
|
164
|
+
schema_version=int(raw.get("schema_version", 1)),
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
@classmethod
|
|
168
|
+
def read(cls, path: Path) -> "EpisodeManifest":
|
|
169
|
+
return cls.from_dict(json.loads(path.read_text(encoding="utf-8")))
|
|
170
|
+
|
|
171
|
+
def to_dict(self) -> dict[str, Any]:
|
|
172
|
+
return {
|
|
173
|
+
"schema_version": self.schema_version,
|
|
174
|
+
"show_slug": self.show_slug,
|
|
175
|
+
"episode_id": self.episode_id,
|
|
176
|
+
"episode_date": self.episode_date,
|
|
177
|
+
"title": self.title,
|
|
178
|
+
"created_at": self.created_at,
|
|
179
|
+
"pipeline_version": self.pipeline_version,
|
|
180
|
+
"source_document": self.source_document,
|
|
181
|
+
"audio_url": self.audio_url,
|
|
182
|
+
"duration": self.duration,
|
|
183
|
+
"transcript_url": self.transcript_url,
|
|
184
|
+
"chapters_url": self.chapters_url,
|
|
185
|
+
"stories": [story.to_dict() for story in self.stories],
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
def write(self, path: Path) -> Path:
|
|
189
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
190
|
+
path.write_text(
|
|
191
|
+
json.dumps(self.to_dict(), ensure_ascii=False, indent=2, sort_keys=True) + "\n",
|
|
192
|
+
encoding="utf-8",
|
|
193
|
+
)
|
|
194
|
+
return path
|