Find the Videos Hacker News Loves

Build a local site that ranks YouTube videos recommended by Hacker News readers.

Introduction

30 Second Summary

A great video shared in a discussion can disappear beneath years of newer comments. The useful signal comes from noticing which videos keep earning recommendations from different people.

In this project, you will build the HN Picks site from live Hacker News comments. You'll use Claude Code with Python to turn those comments into video rankings shaped by distinct authors.

What You'll Build

Picture opening index.html to a dark, searchable grid of 100 videos, then expanding Why? on any card to read the Hacker News comments behind its rank.

By the end of this project, you'll have:

  • A 100-video grid you can scan by thumbnail, title, channel, and the exact label Recommended by N people on Hacker News.
  • An instant title search that filters the cards as you type, plus links that open each video on YouTube.
  • Recommendation evidence you can expand to see authors, dates, excerpts, and links to the original Hacker News comments.
  • Secret Mission: Rebuild the rankings from five years of comments or one topic such as rust, chess, or cooking.

Are there any prerequisites?

You'll need an internet connection, a supported Mac or Windows computer, and a Claude Pro, Max, Ultra, Team, Enterprise, or Console account. The project adds no separate charge beyond the Claude plan you already use.

Before We Start

Before any setup begins, this is your moment to commit to the HN Picks site and the reason you want Hacker News readers to shape its video rankings.

Install Python and Claude Code

The HN Picks site needs a verified Python runtime before any collector can run. It also needs an authenticated Claude Code session before Claude can create project files.

You will install both tools first. You will then start Claude Code inside a dedicated folder so every file lands in the right place.

In this step, get ready to:
  • Install Python 3.15.2.
  • Install Claude Code 2.1.336.
  • Start an authenticated Claude Code session inside my-hn-picks.
Install and verify Python

Python runs every data collection script in this project. Verifying the version now prevents confusing command failures once Claude starts creating those scripts.

macOS

  • Select the macOS installer download.
  • Run the downloaded installer.
  • Follow the installer until Python 3.15.2 finishes installing.

Windows

  • Select the Windows installer (64-bit) download marked Recommended.
  • Run the downloaded installer.
  • Follow the installer until Python 3.15.2 finishes installing.
  • On a Mac, complete Python's certificate setup by double-clicking Install Certificates.command inside /Applications/Python 3.15/.

macOS

  • Verify Python from Terminal by running this command:
python3 --version

What does this command do?

The --version flag asks Python to print its installed version. The command exits as soon as it reports that value.

Windows

  • Verify Python from PowerShell by running this command:
python --version

What does this command do?

The --version flag asks Python to print its installed version. The command exits as soon as it reports that value.

You should see Python 3.15.2 in the output.

✔️ I see Python 3.15.2

Python is ready for the scripts Claude creates later in the project.

ⓧ I see an older version

  • Return to the Python 3.15.2 release page.
  • Run the Python 3.15.2 installer for your operating system.
  • Start a fresh terminal window after installation.
  • Repeat the version check above.

ⓧ Command not found

  • Run the Python 3.15.2 installer again.
  • Close your current terminal window after installation.
  • Start a fresh terminal window.
  • Repeat the version check above.
Install and verify Claude Code

Claude Code works from the terminal where your project files live. Its native installer adds the command you will use to start the project session.

macOS

  • Install Claude Code from Terminal by running the official native installer:
curl -fsSL https://claude.ai/install.sh | bash

What does this command do?

This downloads Claude Code's official macOS installation script. The pipe passes that script to your shell so it can install the command-line tool.

Windows

  • Install Claude Code from PowerShell by running the official native installer:
irm https://claude.ai/install.ps1 | iex

What does this command do?

This downloads Claude Code's official Windows installation script. PowerShell then runs that script to install the command-line tool.

The installer should finish without reporting a failure.

  • Close the current terminal window after the installer finishes.

macOS

  • Press Command-Space to open Spotlight.
  • Type Terminal.
  • Press Return to start a fresh Terminal window.

Windows

  • Open Start.
  • Type PowerShell.
  • Press Enter to start a fresh PowerShell window.

macOS

  • Verify Claude Code from the new Terminal window by running this command:
claude --version

What does this command do?

This asks the installed Claude Code command to report its version. A successful response confirms the new terminal can find the installation.

Windows

  • Verify Claude Code from the new PowerShell window by running this command:
claude --version

What does this command do?

This asks the installed Claude Code command to report its version. A successful response confirms the new terminal can find the installation.

You should see a version number followed by (Claude Code).

✔️ I see version 2.1.336

Claude Code is installed. Your fresh terminal can find the command.

ⓧ I see an older version

  • Run the native installer above again to update Claude Code.
  • Close the current terminal after the update finishes.
  • Start a fresh terminal window.
  • Repeat the Claude Code version check.

ⓧ Command not found

  • Run the native installer above again.
  • Close the current terminal after installation.
  • Start a fresh terminal window.
  • Repeat the Claude Code version check.
  • If the version check still fails after starting a fresh terminal, inspect the installation by running this command in Terminal or PowerShell:
claude doctor

What does this command do?

Claude Code runs read-only checks against its installation. The diagnostic output points to installation or settings problems without changing your project.

Claude Code still unavailable?

Confirm that you started a fresh terminal after running the native installer. Re-run the installer if the diagnostic output says the installation is missing.

Still stuck? Help me troubleshoot my Claude Code installation.

Create the project folder and start Claude Code

The project folder keeps Claude's scripts beside the data files they create. Starting the session from that folder gives Claude the correct project context from the first message.

macOS

  • Move to your Desktop from Terminal by running this command:
cd ~/Desktop

What does this command do?

The cd command changes Terminal's current location. The ~/Desktop path points to the Desktop inside your macOS home folder.

  • Create my-hn-picks on your Desktop by running these commands:
mkdir my-hn-picks
cd my-hn-picks

What do these commands do?

The first command creates the my-hn-picks folder. The second command moves Terminal inside it.

Windows

  • Move to your Desktop from PowerShell by running this command:
cd $env:USERPROFILE\Desktop

What does this command do?

The cd command changes PowerShell's current location. The $env:USERPROFILE\Desktop path points to the Desktop inside your Windows user profile.

  • Create my-hn-picks on your Desktop by running these commands:
mkdir my-hn-picks
cd my-hn-picks

What do these commands do?

The first command creates the my-hn-picks folder. The second command moves PowerShell inside it.

Your terminal prompt should now end with my-hn-picks.

The next command starts an interactive Claude Code session. Claude Code opens a browser sign-in flow if this machine is not authenticated yet.

macOS

  • Start the Claude Code session from my-hn-picks by running this command in Terminal:
claude

What does this command do?

This starts an interactive Claude Code session in the current folder. Claude can now create files in my-hn-picks after you approve its changes.

Windows

  • Start the Claude Code session from my-hn-picks by running this command in PowerShell:
claude

What does this command do?

This starts an interactive Claude Code session in the current folder. Claude can now create files in my-hn-picks after you approve its changes.

  • Complete the browser login when Claude Code asks you to authenticate.
  • Follow the account prompts on the sign-in page Claude Code opens.
  • Return to your terminal when the authenticated Claude Code session appears.

You should now see the interactive Claude Code session running inside my-hn-picks.

Before you send the next message, which Python version do you expect Claude to report from inside my-hn-picks?

  • Ask Claude to verify Python by sending this exact message:
Check that Python works here and tell me which version I have.

What does this prompt do?

Claude checks Python with python3 --version on Mac. It uses python --version on Windows.

The result proves that Claude can reach Python from the folder where the project scripts will live.

  • Approve the Python version command when Claude asks.
  • Select the approval option displayed with the Python version command.

You should see Claude report a Python 3 version from inside my-hn-picks.

That is the setup locked in. Python is available inside an authenticated Claude Code session in your project folder.

Your tools are ready. Next, Claude will build the collector that walks backward through a year of Hacker News comments.

Pull a Year of Hacker News Comments

The Claude Code session from the last step can now use Python inside my-hn-picks. Your next job is to give the project the comments that drive every ranking.

The HN Search API's 1,000-hit ceiling makes a decreasing time cursor essential for collecting a full year.

The collector moves its upper time boundary to the oldest timestamp in each batch. It keeps walking backward until it reaches the start of the 12-month window.

In this step, get ready to:
  • Create get_comments.py with a decreasing time cursor.
  • Run the collector to save one year of comments in comments.json.
  • Inspect one saved comment to confirm it contains a YouTube link.
Create the comment collector

A single response cannot hold a year of matching comments. The collector needs to request older batches until its cursor reaches the start of the date range.

  • Ask Claude to create get_comments.py by sending this exact message in the Claude Code session:
Write get_comments.py using only built-in Python modules. It uses the HN Search API (https://hn.algolia.com/api) search_by_date endpoint with tags=comment and hitsPerPage=1000 to get every comment from the last 12 months that matches youtube.com, then every one that matches youtu.be. Each query returns at most 1000 hits, so walk back in time with numericFilters=created_at_i<(oldest time seen so far) instead of using page. Retry a failed request up to 5 times with a 60 second timeout. Save the comments to comments.json with their id, author, time and text, without duplicates, and print how many it saved.

What does this prompt ask Claude to build?

  • The collector searches search_by_date for comments matching youtube.com or youtu.be.
  • The numericFilters value moves the upper time boundary backward after every batch.
  • The retry loop handles temporary request failures before stopping the collection.
  • The collector uses deduplication before it saves the records to comments.json.

Claude proposes a new get_comments.py file inside my-hn-picks.

  • Approve the creation of get_comments.py when Claude asks.

That is the collector created. The new file now contains the logic for gathering a year of matching comments.

  • Review the imports at the top of get_comments.py for standard-library modules only.
  • Review fetch_hits() for a decreasing cursor value inside numericFilters.

You should see cursor = end_timestamp before the collection loop. You should also see cursor = oldest_timestamp after each batch.

✔️ Awesome, I've got everything!

Your collector uses built-in modules. Its cursor moves backward through the 12-month window.

ⓧ I'd like to double check the full code

Compare Claude's version with this complete get_comments.py reference.

import json
import time
from datetime import datetime, timezone
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import urlopen

API_URL = "https://hn.algolia.com/api/v1/search_by_date"
SEARCH_TERMS = ("youtube.com", "youtu.be")
HITS_PER_PAGE = 1000
TIMEOUT_SECONDS = 60
MAX_RETRIES = 5


def one_year_ago(when):
    try:
        return when.replace(year=when.year - 1)
    except ValueError:
        return when.replace(year=when.year - 1, day=28)


def load_json(url):
    for retry in range(MAX_RETRIES + 1):
        try:
            with urlopen(url, timeout=TIMEOUT_SECONDS) as response:
                return json.load(response)
        except (HTTPError, URLError, TimeoutError, OSError) as error:
            if retry == MAX_RETRIES:
                raise
            print(f"Request failed: {error}. Retry {retry + 1} of {MAX_RETRIES}.")
            time.sleep(min(2 ** retry, 30))


def fetch_hits(term, start_timestamp, end_timestamp):
    cursor = end_timestamp

    while cursor > start_timestamp:
        parameters = {
            "query": term,
            "tags": "comment",
            "hitsPerPage": HITS_PER_PAGE,
            "numericFilters": (
                f"created_at_i>{start_timestamp},created_at_i<{cursor}"
            ),
        }
        url = f"{API_URL}?{urlencode(parameters)}"
        data = load_json(url)
        hits = data.get("hits", [])

        if not hits:
            break

        yield hits

        oldest_timestamp = min(int(hit["created_at_i"]) for hit in hits)
        if oldest_timestamp >= cursor:
            raise RuntimeError("The created_at_i cursor did not move backward.")

        cursor = oldest_timestamp
        print(f"{term}: walked back to {datetime.fromtimestamp(cursor, timezone.utc).date()}")

        if len(hits) < HITS_PER_PAGE:
            break


def main():
    now = datetime.now(timezone.utc)
    start_timestamp = int(one_year_ago(now).timestamp())
    end_timestamp = int(now.timestamp()) + 1
    comments_by_id = {}

    for term in SEARCH_TERMS:
        for hits in fetch_hits(term, start_timestamp, end_timestamp):
            for hit in hits:
                comment_id = str(hit.get("objectID") or "")
                if not comment_id:
                    continue
                comments_by_id[comment_id] = {
                    "id": comment_id,
                    "author": hit.get("author"),
                    "time": int(hit["created_at_i"]),
                    "text": hit.get("comment_text") or "",
                }

    comments = sorted(
        comments_by_id.values(),
        key=lambda comment: (comment["time"], comment["id"]),
    )

    with open("comments.json", "w", encoding="utf-8") as output_file:
        json.dump(comments, output_file, ensure_ascii=False, indent=2)

    print(f"Saved {len(comments):,} comments to comments.json")


if __name__ == "__main__":
    main()

This reference starts both searches at the current time. Each completed batch replaces the cursor with its oldest timestamp.

Run the collector

The collector now needs to traverse the complete 12-month window. Its progress lines show the cursor moving toward older dates.

Before you run it, do you think the collection will stop at 1,000 comments or continue beyond that ceiling?

  • Ask Claude to run get_comments.py by sending this exact message:
Run get_comments.py.

What does this prompt do?

Claude selects the Python command for your operating system. It shows you that command for approval before the collector starts.

Claude proposes the command that matches your operating system.

macOS

Claude proposes python3 get_comments.py in the Claude Code session.

Windows

Claude proposes python get_comments.py in the Claude Code session.

Each network request can wait up to 60 seconds. A quiet stretch within that window is expected.

  • Approve the Python command when Claude asks.

You should see dated progress lines for both search terms. The final line reports a count in the tens of thousands saved to comments.json.

Did the collector stop early?

  • Let the built-in retry finish if the run reports Remote end closed connection.
  • Compare fetch_hits() with the complete reference if the final count is exactly 1,000.

Still stuck? Help me diagnose why my Hacker News comment collector stopped early or saved exactly 1,000 comments.

Inspect one saved comment

The saved count proves that the collector reached beyond one response. A record inspection confirms that the source text contains the links needed by the ranking step.

Before you inspect the file, do you expect the saved record to contain the original comment text or only a video ID?

  • Ask Claude to inspect one record by sending this exact message:
Show me one comment from comments.json and point out the YouTube link in it.

What does this prompt do?

Claude performs a read-only inspection of comments.json. It selects one saved record and identifies the YouTube link inside its text.

Claude reads comments.json and may propose a read-only inspection command.

  • Approve the read-only inspection command if Claude asks.

You should see one JSON record with id, author, time, and text fields. Claude points to a real youtube.com or youtu.be link inside the text.

That is the collection finished. Your project now has a deduplicated year of Hacker News comments ready for ranking.

Your source comments are saved in comments.json. Next, you'll extract the video IDs and rank them by distinct authors.

Rank the Videos

Your comments.json file now holds a year of collected comments. The Claude Code session from earlier can turn those comments into a ranked videos.csv file.

Counting distinct authors prevents one prolific poster from dominating a video's ranking.

In this step, get ready to:
  • Create rank_videos.py with distinct-author ranking.
  • Run rank_videos.py to generate videos.csv.
  • Explain why different people provide a stronger ranking signal.
Create the distinct-author ranker

The saved comments can contain HTML-escaped links. The ranker must unescape them before its regular expressions look for video IDs.

  • Send this exact message in the Claude Code session from earlier:
Write rank_videos.py. It reads comments.json, unescapes the HTML in each comment, and finds every YouTube video id (11 characters) in youtube.com/watch?v=, youtu.be/, /shorts/, /embed/ and /live/ links. Count each video once per author, so one person posting the same link ten times counts once. Save videos.csv with the video id, the number of different people, and the comment ids, sorted with the most recommended first. Print how many videos it found and the top 10.

What does this prompt ask for?

  • The html.unescape() call restores escaped characters before link extraction.
  • The YOUTUBE_PATTERNS collection covers watch links, short links, shorts, embeds, and live videos.
  • The authors set counts each person once for a video.
  • The comment_ids set retains the source comments behind each ranking.
  • The sorted rows place the largest people values first in videos.csv.

Claude creates rank_videos.py inside my-hn-picks and asks for permission to save it.

  • Approve the creation of rank_videos.py.

You should now have rank_videos.py beside comments.json in my-hn-picks.

  • Confirm that html.unescape() runs before YOUTUBE_PATTERNS searches the comment text.
  • Confirm that each video bucket stores an authors set.
  • Confirm that each video bucket stores a comment_ids set.

✔️ Awesome, I've got everything!

Your ranker is ready. Keep the Claude Code session in my-hn-picks for the first run.

ⓧ I'd like to double check the full code

  • Compare your rank_videos.py file with this complete version:
import csv
import html
import json
import re

VIDEO_ID = r"([A-Za-z0-9_-]{11})"
YOUTUBE_PATTERNS = (
    re.compile(
        rf"(?:https?://)?(?:www\.|m\.)?youtube\.com/watch\?"
        rf"(?:[^\s<>\"']*&)?v={VIDEO_ID}",
        re.IGNORECASE,
    ),
    re.compile(
        rf"(?:https?://)?(?:www\.)?youtu\.be/{VIDEO_ID}",
        re.IGNORECASE,
    ),
    re.compile(
        rf"(?:https?://)?(?:www\.|m\.)?youtube\.com/"
        rf"(?:shorts|embed|live)/{VIDEO_ID}",
        re.IGNORECASE,
    ),
)


def extract_video_ids(comment_text):
    unescaped_text = html.unescape(comment_text or "")
    video_ids = set()

    for pattern in YOUTUBE_PATTERNS:
        for match in pattern.finditer(unescaped_text):
            video_ids.add(match.group(1))

    return video_ids


def rank_videos(comments):
    videos = {}

    for comment in comments:
        author = comment.get("author")
        comment_id = str(comment.get("id") or "")
        if not author or not comment_id:
            continue

        for video_id in extract_video_ids(comment.get("text")):
            bucket = videos.setdefault(
                video_id,
                {"authors": set(), "comment_ids": set()},
            )
            bucket["authors"].add(author)
            bucket["comment_ids"].add(comment_id)

    ranked = []
    for video_id, bucket in videos.items():
        ranked.append(
            {
                "video_id": video_id,
                "people": len(bucket["authors"]),
                "comment_ids": sorted(bucket["comment_ids"], key=int),
            }
        )

    return sorted(ranked, key=lambda row: (-row["people"], row["video_id"]))


def write_csv(ranked):
    with open("videos.csv", "w", encoding="utf-8", newline="") as output_file:
        writer = csv.DictWriter(
            output_file,
            fieldnames=("video_id", "people", "comment_ids"),
        )
        writer.writeheader()
        for row in ranked:
            writer.writerow(
                {
                    "video_id": row["video_id"],
                    "people": row["people"],
                    "comment_ids": "|".join(row["comment_ids"]),
                }
            )


def main():
    with open("comments.json", encoding="utf-8") as input_file:
        comments = json.load(input_file)

    ranked = rank_videos(comments)
    write_csv(ranked)

    print(f"Found {len(ranked):,} distinct videos")
    print("Top 10:")
    for position, row in enumerate(ranked[:10], start=1):
        print(f"{position}. {row['video_id']} - {row['people']} people")


if __name__ == "__main__":
    main()
Run the ranker

The first run reads every saved comment and builds the author sets behind each video. Its printed top 10 gives you an immediate view of the strongest recommendations.

Before you send the next message, which videos do you expect to have the largest number of distinct recommenders?

  • Ask Claude to execute the ranker by sending this exact message:
Run it.

What happens next?

Claude chooses the Python command for your operating system. The script reads comments.json before writing the ranked rows to videos.csv.

macOS

  • Approve the python3 rank_videos.py command when Claude proposes it.

Windows

  • Approve the python rank_videos.py command when Claude proposes it.

You should see a distinct-video count followed by a top 10 ordered from the largest people value downward. The same ranked rows are saved in videos.csv.

A Dec 2025 to Nov 2026 test run found 18,267 videos, with the first recommended by 15 or more people. Your live totals can differ as Hacker News comments change.

You have turned a year of comments into a ranking shaped by different people.

Seeing zero videos?

A result of 0 videos usually means escaped links reached the regular expressions unchanged. Confirm that html.unescape() runs before YOUTUBE_PATTERNS.

Need another pair of eyes? Help me find why rank_videos.py extracted zero videos from comments.json.

Explain the ranking signal

The top 10 only matters if its score represents broad interest. Asking Claude to explain the rule helps you connect the code's authors sets to that goal.

  • Ask Claude to explain the ranking choice by sending this exact question:
Why count different people instead of total links?

What should Claude explain?

Total links can reward one person for posting the same video repeatedly. Distinct-author counts give that person one contribution to the video's score.

More people must recommend a video for its people value to rise. That makes broader interest the ranking signal.

Claude should explain that distinct authors reduce repeat-poster bias. No command approval is needed unless Claude asks to inspect videos.csv.

Your videos are ranked by different recommenders, and every row keeps its source comment IDs. Next up, you'll add titles and thumbnails without introducing an API key.

Get the Titles and Thumbnails

Your ranking now identifies which video IDs have support from the most distinct people. Next, Claude Code will extend the ranker with recognizable metadata.

This step makes ranked video IDs browsable by attaching human-readable metadata through YouTube oEmbed without an API key.

In this step, get ready to:
  • Add YouTube oEmbed metadata to rank_videos.py.
  • Run the enriched ranker to write top.json.
Add YouTube oEmbed enrichment

The strongest recommendations already appear first in videos.csv. The enrichment loop follows that order until it has 100 available videos.

  • Send this message in the Claude Code session from earlier:
Add to rank_videos.py: for the top 100 videos in videos.csv, look up each one with YouTube oEmbed (https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=ID&format=json) to get the title and channel. Skip videos that return an error, since those were deleted or made private, and keep going until there are 100. Use https://i.ytimg.com/vi/ID/hqdefault.jpg as the thumbnail. Save top.json and print the top 5 titles.

What does this prompt ask Claude to add?

  • The new get_oembed() function requests the title and author_name fields for one video.
  • The new build_top_videos() function skips failed lookups until it has collected 100 available videos.
  • Each record receives a thumbnail URL plus a video_url that opens the matching YouTube video.
  • Each record preserves its people count plus its source comment_ids.

Claude prepares an edit to rank_videos.py that adds metadata collection plus top.json output.

  • Approve Claude's edit to rank_videos.py when the Claude Code session asks.

The updated rank_videos.py now contains get_oembed() plus build_top_videos().

Run the enriched ranker

Each oEmbed lookup reaches YouTube, so deleted or private videos can fail. The loop skips those records before continuing through the ranking.

Before you run it, which output do you think will prove that the metadata pass reached its target?

  • Ask Claude to run the updated ranker by sending this message:
Run it.

What does this message do?

Claude uses the current session context to identify rank_videos.py as the file to run. It selects the Python command for your platform.

On Mac, Claude prepares python3 rank_videos.py. On Windows, Claude prepares python rank_videos.py.

  • Approve python3 rank_videos.py on Mac or python rank_videos.py on Windows.

You should see Top 5 titles: followed by five real video titles. The final line should say Saved 100 videos to top.json.

You have crossed the key data gap: top.json now carries the titles and thumbnails the site can display.

Are all lookups failing on Mac?

  • Go to /Applications/Python 3.15/ in Finder.
  • Double-click Install Certificates.command.
  • Repeat the run action above.

Still stuck? Help me diagnose why every YouTube oEmbed lookup fails in rank_videos.py on Mac.

✔️ Awesome, I've got everything!

Great work. Confirm that rank_videos.py is saved plus top.json is present in my-hn-picks.

ⓧ I'd like to double check the full code

Compare your updated rank_videos.py with this complete version.

import csv
import html
import json
import re
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import urlopen

TIMEOUT_SECONDS = 60
TOP_VIDEO_COUNT = 100
VIDEO_ID = r"([A-Za-z0-9_-]{11})"
YOUTUBE_PATTERNS = (
    re.compile(
        rf"(?:https?://)?(?:www\.|m\.)?youtube\.com/watch\?"
        rf"(?:[^\s<>\"']*&)?v={VIDEO_ID}",
        re.IGNORECASE,
    ),
    re.compile(
        rf"(?:https?://)?(?:www\.)?youtu\.be/{VIDEO_ID}",
        re.IGNORECASE,
    ),
    re.compile(
        rf"(?:https?://)?(?:www\.|m\.)?youtube\.com/"
        rf"(?:shorts|embed|live)/{VIDEO_ID}",
        re.IGNORECASE,
    ),
)


def extract_video_ids(comment_text):
    unescaped_text = html.unescape(comment_text or "")
    video_ids = set()

    for pattern in YOUTUBE_PATTERNS:
        for match in pattern.finditer(unescaped_text):
            video_ids.add(match.group(1))

    return video_ids


def rank_videos(comments):
    videos = {}

    for comment in comments:
        author = comment.get("author")
        comment_id = str(comment.get("id") or "")
        if not author or not comment_id:
            continue

        for video_id in extract_video_ids(comment.get("text")):
            bucket = videos.setdefault(
                video_id,
                {"authors": set(), "comment_ids": set()},
            )
            bucket["authors"].add(author)
            bucket["comment_ids"].add(comment_id)

    ranked = []
    for video_id, bucket in videos.items():
        ranked.append(
            {
                "video_id": video_id,
                "people": len(bucket["authors"]),
                "comment_ids": sorted(bucket["comment_ids"], key=int),
            }
        )

    return sorted(ranked, key=lambda row: (-row["people"], row["video_id"]))


def write_csv(ranked):
    with open("videos.csv", "w", encoding="utf-8", newline="") as output_file:
        writer = csv.DictWriter(
            output_file,
            fieldnames=("video_id", "people", "comment_ids"),
        )
        writer.writeheader()
        for row in ranked:
            writer.writerow(
                {
                    "video_id": row["video_id"],
                    "people": row["people"],
                    "comment_ids": "|".join(row["comment_ids"]),
                }
            )


def get_oembed(video_id):
    video_url = f"https://www.youtube.com/watch?v={video_id}"
    parameters = urlencode({"url": video_url, "format": "json"})
    oembed_url = f"https://www.youtube.com/oembed?{parameters}"

    with urlopen(oembed_url, timeout=TIMEOUT_SECONDS) as response:
        return json.load(response)


def build_top_videos(ranked):
    top_videos = []

    for row in ranked:
        if len(top_videos) == TOP_VIDEO_COUNT:
            break

        video_id = row["video_id"]
        try:
            metadata = get_oembed(video_id)
            title = metadata["title"]
            channel = metadata["author_name"]
        except (HTTPError, URLError, TimeoutError, OSError, json.JSONDecodeError, KeyError):
            continue

        top_videos.append(
            {
                "video_id": video_id,
                "title": title,
                "channel": channel,
                "thumbnail": f"https://i.ytimg.com/vi/{video_id}/hqdefault.jpg",
                "video_url": f"https://www.youtube.com/watch?v={video_id}",
                "people": row["people"],
                "comment_ids": row["comment_ids"],
            }
        )

    return top_videos


def main():
    with open("comments.json", encoding="utf-8") as input_file:
        comments = json.load(input_file)

    ranked = rank_videos(comments)
    write_csv(ranked)

    print(f"Found {len(ranked):,} distinct videos")
    print("Top 10:")
    for position, row in enumerate(ranked[:10], start=1):
        print(f"{position}. {row['video_id']} - {row['people']} people")

    top_videos = build_top_videos(ranked)
    with open("top.json", "w", encoding="utf-8") as output_file:
        json.dump(top_videos, output_file, ensure_ascii=False, indent=2)

    print("Top 5 titles:")
    for position, video in enumerate(top_videos[:5], start=1):
        print(f"{position}. {video['title']}")
    print(f"Saved {len(top_videos)} videos to top.json")


if __name__ == "__main__":
    main()

Your ranked videos now have the metadata people need to recognize them. Next, you'll turn top.json into the searchable HN Picks site.

Build Your Site

The previous step enriched your ranked video IDs with titles, channels, thumbnails, and links. Your top.json file now holds the records needed for a visual result.

Claude Code will turn the Hacker News rankings trapped in top.json into a page people can browse.

You will use a static site for this first visual version. Each card will lead to YouTube in a new tab.

In this step, get ready to:
  • Create build_site.py with Claude Code.
  • Generate index.html from top.json.
  • Display the HN Picks site from index.html.
Create the site generator

The generator will turn the records in top.json into one local page. Keeping every part inside index.html makes the result easy to display.

  • Ask Claude to create the generator by sending this exact message in the Claude Code session:
Write build_site.py. It reads top.json and writes one index.html with no other files: a grid of video cards like YouTube's home page, each with the thumbnail, title, channel and "Recommended by N people on Hacker News". Clicking a card opens the video on YouTube in a new tab. Add a search box at the top that filters the cards by title as you type. Make it work in dark mode.

What does this prompt ask Claude to build?

  • The generator reads each video record from top.json.
  • The generated index.html holds the page structure, styling, video data, and search behavior.
  • The card links send visitors to the matching video in a new tab.
  • The visible count uses the exact label Recommended by N people on Hacker News.

Claude proposes a new build_site.py file. The proposed file should read top.json without adding external Python packages.

  • Review the proposed build_site.py for the search box, dark-mode styling, video cards, and exact recommendation label.
  • Approve the build_site.py file creation when Claude asks.

You should see Claude confirm that build_site.py now exists inside my-hn-picks.

Generate the local page

The generator must run once before the local page exists. This run reads the current rankings from top.json.

  • Ask Claude to generate index.html by sending this exact message:
Run it.

What does this request do?

  • Claude runs python3 build_site.py on Mac.
  • Claude runs python build_site.py on Windows.
  • The script reads top.json before writing the generated page to index.html.

Claude prepares the matching Python command for your platform.

  • Approve the python3 build_site.py command on Mac or the python build_site.py command on Windows.

You should see a completion message confirming that index.html was built with up to 100 video cards.

Display and test the HN Picks site

The generated page runs locally from index.html. Its search behavior runs directly inside the page.

  • Ask Claude to display the page by sending this exact message:
Open index.html in my browser.

What does this request do?

  • Claude uses open index.html on Mac.
  • Claude uses start index.html on Windows.
  • Your operating system displays the local file with its associated browser.

Claude prepares the matching command for your platform.

  • Approve the open index.html command on Mac or the start index.html command on Windows.

There it is: your ranked data now appears as a dark-mode grid of up to 100 video cards. Each card shows its thumbnail, title, channel, and recommendation count.

Before you test the search, which cards do you expect to remain when the query matches one title word?

  • Filter the grid by entering one word from the first visible video title into the search box.
  • Click the search box at the top of the HN Picks site.

You should see non-matching cards disappear immediately. Every remaining title contains your search word.

  • Open the first filtered video card in a new tab.
  • Click the thumbnail or title on the first remaining card.

You should see the matching video open on YouTube in a new tab. The HN Picks site remains available in its original tab.

Before you inspect the first card again, do you think this version can show which comments caused its ranking?

  • Check the first card for the recommending authors or source comments behind its count.
  • Return to the HN Picks site tab.
  • Scan the first card below its recommendation label.

You will find the video details and recommendation count. You will not find the recommending authors or source comments. That shortfall is the intended result of this first visual version.

Site Missing or Unresponsive?

  • Confirm that index.html sits inside my-hn-picks beside build_site.py.
  • Check that top.json still contains video records if the grid is empty.
  • Reload the local page if the search box does not reflect the latest generated code.

Help me troubleshoot my local HN Picks site.

Your rankings now have a searchable visual home. Next, you will connect each card to the Hacker News comments that explain its position.

Show Why Each Video Made the List

Your HN Picks site already turns the ranked data into a searchable grid. Now you'll connect each card to the comments that earned its place.

A ranking earns trust when readers can trace it back to real comments from Hacker News.

In this step, get ready to:
  • Add expandable recommendation evidence to each video card.
  • Rebuild the HN Picks site with the updated generator.
  • Verify that an evidence link opens its matching Hacker News comment.
Add the recommendation evidence

Each record in `top.json` already carries the `comment_ids` that contributed to its ranking. The updated generator uses those IDs to find the matching records in `comments.json`.

  • Ask Claude Code to update `build_site.py` by sending this exact message in the Claude Code session:
  • Switch back to the Claude Code session inside `my-hn-picks`.
  • Paste the message into the input area.
  • Press **Enter**.
Update build_site.py: under each card add a "Why?" link that opens a short list of the comments that recommended this video (author, date and the first 200 characters), each linking to https://news.ycombinator.com/item?id=COMMENT_ID. Then rebuild index.html.

What does this prompt do?

  • The update reads `comments.json` so each saved `comment_id` can lead back to its original comment.
  • Each evidence panel keeps the author's name and the comment date. It also limits each excerpt to its first 200 characters.
  • Each source points to `https://news.ycombinator.com/item?id=COMMENT_ID` with the real comment ID substituted.
  • The final instruction rebuilds `index.html` so the new controls appear on the HN Picks site.

Claude proposes an edit to `build_site.py` that joins the saved comments to their ranked videos.

  • Approve Claude's edit to `build_site.py`.
  • Review the proposed changes shown beneath Claude's request.
  • Use the approval control beneath the proposed edit.

Claude next requests permission to rebuild `index.html` with the updated generator.

  • Approve `python3 build_site.py` on Mac or `python build_site.py` on Windows.
  • Review the platform command in Claude's permission request.
  • Use the approval control beneath the command.

You should see Claude finish the command with a message confirming that `index.html` was built with the video cards. The rebuilt file now contains the evidence panels.

✔️ Awesome, I've got everything!

Great. `build_site.py` now reads both data files. It has also rebuilt `index.html` with the recommendation evidence.

ⓧ I'd like to double check the full code

Compare your updated `build_site.py` with this complete version.

import html
import json
import re
from datetime import datetime, timezone


def plain_text(raw_html):
    unescaped = html.unescape(raw_html or "")
    without_tags = re.sub(r"<[^>]+>", " ", unescaped)
    return " ".join(without_tags.split())


def comment_date(timestamp):
    return datetime.fromtimestamp(int(timestamp), timezone.utc).strftime("%Y-%m-%d")


def make_site_data(videos, comments):
    comments_by_id = {str(comment["id"]): comment for comment in comments}
    site_data = []

    for video in videos:
        reasons = []
        for comment_id in video.get("comment_ids", [])[:5]:
            comment = comments_by_id.get(str(comment_id))
            if not comment:
                continue

            full_text = plain_text(comment.get("text"))
            excerpt = full_text[:200]
            if len(full_text) > 200:
                excerpt += "..."

            reasons.append(
                {
                    "author": comment.get("author") or "unknown",
                    "date": comment_date(comment["time"]),
                    "excerpt": excerpt,
                    "url": f"https://news.ycombinator.com/item?id={comment_id}",
                }
            )

        site_data.append({**video, "reasons": reasons})

    return site_data


def safe_json(data):
    return (
        json.dumps(data, ensure_ascii=False)
        .replace("&", "\\u0026")
        .replace("<", "\\u003c")
        .replace(">", "\\u003e")
    )


def main():
    with open("top.json", encoding="utf-8") as input_file:
        videos = json.load(input_file)

    with open("comments.json", encoding="utf-8") as input_file:
        comments = json.load(input_file)

    payload = safe_json(make_site_data(videos, comments))

    template = """<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Hacker News Video Picks</title>
  <style>
    :root {
      color-scheme: light dark;
      --background: #f7f7f7;
      --surface: #ffffff;
      --text: #151515;
      --muted: #666666;
      --border: #dddddd;
      --accent: #ff6600;
      --shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
    }

    @media (prefers-color-scheme: dark) {
      :root {
        --background: #101010;
        --surface: #1c1c1c;
        --text: #f2f2f2;
        --muted: #b0b0b0;
        --border: #333333;
        --shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
      }
    }

    * {
      box-sizing: border-box;
    }

    body {
      margin: 0;
      background: var(--background);
      color: var(--text);
      font-family: Arial, Helvetica, sans-serif;
    }

    header {
      position: sticky;
      top: 0;
      z-index: 10;
      padding: 18px clamp(16px, 4vw, 48px);
      background: color-mix(in srgb, var(--background) 92%, transparent);
      border-bottom: 1px solid var(--border);
      backdrop-filter: blur(12px);
    }

    .header-row {
      display: flex;
      align-items: center;
      gap: 16px;
      max-width: 1500px;
      margin: 0 auto;
    }

    h1 {
      margin: 0;
      font-size: clamp(1.2rem, 3vw, 1.8rem);
      white-space: nowrap;
    }

    h1 span {
      color: var(--accent);
    }

    #search {
      width: 100%;
      padding: 12px 14px;
      border: 1px solid var(--border);
      border-radius: 999px;
      background: var(--surface);
      color: var(--text);
      font-size: 1rem;
    }

    main {
      max-width: 1500px;
      margin: 0 auto;
      padding: 28px clamp(16px, 4vw, 48px) 56px;
    }

    #grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
      gap: 26px 18px;
    }

    .card {
      overflow: hidden;
      border: 1px solid var(--border);
      border-radius: 14px;
      background: var(--surface);
      box-shadow: var(--shadow);
      cursor: pointer;
    }

    .card:hover,
    .card:focus-within {
      transform: translateY(-2px);
    }

    .thumbnail-link,
    .thumbnail {
      display: block;
      width: 100%;
    }

    .thumbnail {
      aspect-ratio: 4 / 3;
      object-fit: cover;
      background: #292929;
    }

    .card-body {
      padding: 14px;
    }

    .title {
      display: -webkit-box;
      overflow: hidden;
      margin: 0 0 8px;
      color: var(--text);
      font-size: 1rem;
      font-weight: 700;
      line-height: 1.35;
      text-decoration: none;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
    }

    .channel,
    .count {
      margin: 4px 0;
      color: var(--muted);
      font-size: 0.9rem;
    }

    .count {
      color: var(--accent);
      font-weight: 700;
    }

    .why-link {
      display: inline-block;
      margin-top: 10px;
      color: var(--text);
      font-weight: 700;
    }

    .reasons {
      margin-top: 12px;
      padding-top: 10px;
      border-top: 1px solid var(--border);
    }

    .reason {
      margin: 0 0 12px;
      color: var(--muted);
      font-size: 0.85rem;
      line-height: 1.4;
    }

    .reason a {
      color: var(--accent);
    }

    #empty {
      color: var(--muted);
      text-align: center;
    }

    @media (max-width: 620px) {
      .header-row {
        align-items: stretch;
        flex-direction: column;
      }
    }
  </style>
</head>
<body>
  <header>
    <div class="header-row">
      <h1>HN <span>Picks</span></h1>
      <input id="search" type="search" placeholder="Search video titles" aria-label="Search video titles">
    </div>
  </header>
  <main>
    <div id="grid"></div>
    <p id="empty" hidden>No matching videos.</p>
  </main>
  <script id="video-data" type="application/json">__VIDEO_DATA__</script>
  <script>
    const videos = JSON.parse(document.getElementById("video-data").textContent);
    const grid = document.getElementById("grid");
    const empty = document.getElementById("empty");
    const search = document.getElementById("search");

    function makeLink(text, href, className) {
      const link = document.createElement("a");
      link.textContent = text;
      link.href = href;
      link.target = "_blank";
      link.rel = "noopener noreferrer";
      if (className) link.className = className;
      return link;
    }

    function makeCard(video) {
      const card = document.createElement("article");
      card.className = "card";
      card.addEventListener("click", (event) => {
        if (!event.target.closest("a")) {
          window.open(video.video_url, "_blank", "noopener,noreferrer");
        }
      });

      const thumbnailLink = makeLink("", video.video_url, "thumbnail-link");
      const image = document.createElement("img");
      image.className = "thumbnail";
      image.src = video.thumbnail;
      image.alt = "";
      image.loading = "lazy";
      thumbnailLink.appendChild(image);
      card.appendChild(thumbnailLink);

      const body = document.createElement("div");
      body.className = "card-body";
      body.appendChild(makeLink(video.title, video.video_url, "title"));

      const channel = document.createElement("p");
      channel.className = "channel";
      channel.textContent = video.channel;
      body.appendChild(channel);

      const count = document.createElement("p");
      count.className = "count";
      count.textContent = `Recommended by ${video.people} people on Hacker News`;
      body.appendChild(count);

      const why = document.createElement("a");
      why.href = "#";
      why.className = "why-link";
      why.textContent = "Why?";
      body.appendChild(why);

      const reasons = document.createElement("div");
      reasons.className = "reasons";
      reasons.hidden = true;

      if (video.reasons.length === 0) {
        const missing = document.createElement("p");
        missing.className = "reason";
        missing.textContent = "No saved comment details were found.";
        reasons.appendChild(missing);
      }

      for (const reason of video.reasons) {
        const paragraph = document.createElement("p");
        paragraph.className = "reason";
        const source = makeLink(`${reason.author} on ${reason.date}`, reason.url, "");
        paragraph.appendChild(source);
        paragraph.append(`: ${reason.excerpt}`);
        reasons.appendChild(paragraph);
      }

      why.addEventListener("click", (event) => {
        event.preventDefault();
        reasons.hidden = !reasons.hidden;
        why.textContent = reasons.hidden ? "Why?" : "Hide";
      });

      body.appendChild(reasons);
      card.appendChild(body);
      return card;
    }

    function render(list) {
      grid.replaceChildren(...list.map(makeCard));
      empty.hidden = list.length !== 0;
    }

    search.addEventListener("input", () => {
      const query = search.value.trim().toLowerCase();
      const matches = videos.filter((video) => video.title.toLowerCase().includes(query));
      render(matches);
    });

    render(videos);
  </script>
</body>
</html>
"""

    with open("index.html", "w", encoding="utf-8") as output_file:
        output_file.write(template.replace("__VIDEO_DATA__", payload))

    print(f"Built index.html with {len(videos)} video cards")


if __name__ == "__main__":
    main()
Verify the sources from the top card

The rebuilt page should preserve the searchable grid while adding a small evidence panel to every card. The top card gives you a quick end-to-end check because its saved comment IDs should resolve to visible source links.

Before you display the rebuilt page, do you expect the first card to stop at its recommendation count or reveal the comments behind it?

  • Display the rebuilt HN Picks site by running the command for your platform in a terminal tab inside `my-hn-picks`:

macOS

open index.html

Windows

start index.html

What does this command do?

The command gives `index.html` to your operating system. Your default application for HTML files displays the rebuilt HN Picks site.

You should see the same searchable grid of video cards. Each card now has a `Why?` control beneath the exact `Recommended by N people on Hacker News` label.

  • Select **Why?** on the first video card.
  • Locate the first video card beneath the search box.
  • Find **Why?** below its recommendation label.
  • Click **Why?**.

You should see saved recommending-comment authors and dates. Each entry also includes an excerpt limited to 200 characters.

  • Open one linked author-and-date source from the expanded evidence panel.
  • Choose the linked author and date at the start of an excerpt.

You should see the matching Hacker News item open with the real source comment. That is the ranking made auditable: every score now points back to its evidence.

Why is the evidence list empty?

  • Confirm that the first record in `top.json` still contains `comment_ids`.
  • Compare one saved `comment_id` with the `id` values in `comments.json`.
  • Check that `build_site.py` calls `make_site_data()` before it writes the embedded video data.

Still stuck? Help me trace an empty Why? panel through top.json, comments.json, and build_site.py.

Secret mission

Make the Rankings Yours

Rescope the live Hacker News pipeline to five years or one topic. Then rebuild the HN Picks site without changing its distinct-author ranking rule.

Clean Up Your Resources

Clean Up Your Resources

The local files plus HN Search API and YouTube oEmbed requests add no separate charge. Your existing Claude plan remains the only paid resource, so choose below whether to keep the project ready, pause your work, or delete it entirely.

Resources you used:

  • Authenticated Claude Code session running inside my-hn-picks.
  • Local my-hn-picks folder containing get_comments.py, rank_videos.py, build_site.py, comments.json, videos.csv, top.json, and index.html.

Keep everything running

No action is needed. Choose this option if you want to refresh the rankings or try another data scope.

  • Keep the Claude Code session available for future changes.
  • Leave my-hn-picks in its current location.

The rebuilt HN Picks site stays available from index.html.

Pause - I'll come back to this later

Shut down active work while preserving every script and rebuilt output for later.

  • Close the Terminal window on Mac or the PowerShell window on Windows that contains the Claude Code session.
  • Leave my-hn-picks in its current location.

Your selected five-year or topic-filtered scope remains saved in get_comments.py.

Delete - I don't want to use this again

Deleting my-hn-picks permanently removes every script, dataset, ranking, and generated page from this project.

macOS

  • Close the Terminal window that contains the Claude Code session.
  • Use Finder to locate the my-hn-picks folder.
  • Move the my-hn-picks folder into the Trash.
  • Empty the Trash to remove the folder from your Mac.

You should no longer find my-hn-picks on your Mac, which confirms that every local project resource is gone.

Windows

  • Close the PowerShell window that contains the Claude Code session.
  • Use File Explorer to locate the my-hn-picks folder.
  • Move the my-hn-picks folder into the Recycle Bin.
  • Empty the Recycle Bin to remove the folder from your computer.

You should no longer find my-hn-picks on your computer, which confirms that every local project resource is gone.

Nice Work!

Nice Work!

You did it! You built the HN Picks site with Python and Claude Code from live Hacker News comments. Every ranking now links back to the comments that shaped it.

You've learned how to:

  • Collect a full year of Hacker News comments through the HN Search API. A decreasing created_at_i time cursor moves past the API's 1,000-hit ceiling.
  • Rank extracted YouTube video IDs by distinct authors. Each person counts once per video.
  • Generate a searchable static site from up to 100 videos enriched through YouTube oEmbed. Each Why? panel links a ranking to the saved authors, dates, excerpts, and Hacker News items.
  • Complete the Secret Mission by rebuilding the pipeline for five years of comments or one topic filter. The new rankings preserve the time cursor, distinct-author count, and evidence panels.

Ready to quiz yourself?