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