Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions .github/workflows/magpie.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
name: magpie

on:
workflow_dispatch:
inputs:
steps:
description: What to run (all = crawl, then promote)
type: choice
options: [crawl, promote, all, reextract]
default: crawl
dry-run:
description: Log every write without making it
type: boolean
default: true
# Off until supabase migration 20261119000000_ingest_schema is applied, a
# dry run has been checked, and the time and limits are decided. Scheduled
# runs write.
# To turn it on:
# schedule:
# - cron: '0 4 * * *'

concurrency:
group: magpie
cancel-in-progress: false

env:
SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
SUPABASE_KEY: ${{ secrets.SUPABASE_KEY }}
DRY_RUN: ${{ github.event_name != 'schedule' && inputs.dry-run && '--dry-run' || '' }}

jobs:
magpie:
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- uses: actions/checkout@v7

- uses: astral-sh/setup-uv@v10.3.3
with:
enable-cache: true

- name: Install dependencies
run: uv sync --locked --no-dev

# One crawl run: list both boards, fetch due threads, extract
# candidates. A listing that fails writes nothing and fails the job;
# failed thread fetches are routine and only listed.
- name: Crawl Geekhack
if: github.event_name == 'schedule' || inputs.steps == 'crawl' || inputs.steps == 'all'
run: uv run magpie crawl $DRY_RUN

# Extract every stored first post again (after EXTRACTOR_VERSION is
# bumped), without requests to Geekhack. Manual only.
- name: Extract stored threads again
if: github.event_name == 'workflow_dispatch' && inputs.steps == 'reextract'
run: uv run magpie reextract $DRY_RUN

# Manual only, never on schedule: an IC and its GB are two candidates
# (duplicate keysets), and covers and kits are not reliable enough for
# the review queue until Keebdex has a Discovered tab.
- name: Propose complete keysets to Keebdex
if: github.event_name == 'workflow_dispatch' && (inputs.steps == 'promote' || inputs.steps == 'all')
run: uv run magpie promote $DRY_RUN
119 changes: 111 additions & 8 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ separate repository).
- `config.py`: `require_env(name)` for settings.
- `db.py`: `create_supabase(source=None)`, the only way to create a Supabase
client, and `revision_source(job, origin)` for its source (see "Revision
sources"); `fetch_all(client, table, columns, where)`
for every paged read; `PUBLISHED_FILTER` (Keebdex's published rule); `Row`.
sources"); `fetch_all(client, table, columns, where, order)` for every paged
read (also on `client.schema("ingest")`); `PUBLISHED_FILTER` (Keebdex's
published rule); `Row`.
- `pool.py`: `run_each(items, work)`, network work a few at a time
(`CONCURRENCY`), counting failures.
- `http.py`: `create_http_client()` for reading websites.
Expand All @@ -46,7 +47,7 @@ separate repository).
- `src/aviary/lorikeet/`: reference color palettes. `ral.py` crawls
ralcolorchart.com, `sync.py` plans and writes the `colors` rows, `__main__.py`
is the `lorikeet` command.
- `src/aviary/bowerbird/`: the artisan sync, ported from `../catalog-sync`.
- `src/aviary/bowerbird/`: the artisan sync, ported from catalog-sync (archived).
`gdoc/` holds the Google Docs side (`parser.py`, `dates.py`, `jsregex.py`,
`google.py` for the read-only API calls, `importer.py`); `jsregex.py` also
holds JavaScript's whitespace (`JS_WHITESPACE`, `js_trim`), and per-maker name
Expand All @@ -59,8 +60,16 @@ separate repository).
catalog-sync's image jobs. `references.py` (`IMAGE_COLUMNS`, which images the
database references), `sync.py`, `maintenance.py` (restore, prune, backup),
`__main__.py` the `pelican` command. See "Images and backups".
- Planned, not yet here: `magpie` (forum crawler writing to the `ingest` schema
for staff review). Create a module only when its first real code lands.
- `src/aviary/magpie/`: the Geekhack crawler, ported from huginn without its
web UI. `geekhack.py` (boards, topic URLs, `normalize_image_url`), `fetch.py`
(the polite `Fetcher`), `parsers.py` (board list and first post), `kits.py`,
`classify.py` (title to kind and profile code), `proposal.py` (thread to
keyset candidate, `EXTRACTOR_VERSION`), `plan.py` (listings, fetch schedule,
promotions, pure), `ingest.py` (reads and writes of the `ingest` tables),
`keebdex.py` (keyset and profile reads, the promotion writes), one module
per command (`crawl.py`, `promote.py`, `reextract.py`) with `summary.py`
for what their job summaries share, and `__main__.py` the `magpie` command
line (arguments, `topic`). See "Forum crawl".

## Commands

Expand All @@ -74,6 +83,10 @@ separate repository).
- `uv run --env-file .env bowerbird gdoc|scrape [--maker ID] [--dry-run]`.
- `uv run --env-file .env pelican sync|restore|prune|backup [--dry-run]`
(`restore --force`, `backup --limit N --force-trash`).
- `uv run --env-file .env magpie crawl [--board B] [--max-pages N]
[--fetch-limit N] [--dry-run]`, `magpie promote [--limit N]
[--max-age-days N] [--dry-run]`, `magpie reextract [--limit N]
[--dry-run]`; `uv run magpie topic <id|url>` (no database).

## Rules for jobs

Expand All @@ -93,6 +106,7 @@ separate repository).
(lorikeet's schedule is paused). bowerbird and pelican run at catalog-sync's
old times: bowerbird at 23:00 UTC, pelican sync and restore at 01:00, backup
and the database dump at 02:00, prune at 00:00 on the 1st and the 15th.
magpie has no schedule until its schema is applied.

## Revision sources

Expand All @@ -111,9 +125,11 @@ per process). `create_supabase(source)` sends them when `source` is given.
- `lorikeet` writes only `colors`, which has no revisions, and sends no source.
- `bowerbird gdoc` sends `bowerbird.gdoc`; `bowerbird scrape` gives each maker
a client of its own sending `bowerbird.<maker_id>`; `pelican sync` sends
`pelican.cloudflare-images`; `magpie` will send `magpie.<site>`
(`magpie.geekhack`, `magpie.novelkeys`). These are not the `source` column of
the artisan rows (`gdoc`, `scraper`), which says which sync owns a row.
`pelican.cloudflare-images`. These are not the `source` column of the artisan
rows (`gdoc`, `scraper`), which says which sync owns a row.
- `magpie promote` sends `magpie.geekhack`, the forum its candidates come from
(a vendor store would be `magpie.novelkeys`); `magpie crawl` writes only
`ingest` and sends none.

## Artisan sync

Expand Down Expand Up @@ -229,6 +245,93 @@ source: it is JavaScript's `undefined` versus `null`.
all incoming colorways, not per sculpt. Gaps are harmless: only the relative
order matters.

## Forum crawl

`magpie` is huginn (a crawler with a web UI for reviewing Geekhack topics by
hand) as a batch job. Its parsers were checked against huginn's on saved and
live pages; the choices huginn's UI left to a person are now made from the
topic, and staff review the result in Keebdex instead.

- Its data lives in the `ingest` schema of supabase migration
`20261119000000_ingest_schema.sql` (read its header before changing what
magpie writes): `threads` (listing, first post, fetch queue), `candidates`
(extractions waiting for triage), `crawl_runs`. Staff read and triage them
from the app under RLS; magpie uses the service role. The schema must be
exposed through the Data API.
- `crawl` is one `crawl_runs` row (one running at a time; a run running for
over an hour is marked failed). Each board is listed down to the watermark
of the last succeeded run (the newest last post it saw), its last page, or
`--max-pages`; a board the cap stopped is in `incomplete_boards` and keeps
its old watermark, or, when it never had one, gets the newest last post it
saw (what lies below is backlog, for one run with a higher `--max-pages`).
Every board is read before anything is written, and only a succeeded run
moves watermarks. Stickies are skipped. Geekhack times have
no zone and are stored as UTC.
- A listed thread is due (`next_fetch_at`) when new or when its last post
moved, gone ones included; otherwise the listing only refreshes it. A fetch
stores the `div.post` HTML (`raw_body`, `parsers.parse_post` reads it again)
and its hash (`changed_at` when it changes), then schedules the next fetch:
weekly while the thread is under 90 days old (edits don't bump a thread),
else on new activity only. A failure backs off from an hour, doubling, and
stops after 5 in a row until new activity starts the count over; a 404 sets
`gone_at`. Failures are routine and the run still succeeds. robots.txt is
retried like a page: a 4xx means no rules, unreachable fails the run.
- Each fetched keyset thread (by title, `classify.py`) gets a candidate:
`payload` shaped like the keyset submission (`keyset` columns, `kits`),
`confidence` per field, `match_key` when Keebdex has the keyset. The
`candidates_supersede` trigger drops an extraction already made (same
`EXTRACTOR_VERSION` and content) and supersedes the waiting one; when the
first post goes back to an earlier version it puts that superseded
extraction back to `new` (the summary counts these apart, from the state
read before the insert). Bump the version when `extract()` changes, then
run `reextract`. Keyboards are not extracted yet.
- `reextract` extracts every stored first post (`raw_body`) of threads
neither ignored nor gone again with the current `EXTRACTOR_VERSION` and
saves candidates as `crawl` does, without requests to Geekhack and without
a `crawl_runs` row (watermarks untouched). It refuses while a crawl runs;
running it twice adds nothing.
- Extraction: the title starts with `[GB]`, `[IC]` or `[Pre-order]` (status
by board, so a pre-order on the GB board is Confirmed), and its keycap code
must name exactly one published profile
(`profile_id`, then name: KKB is `keykobo`); a second code ("GMK MTNU
Dasher") picks that profile. The name drops the codes and the profile's name
("GMK CYL Selene" is `gmk/selene`) and what follows ` | `, ` - `, ` : ` or
two spaces (where the listing dropped a dash), and notes in parentheses
(progress, new kits, "Previously ..."); the slug is `url_slugify`. Name and
slug confidence is 0.6: staff should read them. Status is
Interest Check on the IC board, Cancelled when the title says so, else
Confirmed; `ic_date` the IC's posting day; Cherry profiles get sculpt
`1-1-2-3-4-4`. Kits: one per labelled kit image (`kits.py`), else a Base kit
with the cover (the first image when no Base label), with `name` null (it
holds a kit's own name, never its category's). An image file on
`imgur.com` (a redirect page) is stored as its `i.imgur.com` file; a link
in the post that is not a URL is skipped, never failing the fetch. The
crawl summary lists keycap codes that name no Keebdex profile, with up to
3 titles each, and keyset titles with no code: profiles staff may add.
- `promote` runs only by hand (the workflow's `promote` or `all`, never on
schedule) until Keebdex has a Discovered tab: an IC and its GB are two
candidates, so it can insert a keyset twice, and covers and kits are not
reliable enough for the review queue yet. It inserts, newest topic first
and at most `--limit`, the waiting candidates with no `match_key` whose
payload is complete (`missing_for_promotion`) and whose thread was posted
within `--max-age-days` and is neither ignored nor gone: the keyset and its
kits `Pending` with a null `submitted_by`, like catalog-sync's vendor keysets,
then the candidate `promoted` (`promoted_kind` keyset). Keebdex's keyset
queue lists kits, so when the kits fail, or staff triaged the candidate
meanwhile (the claim finds it no longer `new`; listed apart in the
summary, not a failure), the keyset just inserted and its kits are deleted
again. A claim that raises is read back first: the keyset stays when the
candidate is promoted to it or cannot be read, so no candidate points at a
deleted keyset. A failed delete is logged with the id for removal by hand
and the run goes on. A candidate whose keyset Keebdex has now (its topic's
URL in any `topic=` form, or its key, of any source or review status, or a
keyset this run inserts) gets that `match_key` and waits for staff as an
edit; keysets are never updated, a different status is only reported.
Everything else waits for staff.
- An empty read of keysets or profiles writes nothing; a failed promotion
makes `promote` exit 1. Images stay external: `pelican sync` uploads them
once staff approve.

## Images and backups

Image columns: `artisan_colorways.img`, `keysets.img` / `order_graph` /
Expand Down
60 changes: 55 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ bird:
| `lorikeet` | Adds reference color palettes (RAL) to Keebdex | Ready |
| `bowerbird` | Syncs artisan catalogs from makers and Docs | Ready |
| `pelican` | Keeps Keebdex's images on Cloudflare and in R2 | Ready |
| `magpie` | Crawls forum interest checks and group buys | Planned |
| `magpie` | Crawls forum interest checks and group buys | Porting |

`bowerbird` and `pelican` took over the artisan sync and the image jobs from
[catalog-sync](https://github.com/keebdex/catalog-sync), which keeps only its
vendor keyset scraper, run by hand, until `magpie` replaces it.
[catalog-sync](https://github.com/keebdex/catalog-sync), now archived; `magpie`
replaces its vendor keyset scraper.

## Setup

Expand Down Expand Up @@ -71,7 +71,7 @@ Design code up on ralcolorchart.com as it is typed.
## bowerbird

Syncs artisan sculpts and colorways into Keebdex from makers' Google Docs and
maker websites. It is a port of catalog-sync's artisan sync, and replaces it in
maker websites. It is a port of catalog-sync's artisan sync, which it replaced in
production.

```bash
Expand Down Expand Up @@ -106,7 +106,7 @@ uv run --env-file .env bowerbird scrape --dry-run
## pelican

Keeps Keebdex's images on Cloudflare Images and backed up in Cloudflare R2: a
port of catalog-sync's image jobs, which it replaces in production.
port of catalog-sync's image jobs, which it replaced in production.

```bash
uv run --env-file .env pelican sync --dry-run
Expand All @@ -127,6 +127,56 @@ uv run --env-file .env pelican sync --dry-run
- `docs/backups.md` is the operator guide for the R2 bucket: its locks, the
trash, and restoring by hand.

## magpie

Crawls Geekhack's [Interest Checks](https://geekhack.org/index.php?board=132.0)
and [Group Buys](https://geekhack.org/index.php?board=70.0) boards into the
`ingest` schema of Keebdex's database, reads a keyset candidate out of each
keyset thread, and proposes the complete ones as Pending keysets for staff to
review in Keebdex's keyset Submissions. A port of huginn (a local crawler with
a web UI) without the UI: the choices huginn left to a person (profile, cover,
kits) are made from the topic, and what magpie can't settle waits in
`ingest.candidates` for staff.

```bash
uv run --env-file .env magpie crawl --dry-run
```

```bash
uv run --env-file .env magpie promote --dry-run
```

```bash
uv run magpie topic 127176
```

- `crawl` is one run (`ingest.crawl_runs`; one at a time). It lists both
boards (`--board` for one) down to the newest last post the previous
succeeded run saw, up to 5 pages each (`--max-pages`; run once with a large
value to backfill). Every page is read, about one a second, before anything
is written: a page that fails or shows no topics fails the run and writes
nothing. Then it fetches the first post of due threads (new, with new
replies, or a week since the last fetch while under 90 days old; 100 at most,
`--fetch-limit`), keeps the post as it is, and adds a keyset candidate:
profile, name, cover, kits, status, and a confidence per field. A topic that
fails is retried with backoff; one that answers 404 is marked gone.
- `promote` inserts, newest first and at most 25 per run (`--limit`), the
candidates magpie read completely (profile, name, cover, kits), posted in the
last 90 days (`--max-age-days`), that Keebdex doesn't have: a Pending keyset
with no submitter and its Pending kits (one per labelled kit image, or a Base
kit with the cover, so the keyset shows up in the review queue). A candidate
of a keyset Keebdex has (its URL, or the same profile and slug) gets that
keyset as its `match_key` and waits for staff, as do incomplete and older
ones; a different status is reported, never written.
- `topic` prints one topic as JSON and needs no database.
- Needs the `ingest` schema (migration `20261119000000_ingest_schema.sql` in
Keebdex's supabase repository), with `ingest` added to the Data API's exposed
schemas. Promoted keysets show in Keebdex's history under the
`magpie.geekhack` revision source.
- `.github/workflows/magpie.yml` runs the crawl, the promotion, or both from
the Actions tab, as a dry run unless the box is unticked. Its schedule is off
until the schema is applied and a dry run has been checked.

## License

[MIT](LICENSE)
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ dependencies = [
[project.scripts]
bowerbird = "aviary.bowerbird.__main__:main"
lorikeet = "aviary.lorikeet.__main__:main"
magpie = "aviary.magpie.__main__:main"
pelican = "aviary.pelican.__main__:main"

[build-system]
Expand Down
12 changes: 8 additions & 4 deletions src/aviary/common/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from collections.abc import Callable
from typing import Any

from postgrest import SyncPostgrestClient
from supabase import Client, ClientOptions, create_client

from aviary.common.config import require_env
Expand Down Expand Up @@ -62,16 +63,19 @@ def create_supabase(source: str | None = None) -> Client:


def fetch_all(
client: Client,
client: Client | SyncPostgrestClient,
table: str,
columns: str = "*",
where: Callable = lambda query: query,
order: str = "id",
) -> list[Row]:
"""Every row matching `where`, in pages ordered by id. Raises on any error
(supabase-py does): a partial read must never look like "nothing there"."""
"""Every row matching `where`, in pages ordered by `order` (a column whose
values are unique among those rows). `client` may also be a schema's
client (`client.schema("ingest")`). Raises on any error (supabase-py
does): a partial read must never look like "nothing there"."""
rows: list[Row] = []
while True:
query = where(client.table(table).select(columns)).order("id")
query = where(client.table(table).select(columns)).order(order)
data = query.range(len(rows), len(rows) + PAGE_SIZE - 1).execute().data
rows += data
if len(data) < PAGE_SIZE:
Expand Down
2 changes: 2 additions & 0 deletions src/aviary/magpie/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"""magpie: crawls Geekhack's Interest Check and Group Buy boards into the
`ingest` schema and proposes the keysets it finds to Keebdex for review."""
Loading