Get the label mapping from the model dir. This method will do: 1. Try to read label-id mapping from the label_mapping.json 2. Try to read label-id mapping from the configuration.json 3. Try to read label-id mapping from the config.json Args: model_dir: The local model d
(model_dir)
| 104 | |
| 105 | |
| 106 | def parse_label_mapping(model_dir): |
| 107 | """Get the label mapping from the model dir. |
| 108 | |
| 109 | This method will do: |
| 110 | 1. Try to read label-id mapping from the label_mapping.json |
| 111 | 2. Try to read label-id mapping from the configuration.json |
| 112 | 3. Try to read label-id mapping from the config.json |
| 113 | |
| 114 | Args: |
| 115 | model_dir: The local model dir to use. |
| 116 | |
| 117 | Returns: |
| 118 | The label2id mapping if found. |
| 119 | """ |
| 120 | import json |
| 121 | import os |
| 122 | label2id = None |
| 123 | label_path = os.path.join(model_dir, ModelFile.LABEL_MAPPING) |
| 124 | if os.path.exists(label_path): |
| 125 | with open(label_path, encoding='utf-8') as f: |
| 126 | label_mapping = json.load(f) |
| 127 | label2id = {name: idx for name, idx in label_mapping.items()} |
| 128 | |
| 129 | if label2id is None: |
| 130 | config_path = os.path.join(model_dir, ModelFile.CONFIGURATION) |
| 131 | config = Config.from_file(config_path) |
| 132 | if hasattr(config, ConfigFields.model) and hasattr( |
| 133 | config[ConfigFields.model], 'label2id'): |
| 134 | label2id = config[ConfigFields.model].label2id |
| 135 | elif hasattr(config, ConfigFields.model) and hasattr( |
| 136 | config[ConfigFields.model], 'id2label'): |
| 137 | id2label = config[ConfigFields.model].id2label |
| 138 | label2id = {label: id for id, label in id2label.items()} |
| 139 | elif hasattr(config, ConfigFields.preprocessor) and hasattr( |
| 140 | config[ConfigFields.preprocessor], 'label2id'): |
| 141 | label2id = config[ConfigFields.preprocessor].label2id |
| 142 | elif hasattr(config, ConfigFields.preprocessor) and hasattr( |
| 143 | config[ConfigFields.preprocessor], 'id2label'): |
| 144 | id2label = config[ConfigFields.preprocessor].id2label |
| 145 | label2id = {label: id for id, label in id2label.items()} |
| 146 | |
| 147 | config_path = os.path.join(model_dir, 'config.json') |
| 148 | if label2id is None and os.path.exists(config_path): |
| 149 | config = Config.from_file(config_path) |
| 150 | if hasattr(config, 'label2id'): |
| 151 | label2id = config.label2id |
| 152 | elif hasattr(config, 'id2label'): |
| 153 | id2label = config.id2label |
| 154 | label2id = {label: id for id, label in id2label.items()} |
| 155 | if label2id is not None: |
| 156 | label2id = {label: int(id) for label, id in label2id.items()} |
| 157 | return label2id |
no test coverage detected
searching dependent graphs…