|
| 1 | +# Copyright 2024 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from dataclasses import dataclass |
| 16 | +import inspect |
| 17 | +from typing import Callable, Iterable |
| 18 | + |
| 19 | +import google.cloud.bigquery as bigquery |
| 20 | + |
| 21 | +import bigframes |
| 22 | +import bigframes.session._io.bigquery as bf_io_bigquery |
| 23 | + |
| 24 | +_PYTHON_TO_BQ_TYPES = {int: "INT64", float: "FLOAT64", str: "STRING", bytes: "BYTES"} |
| 25 | + |
| 26 | + |
| 27 | +@dataclass(frozen=True) |
| 28 | +class FunctionDef: |
| 29 | + """Definition of a Python UDF.""" |
| 30 | + |
| 31 | + func: Callable # function body |
| 32 | + requirements: Iterable[str] # required packages |
| 33 | + |
| 34 | + |
| 35 | +# TODO(garrettwu): migrate to bigframes UDF when it is available |
| 36 | +class TransformFunction: |
| 37 | + """Simple transform function class to deal with Python UDF.""" |
| 38 | + |
| 39 | + def __init__( |
| 40 | + self, func_def: FunctionDef, session: bigframes.Session, connection: str |
| 41 | + ): |
| 42 | + self._func = func_def.func |
| 43 | + self._requirements = func_def.requirements |
| 44 | + self._session = session |
| 45 | + self._connection = connection |
| 46 | + |
| 47 | + def _input_bq_signature(self): |
| 48 | + sig = inspect.signature(self._func) |
| 49 | + inputs = [] |
| 50 | + for k, v in sig.parameters.items(): |
| 51 | + inputs.append(f"{k} {_PYTHON_TO_BQ_TYPES[v.annotation]}") |
| 52 | + return ", ".join(inputs) |
| 53 | + |
| 54 | + def _output_bq_type(self): |
| 55 | + sig = inspect.signature(self._func) |
| 56 | + return _PYTHON_TO_BQ_TYPES[sig.return_annotation] |
| 57 | + |
| 58 | + def _create_udf(self): |
| 59 | + """Create Python UDF in BQ. Return name of the UDF.""" |
| 60 | + udf_name = str(self._session._loader._storage_manager._random_table()) |
| 61 | + |
| 62 | + func_body = inspect.getsource(self._func) |
| 63 | + func_name = self._func.__name__ |
| 64 | + packages = str(list(self._requirements)) |
| 65 | + |
| 66 | + sql = f""" |
| 67 | +CREATE OR REPLACE FUNCTION `{udf_name}`({self._input_bq_signature()}) |
| 68 | +RETURNS {self._output_bq_type()} LANGUAGE python |
| 69 | +WITH CONNECTION `{self._connection}` |
| 70 | +OPTIONS (entry_point='{func_name}', runtime_version='python-3.11', packages={packages}) |
| 71 | +AS r\"\"\" |
| 72 | +
|
| 73 | +
|
| 74 | +{func_body} |
| 75 | +
|
| 76 | +
|
| 77 | +\"\"\" |
| 78 | + """ |
| 79 | + |
| 80 | + bf_io_bigquery.start_query_with_client( |
| 81 | + self._session.bqclient, |
| 82 | + sql, |
| 83 | + job_config=bigquery.QueryJobConfig(), |
| 84 | + metrics=self._session._metrics, |
| 85 | + ) |
| 86 | + |
| 87 | + return udf_name |
| 88 | + |
| 89 | + def udf(self): |
| 90 | + """Create and return the UDF object.""" |
| 91 | + udf_name = self._create_udf() |
| 92 | + return self._session.read_gbq_function(udf_name) |
| 93 | + |
| 94 | + |
| 95 | +# Blur images. Takes ObjectRefRuntime as JSON string. Outputs ObjectRefRuntime JSON string. |
| 96 | +def image_blur_func( |
| 97 | + src_obj_ref_rt: str, dst_obj_ref_rt: str, ksize_x: int, ksize_y: int |
| 98 | +) -> str: |
| 99 | + import json |
| 100 | + |
| 101 | + import cv2 as cv # type: ignore |
| 102 | + import numpy as np |
| 103 | + import requests |
| 104 | + |
| 105 | + src_obj_ref_rt_json = json.loads(src_obj_ref_rt) |
| 106 | + dst_obj_ref_rt_json = json.loads(dst_obj_ref_rt) |
| 107 | + |
| 108 | + src_url = src_obj_ref_rt_json["access_urls"]["read_url"] |
| 109 | + dst_url = dst_obj_ref_rt_json["access_urls"]["write_url"] |
| 110 | + |
| 111 | + response = requests.get(src_url) |
| 112 | + bts = response.content |
| 113 | + |
| 114 | + nparr = np.frombuffer(bts, np.uint8) |
| 115 | + img = cv.imdecode(nparr, cv.IMREAD_UNCHANGED) |
| 116 | + img_blurred = cv.blur(img, ksize=(ksize_x, ksize_y)) |
| 117 | + bts = cv.imencode(".jpeg", img_blurred)[1].tobytes() |
| 118 | + |
| 119 | + requests.put( |
| 120 | + url=dst_url, |
| 121 | + data=bts, |
| 122 | + headers={ |
| 123 | + "Content-Type": "image/jpeg", |
| 124 | + }, |
| 125 | + ) |
| 126 | + |
| 127 | + return dst_obj_ref_rt |
| 128 | + |
| 129 | + |
| 130 | +image_blur_def = FunctionDef(image_blur_func, ["opencv-python", "numpy", "requests"]) |
0 commit comments