aIbrahiim commented on code in PR #38917: URL: https://github.com/apache/beam/pull/38917#discussion_r3402334349
########## sdks/python/apache_beam/examples/ml_transform/mltransform_image_embedding.py: ########## @@ -0,0 +1,263 @@ +# +# 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. +# + +"""Batch image embedding pipeline using MLTransform. + +The pipeline reads image URIs from a text file, decodes images with Pillow, +generates SentenceTransformers image embeddings through MLTransform, and writes +results to BigQuery using batch file loads. +""" + +import argparse +import hashlib +import io +import logging +import time +from collections.abc import Iterable +from typing import Any + +import apache_beam as beam +from apache_beam.io.filesystems import FileSystems +from apache_beam.ml.transforms.base import MLTransform +from apache_beam.ml.transforms.embeddings.huggingface import SentenceTransformerEmbeddings +from apache_beam.options.pipeline_options import PipelineOptions +from apache_beam.options.pipeline_options import SetupOptions +from apache_beam.options.pipeline_options import StandardOptions +from apache_beam.runners.runner import PipelineResult +from PIL import Image + +IMAGE_COLUMN = 'image' +IMAGE_ID_COLUMN = 'image_id' +IMAGE_URI_COLUMN = 'image_uri' + +DEFAULT_IMAGE_MODEL_NAME = 'clip-ViT-B-32' +DEFAULT_ACCELERATOR = 'type:nvidia-tesla-t4;count:1;install-nvidia-driver' +DEFAULT_EMBEDDING_MIN_RAM = '16GB' + +OUTPUT_TABLE_SCHEMA = { + 'fields': [ + { + 'name': 'image_id', 'type': 'STRING' + }, + { + 'name': 'image_uri', 'type': 'STRING' + }, + { + 'name': 'model_name', 'type': 'STRING' + }, + { + 'name': 'embedding', 'type': 'FLOAT64', 'mode': 'REPEATED' + }, + { + 'name': 'embedding_dim', 'type': 'INT64' + }, + { + 'name': 'infer_ms', 'type': 'INT64' + }, + ] +} + + +def now_millis() -> int: + return int(time.time() * 1000) + + +def sha1_hex(value: str) -> str: + return hashlib.sha1(value.encode('utf-8')).hexdigest() + + +def filter_empty_uri(uri: str) -> Iterable[str]: + uri = uri.strip() + if uri: + yield uri + + +def load_image_from_uri(uri: str) -> bytes: + with FileSystems.open(uri) as file: + return file.read() + + +def decode_pil(image_bytes: bytes) -> Image.Image: + with Image.open(io.BytesIO(image_bytes)) as image: + image = image.convert('RGB') + image.load() + return image + + +class ReadImage(beam.DoFn): + def process(self, uri: str) -> Iterable[dict[str, Any]]: + image_id = sha1_hex(uri) + try: + yield { + IMAGE_ID_COLUMN: image_id, + IMAGE_URI_COLUMN: uri, + IMAGE_COLUMN: decode_pil(load_image_from_uri(uri)), + } + except Exception as exc: + logging.warning( + 'Failed to read or decode image %s (%s): %s', image_id, uri, exc) + + +def _as_dict(row: Any) -> dict[str, Any]: + if hasattr(row, 'as_dict'): + return row.as_dict() + if hasattr(row, '_asdict'): + return row._asdict() + return dict(row) + + +def embedding_to_list(value: Any) -> list[float]: + if hasattr(value, 'tolist'): + value = value.tolist() + return [float(item) for item in value] + + +class FormatImageEmbeddingOutput(beam.DoFn): + def __init__(self, model_name: str): + self.model_name = model_name + + def process(self, row: Any) -> Iterable[dict[str, Any]]: + row = _as_dict(row) + embedding = embedding_to_list(row[IMAGE_COLUMN]) + yield { + IMAGE_ID_COLUMN: row[IMAGE_ID_COLUMN], + IMAGE_URI_COLUMN: row[IMAGE_URI_COLUMN], + 'model_name': self.model_name, + 'embedding': embedding, + 'embedding_dim': len(embedding), + 'infer_ms': now_millis(), Review Comment: The field stores a worker processing timestamp in epoch milliseconds (now_millis()), not inference duration -- 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]
