From 8bab239ac9681b0cff1607507de6dc162bfd3e81 Mon Sep 17 00:00:00 2001 From: HyuuNyackman <107097515+HyuuNyackman@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:27:28 +0900 Subject: [PATCH] =?UTF-8?q?[vfg-83]=20feat:=20GitHub=20Blog=20=E3=81=A8=20?= =?UTF-8?q?Qiita=20=E3=81=AE=E8=A8=98=E4=BA=8B=E3=81=AE=E6=9C=AC=E6=96=87?= =?UTF-8?q?=E3=82=92=E5=8F=B0=E6=9C=AC=E3=81=AE=E6=9D=90=E6=96=99=E3=81=AB?= =?UTF-8?q?=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 19 ++++- config/feeds.json | 3 +- config/videoforge.json | 1 + src/core/config.ts | 12 +++ src/core/types.ts | 2 +- src/ops/archive.test.ts | 11 +++ src/script/check.test.ts | 17 +++++ src/script/materials.ts | 10 ++- src/script/stage.test.ts | 82 +++++++++++++++++++- src/script/stage.ts | 127 ++++++++++++++++++++++++------- src/sources/article-text.test.ts | 63 +++++++++++++++ src/sources/article-text.ts | 110 ++++++++++++++++++++++++++ src/sources/article.test.ts | 127 +++++++++++++++++++++++++++++++ src/sources/article.ts | 105 +++++++++++++++++++++++++ src/sources/index.ts | 1 + src/sources/rss/config.ts | 16 ++++ src/sources/rss/parse.ts | 3 + src/sources/rss/source.ts | 28 ++++--- src/version.test.ts | 13 +++- src/version.ts | 6 ++ 20 files changed, 704 insertions(+), 52 deletions(-) create mode 100644 src/sources/article-text.test.ts create mode 100644 src/sources/article-text.ts create mode 100644 src/sources/article.test.ts create mode 100644 src/sources/article.ts diff --git a/README.md b/README.md index 3ce6e87..4bfac2d 100644 --- a/README.md +++ b/README.md @@ -73,9 +73,26 @@ LLM の選定の指示にも、同じ題材を選ばないことを入れてい - 決まった構成は、「何が新しいか → なぜ注目か → 仕組み → 具体的な使いどころ・例 → ほかとの違い → 注意点・限界」で、最後に任意でまとめの節を足します。台本の節の種類 (`role`) とは、`hook`・`overview`・`detail`・`usecase`・`detail`・`caveat` (・`summary`) の順に対応します (`src/script/steps.ts`)。節の型がそろわない構成と、構成と節の並びが合わない台本は、作り直します。 - 事実は材料にあるものだけを使い、材料から言い切れないことは推測と分かる言い方にします。見直しの段階で、材料にない数字・固有名詞を指摘させて直します。プログラムも、材料にない数字の疑い (2 桁以上の数と小数) を見つけて見直しに渡し、最終の台本に残った疑いを `script.check.json` の `ungroundedNumbers` に残します。 - 見直しの出力は、台本の検査 (写し・必須の節・侮辱の語・Zod) を通します。通らなければ作り直し、それでも通らなければ (または LLM を呼べなければ)、検査を通った下書きを使います (`script.review.json` の `applied: false`)。 -- 材料は、GitHub の題材では README に加えて、最新のリリースの注記 (あれば)、主な言語、最上位のディレクトリ・ファイルの名前、ライセンスです (`topic.json` の `materials` と `license`)。足切りで取った README は使い回し、本文の取得は 4〜5 回の API 呼び出しです。記事の本文 (`materials.articleBody`) は、取れるようになったら差し込めるように、型だけ用意しています。 +- 材料は、GitHub の題材では README に加えて、最新のリリースの注記 (あれば)、主な言語、最上位のディレクトリ・ファイルの名前、ライセンスです (`topic.json` の `materials` と `license`)。足切りで取った README は使い回し、本文の取得は 4〜5 回の API 呼び出しです。記事の本文 (`materials.articleBody`) は、下の「記事の本文の取り方」のとおり、GitHub Blog と Qiita の題材だけ、台本の段階で取って差し込みます。 - `script.check.json` の `stageAttempts` に、段階ごとに LLM を呼んだ回数が残ります。 +### 記事の本文の取り方 + +選んだ題材が GitHub Blog か Qiita の記事のときだけ、台本の段階 (dry-run 以外) で本文を取り、台本の材料 (`article`) に入れます。Zenn・はてなブックマーク・Hacker News のリンク先は取りません。 + +| ソース | 取り方 | +| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------- | +| GitHub Blog | フィード (`config/feeds.json` の `fullText.urlPattern` に合う URL) の `content:encoded` にある全文を使う。Changelog は対象外 | +| Qiita | 公式の API v2 (`GET /api/v2/items/`) の `body` (Markdown) を使う。記事のページの HTML は取らない (公式ヘルプがスクレイピングを禁じている) | + +- 取った HTML・Markdown から、本文の文字だけを残します。コードの塊は残し、画像・スクリプト・装飾は除きます。 +- 長さの上限は `config/videoforge.json` の `articleBody.maxChars` (既定 12,000 文字、最大 30,000) です。待ちの上限は `articleBody.timeoutMs` です。 +- 取れなかったとき (HTTP のエラー・全文がない・上限を超えた) は、警告を出し、今までどおり要約 (`excerpt`) で台本を作ります。 +- 本文は `topic.json` には書きません。台本を作る間だけ実行のディレクトリに `article-body.txt` として置き、段階の終わりに消します。archive の許可の一覧には入れません。ログと `script.check.json` には、取れたかどうかと文字数だけを出します。 +- 写しの検査 (`checkCopy`) は、説明・抜粋・リリースの注記に加えて、この本文にも当てます。本文と 30 字以上同じ文字列が続くセリフは、作り直しの対象です。 +- 取るときの HTTP には、`videoforge/<版> (+https://github.com/HyuuNyackman/videoforge)` の User-Agent を付けます。 +- 概要欄には、これまでどおり出典を載せ、本文をそのまま読み上げません。 + ### 台本の書き方の制限 台本の指示に、製品・企業・作者・利用者を貶めない、断定的に否定しない、根拠のない比較や噂を書かない、特定の思想・団体への賛否を書かない、ことを入れています。作った台本に `config/script-policy.json` の `insultTerms` (強い否定・侮辱の語) があれば、既存の作り直し (1 回) に回し、見つけた語を次の指示に載せます。 diff --git a/config/feeds.json b/config/feeds.json index 4cce575..b4147a3 100644 --- a/config/feeds.json +++ b/config/feeds.json @@ -17,7 +17,8 @@ "id": "github-blog", "name": "GitHub Blog", "url": "https://github.blog/feed/", - "kind": "news" + "kind": "news", + "fullText": { "urlPattern": "^https://github\\.blog/(?!changelog/)" } }, { "id": "github-changelog", diff --git a/config/videoforge.json b/config/videoforge.json index 508b760..86e678c 100644 --- a/config/videoforge.json +++ b/config/videoforge.json @@ -18,6 +18,7 @@ "maxCallsPerModel": 8, "maxTotalMs": 1500000 }, + "articleBody": { "maxChars": 12000, "timeoutMs": 15000 }, "youtube": { "containsSyntheticMedia": false }, "speech": { "engine": "voicevox", diff --git a/src/core/config.ts b/src/core/config.ts index 7415024..15f18d7 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -14,6 +14,9 @@ export class ConfigError extends Error { override name = "ConfigError"; } +/** `articleBody.maxChars` に書ける最大の値 (台本の材料に入れるときの上限も、これ) */ +export const ARTICLE_BODY_MAX_CHARS_LIMIT = 30_000; + const SourceId = z.enum(["github-search", "rss", "hn"]); // 未知のキーはエラーにする (綴りの間違いを黙って無視しない) @@ -134,6 +137,15 @@ export const Config = z.strictObject({ path: ["shortsTargetMs"], }) .prefault({}), + /** 記事の本文 (GitHub Blog の RSS の全文・Qiita の API) を台本の材料に使うときの設定 */ + articleBody: z + .strictObject({ + /** 本文の長さの上限 (文字数)。超えたら本文は使わず、要約で続ける */ + maxChars: z.number().int().positive().max(ARTICLE_BODY_MAX_CHARS_LIMIT).default(12_000), + /** 本文を取る HTTP の呼び出し 1 回の待ちの上限 (ミリ秒) */ + timeoutMs: z.number().int().positive().default(15_000), + }) + .prefault({}), /** 描画のテーマの id (描画の側が持つテーマから選ぶ) */ theme: z.string().min(1).default("dark"), /** BGM。既定は無し */ diff --git a/src/core/types.ts b/src/core/types.ts index 4f98f54..0672bf4 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -44,7 +44,7 @@ export const Materials = z.object({ languages: z.array(z.object({ name: z.string(), percent: z.number() })).optional(), /** リポジトリの最上位の項目の名前 (ディレクトリは末尾に `/`) */ topLevelEntries: z.array(z.string()).optional(), - /** 記事の本文。記事のソースが取れるようになったら入れる (今は使わない) */ + /** 記事の本文 (GitHub Blog・Qiita)。台本の段階が取って材料に入れるだけで、`topic.json` には書かない */ articleBody: z.string().optional(), }); export type Materials = z.infer; diff --git a/src/ops/archive.test.ts b/src/ops/archive.test.ts index dea048a..b2e15b5 100644 --- a/src/ops/archive.test.ts +++ b/src/ops/archive.test.ts @@ -5,6 +5,7 @@ import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { main } from "../cli/main.js"; import { Config } from "../core/config.js"; +import { ARTICLE_BODY_FILE } from "../script/stage.js"; import { ARCHIVE_ALLOWLIST, ArchiveManifest, @@ -102,6 +103,16 @@ describe("許可の一覧", () => { }); }); +describe("記事の本文", () => { + it("許可の一覧になく、実行のディレクトリにあっても archive に入らない", async () => { + expect(ARCHIVE_ALLOWLIST).not.toContain(ARTICLE_BODY_FILE); + await put(ARTICLE_BODY_FILE, "記事の本文"); + const out = join(root, "out-body"); + await stageArchive({ runDir, outDir: out }); + expect(await tree(out)).not.toContain(ARTICLE_BODY_FILE); + }); +}); + describe("manifest", () => { it("SHA・モデル名・版・設定・大きさが入る", async () => { const config = Config.parse({ sources: ["rss"] }); diff --git a/src/script/check.test.ts b/src/script/check.test.ts index 6139202..e063272 100644 --- a/src/script/check.test.ts +++ b/src/script/check.test.ts @@ -80,3 +80,20 @@ describe("checkInsults", () => { expect(checkScript(script, topic).ok).toBe(true); }); }); + +describe("記事の本文の写しの検査", () => { + const body = + "この記事では、新しい仕組みによって、ビルドの時間が半分になったことを、順を追って説明しています。"; + const articleTopic = { ...topic, materials: { articleBody: body } }; + + it("台本が本文の表現をそのまま写していると見つける", () => { + const script = withLine(body); + const { problems } = checkScript(script, articleTopic); + expect(problems.some((p) => p.code === "copy-run" && p.lineId === "s2-l1")).toBe(true); + }); + + it("本文がなければ、同じセリフでも写しとは見ない", () => { + const { problems } = checkScript(withLine(body), topic); + expect(problems.filter((p) => p.code === "copy-run")).toEqual([]); + }); +}); diff --git a/src/script/materials.ts b/src/script/materials.ts index 778ef09..fd1b2bc 100644 --- a/src/script/materials.ts +++ b/src/script/materials.ts @@ -1,3 +1,4 @@ +import { ARTICLE_BODY_MAX_CHARS_LIMIT } from "../core/config.js"; import type { Topic } from "../core/types.js"; /** 材料の種類。事実の一覧の `source` に使う (どの材料から来た事実か) */ @@ -23,13 +24,13 @@ export interface MaterialSection { /** 1 つの材料をプロンプトに入れる長さの上限 (文字数) */ export const MATERIAL_MAX_CHARS = 6000; -const clip = (text: string): string => [...text].slice(0, MATERIAL_MAX_CHARS).join(""); +const clip = (text: string, max = MATERIAL_MAX_CHARS): string => [...text].slice(0, max).join(""); /** 題材 (`topic.json`) から、台本の材料を種類ごとに取り出す。ないものは出さない。 */ export function materialSections(topic: Topic): MaterialSection[] { const sections: MaterialSection[] = []; - const add = (id: MaterialId, label: string, text: string | undefined) => { - if (text && text.trim()) sections.push({ id, label, text: clip(text.trim()) }); + const add = (id: MaterialId, label: string, text: string | undefined, max?: number) => { + if (text && text.trim()) sections.push({ id, label, text: clip(text.trim(), max) }); }; const meta = [ `題名: ${topic.title}`, @@ -67,7 +68,8 @@ export function materialSections(topic: Topic): MaterialSection[] { if (entries && entries.length > 0) add("structure", "最上位のディレクトリ・ファイル", entries.join("\n")); add("license", "ライセンス", topic.license); - add("article", "記事の本文", topic.materials?.articleBody); + // 記事の本文の長さは、取るときに設定の上限で絞っている + add("article", "記事の本文", topic.materials?.articleBody, ARTICLE_BODY_MAX_CHARS_LIMIT); return sections; } diff --git a/src/script/stage.test.ts b/src/script/stage.test.ts index 74f287d..2e75038 100644 --- a/src/script/stage.test.ts +++ b/src/script/stage.test.ts @@ -1,13 +1,13 @@ -import { mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { access, mkdtemp, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { parseConfig } from "../core/config.js"; import { readManifest } from "../core/manifest.js"; import { runStages } from "../core/runner.js"; import { PronunciationReport } from "../speech/dictionary/index.js"; import { Script } from "../core/script-schema.js"; -import { createScriptStage } from "./stage.js"; +import { ARTICLE_BODY_FILE, createScriptStage } from "./stage.js"; import { happyReplies, stagedClient, @@ -137,4 +137,80 @@ describe("createScriptStage", () => { }), ).rejects.toThrow(/GEMINI_API_KEY/); }); + + describe("記事の本文", () => { + const SECRET = "本文だけに出てくる、ふしぎな固有の言い回し"; + const qiita = { ...topic, url: "https://qiita.com/u/items/0123abcd", sourceId: "rss" }; + + async function runWith(articleFetch: typeof fetch) { + const { runDir, dictionaryPath, config } = await setup(); + await writeFile(join(runDir, "topic.json"), JSON.stringify(qiita)); + const client = stagedClient("gemini", happyReplies(topic.key)); + const logs: string[] = []; + const stage = createScriptStage({ + env: {}, + dictionaryPath, + clients: [client], + articleFetch, + }); + await runStages({ + stages: [stage], + to: "script", + ctx: { runId: "r", runDir, config, dryRun: false, log: (m) => logs.push(m) }, + }); + return { runDir, client, logs }; + } + + it("Qiita の題材では本文を取って台本の材料に入れ、本文のファイルは段階の終わりに消す", async () => { + const api = vi.fn(async () => new Response(JSON.stringify({ body: SECRET }))); + const { runDir, client, logs } = await runWith(api as unknown as typeof fetch); + expect(api).toHaveBeenCalledTimes(1); + expect(client.seen[0]!.prompt).toContain(SECRET); + // 本文は topic.json にも、ログにも、台本の検査の記録にも入らない。長さと成否だけ + expect(await readFile(join(runDir, "topic.json"), "utf8")).not.toContain(SECRET); + expect(logs.join("\n")).not.toContain(SECRET); + expect(logs.join("\n")).toContain(`記事の本文を取りました (${[...SECRET].length} 文字)`); + const check = await readFile(join(runDir, "script.check.json"), "utf8"); + expect(check).not.toContain(SECRET); + expect(JSON.parse(check).articleBody).toEqual({ fetched: true, chars: [...SECRET].length }); + await expect(access(join(runDir, ARTICLE_BODY_FILE))).rejects.toThrow(); + }); + + it("取れなかったときは警告を出し、要約のままで続ける", async () => { + const api = vi.fn(async () => new Response("", { status: 500 })); + const { runDir, client, logs } = await runWith(api as unknown as typeof fetch); + expect( + logs.some((m) => m.includes("警告: 記事の本文を取れなかった") && m.includes("HTTP 500")), + ).toBe(true); + expect(client.seen[0]!.prompt).not.toContain("[article]"); + expect( + JSON.parse(await readFile(join(runDir, "script.check.json"), "utf8")).articleBody, + ).toEqual({ + fetched: false, + }); + expect( + Script.parse(JSON.parse(await readFile(join(runDir, "script.json"), "utf8"))), + ).toBeTruthy(); + }); + + it("上限を超えた本文も、警告を出して要約で続ける", async () => { + const api = async () => new Response(JSON.stringify({ body: "あ".repeat(13_000) })); + const { client, logs } = await runWith(api as unknown as typeof fetch); + expect(logs.some((m) => m.includes("本文が長すぎます"))).toBe(true); + expect(client.seen[0]!.prompt).not.toContain("[article]"); + }); + + it("dry-run では本文を取りに行かない", async () => { + const { runDir, dictionaryPath, config } = await setup(); + await writeFile(join(runDir, "topic.json"), JSON.stringify(qiita)); + const api = vi.fn(); + const stage = createScriptStage({ env: {}, dictionaryPath, articleFetch: api as never }); + await runStages({ + stages: [stage], + to: "script", + ctx: { runId: "r", runDir, config, dryRun: true, log: () => {} }, + }); + expect(api).not.toHaveBeenCalled(); + }); + }); }); diff --git a/src/script/stage.ts b/src/script/stage.ts index d89189b..2d5c0a4 100644 --- a/src/script/stage.ts +++ b/src/script/stage.ts @@ -1,5 +1,6 @@ -import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; +import type { Config } from "../core/config.js"; import type { StageDefinition } from "../core/runner.js"; import { Topic } from "../core/types.js"; import { @@ -17,6 +18,7 @@ import { DEFAULT_DICTIONARY_PATH, loadPronunciationDictionary, } from "../speech/dictionary/index.js"; +import { fetchArticleBody, loadFeedsConfig, type FeedsConfig } from "../sources/index.js"; import { checkScript, DEFAULT_SCRIPT_POLICY_PATH, loadScriptPolicy } from "./check.js"; import { fixtureScript } from "./fixture.js"; import { ScriptGenerationError, type GeneratedScript } from "./generate.js"; @@ -25,6 +27,13 @@ import { PROMPT_VERSION } from "./prompt.js"; import { reviewPronunciations, toReport } from "./pronunciation.js"; export const TOPIC_FILE = "topic.json"; +/** + * 記事の本文を、台本を作る間だけ置くファイル。段階の終わりに消すので、archive にも artifact にも残らない + * (archive の許可の一覧にも入れない)。 + */ +export const ARTICLE_BODY_FILE = "article-body.txt"; +export const DEFAULT_FEEDS_PATH = "config/feeds.json"; + export const SCRIPT_FILE = "script.json"; export const SCRIPT_CHECK_FILE = "script.check.json"; export const PRONUNCIATION_REPORT_FILE = "pronunciation-report.json"; @@ -47,6 +56,11 @@ export interface ScriptStageDeps { usage?: LlmUsage; /** やり直しの待ち。テストで時間を進めるときに差し替える */ sleep?: (ms: number) => Promise; + /** 記事の本文を取る HTTP の呼び出し。省くと `fetch`。テストで差し替える */ + articleFetch?: typeof fetch; + /** フィードの設定 (どの記事の全文を使うか)。省くと `config/feeds.json` */ + feeds?: FeedsConfig; + feedsPath?: string; /** テストで LLM のクライアントを差し替える (指定すると env は見ない) */ clients?: readonly LlmClient[]; } @@ -70,6 +84,40 @@ function clientsForRun( return clients; } +type ArticleBodyOutcome = + { status: "skipped" } | { status: "failed" } | { status: "ok"; text: string }; + +/** + * 題材が GitHub Blog か Qiita の記事なら、本文を取って実行のディレクトリに置く。 + * 取れなくても止めず、警告を出して要約で続ける。ログには長さと成否だけを出す (本文は出さない)。 + */ +async function tryFetchArticleBody( + topic: Topic, + deps: ScriptStageDeps, + ctx: { runDir: string; config: Config; log: (m: string) => void }, +): Promise { + try { + const text = await fetchArticleBody( + topic.url, + async () => deps.feeds ?? (await loadFeedsConfig(deps.feedsPath ?? DEFAULT_FEEDS_PATH)), + { + fetch: deps.articleFetch ?? fetch, + maxChars: ctx.config.articleBody.maxChars, + timeoutMs: ctx.config.articleBody.timeoutMs, + }, + ); + if (text === undefined) return { status: "skipped" }; + await mkdir(ctx.runDir, { recursive: true }); + await writeFile(join(ctx.runDir, ARTICLE_BODY_FILE), text); + ctx.log(`script: 記事の本文を取りました (${[...text].length} 文字)`); + return { status: "ok", text }; + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + ctx.log(`警告: 記事の本文を取れなかったので、要約で続けます: ${reason}`); + return { status: "failed" }; + } +} + /** `script` の段階。dry-run では API を呼ばず、決まった台本 (fixture) を返す。 */ export function createScriptStage(deps: ScriptStageDeps): StageDefinition { const usage = @@ -95,42 +143,62 @@ export function createScriptStage(deps: ScriptStageDeps): StageDefinition { `${PROMPT_VERSION}:${ctx.dryRun}:${ctx.config.timeline.shortsTargetMs}:${ctx.config.timeline.charsPerSecond}`, run: async (ctx) => { const usageBefore = usage.snapshot(); - const topic = Topic.parse(JSON.parse(await readFile(join(ctx.runDir, TOPIC_FILE), "utf8"))); + const stored = Topic.parse(JSON.parse(await readFile(join(ctx.runDir, TOPIC_FILE), "utf8"))); const dictionary = await loadPronunciationDictionary( deps.dictionaryPath ?? DEFAULT_DICTIONARY_PATH, ); const policy = await loadScriptPolicy(deps.policyPath ?? DEFAULT_SCRIPT_POLICY_PATH); + // 記事の本文は、dry-run では取らない。台本を作る間だけ手元に置き、終わったら消す + let topic = stored; + let articleBody: { fetched: boolean; chars?: number } | undefined; + if (!ctx.dryRun) { + const body = await tryFetchArticleBody(stored, deps, ctx); + if (body.status !== "skipped") { + articleBody = + body.status === "ok" + ? { fetched: true, chars: [...body.text].length } + : { fetched: false }; + if (body.status === "ok") { + topic = { ...stored, materials: { ...stored.materials, articleBody: body.text } }; + } + } + } + let result: GeneratedScript; let staged: StagedScript | undefined; - if (ctx.dryRun) { - const fixture = fixtureScript(topic.key); - const review = reviewPronunciations(fixture, dictionary); - result = { - script: { ...fixture, pronunciations: review.proposals }, - check: checkScript(fixture, topic, policy), - report: toReport(review), - client: "fixture", - model: "fixture", - clientIndex: 0, - attempts: 0, - promptVersion: PROMPT_VERSION, - warnings: [], - }; - } else { - staged = await generateStagedScript({ - clients: clientsForRun(deps, usage, ctx.log), - topic, - dictionary, - policy, - shorts: { - targetMs: ctx.config.timeline.shortsTargetMs, - charsPerSecond: ctx.config.timeline.charsPerSecond, - }, - log: ctx.log, - }); - result = staged; + try { + if (ctx.dryRun) { + const fixture = fixtureScript(topic.key); + const review = reviewPronunciations(fixture, dictionary); + result = { + script: { ...fixture, pronunciations: review.proposals }, + check: checkScript(fixture, topic, policy), + report: toReport(review), + client: "fixture", + model: "fixture", + clientIndex: 0, + attempts: 0, + promptVersion: PROMPT_VERSION, + warnings: [], + }; + } else { + staged = await generateStagedScript({ + clients: clientsForRun(deps, usage, ctx.log), + topic, + dictionary, + policy, + shorts: { + targetMs: ctx.config.timeline.shortsTargetMs, + charsPerSecond: ctx.config.timeline.charsPerSecond, + }, + log: ctx.log, + }); + result = staged; + } + } finally { + await rm(join(ctx.runDir, ARTICLE_BODY_FILE), { force: true }); } await mkdir(ctx.runDir, { recursive: true }); @@ -151,6 +219,7 @@ export function createScriptStage(deps: ScriptStageDeps): StageDefinition { ungroundedNumbers: staged.ungroundedNumbers, } : {}), + ...(articleBody ? { articleBody } : {}), ...(result.warnings.length > 0 ? { warnings: result.warnings } : {}), }); await write(PRONUNCIATION_REPORT_FILE, result.report); diff --git a/src/sources/article-text.test.ts b/src/sources/article-text.test.ts new file mode 100644 index 0000000..128527d --- /dev/null +++ b/src/sources/article-text.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "vitest"; +import { htmlToText, markdownToText } from "./article-text.js"; + +describe("htmlToText", () => { + const html = ` +
+

見出し

+

本文の強調と リンク & あ <T>

+
図
図の説明
+ +
  • 一つ目
  • 二つ目
+
const a = 1 < 2;
+if (a) {
+  run();
+}
+

おわり

`; + + it("文字だけを取り出し、画像・スクリプト・装飾を除く", () => { + const text = htmlToText(html); + expect(text).toContain("見出し"); + expect(text).toContain("本文の強調と リンク & あ "); + expect(text).toContain("- 一つ目\n- 二つ目"); + expect(text).toContain("図の説明"); + expect(text).not.toMatch(/track|\.a\{| { + expect(htmlToText(html)).toContain("```\nconst a = 1 < 2;\nif (a) {\n run();\n}\n```"); + }); +}); + +describe("markdownToText", () => { + const md = [ + "## はじめに", + "", + "![図](https://example.com/a.png)", + "**強調**した [リンク](https://example.com) です。
", + "", + "```ts:a.ts", + "const x = a < b; // # not heading", + "```", + "", + "---", + "おわり", + ].join("\n"); + + it("画像・リンクの URL・見出しや強調の記号・HTML の部品を除き、コードは残す", () => { + const text = markdownToText(md); + expect(text).toBe( + [ + "はじめに", + "", + "強調した リンク です。", + "", + "```", + "const x = a < b; // # not heading", + "```", + "", + "おわり", + ].join("\n"), + ); + }); +}); diff --git a/src/sources/article-text.ts b/src/sources/article-text.ts new file mode 100644 index 0000000..31d6814 --- /dev/null +++ b/src/sources/article-text.ts @@ -0,0 +1,110 @@ +// 記事の本文 (HTML・Markdown) から、読める文字だけを取り出す。 +// コードの塊は残し、画像・スクリプト・装飾は除く。 + +const NAMED_ENTITIES: Record = { + amp: "&", + lt: "<", + gt: ">", + quot: '"', + apos: "'", + nbsp: " ", + hellip: "…", + mdash: "—", + ndash: "–", + rsquo: "’", + lsquo: "‘", + rdquo: "”", + ldquo: "“", + copy: "©", +}; + +function decodeEntities(text: string): string { + return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (whole, name: string) => { + if (name.startsWith("#")) { + const code = + name[1]?.toLowerCase() === "x" ? parseInt(name.slice(2), 16) : Number(name.slice(1)); + return Number.isInteger(code) && code > 0 && code <= 0x10ffff + ? String.fromCodePoint(code) + : whole; + } + return NAMED_ENTITIES[name.toLowerCase()] ?? whole; + }); +} + +/** 行ごとに空白をつめ、3 つ以上続く空行を 1 つにする。 */ +function tidy(text: string): string { + return text + .split("\n") + .map((line) => line.replace(/[ \t\u00a0]+/g, " ").trim()) + .join("\n") + .replace(/\n{3,}/g, "\n\n") + .trim(); +} + +const DROPPED_BLOCKS = + /<(script|style|noscript|svg|iframe|canvas|video|audio|picture|form|button|template|head)\b[\s\S]*?<\/\1\s*>/gi; +const BLOCK_TAGS = + /<\/?(p|div|br|ul|ol|h[1-6]|tr|table|blockquote|section|article|header|footer|hr|figure|figcaption|details|summary)\b[^>]*>/gi; + +/** 記事の HTML から本文の文字を取り出す。`
` はコードの塊として、改行を残して ``` で囲む。 */
+export function htmlToText(html: string): string {
+  const codeBlocks: string[] = [];
+  const withoutCode = html
+    .replace(//g, "")
+    .replace(DROPPED_BLOCKS, " ")
+    .replace(/]*>([\s\S]*?)<\/pre\s*>/gi, (_, inner: string) => {
+      const code = decodeEntities(inner.replace(//gi, "\n").replace(/<[^>]*>/g, ""))
+        .replace(/\r\n?/g, "\n")
+        .replace(/^\n+|\s+$/g, "");
+      codeBlocks.push(code);
+      return `\n\uE000CODE${codeBlocks.length - 1}\uE001\n`;
+    });
+  const prose = withoutCode
+    .replace(/]*>/gi, "\n- ")
+    .replace(BLOCK_TAGS, "\n")
+    .replace(/<[^>]*>/g, "");
+  const text = tidy(decodeEntities(prose));
+  return text.replace(
+    /\uE000CODE(\d+)\uE001/g,
+    (_, index: string) => `\`\`\`\n${codeBlocks[Number(index)]}\n\`\`\``,
+  );
+}
+
+/** Qiita の API の `body` (Markdown) から、本文の文字を取り出す。コードの塊は残し、画像・HTML の部品・装飾は除く。 */
+export function markdownToText(markdown: string): string {
+  const out: string[] = [];
+  let inFence = false;
+  for (const line of markdown.replace(/\r\n?/g, "\n").split("\n")) {
+    if (/^\s*(```|~~~)/.test(line)) {
+      inFence = !inFence;
+      out.push("```");
+      continue;
+    }
+    if (inFence) {
+      out.push(line);
+      continue;
+    }
+    out.push(
+      line
+        .replace(/!\[[^\]]*\]\([^)]*\)/g, "")
+        .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
+        .replace(/^\s{0,3}#{1,6}\s+/, "")
+        .replace(/^\s*([-*_])(\s*\1){2,}\s*$/, "")
+        .replace(/(\*\*|__|~~)/g, ""),
+    );
+  }
+  // 閉じていない fence は、そこまでをコードとして残す。Markdown に混ざった HTML の部品は除く
+  const joined = out
+    .join("\n")
+    .replace(//g, "")
+    .replace(DROPPED_BLOCKS, " ");
+  const parts = joined.split(/(```[\s\S]*?(?:```|$))/g);
+  return parts
+    .map((part, index) => (index % 2 === 1 ? part : decodeEntities(part.replace(/<[^>]*>/g, ""))))
+    .join("")
+    .split("\n")
+    .map((line) => line.trimEnd())
+    .join("\n")
+    .replace(/\n{3,}/g, "\n\n")
+    .trim();
+}
diff --git a/src/sources/article.test.ts b/src/sources/article.test.ts
new file mode 100644
index 0000000..fba162d
--- /dev/null
+++ b/src/sources/article.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it, vi } from "vitest";
+import { ArticleBodyError, fetchArticleBody } from "./article.js";
+import { parseFeedsConfig } from "./rss/config.js";
+import { USER_AGENT } from "../version.js";
+
+const feeds = parseFeedsConfig({
+  feeds: [
+    {
+      id: "gh",
+      name: "GitHub Blog",
+      url: "https://github.blog/feed/",
+      kind: "news",
+      fullText: { urlPattern: "^https://github\\.blog/(?!changelog/)" },
+    },
+    { id: "zenn", name: "Zenn", url: "https://zenn.dev/feed" },
+  ],
+});
+
+const BLOG_FEED = `
+
+別の記事https://github.blog/news-insights/other/
+別

]]>
+記事https://github.blog/ai-and-ml/post/ +要約

]]>
+全文の段落です。

npm i && run
]]>
+空https://github.blog/empty/要約だけ +
`; + +function ctxWith( + handler: (url: string, init?: RequestInit) => Response | Promise, + maxChars = 12_000, +) { + const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => + handler(String(input), init), + ); + return { + fetchMock, + ctx: { fetch: fetchMock as unknown as typeof fetch, maxChars, timeoutMs: 1000 }, + }; +} +const getFeeds = async () => feeds; + +describe("fetchArticleBody: GitHub Blog (RSS の全文)", () => { + it("content:encoded の全文から文字だけを取り出し、User-Agent を付ける", async () => { + const { ctx, fetchMock } = ctxWith(() => new Response(BLOG_FEED)); + const text = await fetchArticleBody("https://github.blog/ai-and-ml/post/", getFeeds, ctx); + expect(text).toBe("全文の段落です。\n\n```\nnpm i && run\n```"); + expect(fetchMock).toHaveBeenCalledTimes(1); + const init = fetchMock.mock.calls[0]![1]; + expect((init?.headers as Record)["user-agent"]).toBe(USER_AGENT); + }); + + it("全文のない項目・フィードにない記事は、取れなかったとして例外にする", async () => { + const { ctx } = ctxWith(() => new Response(BLOG_FEED)); + await expect(fetchArticleBody("https://github.blog/empty/", getFeeds, ctx)).rejects.toThrow( + /全文がありません/, + ); + await expect(fetchArticleBody("https://github.blog/gone/", getFeeds, ctx)).rejects.toThrow( + /見つかりません/, + ); + }); + + it("対象でない記事 (changelog・Zenn・はてな先) は、取りに行かない", async () => { + const { ctx, fetchMock } = ctxWith(() => new Response(BLOG_FEED)); + for (const url of [ + "https://github.blog/changelog/2026-12-01-x/", + "https://zenn.dev/a/articles/x", + "https://example.com/post", + ]) { + expect(await fetchArticleBody(url, getFeeds, ctx)).toBeUndefined(); + } + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("フィードが HTTP エラーなら例外", async () => { + const { ctx } = ctxWith(() => new Response("", { status: 503 })); + await expect( + fetchArticleBody("https://github.blog/ai-and-ml/post/", getFeeds, ctx), + ).rejects.toThrow("HTTP 503"); + }); +}); + +describe("fetchArticleBody: Qiita (API v2 の body)", () => { + const url = "https://qiita.com/user/items/0123abcd"; + const apiBody = JSON.stringify({ + body: "## 見出し\n![図](https://x/a.png)\n本文です。\n```js\nlet a = 1;\n```", + }); + + it("公式の API の body から文字だけを取り出す (ページの HTML は取らない)", async () => { + const { ctx, fetchMock } = ctxWith(() => new Response(apiBody)); + const text = await fetchArticleBody(url, getFeeds, ctx); + expect(text).toBe("見出し\n\n本文です。\n```\nlet a = 1;\n```"); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0]![0]).toBe("https://qiita.com/api/v2/items/0123abcd"); + const init = fetchMock.mock.calls[0]![1]; + expect((init?.headers as Record)["user-agent"]).toBe(USER_AGENT); + }); + + it("HTTP エラー・本文のない応答・JSON でない応答は、本文を含まない理由の例外", async () => { + for (const [res, pattern] of [ + [new Response("", { status: 404 }), /HTTP 404/], + [new Response("{}"), /本文がありません/], + [new Response("秘密の本文"), /JSON ではありません/], + ] as const) { + const { ctx } = ctxWith(() => res.clone()); + const error = await fetchArticleBody(url, getFeeds, ctx).catch((e: unknown) => e); + expect(error).toBeInstanceOf(ArticleBodyError); + expect((error as Error).message).toMatch(pattern); + expect((error as Error).message).not.toContain("秘密の本文"); + } + }); +}); + +describe("長さの上限", () => { + const url = "https://qiita.com/user/items/0123abcd"; + const body = (n: number) => new Response(JSON.stringify({ body: "あ".repeat(n) })); + + it("上限ちょうどは通り、超えたら例外 (本文は切って使わない)", async () => { + expect(await fetchArticleBody(url, getFeeds, ctxWith(() => body(100), 100).ctx)).toHaveLength( + 100, + ); + const error = await fetchArticleBody(url, getFeeds, ctxWith(() => body(101), 100).ctx).catch( + (e: unknown) => e, + ); + expect((error as Error).message).toBe("本文が長すぎます (101 文字、上限 100 文字)"); + }); +}); diff --git a/src/sources/article.ts b/src/sources/article.ts new file mode 100644 index 0000000..7847168 --- /dev/null +++ b/src/sources/article.ts @@ -0,0 +1,105 @@ +import { USER_AGENT } from "../version.js"; +import { htmlToText, markdownToText } from "./article-text.js"; +import { normalizeUrl } from "./keys.js"; +import type { FeedsConfig } from "./rss/config.js"; +import { parseFeed } from "./rss/parse.js"; + +/** Qiita の記事 (`https://qiita.com//items/`) の URL。本文は公式の API v2 で取る。 */ +export const QIITA_ITEM = /^https:\/\/qiita\.com\/[^/]+\/items\/([0-9a-f]+)\/?$/; + +/** 本文を取るときの外への出口と上限 */ +export interface ArticleBodyContext { + fetch: typeof fetch; + /** 本文の長さの上限 (文字数) */ + maxChars: number; + /** HTTP の呼び出し 1 回の待ちの上限 (ミリ秒) */ + timeoutMs: number; + signal?: AbortSignal | undefined; +} + +/** 本文を取れなかった。メッセージに本文は入れない (理由だけ)。 */ +export class ArticleBodyError extends Error { + override name = "ArticleBodyError"; +} + +function signalFor(ctx: ArticleBodyContext): AbortSignal { + const timeout = AbortSignal.timeout(ctx.timeoutMs); + return ctx.signal ? AbortSignal.any([ctx.signal, timeout]) : timeout; +} + +/** Qiita の API v2 の `body` (Markdown) を、そのまま返す。取れなければ例外。 */ +export async function fetchQiitaRawBody( + id: string, + ctx: Pick, +): Promise { + const response = await ctx.fetch(`https://qiita.com/api/v2/items/${id}`, { + headers: { accept: "application/json", "user-agent": USER_AGENT }, + signal: signalFor({ maxChars: 0, ...ctx }), + }); + if (!response.ok) + throw new ArticleBodyError(`Qiita の API が HTTP ${response.status} を返しました`); + // JSON として読めないときの例外は、応答の一部を含むことがあるので、理由だけに置き換える + const json = (await response.json().catch(() => { + throw new ArticleBodyError("Qiita の API の応答が JSON ではありません"); + })) as { body?: unknown }; + if (typeof json.body !== "string") + throw new ArticleBodyError("Qiita の API の応答に本文がありません"); + return json.body; +} + +async function githubBlogLikeBody( + url: string, + feeds: FeedsConfig, + ctx: ArticleBodyContext, +): Promise { + const feed = feeds.feeds.find((f) => f.fullText && new RegExp(f.fullText.urlPattern).test(url)); + if (!feed) return undefined; + const response = await ctx.fetch(feed.url, { + headers: { + accept: "application/rss+xml, application/atom+xml, application/xml, text/xml", + "user-agent": USER_AGENT, + }, + signal: signalFor(ctx), + }); + if (!response.ok) + throw new ArticleBodyError(`${feed.name} のフィードが HTTP ${response.status} を返しました`); + const wanted = normalizeUrl(url); + const item = parseFeed(await response.text()).find((entry) => { + if (!entry.link) return false; + try { + return normalizeUrl(entry.link) === wanted; + } catch { + return false; + } + }); + if (!item) throw new ArticleBodyError(`${feed.name} のフィードに、この記事が見つかりません`); + if (!item.content) + throw new ArticleBodyError(`${feed.name} のフィードに、この記事の全文がありません`); + return htmlToText(item.content); +} + +/** + * 題材の記事の本文 (文字だけ) を取る。対象は、全文のあるフィード (GitHub Blog) の記事と Qiita の記事だけ。 + * 対象でなければ `undefined`。取れなかったとき・空・上限超えのときは `ArticleBodyError`。 + */ +export async function fetchArticleBody( + url: string, + feeds: () => Promise, + ctx: ArticleBodyContext, +): Promise { + const qiitaId = QIITA_ITEM.exec(url)?.[1]; + let text: string | undefined; + if (qiitaId) { + text = markdownToText(await fetchQiitaRawBody(qiitaId, ctx)); + } else { + const config = await feeds(); + text = await githubBlogLikeBody(url, config, ctx); + } + if (text === undefined) return undefined; + if (!text) throw new ArticleBodyError("本文の文字がありませんでした"); + const chars = [...text].length; + if (chars > ctx.maxChars) { + throw new ArticleBodyError(`本文が長すぎます (${chars} 文字、上限 ${ctx.maxChars} 文字)`); + } + return text; +} diff --git a/src/sources/index.ts b/src/sources/index.ts index f332db0..c2a37fd 100644 --- a/src/sources/index.ts +++ b/src/sources/index.ts @@ -4,3 +4,4 @@ export * from "./types.js"; export * from "./rss/index.js"; export * from "./hn/index.js"; export * from "./github/index.js"; +export * from "./article.js"; diff --git a/src/sources/rss/config.ts b/src/sources/rss/config.ts index 2f5a00d..08e0b3b 100644 --- a/src/sources/rss/config.ts +++ b/src/sources/rss/config.ts @@ -8,6 +8,22 @@ export const FeedConfig = z.strictObject({ url: z.url(), /** GitHub のリポジトリを指さない項目の種類 */ kind: z.enum(["article", "news", "product"]).default("article"), + /** + * フィードに全文 (`content:encoded`) がある記事のとき、台本の材料にその本文を使う。 + * `urlPattern` に合う URL の記事だけが対象 (正規表現)。 + */ + fullText: z + .strictObject({ + urlPattern: z.string().refine((p) => { + try { + new RegExp(p); + return true; + } catch { + return false; + } + }, "正規表現として読めません"), + }) + .optional(), }); export type FeedConfig = z.infer; diff --git a/src/sources/rss/parse.ts b/src/sources/rss/parse.ts index 9a29965..3af109c 100644 --- a/src/sources/rss/parse.ts +++ b/src/sources/rss/parse.ts @@ -7,6 +7,8 @@ export interface FeedItem { /** 要約 (HTML のことがある) */ summary?: string | undefined; published?: string | undefined; + /** 全文 (RSS の `content:encoded`、Atom の `content`。HTML) */ + content?: string | undefined; } const parser = new XMLParser({ @@ -56,6 +58,7 @@ function toItem(raw: Node): FeedItem { title: text(node["title"]), link: linkOf(node["link"]), summary: text(node["description"]) ?? text(node["summary"]) ?? text(node["content"]), + content: text(node["encoded"]) ?? text(node["content"]), published: text(node["pubDate"]) ?? text(node["published"]) ?? diff --git a/src/sources/rss/source.ts b/src/sources/rss/source.ts index b4113df..c938188 100644 --- a/src/sources/rss/source.ts +++ b/src/sources/rss/source.ts @@ -1,4 +1,6 @@ +import { USER_AGENT } from "../../version.js"; import { Candidate, type TopicDetail } from "../../core/index.js"; +import { fetchQiitaRawBody, QIITA_ITEM } from "../article.js"; import { keyForUrl } from "../keys.js"; import { plainText, toIsoDate } from "../text.js"; import type { Source, SourceContext } from "../types.js"; @@ -34,8 +36,7 @@ export function itemToCandidate(item: FeedItem, feed: FeedConfig): Candidate | u return parsed.success ? parsed.data : undefined; } -// Qiita の記事 (`https://qiita.com//items/`) だけは公式の API で本文を取れる -const QIITA_ITEM = /^https:\/\/qiita\.com\/[^/]+\/items\/([0-9a-f]+)\/?$/; +// Qiita の記事は公式の API で本文を取れる (`../article.ts`) const QIITA_EXCERPT_CHARS = 2000; export interface RssSourceOptions { @@ -45,7 +46,10 @@ export interface RssSourceOptions { export function createRssSource({ config }: RssSourceOptions): Source { async function fetchFeed(feed: FeedConfig, ctx: SourceContext): Promise { const response = await ctx.fetch(feed.url, { - headers: { accept: "application/rss+xml, application/atom+xml, application/xml, text/xml" }, + headers: { + accept: "application/rss+xml, application/atom+xml, application/xml, text/xml", + "user-agent": USER_AGENT, + }, signal: withTimeout(ctx), }); if (!response.ok) throw new Error(`HTTP ${response.status}`); @@ -88,15 +92,15 @@ export function createRssSource({ config }: RssSourceOptions): Source { async fetchDetail(candidate, ctx): Promise { const qiitaId = QIITA_ITEM.exec(candidate.url)?.[1]; if (qiitaId) { - const response = await ctx.fetch(`https://qiita.com/api/v2/items/${qiitaId}`, { - headers: { accept: "application/json" }, - signal: withTimeout(ctx), - }); - if (response.ok) { - const body = (await response.json()) as { body?: unknown }; - if (typeof body.body === "string") { - return { excerpt: [...body.body].slice(0, QIITA_EXCERPT_CHARS).join("") }; - } + try { + const body = await fetchQiitaRawBody(qiitaId, { + fetch: ctx.fetch, + timeoutMs: REQUEST_TIMEOUT_MS, + signal: ctx.signal, + }); + return { excerpt: [...body].slice(0, QIITA_EXCERPT_CHARS).join("") }; + } catch { + // API が使えないときは、フィードの説明で続ける } } return { excerpt: candidate.description ?? candidate.title }; diff --git a/src/version.test.ts b/src/version.test.ts index 7cd2884..7791e24 100644 --- a/src/version.test.ts +++ b/src/version.test.ts @@ -1,8 +1,19 @@ import { describe, expect, it } from "vitest"; -import { appBanner } from "./version.js"; +import { readFileSync } from "node:fs"; +import { APP_VERSION, appBanner, USER_AGENT } from "./version.js"; describe("appBanner", () => { it("名前と版を並べる", () => { expect(appBanner("0.0.0")).toBe("videoforge v0.0.0"); }); }); + +describe("USER_AGENT", () => { + it("package.json の版と連絡先を含む", () => { + const pkg = JSON.parse(readFileSync("package.json", "utf8")) as { version: string }; + expect(APP_VERSION).toBe(pkg.version); + expect(USER_AGENT).toBe( + `videoforge/${pkg.version} (+https://github.com/HyuuNyackman/videoforge)`, + ); + }); +}); diff --git a/src/version.ts b/src/version.ts index 47a4e34..d9d7cb0 100644 --- a/src/version.ts +++ b/src/version.ts @@ -4,3 +4,9 @@ export const APP_NAME = "videoforge"; export function appBanner(version: string): string { return `${APP_NAME} v${version}`; } + +/** `package.json` の版と同じにする (テストで確かめる) */ +export const APP_VERSION = "0.0.0"; + +/** 外部へ出る HTTP の呼び出しで、自分を名乗る User-Agent */ +export const USER_AGENT = `${APP_NAME}/${APP_VERSION} (+https://github.com/HyuuNyackman/videoforge)`;