From 5eb6aa19e217e02d00f3e2ddb381359371841fa6 Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Sat, 15 Aug 2026 19:53:09 -0600 Subject: [PATCH 1/2] ADFA-5094: build_kolibri_catalog.py can emit + size the topic tree Extend the catalog generator (run by publish-catalogs.yml and the refreshKolibriCatalog gradle task) to also walk Studio's contentnode_tree and emit the topic tree, so the app can browse channels offline. --measure walks the trees once and prints raw+gzip sizes for both variants with a walked-vs-catalog resource cross-check; --tree {topics,full} writes the chosen asset. topics keeps folders + a per-folder aggregate of direct loose resources (dcount/dbytes), an order of magnitude smaller than full; the live source fills leaf titles online. Tooling only: nothing in the APK changes yet. --- controller/app/tools/build_kolibri_catalog.py | 219 ++++++++++++++++-- 1 file changed, 201 insertions(+), 18 deletions(-) diff --git a/controller/app/tools/build_kolibri_catalog.py b/controller/app/tools/build_kolibri_catalog.py index 91e370c75..58421f20a 100644 --- a/controller/app/tools/build_kolibri_catalog.py +++ b/controller/app/tools/build_kolibri_catalog.py @@ -30,13 +30,16 @@ # ============================================================================ import argparse import datetime +import gzip import json import os import sys +import urllib.parse import urllib.request STUDIO = "https://studio.learningequality.org" ENDPOINT = "/api/public/v2/channel/" +TREE_ENDPOINT = "/api/public/v2/contentnode_tree/" PAGE_SIZE = 250 # well under the server's max_page_size of 1000 TIMEOUT = 60 UA = "Mozilla/5.0 (K2Go catalog builder)" @@ -63,6 +66,10 @@ os.path.dirname(os.path.abspath(__file__)), "..", "src", "main", "assets", "kolibri_catalog.jsonl") +DEFAULT_TREE_OUT = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "..", "src", "main", "assets", + "kolibri_tree.jsonl") + def fetch_page(page): url = "{}{}?public=true&page_size={}&page={}".format( @@ -152,39 +159,215 @@ def write(rows, out_path, source): return os.path.getsize(out_path) +# ---- Tree dump / sizing (ADFA-5094) --------------------------------------- +# The channel LIST above is tiny; the offline-BROWSE feature needs the TOPIC +# TREE too. This walks Studio's contentnode_tree per channel (the same shape the +# app already parses with StudioCatalogMapper) and can emit two variants so we +# can weigh bundle size against coverage: +# full - every node (topics + resource leaves), lean fields incl. own bytes. +# topics - only the folders; each carries its subtree resource count plus the +# count/bytes of its DIRECT loose resources (dcount/dbytes), so a mixed +# level reads "N resources here" without listing leaves. An order of +# magnitude smaller than full; the live source fills the leaf titles online. +# `--measure` walks the trees once and prints raw + gzip sizes and counts for +# BOTH variants without writing anything, and cross-checks the walked resource +# count against the catalog's total_resource_count so an under-walk is visible +# rather than silent. + +def _is_thumb(f): + return bool(f.get("thumbnail")) or str(f.get("preset") or "").endswith("_thumbnail") + + +def fetch_tree_call(node_id, more=None): + url = STUDIO + TREE_ENDPOINT + node_id + "/" + if isinstance(more, dict) and more: + url += "?" + urllib.parse.urlencode(more) + req = urllib.request.Request(url, headers={"User-Agent": UA, + "Accept": "application/json"}) + with urllib.request.urlopen(req, timeout=TIMEOUT) as r: + return json.loads(r.read().decode("utf-8")) + + +def walk_channel_tree(root_id): + """Flat rows for one channel: {id,parent,title,kind,is_leaf,size,count}. + + Recurses children.results and follows children.more paging — the shape + StudioCatalogMapper reads. Never raises past the channel: on any error the + channel contributes [] (and the resource cross-check will flag the shortfall). + """ + rows = [] + + def rec(node, parent_id): + nid = str(node.get("id") or "") + if len(nid) != 32: + return + is_leaf = bool(node.get("is_leaf")) + size = 0 + for f in (node.get("files") or []): + if not _is_thumb(f): + try: + size += int(f.get("file_size") or 0) + except (TypeError, ValueError): + pass + try: + count = int(node.get("total_resource_count") or 0) + except (TypeError, ValueError): + count = 0 + rows.append({ + "id": nid, "parent": parent_id, "title": str(node.get("title") or ""), + "kind": str(node.get("kind") or ""), "is_leaf": is_leaf, + "size": size, "count": count, + }) + ch = node.get("children") or {} + for c in (ch.get("results") or []): + rec(c, nid) + more = ch.get("more") + while isinstance(more, dict) and more: + page = fetch_tree_call(nid, more) + pch = page.get("children") or {} + for c in (pch.get("results") or []): + rec(c, nid) + more = pch.get("more") + + try: + rec(fetch_tree_call(root_id), "") + except Exception as e: # noqa: BLE001 + print(" ! tree {} failed: {}".format(root_id, e), file=sys.stderr) + return [] + return rows + + +def project_rows(rows, variant): + """Project the flat node rows to the fields a variant keeps (lean = small bundle). + + topics keeps only the folders, but folds each folder's DIRECT loose-resource + children into an aggregate (dcount / dbytes) so a mixed level can show + "N resources here - X bytes" without listing every leaf. The individual leaf + titles come from the live source (Studio / box) when online — the bundle is + the offline floor; the fallback fills the gaps. + """ + if variant == "full": + return [{"id": r["id"], "parent": r["parent"], "title": r["title"], + "kind": r["kind"], "leaf": 1 if r["is_leaf"] else 0, "size": r["size"]} + for r in rows] + # topics: aggregate the direct leaf children onto each parent folder + direct = {} + for r in rows: + if r["is_leaf"]: + d = direct.setdefault(r["parent"], [0, 0]) + d[0] += 1 + d[1] += r["size"] + out = [] + for r in rows: + if r["is_leaf"] and r["kind"] != "topic": + continue + dc, db = direct.get(r["id"], (0, 0)) + out.append({"id": r["id"], "parent": r["parent"], "title": r["title"], + "kind": r["kind"], "count": r["count"], "dcount": dc, "dbytes": db}) + return out + + +def serialize(rows): + body = "\n".join(json.dumps(r, ensure_ascii=False, sort_keys=True) for r in rows) + return (body + "\n").encode("utf-8") + + +def human(n): + x = float(n) + for u in ("B", "KB", "MB", "GB"): + if x < 1024: + return "{:.1f} {}".format(x, u) + x /= 1024.0 + return "{:.1f} TB".format(x) + + +def build_all_trees(channels, limit): + chans = channels[:limit] if limit else channels + rows = [] + for i, c in enumerate(chans, 1): + print(" tree {}/{}: {}".format(i, len(chans), c.get("name") or c["id"])) + rows.extend(walk_channel_tree(c.get("root") or c["id"])) + return rows + + +def report_variant(rows, variant): + proj = project_rows(rows, variant) + blob = serialize(proj) + gz = gzip.compress(blob, 9) + print(" {:7s}: {:>8,} nodes | raw {:>10} | gzip {:>10}".format( + variant, len(proj), human(len(blob)), human(len(gz)))) + return proj + + def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--from-file", dest="from_file", - help="parse a saved JSON response instead of fetching") - ap.add_argument("--out", default=os.path.normpath(DEFAULT_OUT)) + help="parse a saved channel-list JSON response instead of fetching") + ap.add_argument("--out", default=None, + help="output path (defaults: catalog->assets/kolibri_catalog.jsonl, " + "tree->assets/kolibri_tree.jsonl)") + ap.add_argument("--tree", choices=["topics", "full"], + help="emit a topic tree (that variant) instead of the channel list") + ap.add_argument("--measure", action="store_true", + help="walk the trees and print raw+gzip sizes for BOTH variants; writes nothing") + ap.add_argument("--limit", type=int, default=0, + help="only the first N channels — a quick sample before the full run") args = ap.parse_args() + # The channel list is needed in every mode (it carries the roots + the + # total_resource_count used for the cross-check). if args.from_file: - print(">> [kolibri catalog] reading {}".format(args.from_file)) + print(">> [kolibri] reading channel list {}".format(args.from_file)) raw = load_dump(args.from_file) source = "file:" + os.path.basename(args.from_file) else: - print(">> [kolibri catalog] fetching {}{}".format(STUDIO, ENDPOINT)) + print(">> [kolibri] fetching channel list {}{}".format(STUDIO, ENDPOINT)) raw = fetch_all() source = STUDIO + ENDPOINT trimmed = [t for t in (trim(r) for r in raw) if t] - dropped = len(raw) - len(trimmed) - rows = dedupe(trimmed) - - if not rows: - print(">> [kolibri catalog] no usable channels; keeping the existing asset", - file=sys.stderr) + channels = dedupe(trimmed) + if not channels: + print(">> [kolibri] no usable channels; keeping the existing asset", file=sys.stderr) return 1 - size = write(rows, args.out, source) - print(">> [kolibri catalog] {} channels -> {} ({:.0f} KB)".format( - len(rows), args.out, size / 1024.0)) - if dropped: - print(">> [kolibri catalog] skipped {} unusable row(s)".format(dropped)) - if len(trimmed) != len(rows): - print(">> [kolibri catalog] collapsed {} duplicate id(s)".format( - len(trimmed) - len(rows))) + # ---- catalog mode (unchanged default behaviour) ---- + if not args.tree and not args.measure: + out = args.out or os.path.normpath(DEFAULT_OUT) + size = write(channels, out, source) + print(">> [kolibri catalog] {} channels -> {} ({:.0f} KB)".format( + len(channels), out, size / 1024.0)) + return 0 + + # ---- tree modes (ADFA-5094) ---- + scope = channels[:args.limit] if args.limit else channels + print(">> [kolibri tree] walking contentnode_tree for {} channel(s){}".format( + len(scope), " (LIMIT)" if args.limit else "")) + rows = build_all_trees(channels, args.limit) + + walked_res = sum(1 for r in rows if r["is_leaf"]) + catalog_res = sum(c.get("total_resource_count") or 0 for c in scope) + flag = "" + if catalog_res and abs(walked_res - catalog_res) > catalog_res * 0.05: + flag = " <-- MISMATCH: under-walk? (deep channels may need per-topic fetch)" + print(">> walked {:,} nodes, {:,} resource leaves; catalog reports {:,} resources{}".format( + len(rows), walked_res, catalog_res, flag)) + + if args.measure: + print(">> sizes (nothing written):") + report_variant(rows, "topics") + report_variant(rows, "full") + return 0 + + proj = report_variant(rows, args.tree) + out = args.out or os.path.normpath(DEFAULT_TREE_OUT) + tmp = out + ".tmp" + os.makedirs(os.path.dirname(out), exist_ok=True) + with open(tmp, "wb") as f: + f.write(serialize(proj)) + os.replace(tmp, out) + print(">> [kolibri tree:{}] {} nodes -> {} ({})".format( + args.tree, len(proj), out, human(os.path.getsize(out)))) return 0 From e152e54f13133304be33b44268b827f4c393e9ca Mon Sep 17 00:00:00 2001 From: Luis Guzman Date: Sat, 15 Aug 2026 20:06:43 -0600 Subject: [PATCH 2/2] ADFA-5094: read the topic tree from channel DBs, not the contentnode_tree API The API crawl 400s on ~half the channels and returns only shallow data (measured: 561 of 352,591 resources walked). Switch to downloading each channel's published content DB (the .sqlite3 that remoteimport uses) and reading content_contentnode + content_file directly: complete and reliable, one download per channel. topics now also carries per-folder subtree bytes for the folder aggregate. Same flags (--measure / --tree {topics,full}); tooling only. --- controller/app/tools/build_kolibri_catalog.py | 158 ++++++++++-------- 1 file changed, 84 insertions(+), 74 deletions(-) diff --git a/controller/app/tools/build_kolibri_catalog.py b/controller/app/tools/build_kolibri_catalog.py index 58421f20a..0cf70f3d6 100644 --- a/controller/app/tools/build_kolibri_catalog.py +++ b/controller/app/tools/build_kolibri_catalog.py @@ -33,13 +33,17 @@ import gzip import json import os +import sqlite3 import sys -import urllib.parse +import tempfile import urllib.request STUDIO = "https://studio.learningequality.org" ENDPOINT = "/api/public/v2/channel/" -TREE_ENDPOINT = "/api/public/v2/contentnode_tree/" +# Published channel content DB — the same artifact Kolibri's remoteimport pulls; it +# holds the whole tree + file sizes, so we read it instead of crawling the public +# contentnode_tree API (which 400s on many channels and only returns shallow data). +DB_URL = STUDIO + "/content/databases/{}.sqlite3" PAGE_SIZE = 250 # well under the server's max_page_size of 1000 TIMEOUT = 60 UA = "Mozilla/5.0 (K2Go catalog builder)" @@ -161,79 +165,76 @@ def write(rows, out_path, source): # ---- Tree dump / sizing (ADFA-5094) --------------------------------------- # The channel LIST above is tiny; the offline-BROWSE feature needs the TOPIC -# TREE too. This walks Studio's contentnode_tree per channel (the same shape the -# app already parses with StudioCatalogMapper) and can emit two variants so we -# can weigh bundle size against coverage: +# TREE too. Rather than crawl the public contentnode_tree API (which 400s on many +# channels and returns only shallow data), download each channel's published +# content DB — the same .sqlite3 Kolibri's remoteimport pulls — and read the whole +# tree straight from content_contentnode + content_file, exactly as the box's +# buildLocalSubtree does locally. One download per channel, complete and reliable. +# Two variants let us weigh bundle size against coverage: # full - every node (topics + resource leaves), lean fields incl. own bytes. -# topics - only the folders; each carries its subtree resource count plus the -# count/bytes of its DIRECT loose resources (dcount/dbytes), so a mixed -# level reads "N resources here" without listing leaves. An order of -# magnitude smaller than full; the live source fills the leaf titles online. -# `--measure` walks the trees once and prints raw + gzip sizes and counts for -# BOTH variants without writing anything, and cross-checks the walked resource -# count against the catalog's total_resource_count so an under-walk is visible -# rather than silent. - -def _is_thumb(f): - return bool(f.get("thumbnail")) or str(f.get("preset") or "").endswith("_thumbnail") - - -def fetch_tree_call(node_id, more=None): - url = STUDIO + TREE_ENDPOINT + node_id + "/" - if isinstance(more, dict) and more: - url += "?" + urllib.parse.urlencode(more) - req = urllib.request.Request(url, headers={"User-Agent": UA, - "Accept": "application/json"}) - with urllib.request.urlopen(req, timeout=TIMEOUT) as r: - return json.loads(r.read().decode("utf-8")) - - -def walk_channel_tree(root_id): - """Flat rows for one channel: {id,parent,title,kind,is_leaf,size,count}. +# topics - only the folders; each carries its subtree resource count + bytes plus +# the count/bytes of its DIRECT loose resources (dcount/dbytes), so a +# mixed level reads "N resources here" without listing leaves. An order +# of magnitude smaller; the live source fills the leaf titles online. +# `--measure` builds both once and prints raw + gzip sizes and counts without +# writing, and cross-checks the walked resource count against the catalog's +# total_resource_count so a failed/short channel is visible rather than silent. + +def download_channel_db(channel_id): + """Fetch a channel's published content DB to a temp file. Caller deletes it.""" + req = urllib.request.Request(DB_URL.format(channel_id), + headers={"User-Agent": UA}) + fd, path = tempfile.mkstemp(prefix="k2go_", suffix=".sqlite3") + with os.fdopen(fd, "wb") as out, urllib.request.urlopen(req, timeout=TIMEOUT) as r: + while True: + chunk = r.read(1 << 16) + if not chunk: + break + out.write(chunk) + return path + + +def walk_channel_db(db_path): + """Flat rows for one channel from its content DB: {id,parent,title,kind,is_leaf, + size,count,subbytes}. size = own content bytes; count/subbytes = subtree totals.""" + con = sqlite3.connect(db_path) + con.row_factory = sqlite3.Row + try: + nodes = con.execute( + "SELECT id, parent_id, title, kind, rght FROM content_contentnode").fetchall() + own = {} + for r in con.execute( + "SELECT f.contentnode_id AS nid, COALESCE(SUM(lf.file_size), 0) AS b " + "FROM content_file f JOIN content_localfile lf ON lf.id = f.local_file_id " + "WHERE f.thumbnail = 0 AND f.supplementary = 0 " + "GROUP BY f.contentnode_id"): + own[r["nid"]] = int(r["b"] or 0) + finally: + con.close() - Recurses children.results and follows children.more paging — the shape - StudioCatalogMapper reads. Never raises past the channel: on any error the - channel contributes [] (and the resource cross-check will flag the shortfall). - """ rows = [] - - def rec(node, parent_id): - nid = str(node.get("id") or "") - if len(nid) != 32: - return - is_leaf = bool(node.get("is_leaf")) - size = 0 - for f in (node.get("files") or []): - if not _is_thumb(f): - try: - size += int(f.get("file_size") or 0) - except (TypeError, ValueError): - pass - try: - count = int(node.get("total_resource_count") or 0) - except (TypeError, ValueError): - count = 0 + for n in nodes: + is_leaf = (n["kind"] != "topic") rows.append({ - "id": nid, "parent": parent_id, "title": str(node.get("title") or ""), - "kind": str(node.get("kind") or ""), "is_leaf": is_leaf, - "size": size, "count": count, + "id": str(n["id"]), "parent": str(n["parent_id"] or ""), + "title": str(n["title"] or ""), "kind": str(n["kind"] or ""), + "is_leaf": is_leaf, "size": own.get(n["id"], 0), + "rght": n["rght"] if n["rght"] is not None else 0, + "count": 0, "subbytes": 0, }) - ch = node.get("children") or {} - for c in (ch.get("results") or []): - rec(c, nid) - more = ch.get("more") - while isinstance(more, dict) and more: - page = fetch_tree_call(nid, more) - pch = page.get("children") or {} - for c in (pch.get("results") or []): - rec(c, nid) - more = pch.get("more") - try: - rec(fetch_tree_call(root_id), "") - except Exception as e: # noqa: BLE001 - print(" ! tree {} failed: {}".format(root_id, e), file=sys.stderr) - return [] + # Subtree totals bottom-up: a node's rght exceeds all its descendants', so + # ascending-rght order processes children before parents (one MPTT tree/channel). + sub_c = {r["id"]: (1 if r["is_leaf"] else 0) for r in rows} + sub_b = {r["id"]: r["size"] for r in rows} + for r in sorted(rows, key=lambda x: x["rght"]): + p = r["parent"] + if p in sub_c: + sub_c[p] += sub_c[r["id"]] + sub_b[p] += sub_b[r["id"]] + for r in rows: + r["count"] = sub_c[r["id"]] + r["subbytes"] = sub_b[r["id"]] return rows @@ -263,7 +264,8 @@ def project_rows(rows, variant): continue dc, db = direct.get(r["id"], (0, 0)) out.append({"id": r["id"], "parent": r["parent"], "title": r["title"], - "kind": r["kind"], "count": r["count"], "dcount": dc, "dbytes": db}) + "kind": r["kind"], "count": r["count"], "bytes": r["subbytes"], + "dcount": dc, "dbytes": db}) return out @@ -285,8 +287,16 @@ def build_all_trees(channels, limit): chans = channels[:limit] if limit else channels rows = [] for i, c in enumerate(chans, 1): - print(" tree {}/{}: {}".format(i, len(chans), c.get("name") or c["id"])) - rows.extend(walk_channel_tree(c.get("root") or c["id"])) + print(" channel {}/{}: {}".format(i, len(chans), c.get("name") or c["id"])) + path = None + try: + path = download_channel_db(c["id"]) + rows.extend(walk_channel_db(path)) + except Exception as e: # noqa: BLE001 + print(" ! channel {} failed: {}".format(c["id"], e), file=sys.stderr) + finally: + if path and os.path.exists(path): + os.remove(path) return rows @@ -341,7 +351,7 @@ def main(): # ---- tree modes (ADFA-5094) ---- scope = channels[:args.limit] if args.limit else channels - print(">> [kolibri tree] walking contentnode_tree for {} channel(s){}".format( + print(">> [kolibri tree] reading published content DBs for {} channel(s){}".format( len(scope), " (LIMIT)" if args.limit else "")) rows = build_all_trees(channels, args.limit) @@ -349,7 +359,7 @@ def main(): catalog_res = sum(c.get("total_resource_count") or 0 for c in scope) flag = "" if catalog_res and abs(walked_res - catalog_res) > catalog_res * 0.05: - flag = " <-- MISMATCH: under-walk? (deep channels may need per-topic fetch)" + flag = " <-- MISMATCH: a channel DB failed to download/parse" print(">> walked {:,} nodes, {:,} resource leaves; catalog reports {:,} resources{}".format( len(rows), walked_res, catalog_res, flag))