A story · tabelline 0.1

FOSDEM's data, made with nanuq

Twenty-six years of FOSDEM schedules, from five kinds of web page to ten tidy tables, cleaned, joined and counted with nanuq, Polars for Nim, in under a second.

tabelline makes display tables from data that is already processed. For the FOSDEM story the processing is done by nanuq, Polars for Nim: the data frame library of Rust and Python, written with Nim's syntax. This is the first time nanuq made a whole dataset from raw files, end to end, and it is worth showing how: every table of the story comes out of about 750 lines of nanuq, which run in less than a second and give the same files, byte for byte, every time.

Reading the code

Green cards like this one are about how the page is made. This story does not use nanuq: it reads the CSV files nanuq wrote with Nim's standard library, and quotes the nanuq code from src/process.nim as it is.

One expression to start

The smallest piece of the work is a name. FOSDEM prints a speaker's name as the speaker typed it, so the same person comes back with accents or without, with a nickname, in other cases. To count who keeps coming back, every name gets a key. In nanuq that is one expression, built from string operations as in Polars, and kept in a proc so it can be used on any column:

proc nameKey(e: Expr): Expr =
  ## A key to match the same person across years: accents and case folded (ø, ł, ß and
  ## friends too), punctuation and nicknames in quotes dropped, spaces collapsed. The key keeps
  ## Latin letters only, so "Bogomil Shopov - Бого" is `bogomil shopov`; a name with no Latin
  ## letter at all (a name in Chinese) keeps its own letters.
  let folded = e.str.normalize(UnicodeForm.NFKD)
   .str.replaceAll(r"\p{Mn}", "")
   .str.replaceAll("\"[^\"]*\"", " ")
   .str.toLowercase
   # letters that NFKD does not split into a base letter and a mark
   .str.replaceMany({"ø": "o", "ł": "l", "ß": "ss", "æ": "ae", "œ": "oe", "ı": "i", "þ": "th", "ð": "d", "đ": "d"})
  let latin = folded.str.replaceAll(r"[^a-z0-9]+", " ").str.stripChars
  choose(if latin == "": folded.str.replaceAll(r"[^\p{L}\p{N}]+", " ").str.stripChars else: latin)

Six people, each showing one thing the key folds:

One person, many spellings
the key, what it folds, and the names as printed
foldsas printed
richard hartmanna nicknameRichard Hartmann · Richard "RichiH" Hartmann
jon maddog hallquotes, caseJon 'Maddog' Hall · Jon Maddog Hall · Jon 'maddog' Hall
kris novaaccents, caseKris Nova · kris "clusterfunk" nóva · Kris Nóva
adrien beraudan accentAdrien Béraud · Adrien Beraud
helge hessß is ssHelge Hess · Helge Heß
aeva blackÆ is aeAeva Black · Æva Black
type Spellings = object
  key, folds, spellings: string
var seen: Table[string, OrderedSet[string]]
for s in data["event_speakers"]:
  seen.mgetOrPut(s["person_key"], initOrderedSet[string]()).incl s["person"]
let picked = [("richard hartmann", "a nickname"), ("jon maddog hall", "quotes, case"),
              ("kris nova", "accents, case"), ("adrien beraud", "an accent"),
              ("helge hess", "ß is ss"), ("aeva black", "Æ is ae")]
var rows: seq[Spellings]
for (k, why) in picked:
  rows.add Spellings(key: k, folds: why, spellings: seen[k].toSeq.join(" · "))
let t = tabella(rows, rownameCol = "key"):
  optCssTheme()
  tabHeader "One person, many spellings", "the key, what it folds, and the names as printed"
  colsLabel {"key": "", "folds": "folds", "spellings": "as printed"}
nbTable t

The key is not clever on purpose: it does not know that "RMS" is Richard Stallman. It is cheap, it is the same on every run, and the story says where it fails.

Three steps, one of them nanuq

The data goes from FOSDEM's websites to ten tables in three steps, each in the tool that suits it:

From the web to ten tables
the scripts in src/, in the order build.sh runs them
toolscriptswhat it does
1. fetchshell: curl, wget, git1download the archive's pages, XML, mailing list and website history, about 200 MB
2. flattenNim, standard library10read HTML, XML, YAML and mbox, write one staging CSV per format
3. processNim with nanuq2clean, join and count: the ten tables, then the story's small ones
type Step = object
  step, tool, does: string
  files: int
let src = fosdem / "src"
var extract = 0
for f in walkFiles(src / "extract_*.nim"): inc extract
let rows = @[
  Step(step: "1. fetch", tool: "shell: curl, wget, git", files: 1,
       does: "download the archive's pages, XML, mailing list and website history, about 200 MB"),
  Step(step: "2. flatten", tool: "Nim, standard library", files: extract,
       does: "read HTML, XML, YAML and mbox, write one staging CSV per format"),
  Step(step: "3. process", tool: "Nim with nanuq", files: 2,
       does: "clean, join and count: the ten tables, then the story's small ones")]
let t = tabella(rows, rownameCol = "step"):
  optCssTheme()
  tabHeader "From the web to ten tables", "the scripts in src/, in the order build.sh runs them"
  colsLabel {"step": "", "files": "scripts", "does": "what it does"}
  colsMoveToEnd ["does"]
nbTable t

The first two steps only move bytes around: the old FOSDEM sites are HTML written by hand, one layout a year, and Nim's standard library reads them with regular expressions, its XML parser and a small mail reader. Everything that needs a decision (what a talk is, who a person is, which devroom is which) happens in the third step, in nanuq. The raw files are not committed; the ten tables are.

The flattening was first written in Python, then ported to Nim: the Nim scripts write the same twenty staging files as the Python ones did, byte for byte, so the ten tables did not change. Here are the scripts of the first two steps, whole, in the order build.sh runs them, then what they share (common.nim) and grid.nim, which spreads the cells of an HTML table over the rows and columns they span (and prints the tables of a page, to look at the old sites):

src/fetch.sh 59 lines
#!/bin/sh
# Downloads the raw FOSDEM sources into $1 (default: ./raw). Nothing here is committed:
# the raw files are ~200 MB. Hosts needed: archive.fosdem.org, fosdem.org, lists.fosdem.org, github.com.
set -eu
RAW=${1:-raw}
mkdir -p "$RAW/xml" "$RAW/html" "$RAW/pages/devrooms" "$RAW/tracks" "$RAW/lists"
A=https://archive.fosdem.org

# 2012-2026: the schedule XML of each edition (Pentabarf, pretalx from 2026).
for y in $(seq 2012 2026); do curl -sSf -o "$RAW/xml/$y.xml" "$A/$y/schedule/xml"; done

# 2001-2006: the old sites, as they are archived (no schedule export then).
for y in $(seq 2001 2006); do
  (cd "$RAW/html" && wget -q -r -l 4 -np -nH -e robots=off --wait=0.2 -T 20 \
    --reject 'jpg,jpeg,png,gif,pdf,css,js,ico,ogg,ogv,avi,mp4,webm,zip,tgz,svg,odp,ppt,pptx,mp3,flv' \
    "$A/$y/") || true   # wget exits non-zero on the archive's broken links
done

# 2007-2011: event index and speakers pages; 2007-2010 also the devroom index and pages.
for y in $(seq 2007 2011); do
  curl -sSf -o "$RAW/pages/events$y.html" "$A/$y/schedule/events.html"
  curl -sSf -o "$RAW/pages/speakers$y.html" "$A/$y/schedule/speakers.html"
done
for y in $(seq 2007 2010); do
  curl -sSf -o "$RAW/pages/devrooms$y.html" "$A/$y/schedule/devrooms.html"
  dir=devrooms; [ "$y" -le 2008 ] && dir=devroom
  for d in $(grep -o "href=\"$dir/[^\"]*\.html\"" "$RAW/pages/devrooms$y.html" | sed "s|href=\"$dir/||;s|\"||" | sort -u); do
    curl -sSf -o "$RAW/pages/devrooms/$y-$d" "$A/$y/schedule/$dir/$d"
  done
  curl -sSf -o "$RAW/pages/devrooms/$y-lightningtalks.html" "$A/$y/schedule/tracks/lightningtalks.html"
done

# 2013-2026: every track page (CfP link, rooms, group).
for y in $(seq 2013 2026); do
  mkdir -p "$RAW/tracks/$y"
  curl -sSf -o "$RAW/tracks/$y/index.html" "$A/$y/schedule/tracks/"
  for t in $(grep -o "href=\"/$y/schedule/track/[^\"]*/\"" "$RAW/tracks/$y/index.html" | sed "s|href=\"/$y/schedule/track/||;s|/\"||" | sort -u); do
    curl -sSf -o "$RAW/tracks/$y/$t.html" "$A/$y/schedule/track/$t/"
  done
done

# 2008-2026: the stands of every edition.
mkdir -p "$RAW/stands"
for y in $(seq 2008 2012); do curl -sSf -o "$RAW/stands/$y.html" "$A/$y/stands.html"; done
for y in $(seq 2013 2026); do curl -sSf -o "$RAW/stands/$y.html" "$A/$y/stands/"; done

# The fosdem@lists.fosdem.org archive (2006-), as one mbox.
curl -sSf -o "$RAW/lists/fosdem.mbox.gz" \
  "https://lists.fosdem.org/hyperkitty/list/fosdem@lists.fosdem.org/export/fosdem.mbox.gz?start=2000-01-01&end=2030-12-31"
gunzip -kf "$RAW/lists/fosdem.mbox.gz"

# The next edition, as announced on fosdem.org: dates and accepted devrooms.
NEXT=${NEXT:-2027}
mkdir -p "$RAW/upcoming"
curl -sSf -o "$RAW/upcoming/accepted-developer-rooms.html" "https://fosdem.org/$NEXT/news/accepted-developer-rooms/"
curl -sSf -o "$RAW/upcoming/fosdem-$NEXT-dates.html" "https://fosdem.org/$NEXT/news/fosdem-$NEXT-dates/"

# FOSDEM's archived website (2013-2025), for the history of devrooms-cfp.yaml.
[ -d "$RAW/fosdem-website" ] || git clone -q --filter=blob:none https://github.com/FOSDEM/website "$RAW/fosdem-website"
src/build.sh 28 lines
#!/bin/sh
# Rebuilds the tables of docs/stories/data/fosdem/ from the raw downloads of fetch.sh.
#   sh build.sh <raw dir> <nanuq checkout>
# Step 1 (Nim, standard library only) flattens the raw XML, HTML, YAML history and
# mbox into staging CSVs; step 2 (Nim + nanuq) cleans, joins and aggregates them.
set -eu
RAW=$1
NANUQ=$2
HERE=$(cd "$(dirname "$0")" && pwd)
OUT=$(dirname "$HERE")
STAGE=${STAGE:-$RAW/stage}
mkdir -p "$STAGE/bin"
run() { s=$1; shift; nim c -d:release --hints:off -o:"$STAGE/bin/$s" "$HERE/$s.nim" && "$STAGE/bin/$s" "$@"; }
run extract_xml "$RAW/xml" "$STAGE"
run extract_eventindex "$RAW/pages" "$STAGE"
run extract_devrooms "$RAW/pages" "$STAGE"
run extract_early "$RAW/html" "$STAGE"
run extract_early_devrooms "$RAW/html" "$STAGE"
run extract_trackpages "$RAW/tracks" "$STAGE"
run extract_cfp_yaml "$RAW/fosdem-website" "$STAGE"
run extract_lists "$RAW/lists/fosdem.mbox" "$STAGE"
run extract_stands "$RAW/stands" "$STAGE"
run extract_upcoming "$RAW/upcoming" "$STAGE" "${NEXT:-2027}"
nim c -d:release --hints:off --path:"$NANUQ/src" -o:"$STAGE/bin/process" "$HERE/process.nim"
"$STAGE/bin/process" "$STAGE" "$OUT"
# The small tables of the story (docs/stories/fosdem.nim), from the tables above.
nim c -d:release --hints:off --path:"$NANUQ/src" -o:"$STAGE/bin/insights" "$HERE/insights.nim"
"$STAGE/bin/insights" "$OUT" "$OUT/story"
src/extract_xml.nim 92 lines
## Flatten FOSDEM Pentabarf/pretalx schedule XML (2012-2026) into staging CSVs.
##
## Usage: extract_xml <raw/xml dir> <stage dir>
## Only parses and flattens; cleaning and aggregation happen in nanuq (process.nim).

import std/[xmlparser, xmltree, algorithm]
import common

proc ownText(x: XmlNode): string =
  ## The text of an element before its first child element (Python's ElementTree `.text`).
  for c in x:
    case c.kind
    of xnText, xnCData: result.add c.text
    of xnEntity: result.add htmlUnescape("&" & c.text & ";")
    of xnElement: break
    else: discard

proc kids(x: XmlNode, tag: string): seq[XmlNode] =
  if x == nil: return
  for c in x:
    if c.kind == xnElement and c.tag == tag: result.add c

proc kid(x: XmlNode, tag: string): XmlNode =
  let k = x.kids(tag)
  if k.len > 0: k[0] else: nil

proc t(x: XmlNode, tag: string): string =
  let c = x.kid(tag)
  if c == nil: "" else: c.ownText.pyStrip

proc keepTrailingSpaces(xml: string): string =
  ## Nim's XML parser trims the spaces at the end of an attribute value, and Python keeps
  ## them (a few links end with one): write them as character references, which it keeps.
  var at = 0
  for m in xml.finditer(rx"""(=\s*"[^"<]*?)([ \t\r\n]+)"|(=\s*'[^'<]*?)([ \t\r\n]+)'"""):
    let q = if m.has(1): '"' else: '\''
    result.add xml[at ..< m.start]
    result.add (if m.has(1): m.group(1) else: m.group(3)) & "&#32;".repeat((if m.has(1): m.group(2) else: m.group(4)).len) & q
    at = m.stop
  result.add xml[at .. ^1]

proc path(x: XmlNode, a, b: string): seq[XmlNode] =
  for c in x.kids(a): result.add c.kids(b)

let src = paramStr(1)
let stage = paramStr(2)
var conf, events, eperson, links, tracks: seq[seq[string]]
var files: seq[string]
for kind, f in walkDir(src, relative = true):
  if f.endsWith(".xml"): files.add f
files.sort
for fn in files:
  let year = $parseInt(fn[0 ..< 4])
  let root = parseXml(keepTrailingSpaces(readFile(src / fn)))
  let c = root.kid("conference")
  conf.add @[year, c.t("title"), c.t("subtitle"), c.t("venue"), c.t("city"), c.t("start"),
             c.t("end"), c.t("days")]
  for tr in root.path("tracks", "track"):
    tracks.add @[year, tr.attr("slug"), tr.ownText.pyStrip, tr.attr("online_qa")]
  for day in root.kids("day"):
    let date = day.attr("date")
    for room in day.kids("room"):
      for ev in room.kids("event"):
        let eid = ev.attr("id")
        let tr = ev.kid("track")
        var video, slides, attachments, nlinks = 0
        for a in ev.path("attachments", "attachment"):
          inc attachments
          if a.attr("type") == "slides" or "slides" in a.ownText.toLowerAscii: inc slides
        for l in ev.path("links", "link"):
          let href = l.attr("href")
          inc nlinks
          if (href.startsWith("https://video.fosdem.org") or href.startsWith("http://video.fosdem.org")) and
             (href.endsWith(".webm") or href.endsWith(".mp4")): inc video
          links.add @[year, eid, href, l.ownText.pyStrip]
        events.add @[year, eid, ev.attr("guid"), date, ev.t("start"), ev.t("duration"),
                     room.attr("name"), ev.t("slug"), ev.t("title"), ev.t("subtitle"),
                     (if tr == nil: "" else: tr.ownText.pyStrip), (if tr == nil: "" else: tr.attr("slug")),
                     ev.t("type"), ev.t("language"), $ev.t("abstract").chars, $ev.t("description").chars,
                     $video, $slides, $attachments, $nlinks]
        for i, p in ev.path("persons", "person"):
          eperson.add @[year, eid, p.attr("id"), p.ownText.pyStrip, $(i + 1)]

writeCsv(stage, "conference.csv", ["year", "title", "subtitle", "venue", "city", "start", "end", "days"], conf)
writeCsv(stage, "xml_tracks.csv", ["year", "track_slug", "track", "online_qa"], tracks)
writeCsv(stage, "xml_events.csv", ["year", "event_id", "guid", "date", "start", "duration", "room", "slug",
                                   "title", "subtitle", "track", "track_slug", "type", "language",
                                   "abstract_chars", "description_chars", "videos", "slides",
                                   "attachments", "links"], events)
writeCsv(stage, "xml_event_persons.csv", ["year", "event_id", "person_id", "name", "position"], eperson)
writeCsv(stage, "xml_links.csv", ["year", "event_id", "href", "text"], links)
echo conf.len, " editions, ", events.len, " events, ", eperson.len, " speaker slots"
src/extract_eventindex.nim 71 lines
## Parse the "event index" pages of FOSDEM 2007-2011 (archive.fosdem.org/<year>/schedule/events.html).
##
## Usage: extract_eventindex <pages dir> <stage dir>
## Writes html_events.csv and html_event_persons.csv in the same shape as the XML staging files.

import std/tables
import common

let src = paramStr(1)
let stage = paramStr(2)
let days = {"Sat": "Saturday", "Sun": "Sunday", "Fri": "Friday"}.toTable

let row = rx"(?s)<tr[^>]*>.*?</tr>"
let titleRe = rx"""(?s)<p class="(?:event-)?title">\s*<a href="events?/([^"]+)\.html">(.*?)</a>"""
let startRe = rx"""start-time">\s*(\d\d?:\d\d)"""
let endRe = rx"""end-time">\s*(\d\d?:\d\d)"""
let subRe = rx"""(?s)<p class="subtitle">(.*?)</p>"""
let speakersRe = rx"""(?s)<td class="speakers">(.*?)</td>"""
let anchor = rx"(?s)<a [^>]*>(.*?)</a>"
let roomRe = rx"""(?s)<td class="event room">(.*?)</td>"""
let whenRe = rx"""(?s)(?:event-timespec|event day start-time)">(.*?)</td>"""
let spanRe = rx"(\w+)\s+(\d\d?:\d\d)\s*→\s*(\d\d?:\d\d)"
let dayRe = rx"""(?s)event day">(.*?)</td>"""
let mediaRe = rx"""(?s)<td class="event-media">(.*?)</td>"""
let videoRe = rx"""href="(https?://video\.fosdem\.org[^"]*)""""

var events, persons: seq[seq[string]]
var years: seq[int]
for y in 2007 .. 2011:
  let fn = src / "events" & $y & ".html"
  if not fileExists(fn): continue
  let s = readText(fn)
  var track = ""
  for tr in s.findall(row):
    if "track-title" in tr:
      track = text(tr)
      continue
    let m = tr.search(titleRe)
    if not m.ok: continue
    let st = tr.search(startRe)
    let en = tr.search(endRe)
    let slug = m.group(1)
    let title = text(m.group(2))
    let sub = tr.search(subRe)
    let sp = tr.search(speakersRe)
    let names = if sp.ok: sp.group(1).findall(anchor, 1).mapIt(text(it)) else: @[]
    let room = tr.search(roomRe)
    let whenM = tr.search(whenRe)
    let w = if whenM.ok: text(whenM.group(1)) else: ""
    let wm = w.match(spanRe)
    var day, start, stop = ""
    if wm.ok:
      day = days.getOrDefault(wm.group(1), wm.group(1)); start = wm.group(2); stop = wm.group(3)
    if not wm.ok and st.ok:
      let dd = tr.search(dayRe)
      day = days.getOrDefault(if dd.ok: text(dd.group(1)) else: "", "")
      start = st.group(1)
      stop = if en.ok: en.group(1) else: ""
    let media = tr.search(mediaRe)
    let hrefs = if media.ok: media.group(1).findall(videoRe, 1) else: @[]
    let eid = $y & "-" & slug
    events.add @[$y, eid, day, start, stop, (if room.ok: text(room.group(1)) else: ""), slug, title,
                 (if sub.ok: text(sub.group(1)) else: ""), track, $hrefs.len, (if hrefs.len > 0: hrefs[0] else: "")]
    years.add y
    for i, n in names:
      persons.add @[$y, eid, n, $(i + 1)]

writeCsv(stage, "html_events.csv", ["year", "event_id", "day", "start", "end", "room", "slug", "title",
                                    "subtitle", "track", "videos", "video"], events)
writeCsv(stage, "html_event_persons.csv", ["year", "event_id", "name", "position"], persons)
echo counts(years)
src/extract_devrooms.nim 70 lines
## Parse FOSDEM 2007-2010 devroom pages (schedule/devroom(s)/<x>.html) and the devroom index pages.
##
## Usage: extract_devrooms <pages dir> <stage dir>
## Writes html_devroom_events.csv (one row per talk) and html_devrooms.csv (devroom, rooms, capacity).

import std/[tables, algorithm]
import common

let src = paramStr(1)
let stage = paramStr(2)
let days = {"Sat": "Saturday", "Sun": "Sunday", "Fri": "Friday"}.toTable

var rows, persons, rooms: seq[seq[string]]
var years: seq[int]
var files: seq[string]
for kind, f in walkDir(src / "devrooms", relative = true): files.add f
files.sort
for fn in files:
  let y = parseInt(fn[0 ..< 4])
  let key = fn.sl(5, -5)
  let s = readText(src / "devrooms" / fn)
  var h1 = s.search(rx"""(?s)<h1[^>]*class="title"[^>]*>(.*?)</h1>""")
  if not h1.ok: h1 = s.search(rx"(?s)<h1[^>]*>(.*?)</h1>")
  var name = if h1.ok: text(h1.group(1)) else: key
  let room = s.search(rx"Room:\s*(?:<[^>]+>\s*)*([^<]+)")
  let bc = s.findall(rx"""<a href="\.\./devrooms?/[^"]+\.html">([^<]+)</a>""", 1)
  if bc.len > 0: name = bc[^1].pyStrip
  let tbl = s.search(rx"""(?s)<table class="track-index">(.*?)</table>""")
  if not tbl.ok: continue
  for tr in tbl.group(1).resplit(rx"<tr[ >]")[1 .. ^1]:
    let whenM = tr.replace("&nbsp;", " ").search(rx"(Sat|Sun|Fri)\s*(?:</a>)?\s*(?:&nbsp;)?\s*(\d\d?:\d\d)\s*-\s*(\d\d?:\d\d)")
    let ev = tr.search(rx"""(?s)<td class="event">\s*<a href="\.\./events/([^"]+)\.html">(.*?)</a>""")
    var slug, title: string
    if not ev.ok:
      let ev2 = tr.search(rx"""(?s)<td class="event">(.*?)</td>""")
      if not ev2.ok or text(ev2.group(1)).len == 0: continue
      slug = ""; title = text(ev2.group(1))
    else:
      slug = ev.group(1); title = text(ev.group(2))
    let sp = tr.search(rx"""(?s)<td class="speaker[^"]*">(.*?)</td>""")
    var names = if sp.ok: sp.group(1).findall(rx"(?s)<a [^>]*>(.*?)</a>", 1).mapIt(text(it)) else: @[]
    if sp.ok and names.len == 0 and text(sp.group(1)).len > 0:
      names = text(sp.group(1)).resplit(rx",| and ").mapIt(it.pyStrip).filterIt(it.len > 0)
    let eid = $y & "-" & (if slug.len > 0: slug else: key & "-" & $rows.len)
    rows.add @[$y, eid, key, name, (if whenM.ok: days.getOrDefault(whenM.group(1), "") else: ""),
               whenM.group(2), whenM.group(3), (if room.ok: text(room.group(1)) else: ""), slug, title]
    years.add y
    for i, n in names:
      persons.add @[$y, eid, n, $(i + 1)]

for y in 2007 .. 2010:
  let fn = src / "devrooms" & $y & ".html"
  if not fileExists(fn): continue
  var s = readText(fn)
  s = s.sl(s.pyFind("<thead>", s.pyFind("Developer Rooms")))
  s = s.sl(0, s.pyFind("</table>"))
  for m in s.finditer(rx"""(?s)href="devrooms?/([^"]+)\.html">([^<]+)</a>(.*?)(?=href="devrooms?/|$)"""):
    var rs = m.group(3).findall(rx"(?s)<a [^>]*rooms/[^>]*>(.*?)</a>", 1).mapIt(text(it))
    var caps = rs.join(" ").findall(rx"\((\d+)\)", 1)
    if caps.len == 0:  # 2008 layout: separate room and capacity cells
      let tds = m.group(3).findall(rx"(?s)<td[^>]*>(.*?)</td>", 1).mapIt(text(it))
      rs = tds.filterIt(it.len > 0 and not it.fullmatch(rx"\d+"))
      caps = tds.filterIt(it.fullmatch(rx"\d+"))
    rooms.add @[$y, m.group(1), text(m.group(2)), rs.mapIt(it.sub(rx"\s*\(\d+\)", "")).join("; "), caps.join("; ")]

writeCsv(stage, "html_devroom_events.csv", ["year", "event_id", "devroom_key", "devroom_page_title", "day",
                                            "start", "end", "room", "slug", "title"], rows)
writeCsv(stage, "html_devroom_persons.csv", ["year", "event_id", "name", "position"], persons)
writeCsv(stage, "html_devrooms.csv", ["year", "devroom_key", "devroom", "rooms", "capacity"], rooms)
echo counts(years), rooms.len, " devroom index rows"
src/extract_early.nim 106 lines
## Parse the main schedule grids of FOSDEM 2001-2006 (OSDEM 2001, FOSDEM 2002-2006).
##
## Usage: extract_early <raw/archive/html dir> <stage dir>
## Writes early_events.csv: year, day, start, end, room, cell (as printed), title, speakers.
## Each year printed its grid a bit differently, so the split of a cell into title and
## speakers follows the year's convention (see `split`). Cells that span all rooms are
## plenary talks in the first room.

import std/[algorithm, sets]
import common, grid

let root = paramStr(1)
let stage = paramStr(2)
const files = [(2001, "2001/program/index.html"), (2002, "2002/schedule/index.html"),
               (2003, "2003/index/schedule.html"), (2004, "2004/2004/index/schedule.html"),
               (2005, "2005/2005/index/schedule.html"), (2006, "2006/2006/index/schedule.html")]
let time = rx"^(\d\d?)[:h](\d\d)\s*(?:-|->|→)\s*(\d\d?)[:h](\d\d)"
let skip = rx"(?i)^(-|/|lunch.*|party|)$"
let devroom = rx"(?i)developers?'? ?room"

proc hhmm(h, m: string): string = align($parseInt(h), 2, '0') & ":" & m

proc split(year: int, cell: string): (string, string, string) =
  ## (title, speakers, room) for a schedule cell.
  var c = cell
  var room = ""
  let j = c.search(rx"\((Jan?s?son)\)")
  if j.ok:
    room = "Janson"; c = (c[0 ..< j.start] & c[j.stop .. ^1]).strip(chars = {' ', '/'})
  if year == 2001:
    let m = c.match(rx"(.+?):\s*(.+)")
    if m.ok and m.group(1).pySplit.len <= 3 and not c.search(rx"(?i)round table|strategies").ok:
      return (m.group(2).pyStrip, m.group(1).pyStrip, room)
    let b = c.match(rx"(.+?) by (.+)")
    if b.ok: return (b.group(1).pyStrip, b.group(2).pyStrip, room)
    return (c, "", room)
  if year == 2002:
    let m = c.match(rx"(.+?):\s*(.+)")
    if m.ok:
      return (m.group(1).pyStrip, m.group(2).sub(rx"\s*[-(]\s*(USA|UK)\)?$", "").strip(chars = {' ', '.'}), room)
    return (c, "", room)
  let parts = c.split(" / ").mapIt(it.pyStrip).filterIt(it.len > 0)
  if parts.len >= 2: return (parts[0 ..< ^1].join(" "), parts[^1], room)
  (c, "", room)

proc normRoom(room: string): string =
  var r = room
  let m = r.search(rx"\((\w+?)(?: room)?$")
  if m.ok: r = m.group(1)
  r = r.sub(rx"\s*\(\d+\)|:\s*\d+ places", "").replace(" / ", " ").pyStrip
  if r == "Jansson": r = "Janson"
  r.capitalFirst

var rows: seq[seq[string]]
var devrooms: HashSet[(int, string, string)]
var years: seq[int]
for (year, fn) in files:
  for g in tables(root / fn):
    var header: seq[string]
    var hasHeader = false
    var day = ""
    for r in g:
      if r.len == 0: continue
      let first = r[0]
      let dm = r[0 ..< min(3, r.len)].join(" ").search(rx"(Saturday|Sunday)")
      if dm.ok and not first.match(time).ok:
        day = dm.group(1)
        if r[1 .. ^1].anyIt(it.search(rx"(?i)room|places|\(\d+\)|chavanne|janson|lameere").ok):
          header = r; hasHeader = true
        continue
      if not hasHeader and r[1 .. ^1].anyIt(it.search(rx"(?i)\(\d+\)|chavanne|lameere").ok):
        header = r; hasHeader = true
        continue
      let m = first.match(time)
      if not m.ok or day.len == 0: continue
      let start = hhmm(m.group(1), m.group(2))
      let stop = hhmm(m.group(3), m.group(4))
      let cells = r[1 .. ^1]
      let filled = cells.filterIt(not it.pyStrip.match(skip).ok)
      var seen: HashSet[string]
      for i, raw in cells:
        let cell = raw.pyStrip
        let inHeader = header.len > 0 and i + 1 < header.len
        if cell.search(devroom).ok and cell notin seen:
          devrooms.incl (year, cell.sub(rx"(?i)\s*developers?'? ?room", "").pyStrip,
                         (if inHeader: normRoom(header[i + 1]) else: ""))
        if cell.match(skip).ok or cell.search(devroom).ok or cell in seen: continue
        seen.incl cell
        let plenary = filled.len > 1 and filled.allIt(it == cell)
        var room = if inHeader: header[i + 1] else: ""
        var (title, speakers, room2) = split(year, cell)
        if plenary or room2.len > 0:
          room = if room2.len > 0: room2 elif header.len > 0: header[1] else: ""
        room = normRoom(room)
        if year == 2006 and title.startsWith("Welcome of visitors"):
          (title, speakers) = ("Welcome of visitors followed by Richard M Stallman's keynote", "Richard M Stallman")
        if title.startsWith("FOSDEM Return Operation"):
          (title, speakers) = (cell.replace(" / ", " "), "")
        rows.add @[$year, day, start, stop, room, cell, title, speakers]
        years.add year

var dr = toSeq(devrooms)
dr.sort
writeCsv(stage, "early_events.csv", ["year", "day", "start", "end", "room", "cell", "title", "speakers"], rows)
writeCsv(stage, "early_grid_devrooms.csv", ["year", "devroom", "room"], dr.mapIt(@[$it[0], it[1], it[2]]))
echo dr.len, " devrooms in the grids; ", counts(years)
src/extract_early_devrooms.nim 79 lines
## Parse FOSDEM 2003-2006 devroom pages: the devroom list and each devroom's schedule page.
##
## Usage: extract_early_devrooms <raw/archive/html dir> <stage dir>
## Writes early_devrooms.csv (year, key, devroom) and early_devroom_events.csv
## (year, key, day, start, end, title, speakers). The pages are free-form, so this is a
## best effort: two layouts are recognised (time before the title, or time before the speaker).

import std/[algorithm, unicode]
import common, grid

let root = paramStr(1)
let stage = paramStr(2)
const T = r"(\d\d?)[.:h](\d\d)"
var devrooms, events: seq[seq[string]]
var dyears, eyears: seq[int]

proc hhmm(h, m: string): string = align($parseInt(h), 2, '0') & ":" & m

proc heading(path: string): string =
  let s = readText(path).sub(rx"<[^>]+>", "|")
  let m = s.search(rx"\|\s*(?:Welcome to the )?([^|]{2,60}?) [Dd]evelopers?'?s?'? ?room")
  if m.ok: m.group(1).sub(spaces, " ").pyStrip else: ""

proc looksLikeName(s: string): bool =
  let w = s.pySplit
  w.len in 1..6 and not (s.endsWith(".") or s.endsWith("!") or s.endsWith("?") or s.endsWith(":")) and
    s.len > 0 and s.runeAt(0).isUpper

for y in 2003 .. 2006:
  let base = if y > 2003: root / $y / $y / "index" else: root / "2003" / "index"
  var pages: seq[string]
  for kind, f in walkDir(base):
    if f.extractFilename.startsWith("dev_room_") and f.endsWith(".html"): pages.add f
  pages.sort
  if y == 2003:
    let s = readText(base / "dev_room.html").sub(rx"<[^>]+>", " ")
    var seen: seq[string]
    for n in s.findall(rx"([A-Z][\w.+/ -]{1,40}?) (?:developers|softwares) room", 1):
      let name = n.pyStrip
      if name notin seen:
        seen.add name
        devrooms.add @[$y, unicode.toLower(name).replace(" ", ""), name]; dyears.add y
    continue
  for p in pages:
    let key = p.extractFilename.sl("dev_room_".len, -5)
    let h = heading(p)
    devrooms.add @[$y, key, (if h.len > 0: h else: key)]; dyears.add y
    let sched = base / "dev_room_" & key / "schedule.html"
    if not fileExists(sched): continue
    var day = ""
    for g in tables(sched):
      for row in g:
        let r = row.filterIt(it.pyStrip.len > 0)
        if r.len < 2: continue
        let dm = r[0].search(rx"(Saturday|Sunday|Friday)")
        if dm.ok and r[0] == r[1]:
          day = dm.group(1); continue
        if day.len == 0: continue
        let (a, b) = (r[0], r[1])
        let m = a.match(rx(T & r"(?:\s*(?:-+>?|–|→|\x{FFFD}|to)\s*" & T & r")?[\s:/.-]*(.*)"))
        if m.ok:
          let start = hhmm(m.group(1), m.group(2))
          let stop = if m.group(3).len > 0: hhmm(m.group(3), m.group(4)) else: ""
          var title = m.group(5).pyStrip
          var parts = b.split(" / ").mapIt(it.pyStrip)
          if title.len == 0:
            title = parts[0]
            parts = if parts.len > 1: parts[1 .. ^1] else: @[]
          let spk = if parts.len > 0 and looksLikeName(parts[^1]) and parts[^1] != title: parts[^1] else: ""
          events.add @[$y, key, day, start, stop, title, spk]; eyears.add y
          continue
        let n = b.match(rx(T & r"\s*\S*\s*" & T & r"\s*(?:/\s*(.*))?"))
        if n.ok:
          events.add @[$y, key, day, hhmm(n.group(1), n.group(2)), hhmm(n.group(3), n.group(4)),
                       a.pyStrip, n.group(5).pyStrip]; eyears.add y

writeCsv(stage, "early_devrooms.csv", ["year", "devroom_key", "devroom"], devrooms)
writeCsv(stage, "early_devroom_events.csv", ["year", "devroom_key", "day", "start", "end", "title", "speakers"], events)
echo counts(dyears), "| ", counts(eyears)
src/extract_trackpages.nim 54 lines
## Parse FOSDEM track pages (archive.fosdem.org/<year>/schedule/track/<slug>/), 2013-2026.
##
## Usage: extract_trackpages <raw/archive/tracks dir> <stage dir>
## Writes track_pages.csv: year, track_slug, track, group (the breadcrumb level above the
## track, such as "Developer rooms", when the site shows one), rooms, CfP link.

import std/[tables, algorithm]
import common

let src = paramStr(1)
let stage = paramStr(2)

proc listdir(d: string): seq[string] =
  for kind, f in walkDir(d, relative = true): result.add f
  result.sort

proc unique(xs: seq[string]): seq[string] =
  for x in xs:
    if x notin result: result.add x

var rows: seq[seq[string]]
var years: seq[int]
var withCfp = 0
for y in listdir(src):
  let d = src / y
  if not y.fullmatch(rx"\d+") or not dirExists(d): continue
  let idx = d / "index.html"
  var groups: Table[string, string]
  if fileExists(idx):  # the tracks index groups tracks under headings (Main tracks, Developer rooms, ...)
    let s = readText(idx)
    var heading = ""
    for m in s.finditer(rx("(?s)<h[34][^>]*>(.*?)</h[34]>|href=\"/" & y & "/schedule/track/([^/\"]+)/\"")):
      if m.has(1): heading = text(m.group(1))
      elif m.group(2).len > 0: discard groups.hasKeyOrPut(m.group(2), heading)
  for fn in listdir(d):
    if fn == "index.html": continue
    let slug = fn.sl(0, -5)
    let s = readText(d / fn)
    let h1 = s.search(rx"""(?s)<div id="pagetitles">\s*<h1>(.*?)</h1>""")
    let bstart = s.pyFind("""class="breadcrumbs"""")
    let crumbs = s.sl(bstart, s.pyFind("</ul>", bstart)).findall(rx"""(?s)<li(?: class="active")?>(.*?)</li>""", 1)
                  .mapIt(text(it)).filterIt(it.len > 0 and it != "/")
    let group = if crumbs.len >= 5: crumbs[^2] else: groups.getOrDefault(slug, "")
    let side = s.search(rx"""(?s)<p class="side-box">(.*?)</p>""")
    let rooms = if side.ok: side.group(1).findall(rx"""/schedule/room/[^"]+/">([^<]+)</a>""", 1) else: @[]
    let box = s.search(rx"""(?s)class="[^"]*track-cfp[^"]*">(.*?)</div>""")
    let cfp = if box.ok: box.group(1).search(rx"""href="([^"]+)"|(https?://[^\s<]+)""") else: Match()
    let link = if cfp.ok: (if cfp.group(1).len > 0: cfp.group(1) else: cfp.group(2)) else: ""
    rows.add @[$parseInt(y), slug, (if h1.ok: text(h1.group(1)) else: slug), group, rooms.unique.join("; "), link]
    years.add parseInt(y)
    if link.len > 0: inc withCfp

writeCsv(stage, "track_pages.csv", ["year", "track_slug", "track", "group", "rooms", "cfp_link"], rows)
echo counts(years), withCfp, " with CfP link"
src/extract_cfp_yaml.nim 86 lines
## Read every version of content/devrooms-cfp.yaml in FOSDEM's archived website repo
## (github.com/FOSDEM/website, 2012-2019 CfP seasons, so editions 2013-2020).
##
## Usage: extract_cfp_yaml <website git clone> <stage dir>
## For each edition (a commit from August on belongs to the next year's edition), keeps the
## last version of the file and writes one row per devroom: edition, day, devroom,
## announcement URL, deadline, and the date the devroom first appeared in the file.

import std/[osproc, tables, algorithm, unicode]
import common

type Row = object
  day, devroom, ann, deadline: string

let repo = paramStr(1)
let stage = paramStr(2)
const path = "content/devrooms-cfp.yaml"

proc git(args: varargs[string]): string =
  execProcess("git", args = @["-C", repo] & @args, options = {poUsePath}).replace("\r\n", "\n").replace("\r", "\n")

proc trimQuotes(s: string): string = s.strip(chars = {'\'', '"', ' '})

proc parse(text: string): seq[Row] =
  var day = ""
  var cur = -1
  if "\ndeadlines:" in text:  # 2012 layout: devroom -> ann (short ids), deadline, days
    for line in text.splitLines:
      let m = line.match(rx"""^  (?! )['"]?(.+?)['"]?:\s*$""")
      if m.ok:
        result.add Row(devroom: m.group(1).pyStrip); cur = result.high; continue
      let kv = line.match(rx"^\s+(ann|deadline|days):\s*(.*?)\s*$")
      let n = line.match(rx"^\s+-\s*(\S+)")
      if cur < 0: continue
      if kv.ok:
        let v = kv.group(2).trimQuotes
        case kv.group(1)
        of "days": result[cur].day = v
        of "ann": result[cur].ann = v
        else: result[cur].deadline = v
      elif n.ok and result[cur].ann.len == 0:
        result[cur].ann = n.group(1)
    for r in result.mitems:
      if r.ann.match(rx"^\d{4}-\w+/\d+$").ok:
        r.ann = "https://lists.fosdem.org/pipermail/fosdem/" & r.ann & ".html"
    return
  for line in text.splitLines:
    let d = line.match(rx"^  (\w+):\s*$")
    if d.ok and d.group(1) in ["both", "saturday", "sunday"]:
      day = d.group(1); continue
    let m = line.match(rx"""^    (?! )['"]?(.+?)['"]?:\s*$""")
    if m.ok and day.len > 0 and m.group(1) notin ["ann", "deadline"]:  # some versions lost an indent
      result.add Row(day: day, devroom: m.group(1).pyStrip); cur = result.high; continue
    let kv = line.match(rx"^\s+(ann|deadline):\s*(.*?)\s*$")
    if kv.ok and cur >= 0:
      if kv.group(1) == "ann": result[cur].ann = kv.group(2).trimQuotes
      else: result[cur].deadline = kv.group(2).trimQuotes

var editions: Table[int, (string, string, seq[Row])]
var firstSeen: Table[(int, string), string]
for line in git("log", "--reverse", "--format=%H %ad", "--date=short", "--", path).split("\n"):
  if line.pyStrip.len == 0: continue
  let parts = line.pySplit
  let (sha, date) = (parts[0], parts[1])
  let y = parseInt(date[0 ..< 4])
  let mo = parseInt(date[5 ..< 7])
  let ed = if mo >= 8: y + 1 else: y
  let rows = parse(git("show", sha & ":" & path))
  for r in rows:
    discard firstSeen.hasKeyOrPut((ed, unicode.toLower(r.devroom)), date)
  if rows.len > 0:
    editions[ed] = (sha, date, rows)

var table: seq[seq[string]]
var eds = toSeq(editions.keys)
eds.sort
var summary: seq[string]
for ed in eds:
  let (sha, date, rows) = editions[ed]
  summary.add $ed & ": " & $rows.len
  for r in rows:
    table.add @[$ed, r.day, r.devroom, r.ann, r.deadline, firstSeen[(ed, unicode.toLower(r.devroom))],
              date & " " & sha[0 ..< 7]]
writeCsv(stage, "cfp_yaml.csv", ["edition", "day", "devroom", "announcement", "deadline", "first_listed",
                                 "last_commit"], table)
echo summary.join(", ")
src/extract_lists.nim 598 lines
## Flatten the fosdem@lists.fosdem.org archive (mbox export, 2006-) into a staging CSV.
##
## Usage: extract_lists <fosdem.mbox> <stage dir>
## Keeps sender *names* only (no e-mail addresses) and no message bodies, apart from
## a few fields read from them: the FOSDEM year they mention and the first pretalx /
## CfP link. Cleaning and classification happen in nanuq (process.nim).
##
## It reads mail as Python's email package does (the compat32 policy, with which this
## table was first made): the same headers, the same text part, the same sender name.

import std/[algorithm, base64, encodings, unicode, sets, tables]
import common

let src = paramStr(1)
let stage = paramStr(2)

# --------------------------------------------------------------------------- the mbox

proc messages(mbox: string): seq[string] =
  ## Each message without its "From " line; the blank line before the next one is not part of it.
  var starts, stops: seq[int]
  var lastEmpty = false
  var pos = 0
  while true:
    if pos >= mbox.len:
      stops.add(if lastEmpty: pos - 1 else: pos)
      break
    let nl = mbox.find('\n', pos)
    let next = if nl < 0: mbox.len else: nl + 1
    if mbox.continuesWith("From ", pos):
      if stops.len < starts.len: stops.add(if lastEmpty: pos - 1 else: pos)
      starts.add pos
      lastEmpty = false
    elif next - pos == 1 and mbox[pos] == '\n': lastEmpty = true
    else: lastEmpty = false
    pos = next
  for i, a in starts:
    let nl = mbox.find('\n', a)
    let body = if nl < 0: mbox.len else: nl + 1
    result.add mbox[min(body, stops[i]) ..< stops[i]]

# ------------------------------------------------------------------------------ a message

type Part = ref object
  headers: seq[(string, string)]   # name, raw value (continuation lines kept)
  body: string                     # bytes; for a multipart, its parts instead
  parts: seq[Part]
  multipart: bool
  default: string                  # the content type when the part has none

proc toAscii(s: string): string =
  ## For matching a line of raw bytes: every 8-bit byte becomes \x01, which no pattern here takes.
  result = s
  for c in result.mitems:
    if c.ord >= 128: c = '\x01'

proc sl2(xs: seq[string]): seq[string] =
  ## Drop the empty last piece that a final line break leaves (as str.splitlines does).
  result = xs
  if result.len > 0 and result[^1].len == 0: discard result.pop

proc lines(s: string): seq[string] =
  ## Lines with their endings (\r\n, \r or \n), as the email parser splits them.
  var a = 0
  var i = 0
  while i < s.len:
    if s[i] == '\n':
      result.add s[a .. i]; a = i + 1
    elif s[i] == '\r':
      if i + 1 < s.len and s[i + 1] == '\n': inc i
      result.add s[a .. i]; a = i + 1
    inc i
  if a < s.len: result.add s[a .. ^1]

proc get(p: Part, name: string): (bool, string) =
  for (k, v) in p.headers:
    if cmpIgnoreCase(k, name) == 0: return (true, v)

proc params(value: string): seq[(string, string)] =
  ## Python's _parseparam and decode_params: the parameters of a header, values unquoted.
  var s = ";" & value
  var plist: seq[string]
  while s.len > 0 and s[0] == ';':
    s = s[1 .. ^1]
    var stop = s.find(';')
    while stop > 0 and (s[0 ..< stop].count('"') - s[0 ..< stop].count("\\\"")) mod 2 == 1:
      stop = s.find(';', stop + 1)
    if stop < 0: stop = s.len
    var f = s[0 ..< stop]
    let i = f.find('=')
    if i >= 0: f = f[0 ..< i].pyStrip.toLowerAscii & "=" & f[i + 1 .. ^1].pyStrip
    plist.add f.pyStrip
    s = s[stop .. ^1]
  for p in plist:
    let i = p.find('=')
    var (k, v) = if i < 0: (p.pyStrip, "") else: (p[0 ..< i].pyStrip, p[i + 1 .. ^1].pyStrip)
    if v.len > 1 and v[0] == '"' and v[^1] == '"':
      v = v[1 ..< ^1].replace("\\\\", "\\").replace("\\\"", "\"")
    result.add (k, v)

proc param(p: Part, name: string): (bool, string) =
  let (has, v) = p.get("content-type")
  if not has: return
  for (k, x) in params(v)[1 .. ^1]:
    if cmpIgnoreCase(k, name) == 0: return (true, x)

proc contentType(p: Part): string =
  let (has, v) = p.get("content-type")
  if not has: return p.default
  let t = v.split(';')[0].pyStrip.toLowerAscii
  if t.count('/') != 1: "text/plain" else: t

let headerLine = rx"^(From |[\x21-\x39\x3B-\x7E]*:|[\t ])"

proc parsePart(data: seq[string], default = "text/plain"): Part =
  result = Part(default: default)
  var i = 0
  var hs: seq[seq[string]]
  while i < data.len:
    let line = data[i]
    if not line.toAscii.search(headerLine).ok:
      if line in ["\n", "\r\n", "\r"]: inc i
      break
    if line[0] in {' ', '\t'}:
      if hs.len > 0: hs[^1].add line
    elif not (i == 0 and line.startsWith("From ")):
      hs.add @[line]
    inc i
  for h in hs:
    let c = h[0].find(':')
    if c <= 0: continue
    let value = (h[0][c + 1 .. ^1].strip(trailing = false, chars = {' ', '\t'}) & h[1 .. ^1].join).strip(leading = false, chars = {'\r', '\n'})
    result.headers.add (h[0][0 ..< c], value)
  let ctype = result.contentType
  let body = data[i .. ^1]
  if ctype.startsWith("multipart/"):
    let (has, b) = result.param("boundary")
    if has:
      let sep = rx("^" & rxEscape("--" & b.pyStrip) & r"(--)?[ \t]*(\r\n|\r|\n)?$")
      var cur: seq[string]
      var inPart = false
      var closed = false
      for line in body:
        let m = line.toAscii.search(sep)
        if m.ok:
          if inPart:
            if cur.len > 0: cur[^1] = cur[^1].strip(leading = false, chars = {'\r', '\n'})
            result.parts.add parsePart(cur, if ctype == "multipart/digest": "message/rfc822" else: "text/plain")
          cur = @[]
          inPart = true
          if m.has(1): closed = true; break
        elif inPart: cur.add line
      if inPart and not closed:
        result.parts.add parsePart(cur, if ctype == "multipart/digest": "message/rfc822" else: "text/plain")
      result.multipart = inPart
      if inPart: return
  elif ctype.startsWith("message/") and ctype != "message/delivery-status":
    result.parts.add parsePart(body)
    result.multipart = true
    return
  result.body = body.join

iterator walk(p: Part): Part =
  var stack = @[p]
  while stack.len > 0:
    let x = stack.pop
    yield x
    for i in countdown(x.parts.high, 0): stack.add x.parts[i]

# ------------------------------------------------------------------------------ decoding

proc qpDecode(s: string, header = false): string =
  ## binascii.a2b_qp.
  var i = 0
  while i < s.len:
    if s[i] == '=':
      inc i
      if i >= s.len: break
      if s[i] in {'\n', '\r'}:
        if s[i] != '\n':
          while i < s.len and s[i] != '\n': inc i
        if i < s.len: inc i
      elif s[i] == '=':
        result.add '='; inc i
      elif i + 1 < s.len and s[i] in HexDigits and s[i + 1] in HexDigits:
        result.add chr(parseHexInt(s[i .. i + 1])); i += 2
      else: result.add '='
    elif header and s[i] == '_':
      result.add ' '; inc i
    else:
      result.add s[i]; inc i

proc b64(s: string): (bool, string) =
  ## binascii.a2b_base64 (not strict): other characters skipped, stops at the padding.
  const alphabet = {'A'..'Z', 'a'..'z', '0'..'9', '+', '/'}
  var clean = ""
  var pads = 0
  for c in s:
    if c in alphabet:
      if pads > 0: break
      clean.add c
    elif c == '=':
      if clean.len mod 4 >= 2:
        inc pads
        if clean.len mod 4 + pads >= 4: break
  let r = clean.len mod 4
  if r == 1: return (false, "")
  if r != 0 and clean.len mod 4 + pads < 4: return (false, "")
  (true, base64.decode(clean & "=".repeat((4 - r) mod 4)))

proc decodeB(s: string): string =
  ## email._encoded_words.decode_b, as get_payload(decode=True) uses it.
  let (ok, v) = b64(s)
  if ok: return v
  let (ok2, v2) = b64(s & "==")
  if ok2: v2 else: s

proc latin1(s: string): string =
  for c in s: result.add $Rune(c.ord)

proc decodeAs(s, charset: string): (bool, string) =
  ## bytes.decode(charset, "replace"); false when Python does not know the charset.
  let cs = charset.toLowerAscii.replace("_", "-")
  case cs
  of "utf-8", "utf8", "u8", "utf", "utf-8-sig": (true, s.utf8Replace)
  of "us-ascii", "ascii", "646", "us":
    var r = ""
    for c in s: r.add(if c.ord < 128: $c else: "�")
    (true, r)
  of "iso-8859-1", "iso8859-1", "latin-1", "latin1", "l1", "8859", "cp819", "iso-ir-100", "latin":
    (true, latin1(s))
  of "windows-1252", "cp1252": (true, s.fromCp1252)
  else:
    try: (true, convert(s, "UTF-8", cs).utf8Replace)
    except CatchableError: (false, "")

proc rawUnicodeEscape(s: string): string =
  ## str.encode("raw-unicode-escape"): characters under 256 as one byte each.
  for r in s.runes:
    if r.int < 0x100: result.add chr(r.int)
    elif r.int < 0x10000: result.add "\\u" & toHex(r.int, 4).toLowerAscii
    else: result.add "\\U" & toHex(r.int, 8).toLowerAscii

proc isSpaceStr(s: string): bool = s.len > 0 and s.pyStrip.len == 0

proc lstrip(s: string): string =
  var i = 0
  for r in s.runes:
    if not (r.isWhiteSpace or r.int in 0x1C..0x1F): break
    i += r.size
  s[i .. ^1]

proc splitLinesPy(s: string): seq[string] =
  ## str.splitlines().
  s.resplit(rx"\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x{85}\x{2028}\x{2029}]").sl2()

let ecre = rx"""=\?([^?]*?)\?([qQbB])\?(.*?)\?="""

proc qWord(w: string): string =
  ## email.quoprimime.header_decode, then raw-unicode-escape.
  let s = w.replace("_", " ")
  var r = ""
  var i = 0
  while i < s.len:
    if s[i] == '=' and i + 2 < s.len and s[i + 1] in HexDigits and s[i + 2] in HexDigits:
      r.add $Rune(parseHexInt(s[i + 1 .. i + 2])); i += 3
    else:
      r.add s[i]; inc i
  r.rawUnicodeEscape

proc decodeHeader(v: string): (bool, string) =
  ## email.header.decode_header, then each part decoded with its charset (utf-8 when it has none).
  if not v.search(ecre).ok: return (true, v)
  var words: seq[(string, string, string)]   # text, encoding ("" when not encoded), charset
  for line in v.splitLinesPy:
    var at = 0
    var first = true
    for m in line.finditer(ecre):
      var plain = line[at ..< m.start]
      if first: plain = plain.lstrip; first = false
      if plain.len > 0: words.add (plain, "", "")
      words.add (m.group(3), m.group(2).toLowerAscii, unicode.toLower(m.group(1)))
      at = m.stop
    var plain = line[at .. ^1]
    if first: plain = plain.lstrip
    if plain.len > 0: words.add (plain, "", "")
  var drop: seq[int]
  for n, w in words:
    if n > 1 and w[1].len > 0 and words[n - 2][1].len > 0 and words[n - 1][0].isSpaceStr:
      drop.add n - 1
  for d in drop.reversed: words.delete(d)
  var collapsed: seq[(string, string)]
  var have = false
  var lastWord, lastCs: string
  for (w, enc, cs) in words:
    var bytes: string
    case enc
    of "": bytes = w.rawUnicodeEscape
    of "q": bytes = qWord(w)
    else:
      var e = w
      if e.len mod 4 != 0: e.add "===".sl(0, 4 - e.len mod 4)
      let (ok, b) = b64(e.rawUnicodeEscape)
      if not ok: return (false, "")
      bytes = b
    if not have:
      lastWord = bytes; lastCs = cs; have = true
    elif cs != lastCs:
      collapsed.add (lastWord, lastCs); lastWord = bytes; lastCs = cs
    elif lastCs.len == 0: lastWord.add " " & bytes
    else: lastWord.add bytes
  collapsed.add (lastWord, lastCs)
  var s = ""
  for (b, cs) in collapsed:
    let (ok, t) = decodeAs(b, if cs.len > 0: cs else: "utf-8")
    if not ok: return (false, "")
    s.add t
  (true, s)

proc unknown8bit(raw: string): string =
  ## A header's 8-bit bytes become one U+FFFD each (a Header with the unknown-8bit charset).
  for c in raw: result.add(if c.ord < 128: $c else: "�")

proc dec(h: (bool, string)): string =
  ## The scripts' `dec`: a header decoded (RFC 2047), its whitespace collapsed.
  if not h[0]: return ""
  let v = unknown8bit(h[1])
  let (ok, s) = decodeHeader(v)
  (if ok: s else: v).sub(spaces, " ").pyStrip

# ---------------------------------------------------------------------- the sender's name

proc stripQuotedRealnames(a: string): string =
  if '"' notin a: return a
  var start = 0
  var open = -1
  var esc = false
  for pos, ch in a:
    if esc: esc = false; continue
    if ch == '\\': esc = true; continue
    if ch == '"':
      if open < 0: open = pos
      else:
        if start != open: result.add a[start ..< open]
        start = pos + 1; open = -1
  if start < a.len: result.add a[start .. ^1]

proc parenthesesOk(a: string): bool =
  var opens = 0
  var esc = false
  for ch in stripQuotedRealnames(a):
    if esc: esc = false; continue
    if ch == '\\': esc = true; continue
    if ch == '(': inc opens
    elif ch == ')':
      dec opens
      if opens < 0: return false
  opens == 0

type Addr = object
  f: string
  pos: int
  comments: seq[string]

const specials = "()<>@,:;.\"[]"
const lws = " \t"
const cr = "\r\n"
const atomends = specials & lws & cr
const phraseends = "()<>@,:;\"[]" & lws & cr

proc delimited(p: var Addr, begin: char, ends: string, comments: bool): string
proc comment(p: var Addr): string = p.delimited('(', ")\r", true)
proc delimited(p: var Addr, begin: char, ends: string, comments: bool): string =
  if p.f[p.pos] != begin: return ""
  var quote = false
  inc p.pos
  while p.pos < p.f.len:
    let c = p.f[p.pos]
    if quote: result.add c; quote = false
    elif c in ends: inc p.pos; break
    elif comments and c == '(': result.add p.comment; continue
    elif c == '\\': quote = true
    else: result.add c
    inc p.pos

proc gotonext(p: var Addr): string =
  while p.pos < p.f.len:
    let c = p.f[p.pos]
    if c in lws & "\n\r":
      if c notin "\n\r": result.add c
      inc p.pos
    elif c == '(': p.comments.add p.comment
    else: break

proc atom(p: var Addr, ends = atomends): string =
  while p.pos < p.f.len and p.f[p.pos] notin ends:
    result.add p.f[p.pos]; inc p.pos

proc phraselist(p: var Addr): seq[string] =
  while p.pos < p.f.len:
    let c = p.f[p.pos]
    if c in lws & cr: inc p.pos
    elif c == '"': result.add p.delimited('"', "\"\r", false)
    elif c == '(': p.comments.add p.comment
    elif c in phraseends: break
    else: result.add p.atom(phraseends)

proc domainLiteral(p: var Addr): string = "[" & p.delimited('[', "]\r", false) & "]"

proc domain(p: var Addr): string =
  while p.pos < p.f.len:
    let c = p.f[p.pos]
    if c in lws: inc p.pos
    elif c == '(': p.comments.add p.comment
    elif c == '[': result.add p.domainLiteral
    elif c == '.': inc p.pos; result.add '.'
    elif c == '@': return ""
    elif c in atomends: break
    else: result.add p.atom

proc addrspec(p: var Addr): string =
  var parts: seq[string]
  discard p.gotonext
  while p.pos < p.f.len:
    var keepWs = true
    let c = p.f[p.pos]
    if c == '.':
      if parts.len > 0 and parts[^1].strip.len == 0: discard parts.pop
      parts.add "."; inc p.pos; keepWs = false
    elif c == '"':
      parts.add "\"" & p.delimited('"', "\"\r", false).replace("\\", "\\\\").replace("\"", "\\\"") & "\""
    elif c in atomends:
      if parts.len > 0 and parts[^1].strip.len == 0: discard parts.pop
      break
    else: parts.add p.atom
    let ws = p.gotonext
    if keepWs and ws.len > 0: parts.add ws
  if p.pos >= p.f.len or p.f[p.pos] != '@': return parts.join
  inc p.pos
  discard p.gotonext
  let d = p.domain
  if d.len == 0: return ""
  parts.join & "@" & d

proc routeaddr(p: var Addr): string =
  if p.f[p.pos] != '<': return
  var route = false
  inc p.pos
  discard p.gotonext
  while p.pos < p.f.len:
    if route: discard p.domain; route = false
    elif p.f[p.pos] == '>': inc p.pos; break
    elif p.f[p.pos] == '@': inc p.pos; route = true
    elif p.f[p.pos] == ':': inc p.pos
    else:
      result = p.addrspec; inc p.pos; break
    discard p.gotonext

proc address(p: var Addr): seq[(string, string)] =
  p.comments = @[]
  discard p.gotonext
  let oldpos = p.pos
  let plist = p.phraselist
  discard p.gotonext
  if p.pos >= p.f.len:
    if plist.len > 0: result = @[(p.comments.join(" "), plist[0])]
  elif p.f[p.pos] in ".@":
    p.pos = oldpos
    let a = p.addrspec
    result = @[(p.comments.join(" "), a)]
  elif p.f[p.pos] == ':':
    inc p.pos
    while p.pos < p.f.len:
      discard p.gotonext
      if p.pos < p.f.len and p.f[p.pos] == ';':
        inc p.pos; break
      result.add p.address
  elif p.f[p.pos] == '<':
    let r = p.routeaddr
    if p.comments.len > 0: result = @[(plist.join(" ") & " (" & p.comments.join(" ") & ")", r)]
    else: result = @[(plist.join(" "), r)]
  else:
    if plist.len > 0: result = @[(p.comments.join(" "), plist[0])]
    elif p.f[p.pos] in specials: inc p.pos
  discard p.gotonext
  if p.pos < p.f.len and p.f[p.pos] == ',': inc p.pos

proc parseaddr(s: string): (string, string) =
  ## email.utils.parseaddr (strict, as in Python 3.13): ("", "") unless there is exactly one address.
  let a = if parenthesesOk(s): s else: "('', '')"
  var p = Addr(f: a)
  var list: seq[(string, string)]
  if a.len > 0:
    while p.pos < p.f.len:
      let ad = p.address
      if ad.len > 0: list.add ad else: list.add ("", "")
  for x in list.mitems:
    if '[' in x[1]: x = ("", "")
  if list.len != 1: ("", "") else: list[0]

# ---------------------------------------------------------------------------------- dates

const monthnames = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
                    "january", "february", "march", "april", "may", "june", "july", "august",
                    "september", "october", "november", "december"]
const daynames = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]

proc parseDate(h: (bool, string)): (bool, int, int, int) =
  ## email.utils.parsedate_to_datetime: year, month and day as the header writes them.
  if not h[0] or h[1].anyIt(it.ord >= 128): return
  var data = h[1].pySplit
  if data.len == 0: return
  if data[0].endsWith(",") or data[0].toLowerAscii in daynames: data.delete(0)
  else:
    let i = data[0].rfind(',')
    if i >= 0: data[0] = data[0][i + 1 .. ^1]
  if data.len == 3:
    let stuff = data[0].split('-')
    if stuff.len == 3: data = stuff & data[1 .. ^1]
  if data.len == 4:
    let s = data[3]
    var i = s.find('+')
    if i == -1: i = s.find('-')
    if i > 0: data = data[0 ..< 3] & @[s[0 ..< i], s[i .. ^1]]
    else: data.add ""
  if data.len < 5: return
  var (dd, mm, yy, tm) = (data[0], data[1], data[2], data[3])
  if dd.len == 0 or mm.len == 0 or yy.len == 0: return
  mm = mm.toLowerAscii
  if mm notin monthnames:
    (dd, mm) = (mm, dd.toLowerAscii)
    if mm notin monthnames: return
  var month = monthnames.find(mm) + 1
  if month > 12: month -= 12
  if dd[^1] == ',': dd = dd[0 ..< ^1]
  if yy.find(':') > 0: (yy, tm) = (tm, yy)
  if yy.len > 0 and yy[^1] == ',': yy = yy[0 ..< ^1]
  if yy.len == 0: return
  if not yy[0].isDigit: yy = data[4]
  if tm.len > 0 and tm[^1] == ',': tm = tm[0 ..< ^1]
  let t = tm.split(':')
  if t.len notin 2..3 and not (t.len == 1 and '.' in t[0]): return
  var y, d: int
  try:
    y = parseInt(yy); d = parseInt(dd)
    let fields = if t.len == 1: t[0].split('.') else: t
    for x in fields: discard parseInt(x)
  except ValueError: return
  if y < 100: y += (if y > 68: 1900 else: 2000)
  const mdays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  let leap = y mod 4 == 0 and (y mod 100 != 0 or y mod 400 == 0)
  if y < 1 or y > 9999 or d < 1 or d > mdays[month - 1] or (month == 2 and d == 29 and not leap): return
  (true, y, month, d)

# ---------------------------------------------------------------------------------- the table

proc body(p: Part): string =
  ## The first text/plain part, decoded with its charset.
  for x in p.walk:
    if x.contentType == "text/plain" and not x.multipart:
      let (_, cte0) = x.get("content-transfer-encoding")
      let cte = cte0.pyStrip.toLowerAscii
      let bytes = case cte
        of "quoted-printable": qpDecode(x.body)
        of "base64": decodeB(x.body.replace("\r\n", "").replace("\n", "").replace("\r", ""))
        else: x.body
      let (has, cs) = x.param("charset")
      let charset = if has and cs.len > 0: cs.toLowerAscii else: "utf-8"
      let (ok, t) = decodeAs(bytes, charset)
      return (if ok: t else: "")

var rows: seq[seq[string]]
for msg in messages(readFile(src)):
  let p = parsePart(lines(msg))
  let d = parseDate(p.get("date"))
  var (name, address) = parseaddr(dec(p.get("from")))
  name = name.pyStrip.strip(chars = {'"'}).strip(chars = {'\''})
  if name.len == 0 or '@' in name:
    name = if address.len > 0: address.split('@')[0] else: ""
    name = name.sub(rx"\s+at\s+.*", "")
  let subj = dec(p.get("subject"))
  let b = body(p)
  let head = b.toRunes
  let scan = subj & " " & $head[0 ..< min(3000, head.len)]
  var years: seq[int]
  for y in scan.findall(rx"(?i)FOSDEM\s*'?(20\d\d|\d\d)\b", 1):
    let v = if y.len == 4: parseInt(y) else: 2000 + parseInt(y)
    if v notin years: years.add v
  years.sort
  let link = b.search(rx"https?://(?:pretalx\.fosdem\.org|penta\.fosdem\.org)[^\s>)\]]*")
  let reply = subj.sub(rx"(?i)^\[FOSDEM\]\s*", "").match(rx"(?i)\s*(re|aw|sv)\s*:").ok
  rows.add @[(if d[0]: $d[1] & "-" & align($d[2], 2, '0') & "-" & align($d[3], 2, '0') else: ""),
             (if d[0]: $d[1] else: ""), name, subj, (if reply: "1" else: "0"), years.join(" "),
             link.group, $head.len]
rows.sort(proc (a, b: seq[string]): int = cmp(a[0], b[0]))
writeCsv(stage, "list_messages.csv", ["date", "year", "sender", "subject", "is_reply", "years_mentioned",
                                      "pretalx_link", "body_chars"], rows)
echo rows.len, " messages"
src/extract_stands.nim 62 lines
## Read the stands of every edition from FOSDEM's archived stands pages (2008-2026).
##
## Usage: extract_stands <raw/stands dir> <stage dir>
## Expects <year>.html from fetch.sh: stands.html for 2008-2012, stands/ from 2013. Writes
## stands.csv (year, stand, building, theme, position): one row per stand as the page lists it
## (a stand shared by two projects is one row, "OpenBSD + OpenSSH").

import std/algorithm
import common

let src = paramStr(1)
let stage = paramStr(2)

var names: seq[string]
for kind, f in walkDir(src, relative = true): names.add f
names.sort
var rows: seq[seq[string]]
for name in names:
  let m = name.match(rx"(\d{4})\.html$")
  if not m.ok: continue
  let year = parseInt(m.group(1))
  let s = readText(src / name)
  var found: seq[(string, string, string)]
  if year <= 2012:
    # an announcement: <h2> buildings (2012) and <li> stands, in the content node
    let a = s.pyFind("""<div class="content">""", s.pyFind("""id="node-"""))
    let b = s.pyFind("""<div class="clearfix">""", a)
    let body = s.sl(a, b)
    var building = ""
    for t in body.finditer(rx"(?s)<(h2|li)[^>]*>(.*?)</\1>"):
      if t.group(1) == "h2":
        building = text(t.group(2)).replace(" building", "").pyStrip
      else:
        found.add (text(t.group(2)), building, "")
  elif year in [2021, 2022]:
    # online: one card per stand, "<h4>Box86 stand <small>Stand</small></h4>"
    for inner in s.findall(rx"(?s)<h4>(.*?)<small>", 1):
      found.add (text(inner).sub(rx"(?i)\s+stand$", ""), "online", "")
  else:
    # tables: a building heading per table, rows of stands (2026: themes as <h5> rows)
    for table in s.findall(rx"(?s)<table.*?</table>"):
      let h = table.search(rx"(?s)<h4>(.*?)</h4>")
      let building = if h.ok: text(h.group(1)) else: ""
      var theme = ""
      for tr in table.findall(rx"(?s)<tr>(.*?)</tr>", 1):
        let h5 = tr.search(rx"(?s)<h5>(.*?)</h5>")
        if h5.ok:
          theme = text(h5.group(1))
          continue
        let p = tr.search(rx"""(?s)class="stands-table-project"[^>]*>(.*?)</td>""")
        if p.ok:
          found.add (text(p.group(1)), building, theme)
          continue
        let tds = tr.findall(rx"(?s)<td[^>]*>(.*?)</td>", 1)
        if tds.len == 2 and text(tds[0]).fullmatch(rx"\d+"):
          found.add (text(tds[1]), building, theme)
  for i, (stand, building, theme) in found:
    if stand.len > 0:
      rows.add @[$year, stand, building, theme, $(i + 1)]

writeCsv(stage, "stands.csv", ["year", "stand", "building", "theme", "position"], rows)
echo rows.len, " stands"
src/extract_upcoming.nim 32 lines
## Read the announced next edition from fosdem.org/<year>/news/: its dates and accepted devrooms.
##
## Usage: extract_upcoming <raw/upcoming dir> <stage dir> <year>
## Expects accepted-developer-rooms.html and fosdem-<year>-dates.html (from fetch.sh). Writes
## upcoming_devrooms.csv (year, devroom, cfp link) and upcoming_edition.csv (year, start, end).

import std/tables
import common

let src = paramStr(1)
let stage = paramStr(2)
let year = parseInt(paramStr(3))

let s = readText(src / "accepted-developer-rooms.html")
let art = s.sl(s.pyFind("<article"), s.pyFind("</article>"))
let ul = art.sl(art.pyFind("<ul>"), art.pyFind("</ul>"))
var rows: seq[seq[string]]
for li in ul.findall(rx"(?s)<li>(.*?)</li>", 1):
  let link = li.search(rx"""href="([^"]+)"""")
  rows.add @[$year, text(li), link.group(1)]
let announced = art.search(rx"""<p class="date-small">([^<]+)</p>""")

let d = text(readText(src / "fosdem-" & $year & "-dates.html"))
let m = d.search(rx("Saturday (\\d+) and Sunday (\\d+) (\\w+) " & $year))
let months = {"January": 1, "February": 2}.toTable
let start = if m.ok: $year & "-" & align($months[m.group(3)], 2, '0') & "-" & align($parseInt(m.group(1)), 2, '0') else: ""
let stop = if m.ok: $year & "-" & align($months[m.group(3)], 2, '0') & "-" & align($parseInt(m.group(2)), 2, '0') else: ""

writeCsv(stage, "upcoming_devrooms.csv", ["year", "devroom", "cfp_link"], rows)
writeCsv(stage, "upcoming_edition.csv", ["year", "start", "end", "devrooms_announced"],
         @[@[$year, start, stop, (if announced.ok: text(announced.group(1)) else: "")]])
echo rows.len, " devrooms announced for ", year, " ", start, " ", stop
src/common.nim 270 lines
## What the extract_*.nim scripts share: reading files as text, the text of a piece of HTML,
## regular expressions with the groups of a match, and staging CSVs.
## Standard library only (std/re needs libpcre, as nanuq does).

import std/[re, strutils, unicode, os, htmlparser, sets, sequtils]
export Regex, strutils, os, sequtils

# ------------------------------------------------------------------------------------ text

proc utf8Replace*(s: string): string =
  ## `s` as UTF-8, each broken sequence replaced by U+FFFD (as Python's errors="replace").
  result = newStringOfCap(s.len)
  var i = 0
  while i < s.len:
    let b = s[i].ord
    if b < 0x80:
      result.add s[i]; inc i; continue
    var need = 0
    var lo = 0x80
    var hi = 0xBF
    case b
    of 0xC2..0xDF: need = 1
    of 0xE0: need = 2; lo = 0xA0
    of 0xE1..0xEC, 0xEE..0xEF: need = 2
    of 0xED: need = 2; hi = 0x9F
    of 0xF0: need = 3; lo = 0x90
    of 0xF1..0xF3: need = 3
    of 0xF4: need = 3; hi = 0x8F
    else: need = 0
    if need == 0:
      result.add "�"; inc i; continue
    var k = 1
    while k <= need:
      if i + k >= s.len: break
      let c = s[i + k].ord
      let (l, h) = if k == 1: (lo, hi) else: (0x80, 0xBF)
      if c < l or c > h: break
      inc k
    if k > need:
      result.add s[i ..< i + k]
    else:
      result.add "�"
    i += k

const cp1252 = [0x20AC, 0, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160,
                0x2039, 0x0152, 0, 0x017D, 0, 0, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013,
                0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0, 0x017E, 0x0178]

proc fromCp1252*(s: string): string =
  ## `s` read as Windows-1252, its five undefined bytes replaced by U+FFFD.
  for c in s:
    let b = c.ord
    if b < 0x80: result.add c
    elif b < 0xA0: result.add (if cp1252[b - 0x80] == 0: "�" else: $Rune(cp1252[b - 0x80]))
    else: result.add $Rune(b)

proc readText*(path: string): string =
  ## A file as Python reads it in text mode: UTF-8 with replacement, newlines as "\n".
  readFile(path).utf8Replace.replace("\r\n", "\n").replace("\r", "\n")

proc isPySpace(r: Rune): bool =
  r.int in 0x1C..0x1F or r.isWhiteSpace

proc pyStrip*(s: string): string =
  ## Python's `str.strip()`: Unicode whitespace at both ends.
  let rs = s.toRunes
  var a = 0
  var b = rs.len
  while a < b and rs[a].isPySpace: inc a
  while b > a and rs[b - 1].isPySpace: dec b
  $rs[a ..< b]

proc pySplit*(s: string): seq[string] =
  ## Python's `str.split()`: the words between runs of whitespace.
  var cur = ""
  for r in s.runes:
    if r.isPySpace:
      if cur.len > 0: result.add cur; cur = ""
    else: cur.add $r
  if cur.len > 0: result.add cur

proc chars*(s: string): int = s.runeLen   ## Python's len(): characters, not bytes

proc pyFind*(s, sub: string, start = 0): int =
  ## Python's `str.find`: a negative start counts from the end.
  var a = start
  if a < 0: a = max(0, s.len + a)
  if a > s.len: return -1
  s.find(sub, a)

proc sl*(s: string, a: int, b = int.high): string =
  ## Python's `s[a:b]`, negative bounds included.
  var x = a
  var y = b
  if x < 0: x = max(0, s.len + x)
  if y < 0: y = max(0, s.len + y)
  x = min(x, s.len)
  y = min(y, s.len)
  if y <= x: "" else: s[x ..< y]

proc capitalFirst*(s: string): string =
  ## The first character in upper case (Python's `r[:1].upper() + r[1:]`).
  if s.len == 0: return s
  let r = s.runeAt(0)
  ($r).toUpper & s[r.size .. ^1]

# ------------------------------------------------------------------------- regular expressions

type Match* = object
  ok*: bool
  first*, last*: int                 ## the whole match, `last` inclusive
  caps: seq[tuple[first, last: int]]
  src: string

proc rx*(p: string): Regex =
  ## A pattern as Python reads it on str: Unicode \w, \s, \d. (?s) and (?i) as in Python.
  re("(*UTF8)(*UCP)" & p, {})

proc search*(s: string, p: Regex, start = 0): Match =
  var caps: array[20, tuple[first, last: int]]
  let (a, b) = findBounds(s, p, caps, start)
  if a < 0: return Match(ok: false)
  Match(ok: true, first: a, last: b, caps: @caps, src: s)

proc match*(s: string, p: Regex): Match =
  ## Python's re.match: a match that starts where the string starts.
  result = search(s, p)
  if result.ok and result.first != 0: result = Match(ok: false)

proc fullmatch*(s: string, p: Regex): bool =
  let m = match(s, p)
  m.ok and m.last == s.len - 1

proc has*(m: Match, i: int): bool =
  ## Did group `i` take part in the match (Python: `m.group(i) is not None`)?
  m.ok and (i == 0 or m.caps[i - 1].first >= 0)

proc group*(m: Match, i = 0): string =
  if not m.has(i): return ""
  if i == 0: m.src[m.first .. m.last]
  else: m.src[m.caps[i - 1].first .. m.caps[i - 1].last]

proc start*(m: Match): int = m.first
proc stop*(m: Match): int = m.last + 1

iterator finditer*(s: string, p: Regex): Match =
  var at = 0
  while at <= s.len:
    let m = search(s, p, at)
    if not m.ok: break
    yield m
    at = if m.last >= m.first: m.last + 1 else: m.first + 1

proc findall*(s: string, p: Regex, g = 0): seq[string] =
  ## The matches, or group `g` of each (Python's findall with one group is `g = 1`).
  for m in finditer(s, p): result.add m.group(g)

proc sub*(s: string, p: Regex, by: string): string =
  ## Python's re.sub with a plain replacement.
  var at = 0
  for m in finditer(s, p):
    result.add s[at ..< m.first]
    result.add by
    at = m.last + 1
  result.add s[min(at, s.len) .. ^1]

proc resplit*(s: string, p: Regex): seq[string] =
  ## Python's re.split (patterns without groups).
  var at = 0
  for m in finditer(s, p):
    result.add s[at ..< m.first]
    at = m.last + 1
  result.add s[min(at, s.len) .. ^1]

# ------------------------------------------------------------------------------------ HTML

const legacy = ["AElig", "AMP", "Aacute", "Acirc", "Agrave", "Aring", "Atilde", "Auml", "COPY",
  "Ccedil", "ETH", "Eacute", "Ecirc", "Egrave", "Euml", "GT", "Iacute", "Icirc", "Igrave", "Iuml",
  "LT", "Ntilde", "Oacute", "Ocirc", "Ograve", "Oslash", "Otilde", "Ouml", "QUOT", "REG", "THORN",
  "Uacute", "Ucirc", "Ugrave", "Uuml", "Yacute", "aacute", "acirc", "acute", "aelig", "agrave",
  "amp", "aring", "atilde", "auml", "brvbar", "ccedil", "cedil", "cent", "copy", "curren", "deg",
  "divide", "eacute", "ecirc", "egrave", "eth", "euml", "frac12", "frac14", "frac34", "gt",
  "iacute", "icirc", "iexcl", "igrave", "iquest", "iuml", "laquo", "lt", "macr", "micro", "middot",
  "nbsp", "not", "ntilde", "oacute", "ocirc", "ograve", "ordf", "ordm", "oslash", "otilde", "ouml",
  "para", "plusmn", "pound", "quot", "raquo", "reg", "sect", "shy", "sup1", "sup2", "sup3", "szlig",
  "thorn", "times", "uacute", "ucirc", "ugrave", "uml", "uuml", "yacute", "yen", "yuml"].toHashSet

let charref = rx"&(#[0-9]+;?|#[xX][0-9a-fA-F]+;?|[^\t\n\f <&#;]{1,32};?)"

proc entity(name: string): string =
  ## A named reference ("amp;" or a legacy "amp"), as Python's html5 table: "" when unknown.
  if name.endsWith(";"):
    let r = entityToRune(name[0 ..< ^1])
    if r.int != 0: return $r
  elif name in legacy:
    return $entityToRune(name)

proc numeric(num: int): string =
  const invalid = [(0x00, 0xFFFD), (0x0d, 0x0D), (0x80, 0x20AC), (0x81, 0x81), (0x82, 0x201A),
    (0x83, 0x0192), (0x84, 0x201E), (0x85, 0x2026), (0x86, 0x2020), (0x87, 0x2021), (0x88, 0x02C6),
    (0x89, 0x2030), (0x8a, 0x0160), (0x8b, 0x2039), (0x8c, 0x0152), (0x8d, 0x8D), (0x8e, 0x017D),
    (0x8f, 0x8F), (0x90, 0x90), (0x91, 0x2018), (0x92, 0x2019), (0x93, 0x201C), (0x94, 0x201D),
    (0x95, 0x2022), (0x96, 0x2013), (0x97, 0x2014), (0x98, 0x02DC), (0x99, 0x2122), (0x9a, 0x0161),
    (0x9b, 0x203A), (0x9c, 0x0153), (0x9d, 0x9D), (0x9e, 0x017E), (0x9f, 0x0178)]
  for (n, r) in invalid:
    if n == num: return $Rune(r)
  if num in 0xD800..0xDFFF or num > 0x10FFFF: return "�"
  if num in 0x1..0x8 or num in 0xE..0x1F or num in 0x7F..0x9F or num in 0xFDD0..0xFDEF or
     num == 0xB or (num and 0xFFFE) == 0xFFFE: return ""
  $Rune(num)

proc htmlUnescape*(s: string): string =
  ## Python's html.unescape.
  if '&' notin s: return s
  var at = 0
  for m in finditer(s, charref):
    result.add s[at ..< m.first]
    at = m.last + 1
    let r = m.group(1)
    if r[0] == '#':
      let digits = r.strip(leading = false, chars = {';'})
      let hex = digits[1] in {'x', 'X'}
      let ds = if hex: digits[2 .. ^1] else: digits[1 .. ^1]
      let significant = ds.strip(trailing = false, chars = {'0'})
      if significant.len > 8: result.add "�"
      else: result.add numeric(if significant.len == 0: 0 elif hex: parseHexInt(significant) else: parseInt(significant))
    else:
      let e = entity(r)
      if e.len > 0: result.add e
      else:
        var done = false
        for x in countdown(r.len - 1, 2):
          let e = entity(r[0 ..< x])
          if e.len > 0:
            result.add e & r[x .. ^1]; done = true; break
        if not done: result.add "&" & r
  result.add s[at .. ^1]

let tags = rx"<[^>]+>"
let spaces* = rx"\s+"

proc text*(s: string): string =
  ## The text of a piece of HTML: tags out, references resolved, whitespace collapsed.
  s.sub(tags, " ").htmlUnescape.sub(spaces, " ").pyStrip

# ------------------------------------------------------------------------------------ CSV

proc field(f: string): string =
  if f.contains({',', '"', '\r', '\n'}): '"' & f.replace("\"", "\"\"") & '"' else: f

proc writeCsv*(dir, name: string, header: openArray[string], rows: seq[seq[string]]) =
  ## A staging CSV as Python's csv module writes it (minimal quoting, "\r\n" line endings).
  createDir(dir)
  var s = header.join(",") & "\r\n"
  for r in rows:
    s.add (if r.len == 1 and r[0] == "": "\"\"" else: r.mapIt(it.field).join(",")) & "\r\n"
  writeFile(dir / name, s)

proc counts*(xs: seq[int]): string =
  ## How many rows each year has, for the line a script prints.
  var years: seq[int]
  for x in xs:
    if x notin years: years.add x
  for y in years: result.add $y & ": " & $xs.count(y) & "  "

proc rxEscape*(s: string): string =
  ## `s` as a literal in a pattern.
  for c in s:
    if c.isAlphaNumeric or c.ord >= 128: result.add c
    else: result.add '\\' & c
src/grid.nim 144 lines
## Expand HTML tables (rowspan/colspan aware) into grids of cell texts.
##
## Usage: grid <html file> [min_cols]   prints the tables as TSV rows, for inspection,
## or import it and call tables(path).

import std/[tables, unicode]
import common

type
  Cell = ref object
    text: string
    rs, cs: int
  Tab = object
    rows: seq[seq[Cell]]
    hasRow: bool
    cell: Cell

const rawText = ["script", "style", "xmp", "iframe", "noembed", "noframes", "textarea", "title"]

proc span(attrs, name: string): int =
  ## rowspan or colspan: its digits, 1 when missing or empty.
  let m = attrs.search(rx("(?i)(?:^|[\\s\"'])" & name & "\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)"))
  let digits = if m.ok: m.group(1).sub(rx"\D", "") else: ""
  if digits.len == 0: 1 else: parseInt(digits)

proc tagEnd(html: string, i: int): int =
  ## Where a start tag ends: its '>', outside quoted attribute values.
  var q = '\0'
  for j in i ..< html.len:
    if q != '\0':
      if html[j] == q: q = '\0'
    elif html[j] in {'"', '\''} and j > 0 and html[j - 1] == '=': q = html[j]
    elif html[j] == '>': return j
  -1

proc parse(html: string): seq[seq[seq[Cell]]] =
  ## The tables of a page, in the order they close, as rows of cells.
  var closed: seq[seq[seq[Cell]]]
  var stack: seq[Tab]
  var data = ""
  proc flush() =
    if data.len > 0 and stack.len > 0 and stack[^1].cell != nil:
      stack[^1].cell.text.add htmlUnescape(data)
    data = ""
  proc start(tag, attrs: string) =
    if tag == "table":
      stack.add Tab()
    elif stack.len == 0: return
    elif tag == "tr":
      stack[^1].rows.add @[]; stack[^1].hasRow = true
    elif tag in ["td", "th"]:
      if not stack[^1].hasRow:
        stack[^1].rows.add @[]; stack[^1].hasRow = true
      stack[^1].cell = Cell(rs: span(attrs, "rowspan"), cs: span(attrs, "colspan"))
      stack[^1].rows[^1].add stack[^1].cell
    elif tag == "br" and stack[^1].cell != nil:
      stack[^1].cell.text.add " / "
  proc stop(tag: string) =
    if tag == "table" and stack.len > 0:
      closed.add stack.pop.rows
    elif tag in ["td", "th"] and stack.len > 0:
      stack[^1].cell = nil
  let lower = html.toLowerAscii
  var i = 0
  while i < html.len:
    if html[i] != '<':
      data.add html[i]; inc i; continue
    if html.continuesWith("<!--", i):
      flush()
      let e = html.search(rx"--!?>", i + 4)
      i = if e.ok: e.stop else: html.len
    elif i + 1 < html.len and html[i + 1] in {'!', '?'}:
      flush()
      let e = html.find('>', i)
      i = if e < 0: html.len else: e + 1
    elif i + 1 < html.len and html[i + 1] == '/' and i + 2 < html.len and html[i + 2].isAlphaAscii:
      flush()
      let e = html.find('>', i)
      let name = html.sl(i + 2, e).search(rx"^[a-zA-Z][^\t\n\r\f />]*").group.toLowerAscii
      stop(name)
      i = if e < 0: html.len else: e + 1
    elif i + 1 < html.len and html[i + 1].isAlphaAscii:
      flush()
      let e = tagEnd(html, i)
      if e < 0: data.add html[i ..< html.len]; break
      let inner = html[i + 1 ..< e]
      let name = inner.search(rx"^[a-zA-Z][^\t\n\r\f />]*").group.toLowerAscii
      let attrs = inner[name.len .. ^1]
      start(name, attrs)
      if attrs.endsWith("/"): stop(name)
      i = e + 1
      if name in rawText and not attrs.endsWith("/"):
        let close = lower.find("</" & name, i)
        let j = if close < 0: html.len else: close
        if name in ["textarea", "title"]: data.add html[i ..< j] else: discard
        flush()
        i = j
    else:
      data.add '<'; inc i
  flush()
  closed

proc expand(rows: seq[seq[Cell]]): seq[seq[string]] =
  ## Rows of texts, each spanning cell copied into every row and column it covers.
  var pending: OrderedTable[(int, int), string]
  for r in rows:
    var line: seq[string]
    var c = 0
    var cells = r
    proc pendingRow(at: int): bool =
      for k in pending.keys:
        if k[0] == at: return true
    while cells.len > 0 or pendingRow(result.len):
      if pending.hasKey((result.len, c)):
        line.add pending[(result.len, c)]; pending.del((result.len, c)); inc c; continue
      if cells.len == 0:
        var later = false
        for k in pending.keys:
          if k[0] == result.len and k[1] > c: later = true
        if later:
          line.add ""; inc c; continue
        break
      let cell = cells[0]
      cells.delete(0)
      let txt = cell.text.split(" / ").mapIt(it.sub(spaces, " ").pyStrip).filterIt(it.len > 0).join(" / ")
      for j in 0 ..< cell.cs:
        for i in 1 ..< cell.rs:
          pending[(result.len + i, c + j)] = txt
        line.add txt
      c += cell.cs
    result.add line

proc tables*(path: string): seq[seq[seq[string]]] =
  ## The tables of an HTML file (UTF-8, or Windows-1252 when it is not), expanded.
  let raw = readFile(path)
  let txt = if raw.utf8Replace == raw: raw else: raw.fromCp1252
  for t in parse(txt): result.add expand(t)

when isMainModule:
  let minCols = if paramCount() > 1: parseInt(paramStr(2)) else: 3
  for i, g in tables(paramStr(1)):
    if g.mapIt(it.len).foldl(max(a, b), 0) >= minCols:
      echo "### table ", i
      for r in g: echo r.join("\t")

Five sources, one table of events

Twenty-six years of schedules come in five shapes: the XML export (2012 on), the event index of the old site (2007–2011), the devroom pages (2007–2010), the printed grid (2001–2006) and the early devroom pages (2004–2006). Each becomes a lazy frame with the same columns, and nanuq stacks them:

let cols = @["year", "event_id", "source", "day", "start", "end", "duration_min", "room", "track",
             "type", "title", "subtitle", "language", "videos", "slides", "url", "video"]
proc pick(lf: LazyFrame): LazyFrame =
  var es: seq[Expr]
  for c in cols:
    es.add(if c in ["year", "duration_min", "videos", "slides"]: col(c).cast(Int64) else: col(c).cast(String))
  lf.select(es)

A lazy frame is a plan, not data: nanuq (Polars underneath) reads the CSV, filters, joins and groups only when collect is called, and in the best order it finds. Here is what each shape gave:

Where the events come from
the source column of events.csv
yearsevents
schedule xml2012–202610,955
devroom page html2004–20101,122
event index html2007–2011422
schedule grid html2001–2006187
type Source = object
  source, years: string
  events: int
var bySource: OrderedTable[string, (int, int, int)]   # events, first year, last year
for e in ev:
  let y = e["year"].parseInt
  let (n, lo, hi) = bySource.getOrDefault(e["source"], (0, 9999, 0))
  bySource[e["source"]] = (n + 1, min(lo, y), max(hi, y))
var rows: seq[Source]
for s, (n, lo, hi) in bySource:
  rows.add Source(source: s, events: n, years: $lo & "–" & $hi)
rows.sort(proc (a, b: Source): int = cmp(b.events, a.events))
let t = tabella(rows, rownameCol = "source"):
  optCssTheme()
  tabHeader "Where the events come from", "the source column of events.csv"
  colsLabel {"source": ""}
  fmtInteger "events"
nbTable t

One vocabulary for twenty-five years

Each source names its slots in its own way: maintrack, lecture, devroom, lightningtalk, or nothing at all, with the kind hidden in the track's name. nanuq's choose reads like an if/elif chain and becomes one Polars when/then/otherwise expression, so the whole vocabulary is in one place:

choose(
  if col("type") == "keynote" or (col("type") == "maintrack" and col.track.str.contains(mainTrackWords)): "keynote"
  elif col("type").isIn(["maintrack", "lecture"]): "main track"
  elif col("type") == "devroom" or col.track.str.contains(r"(?i)devroom|developer room"): "devroom"
  elif col("type").isIn(["lightning", "lightningtalk"]) or col.track.str.contains(r"(?i)lightning"): "lightning talk"
  # ... eleven more cases, for BOFs, stands, workshops and the years 2011 and 2012
  else: "other"
).alias("kind")

What it made of FOSDEM's own words:

The kinds of event
the kind column of events.csv, and the schedule types it comes from most
mostly fromevents
devroomdevroom, (none), lightning10,687
main trackmaintrack, lecture, (none)703
lightning talklightningtalk, (none), lightning679
BOFbof215
standstandtrack158
keynotekeynote, maintrack, (none)91
certificationcertification, (none)69
juniorjunior45
workshoptutorial, workshop26
otherinfodesk, keysigning, (none)13
type Kind = object
  kind, fromTypes: string
  events: int
var count: CountTable[string]
var types: Table[string, CountTable[string]]
for e in ev:
  count.inc e["kind"]
  let st = if e["source_type"] == "": "(none)" else: e["source_type"]
  types.mgetOrPut(e["kind"], initCountTable[string]()).inc st
var rows: seq[Kind]
for k, n in count:
  var ts = types[k]
  ts.sort()
  rows.add Kind(kind: k, events: n, fromTypes: ts.keys.toSeq[0 ..< min(3, ts.len)].join(", "))
rows.sort(proc (a, b: Kind): int = cmp(b.events, a.events))
let t = tabella(rows, rownameCol = "kind"):
  optCssTheme()
  tabHeader "The kinds of event", "the kind column of events.csv, and the schedule types it comes from most"
  colsLabel {"kind": "", "fromTypes": "mostly from"}
  fmtInteger "events"
nbTable t

Joined, grouped, counted

The rest is what data frames are for. People are the speakers grouped by their key, with a handful of aggregations in one agg; over would do the same per group without grouping:

let people = speakers.lazy.join(eventsOut.lazy.select(col.year, col.event_id, col.kind), on = ["year", "event_id"])
  .sort(["year", "event_id", "person"])
  .groupBy(col.person_key, maintainOrder = true)
  .agg(col.person.last.alias("person"),
       col.year.min.alias("first_year"), col.year.max.alias("last_year"),
       col.year.nUnique.alias("editions"), len().alias("talks"),
       (col.kind == "keynote").sum.alias("keynotes"),
       (col.kind == "main track").sum.alias("main_track_talks"),
       (col.kind == "devroom").sum.alias("devroom_talks"),
       col.year.unique.sort.cast(String).str.join(" ").alias("years"))
  .sort(["talks", "person_key"], descending = [true, false])
  .withColumns(col.person_key.str.contains(r"\b(staff|team|panel|volunteers|organi[sz]ers|everyone|various|tbd|tba|speakers|committee|crew|community|board|developers)\b").not.alias("is_person"))
  .select(col.person, col.person_key, col.is_person, col.first_year, col.last_year, col.editions, col.talks,
          col.keynotes, col.main_track_talks, col.devroom_talks, col.years)
  .collect

The devrooms are a full join: the tracks that have talks, and the devrooms the old sites only list by name, matched on a folded name, with coalesce so the key columns meet in one:

let tracks = fromEvents
  .join(listed, on = ["year", "tkey"], how = JoinType.Full, coalesce = some(true))

All of it, the ten tables and then the story's own small ones:

src/process.nim 426 lines
## Turns the staging CSVs (flattened from FOSDEM's raw sources by the extract_*.nim
## scripts) into the tidy tables of docs/stories/data/fosdem/.
##
##   nim r -d:release --path:<nanuq>/src process.nim <stage dir> <out dir>
##
## Every table is built with nanuq (Polars for Nim). Each output CSV starts with a
## `#` comment line that names its sources, as tabelline's readCsv expects.

import std/os
import nanuq

let stage = paramStr(1)
let outDir = paramStr(2)
createDir(outDir)

proc rd(name: string): LazyFrame =
  readCsv(stage / name, inferSchemaLength = none(int)).lazy

proc save(df: DataFrame, name, comment: string) =
  ## nanuq's writeCsv has no comment option, so the `#` line is put in front afterwards.
  let path = outDir / name
  df.writeCsv(path)
  let body = readFile(path)
  writeFile(path, "# " & comment & "\n" & body)
  echo name, ": ", df.height, " rows x ", df.width, " columns"

# ---------------------------------------------------------------- helpers

proc nameKey(e: Expr): Expr =
  ## A key to match the same person across years: accents and case folded (ø, ł, ß and
  ## friends too), punctuation and nicknames in quotes dropped, spaces collapsed. The key keeps
  ## Latin letters only, so "Bogomil Shopov - Бого" is `bogomil shopov`; a name with no Latin
  ## letter at all (a name in Chinese) keeps its own letters.
  let folded = e.str.normalize(UnicodeForm.NFKD)
   .str.replaceAll(r"\p{Mn}", "")
   .str.replaceAll("\"[^\"]*\"", " ")
   .str.toLowercase
   # letters that NFKD does not split into a base letter and a mark
   .str.replaceMany({"ø": "o", "ł": "l", "ß": "ss", "æ": "ae", "œ": "oe", "ı": "i", "þ": "th", "ð": "d", "đ": "d"})
  let latin = folded.str.replaceAll(r"[^a-z0-9]+", " ").str.stripChars
  choose(if latin == "": folded.str.replaceAll(r"[^\p{L}\p{N}]+", " ").str.stripChars else: latin)

proc minutesOf(e: Expr): Expr =
  ## "HH:MM" to minutes after midnight.
  e.str.splitExact(":", 1).struct.field("field_0").cast(Int64) * 60 +
    e.str.splitExact(":", 1).struct.field("field_1").cast(Int64)

proc hhmm(e: Expr): Expr =
  ## minutes after midnight to "HH:MM".
  format("{}:{}", (e div 60).cast(String).str.zfill(2), (e mod 60).cast(String).str.zfill(2))

# ---------------------------------------------------------------- events

# 2012-2026: the schedule XML (Pentabarf until 2025, pretalx from 2026).
let xmlEvents = rd("xml_events.csv").withColumns(
  lit("schedule xml").alias("source"),
  col.date.str.strptime(Date, "%Y-%m-%d").dt.weekday.alias("wd"),
  minutesOf(col.start).alias("start_min"),
  minutesOf(col.duration).alias("duration_min"),
).withColumns(
  choose(if col.wd == 5: "Friday" elif col.wd == 6: "Saturday" elif col.wd == 7: "Sunday" else: "Other").alias("day"),
  hhmm(col.start_min + col.duration_min).alias("end"),
  col.event_id.cast(String),
).select(col.year, col.event_id, col.source, col.day, col.start, col.end, col.duration_min,
         col.room, col.track, col("type"), col.title, col.subtitle, col.language, col.videos, col.slides,
         # the archive of 2012 keeps its pages as event/<slug>.html, later years as event/<slug>/
         choose(if col.year == 2012: format("https://archive.fosdem.org/{}/schedule/event/{}.html", col.year, col.slug)
                else: format("https://archive.fosdem.org/{}/schedule/event/{}/", col.year, col.slug)).alias("url"))
  # the first recording of each event: the MP4 when there is one
  .join(rd("xml_links.csv").filter(col.href.str.contains(r"^https?://video\.fosdem\.org/.*\.(mp4|webm)$"))
          .withColumns(col.event_id.cast(String), col.href.str.endsWith(".mp4").not.alias("not_mp4"))
          .sort(["year", "event_id", "not_mp4", "href"])
          .groupBy(col.year, col.event_id).agg(col.href.first.alias("video")),
        on = ["year", "event_id"], how = JoinType.Left)

# 2007-2011: the event index of the old site (main tracks only until 2010, all of 2011).
let idxEvents = rd("html_events.csv").withColumns(
  lit("event index html").alias("source"),
  (minutesOf(col("end")) - minutesOf(col.start)).alias("duration_min"),
  choose(if col.year == 2011: "" else: "maintrack").alias("type"),
  lit("").alias("language"), lit(0).alias("slides"),
  choose(if col.year == 2011: format("https://archive.fosdem.org/{}/schedule/event/{}.html", col.year, col.slug)
         else: format("https://archive.fosdem.org/{}/schedule/events/{}.html", col.year, col.slug)).alias("url"),
)
# 2007-2010: devroom pages (named after the devroom index of the same year).
let devroomNames = rd("html_devrooms.csv").select(col.year, col.devroom_key, col.devroom)
let devEvents = rd("html_devroom_events.csv")
  .join(devroomNames, on = ["year", "devroom_key"], how = JoinType.Left)
  .withColumns(
    lit("devroom page html").alias("source"),
    choose(if col.devroom_key == "lightningtalks": "Lightning Talks" else: col.devroom).fillNull(col.devroom_key).alias("track"),
    choose(if col.devroom_key == "lightningtalks": "lightningtalk" else: "devroom").alias("type"),
    (minutesOf(col("end")) - minutesOf(col.start)).alias("duration_min"),
    lit("").alias("subtitle"), lit("").alias("language"), lit(0).alias("videos"), lit(0).alias("slides"),
    # these talks have no page of their own: the devroom's page
    choose(if col.devroom_key == "lightningtalks": format("https://archive.fosdem.org/{}/schedule/tracks/lightningtalks.html", col.year)
           elif col.year <= 2008: format("https://archive.fosdem.org/{}/schedule/devroom/{}.html", col.year, col.devroom_key)
           else: format("https://archive.fosdem.org/{}/schedule/devrooms/{}.html", col.year, col.devroom_key)).alias("url"),
    lit("").alias("video"),
  )
# 2001-2006: the printed main schedule grid, and the devroom pages of 2004-2006.
let earlyMain = rd("early_events.csv").withColumns(
  format("{}-main-{}", col.year, intRange(1, len() + 1, dtype = Int64).over(col.year)).alias("event_id"),
  lit("schedule grid html").alias("source"),
  col.room.str.replace(r"^(?:Talk|Tutorials) \((\w+)(?: room)?\)$", "$1")
          .str.replace(r"^(\w)", "$1").alias("room"),
  choose(if col.room.str.startsWith("Tutorials"): "tutorial" else: "maintrack").alias("type"),
  lit("").alias("track"),
  (minutesOf(col("end")) - minutesOf(col.start)).alias("duration_min"),
  lit("").alias("subtitle"), lit("").alias("language"), lit(0).alias("videos"), lit(0).alias("slides"),
  lit("").alias("url"), lit("").alias("video"),
)
let earlyDevNames = rd("early_devrooms.csv")
let earlyDev = rd("early_devroom_events.csv")
  # ids first: a join does not keep the row order unless asked (maintainOrder)
  .withColumns(format("{}-{}-{}", col.year, col.devroom_key, intRange(0, len(), dtype = Int64)).alias("event_id"))
  .join(earlyDevNames, on = ["year", "devroom_key"], how = JoinType.Left)
  .withColumns(
    lit("devroom page html").alias("source"),
    col.devroom.alias("track"), lit("devroom").alias("type"), lit("").alias("room"),
    (minutesOf(col("end")) - minutesOf(col.start)).alias("duration_min"),
    lit("").alias("subtitle"), lit("").alias("language"), lit(0).alias("videos"), lit(0).alias("slides"),
    lit("").alias("url"), lit("").alias("video"),
  )

let cols = @["year", "event_id", "source", "day", "start", "end", "duration_min", "room", "track",
             "type", "title", "subtitle", "language", "videos", "slides", "url", "video"]
proc pick(lf: LazyFrame): LazyFrame =
  var es: seq[Expr]
  for c in cols:
    es.add(if c in ["year", "duration_min", "videos", "slides"]: col(c).cast(Int64) else: col(c).cast(String))
  lf.select(es)

let allEvents = concat([xmlEvents.pick, idxEvents.pick, devEvents.pick, earlyMain.pick, earlyDev.pick])

# What kind of slot a talk is: one vocabulary for 25 years of type and track names.
let mainTrackWords = r"(?i)keynote|opening|closing|welcome"
let events = allEvents.withColumns(
  col.title.str.replaceAll(r"\s+", " ").str.stripChars, col.subtitle.str.replaceAll(r"\s+", " ").str.stripChars,
  col.room.str.stripChars, col.track.str.stripChars,
  choose(
    if col("type") == "keynote" or (col("type") == "maintrack" and col.track.str.contains(mainTrackWords)): "keynote"
    elif col("type").isIn(["maintrack", "lecture"]): "main track"
    elif col("type") == "devroom" or col.track.str.contains(r"(?i)devroom|developer room"): "devroom"
    elif col("type").isIn(["lightning", "lightningtalk"]) or col.track.str.contains(r"(?i)lightning"): "lightning talk"
    elif col("type") == "bof": "BOF"
    elif col("type") == "standtrack": "stand"
    elif col("type") == "junior": "junior"
    elif col("type").isIn(["workshop", "tutorial"]): "workshop"
    elif col("type") == "certification" or col.track.str.contains(r"(?i)certification"): "certification"
    elif col("type").isIn(["keysigning", "infodesk"]) or col.track.str.contains(r"(?i)keysigning"): "other"
    elif col.year == 2012 and col.track.str.contains(r"(?i)keynote"): "keynote"
    elif col.year == 2012 and col.track.str.contains(r"(?i) track$"): "main track"
    elif col.year == 2012 and col("type") == "" and col.track == "CAcert": "other"
    elif col.year == 2012 and col("type") == "": "devroom"
    elif col.year == 2011 and col.track.str.contains(r"(?i)keynote"): "keynote"
    elif col.year == 2011 and col.track.str.contains(r"(?i)track"): "main track"
    elif col.year == 2011: "devroom"
    else: "other"
  ).alias("kind"),
).sort(["year", "day", "start", "room", "title", "event_id"]).collect

# ---------------------------------------------------------------- speakers

let xmlP = rd("xml_event_persons.csv").select(col.year, col.event_id.cast(String), col.name, col.position)
let idxP = rd("html_event_persons.csv").select(col.year, col.event_id, col.name, col.position)
let devP = rd("html_devroom_persons.csv").select(col.year, col.event_id, col.name, col.position)
# Early years have the speakers as text in the event row: split on "&", "," and " and ".
let earlyP = events.lazy.filter(col.source.isIn(["schedule grid html"]) or
                                (col.source == "devroom page html" and col.year <= 2006))
  .select(col.year, col.event_id, col.title)
  .join(concat([earlyMain.select(col.event_id, col.speakers), earlyDev.select(col.event_id, col.speakers)]),
        on = ["event_id"], how = JoinType.Inner)
  .filter(col.speakers != "")
  .withColumns(col.speakers.str.replaceAll(r"\s*(?:&|,| and )\s*", "|").str.split("|").alias("name"))
  .explode("name")
  .withColumns(col.name.str.stripChars, intRange(1, len() + 1, dtype = Int64).over(col.event_id).alias("position"))
  .select(col.year, col.event_id, col.name, col.position)

let speakers = concat([xmlP, idxP, devP, earlyP], how = ConcatMethod.VerticalRelaxed)
  .filter(col.name.isNotNull and col.name != "")
  .withColumns(nameKey(col.name).alias("person_key"))
  .unique(["year", "event_id", "person_key"], keep = UniqueKeepStrategy.First, maintainOrder = true)
  .select(col.year.cast(Int64), col.event_id, col.position.cast(Int64), col.name.alias("person"), col.person_key)
  .sort(["year", "event_id", "position", "person"])
  .collect

let nSpeakers = speakers.lazy.groupBy(col.year, col.event_id).agg(len().alias("speakers"))
let eventsOut = events.lazy.join(nSpeakers, on = ["year", "event_id"], how = JoinType.Left)
  .withColumns(col.speakers.fillNull(0))
  .select(col.year, col.event_id, col.kind, col.track, col.title, col.subtitle, col.day, col.start,
          col("end"), col.duration_min, col.room, col.speakers, col.language, col.videos, col.slides,
          col("type").alias("source_type"), col.source, col.url.fillNull(""), col.video.fillNull(""))
  .sort(["year", "day", "start", "room", "title", "event_id"])
  .collect

# People: one row per person key, with the name as last written.
let people = speakers.lazy.join(eventsOut.lazy.select(col.year, col.event_id, col.kind), on = ["year", "event_id"])
  .sort(["year", "event_id", "person"])
  .groupBy(col.person_key, maintainOrder = true)
  .agg(col.person.last.alias("person"),
       col.year.min.alias("first_year"), col.year.max.alias("last_year"),
       col.year.nUnique.alias("editions"), len().alias("talks"),
       (col.kind == "keynote").sum.alias("keynotes"),
       (col.kind == "main track").sum.alias("main_track_talks"),
       (col.kind == "devroom").sum.alias("devroom_talks"),
       col.year.unique.sort.cast(String).str.join(" ").alias("years"))
  .sort(["talks", "person_key"], descending = [true, false])
  .withColumns(col.person_key.str.contains(r"\b(staff|team|panel|volunteers|organi[sz]ers|everyone|various|tbd|tba|speakers|committee|crew|community|board|developers)\b").not.alias("is_person"))
  .select(col.person, col.person_key, col.is_person, col.first_year, col.last_year, col.editions, col.talks,
          col.keynotes, col.main_track_talks, col.devroom_talks, col.years)
  .collect

eventsOut.save("events.csv", "FOSDEM talks 2001-2026, one row per scheduled event. Sources: archive.fosdem.org schedule XML (2012-2026), event index and devroom pages (2007-2011), printed schedule grids and devroom pages (2001-2006). See README.md.")
speakers.save("event_speakers.csv", "Who spoke in which FOSDEM event (year, event_id as in events.csv). person_key folds case, accents and nicknames to match people across years. Sources as events.csv.")
people.save("people.csv", "FOSDEM speakers 2001-2026, one row per person_key (see event_speakers.csv): first and last year, editions, talks by kind. Derived from events.csv and event_speakers.csv.")

# ---------------------------------------------------------------- tracks

let trackPages = rd("track_pages.csv")
let cfpYaml = rd("cfp_yaml.csv").withColumns(nameKey(col.devroom).alias("tkey"), col.edition.alias("year"))
  .unique(["year", "tkey"], keep = UniqueKeepStrategy.Last)
  .select(col.year, col.tkey, col.announcement.alias("cfp_yaml"), col.deadline.alias("cfp_deadline"))
proc trackKey(e: Expr): Expr =
  nameKey(e).str.replace(r"^the ", "").str.replace(r" (devroom|dev room|developer room|developers room|track)s?$", "")

# Devrooms the old sites list, also those whose talks are not online (2002-2010).
let listed = concat([
  rd("early_grid_devrooms.csv").select(col.year, col.devroom, col.room.alias("listed_rooms"),
                                       lit("").alias("capacity"), lit("schedule grid").alias("list_source")),
  rd("early_devrooms.csv").select(col.year, col.devroom, lit("").alias("listed_rooms"),
                                  lit("").alias("capacity"), lit("devroom page").alias("list_source")),
  rd("html_devrooms.csv").select(col.year, col.devroom, col.rooms.alias("listed_rooms"),
                                 col.capacity.cast(String), lit("devroom index").alias("list_source")),
  rd("upcoming_devrooms.csv").select(col.year, col.devroom, lit("").alias("listed_rooms"),
                                     lit("").alias("capacity"), lit("accepted devrooms news").alias("list_source"),
                                     col.cfp_link.alias("upcoming_cfp")),
], how = ConcatMethod.DiagonalRelaxed)
  .withColumns(trackKey(col.devroom).alias("tkey"), col.year.cast(Int64))
  .unique(["year", "tkey"], keep = UniqueKeepStrategy.First, maintainOrder = true)

let fromEvents = eventsOut.lazy.filter(col.track != "")
  .groupBy(col.year, col.track)
  .agg(col.kind.mode.first.alias("kind"), len().alias("events"),
       col.speakers.sum.alias("speaker_slots"),
       col.room.filter(col.room != "").unique.sort.str.join("; ").alias("rooms"),
       col.day.filter(col.day != "").unique.sort.str.join("; ").alias("days"),
       (col.videos > 0).sum.alias("events_with_video"))
  .withColumns(trackKey(col.track).alias("tkey"))

let tracks = fromEvents
  .join(listed, on = ["year", "tkey"], how = JoinType.Full, coalesce = some(true))
  .withColumns(
    col.track.fillNull(col.devroom),
    col.kind.fillNull("devroom"),
    col.events.fillNull(0), col.speaker_slots.fillNull(0), col.events_with_video.fillNull(0),
    choose(if col.rooms.isNull or col.rooms == "": col.listed_rooms else: col.rooms).alias("rooms"),
  )
  .join(trackPages.withColumns(trackKey(col.track).alias("tkey"))
          .unique(["year", "tkey"], keep = UniqueKeepStrategy.First, maintainOrder = true)
          .select(col.year, col.tkey, col.group, col.cfp_link),
        on = ["year", "tkey"], how = JoinType.Left)
  .join(cfpYaml, on = ["year", "tkey"], how = JoinType.Left)
  .withColumns(choose(
      if col.cfp_link.isNotNull and col.cfp_link != "": col.cfp_link
      elif col.upcoming_cfp.isNotNull and col.upcoming_cfp != "": col.upcoming_cfp
      else: col.cfp_yaml).alias("cfp"))
  .sort(["year", "kind", "track", "list_source"])
  .select(col.year, col.track, col.kind, col.group.alias("site_group"), col.events, col.speaker_slots,
          col.events_with_video, col.rooms, col.capacity, col.days, col.cfp, col.cfp_deadline,
          col.list_source.alias("listed_on"))
  .collect
tracks.save("tracks.csv", "FOSDEM tracks and devrooms per edition 2001-2027 (2027: the accepted devrooms as announced) (events grouped by track; 2001-2006 main talks had no track). CfP links: devrooms-cfp.yaml in github.com/FOSDEM/website (2013-2020), track pages on archive.fosdem.org (2021-2026).")

# ---------------------------------------------------------------- rooms

let rooms = eventsOut.lazy.filter(col.room != "")
  .groupBy(col.year, col.room)
  .agg(len().alias("events"), col.track.filter(col.track != "").nUnique.alias("tracks"),
       col.duration_min.sum.alias("scheduled_minutes"))
  .sort(["year", "events", "room"], descending = [false, true, false])
  .collect
rooms.save("rooms.csv", "Rooms used per FOSDEM edition and how many events they held. Derived from events.csv.")

# ---------------------------------------------------------------- calls for participation

let cfpListings = concat([
  rd("cfp_yaml.csv").select(col.edition.alias("year"), col.devroom, col.day, col.announcement,
                            col.deadline, col.first_listed, lit("website devrooms-cfp.yaml").alias("source")),
  trackPages.filter(col.cfp_link.isNotNull and col.cfp_link != "")
    .select(col.year, col.track.alias("devroom"), lit("").alias("day"), col.cfp_link.alias("announcement"),
            lit("").alias("deadline"), lit("").alias("first_listed"), lit("track page").alias("source")),
], how = ConcatMethod.VerticalRelaxed).sort(["year", "devroom", "source", "announcement", "day", "deadline", "first_listed"]).collect
cfpListings.save("cfp_listings.csv", "Devroom calls for participation as FOSDEM listed them: devrooms-cfp.yaml in github.com/FOSDEM/website (editions 2013-2020) and the CfP link of each track page on archive.fosdem.org (2021-2026).")

# Mailing list: every message of fosdem@lists.fosdem.org (2006-), CfPs flagged.
let msgs = rd("list_messages.csv").withColumns(
  col.subject.str.replace(r"(?i)^(\s*\[FOSDEM\]\s*)+", "").str.stripChars.alias("subject"),
)
let cfpRe = r"(?i)\bcall for (papers|participation|proposals|presentations|talks|speakers|submissions|content)|\bc[f4]p\b|\bcfp\b"
let msgsD = msgs.withColumns(
  intRange(0, len(), dtype = Int64).alias("msg"),
  col.subject.str.contains(cfpRe).alias("is_cfp"),
  col.subject.str.contains(r"(?i)volunteer").alias("is_volunteers"),
  col.date.str.strptime(Date, "%Y-%m-%d").alias("d"),
).withColumns(
  # The next edition after the message's date (FOSDEM is in late January or February).
  choose(if col.d.dt.month >= 3: col.d.dt.year + 1 else: col.d.dt.year).cast(Int64).alias("next_edition"),
)
# The edition a message is about: the FOSDEM year it names (near its date), else the next edition.
let named = msgsD.select(col.msg, col.next_edition,
                         col.years_mentioned.cast(String).str.split(" ").alias("y"))
  .explode("y")
  .withColumns(col.y.cast(Int64, strict = false))
  .filter(col.y >= col.next_edition - 1 and col.y <= col.next_edition + 1)
  .groupBy(col.msg).agg(col.y.min.alias("named"))
let messages = msgsD.join(named, on = ["msg"], how = JoinType.Left)
  .withColumns(col.named.fillNull(col.next_edition).alias("edition"))
  .sort("msg")
  .select(col.date, col.edition, col.sender, col.subject, col.is_reply.cast(Boolean), col.is_cfp,
          col.is_volunteers, col.pretalx_link)
  .collect
let cfpPosts = messages.lazy
  .filter(col.is_cfp and not col.is_reply and not col.is_volunteers)
  .withColumns(
    choose(
      if col.subject.str.contains(r"(?i)call for (developer rooms|devrooms)|call for participation: main tracks|lightning talks and stands|call for stands|stands cfp"): "fosdem call"
      elif col.subject.str.contains(r"(?i)dev ?room|developer room|track|room"): "devroom cfp"
      else: "other cfp"
    ).alias("kind"),
    col.subject
      .str.replaceAll(r"(?i)\[?\bc[f4]p\b\]?|call for (papers|participation|proposals|presentations|talks|speakers|submissions|content)|fosdem\s*'?\d{2,4}|\bfosdem\b|[@:\[\]\-–|]|\b(at|the|for|in|a|an)\b|\b20\d\d\b", " ")
      .str.extract(r"(?i)^\s*(.+?)\s+(?:dev(?:eloper)?\s*rooms?|devroom|track|room)\b", 1)
      .str.replaceAll(r"\s+", " ").str.stripChars.alias("devroom_from_subject"),
  )
  .withColumns(nameKey(col.sender).alias("sender_key"))
  # Did the sender also speak at that edition? (organizers often give a talk in their devroom)
  .join(speakers.lazy.select(col.year.alias("edition"), col.person_key.alias("sender_key"), lit(true).alias("sender_spoke"))
          .unique(["edition", "sender_key"]),
        on = ["edition", "sender_key"], how = JoinType.Left)
  .withColumns(col.sender_spoke.fillNull(false))
  .select(col.edition, col.date, col.kind, col.devroom_from_subject, col.subject, col.sender, col.sender_key,
          col.sender_spoke, col.pretalx_link)
  .sort(["edition", "date", "subject", "sender"])
  .collect
let listYears = messages.lazy.groupBy(col.date.str.head(4).cast(Int64).alias("year"))
  .agg(len().alias("messages"), col.is_reply.not.sum.alias("threads"),
       col.sender.nUnique.alias("senders"),
       (col.is_cfp and not col.is_reply and not col.is_volunteers).sum.alias("cfp_posts"))
  .sort("year").collect

cfpPosts.save("cfp_posts.csv", "Calls for participation posted to fosdem@lists.fosdem.org (2006-2026, HyperKitty mbox export), one row per first post; sender names only. edition is the FOSDEM year the post names, else the next edition after its date.")
listYears.save("mailing_list_years.csv", "Messages per year on fosdem@lists.fosdem.org (HyperKitty mbox export, Sep 2006 - Nov 2026).")

# ---------------------------------------------------------------- editions

let conf = rd("conference.csv").select(col.year, col.start, col("end"), col.venue, col.city)
let early = newDataFrame:
  year: [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011]
  start: ["2001-02-03", "2002-02-16", "2003-02-08", "2004-02-21", "2005-02-26", "2006-02-25",
          "2007-02-24", "2008-02-23", "2009-02-07", "2010-02-06", "2011-02-05"]
  "end": ["2001-02-04", "2002-02-17", "2003-02-09", "2004-02-22", "2005-02-27", "2006-02-26",
          "2007-02-25", "2008-02-24", "2009-02-08", "2010-02-07", "2011-02-06"]
  venue: ["ULB (Université Libre de Bruxelles)", "ULB (Université Libre de Bruxelles)", "ULB (Université Libre de Bruxelles)",
          "ULB (Université Libre de Bruxelles)", "ULB (Université Libre de Bruxelles)", "ULB (Université Libre de Bruxelles)",
          "ULB (Université Libre de Bruxelles)", "ULB (Université Libre de Bruxelles)", "ULB (Université Libre de Bruxelles)",
          "ULB (Université Libre de Bruxelles)", "ULB (Université Libre de Bruxelles)"]
  city: ["Brussels", "Brussels", "Brussels", "Brussels", "Brussels", "Brussels", "Brussels", "Brussels",
         "Brussels", "Brussels", "Brussels"]
let perYear = eventsOut.lazy.groupBy(col.year).agg(
  len().alias("events"),
  (col.kind == "keynote").sum.alias("keynotes"),
  (col.kind == "main track").sum.alias("main_track_talks"),
  (col.kind == "devroom").sum.alias("devroom_talks"),
  (col.kind == "lightning talk").sum.alias("lightning_talks"),
    col.room.filter(col.room != "").nUnique.alias("rooms"),
  (col.videos > 0).sum.alias("events_with_video"),
  col.source.unique.sort.str.join("; ").alias("sources"),
)
let devroomsYear = tracks.lazy.filter(col.kind == "devroom").groupBy(col.year).agg(len().alias("devrooms"))
let peopleYear = speakers.lazy.groupBy(col.year).agg(col.person_key.nUnique.alias("speakers"))
let newPeople = people.lazy.groupBy(col.first_year.alias("year")).agg(len().alias("first_time_speakers"))
let upcoming = rd("upcoming_edition.csv").select(col.year.cast(Int64), col.start, col("end"),
  lit("ULB (Université Libre de Bruxelles)").alias("venue"), lit("Brussels").alias("city"))
let editions = concat([early.lazy.withColumns(col.year.cast(Int64)), conf.withColumns(col.year.cast(Int64)), upcoming],
                      how = ConcatMethod.VerticalRelaxed)
  .withColumns(
    (col.year - 2000).alias("edition"),
    choose(if col.year == 2001: "OSDEM" else: "FOSDEM").alias("name"),
    choose(if col.year.isIn([2021, 2022]): "online" else: "in person").alias("format"),
  )
  .join(perYear, on = ["year"], how = JoinType.Left)
  .join(peopleYear, on = ["year"], how = JoinType.Left)
  .join(devroomsYear, on = ["year"], how = JoinType.Left)
  .withColumns(
    col.devrooms.fillNull(0),
    # 2022 was online too, though its schedule export still names the ULB.
    choose(if col.format == "online": "Online" else: col.venue).alias("venue"),
    choose(if col.format == "online": "" else: col.city).alias("city"),
  )
  .join(newPeople, on = ["year"], how = JoinType.Left)
  .withColumns(
    choose(
      if col.events.isNull: "announced: dates, devrooms and CfPs"
      elif col.year >= 2012: "full schedule"
      elif col.year == 2011: "full schedule (event index)"
      elif col.year >= 2007: "main tracks + devroom pages"
      elif col.year >= 2004: "main grid + most devroom pages"
      else: "main grid only"
    ).alias("coverage"))
  .select(col.year, col.edition, col.name, col.start, col("end"), col.format, col.venue, col.city,
          col.events, col.keynotes, col.main_track_talks, col.devroom_talks, col.lightning_talks,
          col.devrooms, col.rooms, col.speakers, col.first_time_speakers, col.events_with_video,
          col.coverage, col.sources)
  .sort("year").collect
editions.save("editions.csv", "FOSDEM editions 2001-2027 (OSDEM in 2001; 2027 as announced on fosdem.org): dates, venue and counts derived from events.csv. 2021 and 2022 were online. coverage says how complete the schedule is for that year; see README.md.")

# ---------------------------------------------------------------- stands

# 2008-2026: the stands pages (a list until 2012, tables by building after, cards online).
rd("stands.csv")
  .withColumns(col.stand.str.replaceAll(r"\s+", " ").str.stripChars, nameKey(col.stand).alias("stand_key"),
               col.building.fillNull(""), col.theme.fillNull(""))
  .select(col.year, col.stand, col.stand_key, col.building, col.theme)
  .sort(["year", "stand_key", "stand"]).collect
  .save("stands.csv", "Stands at FOSDEM 2008-2026, one row per stand as the archived stands page lists it (archive.fosdem.org/<year>/stands.html until 2012, /<year>/stands/ after; online in 2021 and 2022). stand_key folds case and punctuation; a stand shared by projects is one row.")
src/insights.nim 334 lines
## The small tables of the FOSDEM story (docs/stories/fosdem.nim), computed with nanuq from the
## tidy tables of docs/stories/data/fosdem/.
##
##   nim r -d:release --hints:off --path:<nanuq>/src insights.nim <data dir> <out dir>
##
## Every output is a CSV with a `#` line naming what it is made from, read by the story with
## `readCsv(path, comment = "#")`. The devroom families (renames) are written here by hand.

import std/[os, sequtils]
import nanuq

let data = paramStr(1)
let outDir = paramStr(2)
createDir(outDir)

proc rd(name: string): LazyFrame =
  readCsv(data / name, inferSchemaLength = none(int), commentPrefix = "#").lazy

proc save(df: DataFrame, name, comment: string) =
  let path = outDir / name
  df.writeCsv(path)
  writeFile(path, "# " & comment & "\n" & readFile(path))
  echo name, ": ", df.height, " rows x ", df.width, " columns"

proc trackKey(e: Expr): Expr =
  ## As in process.nim: the name of a track folded to match it across years.
  e.str.normalize(UnicodeForm.NFKD).str.replaceAll(r"\p{Mn}", "")
   .str.toLowercase.str.replaceAll(r"[^a-z0-9]+", " ").str.stripChars
   .str.replace(r"^the ", "")
   .str.replace(r"( (devroom|dev room|developer room|developers room|track)s?)+$", "")

const lastYear = 2027      # the edition announced so far
const lastHeld = 2026      # the last edition with a schedule

# ---------------------------------------------------------------- A. the editions

let editions = rd("editions.csv")

# A1: the dates. Which weekend of the year: FOSDEM is the weekend after the end of January.
editions.withColumns(
    col.start.str.strptime(Date, "%Y-%m-%d").alias("d"),
  ).withColumns(
    col.d.dt.ordinalDay.alias("day_of_year"),
    col.d.dt.weekday.alias("wd"),
    # since 2011 the Saturday falls between 30 January (day 30) and 5 February (day 36)
    (col.d.dt.ordinalDay >= 30 and col.d.dt.ordinalDay <= 36).alias("in_window"),
  ).select(col.year, col.edition, col.name, col.start, col("end"), col.format, col.venue,
           col.day_of_year, col.in_window,
           # the edition's site: archived, or fosdem.org for the next one
           choose(if col.year > lastHeld: format("https://fosdem.org/{}/", col.year)
                  else: format("https://archive.fosdem.org/{}/", col.year)).alias("url"))
  .sort("year").collect
  .save("dates.csv", "The dates of every FOSDEM edition, from editions.csv; day_of_year is the day of the year of the Saturday; in_window: it falls between 30 January and 5 February.")

# A2: how big, by decade.
editions.filter(col.year <= lastHeld).withColumns(
    choose(if col.year < 2010: "2001–2009" elif col.year < 2020: "2010–2019" else: "2020–2026").alias("decade"),
  ).select(col.decade, col.year, col.events, col.devrooms, col.devroom_talks, col.main_track_talks,
           col.lightning_talks, col.speakers, col.coverage)
  .sort("year").collect
  .save("sizes.csv", "Events, devrooms and speakers of every edition held, from editions.csv.")

# A3: the online years, and the years around them.
let events = rd("events.csv")
let talkKinds = ["keynote", "main track", "devroom", "lightning talk"]
let lengths = events.filter(col.kind.isIn(talkKinds) and col.duration_min > 0)
  .groupBy(col.year).agg(col.duration_min.median.alias("median_minutes"))
editions.filter(col.year >= 2018 and col.year <= lastHeld)
  .join(lengths, on = ["year"], how = JoinType.Left)
  .withColumns((col.events_with_video / col.events).alias("with_video"))
  .select(col.year, col.format, col.events, col.devrooms, col.rooms, col.speakers,
          col.median_minutes, col.with_video)
  .sort("year").collect
  .save("online.csv", "The editions of 2018-2026 (2021 and 2022 online), from editions.csv and events.csv; median_minutes of talks (keynotes, main track, devrooms, lightning).")

# ---------------------------------------------------------------- B. the devrooms

# A family is the same devroom under its names. Most renames only drop or add words, and the
# folded key already matches them; these are the ones that need a hand. First match wins.
const families = [
  (r"^mysql|mariadb", "mysql"),
  (r"^micro ?kernel", "microkernels"),
  (r"virtuali[sz]ation|^infrastructure as a service", "virtualization"),
  (r"^llvm", "llvm"),
  (r"^hpc", "hpc"),
  (r"^jabber|^xmpp|^real time communications|^telephony|^open source telephony", "rtc"),
  (r"java$|openjdk|classpath", "free java"),
  (r"openoffice|libreoffice|open document editors|^foss office", "office"),
  (r"^bsd$|^bsd illumos", "bsd"),
  (r"crossdesktop|^cross desktop|^desktops$", "crossdesktop"),
  (r"game development", "games"),
  (r"^config(uration)? (and |systems )*management|^infra management", "config"),
  (r"^testing and|^continuous integration|^test$", "testing"),
  (r"^collaborati", "collaboration"),
  (r"^open research", "open research"),
  (r"trusted computing|^confidential computing", "confidential"),
  (r"^erlang", "erlang"),
  (r"^amateur radio$", "amateur radio"),
  (r"radio", "radio"),
  (r"^monitoring", "monitoring"),
  (r"cad|open hardware", "hardware"),
  (r"^legal", "legal"),
  (r"^embedded$|^embedded and mobile|^embedded mobile", "embedded"),
  (r"^crossdistro|^cross ?distr", "distributions"),
  (r"^perl|^raku", "perl"),
  (r"^ruby", "ruby"),
  (r"^decentrali[sz]ed internet", "decentralized internet"),
  (r"^python", "python"),
  (r"^php", "php"),
  (r"^gnustep|^world of gnustep", "gnustep"),
  (r"^x org|^xorg", "x org"),
  (r"^gcc", "gcc"),
  (r"^matrix", "matrix"),
  (r"^energy", "energy"),
  (r"^emulator", "emulator"),
  (r"^foss on mobile", "foss on mobile"),
  (r"^image based linux", "image based linux"),
  (r"^software bill|^sboms", "sbom"),
  (r"^open source in the european|^open source eu policy", "eu policy"),
  (r"^apis", "apis"),
  (r"^educational|foss educational", "educational"),
  (r"^risc ?v", "risc v"),
  (r"^libre soc|vlsi", "fpga"),
  (r"^graph( |$)", "graph"),
  (r"^containers|^linux containers", "containers"),
  (r"^electronic design|^eda$", "eda"),
  (r"^wine", "wine"),
  (r"^open source search|^search$", "search"),
  (r"^backup", "backup"),
]

proc familyOf(key: Expr): Expr =
  var t = `when`(key.str.contains(families[0][0])).then(families[0][1])
  for (pat, fam) in families[1 .. ^1]:
    t = t.`when`(key.str.contains(pat)).then(fam)
  t.otherwise(key)

let rooms = rd("tracks.csv").filter(col.kind == "devroom")
  .withColumns(trackKey(col.track).alias("key"))
  .withColumns(familyOf(col.key).alias("family"))
  # one row per family and year: the busiest name of that year
  .sort(["family", "year", "events", "track"], descending = [false, false, true, false])
  .groupBy(col.family, col.year)
  .agg(col.track.first.alias("name"), col.events.sum.alias("events"),
       col.track.nUnique.alias("rooms_that_year"))
  .sort(["family", "year"])
  .withColumns(
    col.year.shift(1).over("family").alias("prev"),
    col.year.shift(-1).over("family").alias("next"),
    (col.year - col.year.rank(RankMethod.Ordinal).over("family").cast(Int64)).alias("run"),
  )
  .withColumns(choose(
      if col.prev.isNull: "new"
      elif col.prev == col.year - 1: "continuing"
      else: "back").alias("status"))
  .collect

# B1: the devrooms of 2027 and where they come from.
let byFamily = rooms.lazy.groupBy(col.family).agg(
    col.year.min.alias("first"), col.year.count.alias("editions"),
    col.name.filter(col.year == lastYear - 1).first.alias("name_last_year"),
    col.name.sortBy(col.year).last.alias("name"),
    col.name.unique.len.alias("names"),
  )
rooms.lazy.filter(col.year == lastYear)
  .join(byFamily, on = ["family"], how = JoinType.Left)
  .withColumns(choose(
      if col.status == "new": "new in 2027"
      elif col.status == "back": "back after a pause"
      elif col.first >= 2023: "since 2023 or later"
      elif col.first >= 2013: "since 2013–2022"
      else: "since before 2013").alias("group"),
    choose(if col.name_last_year.isNotNull and trackKey(col.name_last_year) != trackKey(col.name): col.name_last_year
           else: "").alias("was"))
  .join(rd("tracks.csv").filter(col.year == lastYear).select(col.track.alias("name"), col.cfp.fillNull("")),
        on = ["name"], how = JoinType.Left)
  .select(col.group, col.name.alias("devroom"), col.first, col.editions, col.was, col.cfp.fillNull(""))
  .sort(["first", "devroom"]).collect
  .save("devrooms_2027.csv", "The 78 devrooms accepted for FOSDEM 2027 and their history, from tracks.csv; a family is a devroom under its names (the renames matched in insights.nim).")

# B2: the devrooms that ran the most editions.
let streaks = rooms.lazy.groupBy(col.family, col.run).agg(len().alias("streak"))
  .groupBy(col.family).agg(col.streak.max.alias("longest_run"))
rooms.lazy.groupBy(col.family).agg(
    col.year.min.alias("first"), col.year.max.alias("last"), col.year.count.alias("editions"),
    col.events.sum.alias("talks"),
    col.name.sortBy(col.year).last.alias("devroom"),
    col.name.unique.sort.str.join("; ").alias("names"),
    col.name.nUnique.alias("n_names"),
  )
  .join(streaks, on = ["family"], how = JoinType.Left)
  .filter(col.editions >= 10)
  .withColumns((col.last == lastYear).alias("in_2027"))
  .sort(["editions", "first", "devroom"], descending = [true, false, false])
  .select(col.devroom, col.first, col.last, col.editions, col.longest_run, col.talks,
          col.n_names, col.names, col.in_2027)
  .collect
  .save("devrooms_longest.csv", "Devrooms held in ten editions or more, from tracks.csv: years, longest run of consecutive editions, talks, names.")

# B2b: the renames. A name folded to a key matches "Mozilla devroom" and "mozilla"; the families
# above join keys that differ. One row per family with more than one key: its names in order.
let raw = rd("tracks.csv").filter(col.kind == "devroom")
  .withColumns(trackKey(col.track).alias("key"))
  .withColumns(familyOf(col.key).alias("family"))
raw.sort(["family", "key", "year", "events", "track"], descending = [false, false, false, true, false])
  .groupBy(col.family, col.key)
  .agg(col.year.min.alias("from"), col.year.max.alias("to"), col.year.nUnique.alias("years"),
       col.track.last.str.replace(r"(?i)( dev ?room)+$", "").alias("name"))
  .withColumns(choose(
      if col("from") == col.to: format("{} ({})", col.name, col("from"))
      else: format("{} ({}–{})", col.name, col("from"), col.to)).alias("label"))
  .sort(["family", "from", "to", "key"])
  .groupBy(col.family)
  .agg(col.key.count.alias("keys"), col("from").min.alias("first"),
       col.label.str.join("; ").alias("names"),
       col.name.sortBy(col.to).last.alias("devroom"))
  .filter(col.keys > 1)
  .sort(["first", "devroom"])
  .select(col.devroom, col.first, col.keys, col.names)
  .collect
  .save("devroom_renames.csv", "Devrooms that ran under names that differ by more than case, punctuation or the word devroom, matched by the families of insights.nim: their names in order, with years, from tracks.csv.")

# B3: every year, how many devrooms were new, continued, came back, and did not come back.
rooms.lazy.withColumns(
    (col.next.isNull and col.year < lastYear).alias("last_time"))
  .groupBy(col.year).agg(
    len().alias("devrooms"),
    (col.status == "new").sum.alias("new"),
    (col.status == "continuing").sum.alias("continuing"),
    (col.status == "back").sum.alias("back"),
    col.last_time.sum.alias("last_time"))
  .withColumns(choose(if col.year < 2010: "2002–2009" elif col.year < 2020: "2010–2019" else: "2020–2027").alias("decade"))
  .select(col.decade, col.year, col.devrooms, col.new, col.continuing, col.back, col.last_time)
  .sort("year").collect
  .save("devroom_flow.csv", "Devrooms of each edition by where they come from (new, continuing from the year before, back after a pause) and how many never came back (last_time), from tracks.csv; 2002-2006 are partial, see README.md.")

# ---------------------------------------------------------------- C. the people

let speakers = rd("event_speakers.csv")
let people = rd("people.csv")

# C1: the keynotes. The opening talk of every edition is the first talk on Saturday in the main
# room (the room of the first talk of the day: A in 2001, Janson from 2002) that is not the
# welcome; online (2021, 2022), where the main room had only the welcome, the first talk of
# Saturday. From 2007 to 2025 the schedule marks the other keynotes too.
let saturday = events.filter(col.day == "Saturday" and col.kind.isIn(["keynote", "main track"]))
let mainRoom = saturday.sort(["year", "start", "room"]).groupBy(col.year)
  .agg(col.room.first.alias("main_room"))
let welcome = r"(?i)^(welcome|opening|introduction)( (talk|to fosdem( 20\d\d)?|and opening))?$|^(?i)welcome to fosdem"
let names = speakers.sort(["year", "event_id", "position"]).groupBy(col.year, col.event_id)
  .agg(col.person.str.join(", ").alias("by"))
let opening = saturday.join(mainRoom, on = ["year"]).filter(col.title.str.contains(welcome).not)
  .withColumns((col.room != col.main_room).alias("elsewhere"))
  .sort(["year", "elsewhere", "start", "room", "event_id"])
  .groupBy(col.year).agg(col.event_id.first)
  .withColumns(lit(true).alias("opening"))
let notKeynote = r"(?i)^(welcome|closing|donators return|the endgame)|highlights|quiz"
let others = events.filter(col.kind == "keynote" and col.title.str.contains(notKeynote).not)
  .join(names, on = ["year", "event_id"], how = JoinType.Left)
  .filter(col.by.isNotNull and col.by != "FOSDEM" and col.by != "FOSDEM Staff")
  .select(col.year, col.event_id)
concat([opening.select(col.year, col.event_id), others])
  .unique(["year", "event_id"], keep = UniqueKeepStrategy.First, maintainOrder = true)
  .join(events, on = ["year", "event_id"])
  .join(names, on = ["year", "event_id"], how = JoinType.Left)
  .join(opening, on = ["year", "event_id"], how = JoinType.Left)
  .withColumns(col.opening.fillNull(false), col.by.fillNull(""),
               choose(if col.day == "Saturday": 1 else: 2).alias("d"))
  .sort(["year", "opening", "d", "start", "event_id"], descending = [false, true, false, false, false])
  .withColumns(choose(if col.url == "": format("https://archive.fosdem.org/{}/", col.year) else: col.url).alias("url"))
  .select(col.year, col.opening, col.day, col.start, col.title, col.by, col.room, col.url, col.video)
  .collect
  .save("keynotes.csv", "The keynotes of every edition: the opening talk (first talk on Saturday in the main room after the welcome) of every year, and the other keynotes the schedule marks (2007-2025), without the welcome, closing and quiz; with links to each talk's page and video, from events.csv and event_speakers.csv.")

# C2: the people who spoke at the most editions.
people.filter(col.is_person)
  .sort(["editions", "talks", "person"], descending = [true, true, false]).head(15)
  .select(col.person, col.first_year, col.last_year, col.editions, col.talks, col.keynotes,
          col.main_track_talks, col.devroom_talks)
  .collect
  .save("speakers_top.csv", "The 15 people who spoke at the most FOSDEM editions, from people.csv.")

# C3: new faces, every year; and how many devroom calls came from someone who also spoke.
let cfp = rd("cfp_posts.csv").filter(col.kind == "devroom cfp")
  .groupBy(col.edition.alias("year")).agg(len().alias("cfp_posts"), col.sender_spoke.sum.alias("cfp_by_speaker"))
editions.filter(col.year >= 2007 and col.year <= lastHeld)
  .join(cfp, on = ["year"], how = JoinType.Left)
  .withColumns(
    (col.first_time_speakers / col.speakers).alias("first_time_share"),
    (col.speakers - col.first_time_speakers).alias("returning"),
    col.cfp_posts.fillNull(0), col.cfp_by_speaker.fillNull(0))
  .withColumns(choose(if col.year < 2010: "2007–2009" elif col.year < 2020: "2010–2019" else: "2020–2026").alias("decade"))
  .select(col.decade, col.year, col.speakers, col.first_time_speakers, col.returning,
          col.first_time_share, col.cfp_posts, col.cfp_by_speaker)
  .sort("year").collect
  .save("newcomers.csv", "Speakers of every edition from 2007 (the first with full main tracks and devroom pages), how many spoke for the first time, and the devroom calls posted to the fosdem@ list, from editions.csv, people.csv and cfp_posts.csv.")

# ---------------------------------------------------------------- D. Nim at FOSDEM

# Talks about Nim: the title says so, or the Nim devroom of 2022. Talks found in the abstracts
# of the schedule (2012-2026) are read and sorted by hand: about Nim, or about a project built
# with Nim. Talks that only name Nim in a list of languages are left out.
const nimByHand = [
  (2021, "11334", "about Nim"),          # Optimising for humans: Nim on micro-controllers
  (2019, "8698", "built with Nim"),      # Nimbus, Status' Ethereum client
  (2024, "2877", "built with Nim"),      # Chalk, by Crash Override
  (2025, "5848", "uses Nim"),            # transpiling to C with Nim and prescheme
]
let byHand = newDataFrame(series("year", nimByHand.mapIt(it[0])), series("event_id", nimByHand.mapIt(it[1])),
                         series("how", nimByHand.mapIt(it[2]))).lazy
let nimTalks = events
  .join(byHand, on = ["year", "event_id"], how = JoinType.Left)
  .filter(col.how.isNotNull or col.title.str.contains(r"\bNim\b") or col.track == "Nim Programming Language")
  .withColumns(col.how.fillNull("about Nim"))
  .join(names, on = ["year", "event_id"], how = JoinType.Left)
  .select(col.year, col.kind, col.track, col.title, col.by.fillNull(""), col.how, col.url, col.video)
let nimStand = rd("stands.csv").filter(col.stand_key == "nim")
  .select(col.year, lit("stand").alias("kind"), col.building.alias("track"), lit("Nim").alias("title"),
          lit("").alias("by"), lit("stand").alias("how"),
          format("https://archive.fosdem.org/{}/stands/", col.year).alias("url"), lit("").alias("video"))
concat([nimTalks, nimStand], how = ConcatMethod.VerticalRelaxed)
  .sort(["year", "kind", "track", "title"]).collect
  .save("nim.csv", "Nim at FOSDEM: talks about Nim or about projects built with it (titles, the 2022 Nim devroom, and abstracts read by hand), and the Nim stand, from events.csv, event_speakers.csv and stands.csv.")

# A. the stands: how many every year, and the projects with a stand in the most editions.
let stands = rd("stands.csv")
stands.groupBy(col.year).agg(len().alias("stands")).sort("year").collect
  .save("stands_by_year.csv", "Stands of every edition from 2008, from stands.csv.")
stands.sort(["stand_key", "year"]).groupBy(col.stand_key)
  .agg(col.stand.last.alias("stand"), col.year.nUnique.alias("editions"),
       col.year.min.alias("first"), col.year.max.alias("last"))
  .sort(["editions", "first", "stand"], descending = [true, false, false]).head(12)
  .select(col.stand, col.first, col.last, col.editions).collect
  .save("stands_top.csv", "The stands present at the most editions (2008-2026), by name folded to a key, from stands.csv.")

What nanuq did well, and where it pinched

This was nanuq's first long job, and it went well: about 420 lines make the ten tables, 330 more the story's small ones, and both run in a fraction of a second. Writing it also found a few rough edges, which are nanuq's to-do list now:

nanuq, after its first long job
what made the work easy, and what got in the way
did well
lazy framesread, join and group, collect once; fast enough to rerun on every change
choosean if/elif chain that is one expression: 25 years of vocabulary in one place
expressions in procsnameKey, minutesOf, hhmm: written once, used on any column
str and regexUnicode NFKD, replaceAll, extract: the Polars string namespace, all there
concatvertical relaxed and diagonal relaxed: five sources with different columns stack
same outputwith explicit sorts, two runs write the same files, byte for byte
pinched
col.typetype is a Nim keyword: a long type-mismatch error; col("type") works
col["end"]not supported; col("end") works, and newDataFrame wants "end" quoted
coalescethe join wants some(true), not true
writeCsvno comment option: the # line is added after
errorsColumnNotFoundError comes with an empty message
row orderjoins reorder rows: ids made after a join changed between runs
type Note = object
  what, how: string
let good = @[
  Note(what: "lazy frames", how: "read, join and group, collect once; fast enough to rerun on every change"),
  Note(what: "choose", how: "an if/elif chain that is one expression: 25 years of vocabulary in one place"),
  Note(what: "expressions in procs", how: "nameKey, minutesOf, hhmm: written once, used on any column"),
  Note(what: "str and regex", how: "Unicode NFKD, replaceAll, extract: the Polars string namespace, all there"),
  Note(what: "concat", how: "vertical relaxed and diagonal relaxed: five sources with different columns stack"),
  Note(what: "same output", how: "with explicit sorts, two runs write the same files, byte for byte")]
let pinch = @[
  Note(what: "col.type", how: "type is a Nim keyword: a long type-mismatch error; col(\"type\") works"),
  Note(what: "col[\"end\"]", how: "not supported; col(\"end\") works, and newDataFrame wants \"end\" quoted"),
  Note(what: "coalesce", how: "the join wants some(true), not true"),
  Note(what: "writeCsv", how: "no comment option: the # line is added after"),
  Note(what: "errors", how: "ColumnNotFoundError comes with an empty message"),
  Note(what: "row order", how: "joins reorder rows: ids made after a join changed between runs")]
type Line = object
  side, what, how: string
var rows: seq[Line]
for n in good: rows.add Line(side: "did well", what: n.what, how: n.how)
for n in pinch: rows.add Line(side: "pinched", what: n.what, how: n.how)
let t = tabella(rows, rownameCol = "what", groupnameCol = "side"):
  optCssTheme()
  tabHeader "nanuq, after its first long job", "what made the work easy, and what got in the way"
  colsLabel {"what": "", "how": ""}
nbTable t

None of the pinches stopped the work, and each has a workaround in process.nim. The last one is the only one that could have gone unnoticed: Polars does not keep the row order of a join unless asked, so numbering rows after a join gave different ids on different runs. Numbering before the join, and sorting before every write, fixed it.

The ten tables

What nanuq writes: ten CSV files in docs/stories/data/fosdem/, each with a first # line naming its sources, so tabelline's readCsv(path, comment = "#") reads it as it is.

Ten tables
the files nanuq writes
yearsrowscolumns
the schedule
editions2001–20272720
tracks2002–20271,21013
rooms2001–20266925
events2001–202612,68619
event_speakers2001–202614,5665
people2001–20267,55911
the calls
cfp_listings2013–20266697
cfp_posts2007–20277349
mailing_list_years2006–2026215
the floor
stands2008–20269955
type FileRow = object
  group, file, years: string
  rows, columns: int
let groups = {"editions": "the schedule", "tracks": "the schedule", "rooms": "the schedule",
              "events": "the schedule", "event_speakers": "the schedule", "people": "the schedule",
              "cfp_listings": "the calls", "cfp_posts": "the calls", "mailing_list_years": "the calls",
              "stands": "the floor"}.toTable
var rows: seq[FileRow]
for n in names:
  let rs = data[n]
  var years = ""
  for key in ["year", "edition", "first_year"]:
    if key in rs[0]:
      let ys = rs.mapIt(it[key]).filterIt(it.len >= 4).mapIt(it[0..3].parseInt)
      years = $ys.min & "–" & $ys.max
      break
  rows.add FileRow(group: groups[n], file: n, years: years, rows: rs.len, columns: rs[0].len)
let t = tabella(rows, rownameCol = "file", groupnameCol = "group"):
  optCssTheme()
  tabHeader "Ten tables", "the files nanuq writes"
  colsLabel {"file": ""}
  fmtInteger ["rows", "columns"]
nbTable t

And every column, with what it means and how often it is filled:

Every column
what it means, and how often it is filled
meaningfilled
editions
yearthe edition's year (the key)100%
editionits number: 1 for OSDEM 2001, 27 for 2027100%
nameOSDEM or FOSDEM100%
startfirst day100%
endlast day100%
formatin person or online100%
venuethe ULB, or Online100%
cityBrussels92%
eventsevents in the schedule96%
keynotesevents of kind keynote96%
main_track_talksevents of kind main track96%
devroom_talksevents of kind devroom96%
lightning_talksevents of kind lightning talk96%
devroomstracks of kind devroom100%
roomsrooms with at least one event96%
speakersdistinct people who spoke96%
first_time_speakerspeople whose first year is this one96%
events_with_videoevents with a recording96%
coveragehow complete the year's schedule is100%
sourcesthe raw formats the year's events come from96%
tracks
yearthe edition100%
trackthe track or devroom's name that year100%
kinddevroom, main track, keynote, lightning talk, ...100%
site_groupthe site's group above the track, like Developer rooms62%
eventsits events100%
speaker_slotsits speakers summed over events100%
events_with_videoits events with a recording100%
roomsthe rooms it used89%
capacitythe room's seats, where listed (2007–2010)5%
daysthe days it ran91%
cfpits call for participation59%
cfp_deadlinethe call's deadline (2013–2020)24%
listed_onwhere a devroom without talks is listed16%
rooms
yearthe edition100%
roomthe room's name that year100%
eventsevents held there100%
trackstracks that used it100%
scheduled_minutesminutes of scheduled events100%
events
yearthe edition100%
event_idthe schedule's id: unique within a year, with year100%
kindkeynote, main track, devroom, lightning talk, BOF, stand, ...100%
trackthe track or devroom98%
titlethe title100%
subtitlethe subtitle29%
daySaturday, Sunday (Friday for a few)100%
startstart time100%
endend time99%
duration_minminutes99%
roomthe room96%
speakershow many speakers100%
languagethe talk's language, from 201224%
videosrecordings linked100%
slidesslides linked100%
source_typethe schedule's own type94%
sourcethe raw format it comes from100%
urlits page on archive.fosdem.org96%
videoits first recording (MP4 if there is one)70%
event_speakers
yearthe edition100%
event_idthe event (with year)100%
positionorder among the event's speakers100%
personthe name as printed100%
person_keythe folded name that matches across years100%
people
personthe name as last printed100%
person_keythe folded name (the key)100%
is_personfalse for FOSDEM Staff, teams, panels100%
first_yearfirst year spoken100%
last_yearlast year spoken100%
editionsyears spoken100%
talksevents spoken at100%
keynotesof which keynotes100%
main_track_talksof which main track100%
devroom_talksof which in a devroom100%
yearsthe years100%
cfp_listings
yearthe edition100%
devroomthe devroom's name as listed100%
daythe day it was given (2013–2020)48%
announcementthe call's link99%
deadlinethe call's deadline46%
first_listedwhen the website first listed it48%
sourcethe website's YAML, or the track page100%
cfp_posts
editionthe edition the post is for100%
datedate posted100%
kinddevroom cfp, fosdem call or other cfp100%
devroom_from_subjectthe devroom read from the subject89%
subjectthe subject100%
senderthe sender's name (no address)100%
sender_keythe folded name100%
sender_spokewhether the sender spoke that year100%
pretalx_linkthe first pretalx link in the post62%
mailing_list_years
yearthe year100%
messagesmessages100%
threadsfirst posts100%
sendersdistinct senders100%
cfp_postscalls posted100%
stands
yearthe edition100%
standthe stand as listed100%
stand_keythe folded name100%
buildingits building, from 201388%
themeits theme, 202627%
type Col = object
  table, column, meaning, filled: string
var rows: seq[Col]
for c in load(fosdem / "columns.csv"):
  let rs = data[c["table"]]
  let full = rs.countIt(it[c["column"]] != "")
  rows.add Col(table: c["table"], column: c["column"], meaning: c["meaning"],
               filled: $(full * 100 div rs.len) & "%")
let t = tabella(rows, rownameCol = "column", groupnameCol = "table"):
  optCssTheme()
  tabHeader "Every column", "what it means, and how often it is filled"
  tabOptions(tableFontSize = "13px")
  colsLabel {"column": ""}
  colsAlign alRight, ["filled"]
nbTable t

How they join

The tables are tidy: one row per thing, a key per table, and the other tables point to it. The checks below found two things while this story was written. The first: the key of an event is its year and its id, because the XML export numbers events per year, so id 2411 is a talk in 2014 and another in 2025. The second: one speaker of 2026, whose name is written in Chinese, had an empty key, because the first nameKey kept only the letters a to z. It also turned ø, ł and ß into spaces, so Helge Heß and Helge Hess were two people. The key above is the fixed one, and the data was made again: 7,559 people instead of 7,561, and one first-time speaker fewer in 2009 and in 2026.

Checked
run on the ten tables every time this page is built
rowswrong
each key is unique
editions: year270
tracks: year, track1,2100
rooms: year, room6920
events: year, event_id12,6860
event_speakers: year, event_id, position14,5660
people: person_key7,5590
stands: year, stand9950
every pointer finds its row
event_speakers → events14,5660
event_speakers → people14,5660
events → tracks12,4990
events → rooms12,2670
events → editions12,6860
cfp_posts → editions7340
stands → editions9950
every count agrees
editions.events = its events260
events.speakers = its speakers12,6860
tracks.events = its events1,2100
rooms.events = its events6920
mailing_list_years.cfp_posts = the posts210
every value makes sense
editions start on a Saturday270
events end after they start12,6430
people: first year ≤ last year7,5590
type Check = object
  group, check: string
  rows, wrong: int
var rows: seq[Check]
proc add(group, check: string, total, bad: int) =
  rows.add Check(group: group, check: check, rows: total, wrong: bad)
proc keyOf(r: Row, cols: openArray[string]): string = cols.mapIt(r[it]).join("|")
proc dupes(t: string, cols: openArray[string]) =
  var seen: HashSet[string]
  var bad = 0
  for r in data[t]:
    let k = r.keyOf(cols)
    if k in seen: inc bad else: seen.incl k
  add("each key is unique", t & ": " & cols.join(", "), data[t].len, bad)
dupes("editions", ["year"])
dupes("tracks", ["year", "track"])
dupes("rooms", ["year", "room"])
dupes("events", ["year", "event_id"])
dupes("event_speakers", ["year", "event_id", "position"])
dupes("people", ["person_key"])
dupes("stands", ["year", "stand"])
proc points(t, to: string, cols: openArray[string], toCols: openArray[string] = []) =
  let tc = if toCols.len > 0: @toCols else: @cols
  let keys = data[to].mapIt(it.keyOf(tc)).toHashSet
  var rs: seq[Row]
  for r in data[t]:
    if cols.allIt(r[it] != ""): rs.add r
  add("every pointer finds its row", t & " → " & to, rs.len, rs.countIt(it.keyOf(cols) notin keys))
points("event_speakers", "events", ["year", "event_id"])
points("event_speakers", "people", ["person_key"])
points("events", "tracks", ["year", "track"])
points("events", "rooms", ["year", "room"])
points("events", "editions", ["year"])
points("cfp_posts", "editions", ["edition"], ["year"])
points("stands", "editions", ["year"])
proc agrees(t, col, what: string, counted: CountTable[string], cols: openArray[string]) =
  let rs = data[t].filterIt(it[col] != "")
  add("every count agrees", what, rs.len, rs.countIt(it[col].parseInt != counted[it.keyOf(cols)]))
var perYear, perEvent, perTrack, perRoom, perPostYear: CountTable[string]
for e in ev:
  perYear.inc e["year"]
  if e["track"] != "": perTrack.inc e.keyOf(["year", "track"])
  if e["room"] != "": perRoom.inc e.keyOf(["year", "room"])
for s in data["event_speakers"]: perEvent.inc s.keyOf(["year", "event_id"])
for p in data["cfp_posts"]: perPostYear.inc p["date"][0..3]
agrees("editions", "events", "editions.events = its events", perYear, ["year"])
agrees("events", "speakers", "events.speakers = its speakers", perEvent, ["year", "event_id"])
agrees("tracks", "events", "tracks.events = its events", perTrack, ["year", "track"])
agrees("rooms", "events", "rooms.events = its events", perRoom, ["year", "room"])
agrees("mailing_list_years", "cfp_posts", "mailing_list_years.cfp_posts = the posts", perPostYear, ["year"])
let eds = data["editions"]
add("every value makes sense", "editions start on a Saturday", eds.len,
    eds.countIt(it["start"].parse("yyyy-MM-dd").weekday != dSat))
let timed = ev.filterIt(it["start"] != "" and it["end"] != "")
add("every value makes sense", "events end after they start", timed.len,
    timed.countIt(it["start"] >= it["end"]))
add("every value makes sense", "people: first year ≤ last year", data["people"].len,
    data["people"].countIt(it["first_year"] > it["last_year"]))
let t = tabella(rows, rownameCol = "check", groupnameCol = "group"):
  optCssTheme()
  tabHeader "Checked", "run on the ten tables every time this page is built"
  tabOptions(tableFontSize = "14px")
  colsLabel {"check": "", "rows": "rows", "wrong": "wrong"}
  fmtInteger ["rows", "wrong"]
nbTable t

Zero everywhere: the tables hold together. They also agree with themselves across files that nanuq wrote separately, which is the best sign that nothing was lost between the steps. What the checks cannot see is what FOSDEM's old sites never had: the schedules are complete from 2011, partial before (the story marks those years), and there is no list of who organised a devroom.

How this story is built

The story reads the ten CSV files with Nim's parsecsv, as rows of strings, and makes every table and check from them with tabelline: no nanuq is needed to build the site. The nanuq code above is read from src/process.nim when the page is built, so it is the code that made the data. To make the data again, from the raw files:

sh src/fetch.sh raw                   # about 200 MB from archive.fosdem.org and friends
sh src/build.sh raw <nanuq checkout>  # Nim flattens, nanuq makes the tables