shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1944120983


##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# 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 annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
+    "EnsembleAnomalyDetector",
+    "AnomalyDetector",
+    "ThresholdFn",
+    "AggregationFn",
+    "*"
+]
+KNOWN_SPECIFIABLE = {"*": {}}
+
+SpecT = TypeVar('SpecT', bound='Specifiable')
+
+
+def get_subspace(cls, type=None):
+  if type is None:
+    subspace = "*"
+    for c in cls.mro():
+      if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+        subspace = c.__name__
+        break
+    return subspace
+  else:
+    for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
+      if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
+        return subspace
+    raise ValueError(f"subspace for {cls.__name__} not found.")
+
+
[email protected](frozen=True)
+class Spec():
+  type: str
+  config: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+
+@runtime_checkable
+class Specifiable(Protocol):
+  _key: ClassVar[str]
+  _init_params: dict[str, Any]
+
+  @staticmethod
+  def _from_spec_helper(v):
+    if isinstance(v, Spec):
+      return Specifiable.from_spec(v)
+
+    if isinstance(v, List):
+      return [Specifiable._from_spec_helper(e) for e in v]
+
+    return v
+
+  @classmethod
+  def from_spec(cls, spec: Spec) -> Self:
+    if spec.type is None:
+      raise ValueError(f"Spec type not found in {spec}")
+
+    subspace = get_subspace(cls, spec.type)
+    subclass: Type[Self] = KNOWN_SPECIFIABLE[subspace].get(spec.type, None)
+    if subclass is None:
+      raise ValueError(f"Unknown spec type '{spec.type}' in {spec}")
+
+    args = {k: Specifiable._from_spec_helper(v) for k, v in 
spec.config.items()}
+
+    return subclass(**args)
+
+  @staticmethod
+  def _to_spec_helper(v):
+    if isinstance(v, Specifiable):
+      return v.to_spec()
+
+    if isinstance(v, List):
+      return [Specifiable._to_spec_helper(e) for e in v]
+
+    return v
+
+  def to_spec(self) -> Spec:
+    if getattr(type(self), '_key', None) is None:
+      raise ValueError(
+          f"'{type(self).__name__}' not registered as Specifiable. "
+          f"Decorate ({type(self).__name__}) with @specifiable")
+
+    args = {k: self._to_spec_helper(v) for k, v in self._init_params.items()}
+
+    return Spec(type=self.__class__._key, config=args)
+
+
+def register(cls, key, error_if_exists) -> None:
+  if key is None:
+    key = cls.__name__
+
+  subspace = get_subspace(cls)
+  if subspace in KNOWN_SPECIFIABLE and key in KNOWN_SPECIFIABLE[
+      subspace] and error_if_exists:
+    raise ValueError(f"{key} is already registered for specifiable")
+
+  if subspace not in KNOWN_SPECIFIABLE:
+    KNOWN_SPECIFIABLE[subspace] = {}
+  KNOWN_SPECIFIABLE[subspace][key] = cls
+
+  cls._key = key
+
+
+def track_init_params(inst, init_method, *args, **kwargs):
+  params = dict(
+      zip(inspect.signature(init_method).parameters.keys(), (None, ) + args))
+  del params['self']
+  params.update(**kwargs)
+  inst._init_params = params
+
+
+def specifiable(
+    my_cls=None,
+    /,
+    *,
+    key=None,
+    error_if_exists=True,
+    on_demand_init=True,
+    just_in_time_init=True):

Review Comment:
   I added some more comments. PTAL.



##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# 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 annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
+    "EnsembleAnomalyDetector",
+    "AnomalyDetector",
+    "ThresholdFn",
+    "AggregationFn",
+    "*"
+]
+KNOWN_SPECIFIABLE = {"*": {}}
+
+SpecT = TypeVar('SpecT', bound='Specifiable')
+
+
+def get_subspace(cls, type=None):
+  if type is None:
+    subspace = "*"
+    for c in cls.mro():
+      if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+        subspace = c.__name__
+        break
+    return subspace
+  else:
+    for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
+      if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
+        return subspace
+    raise ValueError(f"subspace for {cls.__name__} not found.")
+
+
[email protected](frozen=True)
+class Spec():
+  type: str
+  config: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+
+@runtime_checkable
+class Specifiable(Protocol):
+  _key: ClassVar[str]
+  _init_params: dict[str, Any]
+
+  @staticmethod
+  def _from_spec_helper(v):
+    if isinstance(v, Spec):
+      return Specifiable.from_spec(v)
+
+    if isinstance(v, List):
+      return [Specifiable._from_spec_helper(e) for e in v]
+
+    return v
+
+  @classmethod
+  def from_spec(cls, spec: Spec) -> Self:
+    if spec.type is None:
+      raise ValueError(f"Spec type not found in {spec}")
+
+    subspace = get_subspace(cls, spec.type)
+    subclass: Type[Self] = KNOWN_SPECIFIABLE[subspace].get(spec.type, None)
+    if subclass is None:
+      raise ValueError(f"Unknown spec type '{spec.type}' in {spec}")
+
+    args = {k: Specifiable._from_spec_helper(v) for k, v in 
spec.config.items()}
+
+    return subclass(**args)
+
+  @staticmethod
+  def _to_spec_helper(v):
+    if isinstance(v, Specifiable):
+      return v.to_spec()
+
+    if isinstance(v, List):
+      return [Specifiable._to_spec_helper(e) for e in v]
+
+    return v
+
+  def to_spec(self) -> Spec:
+    if getattr(type(self), '_key', None) is None:
+      raise ValueError(
+          f"'{type(self).__name__}' not registered as Specifiable. "
+          f"Decorate ({type(self).__name__}) with @specifiable")
+
+    args = {k: self._to_spec_helper(v) for k, v in self._init_params.items()}
+
+    return Spec(type=self.__class__._key, config=args)
+
+
+def register(cls, key, error_if_exists) -> None:
+  if key is None:
+    key = cls.__name__
+
+  subspace = get_subspace(cls)
+  if subspace in KNOWN_SPECIFIABLE and key in KNOWN_SPECIFIABLE[
+      subspace] and error_if_exists:
+    raise ValueError(f"{key} is already registered for specifiable")
+
+  if subspace not in KNOWN_SPECIFIABLE:
+    KNOWN_SPECIFIABLE[subspace] = {}
+  KNOWN_SPECIFIABLE[subspace][key] = cls
+
+  cls._key = key
+
+
+def track_init_params(inst, init_method, *args, **kwargs):
+  params = dict(
+      zip(inspect.signature(init_method).parameters.keys(), (None, ) + args))
+  del params['self']
+  params.update(**kwargs)
+  inst._init_params = params

Review Comment:
   Sure.



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