In this section
- Describe render · cosmic / tools/explore/describe.py lines 1–700
Describe
A Python command-line tool in the explore folder of Cosmic that maps build graph, overhead lines (OHL) and the Renewable Energy Planning Database (REPD) register, using G99/1 and IEC 60287.
rendercosmic / tools/explore/describe.py · lines 1–700 of 1758 · Entry point · pattern clean_comment (shared by 2 files)
- What it does
- It maps build graph, overhead lines (OHL), the REPD register and battery storage (BESS). Defines 67 functions or classes, including _strip_markers, _is_heading, _codeish, _quote, code_quote. Uses libraries argparse, collections, json, os, posixpath. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain terms in the code: overhead lines (OHL), the REPD register, battery storage (BESS).
- Inputs & outputs
- In: JSON file build_graph.json; DuckDB queries; command-line arguments. Out: JSON file; interactive map; SVG drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326, Web Mercator / EPSG:3857.
- Downstream impact
- Used directly by 11 files: Feeder 47 (cosmic); Arena (cosmic); Describe Bigbang (cosmic); Judge (cosmic); and 7 more. Reached from 5 other entry points, including Extras (cosmic); Ship (cosmic); Test Build (cosmic).
- What it achieves
- It cleans comment (`clean_comment`), joins words (`join_words`) and cleans objects (`clean_objects`). Careful one-line descriptions for Explore Code, from evidence only. It accepts `--graph`, `--src` and `--sample`.
- Why it matters
- Imported by 8 files, including Feeder 47, Arena and Describe Bigbang. Checked by 3 tests, including Test Cadastre 27.
- Application
- cosmic · tools/explore · Python CLI
- Uses
- argparse, collections, json, os, posixpath, re, sys
- Used by
- imported by Feeder 47 (sys.path import), imported by Arena (sys.path import), imported by Describe Bigbang (sys.path import), imported by Judge (sys.path import), imported by Cadastre 27 (sys.path import), imported by Primer 48 (sys.path import), imported by Baseline (sys.path import), imported by Test Cadastre 27 (sys.path import), and 3 more
- Produces
- code_quote, clean_comment, leading_comment, config_summary, workflow_facts, main_only, readme_sentences, readme_match, fix_case, article, join_words, dedupe_words
- Defines here
- _strip_markers, _is_heading, _codeish, _quote, code_quote, _sentences, _cap_words, _finish, _strip_name_prefix, clean_comment, leading_comment, config_summary, workflow_facts, main_only, _md_inline, readme_sentences, flush, readme_match, fix_case, fix, word, article, join_words, dedupe_words, expand_once, rep, collapse_expansions, rep, polish_title, word
- 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/describe.py:1-700 · blob bb0a99ba93b52a7fa06c65b18da866bbb292e359 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
r"""tools/explore/describe.py - careful one-line descriptions for Explore Code, from evidence only.
build.py gathers the evidence (title, kind, role, names, the file's own comments, README sentences, data
sources, layer and UI labels, domain nouns, what imports the file, where it is published). This module turns
that evidence into the four texts a reader sees: title, synopsis, achieves (What it achieves) and why (Why it
matters), plus where each came from. It reads no files and makes no network calls; every function is pure
and deterministic, so the same evidence always gives the same words.
Statement discipline (vedic- docs/VEDIC-LANGUAGE.md): say what the evidence shows, say less when it is thin,
and never add a fact (a proper noun, data source, number or URL) that is not in the evidence. Text that comes
from the file is cleaned, not rewritten: status notes, version stamps, hashes, dates, run instructions and
AI banners are dropped; raw identifiers are kept only as `code`.
Entry points
describe(ev) -> {'title', 'synopsis', 'achieves', 'why', 'provenance'}
evidence_from_build(i, files, imported_by, metas, repo_title, titles_by_path, leaks) -> ev for build.py
leading_comment(path, text) -> the file's raw leading comment/docstring (for build.py's capability_of)
clean_comment(raw, ...) -> one or two plain sentences, or ''
readme_sentences(text) -> complete sentences of a README (paragraph lines joined first)
readme_match(sentences, path) -> the sentence that names the file, or ''
config_summary(path, text) -> a configuration file's own title/summary/purpose/description
workflow_facts(text) -> {'name', 'triggers', 'runs', 'publishes'} of a GitHub Actions workflow
polish_title(title) -> title with glued versions split, placeholders dropped, acronyms cased
invented(output, evidence) -> proper nouns / URLs in output that the evidence does not contain
Evidence dict for describe() (every key optional except title and kind):
title, kind, role, repo, repo_title, path, name_words what build.py already has per file
comment raw leading comment (leading_comment) or build.py's cleaned capability text
config config_summary() text; workflow: workflow_facts() dict, plus optional 'run_titles' {script path: estate title}
readme list of README sentences, nearest folder first (readme_sentences)
vedic {'function', 'output', 'inputs': [...], 'word'} for a matched VEDIC meaning
defines defined names, in file order
verb, objects, sources build.py synopsis parts (f['syn_parts']); sources may be '<repo> data'
has_map the file draws a map (MapLibre/Leaflet evidence)
published public URL where the repository shows Pages evidence
dependents [{'title', 'kind', 'role', 'repo', 'published', 'is_map'}] files that import this one
imports [{'title', 'kind', 'repo'}] estate files this one imports (used for tests)
repo_titles {slug: title} to name '<slug> data' sources; entry: bool; main_only: thin entry file
specifics standards and method names found in the source (specifics(text))
context estate experiment facts for this file (attach_context): clarity, verdict, twin, set_aside,
community, element. Optional: load_context() reads the experiment files once (missing -> skip).
Version 2 (GENERATOR_VERSION, CHANGELOG.md): place from folder + repository name, verb-led function clauses one
name each (Big Bang R1), verified standards/methods (R4), an imperative leading comment folded into the synopsis
instead of repeated, and one status line from the experiments (clean manifest, identity, Clarity, lab communities,
periodic elements) in "why". Repository descriptor sentences are never pasted into the synopsis.
"""
import argparse
import collections
import json
import os
import posixpath
import re
import sys
GENERATOR_VERSION = 'describe-3 (2026-12-05)' # bump with a CHANGELOG.md entry when the words change
# Folder words in the synopsis place (won on the Big Bang judge, invented 0). EXPLORE_DESCRIBE_FOLDER=0 turns it off.
FOLDER_PLACE = os.environ.get('EXPLORE_DESCRIBE_FOLDER', '1') != '0'
# ---------------------------------------------------------------- glossary
# lower-case key -> (shown form, expansion or None). Expansions are given once, on first use in a description
# set (title + synopsis + achieves + why), and never when the title already carries them.
GLOSSARY = {
'ohl': ('OHL', 'overhead line'), 'sld': ('SLD', 'single-line diagram'),
'bess': ('BESS', 'battery energy storage system'), 'dno': ('DNO', 'distribution network operator'),
'tso': ('TSO', 'transmission system operator'), 'repd': ('REPD', 'Renewable Energy Planning Database'),
'ugc': ('UGC', 'underground cable'), 'etys': ('ETYS', 'Electricity Ten Year Statement'),
'naei': ('NAEI', 'National Atmospheric Emissions Inventory'), 'ukpn': ('UKPN', 'UK Power Networks'),
'neso': ('NESO', 'National Energy System Operator'), 'bmrs': ('BMRS', 'Balancing Mechanism Reporting Service'),
'ssen': ('SSEN', None), 'pv': ('PV', None), 'gb': ('GB', None), 'uk': ('UK', None), 'gis': ('GIS', None),
}
for _w in ('hv lv mv ac dc api csv json ui ci html css url gpu llm svg pdf kml osm cli http https sql xml dem dtm '
'dsm crs utm rgb mcp cvaa iec bbc rss ckan cfd ppa ev cad bom iso dom ostn15 wgs84 osgb lccc desnz '
'ukceh ngr xlpe ehv mpan mppt sha hs2'.split()):
GLOSSARY.setdefault(_w, (_w.upper(), None))
for _w in ('LiDAR SatNav GridAtlas GeoJSON TopoJSON WebGL WebGPU DuckDB GitHub MapLibre Elexon JavaScript TypeScript '
'GlobalGrid2050 OpenStreetMap PipelineNews Parquet Leaflet ChatGPT PMTiles Playwright pandapower'.split()):
GLOSSARY[_w.lower()] = (_w, None)
UNITS = {'kv': 'kV', 'mv': 'MV', 'kva': 'kVA', 'mva': 'MVA', 'kw': 'kW', 'mw': 'MW', 'gw': 'GW', 'kwh': 'kWh',
'mwh': 'MWh', 'gwh': 'GWh', 'twh': 'TWh', 'hz': 'Hz', 'mm2': 'mm²'}
# Words never re-cased even if they look like a glossary key in running English.
CASE_SKIP = {'ev', 'dom', 'sha', 'mv', 'ci', 'ui', 'cad', 'iso', 'bom', 'ac', 'dc', 'cli', 'gpu', 'ngr', 'http', 'https',
'dem', 'crs', 'utm', 'iec', 'bbc', 'rss', 'cfd', 'ppa', 'mcp'}
# ---------------------------------------------------------------- phrase bank
# (article-free kind noun, map variant). Keyed by build.py's kind.
KIND_NOUN = {
'page': 'web page', 'test': 'test', 'workflow': 'GitHub Actions workflow', 'style sheet': 'style sheet',
'JavaScript module': 'JavaScript module', 'script': 'JavaScript file', 'TypeScript module': 'TypeScript module',
'Python module': 'Python module', 'Python CLI': 'Python command-line tool', 'shell script': 'shell script',
'PowerShell script': 'PowerShell script', 'batch script': 'batch script', 'configuration': 'configuration file',
'SQL query': 'SQL query', 'component': 'UI component', 'shader': 'shader',
}
# build.py verbs -> (verb with objects, verb alone or None). None = too vague to say without objects.
VERBS = {
'maps': ('maps', None), 'draws': ('draws', None), 'fetches': ('fetches', None), 'loads': ('reads', None),
'calculates': ('works with', None), 'tests': ('tests', None), 'runs': ('runs', None),
'builds and publishes': ('builds and publishes', 'builds and publishes the site'),
'lists and searches': ('lists and searches', None),
}
TRIGGER_WORDS = {'push': 'on push', 'pull_request': 'on pull requests', 'pull_request_target': 'on pull requests',
'schedule': 'on a schedule', 'workflow_dispatch': 'by hand', 'workflow_run': 'after another workflow',
'release': 'on release', 'repository_dispatch': 'on an external trigger', 'workflow_call': 'when called'}
VERB_LEAD = { # file names that start with a verb: stem -> third person
'fetch': 'fetches', 'build': 'builds', 'make': 'makes', 'create': 'creates', 'generate': 'generates',
'compile': 'compiles', 'parse': 'parses', 'load': 'loads', 'import': 'imports', 'export': 'exports',
'convert': 'converts', 'validate': 'validates', 'verify': 'verifies', 'check': 'checks', 'compute': 'computes',
'calculate': 'calculates', 'render': 'renders', 'draw': 'draws', 'plot': 'plots', 'update': 'updates',
'sync': 'syncs', 'download': 'downloads', 'merge': 'merges', 'publish': 'publishes', 'deploy': 'deploys',
'scan': 'scans', 'extract': 'extracts', 'clean': 'cleans', 'audit': 'audits',
'derive': 'derives', 'monitor': 'monitors',
'apply': 'applies', 'patch': 'patches', 'refresh': 'refreshes', 'rebuild': 'rebuilds',
'repair': 'repairs', 'track': 'tracks', 'resume': 'resumes', 'promote': 'promotes', 'attest': 'attests',
'backfill': 'backfills', 'restore': 'restores', 'split': 'splits', 'compress': 'compresses', 'sign': 'signs',
'estimate': 'estimates', 'detect': 'detects', 'find': 'finds', 'measure': 'measures',
'collect': 'collects', 'summarise': 'summarises', 'summarize': 'summarizes', 'prepare': 'prepares',
}
# ---------------------------------------------------------------- comment cleaning
BOX = re.compile(r'[─━═│┃┌┐└┘├┤┬┴┼╔╗╚╝║▀▄█■□▪●◆★☆✓✔✗✘→←↑↓⇒•·]{2,}|[─━═]+')
DROP_LINE = re.compile(
r'^\W*(20\d{6,}\b|notice\s*:|(?:module|file|filename|name)\s*:\s*\S+$|spdx|copyright|\(c\)|©|all rights reserved|licen[cs]ed? (under|to)|apache|mit licen|copied unchanged|'
r'copy of|do not (edit|modify|change)|byte-identical|everything below|auto-?generated|generated (by|with|from|on)|'
r'eslint|@ts-|prettier|jshint|global |todo|fixme|xxx|hack\b|usage\s*:|run with|example\s*:|\$ |>>> |'
r'(python3?|node|bash|sh|npm|npx|pip|pwsh|deno)\s+[\w./-]+|modular star family|family #|commit [0-9a-f]{6}|'
r'owner direction|opus team|team-?\d|nl-\d{3}|neural-link|coordination\s*:|-\*-|vim:|@(param|returns?|type|'
r'typedef|module|file|author|license|see|example|throws)\b)', re.I)
AI_BANNER = re.compile(r'\b(chatgpt|claude|codex|gemini|opus|gpt-?\d|copilot)\b.{0,40}\b(generated|wrote|written|'
r'authored|team|session|made|built|created)\b|\b(generated|written|authored|made|built|created)'
r' (by|with) (chatgpt|claude|codex|gemini|opus|gpt-?\d|copilot)', re.I)
STATUS_SENT = re.compile(r'^\W*(?:[\w\-]+\s+){0,2}(?:candidate|retired|deprecated|superseded|frozen|unreviewed|'
r'quarantined|example only|legacy|archived|placeholder|draft)\s*(?:[,:;—–.]|$)|^\W*(?:retired|'
r'deprecated|superseded|unreviewed|quarantined|legacy|archived|placeholder)\b|\b(?:not composed|'
r'not published|no production|do not use|work in progress|preview only|copied (?:unchanged|from)|'
r'generation \d{8,}|version \d|v\d+\.\d+(?:\.\d+)*:)', re.I)
STATUS_PREFIX = re.compile(r'^(?:(?:unreviewed|quarantined|research|regional|candidate|draft|legacy|deprecated|'
r'experimental|example only|retired|archived|preview only|[A-Z]{1,4}-\d{1,3})[\s,]*)+[:;—–-]\s*', re.I)
HASH = re.compile(r'@?\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,64}\b', re.I)
STAMP = re.compile(r'(?<!\d)20\d{6}(?:T?\d{4,6}Z?)?(?!\d)|\b20\d\d-\d\d-\d\d(?:[T ]\d\d:\d\d(?::\d\d)?Z?)?\b')
URL = re.compile(r'https?://[^\s\'"`)<>\]]+')
CODE_EXT = r'(?:mjs|cjs|js|ts|tsx|jsx|py|html?|css|sh|ps1|ya?ml|json|geojson|csv|parquet|md|sql|toml)'
FILE_PREFIX = re.compile(r'^`?[\w.\-/{}]+\.' + CODE_EXT + r'`?(?:\s*(?:[—–:]|-(?=\s)|,)|\s[^—–:`]{0,80}?\s[—–])\s*', re.I)
IDENT = re.compile(r'(?<![`\w./\-])(?:\.{0,2}/?(?:[\w.\-{}*\[\]]+/){2,}[\w.\-{}*\[\]]*|'
r'\.{0,2}/?[\w.\-{}*\[\]]+/(?:[\w\-{}*\[\]]+\.\w+)?(?![\w/])|'
r'[\w\-]+\.' + CODE_EXT + r'\b|[a-z]+[A-Z]\w*|[A-Za-z]+_\w+|\w+\(\))(?![`\w])')
SENT_SPLIT = re.compile(r'(?<=[.!?])\s+(?=[A-Z0-9`"“(\'])')
HEADING = re.compile(r'^[A-Z0-9][A-Z0-9 &/,:()\'\-–—.]{2,}$')
def _strip_markers(line):
s = line.strip()
s = re.sub(r'^(?:/\*+|\*+/|\*+(?=\s|$)|//+|#+(?!!)|<!--|-->|"""|\'\'\'|<#|#>|--(?=\s)|;;+|rem\s)', '', s, flags=re.I)
s = re.sub(r'(?:\*+/|-->|"""|\'\'\'|#>)\s*$', '', s)
s = BOX.sub(' ', s)
return s.strip(' \t*=~_')
def _is_heading(s):
letters = [c for c in s if c.isalpha()]
return bool(letters) and len(s.split()) <= 9 and sum(c.isupper() for c in letters) / len(letters) > 0.8 \
and HEADING.match(s) is not None
def _codeish(s):
"""A line that is code, a command or a column-aligned usage table, not prose."""
return bool(re.search(r'\S {3,}\S', s) or re.match(r'^[\w.]+\s*[=(:{]\s*\S*[)};]?\s*$', s) or
re.search(r'[{}]\s*$|[)\]\'"]\s*;\s*$|=>|\bfunction\s*\w*\s*\(|^\s*(?:import|from)\s+\S+\s+(?:import|from)\b|'
r'\breturn\b.*;|^\s*(?:const|let|var|def|class)\s+\w+', s) or
(sum(c in '{}[]()=<>;|$' for c in s) > max(3, len(s) / 12)))
def _quote(m):
w = m.group(0)
if w.lower() in UNITS or w.lower() in GLOSSARY or re.match(r'^\d', w):
return w
tail = ''
while w and w[-1] in '.,:;':
w, tail = w[:-1], w[-1] + tail
return '`%s`%s' % (w, tail) if w else tail
def code_quote(text):
"""Wrap raw identifiers (camelCase, snake_case, file names, paths, calls) in backticks; URLs and text
already in backticks untouched."""
if '`' in text:
return ''.join(seg if seg.startswith('`') and seg.endswith('`') and len(seg) > 1 else code_quote(seg)
for seg in re.split(r'(`[^`]*`)', text))
out, last = [], 0
for m in URL.finditer(text):
out.append(IDENT.sub(_quote, text[last:m.start()]))
out.append(m.group(0))
last = m.end()
out.append(IDENT.sub(_quote, text[last:]))
return ''.join(out)
def _sentences(text):
return [s.strip() for s in SENT_SPLIT.split(text) if s.strip()]
def _cap_words(text, n):
"""At most n words, cut at a clause boundary when possible; ends with punctuation."""
ws = text.split()
if len(ws) <= n:
return text
head = ' '.join(ws[:n])
for sep in ('; ', ' — ', ' – ', ': ', ', '):
k = head.rfind(sep)
if k >= len(head) * 0.5:
return head[:k].rstrip(',;:—– ') + '.'
return head.rstrip(',;:—– ') + '…'
def _finish(s):
s = re.sub(r'\s+', ' ', s).strip(' ,;:-—–')
s = re.sub(r'…\.+$', '…', s)
if s and s[-1] not in '.!?…':
s += '…' if re.search(r'\b(the|a|an|so|and|or|of|to|for|in|on|with|that|by|from|as)$', s, re.I) else '.'
if s and s[0].islower() and not s.startswith('`'):
s = s[0].upper() + s[1:]
return s
def _strip_name_prefix(s, names):
"""Drop a leading 'name — ', 'name: ', 'name - ' where name is the file, its stem, or the repository."""
s2 = FILE_PREFIX.sub('', s, count=1)
if s2 != s:
return s2
for n in names:
if not n:
continue
variants = {n, n.replace('_', ' '), n.replace('-', ' '), n.replace('_', '-'), n.replace('-', '_')}
for v in sorted(variants, key=len, reverse=True):
m = re.match(r'^`?%s`?\s*(?:[—–:]|-(?=\s))\s*' % re.escape(v), s, re.I)
if m and len(s) - m.end() > 8:
return s[m.end():]
return s
def clean_comment(raw, file_name='', names=(), max_words=40, title=''):
"""Developer comment -> one or two plain sentences ('' if nothing usable remains). Sentences that only
restate `title` are skipped, so a docstring whose first line repeats the file name yields its next line."""
if not raw:
return ''
raw = re.sub(r'<[^>]{1,200}>', ' ', raw)
paras, cur = [], []
for line in raw.replace('\r', '').split('\n'):
s = _strip_markers(line)
s = re.sub(r'(?:^|[\s,;(-])(?:usage|run|run with|example|requires)\s*:\s.*$', '', s, flags=re.I).strip()
if not s:
if cur:
paras.append(cur)
cur = []
continue
if DROP_LINE.match(s) or AI_BANNER.search(s) or _codeish(s):
if cur and DROP_LINE.match(s) is None and not _codeish(s):
paras.append(cur)
cur = []
continue
if _is_heading(s) or re.match(r'^[\w ]{2,30}:$', s):
if cur:
paras.append(cur)
cur = []
continue
cur.append(s)
if cur:
paras.append(cur)
stem = posixpath.basename(file_name).split('.')[0] if file_name else ''
keep = []
for p in paras:
text = ''
for s in p:
if text and not re.search(r'[.!?:;,(\-—–]$', text) and (re.match(r'^[A-Z][a-z]+(?:s|ed)\b', s) or
(len(text.split()) <= 5 and re.match(r'^[A-Z][a-z]', s))):
text += '.' # "... from energysecurity.gov.uk" / "Parses to GeoJSON": a new sentence
text = (text + ' ' + s).strip()
text = URL.sub(lambda m: re.sub(r'^https?://(www\.)?', '', m.group(0)).split('/')[0], text)
text = re.sub(r'[,;]?\s*\bgeneration\s+20\d{6,}\w*(?:\s*\(UTC\))?|[,;]?\s*\bApache-2\.0\b(?:\s*\([^)]*\))?', '',
text, flags=re.I)
text = code_quote(text)
text = re.sub(r'(?::\s*|\s)(?:python3?|node|bash|npx|pwsh|deno)(?:\s+-[-\w]+)*\s+`[^`]+`[^.;]*', '', text)
text = ''.join(seg if seg.startswith('`') else STAMP.sub('', HASH.sub('', seg))
for seg in re.split(r'(`[^`]*`)', text))
text = re.sub(r'\(\s*(?:UTC)?\s*\)|\s+,', lambda m: '' if m.group(0).startswith('(') else ',', text)
text = _strip_name_prefix(text, [file_name and posixpath.basename(file_name), stem] + list(names))
for sent in _sentences(text):
sent = STATUS_PREFIX.sub('', sent).strip()
sent = re.sub(r'^(?:Tests?|Checks?)\s*:\s*', 'Tests ', sent)
sent = re.sub(r'^(?:Step|Purpose|Summary|What|Why)\s*:\s*', '', sent)
sent = _strip_name_prefix(sent, [stem] + list(names))
words = re.findall(r'[A-Za-z]{2,}', sent)
if len(words) < 3 or (STATUS_SENT.search(sent) and len(sent.split()) <= 14):
continue
if re.match(r'^(see|usage|example|note|todo|copyright)\b', sent, re.I):
continue
letters = re.sub(r'`[^`]*`|[^A-Za-z]', '', sent)
if letters and sum(c.isupper() for c in letters) / len(letters) > 0.7 and len(sent.split()) > 3:
continue # SHOUTED banner sentences
if re.search(r'\bcopyright\b|©|all rights reserved', sent, re.I):
continue
if len(re.findall(r':\d+', sent)) >= 3:
continue # line-number reference lists
if title and _restates(sent, title + ' ' + ' '.join(names)):
continue
keep.append(sent)
if keep:
break
if not keep:
return ''
out = keep[0]
if len(out.split()) < 6 and len(keep) > 1:
out = out.rstrip() + ('' if out.rstrip()[-1:] in '.!?' else '.') + ' ' + keep[1]
out = _cap_words(out, max_words)
return fix_case(_finish(out))
# ---------------------------------------------------------------- reading the file's own words
def leading_comment(path, text):
"""Raw leading comment / docstring / HTML description of a file (uncleaned; '' if none)."""
e = path.rsplit('.', 1)[-1].lower() if '.' in path else ''
lines = text.replace('\r', '').split('\n')[:80]
head = '\n'.join(lines)
if e in ('html', 'htm'):
out = []
for rx in (r'<meta\s+name=["\']description["\']\s+content=["\']([^"\']+)', r'<!--(.*?)-->',
r'<title>([^<]+)</title>'):
m = re.search(rx, head, re.I | re.S)
if m:
out.append(re.sub(r'\s+[|·]\s+', '.\n\n', m.group(1).strip()))
return '\n\n'.join(out)
if e == 'py':
m = re.match(r'\s*(?:#[^\n]*\n|\s*\n)*\s*[rubRUB]*("""|\'\'\')(.*?)\1', head, re.S)
cm = []
for l in lines[:30]:
if l.strip().startswith('#'):
if not l.startswith('#!') and not re.match(r'^#.*coding[:=]', l):
cm.append(l)
elif l.strip() and not (not cm and re.match(r'^(import|from)\s', l)):
break
return '\n'.join(([m.group(2), ''] if m else []) + cm[:12])
if e in ('ps1',):
m = re.search(r'<#(.*?)#>', head, re.S)
if m:
return m.group(1)
block = re.match(r'\s*(?:#![^\n]*\n)?(?:\s*(?:[\'"]use \w+[\'"];?|import\b[^\n]*|//[^\n]*)\n)*?\s*/\*(.*?)\*/', head, re.S)
out, started = [], False
for l in lines[:50]:
s = l.strip()
if s.startswith(('//', '#')) and not s.startswith('#!'):
out.append(s)
started = True
elif started and s:
break
elif s and not re.match(r"""^(['"]use \w+['"];?|import\b|<!doctype|<html|---$|%YAML)""", s, re.I) and not started:
if block is None:
break
parts = []
if block:
parts.append(block.group(1))
if out:
parts.append('\n'.join(out))
return '\n\n'.join(parts)
def config_summary(path, text):
"""A configuration file's own statement: top-level description/summary/purpose/title (YAML, JSON, TOML)."""
keys = ('description', 'summary', 'purpose', 'title', 'about')
found = {}
for line in text.replace('\r', '').split('\n')[:120]:
m = re.match(r'^["\']?(%s)["\']?\s*[:=]\s*["\']?(.*?)["\']?,?\s*$' % '|'.join(keys), line, re.I)
if m and m.group(1).lower() not in found:
v = m.group(2).strip()
if v in ('>', '|', '>-', '|-', ''):
rest = text.split(line, 1)[1].split('\n')
v = ' '.join(l.strip() for l in rest[:6] if l.startswith((' ', '\t')) and l.strip())
found[m.group(1).lower()] = v
for k in ('description', 'summary', 'purpose', 'about'):
if len(found.get(k, '').split()) >= 4:
return found[k]
if len(found.get('title', '').split()) >= 3:
return found['title']
return ''
def workflow_facts(text):
"""Name, triggers, scripts run and whether it publishes, from a GitHub Actions workflow file."""
m = re.search(r'^name:\s*["\']?([^"\'#\n]+?)["\']?\s*$', text, re.M)
trig = []
on = re.search(r'^(?:on|"on"|\'on\'|true):\s*(.*?)(?=^\S)', text + '\nx', re.M | re.S)
if on:
body = on.group(1)
for k in TRIGGER_WORDS:
if re.search(r'(^|[\s\[,])%s\b' % k, body):
trig.append(k)
runs = []
for r in re.findall(r'(?:python3?|node|bash|sh|pwsh|deno run)\s+(?:-\w+\s+)*([\w./-]+\.(?:py|mjs|js|cjs|sh|ps1|ts))', text):
if r not in runs:
runs.append(r)
pub = bool(re.search(r'deploy-pages|upload-pages-artifact|gh-pages|peaceiris/actions-gh-pages', text))
return {'name': m.group(1).strip() if m else '', 'triggers': trig, 'runs': runs[:4], 'publishes': pub}
def main_only(text):
"""A thin entry file: only imports and a call to main(); returns the module it runs, or ''."""
code = [l.strip() for l in text.split('\n') if l.strip() and not l.strip().startswith(('#', '"""', "'''"))]
if not code or len(code) > 6 or not any(re.match(r'^(?:raise SystemExit\()?main\(\)\)?$', l) or
l.startswith('sys.exit(main())') for l in code):
return ''
for l in code:
m = re.match(r'^from\s+([\w.]+)\s+import\s+main\b', l)
if m:
return m.group(1)
return 'main'
# ---------------------------------------------------------------- READMEs
def _md_inline(t):
t = re.sub(r'!\[[^\]]*\]\([^)]*\)', '', t)
t = re.sub(r'\[([^\]]+)\]\([^)]*\)', r'\1', t)
t = re.sub(r'(\*\*|__)(.+?)\1', r'\2', t)
t = re.sub(r'(?<![\w*])\*(?!\s)(.+?)\*(?!\w)', r'\1', t)
t = re.sub(r'<[^>]+>', '', t)
return re.sub(r'\s+', ' ', t).strip()
def readme_sentences(text, cap=300):
"""Complete sentences of a README: paragraph lines joined first (so wrapped lines are not cut), list
items kept whole, code, tables, headings, HTML and badges skipped."""
text = re.sub(r'<!--.*?-->', '', text.replace('\r', ''), flags=re.S)
if text.startswith('---\n'):
end = text.find('\n---', 4)
text = text[end + 4:] if end > 0 else text
paras, cur, fence = [], [], False
def flush():
if cur:
paras.append(' '.join(cur))
cur.clear()
for line in text.split('\n'):
s = line.strip()
if s.startswith(('```', '~~~')):
fence = not fence
flush()
continue
if fence or line.startswith((' ', '\t')) and not cur:
continue
if not s or s.startswith(('#', '|', '<', '[![', '![')) or re.match(r'^[-=*_]{3,}$', s):
flush()
continue
if re.match(r'^([-*+]|\d+[.)])\s+', s):
flush()
s = re.sub(r'^([-*+]|\d+[.)])\s+', '', s)
cur.append(s.lstrip('> ').strip())
flush()
out = []
for p in paras:
for sent in _sentences(_md_inline(p)):
if 5 <= len(sent.split()) <= 60 and re.search(r'[.!?:)]$|[a-z]$', sent):
out.append(sent)
if len(out) >= cap:
return out
return out
README_REJECT = re.compile(r'^(run|use|open|install|see|click|clone|copy|then|to run|type|press|go to|visit|cd|'
r'validation|commands?|example|usage)\b|`[^`]*\b(node|python3?|npm|npx|bash)\b|'
r'\bPR #\d|\bmerged\b|\bvalidated\b|\bpassed\b|\breceipt\b|\bcommit\b|^\W*$', re.I)
README_STOP = {'index', 'main', 'app', 'page', 'script', 'module', 'utils', 'util', 'core', 'data', 'file', 'test',
'tests', 'tools', 'tool', 'html', 'style', 'styles', 'version', 'final', 'copy', 'with', 'from', 'this',
'that', 'browser', 'build', 'check', 'config', 'common', 'shared', 'lib', 'helpers', 'run'}
def readme_match(sentences, path):
"""The README sentence that names this file (exact file name, or its stem as a word); the clause about
the file when a sentence names several files. '' if none: a sentence that only shares words is not used."""
name = posixpath.basename(path)
stem = name.split('.')[0]
stem_words = [w for w in re.split(r'[_\-\s.]+', re.sub(r'(?<!\d)20\d{6,}', '', stem).lower())
if len(w) >= 4 and w not in README_STOP]
best, best_score = '', 0
for sent in sentences:
if README_REJECT.search(sent):
continue
low = sent.lower()
score = 0
if re.search(r'(?<![\w-])%s(?![\w-])' % re.escape(name.lower()), low):
score = 3
elif len(stem) >= 5 and re.search(r'[-_]', stem) and \
re.search(r'(?<![\w-])%s(?![\w-])' % re.escape(stem.lower()), low):
score = 2
elif len(stem_words) >= 3 and all(re.search(r'\b%s' % w, low) for w in stem_words):
score = 1
if score > best_score:
best, best_score = sent, score
if not best:
return ''
clauses = re.split(r';\s+|\.\s+', best)
if len(clauses) > 1:
for c in clauses:
if name.lower() in c.lower() or stem.lower() in c.lower():
best = c
break
return best
# ---------------------------------------------------------------- English helpers
def fix_case(text):
"""Domain capitalisation (kV, GB, DNO, REPD, LiDAR, SatNav, GridAtlas ...) outside code and URLs."""
def fix(seg):
def word(m):
w = m.group(0)
lo = w.lower()
mu = re.match(r'^(\d+(?:\.\d+)?)\s?(%s)$' % '|'.join(UNITS), lo)
if mu:
return mu.group(1) + UNITS[mu.group(2)]
if lo in GLOSSARY and lo not in CASE_SKIP:
shown = GLOSSARY[lo][0]
return shown
return w
return re.sub(r'\b\d+(?:\.\d+)?\s?(?:%s)\b|\b[A-Za-z][A-Za-z0-9]*\b' % '|'.join(UNITS), word, seg, flags=re.I)
parts = re.split(r'(`[^`]*`|https?://\S+|"[^"]*"|\b[\w-]+(?:\.[\w-]+)+\b)', text)
return ''.join(p if i % 2 else fix(p) for i, p in enumerate(parts))
def article(phrase):
w = phrase.split()[0] if phrase.split() else ''
if not w:
return 'a'
if w.isupper() and len(w) <= 5:
return 'an' if w[0] in 'AEFHILMNORSX' else 'a'
lo = w.lower()
if lo.startswith(('uni', 'use', 'usa', 'one', 'eu', 'ure')):
return 'a'
if lo.startswith(('hour', 'honest')):
return 'an'
return 'an' if lo[0] in 'aeiou' else 'a'
def join_words(xs):
xs = [x for x in xs if x]
if not xs:
return ''
return xs[0] if len(xs) == 1 else ', '.join(xs[:-1]) + ' and ' + xs[-1]
def dedupe_words(text):
"""'data data' -> 'data'; 'Test for Test X' style doubles."""
return re.sub(r'\b(\w+)(\s+\1\b)+', r'\1', text, flags=re.I)
def expand_once(text, already, protect=()):
"""Expand glossary abbreviations on first use ('DNO' -> 'distribution network operator (DNO)'), skipping any
that `already` (the title, where the reader meets it first) contains, any earlier in this text, and any inside
a `protect` phrase (a repository name is a name, not prose)."""
seen = set(a for a in GLOSSARY if GLOSSARY[a][1] and re.search(r'\b%s\b' % GLOSSARY[a][0], already))
for ph in protect:
if ph and ph in text:
text = text.replace(ph, '\x00%d\x00' % protect.index(ph))
restore = lambda t: re.sub(r'\x00(\d+)\x00', lambda m: protect[int(m.group(1))], t)
def rep(m):
lo = m.group(0).lower()
if lo in seen or not GLOSSARY.get(lo, (0, None))[1]:
return m.group(0)
seen.add(lo)
long_ = GLOSSARY[lo][1]
return '%s (%s)' % (long_, GLOSSARY[lo][0])
parts = re.split(r'(`[^`]*`|https?://\S+|"[^"]*"|\([A-Z]{2,5}\))', text)
for i, p in enumerate(parts):
if i % 2 == 0:
parts[i] = re.sub(r'\b(?:%s)\b' % '|'.join(GLOSSARY[k][0] for k in GLOSSARY if GLOSSARY[k][1]), rep, p)
else:
mm = re.match(r'^\(([A-Z]{2,5})\)$', p)
if mm:
seen.add(mm.group(1).lower())
return restore(''.join(parts))
def collapse_expansions(text):
"""'Renewable Energy Planning Database (REPD) Source' -> 'REPD Source': the words before '(ABBR)' whose
initials spell ABBR are replaced by ABBR."""
def rep(m):
ab = m.group(2)
ws = m.group(1).split()
for n in range(min(len(ws), len(ab) + 2), 0, -1):
init = ''.join(w[0] for w in re.split(r'[\s-]+', ' '.join(ws[-n:])) if w).upper()
if init == ab.upper():
return ' '.join(ws[:-n] + [ab]).strip()
return m.group(0)
return re.sub(r'((?:[A-Za-z][\w-]*\s+){1,7}?)\(([A-Z]{2,6})\)', lambda m: rep(m) + ' ', text).replace(' ', ' ').strip()
def polish_title(title):
"""Light title repair: glued version suffixes split ('Sourcesv7' -> 'Sources v7'), template placeholders
dropped ('{GEN} '), acronyms cased from the glossary ('Bbc Rss' -> 'BBC RSS', 'Mwh' -> 'MWh')."""
t = re.sub(r'\{[A-Z_]+\}\s*', '', title)
t = re.sub(r'\b([A-Za-z]{3,}?)v(\d+(?:[._]\d+)*)\b', lambda m: '%s v%s' % (m.group(1), m.group(2))
if m.group(1).lower() not in ('dri', 'ser', 'mo') else m.group(0), t)
def word(m):
w = m.group(0)
lo = w.lower()
if lo in UNITS:
return UNITS[lo]
if lo in GLOSSARY and (w.istitle() or w.islower()) and lo not in ('ev', 'dom', 'iso', 'bom', 'cad', 'sha'):
return GLOSSARY[lo][0]
return w
t = re.sub(r'(?<![\w(])[A-Za-z][a-z0-9]*\b', word, t)
t = re.sub(r'(?<=\w) a$', ' A', t)
return dedupe_words(re.sub(r'\s+', ' ', t)).strip(' —-') or title
# ---------------------------------------------------------------- evidence filters
JUNK_OBJ = {'style', 'data', 'its inputs', 'current', 'next', 'negative', 'code', 'array', 'run', 'result', 'results',
'none', 'absent', 'seed', 'receipt', 'status', 'choice', 'output', 'input', 'value', 'values', 'item',
'items', 'list', 'state', 'main', 'default', 'config', 'library', 'graph', 'random', 'record', 'report',
'evidence', 'nodes', 'edges', 'keys', 'modules', 'layers', 'editions', 'universe', 'derived', 'apps',
'automation', 'release', 'live set', 'browser registry', 'candidate', 'candidates', 'build', 'registry',
'manifest', 'snapshot', 'proof', 'check', 'checks', 'verification', 'replacement', 'presentation',
'homepage', 'entity types', 'scopes preflight', 'center only', 'cells result', 'coords', 'atoms', 'rb'}
DOMAIN_OBJ = re.compile(r'^(substations|overhead lines( \(OHL\))?|underground cables|cables|solar|battery storage'
r'( \(BESS\))?|the REPD register|interconnectors|transformers|wind|LiDAR terrain|postcodes|'
r'A roads|B roads|motorways|\d{2,3}kV(/\d{3}V)?)$')
def clean_objects(objects, title='', kind='', role=''):
"""Drop object phrases that are code, hashes, placeholders, generic words or the title itself."""
out = []
tl = title.lower()
for o in objects or []:
o = o.strip()
lo = o.lower().strip('"')
if not o or len(lo) < 3 or lo in JUNK_OBJ or HASH.search(o) or STAMP.search(o):
continue
if re.search(r'[%${}+<>\\|=]|\besc\(|\(|\)\s*$|^\W|\d{4,}', o.replace('(OHL)', '').replace('(BESS)', '')):
continue
if o.startswith('"'):
label = o.strip('"')
if label.lower() in tl or tl in label.lower() or not re.search(r'[a-z]', label) or len(label.split()) > 6:
continue # UI labels that repeat the title, are shouted, or are long sentences say little
o = '“%s”' % label
elif (lo in tl or (len(tl.split()) >= 2 and tl in lo)) and not DOMAIN_OBJ.match(o):
continue
if kind in ('test', 'workflow') and not DOMAIN_OBJ.match(o):
continue # fixture words in tests are not what the test covers
if any(lo == x.lower().strip('“”') for x in out):
continue
out.append(o)
return out[:4]
def clean_sources(sources, repo='', repo_titles=None):
out = []
for s in sources or []:
s = s.strip()
if not s or re.search(r'[%${}]|127\.0\.0\.1|localhost|0\.0\.0\.0|:\d+$', s):
continue
m = re.match(r'^([\w.\-]+) data$', s)
if m:
slug = m.group(1)
if slug.lower() == (repo or '').lower():
continue
name = (repo_titles or {}).get(slug) or slug
s = name + ' repository'
if s not in out:
out.append(s)
return out[:3]
def _repo_list(srcs):
"""['GridAtlas repository', 'Spiders repository', 'NESO data portal'] -> 'the GridAtlas and Spiders
repositories and NESO data portal'."""
repos = [s[:-11] for s in srcs if s.endswith(' repository')]
other = [s for s in srcs if not s.endswith(' repository')]
parts = list(other)
if repos:
parts.append('the %s %s' % (join_words(repos), 'repository' if len(repos) == 1 else 'repositories'))
return join_words(parts)
def _page_name(title):
parts = [p.strip() for p in title.split(' — ')]
name = parts[-1]
if re.sub(r'\s*(Index )?Page$', '', name).strip().lower() in ('', 'index', 'app', 'main') and len(parts) > 1:
name = parts[-2]
return re.sub(r'\s*(Index )?Page$', '', name).strip() or title
# ---------------------------------------------------------------- code evidence (owner review 2026-12-05)
# When a file has no comment or README evidence its synopsis used to say only kind + repository + topic. code_facts()
# reads what the code itself computes and gives one evidence-only verb phrase. Words come only from the file's
# identifiers and strings (split camelCase / snake_case, GLOSSARY and UNITS applied) or from the fixed FORMULAS,
# DRAWING and UNIT_WORDS tables below, whose phrases name a recognised formula or call, never a fact about the world.
CODE_VERBS = dict(VERB_LEAD, calc='calculates', format='formats', sort='sorts', filter='filters', normalise='normalises',
normalize='normalizes', resolve='resolves', read='reads', write='writes', save='saves', show='shows',
toggle='toggles', search='searches', add='adds', remove='removes', snap='snaps', score='scores',
rank='ranks', match='matches', group='groups', count='counts', list='lists', encode='encodes',
decode='decodes', interpolate='interpolates', simulate='simulates', solve='solves', optimise='optimises',
optimize='optimizes', classify='classifies', assign='assigns', place='places', animate='animates',