Untitled
unknown
plain_text
a year ago
2.9 kB
3
Indexable
Never
def task(**kwargs): try: task_id = kwargs['task_id'] input_images_url = f"{TASKS_SERVER_URL}/api/task/{task_id}/node/cropping/file/cropped.nii.gz" # input_images_url = kwargs['input_images_url'] output_file_url = f"{TASKS_SERVER_URL}/api/task/{task_id}/node/preprocessing/file" # output_file_url = kwargs['output_images_url'] except KeyError as err: logging.error(f'KeyError: {err}') return False # download input images and save to tempdir try: tempdir = tempfile.TemporaryDirectory() res = requests.get(input_images_url) res.raise_for_status() with open(os.path.join(tempdir.name, 'input_images.nii.gz'), 'wb') as f: f.write(res.content) input_images_path = os.path.join(tempdir.name, 'input_images.nii.gz') except requests.exceptions.HTTPError as err: logging.error(f'HTTPError: {err}') return False logging.info("start preprocessing on %s",datetime.datetime.now().isoformat()) # preprocess images try: config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'liver_duplicate_nnunet_config.json') if not os.path.exists(config_file): raise FileNotFoundError(f'Config file {config_file} not found') liver_preprocessing = LiverPreprocessing(config_file) preprocessed = liver_preprocessing([input_images_path,input_images_path]) except Exception as err: logging.error(f'Error: {err}') return False logging.info("end preprocessing%s",datetime.datetime.now().isoformat()) # save preprocessed images to tempdir try: preprocessed_data_path = os.path.join(tempdir.name, 'preprocessed.npy') np.save(preprocessed_data_path, preprocessed['data']) preprocessed_properties_path = os.path.join(tempdir.name, 'preprocessed_properties.json') with open(preprocessed_properties_path, 'w') as f: json.dump(preprocessed['data_properites'], f) except Exception as err: logging.error(f'Error: {err}') return False # upload preprocessed output try: with open(preprocessed_data_path, 'rb') as f: res = requests.post( output_file_url, files={'filename': (None, 'preprocessed.npy'),'file': f} ) res.raise_for_status() with open(preprocessed_properties_path, 'rb') as f: res = requests.post( output_file_url, files={'filename': (None, 'preprocessed_properties.json'),'file': f} ) res.raise_for_status() except requests.exceptions.HTTPError as err: logging.error(f'HTTPError: {err}') return False tempdir.cleanup() return True