Source code

Download source archive ↓

src/piflow_portable.py

1"""Arrow stream adapters for portable PiFlow components."""
2
3import bisect
4import json
5import math
6import re
7import statistics
8from xml.etree import ElementTree
9
10import pyarrow as pa
11import pyarrow.compute as pc
12import piflow_documents as documents
13import piflow_collections as collections
14import piflow_tabular as tabular
15from xstream_operator import descriptor, preview_process, records_schema, result, run_operator
16
17MAX_INPUT = 8 * 1024 * 1024
18HALF_WIDTH = str.maketrans({**{c: c - 65248 for c in range(0xff01, 0xff5f)}, 0x3000: 32})
19PROVINCES = dict(zip(
20    "beijing tianjin shanghai chongqing anhui fujian gansu guangdong guizhou hainan hebei heilongjiang "
21    "henan hubei hunan jiangsu jiangxi jilin liaoning qinghai shaanxi shanxi shandong sichuan yunnan "
22    "zhejiang inner-mongolia ningxia guangxi xinjiang tibet".split(),
23    "北京 天津 上海 重庆 安徽 福建 甘肃 广东 贵州 海南 河北 黑龙江 河南 湖北 湖南 江苏 江西 吉林 辽宁 "
24    "青海 陕西 山西 山东 四川 云南 浙江 内蒙古自治区 宁夏回族自治区 广西壮族自治区 新疆维吾尔自治区 西藏自治区".split(),
25))
26CLEANERS = {"email_clean", "phone_number_clean", "identity_number_clean", "province_clean", "title_clean"}
27SCALERS = {"max_min_normalization", "scope_normalization", "z_score", "discretization"}
28
29
30def clean(value, operation):
31    if value is None:
32        return "" if operation == "province_clean" else None
33    if not isinstance(value, str):
34        raise ValueError("cleaning columns must contain strings")
35    value = value.translate(HALF_WIDTH)
36    if operation == "title_clean":
37        return value
38    if operation == "email_clean":
39        value = value.lower()
40        return value if re.fullmatch(r"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z0-9-]+", value) else ""
41    if operation == "phone_number_clean":
42        value = re.sub("[^0-9]", "", value)
43        return value if re.fullmatch(r"1[34578][0-9]{9}", value) else None
44    if operation == "identity_number_clean":
45        value = re.sub("[^0-9X]", "", value.upper()).lstrip("0")
46        if re.fullmatch("[0-9]{15}", value):
47            return value
48        if re.fullmatch("[0-9]{17}[0-9X]", value):
49            weights = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
50            checksum = sum(int(digit) * weight for digit, weight in zip(value, weights))
51            if value[-1] == "10X98765432"[checksum % 11]:
52                return value
53        return None
54    normalized = value.strip().casefold().replace(" ", "-")
55    for pinyin, name in PROVINCES.items():
56        if normalized in {pinyin, name.casefold(), name + "省", name + "市"}:
57            return name
58        if name.endswith("自治区") and normalized in {"内蒙古", "宁夏", "广西", "新疆", "西藏"} and name.startswith(normalized):
59            return name
60    return value
61
62
63def names(text):
64    values = [value.strip() for value in text.split(",")]
65    if not all(values) or len(values) != len(set(values)):
66        raise ValueError("column names must be unique and nonempty")
67    return values
68
69
70def field_indices(schema, columns):
71    indices = [schema.get_field_index(name) for name in columns]
72    if -1 in indices:
73        raise ValueError("input includes an unknown or ambiguous column")
74    return indices
75
76
77def scale_columns(operation, params):
78    if operation == "z_score":
79        ins, outs = names(params["inputCols"]), names(params["outputCols"])
80        if len(ins) != len(outs):
81            raise ValueError("inputCols and outputCols must contain the same number of names")
82        return list(zip(ins, outs))
83    return [(params["inputCol"], params["outputCol"])]
84
85
86def scale(values, operation, params):
87    available = [float(value) for value in values if value is not None]
88    if not all(map(math.isfinite, available)):
89        raise ValueError("scaling requires finite numeric input")
90    if not available:
91        return values
92    if operation == "discretization":
93        count = params["numBins"]
94        if not 2 <= count <= 1000:
95            raise ValueError("numBins must be from 2 to 1000")
96        if params["method"] == "EqualWidth":
97            if any(value < 0 or value > count for value in available):
98                raise ValueError("EqualWidth accepts values from zero through numBins")
99            apply = lambda value: min(int(value), count - 1)
100        elif params["method"] == "EqualFrequency":
101            ordered = sorted(available)
102            cuts = sorted({ordered[min(len(ordered) - 1, math.ceil(len(ordered) * i / count) - 1)]
103                           for i in range(1, count)} - {ordered[0], ordered[-1]})
104            apply = lambda value: bisect.bisect_right(cuts, value)
105        else:
106            raise ValueError("method must be EqualWidth or EqualFrequency")
107    else:
108        if operation == "z_score":
109            origin = statistics.mean(available)
110            spread = statistics.stdev(available) if len(available) > 1 else 0
111        else:
112            origin = min(available)
113            spread = max(available) - origin
114        low, high = params["range"] if operation == "scope_normalization" else (0, 1)
115        if not math.isfinite(low) or not math.isfinite(high) or low >= high:
116            raise ValueError("range must have two increasing finite bounds")
117        apply = lambda value: (value - origin) / spread * (high - low) + low if spread else None
118    return [None if value is None else apply(value) for value in values]
119
120
121def replace_column(table, name, values):
122    index = table.schema.get_field_index(name)
123    return table.append_column(name, values) if index < 0 else table.set_column(index, name, values)
124
125
126def collect(chunks):
127    data = bytearray()
128    for chunk in chunks:
129        data.extend(chunk)
130        if len(data) > MAX_INPUT:
131            raise ValueError("input exceeds 8 MiB")
132    return bytes(data)
133
134
135def collect_records(port, schema):
136    batches, size, rows = [], 0, 0
137    for batch in port.records():
138        size += batch.nbytes
139        rows += batch.num_rows
140        if size > MAX_INPUT or rows > 100_000:
141            raise ValueError("batch operation accepts at most 8 MiB and 100,000 records")
142        batches.append(batch)
143    return pa.Table.from_batches(batches, schema=schema)
144
145
146def json_rows(data):
147    def invalid_number(value):
148        raise ValueError("non-finite JSON number: " + value)
149
150    root = json.loads(data, parse_constant=invalid_number)
151    rows = root if isinstance(root, list) else [root]
152    if not all(isinstance(row, dict) for row in rows):
153        raise ValueError("JSON input must be an object or an array of objects")
154    # Arrow's Python row inference reads its columns from the first row.
155    columns = dict.fromkeys(key for row in rows for key in row)
156    return pa.table({column: [row.get(column) for row in rows] for column in columns})
157
158
159class XmlBuilder(ElementTree.TreeBuilder):
160    def doctype(self, name, pubid, system):
161        raise ValueError("XML document types are unsupported")
162
163
164def xml_root(data):
165    if len(data) > MAX_INPUT:
166        raise ValueError("XML exceeds 8 MiB")
167    return ElementTree.fromstring(data, parser=ElementTree.XMLParser(target=XmlBuilder()))
168
169
170def xml_rows(root, operation, params):
171    if operation == "xml_parser":
172        selected = list(root.iter(params["rowTag"]))
173        columns = list(dict.fromkeys(child.tag for row in selected for child in row))
174    else:
175        tags = names(params["label"])
176        if root.tag != tags[0] or len(tags) < 2:
177            raise ValueError("label must start with the root and name a repeated child tag")
178        selected = root.findall("/".join(tags[1:]))
179        columns = names(params["schema"])
180    return pa.table({column: pa.array([row.findtext(column) or None for row in selected], type=pa.string())
181                     for column in columns})
182
183
184def xml_model(node, depth=0):
185    if depth >= 32:
186        raise ValueError("XML nesting exceeds 32 levels")
187    if not node.attrib and not len(node):
188        return node.text
189    model = {"@" + name: value for name, value in node.attrib.items()}
190    if node.text and node.text.strip():
191        model["#text"] = node.text
192    groups = {}
193    for child in node:
194        groups.setdefault(child.tag, []).append(xml_model(child, depth + 1))
195    model.update({key: values[0] if len(values) == 1 else values for key, values in groups.items()})
196    return model
197
198
199def parse_xml_column(value):
200    if value is None:
201        return None
202    root = xml_root(value)
203    return json.dumps({root.tag: xml_model(root)}, ensure_ascii=False)
204
205
206def put_xml_row(root, row):
207    target = ElementTree.SubElement(root, "ROW")
208    for name, value in row.items():
209        if not re.fullmatch(r"[a-zA-Z_][a-zA-Z0-9_.-]*", name):
210            raise ValueError("record column is not an XML name: " + name)
211        if isinstance(value, (list, dict)):
212            raise ValueError("XML serialization accepts scalar columns")
213        if value is not None:
214            ElementTree.SubElement(target, name).text = str(value)
215
216
217def emit(ctx, table, port="result"):
218    out = ctx.records_output(port, table.schema)
219    for batch in table.to_batches(max_chunksize=1024):
220        out.write(batch)
221
222
223def emit_graph(ctx, edges, vertices):
224    tables = {
225        "edges": pa.Table.from_pylist(edges, schema=collections.EDGE_SCHEMA),
226        "vertex": pa.Table.from_pylist(vertices, schema=collections.VERTEX_SCHEMA),
227    }
228    outputs = {name: ctx.records_output(name, table.schema) for name, table in tables.items()}
229    for name, table in tables.items():
230        for batch in table.to_batches(max_chunksize=1024):
231            outputs[name].write(batch)
232
233
234def inferred_schema(operation, schema, params):
235    if operation == "average_temperature":
236        return tabular.SENSOR_SCHEMA
237    if operation in {"data_sort", "complement_by_memcache"}:
238        return schema
239    if operation == "field_type_conversion" and schema is not None:
240        return tabular.numeric_schema(schema, params, names)
241    if operation == "all_fields_clean_neo4j" and schema is not None:
242        return tabular.string_schema(schema)
243    if operation == "person_id_expansion" and schema is not None:
244        removed = [params["expandIDField"], params["expandIDType"]]
245        field_indices(schema, removed)
246        retained = [field for field in schema if field.name not in removed]
247        added = [*collections.ID_FIELDS, "source", "uuid", "id_hash"]
248        if len(set(removed)) != 2 or any(field.name in added for field in retained):
249            raise ValueError("input names conflict with generated identity fields")
250        return pa.schema(retained + [pa.field(name, pa.string()) for name in added], metadata=schema.metadata)
251    if operation == "folder_csv_parser":
252        return pa.schema([(name, pa.string()) for name in names(params["schema"])])
253    if operation == "select_files_by_name":
254        return pa.schema([("path", pa.string())])
255    if operation == "card_code_clean" and schema is not None:
256        field = schema.field(field_indices(schema, [params["cardCodeField"], params["cardTypeField"]])[0])
257        if not pa.types.is_string(field.type):
258            raise ValueError("cardCodeField must be a string column")
259        return schema
260    if operation == "regex_text_process" and schema is not None:
261        column = schema.field(field_indices(schema, [params["columnName"]])[0])
262        if not pa.types.is_string(column.type) or column.name + "_new" in schema.names:
263            raise ValueError("input must be a string column with an unused _new field name")
264        return schema.append(pa.field(column.name + "_new", pa.string()))
265    if operation == "pdf_parser":
266        return pa.schema([("page", pa.int64()), ("text", pa.string())])
267    if operation in {"docx_parser", "html_parser"}:
268        return documents.RECORDS_TEXT
269    if operation == "pptx_parser":
270        return documents.RECORDS_TEXT.append(pa.field("slide", pa.int64()))
271    if operation == "xml_parser_generate_new_field" and schema is not None:
272        field_indices(schema, [params["decoderField"]])
273        name = params["newField"]
274        if not name or name in schema.names:
275            raise ValueError("newField must be nonempty and absent from the input")
276        return schema.append(pa.field(name, pa.string()))
277    if operation in CLEANERS | {"xml_parser_columns"} and schema is not None:
278        columns = params["xmlColumns"] if operation == "xml_parser_columns" else params["columnName"]
279        indices = field_indices(schema, names(columns))
280        if any(not pa.types.is_string(schema.field(i).type) and not pa.types.is_large_string(schema.field(i).type)
281               for i in indices):
282            raise ValueError("selected columns must be strings")
283        return pa.schema([pa.field(field.name, pa.string()) if i in indices else field
284                          for i, field in enumerate(schema)], metadata=schema.metadata)
285    if operation in SCALERS and schema is not None:
286        for source, target in scale_columns(operation, params):
287            field = schema.field(field_indices(schema, [source])[0])
288            if not (pa.types.is_integer(field.type) or pa.types.is_floating(field.type)):
289                raise ValueError("scaling requires integer or floating-point columns")
290        for source, target in scale_columns(operation, params):
291            field = pa.field(target, pa.float64())
292            index = schema.get_field_index(target)
293            schema = schema.append(field) if index == -1 else schema.set(index, field)
294    if operation == "json_string_parser":
295        return json_rows(params["jsonString"]).schema
296    if operation == "xml_string_parser":
297        return pa.schema([(column, pa.string()) for column in names(params["schema"])])
298    return schema if operation in CLEANERS | SCALERS | {"xml_parser_columns"} else None
299
300
301def process(ctx, operation):
302    params = ctx.params
303    if operation in {"json_string_parser", "xml_string_parser"}:
304        if operation == "json_string_parser":
305            emit(ctx, json_rows(params["jsonString"]))
306        else:
307            emit(ctx, xml_rows(xml_root(params["XmlString"]), operation, params))
308        return
309    if operation in collections.FOLDER_OPERATORS:
310        emit(ctx, collections.folder_tables(ctx, operation, params, collect, json_rows, xml_root, xml_rows, names))
311        return
312    if operation == "complement_by_memcache":
313        lookup = ctx.input("lookup")
314        materialized = collect_records(lookup, lookup.schema)
315        tabular.enrich_records(ctx, materialized, ctx.input("source").schema, names)
316        return
317    if operation == "excel_write_multiple_sheets":
318        collections.excel_workbook(ctx, collect_records)
319        return
320    if operation == "label_propagation":
321        edges = ctx.input("edges")
322        edge_rows = collect_records(edges, edges.schema).to_pylist()
323        vertex = ctx.input("vertex")
324        vertex_rows = collect_records(vertex, vertex.schema).to_pylist()
325        labels = collections.label_propagation(edge_rows, vertex_rows, params["maxIter"])
326        emit_graph(ctx, edge_rows, labels)
327        return
328    source = ctx.input("source")
329    if operation == "load_graph":
330        edges, vertices = collections.load_graph(collect(source.bytes()))
331        emit_graph(ctx, edges, vertices)
332    elif operation == "select_files_by_name":
333        schema = inferred_schema(operation, source.schema, params)
334        index = field_indices(source.schema, [params["pathColumn"]])[0]
335        pattern = params["selectionConditions"]
336        if not isinstance(pattern, str) or len(pattern) > 256:
337            raise ValueError("selectionConditions must be a glob up to 256 characters")
338        out = ctx.records_output("result", schema)
339        for batch in source.records():
340            matching = [value for value in batch.column(index).to_pylist() if collections.file_matches(value, pattern)]
341            out.write(pa.RecordBatch.from_arrays([pa.array(matching, type=pa.string())], schema=schema))
342    elif operation == "regex_text_process":
343        schema = inferred_schema(operation, source.schema, params)
344        index = field_indices(schema, [params["columnName"]])[0]
345        pattern, replacement = params["regex"], params["replaceStr"]
346        if len(pattern) > 1024 or len(replacement) > 2048:
347            raise ValueError("regular expression or replacement exceeds its size limit")
348        out = ctx.records_output("result", schema)
349        for batch in source.records():
350            # RE2 executes without backtracking. Limit input and expansion before calling Arrow.
351            column = batch.column(index)
352            widths = pc.binary_length(column).to_pylist()
353            max_bytes = sum((width + 1) * (len(replacement.encode()) + 1) for width in widths if width is not None)
354            if max_bytes > 32 * 1024 * 1024:
355                raise ValueError("potential regex expansion exceeds 32 MiB in one batch")
356            changed = pc.replace_substring_regex(column, pattern, replacement)
357            out.write(pa.RecordBatch.from_arrays([*batch.columns, changed], schema=schema))
358    elif operation in {"data_sort", "average_temperature"}:
359        table = collect_records(source, source.schema)
360        result = tabular.average_temperature(table.to_pylist()) if operation == "average_temperature" else tabular.sorted_table(table, params, names)
361        emit(ctx, result)
362    elif operation in {"field_type_conversion", "all_fields_clean_neo4j"}:
363        schema = inferred_schema(operation, source.schema, params)
364        out = ctx.records_output("result", schema)
365        for batch in source.records():
366            columns = []
367            for index, field in enumerate(schema):
368                column = pc.cast(batch.column(index), field.type)
369                if operation == "all_fields_clean_neo4j":
370                    column = pc.replace_substring(column, '"', '')
371                columns.append(column)
372            out.write(pa.RecordBatch.from_arrays(columns, schema=schema))
373    elif operation in {"card_code_clean", "person_id_expansion"}:
374        schema = inferred_schema(operation, source.schema, params)
375        out = ctx.records_output("result", schema)
376        for batch in source.records():
377            rows = batch.to_pylist()
378            if operation == "card_code_clean":
379                for row in rows:
380                    if str(row[params["cardTypeField"]]) == "1":
381                        key = params["cardCodeField"]
382                        row[key] = clean(row[key], "identity_number_clean")
383            else:
384                rows = [collections.expand_id(row, params) for row in rows]
385            out.write(pa.RecordBatch.from_pylist(rows, schema=schema))
386    elif operation in {"docx_parser", "pptx_parser", "html_parser", "pdf_parser", "flatten_xml_parser",
387                       "evaluate_json_path", "decompress_gzip"}:
388        data = collect(source.bytes())
389        if operation == "decompress_gzip":
390            out = ctx.bytes_output("result")
391            for chunk in documents.decompress(data):
392                out.write(chunk)
393            return
394        if operation == "html_parser":
395            table = documents.html_text(data)
396        elif operation == "pdf_parser":
397            table = documents.pdf_text(data, inferred_schema(operation, None, params))
398        elif operation in {"docx_parser", "pptx_parser"}:
399            table = documents.office_text(data, operation, xml_root)
400        elif operation == "evaluate_json_path":
401            table = documents.json_field(data, params["tag"], json_rows)
402        else:
403            table = documents.flatten_xml(xml_root(data), params)
404        emit(ctx, table)
405    elif operation == "xml_parser_generate_new_field":
406        schema = inferred_schema(operation, source.schema, params)
407        source_index = schema.get_field_index(params["decoderField"])
408        out = ctx.records_output("result", schema)
409        for batch in source.records():
410            values = [documents.xml_value(value, params["tagXPath"], xml_root)
411                      for value in batch.column(source_index).to_pylist()]
412            out.write(pa.RecordBatch.from_arrays([*batch.columns, pa.array(values, type=pa.string())], schema=schema))
413    elif operation in {"json_parser", "xml_parser"}:
414        data = collect(source.bytes())
415        emit(ctx, json_rows(data) if operation == "json_parser" else xml_rows(xml_root(data), operation, params))
416    elif operation == "json_save":
417        out = ctx.bytes_output("result")
418        for batch in source.records():
419            for row in batch.to_pylist():
420                out.write((json.dumps(row, ensure_ascii=False, allow_nan=False) + "\n").encode())
421    elif operation == "xml_save":
422        out = ctx.bytes_output("result")
423        out.write(b"<ROWS>")
424        for batch in source.records():
425            for row in batch.to_pylist():
426                temp = ElementTree.Element("ROWS")
427                put_xml_row(temp, row)
428                out.write(ElementTree.tostring(temp[0], encoding="utf-8"))
429        out.write(b"</ROWS>")
430    elif operation in SCALERS:
431        schema = source.schema
432        inferred_schema(operation, schema, params)
433        original = collect_records(source, schema)
434        table = original
435        for origin, target in scale_columns(operation, params):
436            values = scale(original[origin].to_pylist(), operation, params)
437            table = replace_column(table, target, pa.array(values, type=pa.float64()))
438        emit(ctx, table)
439    else:
440        schema = inferred_schema(operation, source.schema, params)
441        selected = names(params["xmlColumns"] if operation == "xml_parser_columns" else params["columnName"])
442        indices = field_indices(source.schema, selected)
443        out = ctx.records_output("result", schema)
444        for batch in source.records():
445            arrays = list(batch.columns)
446            for index in indices:
447                values = arrays[index].to_pylist()
448                cleaned = (parse_xml_column(value) if operation == "xml_parser_columns" else clean(value, operation)
449                           for value in values)
450                arrays[index] = pa.array(cleaned, type=pa.string())
451            out.write(pa.RecordBatch.from_arrays(arrays, schema=schema))
452
453
454def start(operation, output_view):
455    output_views = output_view if isinstance(output_view, dict) else {"result": output_view}
456    def execute(ctx):
457        process(ctx, operation)
458
459    def infer(inputs, params):
460        outputs = {}
461        for port, view in output_views.items():
462            schema = None
463            if view == "records":
464                if operation in {"load_graph", "label_propagation"}:
465                    schema = collections.EDGE_SCHEMA if port == "edges" else collections.VERTEX_SCHEMA
466                else:
467                    source = inputs.get("source")
468                    schema = inferred_schema(operation, records_schema(source) if source else None, params)
469            formats = ["arrow"] if view == "records" else ["xlsx"] if operation == "excel_write_multiple_sheets" else ["binary"]
470            outputs[port] = descriptor([view], formats, schema,
471                                       certainty="known" if schema is not None or view == "bytes" else "unknown")
472        return result(outputs)
473
474    def preview(inputs, params, limits):
475        if operation in collections.FOLDER_OPERATORS or operation == "excel_write_multiple_sheets":
476            return {}
477        return preview_process(execute, inputs, params, limits)
478
479    run_operator(execute, infer, preview_outputs=preview)