XiaoHongbo-Hope commented on code in PR #11299:
URL: https://github.com/apache/paimon/pull/11299#discussion_r4696061067


##########
paimon-python/pypaimon/multimodal/lerobot/export.py:
##########
@@ -0,0 +1,538 @@
+# 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.
+
+"""Export a source Dataset from Paimon to LeRobot v2.0, v2.1, or v3.0."""
+
+import copy
+import hashlib
+import json
+import re
+import shutil
+import tempfile
+from pathlib import Path
+from urllib.parse import urlparse
+
+import pyarrow as pa
+import pyarrow.parquet as pq
+
+from pypaimon.catalog.catalog_exception import TableNotExistException
+from pypaimon.common.options.core_options import CoreOptions
+from pypaimon.data.generic_variant import GenericVariant
+from pypaimon.multimodal.lerobot.dataset import _component_table, _read_arrow
+from pypaimon.multimodal.lerobot.metadata import (
+    _companion_identifier, _companion_table_identifiers, _dataset_fps,
+    _validate_tag_name,
+)
+from pypaimon.multimodal.lerobot.reader import _PaimonTableFrameReader
+from pypaimon.multimodal.table import _target_schema
+from pypaimon.table.row.blob import Blob, VideoFrameDescriptor
+from pypaimon.table.object.object_table import ObjectTable
+
+
+_V2_DATA_PATH = 
"data/chunk-{episode_chunk:03d}/episode_{episode_index:06d}.parquet"
+_V2_VIDEO_PATH = 
"videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4"
+_V3_DATA_PATH = "data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet"
+_V3_VIDEO_PATH = 
"videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4"
+
+
+def export_to_lerobot(connection, table_name, *, output_table,
+                      version="v3.0", dataset_id=None, tag_name=None,
+                      batch_size=1024):
+    """Export one original Dataset; the destination must not already exist.
+
+    The v3 exporter copies each encoded video payload once. The v2 exporter
+    writes one exact-frame MP4 per Episode and camera; this requires PyAV.
+    Both formats preserve source-local frame, Episode, and task indices.
+    """
+    if version not in ("v2.0", "v2.1", "v3.0"):
+        raise ValueError("LeRobot export version must be v2.0, v2.1, or v3.0.")
+    if isinstance(batch_size, bool) or not isinstance(batch_size, int) \
+            or batch_size <= 0:
+        raise ValueError("batch_size must be a positive integer.")
+    if dataset_id is not None and (not isinstance(dataset_id, str)
+                                   or not dataset_id):
+        raise ValueError("dataset_id must be a non-empty string.")
+    if tag_name is not None:
+        _validate_tag_name(tag_name)
+    if not isinstance(output_table, str) or not output_table:
+        raise ValueError("output_table must name an Object Table.")
+    table = connection.catalog.get_table(connection._identifier(output_table))
+    if not isinstance(table, ObjectTable):
+        raise ValueError("output_table must name an Object Table.")
+    object_location = table.location()
+    parsed = urlparse(object_location)
+    if parsed.scheme != "oss" or not parsed.netloc:
+        raise ValueError("Object Table output must use OSS storage.")
+    try:
+        frames = connection.get_table(table_name)
+    except TableNotExistException:
+        frames_name = _companion_identifier(
+            connection._identifier(table_name), "_frames")
+        frames = connection.get_table(frames_name)
+    raw_frames = frames.raw_table
+    identifiers = _companion_table_identifiers(raw_frames)
+    catalog = connection.catalog
+    read_frames = _component_table(catalog, raw_frames, tag_name)
+    datasets = _component_table(
+        catalog, catalog.get_table(identifiers["datasets"]), tag_name)
+    episodes = _component_table(
+        catalog, catalog.get_table(identifiers["episodes"]), tag_name)
+    sources = _read_arrow(datasets, _target_schema(datasets).names)
+    if dataset_id is None:
+        if sources.num_rows != 1:
+            raise ValueError(
+                "dataset_id is required when the LeRobot group has %d 
Datasets."
+                % sources.num_rows)
+        source = sources.to_pylist()[0]
+    else:
+        selected = [row for row in sources.to_pylist()
+                    if row["id"] == dataset_id]
+        if len(selected) != 1:
+            raise ValueError("LeRobot dataset_id %r was not found." % 
dataset_id)
+        source = selected[0]
+    source_id = source["id"]
+    if (not isinstance(source_id, str)
+            or re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", source_id) is None):
+        raise ValueError("LeRobot Dataset id is not a safe directory name.")
+    target_uri = object_location.rstrip("/") + "/" + source_id
+    if _prefix_has_files(table.file_io, target_uri):
+        raise FileExistsError(target_uri)
+    info = json.loads(source["info"])
+    info["fps"] = _dataset_fps(info.get("fps"))
+    source_episodes = _read_source_episodes(episodes, source["id"])
+    episode_schema = _target_schema(episodes)
+    if len(source_episodes) != info["total_episodes"]:
+        raise ValueError("LeRobot Episode count disagrees with Dataset 
metadata.")
+    expected = 0
+    for number, episode in enumerate(source_episodes):
+        if (episode["episode_index"] != number
+                or episode["dataset_from_index"] != expected
+                or episode["dataset_to_index"] - expected != 
episode["length"]):
+            raise ValueError("LeRobot source Episode ranges are not 
contiguous.")
+        expected = episode["dataset_to_index"]
+    if expected != info["total_frames"]:
+        raise ValueError("LeRobot Frame count disagrees with Dataset 
metadata.")
+
+    stage = None
+    reader = None
+    try:
+        stage = Path(tempfile.mkdtemp(prefix=".lerobot-export-"))
+        reader = _PaimonTableFrameReader(
+            read_frames, columns=_target_schema(read_frames).names)
+        _write_dataset(stage, reader, source, info, source_episodes,
+                       episode_schema, version, batch_size)
+        reader.close()
+        reader = None
+        _upload_to_object_table(stage, target_uri, table.file_io)
+        return target_uri
+    finally:
+        if reader is not None:
+            reader.close()
+        if stage is not None and stage.exists():
+            shutil.rmtree(stage)
+
+
+def _upload_to_object_table(stage, prefix, file_io):
+    if _prefix_has_files(file_io, prefix):

Review Comment:
   Thanks. This PR assumes one writer per Dataset ID. The unsafe rollback is 
fixed, but same-ID concurrent exports remain unsupported; a cross-process 
guarantee needs strict exclusive-create in FileIO. I will leave this P1 open if 
concurrent export is required for merge.



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

Reply via email to