You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by GitBox <gi...@apache.org> on 2020/09/16 07:55:46 UTC

[GitHub] [beam] chamikaramj commented on a change in pull request #12841: [BEAM-10894] Basic CSV reading and writing.

chamikaramj commented on a change in pull request #12841:
URL: https://github.com/apache/beam/pull/12841#discussion_r489208399



##########
File path: sdks/python/apache_beam/dataframe/io.py
##########
@@ -0,0 +1,178 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import
+
+from io import BytesIO
+from io import StringIO
+from io import TextIOWrapper
+
+import pandas as pd
+
+import apache_beam as beam
+from apache_beam import io
+from apache_beam.dataframe import frame_base
+
+
+def read_csv(path, *args, **kwargs):
+  return _ReadFromPandas(pd.read_csv, path, args, kwargs)
+

Review comment:
       Is there a reason to provide these as methods instead of transforms (similar to other IO connectors) ?

##########
File path: sdks/python/apache_beam/dataframe/io.py
##########
@@ -0,0 +1,178 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import
+
+from io import BytesIO
+from io import StringIO
+from io import TextIOWrapper
+
+import pandas as pd
+
+import apache_beam as beam
+from apache_beam import io
+from apache_beam.dataframe import frame_base
+
+
+def read_csv(path, *args, **kwargs):

Review comment:
       Please add pydocs for public API here (or add a TODO/JIRA for this).

##########
File path: sdks/python/apache_beam/dataframe/io.py
##########
@@ -0,0 +1,178 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import
+
+from io import BytesIO
+from io import StringIO
+from io import TextIOWrapper
+
+import pandas as pd
+
+import apache_beam as beam
+from apache_beam import io
+from apache_beam.dataframe import frame_base
+
+
+def read_csv(path, *args, **kwargs):
+  return _ReadFromPandas(pd.read_csv, path, args, kwargs)
+
+
+def write_csv(df, path, *args, **kwargs):
+  from apache_beam.dataframe import convert
+  # TODO(roberwb): Amortize the computation for multiple writes?
+  return convert.to_pcollection(df) | _WriteToPandas(
+      pd.DataFrame.to_csv, path, args, kwargs, incremental=True, binary=False)
+
+
+def _prefix_range_index_with(prefix, df):
+  if isinstance(df.index, pd.RangeIndex):
+    return df.set_index(prefix + df.index.map(str).astype(str))
+  else:
+    return df
+
+
+class _ReadFromPandas(beam.PTransform):
+  def __init__(self, reader, path, args, kwargs):
+    if not isinstance(path, str):
+      raise frame_base.WontImplementError('non-deferred')
+    self.reader = reader
+    self.path = path
+    self.args = args
+    self.kwargs = kwargs
+
+  def expand(self, root):
+    # TODO(robertwb): Handle streaming (with explicit schema).
+    paths_pcoll = root | beam.Create([self.path])
+    first = io.filesystems.FileSystems.match([self.path],
+                                             limits=[1
+                                                     ])[0].metadata_list[0].path
+    with io.filesystems.FileSystems.open(first) as handle:
+      df = next(self.reader(handle, *self.args, chunksize=100, **self.kwargs))
+
+    # TODO(robertwb): Actually make an SDF.
+    def expand_pattern(pattern):
+      for match_result in io.filesystems.FileSystems.match([pattern]):
+        for metadata in match_result.metadata_list:
+          yield metadata.path
+
+    pcoll = (
+        paths_pcoll
+        | beam.FlatMap(expand_pattern)
+        | beam.ParDo(_ReadFromPandasDoFn(self.reader, self.args, self.kwargs)))
+    from apache_beam.dataframe import convert
+    return convert.to_dataframe(
+        pcoll, proxy=_prefix_range_index_with(':', df[:0]))
+
+
+class _ReadFromPandasDoFn(beam.DoFn):
+  def __init__(self, reader, args, kwargs):
+    # avoid pickling issues
+    self.reader = reader.__name__
+    self.args = args
+    self.kwargs = kwargs
+
+  def process(self, path):
+    reader = getattr(pd, self.reader)
+    for df in reader(path, *self.args, chunksize=100, **self.kwargs):
+      yield _prefix_range_index_with(path + ':', df)
+
+
+class _WriteToPandas(beam.PTransform):
+  def __init__(
+      self, writer, path, args, kwargs, incremental=False, binary=True):
+    self.writer = writer
+    self.path = path
+    self.args = args
+    self.kwargs = kwargs
+    self.incremental = incremental
+    self.binary = binary
+
+  def expand(self, pcoll):
+    return pcoll | io.Write(
+        _WriteToPandasFileBasedSink(
+            self.writer,
+            self.path,
+            self.args,
+            self.kwargs,
+            self.incremental,
+            self.binary))
+
+
+class _WriteToPandasFileBasedSink(io.FileBasedSink):

Review comment:
       Instead of extending FileBasedSink here please implement a fileio.FileSink and use fileio.WriteToFiles.
   https://github.com/apache/beam/blob/master/sdks/python/apache_beam/io/fileio.py#L76

##########
File path: sdks/python/apache_beam/dataframe/io.py
##########
@@ -0,0 +1,178 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import
+
+from io import BytesIO
+from io import StringIO
+from io import TextIOWrapper
+
+import pandas as pd
+
+import apache_beam as beam
+from apache_beam import io
+from apache_beam.dataframe import frame_base
+
+
+def read_csv(path, *args, **kwargs):
+  return _ReadFromPandas(pd.read_csv, path, args, kwargs)
+
+
+def write_csv(df, path, *args, **kwargs):
+  from apache_beam.dataframe import convert
+  # TODO(roberwb): Amortize the computation for multiple writes?
+  return convert.to_pcollection(df) | _WriteToPandas(
+      pd.DataFrame.to_csv, path, args, kwargs, incremental=True, binary=False)
+
+
+def _prefix_range_index_with(prefix, df):
+  if isinstance(df.index, pd.RangeIndex):
+    return df.set_index(prefix + df.index.map(str).astype(str))
+  else:
+    return df
+
+
+class _ReadFromPandas(beam.PTransform):
+  def __init__(self, reader, path, args, kwargs):
+    if not isinstance(path, str):
+      raise frame_base.WontImplementError('non-deferred')
+    self.reader = reader
+    self.path = path
+    self.args = args
+    self.kwargs = kwargs
+
+  def expand(self, root):
+    # TODO(robertwb): Handle streaming (with explicit schema).
+    paths_pcoll = root | beam.Create([self.path])
+    first = io.filesystems.FileSystems.match([self.path],
+                                             limits=[1
+                                                     ])[0].metadata_list[0].path
+    with io.filesystems.FileSystems.open(first) as handle:
+      df = next(self.reader(handle, *self.args, chunksize=100, **self.kwargs))
+
+    # TODO(robertwb): Actually make an SDF.
+    def expand_pattern(pattern):
+      for match_result in io.filesystems.FileSystems.match([pattern]):
+        for metadata in match_result.metadata_list:
+          yield metadata.path
+
+    pcoll = (
+        paths_pcoll
+        | beam.FlatMap(expand_pattern)

Review comment:
       Probably we can replace above file-handling related transforms with transforms available in fileio.
   https://github.com/apache/beam/blob/master/sdks/python/apache_beam/io/fileio.py
   
   For example,
   fileio.MatchFiles(self.path) | ParDo(_ReadFromPandasFromReadableFileDoFn())
   
   (ReadableFile.metadata.path gives the file path).




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org