Files

373 lines
14 KiB
Python

#!/usr/bin/env python3
"""Generate a complete CNN-style Chinese page from a high-level JSON spec."""
from __future__ import annotations
import argparse
import copy
import json
import sys
from collections.abc import Mapping
from pathlib import Path
import render_cnn_page as renderer
LATEST_VISUALS = ("coast", "city", "deep-sea")
VIDEO_VISUALS = ("night-city", "space", "music")
WORLD_VISUALS = ("trade", "market", "payments", "energy")
def _read_spec(path: Path) -> dict[str, object]:
try:
value = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise renderer.DataValidationError(f"Invalid spec JSON: {exc}") from exc
if not isinstance(value, dict):
raise renderer.DataValidationError("Spec JSON must be an object")
return value
def _string(value: object, path: str, *, required: bool = False) -> str:
if value is None and not required:
return ""
if not isinstance(value, str) or (required and not value.strip()):
suffix = "a non-empty string" if required else "a string"
raise renderer.DataValidationError(f"{path} must be {suffix}")
return value.strip()
def _strings(value: object, path: str, *, limit: int) -> list[str]:
if value is None:
return []
if not isinstance(value, list) or not 1 <= len(value) <= limit:
raise renderer.DataValidationError(f"{path} must contain between 1 and {limit} strings")
result: list[str] = []
for index, item in enumerate(value):
text = _string(item, f"{path}[{index}]", required=True)
_require_chinese(text, f"{path}[{index}]")
result.append(text)
return result
def _require_chinese(value: str, path: str) -> None:
if not any("\u3400" <= char <= "\u9fff" for char in value):
raise renderer.DataValidationError(f"{path} must contain Simplified Chinese reader-visible text")
def _optional_chinese(spec: Mapping[str, object], key: str) -> str:
value = _string(spec.get(key), key)
if value:
_require_chinese(value, key)
return value
def _media(value: object) -> dict[str, object] | None:
if value is None:
return None
if not isinstance(value, Mapping):
raise renderer.DataValidationError("media must be an object or null")
media_type = _string(value.get("type"), "media.type") or "image"
if media_type not in {"image", "video", "webpage"}:
raise renderer.DataValidationError("media.type must be image, video, or webpage")
media: dict[str, object] = {"type": media_type}
if media_type == "webpage":
media["pageUrl"] = _string(
value.get("pageUrl"),
"media.pageUrl",
required=True,
)
media["title"] = _string(
value.get("title"),
"media.title",
required=True,
)
if value.get("description"):
media["description"] = _string(
value.get("description"),
"media.description",
)
media["embed"] = bool(value.get("embed", False))
else:
media["mediaUrl"] = _string(
value.get("url"),
"media.url",
required=True,
)
media["alt"] = _string(value.get("alt"), "media.alt") or "用户提供的新闻媒体"
if value.get("pageUrl"):
media["pageUrl"] = _string(value.get("pageUrl"), "media.pageUrl")
if media_type == "video" and value.get("posterUrl"):
media["posterUrl"] = _string(
value.get("posterUrl"),
"media.posterUrl",
)
return media
def _replace_story_titles(
defaults: list[dict[str, object]],
titles: list[str],
*,
prefix: str,
visuals: tuple[str, ...],
include_summary: bool,
topic: str,
) -> list[dict[str, object]]:
items: list[dict[str, object]] = []
for index, title in enumerate(titles):
item = copy.deepcopy(defaults[index % len(defaults)])
item["id"] = f"{prefix}-{index + 1:02d}"
item["title"] = title
item["visual"] = visuals[index % len(visuals)]
if include_summary:
item["kicker"] = "专题"
item["summary"] = f"围绕{topic}整理的中文示意报道,页面内容可在设置中继续编辑。"
item["time"] = f"{index + 1} 小时前 · 示意"
elif "meta" in item:
item["meta"] = "视频示意"
item["duration"] = f"0{index + 3}:1{index}"
else:
item["kicker"] = "观察"
item["time"] = f"{index + 1} 小时前 · 示意"
items.append(item)
return items
def build_document(spec: dict[str, object]) -> dict[str, object]:
allowed = {
"topic",
"headline",
"headlineSummary",
"breaking",
"pageTitle",
"description",
"theme",
"kicker",
"byline",
"latestHeadlines",
"videoHeadlines",
"worldHeadlines",
"sideHeadlines",
"updates",
"analysisTitle",
"analysisText",
"media",
}
unknown = sorted(set(spec) - allowed)
if unknown:
raise renderer.DataValidationError("Unknown spec keys: " + ", ".join(unknown))
topic = _string(spec.get("topic"), "topic", required=True)
headline = _optional_chinese(spec, "headline") or f"{topic}发布最新计划,中文专题页面同步上线"
headline_summary = _optional_chinese(spec, "headlineSummary") or (f"本页面围绕{topic}整理品牌动态、内容观察与社区反馈,所有新闻和数据均为中文示意内容。")
breaking = _optional_chinese(spec, "breaking") or f"{topic}成为今日中文专题关注焦点"
page_title = _optional_chinese(spec, "pageTitle") or f"CNN 中文专题 · {topic}"
description = _optional_chinese(spec, "description") or f"围绕{topic}制作的 CNN 风格中文新闻示意页面。"
kicker = _optional_chinese(spec, "kicker") or "特别报道 · 中文示意"
byline = _string(spec.get("byline"), "byline") or "CNN 中文编辑台"
theme = _string(spec.get("theme"), "theme") or "light"
if theme not in renderer.THEMES:
raise renderer.DataValidationError("theme must be auto, light, or dark")
latest_titles = _strings(spec.get("latestHeadlines"), "latestHeadlines", limit=12) or [
f"{topic}推出新计划,首批体验活动正式启动",
f"从创意到产品:{topic}团队分享设计思路",
f"社区观察:用户如何参与{topic}内容共创",
]
video_titles = _strings(spec.get("videoHeadlines"), "videoHeadlines", limit=8) or [
f"现场直击:走进{topic}的创作空间",
f"三分钟了解{topic}最新进展",
f"幕后故事:{topic}团队讲述项目历程",
]
world_titles = _strings(spec.get("worldHeadlines"), "worldHeadlines", limit=16) or [
f"{topic}跨区域合作计划公布",
f"市场观察:{topic}相关讨论持续升温",
f"数字内容让{topic}触达更多社区",
f"可持续实践成为{topic}下一阶段重点",
]
side_titles = _strings(spec.get("sideHeadlines"), "sideHeadlines", limit=4) or [
f"{topic}如何把创意转化为日常体验",
f"团队访谈:{topic}背后的设计选择",
]
update_titles = _strings(spec.get("updates"), "updates", limit=12) or [
f"{topic}专题页面完成首轮内容更新",
"中文示意报道与栏目内容已同步",
"读者可通过设置按钮继续编辑页面数据",
]
analysis_title = _optional_chinese(spec, "analysisTitle") or f"{topic}为何能够持续获得关注?"
analysis_text = _optional_chinese(spec, "analysisText") or (f"{topic}把清晰的内容表达、稳定的视觉识别和持续的社区互动结合起来。真正的考验在于后续内容能否保持一致,并形成可持续的参与机制。")
data = renderer._read_json(renderer.DEFAULT_DATA_PATH)
data["site"].update(
{
"pageTitle": page_title,
"description": description,
"theme": theme,
"date": "中文示意页面 · 非实时新闻",
"utilityLinks": ["专题", "新闻简报"],
"marketSummary": [
{"label": "关注度", "value": "示意", "direction": "flat"},
{"label": "讨论度", "value": "非实时", "direction": "flat"},
],
"weather": "页面内容为中文示意",
"frontLabel": f"头版 · {topic}",
}
)
data["navigation"]["drawerFooter"] = "CNN 中文专题 · 概念页面"
data["breaking"].update({"label": "快讯", "text": breaking, "time": "刚刚 · 示意"})
primary = data["lead"]["primary"]
primary.update(
{
"kicker": kicker,
"title": headline,
"summary": headline_summary,
"byline": byline,
"updated": "更新于刚刚 · 示意",
"readingTime": "阅读 5 分钟",
"visualLabel": f"{topic}中文专题示意视觉",
"tag": "专题",
"credit": "CNN / 中文示意视觉",
}
)
if "media" in spec:
media = _media(spec.get("media"))
if media is None:
primary.pop("media", None)
else:
primary["media"] = media
data["lead"]["sideStories"] = [
{
"kicker": "延伸阅读",
"title": title,
"summary": f"从不同角度理解{topic}的内容表达与用户体验。",
"visual": "train" if index == 0 else None,
}
for index, title in enumerate(side_titles)
]
data["lead"]["updatesTitle"] = "专题更新"
data["lead"]["updates"] = [{"time": f"0{9 + index}:0{index}", "text": text} for index, text in enumerate(update_titles)]
data["latest"]["title"] = "最新报道"
data["latest"]["items"] = _replace_story_titles(
data["latest"]["items"],
latest_titles,
prefix="latest",
visuals=LATEST_VISUALS,
include_summary=True,
topic=topic,
)
data["video"].update(
{
"title": "视频与现场",
"modalTitle": "CNN 中文视频",
"liveTitle": "专题视频",
"liveSubtitle": f"正在播放:{topic}",
"modalNote": "视频内容为互动示意,可通过上传按钮替换素材。",
}
)
data["video"]["items"] = _replace_story_titles(
data["video"]["items"],
video_titles,
prefix="video",
visuals=VIDEO_VISUALS,
include_summary=False,
topic=topic,
)
data["world"]["title"] = f"{topic}与相关观察"
data["world"]["items"] = _replace_story_titles(
data["world"]["items"],
world_titles,
prefix="world",
visuals=WORLD_VISUALS,
include_summary=False,
topic=topic,
)
data["world"]["analysis"].update(
{
"kicker": "CNN 中文分析 · 示意",
"title": analysis_title,
"text": analysis_text,
"author": "中文专题编辑部",
"role": "页面内容策划",
"initial": "编",
}
)
data["markets"].update(
{
"title": "趋势快照 · 示意数据",
"moreLabel": "非实时数据 →",
"items": [
{"name": "内容关注", "value": "示意", "change": "非实时", "direction": "flat"},
{"name": "社区讨论", "value": "示意", "change": "非实时", "direction": "flat"},
{"name": "视频热度", "value": "示意", "change": "非实时", "direction": "flat"},
{"name": "专题更新", "value": "示意", "change": "非实时", "direction": "flat"},
],
}
)
data["newsletter"].update(
{
"title": f"订阅{topic}中文专题更新",
"text": "接收页面内容更新提醒;本表单仅用于交互演示。",
"button": "演示订阅",
"successPrefix": "演示订阅信息已记录:",
}
)
data["footer"].update(
{
"tagline": f"从中文专题出发,持续关注{topic}。",
"copyright": "© 2026 CNN 风格概念页面。本页面内容均为中文示意。",
"legal": "隐私 · 条款 · 内容说明",
}
)
return data
def _next_paths(output_dir: Path) -> tuple[Path, Path]:
for index in range(1, 1001):
stem = "cnn-page" if index == 1 else f"cnn-page-{index}"
data_path = output_dir / f"{stem}-data.json"
html_path = output_dir / f"{stem}.html"
if not data_path.exists() and not html_path.exists():
return data_path, html_path
raise renderer.DataValidationError("Unable to allocate output filenames")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--spec", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
args = parser.parse_args(argv)
try:
data = build_document(_read_spec(args.spec))
summary = renderer.validate_document(data)
rendered = renderer.render_document(
data,
renderer.TEMPLATE_PATH.read_text(encoding="utf-8"),
renderer.RUNTIME_PATH.read_text(encoding="utf-8"),
)
data_path, html_path = _next_paths(args.output_dir)
renderer._write_new(
data_path,
json.dumps(data, ensure_ascii=False, indent=2) + "\n",
)
renderer._write_new(html_path, rendered)
except (renderer.DataValidationError, OSError, UnicodeError) as exc:
renderer._emit({"status": "error", "action": "fast-cnn-page", "error": str(exc)})
return 2
renderer._emit(
{
"status": "ok",
"action": "fast-cnn-page",
"data": str(data_path),
"html": str(html_path),
**summary,
}
)
return 0
if __name__ == "__main__":
sys.exit(main())