Hacker News タイトル日本語

About

Hacker News のタイトルとページの概要を日本語に翻訳して掲載しています。

仕組み

Hacker News RSSから最新のフィードをJSONで取得し、D1データベースに保管。

保管したエントリーに対してリンク先コンテンツ情報の取得と翻訳処理を行っています。

最新のフィードをJSONで取得

エンドポイントにnewest.jsonfeed?count=5&points=150のオプションを追加して、ポイントの高い記事を5件取得しています。

リンク先コンテンツ情報の取得

Workers の Runtime APIs である HTMLRewriterを使って、リンク先コンテンツ情報の取得を行います。

次のコードでOgpタグから情報を取得します。

class OgpHandler {
  title: string;
  description: string;
  image_og: string;
  image_twitter: string;

  constructor() {
    this.title = "";
    this.description = "";
    this.image_og = "";
    this.image_twitter = "";
  }

  element(element: Element) {
    if (element.getAttribute("name") === "description") {
      this.description = element.getAttribute("content") ?? "";
    } else if (element.getAttribute("name") === "twitter:image") {
      this.image_twitter = element.getAttribute("content") ?? "";
    }

    const property = element.getAttribute("property");

    if (property === "og:title") {
      this.title = element.getAttribute("content") ?? "";
    } else if (property === "og:description") {
      this.description = element.getAttribute("content") ?? "";
    } else if (property === "og:image") {
      this.image_og = element.getAttribute("content") ?? "";
    }
  }
}

翻訳

Workers AIを使って、タイトルと概要の日本語訳を行います。

モデルはm2m100-1.2bを使います。

コードおよびプロンプトは次の通りです。

const response = await ai.run("@cf/meta/m2m100-1.2b", {
  text: text,
  source_lang: "english",
  target_lang: "japanese",
});

要約

取得した OGP の description から英語の要約を作成します。

モデルはllama-3-8b-instruct-awqを使います。

const rawResponse = await ai.run("@cf/meta/llama-3-8b-instruct-awq", {
  messages,
});

タグ生成

タイトルから IT・技術系の記事に合う英単語タグを 1 つ生成します。

モデルはllama-3-8b-instruct-awqを使います。

const answer: LlamaAnswer = await ai.run("@cf/meta/llama-3-8b-instruct-awq", {
  messages: [
    {
      role: "user",
      content: `\
      Given the following title from an IT Tech blog, generate a single tag:${titileEN}.\
      The tag should be a single English word, maximum 8 characters in length, relevant to IT and technology topics, and best capture the main subject or theme of the post.\
      Please provide only the tag, without any additional explanation.\
      `,
    },
  ],
});