In this section
- Build render · cosmic / tools/explore/build.py lines 2101–2800
Build
A Python command-line tool in the explore folder of Cosmic that maps dictionary and build graph, using EPSG:27700 and EPSG:4326, and uses data from the GridAtlas, ventus-grid-engine and SatNav repositories.
rendercosmic / tools/explore/build.py · lines 2101–2800 of 3776 (continued from section 1080) · Entry point · pattern clean_comment (shared by 2 files)
- What it does
- It maps dictionary, build graph, words and solar. Defines 114 functions or classes, including words_of, git, ext, slug, load_leaks. Uses libraries argparse, collections, datetime, fnmatch, html. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain terms in the code: solar, 132kV, 33kV, 11kV, 11kV/400V, 400V. README: "`build.py` is the method"
- Inputs & outputs
- In: data source: gridatlas data; data source: ventus-grid-engine data; data source: satnav data; data source: solar-electrical-topology-analysis-engine-text-based data; JSON file dictionary.json; JSON file build_graph.json; Parquet file code.parquet; Parquet file words.parquet. Out: Parquet file; JSON file; interactive map; SVG drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326, Web Mercator / EPSG:3857, ETRS89 / EPSG:4258. Voltage levels named: 132kV, 33kV, 11kV, 11kV/400V, 400V.
- Downstream impact
- Used directly by 3 files: Cadastre 27 (cosmic); Ship (cosmic); Test Build (cosmic). Reached from 1 other entry point, including Test Ship (cosmic).
- What it achieves
- It loads leaks (`load_leaks`), loads essays (`load_essays`) and cleans key (`clean_key`). The README says: `build.py` is the method. Its code works with 132 kV, 33 kV and 11 kV. It writes `words/index.html`.
- Why it matters
- Imported by Cadastre 27. Run by Ship. Checked by Test Build.
- Application
- cosmic · tools/explore · Python CLI
- Uses
- Describe (import), Agentdocs (import), GridAtlas — Index Page (estate URL), SatNav — Scope Page (estate URL), Solar Electrical Topology Analysis Engine Text Based — Index Page (estate URL), argparse, collections, datetime, fnmatch, html, json, os, posixpath
- Used by
- imported by Cadastre 27 (sys.path import), run by Ship (script call), imported by Test Build (import)
- Produces
- words_of, git, ext, slug, load_leaks, humanise, kind_of, name_words, stamp_note, title_parts, title_of, repo_title
- Defines here
- data_phrase, pages_url, join_words, synopsis_of, add, sectionise, flush, Site, __init__, write, ventus_org, badge, build, root_ok, flink, aside_note, crumbs, lic_of, lic_url
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/build.py:2101-2800 · blob a82b6f8252f926b3e24b5469dc1f3b7b2ead6a33 · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: unknown · users: none · canonical: unknown
(r'ventusltd\.github\.io/([\w.-]+)', lambda m: '%s data' % m.group(1)),
(r'api\.postcodes\.io', 'postcodes.io'), (r'overpass', 'OpenStreetMap (Overpass)'),
(r'environment\.data\.gov\.uk', 'Environment Agency'), (r'basemaps\.cartocdn\.com', 'CARTO basemap'),
(r'nominatim', 'OpenStreetMap Nominatim'), (r'elexon|bmrs', 'Elexon BMRS'),
(r'nationalgrideso\.com|neso\.energy', 'NESO data portal'),
(r'ukpowernetworks\.opendatasoft\.com|ukpowernetworks', 'UK Power Networks open data'),
(r'ssen\.co\.uk|ssen-', 'SSEN'), (r'tile\.openstreetmap\.org', 'OpenStreetMap tiles'),
(r'api\.github\.com', 'GitHub API'), (r'carbonintensity\.org\.uk', 'Carbon Intensity API'),
(r'api\.os\.uk', 'Ordnance Survey'), (r'opentopodata|open-elevation', 'open elevation data'),
]
NOT_DATA = re.compile(r'cdn\.|jsdelivr|unpkg|cdnjs|fonts\.(googleapis|gstatic)|w3\.org|schema\.org|^github\.com|'
r'shields\.io|googletagmanager|creativecommons|spdx\.org|example\.(com|org)|localhost', re.I)
URL_RX = re.compile(r'''https?://[^\s'"`)<>{}\\]+''')
FETCH_URL = re.compile(r'''(?:fetch|axios(?:\.get)?|requests\.(?:get|post)|urlopen|read_csv|read_json|read_parquet|'''
r'''read_file|getJSON|\.load)\(\s*[fr]?[`'"](https?://[^`'"\s]+)''')
DATA_FILE = re.compile(r'''[`'"/]([\w.\-]+\.(?:geojson|topojson|json|csv|parquet|pmtiles|xlsx|gpkg|kml|gpx))(?:\?[^`'"]*)?[`'"]''', re.I)
LAYER_ID = re.compile(r'''add(?:Layer|Source)\(\s*(?:\{[^}]{0,200}?\bid\s*:\s*)?['"]([\w\- ]{3,40})['"]''')
UI_TEXT = re.compile(r'<(h[1-3]|button|label|title)\b[^>]*>([^<]{3,60})</\1>', re.I)
DATA_STOP = {'data', 'latest', 'final', 'new', 'old', 'index', 'all', 'export', 'output', 'out', 'tmp', 'test',
'sample', 'demo', 'package', 'lock', 'manifest', 'config', 'settings', 'tsconfig', 'src', 'layer', 'source',
'json', 'geojson', 'csv', 'parquet', 'min', 'v', 'file', 'files'}
NOUNS = [(r'\b(?:a)[-_ ]roads?\b', 'A roads'), (r'\b(?:b)[-_ ]roads?\b', 'B roads'), (r'\bmotorways?\b', 'motorways'),
(r'\bsubstations?\b', 'substations'), (r'\boverhead[-_ ]lines?\b|\bohl\b', 'overhead lines (OHL)'),
(r'\bunderground[-_ ]cables?\b', 'underground cables'), (r'\bcables?\b', 'cables'), (r'\bsolar\b', 'solar'),
(r'\bbess\b|\bbattery[-_ ]storage\b', 'battery storage (BESS)'), (r'\brepd\b', 'the REPD register'),
(r'\binterconnectors?\b', 'interconnectors'), (r'\btransformers?\b', 'transformers'),
(r'\bwind\b', 'wind'), (r'\blidar\b', 'LiDAR terrain'), (r'\bpostcodes?\b', 'postcodes')]
NOUN_RX = [(re.compile(r), p) for r, p in NOUNS]
NOUN_ANY = re.compile('|'.join('(?:%s)' % r for r, p in NOUNS))
VOLT_RX = re.compile(r'(?<![\w.])(\d{2,3})\s?kv(?:\s?/\s?(\d{3})\s?v)?\b')
KIND_LABEL = {'page': 'Page', 'style sheet': 'Style sheet', 'workflow': 'Workflow', 'test': 'Test',
'Python CLI': 'Python tool', 'Python module': 'Python module', 'JavaScript module': 'JavaScript module',
'TypeScript module': 'TypeScript module', 'script': 'Script', 'shell script': 'Shell script',
'PowerShell script': 'PowerShell script', 'batch script': 'Batch script', 'configuration': 'Configuration',
'SQL query': 'SQL query', 'component': 'Component', 'shader': 'Shader'}
LAYER_STOP = {'style', 'source', 'data', 'layer', 'base', 'basemap', 'background', 'find', 'main', 'default', 'points',
'lines', 'polygons', 'labels', 'highlight', 'selected', 'hover', 'temp', 'tmp', 'osm', 'tiles', 'raster'}
MAP_RX = re.compile(r'maplibregl\.|\bL\.map\(|addLayer\(|new\s+ol\.Map|mapboxgl\.|leaflet', re.I)
def data_phrase(name):
"""A data file or layer name in words: 132kv_ohl.geojson -> 132kV overhead lines; a_roads -> A roads."""
ws = name_words(name)
out, i = [], 0
while i < len(ws):
w = ws[i]
nxt = ws[i + 1] if i + 1 < len(ws) else ''
if w in ('a', 'b') and nxt in ('road', 'roads'):
out.append(w.upper() + ' roads')
i += 2
continue
i += 1
if w in DATA_STOP or w.isdigit() or re.match(r'^v\d+$', w):
continue
m = UNIT_RX.match(w)
if m:
out.append(m.group(1) + UNITS[m.group(2).lower()])
elif w == 'ohl':
out.append('overhead lines')
elif w == 'ugc':
out.append('underground cables')
elif w in TERMS:
out.append(TERMS[w][0])
else:
out.append(w)
return ' '.join(out)
def pages_url(meta, path, has_index):
"""Public address of a page, only where the repository shows Pages evidence (CNAME, .nojekyll, a Pages
workflow, or its own files naming ventusltd.github.io/<repo>)."""
base = meta.get('pages')
if not base:
return ''
e = ext(path)
d = posixpath.dirname(path)
if e in ('html', 'htm'):
name = path.rsplit('/', 1)[-1]
return base + (d + '/' if d else '') if name.lower() in ('index.html', 'index.htm') else base + path
if has_index(meta['repo'], d):
return base + (d + '/' if d else '')
return ''
def join_words(xs):
xs = list(xs)
return xs[0] if len(xs) == 1 else ', '.join(xs[:-1]) + ' and ' + xs[-1] if xs else ''
def synopsis_of(f, meta, has_index, repo_t):
"""One or two sentences: kind + subject, verb, key elements, sources, where it runs. Evidence only."""
text = f['text']
sources, seen_src = [], set()
fetched = FETCH_URL.findall(text) if gate(f, ('fetch', 'axios', 'requests.', 'urlopen', 'read_', 'getjson', '.load(')) else []
fetched_set = set(fetched)
for u in fetched + (URL_RX.findall(text) if 'http' in f['low'] else []):
host = re.sub(r'^https?://(www\.)?', '', u)
if NOT_DATA.search(host):
continue
name = None
for rx, nm in HOSTS:
m = re.search(rx, host, re.I)
if m:
name = nm(m) if callable(nm) else nm
break
if name is None and u in fetched_set:
name = host.split('/')[0]
if name and name.lower() != ('%s data' % f['repo']).lower() and name.lower() not in seen_src:
seen_src.add(name.lower())
sources.append(name)
objects = []
def add(p):
p = p.strip()
if len(p) < 2 or len(p) > 50:
return
lo = p.lower()
for i, o in enumerate(objects):
if lo in o.lower():
return
if o.lower() in lo:
objects[i] = p
return
objects.append(p)
for fn in (DATA_FILE.findall(text)[:20] if gate(f, ('.json', '.geojson', '.csv', '.parquet', '.pmtiles', '.xlsx', '.gpkg', '.kml', '.gpx')) else []):
if fn.lower() not in ('package.json', 'package-lock.json', 'tsconfig.json', 'manifest.json'):
add(data_phrase(fn))
for lid in (LAYER_ID.findall(text)[:20] if gate(f, ('addlayer', 'addsource')) else []):
if lid.lower() not in LAYER_STOP:
add(data_phrase(lid))
hay = ' '.join(name_words(f['path'])) + '\n' + f['low'][:200000]
counts = []
if 'kv' in hay:
for m in VOLT_RX.finditer(hay):
counts.append(m.group(1) + 'kV' + ('/' + m.group(2) + 'V' if m.group(2) else ''))
vc = collections.Counter(counts)
nc = collections.Counter()
for m in NOUN_ANY.finditer(hay):
w = m.group(0)
for rx, p in NOUN_RX:
if rx.fullmatch(w):
nc[p] += 1
break
ranked = [(c, v) for v, c in vc.items()] + [(c, p) for p, c in nc.items()]
for c, p in sorted(ranked, key=lambda x: -x[0]):
if c >= 2 and len(objects) < 5:
add(p)
ui = 0
for tag, label in (UI_TEXT.findall(text)[:8] if gate(f, ('<h1', '<h2', '<h3', '<button', '<label', '<title')) else []):
label = re.sub(r'\s+', ' ', html.unescape(label)).strip()
if ui < 2 and len(objects) < 5 and re.search(r'[A-Za-z]{3,}', label) and '{' not in label and '$' not in label \
and label.lower() != f['subject'].lower():
n0 = len(objects)
add('"%s"' % label)
ui += len(objects) - n0
objects = objects[:5]
kind = f['kind']
label = KIND_LABEL.get(kind, kind[:1].upper() + kind[1:])
has_map = gate(f, ('maplibregl', 'l.map(', 'addlayer', 'ol.map', 'mapboxgl', 'leaflet')) and bool(MAP_RX.search(text))
if kind == 'page' and has_map:
label = 'Map page'
if f['role'] == 'test' or kind == 'test':
verb = 'tests'
elif kind == 'workflow':
verb = 'builds and publishes' if re.search(r'deploy-pages|upload-pages-artifact|gh-pages|publish', text) else 'runs'
elif has_map:
verb = 'maps'
elif 'dom' in f['effects'] and f['draw_n'] and kind != 'style sheet':
verb = 'draws'
elif 'network' in f['effects']:
verb = 'fetches'
elif f['reads']:
verb = 'loads'
elif not f['effects'] and f['role'] in ('geodesy', 'electrical', 'transform', 'energy-data') and f['defs']:
verb = 'calculates'
elif re.search(r'\b(search|filter)\w*\(', text):
verb = 'lists and searches'
else:
verb = ''
f['syn_parts'] = (verb, list(objects), list(sources))
s = '%s for %s' % (label, f['subject']) if f['subject'] else label
if verb and objects:
s += ' that %s %s' % (verb, join_words(objects))
elif objects:
s += ', covering %s' % join_words(objects)
elif verb and verb != 'runs':
s += (' that %s %s' % (verb, 'data' if verb in ('fetches', 'loads') else 'its inputs' if verb == 'calculates' else '')).rstrip()
if sources:
s += ' from %s' % join_words(sources[:3])
s += '.'
tail = ['Part of %s' % repo_t]
url = pages_url(meta, f['path'], has_index)
if url:
tail.append('published at %s' % url)
f['published'] = url
links = []
for u in re.findall(r'''href=["'](https?://(?:globalgrid2050\.com|ventusltd\.github\.io)[^"'#?]*)''', text):
u = u.rstrip('/') + '/'
short = re.sub(r'^https?://', '', u).rstrip('/')
if short not in links and u != url:
links.append(short)
if links:
tail.append('links to %s' % join_words(links[:3]))
return trim(s + ' ' + '; '.join(tail) + '.', 420)
# ---------------------------------------------------------------- cutting
def sectionise(files, lo, hi):
sections, cur, n = [], [], 0
def flush():
nonlocal cur, n
if cur:
sections.append(cur)
cur, n = [], 0
prev_topic = None
for fi, f in enumerate(files):
if prev_topic is not None and f['topic'] != prev_topic and n >= lo // 2:
flush()
prev_topic = f['topic']
start, total = 1, len(f['lines'])
while start <= total:
left = total - start + 1
if n + left <= hi:
cur.append((fi, start, total))
n += left
start = total + 1
elif n >= lo:
flush()
else:
take = hi - n
cur.append((fi, start, start + take - 1))
start += take
n += take
flush()
flush()
return sections
# ---------------------------------------------------------------- writing
CSS = """body{background:#000;color:#fff;font:15px/1.55 ui-monospace,Menlo,Consolas,monospace;margin:0}
header,nav,main,footer{max-width:1100px;margin:0 auto;padding:0 18px}a{color:#66ccff}
.brand{color:#00ffff;margin:20px 0 2px;font-size:13px;letter-spacing:.06em}h1{font-size:22px;margin:4px 0 8px}
h2{font-size:16px;margin:28px 0 4px;overflow-wrap:anywhere}h3{font-size:14px;margin:18px 0 4px}
nav{display:flex;gap:16px;flex-wrap:wrap;padding-top:10px;padding-bottom:10px;border-bottom:1px solid #2f343d}
.crumbs{font-size:13px;color:#a6adbb;margin:6px 0}.k{color:#a6adbb;font-size:12px;overflow-wrap:anywhere}
pre{background:#0b0e14;border:1px solid #2f343d;padding:12px;overflow-x:auto;font-size:13px;line-height:1.5;tab-size:4}
dl.v{display:grid;grid-template-columns:max-content 1fr;gap:2px 14px;font-size:13px;margin:8px 0}dl.v dt{color:#66ccff}
dl.v dd{margin:0;overflow-wrap:anywhere}table{border-collapse:collapse;width:100%;font-size:13px}
td,th{border-bottom:1px solid #2f343d;padding:5px 8px;text-align:left;vertical-align:top}th{color:#00ffff}
input,button{background:#0b0e14;color:#fff;border:1px solid #2f343d;padding:7px;font:inherit}p{max-width:900px}
:target{outline:1px solid #0066ff}ul.links{columns:2 320px}li{margin:4px 0}
section.file{border-left:4px solid #4c5a65;padding-left:12px;margin-left:-16px}
.syn{background:#0b0e14;border-left:2px solid #00ffff;padding:6px 10px;margin:4px 0 6px;max-width:none}
.badge{display:inline-block;color:#000;border-radius:3px;padding:0 6px;font-size:11px;margin-right:6px}
.ctx,.essay{background:#0b0e14;border:1px solid #2f343d;padding:8px 14px;margin:14px 0}
.ctx h3{margin-top:4px;color:#00ffff}.prov{color:#00ff88;font-size:12px;margin:2px 0 6px}
.flag{color:#ffd24a}.cand{display:block;color:#ffd24a;font-size:14px}.entry{color:#00ff88}dl.four{border-left:2px solid #00ff88;padding-left:10px}
.lic{display:inline-block;border:1px solid #00ffff;color:#00ffff;border-radius:3px;padding:0 5px;font-size:11px}
.lic.none{border-color:#ffd24a;color:#ffd24a}details summary{cursor:pointer;color:#66ccff}
.tldr{margin:8px 0;padding-left:1.4em;line-height:1.5}.tldr li{margin:2px 0}
details.fold summary h3{display:inline;margin:0 .6em 0 0;font-size:1em}details.fold{margin:4px 0}
""" + ''.join('section.r-%s{border-left-color:%s}.badge.r-%s{background:%s}\n' % (k, c, k, c) for k, t, c in ROLES) + \
"""/* v2 layer (GENERATOR 2.0.0): phone basics, focus, reduced motion, cards; after SWATCH-29's explore-v2.css */
*,*::before,*::after{box-sizing:border-box}
body{font-size:16px;line-height:1.6;-webkit-text-size-adjust:100%}
header,nav,main,footer{max-width:1100px}
h1{font-size:clamp(26px,6vw,44px);font-weight:500;line-height:1.15;letter-spacing:-.03em;margin:12px 0;overflow-wrap:anywhere}
a,dd,td,li,p,.crumbs,main{overflow-wrap:anywhere;min-width:0}
a{text-underline-offset:3px}
a:focus-visible,button:focus-visible,input:focus-visible,summary:focus-visible,select:focus-visible,[tabindex]:focus-visible{outline:2px solid #00ffff;outline-offset:3px;border-radius:2px}
nav{gap:8px;align-items:center}
nav a{display:inline-flex;align-items:center;min-height:44px;padding:4px 12px;border:1px solid #2f343d;border-radius:999px;text-decoration:none;font-size:14px}
nav a:hover{border-color:#00ffff;background:#0b0e14}
table{display:block;overflow-x:auto;max-width:100%}
input,button,select,textarea{font-size:16px;min-height:44px;border-radius:6px}
input[type=search],#q{width:100%;max-width:640px;padding:10px 12px}
button{padding:8px 16px;cursor:pointer;color:#66ccff}button:hover{border-color:#00ffff}
details summary{min-height:44px;display:flex;align-items:center}
.badge.r-other{color:#fff}
.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
ul.cards{list-style:none;padding:0;display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:12px;margin:12px 0}
ul.cards>li{margin:0;background:#0b0e14;border:1px solid #2f343d;border-radius:6px;padding:14px 16px;color:#a6adbb;font-size:14px;transition:border-color .16s,transform .16s}
ul.cards>li:hover{border-color:#00ffff;transform:translateY(-2px)}
ul.cards .t{display:flex;align-items:center;min-height:44px;font-size:17px;text-decoration:none;color:#66ccff}
ul.cards .n{display:block;margin-top:8px;font-size:11px;letter-spacing:.1em;text-transform:uppercase;color:#00ffff}
.strip{display:flex;height:6px;border-radius:3px;overflow:hidden;margin-top:10px}.strip i{display:block;height:6px}
.chips{display:flex;flex-wrap:wrap;gap:8px;margin:10px 0;padding:0;list-style:none}
.chips a,.chips button{display:inline-flex;align-items:center;min-height:44px;padding:4px 14px;border:1px solid #2f343d;border-radius:999px;background:#0b0e14;color:#66ccff;text-decoration:none;font:inherit;font-size:14px}
.aside{background:#140f00;border-left:3px solid #ffd24a;padding:6px 10px;margin:6px 0;font-size:14px}
.bar{height:6px;background:#0b0e14;border:1px solid #2f343d;border-radius:3px;max-width:640px;overflow:hidden}.bar i{display:block;height:100%;width:0;background:#00ffff}
@media (prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important;scroll-behavior:auto!important}ul.cards>li:hover{transform:none}}
@media (max-width:600px){header,nav,main,footer{padding-left:14px;padding-right:14px}
nav{flex-wrap:nowrap;overflow-x:auto;scrollbar-width:none}nav a{flex:none}
dl.v{grid-template-columns:1fr;gap:0}dl.v dt{margin-top:10px}
ul.links{columns:1}main li{margin:0;padding:2px 0}main li a,main h3 a,.crumbs a,footer a{display:inline-block;padding:10px 0;min-height:44px}
section.file{margin-left:0;padding-left:10px}pre{font-size:12px}}
"""
# Index play row: reveal cards whose page exists in this publish (extras are added after build.py, so their links are
# set only when the page answers, never as a dead href), and "Surprise me" opens a random section. %d = section count.
PLAY_JS = """(function(){var n=%d,w=String(n).length<4?4:String(n).length;
var s=document.getElementById('surprise');if(s)s.addEventListener('click',function(e){e.preventDefault();
var k=String(1+Math.floor(Math.random()*n));while(k.length<w)k='0'+k;location.href='s/'+k+'.html'});
if(!window.fetch||location.protocol==='file:')return;
document.querySelectorAll('[data-probe]').forEach(function(el){var u=el.getAttribute('data-probe');
if(el.tagName==='A'&&document.querySelector('nav a[href="'+u+'"]'))return;
fetch(u,{method:'HEAD'}).then(function(r){if(!r.ok)return;var a=el.tagName==='A'?el:el.querySelector('a');
if(a)a.href=u;el.hidden=false}).catch(function(){})})})();"""
class Site:
def __init__(self, out, base):
self.out, self.base = out, base
self.titles = collections.Counter()
def write(self, rel, title, desc, body, depth, jsonld=None):
up = '../' * depth
self.titles[title] += 1
ld = ('<script type="application/ld+json">%s</script>' % json.dumps(jsonld, ensure_ascii=False).replace('</', '<\\/')
if jsonld else '')
doc = ('<!doctype html><html lang="en"><head><meta charset="utf-8">'
'<meta name="viewport" content="width=device-width,initial-scale=1"><title>%s</title>'
'<meta name="generator" content="explore build.py %s">'
'<meta name="description" content="%s"><meta name="author" content="%s"><link rel="canonical" href="%s">'
'<link rel="stylesheet" href="%sexplore.css">%s</head><body>%s'
'<footer><p class="k">GlobalGrid2050 Explore Code · funded by VENTUS LTD · code under each repository\'s '
'own licence · <a href="%sindex.html">index</a> · <a href="%ssearch.html">search</a> · '
'<a href="%sllms.txt">llms.txt</a></p></footer></body></html>\n'
% (E(title), GENERATOR_VERSION, E(desc[:300]), E(AUTHOR), self.base + rel, up, ld, body, up, up, up))
p = os.path.join(self.out, rel)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, 'w', encoding='utf-8', newline='\n') as fh:
fh.write(doc)
def ventus_org():
return {'@type': 'Organization', 'name': 'Ventus Ltd'}
def badge(role):
return '<span class="badge r-%s">%s</span>' % (role, role)
def build(src, out, base, lo, hi, kuiper_tools, essays_dir=None, repos=None, clean_manifest=None, duckdb_dir=None):
leaks = load_leaks(kuiper_tools)
files, left, metas = scan(src, leaks, set(repos) if repos else None)
vedic = load_vedic(src)
essays = load_essays(essays_dir)
for f in files:
f['topic'] = topic_of(f)
order = {k: i for i, (k, *_r) in enumerate(TOPICS)}
files.sort(key=lambda f: (order[f['topic']], f['repo'].lower(), f['path']))
by_path = {(f['repo'], f['path']): i for i, f in enumerate(files)}
set_aside, clean_info = load_clean_manifest(clean_manifest, files)
main_view = lambda fi: fi not in set_aside
index_dirs = {(f['repo'], posixpath.dirname(f['path'])) for f in files
if f['path'].rsplit('/', 1)[-1].lower() in ('index.html', 'index.htm')}
has_index = lambda repo, d: (repo, d) in index_dirs
for f in files:
f['defs'] = definitions(f['path'], f['lines'])
f['cap'] = capability_of(f['path'], f['lines'])
f['refs'] = refs_of(f['path'], f['lines'])
f['syspath'] = python_syspath_dirs(f['path'], f['lines']) if f['path'].endswith('.py') else []
f['exports'] = exports_of(f['path'], f['lines'], f['defs'])
f['vedic'] = vedic_matches(f, vedic)
f['title'], f['subject'], f['qual'], f['kind'] = title_parts(f['repo'], f['path'], f['lines'])
f['title'] = describe.polish_title(f['title'])
f['name_words'] = name_words(f['path'])
f['version'] = stamp_note(f['path'])
f['text'] = '\n'.join(f['lines'])
f['low'] = f['text'].lower()
effects_of(f)
# Edges: every reference resolved to an estate file, any repository (Resolver; kinds in EDGE_KINDS)
resolver = Resolver(files, metas)
imported_by = collections.defaultdict(list)
mentioned_by = collections.defaultdict(list) # comment-url only
used_kind = {} # (from, to) -> first kind, for "Used by ... (kind)"
edges = []
for i, f in enumerate(files):
f['links'], f['link_kinds'], f['link_via'] = [], [], []
out_edges, f['ext_imports'] = resolver.edges_of(i)
seen_k = set()
f.setdefault('mentions', [])
code_targets = {j for j, kind, via in out_edges if kind != 'comment-url'}
for j, kind, via in out_edges:
if kind == 'comment-url': # a mention, not a load: kept in edges, never in imports/reachability
if j not in code_targets and j not in f['mentions']:
f['mentions'].append(j)
mentioned_by[j].append(i)
edges.append([i, j, kind, via])
continue
if (j, kind) not in seen_k:
seen_k.add((j, kind))
edges.append([i, j, kind, via])
if j not in f['links']:
f['links'].append(j)
f['link_kinds'].append(kind)
f['link_via'].append(via)
imported_by[j].append(i)
used_kind[(i, j)] = kind
f['ext_imports'] = list(dict.fromkeys(f['ext_imports']))
# Pages evidence per repository, for "published at"
for r, meta in metas.items():
own = 'ventusltd.github.io/%s' % r.lower()
if meta.get('cname'):
meta['pages'] = 'https://%s/' % meta['cname']
elif meta.get('nojekyll') or any(
f['repo'] == r and ((f['path'].startswith('.github/workflows/') and
re.search(r'deploy-pages|upload-pages-artifact', f['text']))
or own in f['low']) for f in files):
meta['pages'] = 'https://ventusltd.github.io/%s/' % r
else:
meta['pages'] = ''
# Function: role, stage, pattern, entry points, reachability
pkg_entries = package_entries(metas, by_path)
script_targets = set() # loaded by a page's <script src>, or called from a workflow or the Pages root index
for i, f in enumerate(files):
root_index = posixpath.join(resolver.pages_root.get(f['repo'], ''), 'index.html')
for j, k in zip(f['links'], f['link_kinds']):
if (ext(f['path']) in ('html', 'htm') and k in EXT_KINDS) or k == 'workflow-run' or \
(f['path'] == root_index and k != 'estate-url'):
script_targets.add(j)
for i, f in enumerate(files):
f['role'] = role_of(f)
f['stage'] = stage_of(f)
f['entry'] = (f['kind'] == 'page' or f['kind'] == 'workflow' or f['kind'] == 'Python CLI' or f['entry_main']
or i in pkg_entries or i in script_targets)
assign_patterns(files, leaks)
reach = set(i for i, f in enumerate(files) if f['entry'])
queue = collections.deque(reach)
while queue:
i = queue.popleft()
for j in files[i]['links']:
if j not in reach:
reach.add(j)
queue.append(j)
for i, f in enumerate(files):
f['reachable'] = i in reach
# Context tiers: essays (human), nearest README (readme_derived), else auto
def root_ok(r):
"""The root README's chosen paragraph scores README_THRESHOLD or more (readme_pick)."""
rd = metas[r]['readmes'].get('')
return bool(rd and rd[1] and rd[2] is not None and rd[2] >= README_THRESHOLD)
for f in files:
meta = metas[f['repo']]
d = posixpath.dirname(f['path'])
f['essay'] = essays.get((f['repo'], 'file', f['path']))
f['context'], f['context_src'] = '', ''
chain = []
while True:
chain.append(d)
if not d:
break
d = posixpath.dirname(d)
if not f['essay']:
for c in chain:
if c and (f['repo'], 'folder', c) in essays:
f['essay'] = essays[(f['repo'], 'folder', c)]
break
f['repo_essay'] = essays.get((f['repo'], 'repo', ''))
for c in chain:
rd = meta['readmes'].get(c)
if rd and rd[1]:
if c == '' and not root_ok(f['repo']):
break # a weak root README paragraph is not shown as context (README_THRESHOLD)
f['context'], f['context_src'] = rd[1], rd[0]
break
f['essay_status'] = 'human' if (f['essay'] or f['repo_essay']) else 'readme_derived' if f['context'] else 'auto'
# Tier 3: synopsis, what it achieves, why it matters (describe.py; provenance comment | code | readme | name).
# Synopsis parts and published URLs for every file first: a file's why reads its dependents' "published".
titles_by_path = {(g['repo'], g['path']): g['title'] for g in files}
for f in files:
synopsis_of(f, metas[f['repo']], has_index, repo_title(f['repo']))
for i, f in enumerate(files):
d = describe.describe(describe.evidence_from_build(i, files, imported_by, metas, repo_title,
titles_by_path, leaks))
f['synopsis'], f['achieves'], f['why'] = d['synopsis'], d['achieves'], d['why']
f['achieves_src'] = d['provenance']['achieves']
f['desc_note'] = d.get('note', '') # LAWS K1: "Described from its file name only (a candidate ...)"
# Agent ingestion fields (agentdocs.py; GRAPH-CONTRACT.md "Agent ingestion fields"): domain_stage,
# commercial_user, data_contracts, canonical_status, signatures and the four-part block. Evidence only.
entries = [i for i, f in enumerate(files) if f['entry']]
reached_by, reach_size = agentdocs.entry_reach([f['links'] for f in files], entries)
for i, f in enumerate(files):
f['published'] = f.get('published', '')
f['sigs'] = agentdocs.signatures_of(f['path'], f['text'], f['exports'], leaks)
srcs = [s for s in f['syn_parts'][2] if not leaks(s)]
f['dc'] = agentdocs.data_contracts_of(f, srcs)
f['dstage'], f['dstage_ev'] = agentdocs.domain_stage_of(f['repo'], f['name_words'], f['topic'], f['dc']['voltages'])
f['users'] = agentdocs.commercial_users_of(f['dstage'], agentdocs.words_of(f['repo']) + f['name_words'])
statuses = agentdocs.canonical_statuses(
[{'repo': f['repo'], 'path': f['path'], 'text': f['text'], 'reachable': f['reachable'], 'entry': f['entry'],
'pattern': f['pattern'], 'defines': [n for n, k, ln in f['defs'] if k != 'workflow'], 'lines': f['lines'],
'role': f['role']} for f in files], imported_by, set(CORE_REPOS))
for i, f in enumerate(files):
f['canon'], f['dup_of'] = statuses[i]
verb, objects, _s = f['syn_parts']
meta = metas[f['repo']]
rs, d = [], posixpath.dirname(f['path'])
while True:
rs.extend(x for x in meta.get('readme_sentences', {}).get(d, []) if not leaks(x))
if not d:
break
d = posixpath.dirname(d)
terms = [o for o in describe.clean_objects(objects, f['title'], f['kind'], f['role']) if describe.DOMAIN_OBJ.match(o)]
terms += [v for v in f['dc']['voltages'] if v not in terms]
f['four'] = {
'does': agentdocs.what_it_does(verb, describe.clean_objects(objects, f['title'], f['kind'], f['role']),
[n for n, k, ln in f['defs'] if k != 'workflow' and not leaks(n)],
f['ext_imports'], f['effects'], f['kind']),
'why': agentdocs.why_it_exists(f['dstage'], f['dstage_ev'], terms, describe.readme_match(rs, f['path'])),
'io': agentdocs.contracts_words(f['dc']),
'impact': agentdocs.downstream_impact(i, files, imported_by, reached_by),
}
sections = sectionise(files, lo, hi)
width = max(4, len(str(len(sections))))
sname = lambda i: 's/%0*d.html' % (width, i)
first_section = {}
for si, parts in enumerate(sections, 1):
for bi, (fi, a, b) in enumerate(parts, 1):
first_section.setdefault(fi, (si, bi))
stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%S+00:00')
site = Site(out, base)
os.makedirs(out, exist_ok=True)
open(os.path.join(out, 'explore.css'), 'w').write(CSS)
topic_title = {k: t for k, t, d, _ in TOPIC_RX}
all_names = {n for f in files for n, k, i in f['defs'] if not leaks(n)}
# Section titles: from the file holding most lines; repeated titles get "part k"
sec_titles, seen_t = [], collections.Counter()
for parts in sections:
dom = max(parts, key=lambda p: p[2] - p[1] + 1)[0]
others = len({fi for fi, a, b in parts}) - 1
t = files[dom]['title'] + (' and %d more file%s' % (others, '' if others == 1 else 's') if others else '')
seen_t[t] += 1
sec_titles.append((t, dom, seen_t[t]))
totals = collections.Counter(t for t, d, k in sec_titles)
sec_titles = [t + (' (part %d)' % k if totals[t] > 1 else '') for t, d, k in sec_titles], [d for t, d, k in sec_titles]
sec_title, sec_dom = sec_titles
# Essays: the first section holding any file each folder/file essay covers
essay_home = {}
for si, parts in enumerate(sections, 1):
for fi, a, b in parts:
es = files[fi]['essay']
if es and es['id'] not in essay_home:
essay_home[es['id']] = si
def flink(fi, up):
si, bi = first_section[fi]
f = files[fi]
return '<a href="%s%s#f%d">%s</a>' % (up, sname(si), bi, E(f['title']))
def aside_note(fi, up):
"""The one set-aside line on a file's own section page (clean/CONTRACT.md section 6), with its evidence."""
rec = set_aside.get(fi)
if not rec:
return ''
cat = rec['category']
tgt = ''
if rec.get('target_fi') is not None and rec['target_fi'] in first_section:
tgt = ' The file that stays: %s.' % flink(rec['target_fi'], up)
pct = near_copy_pct(rec)
if pct is not None:
tgt = ' %d%% of lines shared with %s; read that one first.' % (pct, flink(rec['target_fi'], up))
ev = ''.join('<li>%s</li>' % E(str(x)) for x in (rec.get('evidence') or [])[:8])
return ('<p class="aside">Set aside from the main view: %s (%s, proposed by %s%s).%s '
'<a href="%sset-aside.html#c-%s">All set-aside files, with reasons</a>. Nothing was deleted.</p>%s'
% (E(rec.get('reason') or CLEAN_CATEGORY_TITLE[cat]), E(cat), E(str(rec.get('proposer') or 'unknown')),
', a dry run awaiting owner review' if clean_info and clean_info.get('dry_run') else '',
tgt, up, cat, ('<details><summary>Evidence</summary><ul>%s</ul></details>' % ev) if ev else ''))
def crumbs(topic, repo=None, folder=None, up='', essay=None):
c = ['<a href="%sindex.html">Explore Code</a>' % up,
'<a href="%stopics/%s.html">%s</a>' % (up, topic, E(topic_title[topic]))]
if repo:
c.append('<a href="%srepos/%s.html">%s</a>' % (up, slug(repo), E(repo)))
if folder:
c.append('<a href="%srepos/%s.html#d-%s">%s</a>' % (up, slug(repo), slug(folder), E(folder)) if repo else E(folder))
if essay:
c.append(essay)
return '<p class="crumbs">Part of: %s</p>' % ' / '.join(c)
def lic_of(repo):
m = metas[repo]
return m['license']
def lic_url(repo):
m = metas[repo]
if not m['license_file']:
return None
return 'https://github.com/Ventusltd/%s/blob/%s/%s' % (repo, m['commit'], urllib.parse.quote(m['license_file']))
words = []
code_rows = []
section_meta = []
readme_files = set()
for si, parts in enumerate(sections, 1):
tcount = collections.Counter(files[fi]['topic'] for fi, a, b in parts)
topic = tcount.most_common(1)[0][0]
repos = list(dict.fromkeys(files[fi]['repo'] for fi, a, b in parts))
lines_n = sum(b - a + 1 for fi, a, b in parts)
langs = collections.Counter()
blocks, toc = [], []
shown_ctx = set()
essays_here = []
for bi, (fi, a, b) in enumerate(parts, 1):
f = files[fi]
if f['essay'] and f['essay'] not in essays_here:
essays_here.append(f['essay'])
langs[LANG.get(ext(f['path']), ext(f['path']).upper() or 'text')] += b - a + 1
q = urllib.parse.quote(f['path'])
gh = 'https://github.com/Ventusltd/%s/blob/%s/%s#L%d-L%d' % (f['repo'], f['commit'], q, a, b)
local_defs = [(n, k, i) for n, k, i in f['defs'] if a <= i <= b]
for n, k, i in local_defs:
if not leaks(n):
words.append((n, k, f['repo'], f['path'], i, si, bi))
for i in range(a, b + 1):
code_rows.append((f['repo'], f['path'], i, f['lines'][i - 1], si, bi))
cont = '' if a == 1 else ' (continued from <a href="../%s#f%d">section %d</a>)' % (
sname(first_section[fi][0]), first_section[fi][1], first_section[fi][0])
ctx = ''
if f['context'] and (f['repo'], f['context_src']) not in shown_ctx:
shown_ctx.add((f['repo'], f['context_src']))
readme_files.add(fi)
ctx = ('<aside class="ctx"><h3>Environment and domain context</h3><p>%s</p><p class="k">From the nearest '
'README: <a href="https://github.com/Ventusltd/%s/blob/%s/%s">%s/%s</a></p></aside>'
% (E(f['context']), E(f['repo']), f['commit'], urllib.parse.quote(f['context_src']),
E(f['repo']), E(f['context_src'])))
elif f['context']:
readme_files.add(fi)
ved = ''
if f['vedic']:
ved = ''.join('<dt>VEDIC</dt><dd><strong>%s</strong> (%s): %s%s. %s → %s</dd>'
% (E(e['word']), E(e.get('gg_id', '')), E(e.get('estate_group') or ''),
(' · ' + E(e['discipline'])) if e.get('discipline') else '',
E(', '.join(e.get('inputs') or [])), E(str(e.get('output') or '')))
for e in f['vedic'][:3])
uses = ['%s (%s)' % (flink(j, '../'), EDGE_LABEL[k]) for j, k in zip(f['links'][:8], f['link_kinds'])]
if len(f['links']) > 8:
uses.append('and %d more' % (len(f['links']) - 8))
ext_uses = [E(s) for s in f['ext_imports']][:8]
ub = imported_by.get(fi, [])
usedby = ['%s %s (%s)' % (EDGE_VERB[used_kind[(j, fi)]], flink(j, '../'), EDGE_LABEL[used_kind[(j, fi)]])
for j in ub[:8]]
if len(ub) > 8:
usedby.append('and %d more' % (len(ub) - 8))
mb = mentioned_by.get(fi, [])
usedby += ['mentioned in %s (comment link)' % flink(j, '../') for j in mb[:4]]
if len(mb) > 4:
usedby.append('mentioned in %d more (comment links)' % (len(mb) - 4))
defs_html = ', '.join('<a href="../words/%s.html#%s">%s</a>' % (word_page_of(n), slug(n), E(n))
for n, k, i in local_defs[:30])
folder = posixpath.dirname(f['path']) or '/'
flags = []
if f['entry']:
flags.append('<span class="entry">Entry point</span>')
elif not f['reachable']:
flags.append('<span class="flag">Not reached from any entry point (candidate for review)</span>')
if f['pattern']:
pt = E(f['pattern'])
if f['pattern'] in all_names:
pt = '<a href="../words/%s.html#%s">%s</a>' % (word_page_of(f['pattern']), slug(f['pattern']), pt)
flags.append('pattern %s (shared by %d files)' % (pt, f['pattern_n']))
why = E(f['why']) if f['why'] else (
'No other file in the estate was found to import it' + ('; it is an entry point.' if f['entry'] else '.'))
blocks.append(
'%s<section id="f%d" class="file r-%s"><h2>%s</h2><p class="syn">%s</p>%s'
'<p class="k">%s%s / %s · lines %d–%d of %d%s%s%s</p>%s'
'<dl class="v"><dt>What it achieves</dt><dd>%s</dd><dt>Why it matters</dt><dd>%s</dd>'
'<dt>Application</dt><dd><a href="../repos/%s.html">%s</a> · %s · %s</dd>%s'
'<dt>Uses</dt><dd>%s</dd><dt>Used by</dt><dd>%s</dd><dt>Produces</dt><dd>%s</dd>'
'<dt>Defines here</dt><dd>%s</dd>'
'<dt>Cannot conclude</dt><dd>Whether this code runs, is used by a live app today, or is correct. '
'This is a static reading.</dd>'
'<dt>Evidence</dt><dd>%s@%s %s:%d-%d · blob %s · <a href="%s">GitHub at these lines</a></dd>'
'<dt>State</dt><dd>%s</dd></dl><pre><code>%s</code></pre></section>'
% (ctx, bi, f['role'], E(f['title']), E(f['synopsis']), aside_note(fi, '../'),
badge(f['role']), E(f['repo']), E(f['path']), a, b, len(f['lines']),
(' · ' + E(f['version'])) if f['version'] else '', cont,
(' · ' + ' · '.join(flags)) if flags else '', agentdocs.four_part_html(f['four']),
(E(f['achieves']) or 'No statement of purpose was found in the file, a README line naming it, or its name.')
+ (' <span class="cand">%s</span>' % E(f['desc_note']) if f.get('desc_note') else ''), why,
slug(f['repo']), E(f['repo']), E(folder), E(f['kind']), ved,
', '.join(uses + ext_uses) or 'none found', ', '.join(usedby) or 'none found',
E(', '.join(f['exports'][:12])) or 'none declared', defs_html or 'none',
E(f['repo']), f['commit'], E(f['path']), a, b, f['blob'], E(gh),
'achieves: %s · context: %s · stage: %s · effects: %s · domain stage: %s · users: %s · canonical: %s'
% (f['achieves_src'], f['essay_status'], f['stage'], ', '.join(f['effects']) or 'none found',
f['dstage'], ', '.join(f['users']) or 'none', f['canon']),