codewarnab commented on code in PR #41186:
URL: https://github.com/apache/beam/pull/41186#discussion_r4669852513
##########
sdks/python/apache_beam/yaml/yaml_io.py:
##########
@@ -99,6 +104,260 @@ def write_to_text(pcoll, path: str):
lambda x: str(getattr(x, sole_field_name))) | beam.io.WriteToText(path)
+def read_from_csv(
+ path: str,
+ *,
+ sep: str = ',',
+ comment: Optional[str] = None,
+ filename_column: Optional[str] = None,
+ error_handling: Optional[Mapping[str, Any]] = None,
+ **kwargs):
+ """Reads comma-separated values (csv) files into a PCollection of rows.
+
+ Without ``error_handling``, this is ``apache_beam.io.ReadFromCsv``.
+
+ With ``error_handling``, each record is parsed on its own, and records
+ that fail to parse go to the error output instead of failing the pipeline.
+ Each error row has the source file path and the raw record text.
+ The column types come from the first 100 records of the first file.
Review Comment:
I used 100 because Beam's existing reader (`ReadViaPandas`) also looks at
the first 100 rows to work out the column types:
[apache_beam/dataframe/io.py#L288-L290](https://github.com/apache/beam/blob/fae0f5299be93bb232358f4dadd1191eb14f3aaa/sdks/python/apache_beam/dataframe/io.py#L288-L290).
Using the same number means turning on `error_handling` gives the same types
as leaving it off. I can make it a shared constant or a setting if you prefer.
##########
sdks/python/apache_beam/yaml/yaml_io.py:
##########
@@ -99,6 +104,260 @@ def write_to_text(pcoll, path: str):
lambda x: str(getattr(x, sole_field_name))) | beam.io.WriteToText(path)
+def read_from_csv(
+ path: str,
+ *,
+ sep: str = ',',
+ comment: Optional[str] = None,
+ filename_column: Optional[str] = None,
+ error_handling: Optional[Mapping[str, Any]] = None,
+ **kwargs):
+ """Reads comma-separated values (csv) files into a PCollection of rows.
+
+ Without ``error_handling``, this is ``apache_beam.io.ReadFromCsv``.
+
+ With ``error_handling``, each record is parsed on its own, and records
+ that fail to parse go to the error output instead of failing the pipeline.
+ Each error row has the source file path and the raw record text.
+ The column types come from the first 100 records of the first file.
+
+ Args:
+ path (str): The file path to read from. The path can contain glob
+ characters such as ``*`` and ``?``.
+ sep (str): The field delimiter.
+ comment (str): Lines that start with this character are skipped.
+ filename_column (str): If set, the name of a column to add to each
+ record, containing the path of the source file.
+ error_handling: If specified, should be a mapping giving an output into
+ which to emit records that failed to parse, as described at
+ https://beam.apache.org/documentation/sdks/yaml-errors/
+ """
+ if not error_handling:
+ return beam_io.ReadFromCsv(
+ path,
+ sep=sep,
+ comment=comment,
+ filename_column=filename_column,
+ **kwargs)
+ if kwargs:
+ raise ValueError(
+ f'ReadFromCsv does not support {sorted(kwargs)} with error_handling.')
+
+ def sample(handle):
+ return pd.read_csv(
+ handle,
+ sep=sep,
+ comment=comment,
+ nrows=_SAMPLE_SIZE,
+ on_bad_lines='skip')
+
+ def parse_record(header, record, dtypes):
+ columns = list(dtypes)
+ fields = pd.read_csv(
+ io.StringIO(record), header=None, sep=sep, comment=comment, dtype=str)
+ if len(fields.columns) != len(columns):
+ raise ValueError(
+ f'Expected {len(columns)} fields, got {len(fields.columns)}.')
+ df = pd.read_csv(
+ io.StringIO(header + record), sep=sep, comment=comment, dtype=dtypes)
+ if list(df.columns) != columns:
+ raise ValueError(
+ f'The file header {list(df.columns)} does not match {columns}.')
+ return df
+
+ def parse_file(lines, proxy):
+ dtypes = proxy.dtypes.drop(filename_column, errors='ignore').to_dict()
+ header = None
+ for record in _join_quoted_lines(lines, comment):
+ if not record.strip():
+ continue
+ if header is None:
+ header = record
+ else:
+ yield record, functools.partial(parse_record, header, record, dtypes)
+
+ return _ReadFilesWithErrors(
+ path, sample, parse_file, filename_column, error_handling)
+
+
+def read_from_json(
+ path: str, *, error_handling: Optional[Mapping[str, Any]] = None,
**kwargs):
+ """Reads newline-delimited JSON files into a PCollection of rows.
+
+ Without ``error_handling``, this is ``apache_beam.io.ReadFromJson``.
+
+ With ``error_handling``, each line is parsed on its own, and lines
+ that fail to parse go to the error output instead of failing the pipeline.
+ Each error row has the source file path and the raw line.
+ The column types come from the first 100 records of the first file.
+
+ Args:
+ path (str): The file path to read from. The path can contain glob
+ characters such as ``*`` and ``?``.
+ error_handling: If specified, should be a mapping giving an output into
+ which to emit lines that failed to parse, as described at
+ https://beam.apache.org/documentation/sdks/yaml-errors/
+ """
+ if not error_handling:
+ return beam_io.ReadFromJson(path, **kwargs)
+ if kwargs:
+ raise ValueError(
+ f'ReadFromJson does not support {sorted(kwargs)} with error_handling.')
+
+ def read_json(text):
+ return pd.read_json(
+ io.StringIO(text), orient='records', lines=True, dtype=False)
+
+ def sample(handle):
+ good_lines = []
+ for line in itertools.islice(handle, _SAMPLE_SIZE):
+ try:
+ if isinstance(json.loads(line), dict):
+ good_lines.append(line)
+ except ValueError:
+ pass
+ if not good_lines:
+ raise ValueError(
+ f'Found no JSON objects in the first {_SAMPLE_SIZE} lines '
+ 'of the first file, so the column types are unknown.')
+ return read_json(''.join(good_lines))
+
+ def parse_record(line, proxy):
+ value = json.loads(line)
+ if not isinstance(value, dict):
+ raise ValueError('Expected a JSON object.')
+ unknown_fields = set(value) - set(proxy.columns)
+ if unknown_fields:
+ raise ValueError(f'Unknown fields {sorted(unknown_fields)}.')
+ return read_json(line).reindex(columns=proxy.columns)
+
+ def parse_file(lines, proxy):
+ for line in lines:
+ if line.strip():
+ yield line, functools.partial(parse_record, line, proxy)
+
+ return _ReadFilesWithErrors(path, sample, parse_file, None, error_handling)
+
+
+# The number of records used to infer column types when error_handling is set.
+_SAMPLE_SIZE = 100
Review Comment:
Same reason as above.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]