In this section
- Extract render · vedic- / fingerprints/extract.py lines 435–1134
Extract
A Python command-line tool in the fingerprints folder of VEDIC that draws units, extract summary, cables and substations, using SHA-256 and haversine.
rendervedic- / fingerprints/extract.py · lines 435–1134 of 1142 (continued from section 1666) · Entry point · pattern file_rows (shared by 2 files)
- What it does
- It draws units, extract summary, cables and substations. Defines 40 functions or classes, including TokenizeFailure, _lex, js_tokenize, bracket_match, _is. Uses libraries argparse, ast, bisect, collections, hashlib. 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 stage agent_infra (repository name word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: cables, substations, 11kV. README: "Better evidence from extraction: add `unit_terms` or side-effect patterns in `extract.py` together with a test in `test_extract.py`"
- Inputs & outputs
- In: Parquet file units.parquet; JSON file extract-summary.json; browser IndexedDB; command-line arguments. Out: JSON file. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 11kV.
- Downstream impact
- Used directly by 2 files: Test Extract (vedic-); VEDIC Fingerprints Workflow (vedic-).
- What it achieves
- It cleans doc (`clean_doc`) and is built from the tokenize failure class (`TokenizeFailure`) and the js tokenize helper (`js_tokenize`). One row per code unit (function, method, class, arrow) of the Ventusltd estate. Its code works with 11 kV. It accepts `--src`, `--out` and `--repos`.
- Why it matters
- Run by VEDIC Fingerprints Workflow. Checked by Test Extract.
- Application
- vedic- · fingerprints · Python CLI
- Uses
- argparse, ast, bisect, collections, hashlib, io, json, keyword
- Used by
- imported by Test Extract (import), run by VEDIC Fingerprints Workflow (workflow run)
- Produces
- TokenizeFailure, js_tokenize, bracket_match, js_params, js_units, minhash, jaccard, sha, unit_terms, side_effects, clean_doc, LineIndex
- Defines here
- _class_methods, _tok_hash, _salt, _mix, minhash, jaccard, sha, _letter_ok, unit_terms, side_effects, _compact, clean_doc, LineIndex, __init__, line, js_rows, html_rows, _py_tokens, _strip_str, _py_call_name, py_rows, visit, git, scan, file_rows, finish_rows, to_table, process_files, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 fingerprints/extract.py:435-1134 · blob 6aa04263ba9350b49ddf2bf51bc250e47adbb02c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: agent_infra · users: ai_agent · canonical: unknown
continue
k = _skip_generic(toks, k)
if _is(toks, k, '(') and match[k] > k:
c = match[k]
p = c + 1
if _is(toks, p, ':'):
q = p
while q < min(n, p + 30) and not _is(toks, q, '=>'):
q = match[q] + 1 if toks[q][1] in ('(', '[', '{') and match[q] > q else q + 1
p = q
if not _is(toks, p, '=>'):
continue
params = js_params(toks, match, k, c)
body = p + 1
elif _ident(toks, k) and _is(toks, k + 1, '=>'):
params, body = [toks[k][1]], k + 2
else:
continue
if body >= n:
continue
if _is(toks, body, '{'):
end = match[body]
if end < 0:
continue
else:
end = _expr_end(toks, match, body)
units.append(('arrow', name, params, i, end, j))
elif x == 'function':
start = i - 1 if i > 0 and toks[i - 1][1] == 'async' and toks[i - 1][0] == 'i' else i
j = i + 1
if _is(toks, j, '*'):
j += 1
name, name_idx = None, -1
if _ident(toks, j) and not _is(toks, j, '('):
name, name_idx = toks[j][1], j
j += 1
j = _skip_generic(toks, j)
if not _is(toks, j, '(') or match[j] < j:
continue
c = match[j]
body = _find_body(toks, match, c + 1)
if body < 0 or match[body] < body:
continue
kind = 'function'
if name is None:
if i in fn_override:
name, start, kind = fn_override[i]
else:
q = start - 1
if _is(toks, q, ':') and q >= 1 and toks[q - 1][0] in ('i', 's') and \
(q < 2 or toks[q - 2][1] in ('{', ',')):
name, start, kind = toks[q - 1][1].strip('\'"'), q - 1, 'method'
elif _is(toks, q, '=') and _ident(toks, q - 1):
chain, r = [toks[q - 1][1]], q - 1
while r >= 2 and toks[r - 1][1] == '.' and _ident(toks, r - 2):
chain.insert(0, toks[r - 2][1])
r -= 2
if len(chain) < 2:
continue # plain `x = function` (no declarator): ambiguous scope, skip
name, start = chain[-1], r
kind = 'method' if 'prototype' in chain else 'function'
else:
continue
units.append((kind, name, js_params(toks, match, j, c), start, match[body], name_idx))
elif x == 'class':
j = i + 1
name = '<anonymous>'
name_idx = -1
if _ident(toks, j) and toks[j][1] not in ('extends', 'implements'):
name, name_idx = toks[j][1], j
o = j
while o < min(n, j + 80) and not _is(toks, o, '{'):
if toks[o][1] in (';', ')', ']', '}') and toks[o][0] == 'p':
o = n
break
o = match[o] + 1 if toks[o][1] in ('(', '[') and match[o] > o else o + 1
if not _is(toks, o, '{') or match[o] < o:
continue
e = match[o]
units.append(('class', name, [], i, e, name_idx))
units.extend(_class_methods(toks, match, o, e))
return units
def _class_methods(toks, match, o, e):
out = []
k = o + 1
while k < e:
t, x, _ = toks[k]
if t == 'p' and x in ('(', '[', '{') and match[k] > k:
k = match[k] + 1
continue
if t == 'p' and x == '@': # decorator
k += 2
if _is(toks, k, '(') and match[k] > k:
k = match[k] + 1
continue
start = k
while _ident(toks, k) and toks[k][1] in CLASS_MODS and k + 1 < e and \
(toks[k + 1][0] == 'i' or toks[k + 1][1] in ('*', '[') or toks[k + 1][0] == 's'):
k += 1
if _is(toks, k, '*'):
k += 1
if k < e and toks[k][0] in ('i', 's', 'n'):
name, name_idx = toks[k][1].strip('\'"'), k
q = k + 1
if _is(toks, q, '?') or _is(toks, q, '!'):
q += 1
q = _skip_generic(toks, q)
if _is(toks, q, '(') and match[q] > q:
c = match[q]
body = _find_body(toks, match, c + 1)
if body > 0 and match[body] > body:
out.append(('method', name, js_params(toks, match, q, c), start, match[body], name_idx))
k = match[body] + 1
continue
if _is(toks, q, ':'): # TS field type
while q < e and not _is(toks, q, '=') and not _is(toks, q, ';'):
q = match[q] + 1 if toks[q][1] in ('(', '[', '{') and match[q] > q else q + 1
if _is(toks, q, '='):
r = q + 1
if _ident(toks, r) and toks[r][1] == 'async':
r += 1
r = _skip_generic(toks, r)
params, body = None, -1
if _is(toks, r, '(') and match[r] > r and _is(toks, match[r] + 1, '=>'):
params, body = js_params(toks, match, r, match[r]), match[r] + 2
elif _ident(toks, r) and _is(toks, r + 1, '=>'):
params, body = [toks[r][1]], r + 2
if params is not None and body < e:
end = match[body] if _is(toks, body, '{') else _expr_end(toks, match, body)
if end >= body:
out.append(('method', name, params, start, end, name_idx))
k = end + 1
continue
k += 1
return out
# ------------------------------------------------------------------ shared helpers
_TOK_CACHE = {}
_P64 = 0x100000001b3
_M64 = (1 << 64) - 1
def _tok_hash(t):
h = _TOK_CACHE.get(t)
if h is None:
h = int.from_bytes(hashlib.blake2b(t.encode('utf-8', 'replace'), digest_size=8, person=b'vedic-tok').digest(), 'little')
_TOK_CACHE[t] = h
return h
def _salt(i, which):
return int.from_bytes(hashlib.blake2b(f'{MINHASH_SEED}/{i}/{which}'.encode(), digest_size=8).digest(), 'little')
_A = np.array([_salt(i, 'a') | 1 for i in range(N_HASH)], dtype=np.uint64)
_B_ = np.array([_salt(i, 'b') for i in range(N_HASH)], dtype=np.uint64)
def _mix(v):
v = v ^ (v >> np.uint64(30))
v = v * np.uint64(0xbf58476d1ce4e5b9)
v = v ^ (v >> np.uint64(27))
v = v * np.uint64(0x94d049bb133111eb)
return v ^ (v >> np.uint64(31))
def minhash(stream):
"""64 uint32 MinHash values of the 5-token shingles of a structural token stream (see module doc)."""
hs = [_tok_hash(t) for t in stream] or [0]
with np.errstate(over='ignore'):
if len(hs) < SHINGLE:
v = 0
for h in hs:
v = (v * _P64 + h) & _M64
v = np.array([v], dtype=np.uint64)
else:
seq = np.array(hs, dtype=np.uint64)
m = len(hs) - SHINGLE + 1
v = seq[0:m].copy()
for k in range(1, SHINGLE):
v = v * np.uint64(_P64) + seq[k:k + m]
v = _mix(v)
vals = (v[:, None] * _A[None, :] + _B_[None, :]) >> np.uint64(32)
return vals.min(axis=0).astype(np.uint32)
def jaccard(a, b):
return float(np.mean(np.asarray(a) == np.asarray(b)))
def sha(s):
return hashlib.sha256(s.encode('utf-8', 'replace')).hexdigest()
_PIECE = re.compile(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+')
_WORD = re.compile(r'[a-z][a-z0-9]*')
_NUM_UNIT = re.compile(r'\d\s*([a-z]{1,3})\b')
# Single-letter unit terms (a, m, v, w, h, s) are almost always loop variables or generic names. They
# count only (1) as a piece right after a number or a quantity/unit context piece (cableLengthM,
# voltageV, span50M, dropPercentV), or (2) as a whole parameter name when the same unit already shows a
# non-ambiguous domain term (voltageDrop(i, v) with kv/cable elsewhere). Strings need a number first.
UNIT_CONTEXT = {'length', 'len', 'dist', 'distance', 'height', 'width', 'depth', 'radius', 'span', 'size',
'voltage', 'volt', 'volts', 'current', 'power', 'drop', 'loss', 'losses', 'nominal', 'rated',
'rating', 'peak', 'load', 'speed', 'duration', 'delay', 'interval', 'timeout', 'elevation',
'altitude', 'offset', 'step', 'spacing', 'pitch', 'separation', 'route', 'cable', 'line'}
def _letter_ok(pieces, idx):
"""A single-letter piece counts only after a number or a unit-context/domain piece."""
if idx == 0:
return False
prev = pieces[idx - 1]
return prev.isdigit() or prev in UNIT_CONTEXT or (prev in TERM_GROUP and prev not in AMBIGUOUS)
def unit_terms(identifiers, strings, params=()):
found = set()
for ident in identifiers:
low = ident.lower().strip('#$_')
if low in TERM_GROUP and low not in AMBIGUOUS:
found.add(low)
pieces = []
for part in re.split(r'[_$#]+', ident):
if part:
if part.lower() in TERM_GROUP and part.lower() not in AMBIGUOUS:
found.add(part.lower())
pieces.extend(p.lower() for p in _PIECE.findall(part))
idx = 0
while idx < len(pieces): # greedy: a joined pair first (k+Wh -> kwh, M+Wh -> mwh), then the piece
pair = pieces[idx] + pieces[idx + 1] if idx + 1 < len(pieces) else ''
if pair in TERM_GROUP and pair not in AMBIGUOUS:
found.add(pair)
idx += 2
continue
p = pieces[idx]
if p in TERM_GROUP:
if len(p) == 1:
if _letter_ok(pieces, idx):
found.add(p)
elif p not in AMBIGUOUS or (idx > 0 and len(pieces) > 1):
found.add(p)
idx += 1
for s in strings:
low = s.lower()
if len(low) > 2000:
low = low[:2000]
for w in _WORD.findall(low):
if w in TERM_GROUP and w not in AMBIGUOUS:
found.add(w)
for u in _NUM_UNIT.findall(low):
if u in TERM_GROUP:
found.add(u)
if found: # whole single-letter parameter names, only with domain context already present
for p in params:
low = (p or '').lower()
if len(low) == 1 and low in TERM_GROUP:
found.add(low)
return sorted(found)
def side_effects(compact, lang):
return sorted({cat for cat, rx in SIDE_RX[lang] if rx.search(compact)})
def _compact(pieces):
"""pieces: list of (is_word, text). Joined with nothing, one space between two word tokens."""
out, prev_word = [], False
for w, x in pieces:
if w and prev_word:
out.append(' ')
out.append(x)
prev_word = w
return ''.join(out)
def clean_doc(text):
text = re.sub(r'^\s*/\*+|\*+/\s*$', '', text)
text = re.sub(r'(?m)^\s*(\*|//+|#+)', ' ', text)
text = re.sub(r'\s+', ' ', text).strip(' -=*#/!')
if len(text) > MAX_DOC:
text = text[:MAX_DOC - 1].rsplit(' ', 1)[0] + '…'
return text
class LineIndex:
def __init__(self, text):
self.nl = [m.start() for m in re.finditer('\n', text)]
def line(self, off):
return bisect.bisect_left(self.nl, off) + 1
# ------------------------------------------------------------------ JavaScript units -> rows
def js_rows(src, base_line=0):
"""Tokenize a JS/TS source (or a <script> body starting after base_line lines) into unit rows."""
toks, comments = js_tokenize(src)
match = bracket_match(toks)
li = LineIndex(src)
cm_by_end = {}
for a, b, txt in comments:
cm_by_end.setdefault(li.line(max(a, b - 1)), []).append((li.line(a), txt))
rows = []
for kind, name, params, s, e, name_idx in js_units(toks, match):
if e < s:
continue
lf = li.line(toks[s][2])
last = toks[e]
lt = li.line(last[2] + len(last[1]) - 1)
seg = toks[s:e + 1]
struct, exact, idents, strings, comp = [], [], [], [], []
for t, x, _ in seg:
exact.append(x)
if t == 'i':
if x in JS_KEYWORDS:
struct.append(x)
else:
struct.append('ID')
idents.append(x)
comp.append((True, x))
elif t == 'n':
struct.append('NUM')
comp.append((True, '0'))
elif t in ('s', 't'):
struct.append('STR')
strings.append(x[1:-1])
comp.append((False, '""'))
elif t == 'r':
struct.append('REGEX')
comp.append((False, '/re/'))
else:
struct.append(x)
comp.append((False, x))
calls, seen = [], set()
for q in range(s, e):
t, x, _ = toks[q]
if t != 'i' or x in NONCALL or q == name_idx or toks[q + 1][1] != '(' or toks[q + 1][0] != 'p':
continue
if q > 0 and toks[q - 1][1] == 'function':
continue
c = match[q + 1]
if c > 0 and c + 1 < len(toks) and toks[c + 1][1] == '{' and toks[c + 1][0] == 'p':
continue # method definition, not a call
chain, r = [x], q
while r >= 2 and toks[r - 1][1] in ('.', '?.') and toks[r - 2][0] == 'i' and len(chain) < 4:
chain.insert(0, toks[r - 2][1])
r -= 2
nm = '.'.join(chain)
if nm not in seen:
seen.add(nm)
calls.append(nm)
if len(calls) >= MAX_CALLS:
break
doc_parts, cur = [], lf - 1
while cur in cm_by_end:
a_line, txt = cm_by_end[cur][-1]
doc_parts.insert(0, txt)
cur = a_line - 1
rows.append(dict(lang='javascript', kind=kind, name=name or '<anonymous>', params=params,
line_from=lf + base_line, line_to=lt + base_line, n_lines=lt - lf + 1, n_tokens=len(struct),
exact_hash=sha(' '.join(exact)), struct=struct, doc=clean_doc(' '.join(doc_parts)),
calls=calls, unit_terms=unit_terms([name or ''] + params + idents, strings, params),
side_effects=side_effects(_compact(comp), 'javascript')))
return rows
_SCRIPT = re.compile(r'<script\b([^>]*)>(.*?)</script\s*>', re.I | re.S)
_JS_TYPES = ('', 'text/javascript', 'application/javascript', 'module', 'text/babel', 'application/ecmascript',
'text/ecmascript', 'text/jsx')
def html_rows(text):
rows, n_scripts = [], 0
for m in _SCRIPT.finditer(text):
attrs = m.group(1)
tm = re.search(r'''\btype\s*=\s*["']?([^"'\s>]+)''', attrs, re.I)
if tm and tm.group(1).lower() not in _JS_TYPES:
continue
body = m.group(2)
if not body.strip():
continue
n_scripts += 1
rows.extend(js_rows(body, text.count('\n', 0, m.start(2))))
return rows, n_scripts
# ------------------------------------------------------------------ Python units -> rows
def _py_tokens(text):
"""Structural entries (row, struct, exact, kind, payload) from tokenize, f-strings collapsed."""
starts = [0]
for m in re.finditer('\n', text):
starts.append(m.end())
out = []
gen = tokenize.generate_tokens(io.StringIO(text).readline)
FSS = getattr(tokenize, 'FSTRING_START', -1)
FSM = getattr(tokenize, 'FSTRING_MIDDLE', -2)
FSE = getattr(tokenize, 'FSTRING_END', -3)
comments = {}
fdepth, fstart, fparts = 0, None, []
for tok in gen:
tt = tok.type
if fdepth:
if tt == FSS:
fdepth += 1
elif tt == FSE:
fdepth -= 1
if fdepth == 0:
(r0, c0), (r1, c1) = fstart, tok.end
raw = text[starts[r0 - 1] + c0:starts[r1 - 1] + c1]
out.append((r0, 'STR', raw, 's', ''.join(fparts)))
elif tt == FSM:
fparts.append(tok.string)
continue
if tt == FSS:
fdepth, fstart, fparts = 1, tok.start, []
elif tt == tokenize.NAME:
if keyword.iskeyword(tok.string):
out.append((tok.start[0], tok.string, tok.string, 'k', None))
else:
out.append((tok.start[0], 'ID', tok.string, 'i', tok.string))
elif tt == tokenize.NUMBER:
out.append((tok.start[0], 'NUM', tok.string, 'n', None))
elif tt == tokenize.STRING:
out.append((tok.start[0], 'STR', tok.string, 's', tok.string))
elif tt == tokenize.OP or tt == tokenize.ERRORTOKEN:
if tok.string.strip():
out.append((tok.start[0], tok.string, tok.string, 'p', None))
elif tt == tokenize.NEWLINE:
out.append((tok.start[0], 'NEWLINE', '\n', 'x', None))
elif tt == tokenize.INDENT:
out.append((tok.start[0], 'INDENT', '<IND>', 'x', None))
elif tt == tokenize.DEDENT:
out.append((tok.start[0], 'DEDENT', '<DED>', 'x', None))
elif tt == tokenize.COMMENT:
if tok.line.strip().startswith('#'):
comments[tok.start[0]] = tok.string
return out, comments
def _strip_str(s):
m = re.match(r'(?is)^[rbuf]*("""|\'\'\'|"|\')(.*)\1$', s, re.S)
return m.group(2) if m else s
def _py_call_name(f):
parts = []
while isinstance(f, ast.Attribute):
parts.insert(0, f.attr)
f = f.value
if isinstance(f, ast.Name):
parts.insert(0, f.id)
return '.'.join(parts[-4:])
return parts[-1] if parts else None
def py_rows(text):
with warnings.catch_warnings():
warnings.simplefilter('ignore')
tree = ast.parse(text)
entries, comments = _py_tokens(text)
rowsidx = [e[0] for e in entries]
found = []
def visit(node):
for ch in ast.iter_child_nodes(node):
if isinstance(ch, (ast.FunctionDef, ast.AsyncFunctionDef)):
found.append(('method' if isinstance(node, ast.ClassDef) else 'function', ch))
visit(ch)
elif isinstance(ch, ast.ClassDef):
found.append(('class', ch))
visit(ch)
else:
visit(ch)
visit(tree)
rows = []
for kind, node in found:
lf = min([node.lineno] + [d.lineno for d in node.decorator_list])
lt = node.end_lineno or node.lineno
a = bisect.bisect_left(rowsidx, lf)
b = bisect.bisect_right(rowsidx, lt)
seg = entries[a:b]
struct = [e[1] for e in seg]
exact = [e[2] for e in seg]
n_tok = sum(1 for e in seg if e[3] != 'x')
idents = [e[4] for e in seg if e[3] == 'i']
strings = [_strip_str(e[4]) if e[2] == e[4] else e[4] for e in seg if e[3] == 's']
comp = [(e[3] in ('i', 'k', 'n'), '""' if e[3] == 's' else ('0' if e[3] == 'n' else e[2]))
for e in seg if e[3] != 'x']
params = []
if kind != 'class':
ar = node.args
params = [x.arg for x in ar.posonlyargs + ar.args]
if ar.vararg:
params.append(ar.vararg.arg)
params += [x.arg for x in ar.kwonlyargs]
if ar.kwarg:
params.append(ar.kwarg.arg)
doc = ast.get_docstring(node) or ''
if not doc:
parts, cur = [], lf - 1
while cur in comments:
parts.insert(0, comments[cur])
cur -= 1
doc = ' '.join(parts)
calls, seen = [], set()
for sub in ast.walk(node):
if isinstance(sub, ast.Call):
nm = _py_call_name(sub.func)
if nm and nm not in seen:
seen.add(nm)
calls.append(nm)
if len(calls) >= MAX_CALLS:
break
rows.append(dict(lang='python', kind=kind, name=node.name, params=params, line_from=lf, line_to=lt,
n_lines=lt - lf + 1, n_tokens=n_tok, exact_hash=sha(' '.join(exact)), struct=struct,
doc=clean_doc(doc), calls=calls, unit_terms=unit_terms([node.name] + params + idents, strings, params),
side_effects=side_effects(_compact(comp), 'python')))
return rows
# ------------------------------------------------------------------ reading the estate
def git(d, *a, binary=False):
r = subprocess.run(['git', '-C', d] + list(a), capture_output=True)
return r.stdout if binary else r.stdout.decode('utf-8', 'replace').strip()
def scan(src, only=None):
"""Explore Code selection, restricted to the parsed languages. Returns (files, skipped Counter, repos)."""
files, left, repos = [], collections.Counter(), []
seen = set()
for repo_dir in sorted(os.listdir(src), key=str.lower):
d = os.path.join(src, repo_dir)
if not os.path.isdir(os.path.join(d, '.git')):
continue
url = git(d, 'config', '--get', 'remote.origin.url')
if not url.lower().startswith('https://github.com/ventusltd/'):
continue
repo = url.rstrip('/').split('/')[-1]
repo = repo[:-4] if repo.endswith('.git') else repo
if only and repo not in only and repo_dir not in only:
continue
repos.append(repo)
commit = git(d, 'rev-parse', 'HEAD')
listing = git(d, 'ls-tree', '-r', '-l', '-z', 'HEAD', binary=True).decode('utf-8', 'replace')
items = []
for ent in listing.split('\0'):
if '\t' not in ent:
continue
meta, path = ent.split('\t', 1)
mode, typ, sha1, size = meta.split()
if typ == 'blob' and size != '-' and 0 < int(size) <= 1_000_000 and EXT.search(path) and not SKIP.search(path):
if PARSE_EXT.search(path):
items.append((path, sha1))
else:
left['code file in a language without a parser'] += 1
p = subprocess.Popen(['git', '-C', d, 'cat-file', '--batch'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for path, sha1 in items:
p.stdin.write((sha1 + '\n').encode())
p.stdin.flush()
hdr = p.stdout.readline().split()
if len(hdr) < 3 or hdr[1] == b'missing':
left['not fetched'] += 1
continue
n = int(hdr[2])
data = p.stdout.read(n)
p.stdout.read(1)
if sha1 in seen:
left['duplicate blob'] += 1
continue
if b'\0' in data[:8000]:
left['binary'] += 1
continue
seen.add(sha1)
lines = data.decode('utf-8', 'replace').split('\n')
if lines and lines[-1] == '':
lines.pop()
if not lines or n / len(lines) > 400:
left['minified or one-line'] += 1
continue
files.append({'repo': repo, 'commit': commit, 'path': path, 'blob': sha1, 'lines': lines})
p.stdin.close()
p.wait()
newest = {}
for f in files:
fam = f['repo'] + '|' + STAMP.sub('#', f['path'])
key = (max(STAMP.findall(f['path']) or ['']), f['path'])
if fam not in newest or key > newest[fam][0]:
newest[fam] = (key, f)
left['older timestamped versions'] = len(files) - len(newest)
return [f for _, f in newest.values()], left, repos
def file_rows(path, text):
"""Rows for one file. Raises TokenizeFailure / SyntaxError etc. on parse problems."""
e = path.rsplit('.', 1)[-1].lower()
if e == 'py':
return py_rows(text), 'python'
if e in ('html', 'htm'):
rows, n = html_rows(text)
return rows, 'html' if n else 'html-no-script'
return js_rows(text), 'javascript'
COLUMNS = [
('schema', pa.string()), ('unit_id', pa.string()), ('repo', pa.string()), ('commit', pa.string()),
('path', pa.string()), ('blob', pa.string()), ('lang', pa.string()), ('kind', pa.string()),
('name', pa.string()), ('params', pa.list_(pa.string())), ('line_from', pa.int32()), ('line_to', pa.int32()),
('n_lines', pa.int32()), ('n_tokens', pa.int32()), ('exact_hash', pa.string()), ('struct_hash', pa.string()),
('minhash', pa.list_(pa.uint32())), ('doc', pa.string()), ('calls', pa.list_(pa.string())),
('unit_terms', pa.list_(pa.string())), ('side_effects', pa.list_(pa.string())), ('pure', pa.bool_()),
]
ARROW_SCHEMA = pa.schema(COLUMNS)
def finish_rows(rows, f):
"""Filter by size, add identity, hashes and minhash; dedupe identical ranges."""
out, ids = [], set()
for r in rows:
if r['n_lines'] < MIN_LINES or r['n_tokens'] < MIN_TOKENS:
continue
uid = sha(f"{f['repo']}@{f['commit']}:{f['path']}:{r['line_from']}-{r['line_to']}")[:16]
if uid in ids:
continue
ids.add(uid)
struct = r.pop('struct')
r.update(schema=SCHEMA, unit_id=uid, repo=f['repo'], commit=f['commit'], path=f['path'], blob=f['blob'],
struct_hash=sha(' '.join(struct)), minhash=minhash(struct), pure=not r['side_effects'])
out.append(r)
return out
def to_table(rows):
rows.sort(key=lambda r: (r['repo'], r['path'], r['line_from'], r['name'], r['line_to'], r['kind']))
cols = {}
for name, typ in COLUMNS:
if name == 'minhash':
flat = np.concatenate([r['minhash'] for r in rows]) if rows else np.zeros(0, np.uint32)
offsets = np.arange(0, (len(rows) + 1) * N_HASH, N_HASH, dtype=np.int32)
cols[name] = pa.ListArray.from_arrays(pa.array(offsets), pa.array(flat, type=pa.uint32()))
else:
cols[name] = pa.array([r[name] for r in rows], type=typ)
return pa.Table.from_arrays([cols[n] for n, _ in COLUMNS], schema=ARROW_SCHEMA)
def process_files(files, skipped):
"""Parse each file into finished rows. A file that fails to tokenize or parse is skipped and counted
in `skipped`; nothing raises."""
rows, units_files, lines_read = [], collections.Counter(), 0
for f in files:
text = '\n'.join(f['lines']) + '\n'
lines_read += len(f['lines'])
try:
frs, kind = file_rows(f['path'], text)
done = finish_rows(frs, f)
except TokenizeFailure:
skipped['javascript tokenizer failure'] += 1
continue
except (SyntaxError, ValueError, tokenize.TokenError, RecursionError, MemoryError):
skipped['python syntax or tokenize error'] += 1
continue
except Exception as ex: # never crash on one bad file
skipped['unexpected parser error: ' + type(ex).__name__] += 1
continue
units_files[kind] += 1
rows.extend(done)
return rows, units_files, lines_read
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
ap.add_argument('--src', required=True, help='folder of clones')
ap.add_argument('--out', required=True, help='output folder')
ap.add_argument('--repos', default='', help='comma-separated repo names (default: all)')
a = ap.parse_args(argv)
t0 = time.time()
only = {x.strip() for x in a.repos.split(',') if x.strip()} or None
files, skipped, repos = scan(a.src, only)
files.sort(key=lambda f: (f['repo'], f['path']))
rows, units_files, lines_read = process_files(files, skipped)
table = to_table(rows)
os.makedirs(a.out, exist_ok=True)
out_path = os.path.join(a.out, 'units.parquet')
pq.write_table(table, out_path, compression='zstd', write_statistics=True)
by = collections.Counter((r['lang'], r['kind']) for r in rows)
with open(os.path.abspath(__file__), 'rb') as fh:
script_sha = hashlib.sha256(fh.read()).hexdigest()
summary = {
'schema': SCHEMA, 'script_sha256': script_sha, 'minhash_seed': MINHASH_SEED,
'repos': len(repos), 'repo_names': repos,
'files_read': len(files), 'lines_read': lines_read, 'files_parsed_by_kind': dict(sorted(units_files.items())),
'files_skipped': dict(sorted(skipped.items())),
'units': len(rows), 'units_by_lang_kind': {f'{l}/{k}': v for (l, k), v in sorted(by.items())},
'units_parquet_bytes': os.path.getsize(out_path),
'runtime_seconds': round(time.time() - t0, 1),
}
with open(os.path.join(a.out, 'extract-summary.json'), 'w') as fh: