|
| 1 | +import abc |
| 2 | +import inspect |
| 3 | +from typing import Any, Dict, List, Callable |
| 4 | + |
| 5 | +from starwhale.utils import console |
| 6 | +from starwhale.base.models.base import SwBaseModel |
| 7 | + |
| 8 | +Inputs = Any |
| 9 | +Outputs = Any |
| 10 | + |
| 11 | + |
| 12 | +class ComponentSpec(SwBaseModel): |
| 13 | + name: str |
| 14 | + type: str |
| 15 | + |
| 16 | + def __hash__(self) -> int: |
| 17 | + return hash((self.name, self.type)) |
| 18 | + |
| 19 | + |
| 20 | +class ServiceType(abc.ABC): |
| 21 | + """Protocol for service types.""" |
| 22 | + |
| 23 | + @property |
| 24 | + @abc.abstractmethod |
| 25 | + def arg_types(self) -> Dict[str, Any]: |
| 26 | + ... |
| 27 | + |
| 28 | + @property |
| 29 | + @abc.abstractmethod |
| 30 | + def name(self) -> str: |
| 31 | + ... |
| 32 | + |
| 33 | + def _validate_fn_with_arg_types(self, func: Callable) -> None: |
| 34 | + """Validate the function with the argument types.""" |
| 35 | + sig = inspect.signature(func) |
| 36 | + params = sig.parameters |
| 37 | + |
| 38 | + # check the type of each argument |
| 39 | + for name, param in params.items(): |
| 40 | + expected_type = self.arg_types[name] |
| 41 | + arg_type = param.annotation |
| 42 | + if arg_type is inspect.Parameter.empty: |
| 43 | + console.warn(f"Argument type {name} is not specified.") |
| 44 | + continue |
| 45 | + if arg_type is not expected_type: |
| 46 | + raise ValueError( |
| 47 | + f"Argument type {name} should be {expected_type}, not {arg_type}." |
| 48 | + ) |
| 49 | + |
| 50 | + def validate(self, value: Callable) -> None: |
| 51 | + """ |
| 52 | + Validate the service type |
| 53 | + The function should raise a ValueError if the function is not valid. |
| 54 | + :param value: the function to validate |
| 55 | + """ |
| 56 | + self._validate_fn_with_arg_types(value) |
| 57 | + |
| 58 | + @abc.abstractmethod |
| 59 | + def router_fn(self, func: Callable) -> Callable: |
| 60 | + ... |
| 61 | + |
| 62 | + @abc.abstractmethod |
| 63 | + def components_spec(self) -> List[ComponentSpec]: |
| 64 | + ... |
| 65 | + |
| 66 | + |
| 67 | +def all_components_are_gradio( |
| 68 | + inputs: Inputs, outputs: Outputs |
| 69 | +) -> bool: # pragma: no cover |
| 70 | + """Check if all components are Gradio components.""" |
| 71 | + if inputs is None and outputs is None: |
| 72 | + return False |
| 73 | + |
| 74 | + if not isinstance(inputs, list): |
| 75 | + inputs = inputs is not None and [inputs] or [] |
| 76 | + if not isinstance(outputs, list): |
| 77 | + outputs = outputs is not None and [outputs] or [] |
| 78 | + |
| 79 | + try: |
| 80 | + import gradio |
| 81 | + except ImportError: |
| 82 | + gradio = None |
| 83 | + |
| 84 | + return all( |
| 85 | + [ |
| 86 | + gradio is not None, |
| 87 | + all([isinstance(inp, gradio.components.Component) for inp in inputs]), |
| 88 | + all([isinstance(out, gradio.components.Component) for out in outputs]), |
| 89 | + ] |
| 90 | + ) |
0 commit comments