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を使って、タイトルと概要の日本語訳を行います。

モデルはllama-2-7b-chat-int8を使います。

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

const answer: LlamaAnswer = await ai.run("@cf/meta/llama-2-7b-chat-int8", {
    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.\
        `,
    },
    ],
});