In this section
- Cadastre 27 ingest · cosmic / tools/explore/bigbang/rules/CADASTRE-27.py lines 1–585
Cadastre 27
A Python command-line tool in the rules folder of Cosmic that reads build graph and dictionary, using haversine and Vincenty.
ingestcosmic / tools/explore/bigbang/rules/CADASTRE-27.py · lines 1–585 of 585 · Entry point · pattern _first_sentence (shared by 2 files)
- What it does
- It loads build graph and dictionary. Defines 26 functions or classes, including _graph, _dictionary, _readme_for, _words, _area. Uses libraries collections, json, os, posixpath, re. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file build_graph.json; JSON file dictionary.json; command-line arguments. Coordinate systems named: WGS84 / EPSG:4326, Web Mercator / EPSG:3857.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the rank step (`rank`) and the translate step (`translate`). ESTATE CONTEXT rule set for the big bang translation tournament.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- cosmic · tools/explore/bigbang/rules · Python CLI
- Uses
- Build (sys.path import), Describe (sys.path import), collections, json, os, posixpath, re, sys
- Used by
- none found
- Produces
- translate
- Defines here
- _graph, _dictionary, _readme_for, _words, _area, _first_sentence, _plain, _short, _fact, _connections, rank, _family, _dict_word, _uniq, _cap, _clip_words, _verb3, _func_doc, _doc_clause, _params, _explain, _main_functions, _context_sentence, _code_terms, _sent, translate
- 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/bigbang/rules/CADASTRE-27.py:1-585 · blob 7ac105559faeb4febcf4cbe2860600df92431950 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""bigbang/rules/CADASTRE-27.py - ESTATE CONTEXT rule set for the big bang translation tournament.
Translates a file by where it lives and how it is connected, then adds one verified fact about its code:
* repository title (build.repo_title) and the folder the file sits in, with timestamp prefixes removed;
* the README paragraph of the nearest folder whose README passes build.readme_pick at README_THRESHOLD;
* the page that loads the file and the files it uses or is used by (build_graph.json dependents/imports,
edge kinds from the graph's edges list for the verb: loaded by / imported by / run by ...);
* the timestamp family (sibling copies whose path differs only in a 20YYMMDDhhmm stamp);
* the live URL (the file's own 'published', else that of the page that loads it);
* a vedic- dictionary word when a defined name matches a dictionary entry (build.vedic_matches rule) or
a fingerprint candidate row that is already a dictionary word.
The code fact comes from describe.code_facts, else the file's own leading comment, else its defined names.
Evidence only: every name used comes from the graph, the source, its README or the vedic- data files.
Deterministic, stdlib only, no network.
translate(file_record, source_text) -> {'title', 'synopsis', 'achieves'}
"""
import collections
import json
import os
import posixpath
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
EXPLORE = os.path.dirname(os.path.dirname(HERE))
if EXPLORE not in sys.path:
sys.path.insert(0, EXPLORE)
import build # noqa: E402 (read-only use: repo_title, readme_pick, README_THRESHOLD)
import describe # noqa: E402 (read-only use: code_facts, leading_comment, clean_comment, polish_title)
GRAPH = os.environ.get('BIGBANG_GRAPH', '/tmp/site8/explore-code/build_graph.json')
SRC = os.environ.get('BIGBANG_SRC', '/home/claude/src')
VEDIC = os.environ.get('BIGBANG_VEDIC', '/home/claude/vedic-')
STAMP_SEG = re.compile(r'(?<![0-9])20\d{6}(?:\d{2,6})?(?![0-9])')
GENERIC_DIRS = {'src', 'js', 'lib', 'libs', 'assets', 'static', 'public', 'dist', 'scripts', 'script', 'app', 'apps',
'modules', 'module', 'core', 'css', 'styles', 'releases', 'release', 'versions', 'build', 'web',
'site', 'docs', 'pages', 'www', 'code', 'tools', 'utils', 'util', 'helpers', 'common', 'shared',
'engine', 'original', 'current', 'latest', 'v', 'data', 'files', 'test', 'tests', 'archive'}
VERB = {'script-src': 'loaded by', 'stylesheet': 'styles', 'modulepreload': 'loaded by', 'import': 'imported by',
'python-relative': 'imported by', 'sys-path': 'imported by', 'require': 'required by',
'dynamic-import': 'imported by', 'url-import-meta': 'loaded by', 'iframe': 'embedded in',
'script-call': 'run by', 'workflow-run': 'run by', 'worker': 'started by', 'fetch': 'fetched by',
'link': 'linked from', 'estate-url': 'named in'}
LOAD_KINDS = ('script-src', 'stylesheet', 'modulepreload', 'import', 'python-relative', 'sys-path', 'require',
'dynamic-import', 'url-import-meta', 'iframe', 'script-call', 'workflow-run', 'worker', 'fetch')
RELIGIOUS = re.compile(r'\b(god|gods|divine|sacred|holy|spiritual|religio\w*|scripture\w*|mantra\w*|veda|vedas|'
r'vedic|hindu\w*|temple|prayer\w*|worship\w*|deity|deities|soul)\b', re.I)
_STATE = {}
# ---------------------------------------------------------------- estate data (loaded once)
def _graph():
if 'g' not in _STATE:
try:
with open(GRAPH, encoding='utf-8') as fh:
g = json.load(fh)
except OSError:
g = {'files': [], 'edges': []}
F = g.get('files') or []
kinds = collections.defaultdict(dict) # kinds[user][used] = edge kind
for e in g.get('edges') or []:
a, b, k = e[0], e[1], e[2]
if k != 'comment-url':
kinds[a].setdefault(b, k)
fam = collections.defaultdict(list)
for f in F:
if STAMP_SEG.search(f['path']):
fam[(f['repo'], STAMP_SEG.sub('*', f['path']))].append(f['id'])
_STATE.update(g=g, F=F, kinds=kinds, fam=fam, readme={})
return _STATE
def _dictionary():
if 'dict' not in _STATE:
by_name = collections.defaultdict(list)
try:
with open(os.path.join(VEDIC, 'data', 'dictionary.json'), encoding='utf-8') as fh:
entries = json.load(fh).get('entries', [])
except (OSError, ValueError):
entries = []
words = set()
for e in entries:
if not e.get('word'):
continue
words.add(e['word'])
parts = (e.get('translation_ref') or '').split(':')
ref = parts[-1].strip()
if ref:
mods = [t.lower() for t in parts[:-1] if t and not t.isdigit() and t not in ('source', 'engine')]
by_name[ref].append((e['word'], mods, e.get('output') or ''))
fp = collections.defaultdict(set) # fingerprint name -> dictionary words (rows already in the dictionary)
try:
with open(os.path.join(VEDIC, 'fingerprints', 'out', 'candidates.md'), encoding='utf-8') as fh:
for line in fh:
c = [x.strip() for x in line.split('|')]
if len(c) > 5 and c[1].isdigit() and c[4] in words:
for n in re.split(r',\s*', re.sub(r'\(\+\d+ siblings?\)', '', c[3])):
n = n.strip()
if len(n) >= 4:
fp[n].add(c[4])
except OSError:
pass
_STATE['dict'] = (by_name, fp)
return _STATE['dict']
def _readme_for(repo, d):
"""(paragraph, folder) from the nearest README in the folder chain that passes readme_pick at threshold."""
st = _graph()
cache = st['readme']
while True:
key = (repo, d)
if key not in cache:
cache[key] = ''
base = os.path.join(SRC, repo, d)
try:
for n in sorted(os.listdir(base)):
if re.match(r'^readme(\.(md|markdown|txt))?$', n, re.I):
with open(os.path.join(base, n), encoding='utf-8', errors='replace') as fh:
text, score = build.readme_pick(fh.read(), repo)
if text and score is not None and score >= build.README_THRESHOLD:
cache[key] = text
break
except OSError:
pass
if cache[key]:
return cache[key], d
if not d:
return '', ''
d = posixpath.dirname(d)
# ---------------------------------------------------------------- phrasing helpers
def _words(seg):
seg = STAMP_SEG.sub(' ', seg)
seg = re.sub(r'\.[a-z0-9]+$', '', seg)
seg = re.sub(r'([a-z])([A-Z])', r'\1 \2', seg)
return [w for w in re.split(r'[^A-Za-z0-9]+', seg) if w and not re.match(r'^v?\d+$', w, re.I)]
def _area(path, skip=''):
"""Plain name of the folder area a file sits in, e.g. 'solar design studio site world'."""
segs = path.split('/')[:-1]
keep = []
for s in segs:
ws = [w for w in _words(s) if w.lower() not in GENERIC_DIRS]
if ws:
keep.append(' '.join(w.lower() for w in ws))
out = []
sk = re.sub(r'[^a-z0-9]', '', skip.lower())
keep = [k for k in keep if not sk or re.sub(r'[^a-z0-9]', '', k) not in sk]
return keep[0] if keep else ''
def _first_sentence(text, cap=32):
text = describe.HASH.sub('', describe.STAMP.sub('', text))
text = describe.URL.sub('', text)
s = re.split(r'(?<=[.!?])\s+(?=[A-Z0-9"(])', text.strip())[0].strip()
ws = s.split()
if len(ws) > cap:
return ''
s = s.rstrip(' .;:,')
return s
def _plain(name):
return describe.polish_title(name) if name else ''
def _short(name):
"""Short form of an estate title: the part after the last ' — ' (the file's own name)."""
t = _plain(name)
return t.split(' — ')[-1] if ' — ' in t else t
def _fact(rec, text):
"""One verified fact about the code: (phrase, identifiers)."""
defines = rec.get('defines') or []
if rec.get('kind') == 'workflow' or re.search(r'^jobs:', text or '', re.M) and rec.get('path', '').endswith(('.yml', '.yaml')):
wf = describe.workflow_facts(text or '')
runs = [r for r in wf.get('runs') or [] if r in text][:2]
trig = [describe.TRIGGER_WORDS[t] for t in wf.get('triggers') or [] if t in describe.TRIGGER_WORDS][:3]
if runs:
ph = 'runs %s' % describe.join_words('`%s`' % r for r in runs)
if trig:
ph += ' %s' % describe.join_words(trig)
if wf.get('publishes'):
ph += ' and publishes the site'
return ph, runs
if trig:
return 'is a GitHub Actions workflow that runs %s' % describe.join_words(trig), []
raw = describe.leading_comment(rec.get('path', ''), text or '')
dc = _doc_clause(raw, '\0')
if dc:
return dc[3:], []
cf = describe.code_facts(text or '', rec.get('kind', ''), defines, rec.get('title', ''))
if cf and cf.get('phrase'):
return cf['phrase'], cf.get('terms') or []
c = describe.clean_comment(raw, posixpath.basename(rec.get('path', '')), defines, 24, rec.get('title', ''))
if c:
c = _first_sentence(c, 20)
if c and not RELIGIOUS.search(c) and not BAD_PLAIN.search(c) and not re.search(r'[`:;()\[\]{}<>=|-]', c) \
and not re.search(r'\b(?:and|for|an|the|of|to|a)$', c):
return 'says of itself: "%s"' % c, []
names = [n for n in defines if len(n) >= 4 and not n.startswith('_') and n in (text or '')
and re.match(r'^[A-Za-z_$][\w$.]*$', n)][:3]
if names:
return 'defines %s' % describe.join_words('`%s`' % n for n in names), names
return '', []
def _connections(rec):
st = _graph()
F, kinds = st['F'], st['kinds']
i = rec.get('id')
users = []
for j in rec.get('dependents') or []:
if 0 <= j < len(F):
users.append((F[j], kinds.get(j, {}).get(i, '')))
uses = [F[j] for j in rec.get('imports') or [] if 0 <= j < len(F)]
# the loader: a page that loads it by a load edge first, then any loader
def rank(u):
h, k = u
return (h['kind'] != 'page', k not in LOAD_KINDS, h['repo'] != rec.get('repo'), h['id'])
users.sort(key=rank)
return users, uses
def _family(rec):
st = _graph()
if not STAMP_SEG.search(rec.get('path', '')):
return 0
return len(st['fam'].get((rec.get('repo'), STAMP_SEG.sub('*', rec['path'])), []))
def _dict_word(rec, text):
by_name, fp = _dictionary()
path = (rec.get('repo', '') + '/' + rec.get('path', '')).lower()
for n in rec.get('defines') or []:
if n not in (text or ''):
continue
distinctive = len(n) >= 8 and re.search(r'[a-z][A-Z]', n)
for word, mods, _out in by_name.get(n, []):
if distinctive or any(m in path for m in mods):
return word, n
for n in rec.get('defines') or []:
if n in fp and n in (text or '') and len(n) >= 6:
return sorted(fp[n])[0], n
return '', ''
def _uniq(xs):
out = []
for x in xs:
if x and x not in out:
out.append(x)
return out
def _cap(s):
return s[:1].upper() + s[1:] if s else s
def _clip_words(s, n):
ws = s.split()
if len(ws) <= n:
return s
cut = ' '.join(ws[:n])
# do not leave a half-open backtick or parenthesis
if cut.count('`') % 2:
cut = cut[:cut.rfind('`')].rstrip(' ,(')
if cut.count('(') > cut.count(')'):
cut = cut[:cut.rfind('(')].rstrip(' ,')
return cut.rstrip(' ,;:') + ''
# ---------------------------------------------------------------- per-function explanations (verified in source)
VERB_EXTRA = {'get': 'gets', 'set': 'sets', 'init': 'sets up', 'setup': 'sets up', 'make': 'makes', 'on': 'handles',
'handle': 'handles', 'is': 'checks for', 'has': 'checks for', 'can': 'checks whether it can',
'should': 'decides whether to', 'use': 'uses', 'run': 'runs', 'open': 'opens', 'close': 'closes',
'start': 'starts', 'stop': 'stops', 'select': 'selects', 'pick': 'picks', 'find': 'finds',
'ensure': 'ensures', 'assert': 'asserts', 'require': 'requires', 'emit': 'emits', 'send': 'sends',
'post': 'posts', 'push': 'pushes', 'pop': 'pops', 'reset': 'resets', 'clear': 'clears', 'hide': 'hides',
'set_': 'sets', 'append': 'appends', 'insert': 'inserts', 'delete': 'deletes', 'replace': 'replaces',
'split': 'splits', 'join': 'joins', 'wrap': 'wraps', 'escape': 'escapes', 'hash': 'hashes',
'apply': 'applies', 'attach': 'attaches', 'bind': 'binds', 'mount': 'mounts', 'register': 'registers',
'describe': 'describes', 'explain': 'explains', 'compare': 'compares', 'test': 'tests', 'write': 'writes',
'print': 'prints', 'log': 'logs', 'warn': 'warns', 'fail': 'fails on', 'parse': 'parses'}
DOC_VERBS = dict(describe.CODE_VERBS, **{k: v for k, v in VERB_EXTRA.items() if not k.endswith('_')})
def _verb3(w):
w = w.lower()
if w in DOC_VERBS:
return DOC_VERBS[w]
return ''
def _func_doc(name, text, path):
"""Raw comment or docstring attached to the definition of `name`, or ''."""
n = re.escape(name)
if path.endswith('.py'):
m = re.search(r'^[ \t]*(?:async[ \t]+)?(?:def|class)[ \t]+' + n + r'\b[^\n]*\n[ \t]*[rbuRBU]{0,2}("""|\'\'\')(.*?)\1',
text, re.M | re.S)
if m and m.start() < 390000:
return m.group(2)[:600]
return ''
m = re.search(r'^[ \t]*(?:export[ \t]+)?(?:default[ \t]+)?(?:async[ \t]+)?(?:function\*?[ \t]+' + n +
r'\b|(?:const|let|var)[ \t]+' + n + r'[ \t]*=|class[ \t]+' + n + r'\b|(?:static[ \t]+)?' + n +
r'[ \t]*\([^)\n]*\)[ \t]*\{)', text, re.M)
if not m:
return ''
before = text[max(0, m.start() - 1500):m.start()].rstrip()
b = re.search(r'/\*\*?((?:(?!\*/).)*)\*/\s*$', before, re.S)
if b:
return b.group(1)
lines = before.split('\n')
got = []
for ln in reversed(lines):
t = ln.strip()
if t.startswith('//'):
got.append(t.lstrip('/').strip())
else:
break
return '\n'.join(reversed(got))
def _doc_clause(raw, name):
if not raw:
return ''
raw = re.sub(r'^\s*\*\s?', '', raw, flags=re.M)
raw = re.sub(r'^\s*@\w+.*$', '', raw, flags=re.M)
c = describe.clean_comment(raw, '', (name,), 30)
if not c:
return ''
s = re.split(r'(?<=[.!?])\s+', c.strip())[0].strip().rstrip(' .;:,')
s = s.replace('`', '')
if not s or len(s.split()) > 16 or len(s.split()) < 2 or BAD_PLAIN.search(s) or RELIGIOUS.search(s) or \
re.search(r'[;:()\[\]{}<>=|]', s) or name in s:
return ''
w = s.split()
first = w[0]
v = _verb3(first)
if v and first[:1].isupper() or (v and first.islower()):
return 'It %s %s' % (v, ' '.join(w[1:]))
if first.lower().endswith('s') and _verb3(first.lower()[:-1]) or first.lower() in ('returns', 'gets', 'computes'):
return 'It %s %s' % (first.lower(), ' '.join(w[1:]))
if first in ('A', 'An', 'The'):
return 'It has %s %s' % (first.lower(), ' '.join(w[1:]))
return ''
def _params(name, rec, text):
sigs = rec.get('signatures') or []
for sg in sigs:
m = re.match(r'^(?:export\s+|async\s+|static\s+)*' + re.escape(name) + r'\((.*)\)\s*$', sg.strip())
if m:
raw = m.group(1)
break
else:
m = re.search(r'(?:def|function)\s+' + re.escape(name) + r'\s*\(([^)]*)\)', text)
raw = m.group(1) if m else ''
raw = re.sub(r'\{[^}]*\}|\[[^\]]*\]', ' ', raw)
out = []
for p in raw.split(','):
p = re.split(r'[=:]', p)[0].strip().lstrip('*.').strip()
if re.match(r'^[A-Za-z_$][\w$]*$', p) and p not in ('self', 'cls', 'this'):
ws = [w for w in describe.ident_words(p) if w.isalpha()]
if ws:
out.append(' '.join(ws))
return out[:3]
def _explain(name, rec, text):
"""'It builds a research catalogue (`build`).' style sentence, from its doc comment, its name or its params."""
c = _doc_clause(_func_doc(name, text, rec.get('path', '')), name)
if c:
return '%s (`%s`).' % (c, name)
ws = [w for w in describe.ident_words(name) if w]
if len(ws) >= 2 and all(re.match(r'^[a-z0-9]+$', w) for w in ws):
v = _verb3(ws[0])
while len(ws) > 2 and ws[-1] in ('of', 'for', 'at', 'to', 'by', 'from', 'in', 'on', 'with'):
ws = ws[:-1]
if ws[-1] in ('of', 'for', 'at', 'to', 'by', 'from', 'in', 'on', 'with') and not v:
ws = ws[:-1]
rest = ' '.join(ws[1:])
if v:
return 'It %s %s (`%s`).' % (v, rest, name)
if len(' '.join(ws)) >= 4:
return 'It works with %s (`%s`).' % (' '.join(ws), name)
ps = [p for p in _params(name, rec, text) if len(p) >= 3]
if ps:
return 'It takes %s in `%s`.' % (describe.join_words(ps), name)
return ''
# ---------------------------------------------------------------- the rule set
NAME = 'CADASTRE-27'
STRATEGY = 'Estate context: repository, folder README, loading page, graph neighbours, timestamp family, live URL, vedic- dictionary word, plus one verified code fact.'
BAD_PLAIN = re.compile(r'(?<![\w`])(?:[a-z]+[A-Z]\w+|[a-z]+_\w+|\w+\.(?:mjs|cjs|py|js)\b)|\{[A-Z]+\}|%[sd]|\$\{|'
r'\b(\w+) \1\b|(?i:\b(candidate|not composed|not published|no production|retired|deprecated|'
r'superseded|unreviewed|quarantined|example only|copied|placeholder|e\.g|i\.e)\b)|COPIED|'
r'\b20\d{6,}\b|\b[0-9a-f]{10,}\b|\b\d{4}-\d\d-\d\d\b|\. [a-z]|"|…')
def _main_functions(rec, text):
out = []
for d in rec.get('defines') or []:
if d.startswith('_') or d.startswith('test') or d in ('main', '__init__') or len(d) < 3:
continue
if d not in out:
out.append(d)
return [d for d in out[:6] if d in text and re.match(r'^[A-Za-z_$][\w$.]*$', d)]
def _context_sentence(para):
"""First clean sentence of a README paragraph (no identifiers, dates, hashes, status words), or ''."""
para = describe.URL.sub('', para)
for s in re.split(r'(?<=[.!?])\s+(?=[A-Z0-9(])', para.strip()):
s = s.strip().rstrip(' .;:,!?')
n = len(s.split())
if 5 <= n <= 26 and re.match(r'^[A-Z]', s) and not BAD_PLAIN.search(s) and not RELIGIOUS.search(s) \
and s.count('(') == s.count(')'):
return s
return ''
STD = re.compile(r'\b(?:IEC|BS|EN|IEEE|ISO|ENA|IET|ANSI)\s?[A-Z]?\s?\d{3,5}(?:[-:]\d+)*\b|\bG(?:59|83|98|99)\b|'
r'\bP2/[67]\b|\bEPSG:\d{4,5}\b|\bRFC\s?\d{3,5}\b')
FORMULAS = ['haversine', 'vincenty', 'newton-raphson', 'gauss-seidel', 'pagerank', 'dijkstra', 'kruskal',
'bradley-terry', 'louvain', 'least squares', 'kalman', 'fourier', 'monte carlo', 'bisection',
'bilinear', 'interpolation', 'douglas-peucker', 'delaunay', 'voronoi', 'convex hull', 'k-means',
'sha-256', 'sha256', 'crc32', 'base64', 'web mercator', 'mercator', 'helmert', 'ostn15', 'wgs84',
'voltage drop', 'power factor', 'derating', 'thermal resistance', 'short-circuit', 'fault level',
'load flow', 'power flow', 'per-unit', 'impedance', 'reactance', 'capacitance', 'skin effect',
'irradiance', 'mppt', 'lcoe', 'npv', 'discount rate', 'regression', 'percentile', 'median',
'standard deviation', 'cosine similarity', 'jaccard', 'levenshtein', 'breadth-first', 'depth-first',
'topological sort', 'quadtree', 'geohash', 'ray casting', 'point in polygon']
UNIT_SYM = ['kV', 'kVA', 'MVA', 'MVAr', 'kW', 'MW', 'GW', 'kWh', 'MWh', 'GWh', 'TWh', 'Hz', 'mm²']
def _code_terms(text, already):
"""Standards, named methods and units that the source itself names (word-bounded), not yet in `already`."""
out = []
for m in STD.finditer(text[:400000]):
k = re.sub(r'\s+', ' ', m.group(0))
if k not in out and k not in already:
out.append(k)
low = text.lower()
for w in FORMULAS:
if len(out) >= 4:
break
if re.search(r'(?<![\w-])' + re.escape(w) + r'(?![\w-])', low) and w not in already.lower() and \
not any(w in o.lower() for o in out):
out.append(w)
for u in UNIT_SYM:
if len(out) >= 4:
break
if len(re.findall(r'(?<![A-Za-z])' + re.escape(u) + r'(?![A-Za-z])', text)) >= 2 and \
not re.search(r'(?<![A-Za-z])' + re.escape(u) + r'(?![A-Za-z])', already):
out.append(u)
return out[:3]
def _sent(lead, link, body):
return '%s: %s%s.' % (lead, (link + ', ') if link else '', body)
def translate(file_record, source_text):
rec = file_record or {}
text = source_text or ''
ctx = rec.get('ctx') or {}
repo = rec.get('repo', '')
rt = ctx.get('repo_title') or ''
if not rt or len(rt.split()) > 5 or '.' in rt.rstrip('.') or rt.endswith('.'):
rt = build.repo_title(repo) if repo else ''
title = _plain(rec.get('title', '')) or posixpath.basename(rec.get('path', '')) or 'File'
if len(title.split()) > 8 and ' — ' in title:
title = title.split(' — ')[-1]
area = _area(rec.get('path', ''), rt + ' ' + title)
users, uses = _connections(rec)
fact, terms = _fact(rec, text)
mains = _main_functions(rec, text)
# synopsis: "Part of <Repo>'s <area> folder: loaded by <page>, it <fact>."
lead = 'Part of %s' % rt if rt else 'Part of this repository'
if area:
lead += "'s %s folder" % area
link = ''
if users:
h, k = users[0]
verb = VERB.get(k) or 'used by'
link = ('the style sheet of %s' if verb == 'styles' else verb + ' %s') % _short(h['title'])
if _short(h['title']).lower() == title.lower():
link = ('the style sheet of %s' if verb == 'styles' else verb + ' %s') % _plain(h['title'])
if len(users) > 1:
link += ' and %d other file%s' % (len(users) - 1, '' if len(users) == 2 else 's')
elif uses:
link = 'using %s' % describe.join_words(_uniq(_short(u['title']) for u in uses)[:2])
if len(uses) > 2:
link += ' and %d more' % (len(uses) - 2)
if not fact and mains:
fact = 'defines %s' % describe.join_words('`%s`' % m for m in mains[:3])
body = 'it %s' % fact if fact else 'it is a %s' % describe.KIND_NOUN.get(rec.get('kind', ''), 'file')
synopsis = _sent(lead, link, body)
if len(synopsis.split()) > 40 and fact:
parts = re.split(r', | and (?![^(]*\))', fact)
while len(parts) > 1 and len(synopsis.split()) > 40 and parts[-2].strip():
parts.pop()
body = 'it %s' % ', '.join(parts)
synopsis = _sent(lead, link, body)
if len(synopsis.split()) > 40 and ' and ' in link:
link = link.split(' and ')[0]
synopsis = _sent(lead, link, body)
if len(synopsis.split()) > 40:
synopsis = _clip_words(synopsis, 39).rstrip('.') + '.'
if len(synopsis.split()) < 12:
synopsis = synopsis.rstrip('.') + ', as a %s in %s.' % (
describe.KIND_NOUN.get(rec.get('kind', ''), 'file'), rt or 'this repository')
# achieves: README context + main functions + family + live URL + dictionary word + neighbours
bits = []
para, d = _readme_for(repo, posixpath.dirname(rec.get('path', '')))
cs = _context_sentence(para) if para else ''
if cs:
bits.append('%s says: %s.' % ('Its folder README' if d else 'The %s README' % rt, cs))
rest = [m for m in mains if '`%s`' % m not in synopsis]
listed = []
for m in rest:
e = _explain(m, rec, text)
if e:
bits.append(e)
else:
listed.append(m)
if listed:
listed = listed[:3]
bits.append('Other main %s %s.' % ('functions are' if len(listed) > 1 else 'function is',
describe.join_words('`%s`' % m for m in listed)))
so_far = synopsis + ' ' + ' '.join(bits)
terms = _code_terms(text, so_far)
if terms:
bits.append('Its code refers to %s.' % describe.join_words(terms))
ext = [x for x in rec.get('imports_external') or [] if x in text and '`%s`' % x not in so_far
and re.match(r'^[\w@./:\-]+$', x)][:2]
nq = len(set(re.findall(r'`([^`]+)`', so_far)))
if ext and nq < 4:
bits.append('Beyond the estate it relies on %s.' % describe.join_words('`%s`' % x for x in ext))
n = _family(rec)
if n > 1:
bits.append('It is one of %d timestamped versions of this file.' % n)
url = rec.get('published') or ''
if not url:
for h, _k in users:
if h.get('published') and h['repo'] == repo:
url = h['published']
break
if url:
bits.append('It is served at %s.' % url)
word, name = _dict_word(rec, text)
if word:
bits.append('Its `%s` matches the vedic- dictionary word %s.' % (name, word.lower()))
if uses and users:
bits.append('It uses %s.' % describe.join_words(_uniq(_short(u['title']) for u in uses)[:3]))
achieves = ' '.join(bits)
if not achieves:
achieves = 'It sits in %s%s.' % (rt or 'this repository', (", in the %s folder" % area) if area else '')
return {'title': title, 'synopsis': synopsis, 'achieves': achieves}
if __name__ == '__main__':
st = _graph()
for i in [int(x) for x in sys.argv[1:]] or [500]:
r = st['F'][i]
try:
with open(os.path.join(SRC, r['repo'], r['path']), encoding='utf-8', errors='replace') as fh:
src = fh.read(400000)
except OSError:
src = ''
print(json.dumps(translate(r, src), indent=1))