1 # hair Makefile. One file, no support code. Temps in $(Tmp); html 2 # into $(Root)/docs. "make" = help. "make it=f" edits f in nvim. 3 # Every repo path is spelled $(Root)/..., so sub-directories can 4 # reuse all of this with a one-line Makefile: include ../Makefile 5 # Long payloads live at the end as comment blocks #<name> ... 6 # #</name>; make greps its own source to build them (see mark). 7 # Inside a block, text is verbatim (no $$ doubling): {Tmp} and 8 # {Here} (the repo root) are filled in by sed at extraction time. 9 SHELL := bash 10 .SHELLFLAGS := -o pipefail -ec # a dead gawk must kill the pipe 11 .DELETE_ON_ERROR: # failed recipes leave no corpses 12 MAKEFLAGS += --no-print-directory 13 .SILENT: 14 # no __pycache__ litter, here or in `make sh` 15 export PYTHONDONTWRITEBYTECODE := 1 16 Tmp ?= $(HOME)/tmp/hair 17 it ?= 18 cols ?= 6 19 Root := $(shell git rev-parse --show-toplevel) 20 21 ifeq ($(it),) 22 .DEFAULT_GOAL := help 23 else 24 .DEFAULT_GOAL := edit 25 endif 26 27 Need = gawk nvim git python3 sed tail basename mkdir 28 29 deps: ## complain about any missing tools, else silence 30 miss=""; for c in $(Need); do command -v $$c >/dev/null || \ 31 miss="$$miss $$c"; done; \ 32 [ -z "$$miss" ] || { echo "missing:$$miss"; \ 33 echo "try: sudo apt install -y gawk neovim (or brew install)"; \ 34 exit 1; } 35 36 help: deps $(Tmp)/help.awk ## show this help 37 gawk -f $(Tmp)/help.awk $(Root)/Makefile 38 39 pull: ## update from main 40 git pull 41 42 push: ## save to main 43 echo -en "\033[33mWhy this push? \033[0m"; read x; \ 44 git commit -am "$$x"; git push; git status 45 46 clean: ## remove build litter: dist/ build/ *.egg-info __pycache__ 47 cd $(Root); rm -rf dist build *.egg-info; \ 48 find . -name __pycache__ -type d -prune -exec rm -rf {} +; \ 49 find . -name '*.pyc' -delete; echo "cleaned" 50 51 dist: clean ## build wheel + sdist into dist/ (and check them) 52 cd $(Root); rm -rf dist build *.egg-info; \ 53 python3 -m pip install -q --upgrade build twine; \ 54 python3 -m build; python3 -m twine check dist/* 55 56 testpypi: dist ## upload to TestPyPI (practice index; needs a test.pypi token) 57 python3 -m twine upload --repository testpypi $(Root)/dist/* 58 59 pypi: dist ## upload to the REAL PyPI (run testpypi first; asks y/N) 60 echo -en "\033[31mReally upload to real PyPI? [y/N] \033[0m"; read x; \ 61 [ "$$x" = y ] && python3 -m twine upload --verbose $(Root)/dist/* || echo "skipped" 62 63 edit: $(Tmp)/init.lua ## edit $(it) in nvim (use: make it=file) 64 nvim --clean -u $(Tmp)/init.lua -i $(Tmp)/shada $(it) 65 66 serve: ## serve docs/ at http://localhost:8000 67 cd $(Root)/docs && python3 -m http.server 68 69 sh: $(Tmp)/bashrc $(Tmp)/init.lua ## bash with our prompt and aliases 70 bash --rcfile $(Tmp)/bashrc -i 71 72 $(Tmp): 73 mkdir -p $(Tmp)/undo $(Tmp)/swap $(Tmp)/backup 74 75 #-- config files --------------------------------------------------- 76 H := \# 77 mark = gawk -v RS= 'index($$0,"$(H)<$(1)>")==1' $(Root)/Makefile | tail -n +2 \ 78 | sed -e 's/^$(H) \{0,1\}//' -e 's|{Tmp}|$(Tmp)|g' \ 79 -e 's|{Here}|$(Root)|g' -e 's|{Name}|$(notdir $(Root))|g' 80 81 $(Tmp)/help.awk: $(Root)/Makefile | $(Tmp) ; $(call mark,help.awk) > $@ 82 $(Tmp)/init.lua: $(Root)/Makefile | $(Tmp) ; $(call mark,init.lua) > $@ 83 $(Tmp)/bashrc: $(Root)/Makefile | $(Tmp) ; $(call mark,bashrc) > $@ 84 $(Tmp)/hi.py : $(Root)/Makefile | $(Tmp) ; $(call mark,hi.py) > $@ 85 $(Tmp)/loc.py : $(Root)/Makefile | $(Tmp) ; $(call mark,loc.py) > $@ 86 .gitignore: $(Root)/Makefile ; $(call mark,gitignore) > $(Root)/$@ 87 LICENSE.md: $(Root)/Makefile ; $(call mark,license) > $(Root)/$@ 88 89 #-- examples --------------------------------------------------- 90 # hair.py is the library; each eg/*.py is one small example of it 91 loc: $(Tmp)/loc.py ## lines of code in hair/ and each eg/ file 92 cd $(Root) && python3 $(Tmp)/loc.py hair/*.py eg/*.py 93 94 #-- website --------------------------------------------------- 95 # used in publish: a parentless commit of scratch index last staged 96 snap = $$(git commit-tree $$(git write-tree) -m publish) 97 98 # one <li> link per non-empty file in $(1) (href = basename.html) 99 links = for f in $(1); do [ -s "$$f" ] || continue; \ 100 b=$$(basename $$f); \ 101 echo "<li><a href=\"$$b.html\">$$b</a></li>"; done 102 103 # emit the index page (header, Sources, Examples, lines-of-code, footer) 104 # to stdout; the caller redirects it. The {} group all the echoes so a 105 # single external redirect captures them. Plain `=` (not `define`) so 106 # there is no trailing newline to break `$(INDEX) > file`. 107 INDEX = { $(call mark,index.top); \ 108 $(call mark,index.why); \ 109 echo "<b>Sources</b><ul>"; $(call links,$(Root)/hair/*.py Makefile); \ 110 echo "</ul><b>Examples</b><ul>"; $(call links,$(Root)/eg/*.py); \ 111 echo "</ul><b>Lines of code</b><pre style=\"font-size:9pt\">"; \ 112 (cd $(Root) && python3 $(Tmp)/loc.py hair/*.py eg/*.py); echo "</pre>"; \ 113 $(call mark,index.bot); } 114 115 publish: $(Tmp)/hi.py $(Tmp)/loc.py ## render all sources to docs/, push to gh-pages 116 cd $(Root) && for f in hair/*.py eg/*.py Makefile; do \ 117 [ -s "$$f" ] && $(MAKE) hi it=$$f; done # -s: skip empty __init__ 118 $(INDEX) > $(Root)/docs/index.html 119 cd $(Root); export GIT_INDEX_FILE=$(Tmp)/pubindex; \ 120 git --work-tree=docs add -A . && \ 121 git push -q -f origin $(snap):refs/heads/gh-pages 122 echo "https://timm.github.io/hair/" 123 124 #-- highlight --------------------------------------------------- 125 # render source as tiny-type, n-column, colored html. hi.py picks 126 # the syntax faces from the file's suffix, so there is nothing to 127 # pass but cols and the file itself. 128 129 page = $(Root)/docs/$(notdir $(it)).html 130 131 hi: $(page) ## render $(it) as colored html into docs/ 132 $(page): $(it) $(Tmp)/hi.py 133 python3 $(Tmp)/hi.py $(cols) $< > $@ 134 135 #-- payloads: comment blocks, extracted by `mark` --------------- 136 # a block is one blank-line-delimited paragraph starting 137 # "#<name>" (awk RS= reads paragraphs; one condition selects) 138 139 # ────────────────────────────────────────────────────────────── 140 141 #<index.bot> 142 # <b>Problems</b><br> 143 # <a href="https://github.com/timm/{Name}/issues">raise an issue</a> 144 # <p> 145 # <b>License</b><br> 146 # <a href="https://github.com/timm/{Name}/blob/main/LICENSE.md">(c) 2026</a> 147 # by <a href="https://timm.fyi">timm</a>. 148 # Share and enjoy. 149 # </span></td></tr></table></center> 150 # <p> 151 # <center> 152 # <a href="https://github.com/timm/{Name}"><img src="img/gh.svg?v=5" alt="github"></a> 153 # <a href="https://www.csc.ncsu.edu"><img src="img/ncsu.svg?v=5" alt="NC State Computer Science"></a> 154 # </center> 155 156 # ────────────────────────────────────────────────────────────── 157 158 #<index.top> 159 # <meta charset=utf-8><title>timm / {Name}</title> 160 # <meta name=viewport content="width=device-width,initial-scale=1"> 161 # <body style="margin:0;padding:2em 16px;"> 162 # <center><h1 style="font-weight:normal;font-family:'Times New Roman',Times,serif">hair : hands-on AI recipes</h1></center> 163 # <p> 164 # <center><table cellspacing=0 cellpadding=0 border=0> 165 # <tr><td align="left"><span style="font-size:12pt"> 166 167 # ────────────────────────────────────────────────────────────── 168 169 170 # ────────────────────────────────────────────────────────────── 171 172 #<index.why> 173 # <center><div style="max-width:600px;text-align:left;font-size:11pt"> 174 # <center><img src="img/hair.png" width=230 alt="hair"></center> 175 # <p>Do stakeholdes want classification, regression, or 176 # optimization? In my experience, they ask all sorts of quirky questions 177 # like "which of these is risky?", "what should 178 # we try next?", "is this one weird?. Then they leave you to turn that 179 # into code. 180 # <p>Here's the good news: all thise things 181 # they ask you to do often share parts (distances between rows; 182 # summaries of columns; splits; a little statistics, etc). And 183 # once they build 184 # those parts once and the next task arrives half-written. > 185 # <svg width="205" height="130" style="float:right;margin:.8em 0 .6em 1.2em" 186 # role="img" aria-label="new lines of code per new task, falling"> 187 # <text x="0" y="20" font-size="11" fill="#555">new lines</text> 188 # <line x1="26" y1="22" x2="26" y2="96" stroke="#bbb"/> 189 # <line x1="26" y1="96" x2="200" y2="96" stroke="#bbb"/> 190 # <polyline fill="none" stroke="#0969da" stroke-width="2" 191 # points="28,24 46,60 64,71 83,76 101,79 119,81 137,82 155,83 174,84 192,85"/> 192 # <text x="28" y="110" font-size="9" fill="#555" text-anchor="middle">1</text> 193 # <text x="46" y="110" font-size="9" fill="#555" text-anchor="middle">2</text> 194 # <text x="64" y="110" font-size="9" fill="#555" text-anchor="middle">3</text> 195 # <text x="83" y="110" font-size="9" fill="#555" text-anchor="middle">4</text> 196 # <text x="101" y="110" font-size="9" fill="#555" text-anchor="middle">5</text> 197 # <text x="119" y="110" font-size="9" fill="#555" text-anchor="middle">6</text> 198 # <text x="137" y="110" font-size="9" fill="#555" text-anchor="middle">7</text> 199 # <text x="155" y="110" font-size="9" fill="#555" text-anchor="middle">8</text> 200 # <text x="174" y="110" font-size="9" fill="#555" text-anchor="middle">9</text> 201 # <text x="192" y="110" font-size="9" fill="#555" text-anchor="middle">10</text> 202 # <text x="110" y="126" font-size="11" fill="#555" text-anchor="middle">task</text> 203 # </svg> 204 # <p>I call this 205 # the 206 # <b>hair</b> heuristic: <b>H</b>alf <b>A</b>lready <b>I</b>mplemented 207 # (making <b>R</b>euse easy); i.e. after many tasks, task+1 takes nearly 208 # no effort. 209 # <p>Now compare this to asking an LLM for an AI workbench: you get code too big 210 # to understand, trust, or change safely, where each change calls 211 # for more code, which calls for more changes. That recursive 212 # explosion is AI slop. <p>Small code is an antidote to AI slop: easy to 213 # read, trust, change and teach; little to install or attack; and 214 # likely to outlive the frameworks it never used. 215 # </div></center> 216 # <p style="clear:both"> 217 218 219 # ────────────────────────────────────────────────────────────── 220 221 #<help.awk> 222 # # pretty help: targets with trailing ## comments. The target 223 # # lines go through an output pipe (awk can print into a shell 224 # # command!); close() flushes it so the footer prints last. 225 # BEGIN {FS=":.*##" 226 # print "\n\033[1mmake\033[0m [\033[36mWHAT\033[0m]\n"} 227 # /^[a-z.]+:.*##/ {printf " make \033[36m%-8s\033[0m %s\n", $1, $2 | "sort"} 228 # END { print " make \033[36mit=F\033[0m edit file F in nvim\n"} 229 230 # ────────────────────────────────────────────────────────────── 231 232 #<init.lua> 233 # -- generated by Makefile; edit there, not here 234 # vim.opt.expandtab = true 235 # vim.opt.shiftwidth = 2 236 # vim.opt.tabstop = 2 237 # vim.opt.number = true 238 # vim.opt.wrap = false 239 # vim.opt.ignorecase = true 240 # vim.opt.smartcase = true 241 # vim.opt.colorcolumn = "75" 242 # vim.opt.clipboard = "unnamedplus" -- yank <-> system clipboard 243 # vim.opt.hlsearch = true 244 # vim.opt.undofile = true 245 # vim.opt.undodir = "{Tmp}/undo" 246 # vim.opt.directory = "{Tmp}/swap" 247 # vim.opt.backupdir = "{Tmp}/backup" 248 # vim.opt.statusline = "%f %m %r %=%l:%c" 249 # vim.cmd [[autocmd BufReadPost * silent! normal! g`"]] 250 # vim.cmd [[syntax on]] 251 # vim.cmd [[colorscheme lunaperche]] 252 253 # ────────────────────────────────────────────────────────────── 254 255 #<license> 256 # # MIT License 257 # 258 # Copyright (c) 2026 Tim Menzies <timm@ieee.org> 259 # 260 # Permission is hereby granted, free of charge, to any person obtaining a 261 # copy of this software and associated documentation files (the 262 # "Software"), to deal in the Software without restriction, including 263 # without limitation the rights to use, copy, modify, merge, publish, 264 # distribute, sublicense, and/or sell copies of the Software, and to 265 # permit persons to whom the Software is furnished to do so, subject to 266 # the following conditions: 267 # 268 # The above copyright notice and this permission notice shall be 269 # included in all copies or substantial portions of the Software. 270 # 271 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 272 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 273 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 274 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 275 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 276 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 277 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 278 # SOFTWARE. 279 280 # 281 # ────────────────────────────────────────────────────────────── 282 283 #<gitignore> 284 # # generated html stays out of main (published via gh-pages) 285 # docs/*.html 286 # # python 287 # __pycache__/ 288 # *.py[cod] 289 # *.egg-info/ 290 # .venv/ 291 # venv/ 292 # build/ 293 # dist/ 294 # .pytest_cache/ 295 # .mypy_cache/ 296 # .ruff_cache/ 297 # .coverage 298 # .ipynb_checkpoints/ 299 # # nvim / vim 300 # *.swp 301 # *.swo 302 # *~ 303 # .netrwhist 304 # Session.vim 305 # .nvimlog 306 # # lua 307 # luac.out 308 # *.rock 309 # lua_modules/ 310 # .luarocks/ 311 # # os 312 # .DS_Store 313 314 # ────────────────────────────────────────────────────────────── 315 316 #<bashrc> 317 # # generated by Makefile; edit there, not here 318 # export HISTFILE={Tmp}/bash_history 319 # export EDITOR="nvim --clean -u {Tmp}/init.lua -i {Tmp}/shada" 320 # alias ls="ls -G" 321 # alias vi='$EDITOR' 322 # alias gs="git status -sb" 323 # alias gl="git log --oneline --graph -12" 324 # alias gd="git diff --stat" 325 # alias ..="cd .." 326 # alias ...="cd ../.." 327 # alias root='cd "$(git rev-parse --show-toplevel)"' 328 # alias serve="python3 -m http.server" 329 # mk() { mkdir -p "$1" && cd "$1"; } # make dir and enter it 330 # h() { history | grep -i "$1" | tail; } # search own history 331 # f() { grep -rniI --exclude-dir=.git "$1" .; } # find text here 332 # # every ## make rule is a command here: argless ones as aliases 333 # # (parsed live from the Makefile, so new rules auto-appear); 334 # # file-taking ones as functions; sh excluded (shadows /bin/sh) 335 # for t in $(gawk -F: '/^[a-z]+:.*##/ && !/^(sh|edit|hi):/ {print $1}' {Here}/Makefile); do 336 # alias $t="make -C {Here} $t" 337 # done 338 # edit() { make -C {Here} edit it="$1"; } 339 # hi() { make -C {Here} hi it="$1" cols="${2:-3}"; } 340 # export HISTCONTROL=ignoredups 341 # export COL='grep --line-buffered --color=always -E [0-9.]*!|$' # |$COL 342 # shopt -s autocd 2>/dev/null # bare dir name = cd 343 # # prompt: parent/dir (branch*) -- star = dirty working tree 344 # _p() { 345 # local b=$(git branch --show-current 2>/dev/null) s= 346 # if [ -n "$b" ]; then 347 # [ -n "$(git status --porcelain 2>/dev/null)" ] && s="*" 348 # b=" \033[33m($b$s)" 349 # fi 350 # PS1="\033[36m$(basename "${PWD%/*}")/\W$b\033[0m> " 351 # } 352 # PROMPT_COMMAND=_p 353 354 # ────────────────────────────────────────────────────────────── 355 356 #<loc.py> 357 # # lines of code per file: no blanks, comments or top docstring. 358 # # count on the LEFT, path on the right; empty files are skipped. 359 # import ast, sys 360 # for path in sys.argv[1:]: 361 # src = open(path).read() 362 # tree = ast.parse(src) 363 # doc = tree.body[0] if ast.get_docstring(tree) else None 364 # skip = set(range(doc.lineno, doc.end_lineno + 1)) if doc else set() 365 # n = sum(1 for i, s in enumerate(src.split("\n"), 1) if s.strip() 366 # and not s.strip().startswith("#") and i not in skip) 367 # if n: print("%5d %s" % (n, path)) 368 369 # ────────────────────────────────────────────────────────────── 370 371 #<hi.py> 372 # # a2ps for the browser: tiny type, N columns, line numbers. 373 # # One pass: named-group alternation, first rule wins, so strings 374 # # beat comments beat keywords -- no placeholder or state games. 375 # # Section banners (lines starting #-- name ---) each take the 376 # # next pale background. MISC names share one blue; white before 377 # # the first banner and at main. Faces (keywords/comment/func) are 378 # # chosen HERE from the file suffix, so callers pass just cols+file. 379 # import re, sys, html, os 380 # 381 # FACES = { 382 # "py": ("if elif else for while return break continue def lambda " 383 # "yield import from as and or not in is class try except " 384 # "with pass True False None self", 385 # r"#.*", 386 # r"(?<=def )\w+|(?<=class )\w+" 387 # ), 388 # "lua": ("function local end if then else elseif for while do " 389 # "repeat until return require nil true false and or not", 390 # r"--.*", 391 # r"(?<=function )\w+") 392 # } 393 # MK = ("define endef export ifeq ifneq ifdef ifndef else endif " 394 # "include call shell filter notdir wildcard foreach", 395 # r"#.*", 396 # r"^[A-Za-z0-9_.]+(?=:)|[$][(][A-Za-z0-9_]+[)]" 397 # ) 398 # 399 # cols = sys.argv[1] if len(sys.argv) > 1 else "6" 400 # path = sys.argv[2] if len(sys.argv) > 2 else "-" 401 # src = open(path).read() if path != "-" else sys.stdin.read() 402 # base = os.path.basename(path) 403 # kw, com, fun = FACES.get(base.rsplit(".",1)[-1] if "." in base else "", MK) 404 # 405 # RULES = [ 406 # ("str", r'"""[\s\S]*?"""|"[^"]*"|\'[^\']*\''), 407 # ("com", com), 408 # ("fun", fun), 409 # ("kw", r"\b(?:%s)\b" % "|".join(map(re.escape, kw.split()))), 410 # ("num", r"\b\d+\.?\d*\b")] 411 # COLOR = dict(str="#a31515", com="#6a737d", fun="#795e26", 412 # kw="#0033b3", num="#098658", n="#b0b0b0") 413 # BG = ["#fff4e0","#eaf8ec","#f1ecfd","#e2f6f6", # cream green 414 # "#fdfbd8","#fdecf3","#f1f1f1","#ffe9e2"] # lilac teal .. 415 # BLUE, WHITE = "#eaf2ff", "#ffffff" 416 # MISC = r"#-- *(tricks|lib|misc)\b" 417 # MAIN = r"#-- *main\b" 418 # 419 # PAT = re.compile("|".join("(?P<%s>%s)" % kv for kv in RULES), re.M) 420 # 421 # def paint(m) -> str: 422 # return '<span style="color:%s">%s</span>' % (COLOR[m.lastgroup], m.group()) 423 # 424 # out = PAT.sub(paint, html.escape(src, quote=False)) 425 # 426 # print('<meta charset=utf-8>' 427 # '<meta name=viewport content="width=device-width,initial-scale=1">' 428 # '<link rel=stylesheet href="https://fonts.googleapis.com/css2' 429 # '?family=JetBrains+Mono:wght@400&display=swap">' 430 # '<style>html{-webkit-text-size-adjust:100%;text-size-adjust:100%}' 431 # '@media screen and (max-width:700px){body{margin:4px}' # phones: 432 # 'pre{columns:1!important;font-size:calc(100vw/50)!important;' 433 # 'white-space:pre-wrap;overflow-wrap:anywhere}}</style>' # 80ch fits 434 # '<body style="background:#ffffff">') 435 # print('<pre style="font:6.5pt/1.4 JetBrains Mono,Monaco,Menlo,monospace;' 436 # 'color:#1f2328;columns:%s 80ch;column-gap:2em;' 437 # 'column-rule:1px solid #dddddd">' % cols) 438 # carry, bg, k = "", WHITE, 0 439 # for n, (raw, line) in enumerate(zip(src.split("\n"), 440 # out.split("\n")), 1): 441 # if raw.startswith("#--"): # new conceptual block 442 # if re.match(MISC, raw): bg = BLUE 443 # elif re.match(MAIN, raw): bg = WHITE 444 # else: bg, k = BG[k % len(BG)], k + 1 445 # line = carry + line 446 # opens = re.findall(r"<span[^>]*>", line) 447 # carry = "" 448 # if len(opens) > line.count("</span>"): 449 # carry = opens[-1]; line += "</span>" 450 # print('<span style="display:block;background:%s">' 451 # '<span style="color:%s">%4d</span> %s</span>' 452 # % (bg, COLOR["n"], n, line), end="") 453 # # end="": a block span already ends its line; a \n here too 454 # # would show in <pre> as a blank line after every source line. 455 # print("</pre>") 456