|
| 1 | +import json |
| 2 | +import traceback |
| 3 | +import os |
| 4 | + |
| 5 | +from controller.transfer.record_transfer_manager import download_file |
| 6 | +from submodules.model import UploadTask, enums |
| 7 | +from submodules.model.business_objects import project, record |
| 8 | +from controller.upload_task import manager as task_manager |
| 9 | +from typing import Set, Dict, Any, Optional |
| 10 | + |
| 11 | + |
| 12 | +def prepare_label_studio_import(project_id: str, task: UploadTask) -> None: |
| 13 | + # pre init to ensure we can always append an error |
| 14 | + file_additional_info = __get_blank_file_additional_info() |
| 15 | + project_item = project.get(project_id) |
| 16 | + if not project_item: |
| 17 | + file_additional_info["errors"].append("Can't find project".format(e)) |
| 18 | + try: |
| 19 | + is_project_update = record.count(project_id) != 0 |
| 20 | + file_path = download_file(project_id, task) |
| 21 | + _, extension = os.path.splitext(file_path) |
| 22 | + if extension == ".json": |
| 23 | + with open(file_path) as file: |
| 24 | + data = json.load(file) |
| 25 | + analyze_file(data, file_additional_info, is_project_update) |
| 26 | + else: |
| 27 | + file_additional_info["errors"].append(f"Unsupported file type {extension}") |
| 28 | + except Exception as e: |
| 29 | + file_additional_info["errors"].append( |
| 30 | + "Error while analyzing file: {}".format(e) |
| 31 | + ) |
| 32 | + print(traceback.format_exc(), flush=True) |
| 33 | + dumped_info = json.dumps(file_additional_info) |
| 34 | + task_manager.update_task( |
| 35 | + project_id, |
| 36 | + task.id, |
| 37 | + state=enums.UploadStates.PREPARED.value, |
| 38 | + file_additional_info=dumped_info, |
| 39 | + ) |
| 40 | + |
| 41 | + |
| 42 | +def analyze_file( |
| 43 | + data: Dict[str, Any], file_additional_info: Dict[str, Any], is_project_update: bool |
| 44 | +) -> None: |
| 45 | + user_id_counts = {} |
| 46 | + tasks = set() |
| 47 | + record_count = 0 |
| 48 | + ex_no_kern_id = None |
| 49 | + ex_drafts = None |
| 50 | + ex_predictions = None |
| 51 | + ex_extraction = None |
| 52 | + ex_multiple_choices = None |
| 53 | + # multiple annotation for a user within the same record/task |
| 54 | + ex_multiple_annotations = None |
| 55 | + |
| 56 | + for record in data: |
| 57 | + if type(record) is not dict: |
| 58 | + file_additional_info["errors"].append("Import format not recognized") |
| 59 | + break |
| 60 | + record_count += 1 |
| 61 | + record_id = record["id"] |
| 62 | + if not ex_drafts and __check_record_has_values_for(record, "drafts"): |
| 63 | + ex_drafts = f"\n\tExample: record {record_id}" |
| 64 | + if not ex_predictions and __check_record_has_values_for(record, "predictions"): |
| 65 | + ex_predictions = f"\n\tExample: record {record_id}" |
| 66 | + if not ex_multiple_annotations and __check_record_has_multi_annotation(record): |
| 67 | + ex_multiple_annotations = f"\n\tExample: record {record_id}" |
| 68 | + if ( |
| 69 | + is_project_update |
| 70 | + and not ex_no_kern_id |
| 71 | + and not __check_record_has_values_for( |
| 72 | + record, "data", "kern_refinery_record_id" |
| 73 | + ) |
| 74 | + ): |
| 75 | + ex_no_kern_id = f"\n\tExample: record {record_id}" |
| 76 | + for annotation in record["annotations"]: |
| 77 | + annotation_id = annotation["id"] |
| 78 | + if not ex_extraction and __check_annotation_has_extraction(annotation): |
| 79 | + ex_extraction = ( |
| 80 | + f"\n\tExample: record {record_id} - annotation {annotation_id}" |
| 81 | + ) |
| 82 | + if not ex_multiple_choices and __check_annotation_has_multiclass( |
| 83 | + annotation |
| 84 | + ): |
| 85 | + ex_multiple_choices = ( |
| 86 | + f"\n\tExample: record {record_id} - annotation {annotation_id}" |
| 87 | + ) |
| 88 | + user_id = annotation["completed_by"] |
| 89 | + __add_annotation_target(annotation, tasks) |
| 90 | + |
| 91 | + if user_id in user_id_counts: |
| 92 | + user_id_counts[user_id] += 1 |
| 93 | + else: |
| 94 | + user_id_counts[user_id] = 1 |
| 95 | + |
| 96 | + if ex_drafts: |
| 97 | + file_additional_info["warnings"].append( |
| 98 | + "Label Studio drafts are not supported." + ex_drafts |
| 99 | + ) |
| 100 | + |
| 101 | + if ex_predictions: |
| 102 | + file_additional_info["warnings"].append( |
| 103 | + "Label Studio predictions are not supported." + ex_predictions |
| 104 | + ) |
| 105 | + |
| 106 | + if ex_extraction: |
| 107 | + file_additional_info["warnings"].append( |
| 108 | + "Named Entity Recognition / extraction labels are not supported.\nThese annotations will be ignored if you proceed." |
| 109 | + + ex_extraction |
| 110 | + ) |
| 111 | + if ex_multiple_choices: |
| 112 | + file_additional_info["warnings"].append( |
| 113 | + "Multiple choices for a result set are not supported.\nThese annotations will be ignored if you proceed." |
| 114 | + + ex_multiple_choices |
| 115 | + ) |
| 116 | + if ex_multiple_annotations: |
| 117 | + file_additional_info["errors"].append( |
| 118 | + "Multiple annotations for the same user within the same record\ntargeting the same task are not supported." |
| 119 | + + ex_multiple_annotations |
| 120 | + ) |
| 121 | + if ex_no_kern_id: |
| 122 | + file_additional_info["errors"].append( |
| 123 | + "Project update without kern record id. Can't update project (see restrictions)." |
| 124 | + + ex_multiple_annotations |
| 125 | + ) |
| 126 | + |
| 127 | + file_additional_info["user_ids"] = list(user_id_counts.keys()) |
| 128 | + file_additional_info["tasks"] = list(tasks) |
| 129 | + file_additional_info["file_info"]["records"] = record_count |
| 130 | + file_additional_info["file_info"]["annotations"] = user_id_counts |
| 131 | + |
| 132 | + |
| 133 | +def __add_annotation_target(annotation: Dict[str, Any], tasks: Set[str]) -> None: |
| 134 | + tasks |= __get_annotation_targets(annotation) |
| 135 | + |
| 136 | + |
| 137 | +def __get_annotation_targets(annotation: Dict[str, Any]) -> Set[str]: |
| 138 | + target = annotation.get("result") |
| 139 | + if target and len(target) > 0: |
| 140 | + return {t["from_name"] for t in target if "from_name" in t} |
| 141 | + return {} |
| 142 | + |
| 143 | + |
| 144 | +def __check_record_has_values_for( |
| 145 | + record: Dict[str, Any], key: str, sub_key: Optional[str] = None |
| 146 | +) -> bool: |
| 147 | + value = record.get(key) |
| 148 | + if value: |
| 149 | + if not sub_key: |
| 150 | + return True |
| 151 | + else: |
| 152 | + return __check_record_has_values_for(value, sub_key) |
| 153 | + return False |
| 154 | + |
| 155 | + |
| 156 | +def __check_record_has_multi_annotation(record: Dict[str, Any]) -> bool: |
| 157 | + annotations = record.get("annotations") |
| 158 | + if not annotations or len(annotations) < 2: |
| 159 | + return False |
| 160 | + lookup = {} |
| 161 | + for annotation in annotations: |
| 162 | + user_id = annotation.get("completed_by") |
| 163 | + if user_id not in lookup: |
| 164 | + lookup[user_id] = {} |
| 165 | + targets = __get_annotation_targets(annotation) |
| 166 | + for target in targets: |
| 167 | + if target not in lookup[user_id]: |
| 168 | + lookup[user_id][target] = 1 |
| 169 | + else: |
| 170 | + return True |
| 171 | + return False |
| 172 | + |
| 173 | + |
| 174 | +def __check_annotation_has_extraction(annotation: Dict[str, Any]) -> bool: |
| 175 | + results = annotation.get("result") |
| 176 | + if not results: |
| 177 | + return False |
| 178 | + for result in results: |
| 179 | + if result.get("type") != "choices": |
| 180 | + return True |
| 181 | + return False |
| 182 | + |
| 183 | + |
| 184 | +def __check_annotation_has_multiclass(annotation: Dict[str, Any]) -> bool: |
| 185 | + results = annotation.get("result") |
| 186 | + if not results: |
| 187 | + return False |
| 188 | + for result in results: |
| 189 | + if result.get("type") == "choices" and len(result["value"]["choices"]) > 1: |
| 190 | + return True |
| 191 | + return False |
| 192 | + |
| 193 | + |
| 194 | +def __get_blank_file_additional_info() -> Dict[str, Any]: |
| 195 | + return { |
| 196 | + "user_ids": [], |
| 197 | + "tasks": [], |
| 198 | + "errors": [], |
| 199 | + "warnings": [], |
| 200 | + "info": [], |
| 201 | + "file_info": {"records": 0, "annotations": {}}, |
| 202 | + } |
0 commit comments