File size: 19,517 Bytes
d9b105f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 | """Named table parts for projects: read, stack, join and reference lookup.
The source shape is retained in the project plan. Columns are read from that
shape, not from the first file mentioned. The writer embeds runtime_source()
so a generated project remains a standalone standard-library program. The
outside judge has its own evaluator in judge/project_sources_judge.py.
"""
import re
from pathlib import Path
# This is also the source embedded in generated projects. Keep all its names
# separate from the older generated table/probe helpers.
_RUNTIME = r'''
import csv as _source_csv
import json as _source_json
import math as _source_math
from pathlib import Path as _SourcePath
class ProjectSourceError(ValueError):
pass
def _source_path(root, name):
base = _SourcePath(root).resolve()
# C15b: the name must stay inside the project folder as written ("../x.csv" is refused); a link the project keeps in
# its own folder (an adopted capability reading Oracle7's live records) is one of its sources
import os as _source_os
named = _SourcePath(_source_os.path.normpath(str(base / name)))
if named != base and base not in named.parents:
raise ProjectSourceError("source %s is outside the project folder" % name)
path = named
if not path.is_file():
raise ProjectSourceError("source %s is not in the project yet; add it and continue" % name)
return path
def _source_table(root, name):
path = _source_path(root, name)
try:
if str(name).lower().endswith('.jsonl'):
rows = [_source_json.loads(line) for line in path.read_text(encoding='utf-8-sig').splitlines() if line.strip()]
cols = list(rows[0]) if rows and isinstance(rows[0], dict) else []
elif str(name).lower().endswith('.json'):
rows = _source_json.loads(path.read_text(encoding='utf-8-sig'))
if isinstance(rows, dict):
rows = next((v for v in rows.values() if isinstance(v, list)), [rows])
if not isinstance(rows, list):
raise ProjectSourceError("%s must contain a table of records" % name)
cols = list(rows[0]) if rows and isinstance(rows[0], dict) else []
elif str(name).lower().endswith('.csv'):
with path.open(encoding='utf-8-sig', newline='') as handle:
reader = _source_csv.DictReader(handle)
cols = list(reader.fieldnames or [])
rows = list(reader)
if len(set(cols)) != len(cols) or any(not c for c in cols):
raise ProjectSourceError("%s has missing or duplicate column names" % name)
else:
raise ProjectSourceError("%s is not a CSV, JSON or JSONL table" % name)
except (OSError, ValueError, TypeError) as exc:
if isinstance(exc, ProjectSourceError):
raise
raise ProjectSourceError("%s could not be read as a table: %s" % (name, exc)) from exc
if any(not isinstance(row, dict) or set(row) != set(cols) for row in rows):
raise ProjectSourceError("%s has records with different columns or non-record rows" % name)
if any(not isinstance(c, str) for c in cols):
raise ProjectSourceError("%s has non-text column names" % name)
return cols, [dict(row) for row in rows]
def _source_key(row, columns):
key = []
for column in columns:
value = row.get(column)
if value is None or str(value).strip() == '':
return None
if isinstance(value, (list, dict)) or isinstance(value, float) and not _source_math.isfinite(value):
raise ProjectSourceError("join column %s must contain finite scalar keys" % column)
key.append(str(value).strip())
return tuple(key)
def source_snapshot(source, root='.'):
"""Return (ordered columns, rows), retaining empty CSV schemas."""
if not isinstance(source, dict):
raise ProjectSourceError("the source shape must name its part")
op = source.get('op')
if op == 'read':
return _source_table(root, source['file'])
if op == 'union':
inputs = source.get('inputs') or []
if not inputs:
raise ProjectSourceError("stacking needs at least one source")
cols, rows = None, []
for child in inputs:
child_cols, child_rows = source_snapshot(child, root)
if not child_cols and not child_rows:
continue
if cols is None:
cols = child_cols
if set(child_cols) != set(cols):
raise ProjectSourceError("stacked sources have different columns: %s versus %s" % (cols, child_cols))
rows.extend({c: row[c] for c in cols} for row in child_rows)
return cols or [], rows
if op not in ('join', 'lookup'):
raise ProjectSourceError("unknown source part %r" % op)
left_cols, left_rows = source_snapshot(source['left'], root)
right_cols, right_rows = source_snapshot(source['right'], root)
keys = source.get('keys') or []
if not keys or any(not isinstance(pair, (list, tuple)) or len(pair) != 2 for pair in keys):
raise ProjectSourceError("a join needs named left and right key columns")
left_keys, right_keys = [p[0] for p in keys], [p[1] for p in keys]
if len(set(left_keys)) != len(left_keys) or len(set(right_keys)) != len(right_keys):
raise ProjectSourceError("a join key column was bound more than once")
if any(c not in left_cols for c in left_keys) or any(c not in right_cols for c in right_keys):
raise ProjectSourceError("join key columns are missing: %s; left %s; right %s" % (keys, left_cols, right_cols))
right_out = [c for c in right_cols if c not in right_keys]
collisions = sorted(set(left_cols) & set(right_out))
if collisions:
raise ProjectSourceError("both sources supply %s; rename the non-key columns explicitly before joining" % ', '.join(collisions))
how = source.get('how', 'inner')
if how not in ('inner', 'left'):
raise ProjectSourceError("join kind %r is not represented; name inner or left" % how)
index = {}
for row in right_rows:
key = _source_key(row, right_keys)
if key is not None:
if op == 'lookup' and key in index:
raise ProjectSourceError("lookup has more than one reference row for key %s" % (key,))
index.setdefault(key, []).append(row)
rows = []
for row in left_rows:
key = _source_key(row, left_keys)
matches = index.get(key, []) if key is not None else []
if not matches and op == 'lookup':
raise ProjectSourceError("lookup has no reference row for key %s; supply a matching reference" % (key,))
for match in matches:
rows.append(dict(row, **{c: match[c] for c in right_out}))
if not matches and how == 'left':
rows.append(dict(row, **{c: None for c in right_out}))
return left_cols + right_out, rows
SOURCE_ROOT = '.' # where this program's sources are read: its folder when run there; an adopted capability's own folder
def read_source(source, root=None):
return source_snapshot(source, SOURCE_ROOT if root is None else root)[1]
'''
exec(_RUNTIME)
SourceError = ProjectSourceError
DATA = re.compile(r"(?<![\w./-])([\w./-]+\.(?:csv|jsonl|json))\b", re.I)
_SINK = re.compile(r"\b(?:save|write|export|output|dump|store)\w*\b[^;!?]{0,180}?\b(?:to|into|as)\s+`?([\w./-]+\.(?:csv|jsonl|json|txt|html))\b", re.I)
_COL = r"[a-zA-Z_][\w]*(?:\.[a-zA-Z_][\w]*)?"
_RELATION_WORDS = "join joins joined joining match matches matched matching inner left outer lookup lookups reference references combine combines combined combining stack stacks stacked stacking append appends appended union concatenate concatenated"
def runtime_source():
"""Standard-library helpers to embed verbatim in a generated module."""
return _RUNTIME.strip() + '\n'
def evaluate(root, source):
return read_source(source, root)
def files(source):
if not source:
return []
if source.get('op') == 'read':
return [source['file']]
children = source.get('inputs') if source.get('op') == 'union' else [source.get('left'), source.get('right')]
return list(dict.fromkeys(f for child in children or [] for f in files(child)))
def input_files(text, output_files=()):
"""Separate file occurrences by role, retaining an explicit read of a sink.
Output-only files never become inputs merely because they exist. If a file
is explicitly read AND written, retain its input role so the caller can
refuse that overwrite before writing the generated project.
"""
outputs = set(output_files)
targets = []
for sink in _SINK.finditer(text):
outputs.add(sink.group(1))
targets.append(sink.span(1))
end = sink.end(1)
# "export to first.csv and second.csv" names two sinks, not a union.
while True:
extra = re.match(r'`?\s*(?:,|and)\s+`?([\w./-]+\.(?:csv|jsonl|json|txt|html))\b', text[end:], re.I)
if not extra:
break
outputs.add(extra.group(1))
targets.append((end + extra.start(1), end + extra.end(1)))
end += extra.end(1)
explicit_input = re.compile(r'\b(?:from|read|reads|reading|load|loads|loading|using|uses|'
r'join|joins|joined|joining|combine|combines|combined|stack|stacks|'
r'append|appends|union|lookup|reference|with|and|of|for)\s+'
r'(?:(?:the|a)\s+)?(?:(?:file|table)\s+(?:(?:named|called)\s+)?)?`?$', re.I)
inputs = []
for mention in DATA.finditer(text):
if any(start <= mention.start(1) and mention.end(1) <= end for start, end in targets):
continue
name = mention.group(1)
if name not in outputs or explicit_input.search(text[:mention.start(1)]):
inputs.append(name)
return list(dict.fromkeys(inputs))
def _numeric(value):
if value is None or isinstance(value, bool):
return False
try:
return bool(str(value).strip()) and __import__('math').isfinite(float(value))
except (ValueError, TypeError):
return False
def describe(root, source):
cols, rows = source_snapshot(source, root)
url = next((c for c in cols if rows and all(re.match(r'^https?://', str(r.get(c, '')), re.I) for r in rows)), None)
key = next((c for c in cols if c != url and rows and len({str(r.get(c)) for r in rows}) == len(rows)
and not all(_numeric(r.get(c)) for r in rows)), None)
if key is None:
key = next((c for c in cols if c != url and rows and len({str(r.get(c)) for r in rows}) == len(rows)), None)
names = files(source)
return {'file': names[0] if names else None, 'files': names, 'source': source, 'cols': cols, 'url': url, 'key': key,
'n': len(rows), 'numeric': [c for c in cols if rows and all(_numeric(r.get(c)) for r in rows)],
'sample': dict(rows[0]) if rows else {},
'hosts': sorted({re.sub(r'^https?://([^/:]+).*$', r'\1', str(r[url])) for r in rows}) if url else []}
def _read(file):
return {'op': 'read', 'file': file}
def _column(token, cols, names):
bits = token.strip('`').split('.')
if len(bits) == 2 and bits[0].lower() not in {Path(n).stem.lower() for n in names}:
return None
return next((c for c in cols if c.lower() == bits[-1].lower()), None)
def _key_phrase(text, left_cols, right_cols, left_files, right_files, allow_incomplete=False):
"""The bounded binding text and raw column pairs, before column validation."""
marker = re.search(r'\b(?:matching|matched|matches|match)(?:\s+(?:on|by))?\s+', text, re.I)
if marker is None:
# An unqualified `on` immediately before a column is the source binding;
# `on a page` and `group by` are not source bindings.
candidates = list(re.finditer(r'\bon\s+(?=' + _COL + r')', text, re.I))
for candidate in reversed(candidates):
word = re.match(_COL, text[candidate.end():])
if word and (_column(word.group(), left_cols, left_files) or _column(word.group(), right_cols, right_files)):
marker = candidate
break
if marker is None:
return None, None
tail = text[marker.end():]
pair = re.match(r'(' + _COL + r')\s*(?:=|\b(?:equals|to|with)\b)\s*(' + _COL + r')', tail, re.I)
if pair:
a, b = pair.groups()
return [[a, b]], (marker.start(), marker.end() + pair.end())
first = re.match(_COL, tail)
if not first:
if allow_incomplete:
return [], (marker.start(), marker.end())
raise SourceError('name a column after matching on')
tokens = [first.group()]
end = first.end()
while True:
more = re.match(r'\s*(?:,|and)\s*(' + _COL + r')', tail[end:], re.I)
if not more:
break
token = more.group(1)
if not (_column(token, left_cols, left_files) and _column(token, right_cols, right_files)):
break
following = tail[end + more.end():]
if re.match(r'\s+(?:is|are|over|above|under|below|more than|less than|at least|at most)\b', following, re.I):
break
tokens.append(token)
end += more.end()
return [[token, token] for token in tokens], (marker.start(), marker.end() + end)
def _keys(text, left_cols, right_cols, left_files, right_files, override=None):
"""Use an explicit correction, an original binding, or one shared column."""
pairs, span = _key_phrase(text, left_cols, right_cols, left_files, right_files, allow_incomplete=override is not None)
if override is not None:
pairs, replacement_span = _key_phrase(override, left_cols, right_cols, left_files, right_files)
if pairs is None:
raise SourceError('the key correction must say matching on a column or left_column = right_column')
remainder = override[:replacement_span[0]] + override[replacement_span[1]:]
if remainder.strip(' \t\r\n.!?'):
raise SourceError('the key correction also contains another request; give only the matching columns, then describe the next operation separately')
if pairs is None:
common = [c for c in left_cols if c in right_cols]
if len(common) != 1:
raise SourceError('name the matching key columns; shared columns are %s' % (', '.join(common) or 'none'))
return [[common[0], common[0]]], None
keys = []
for a, b in pairs:
left = _column(a, left_cols, left_files)
right = _column(b, right_cols, right_files)
if left is None or right is None:
raise SourceError('matching %s to %s does not name a left and right column' % (a, b))
keys.append([left, right])
return keys, span
def resolve(text, root, fallback=None, output_files=(), key_override=None):
"""Receive one command's source shape and resulting columns.
Returns source/world/holes/owned/files/ops_text. The caller reads row
operations against world['cols'], and can use ops_text to avoid interpreting
a join's key binding as an operation on the resulting rows.
"""
names = input_files(text, output_files)
fallback = _read(fallback) if isinstance(fallback, str) else fallback
result = {'source': None, 'world': None, 'holes': [], 'owned': [], 'files': names, 'ops_text': text,
'retired_key_bindings': [], 'key_override': key_override}
low = DATA.sub(' FILE ', text.lower())
join_words = key_override is not None or bool(re.search(r'\b(?:join|joins|joined|joining|matching|matched|matches|match)\b', low))
is_stack = bool(re.search(r'\b(?:combine|combines|combined|combining|stack|stacks|stacked|stacking|append|appends|appended|union|concatenate|concatenates)\b', low))
lookup_words = bool(re.search(r'\b(?:lookup|look up|reference)\b', low))
uses_rate = bool(re.search(r'\b(?:with|using)\s+(?:the\s+)?rates?\b', low))
is_lookup = lookup_words or bool(uses_rate and not is_stack and not re.search(r'\bjoin\w*\b', low))
is_join = join_words or bool(not is_stack and re.search(r'\bwith\b', low) and len(names) >= 2)
try:
if not names:
source = fallback
elif len(names) == 1:
source = _read(names[0])
if is_lookup and fallback and names[0] not in files(fallback):
left, right = fallback, source
keys, span = _keys(text, source_snapshot(left, root)[0], source_snapshot(right, root)[0], files(left), files(right), key_override)
source = {'op': 'lookup', 'left': left, 'right': right, 'keys': keys, 'how': 'left'}
if span:
result['ops_text'] = text[:span[0]] + ' ' + text[span[1]:]
if key_override is not None:
result['retired_key_bindings'] = [text[span[0]:span[1]]]
elif is_lookup or is_join:
if len(names) != 2:
raise SourceError('join or lookup names more than two sources; supply the next pair and its matching columns explicitly')
left, right = _read(names[0]), _read(names[1])
# "lookup rates.csv for prices.csv" names the reference first.
if re.search(r'\b(?:lookup|look up)\s+`?' + re.escape(names[0]) + r'\b', text, re.I):
left, right = right, left
keys, span = _keys(text, source_snapshot(left, root)[0], source_snapshot(right, root)[0], files(left), files(right), key_override)
left_position = text.lower().find(files(left)[0].lower())
before_left = text[:left_position] if left_position >= 0 else ''
keeps_left = re.search(r'\bleft\s+(?:outer\s+)?join\b', low) or re.search(r'\b(?:each|every|all)\b', before_left, re.I)
how = 'left' if is_lookup or keeps_left else 'inner'
if re.search(r'\binner\s+join\b', low):
how = 'inner'
source = {'op': 'lookup' if is_lookup else 'join', 'left': left, 'right': right, 'keys': keys, 'how': how}
if span:
result['ops_text'] = text[:span[0]] + ' ' + text[span[1]:]
if key_override is not None:
result['retired_key_bindings'] = [text[span[0]:span[1]]]
elif is_stack or re.search(r'\bFILE\s*(?:,|and)', low):
source = {'op': 'union', 'inputs': [_read(name) for name in names]}
else:
raise SourceError('several input tables are named; say whether to stack them or join them on named columns')
if source is None:
return result
world = describe(root, source)
result.update(source=source, world=world, files=files(source))
if source.get('op') != 'read':
result['owned'] = _RELATION_WORDS.split()
except (SourceError, KeyError, TypeError, OSError) as exc:
result['holes'].append({'kind': 'source', 'files': names, 'text': str(exc)})
result['source'] = locals().get('source')
return result
|