|
| 1 | +from dataclasses import is_dataclass, fields, MISSING |
| 2 | +from enum import Enum |
| 3 | +from typing import Type, Literal, Optional, Union, get_origin, get_args |
| 4 | + |
| 5 | + |
| 6 | +def get_option_definer(conf_cls: Type, conf_comment: dict): |
| 7 | + """ |
| 8 | + 生成配置选项字典, 将 py 数据类型转换为 json 可序列化的数据类型。 |
| 9 | +
|
| 10 | + Args: |
| 11 | + conf_cls (Type): 需要是 dataclass 或者有 to_options 方法。to_options 方法返回一个字典,结构与 options 相同。 |
| 12 | + conf_comment (dict): 配置字段的注释信息。 |
| 13 | +
|
| 14 | + Returns: |
| 15 | + dict: 配置选项字典。 |
| 16 | +
|
| 17 | + Raises: |
| 18 | + ValueError: 如果 conf_cls 不是 dataclass 且没有 to_options 方法。 |
| 19 | + """ |
| 20 | + has_method = hasattr(conf_cls, "to_options") and callable( |
| 21 | + getattr(conf_cls, "to_options") |
| 22 | + ) |
| 23 | + if has_method: |
| 24 | + return conf_cls.to_options() |
| 25 | + elif is_dataclass(conf_cls): |
| 26 | + _fields = fields(conf_cls) |
| 27 | + |
| 28 | + options = dict() |
| 29 | + |
| 30 | + for field in _fields: |
| 31 | + option_default = field.default |
| 32 | + if option_default is MISSING: |
| 33 | + option_default = None |
| 34 | + |
| 35 | + option_type = field.type |
| 36 | + required = True |
| 37 | + if field.name == "device": |
| 38 | + option_type = Literal["cuda", "cpu"] |
| 39 | + if isinstance(option_type, type): |
| 40 | + if issubclass(option_type, Enum): # type: ignore |
| 41 | + all_values = [option.value for option in option_type] |
| 42 | + option_type = all_values |
| 43 | + else: |
| 44 | + option_type = option_type.__name__ |
| 45 | + elif get_origin(option_type) is Union: |
| 46 | + option_type = "str" |
| 47 | + elif get_origin(option_type) is Literal: |
| 48 | + option_type = get_args(option_type) |
| 49 | + elif get_origin(option_type) is Optional: |
| 50 | + required = False |
| 51 | + option_type = get_args(option_type)[0] |
| 52 | + else: |
| 53 | + required = False |
| 54 | + option_type = "str" |
| 55 | + |
| 56 | + comment_dict = conf_comment.get(field.name, {}) |
| 57 | + description = comment_dict.get("description") |
| 58 | + range = comment_dict.get("range") |
| 59 | + comment = f"{description} {range}" if description else None |
| 60 | + options[field.name] = { |
| 61 | + "default": option_default, |
| 62 | + "type": option_type, |
| 63 | + "required": required, |
| 64 | + "comment": comment, |
| 65 | + } |
| 66 | + |
| 67 | + return options |
| 68 | + else: |
| 69 | + raise ValueError( |
| 70 | + f"{conf_cls.__name__} should be a dataclass or have a to_options method." |
| 71 | + ) |
0 commit comments