datamint 2.48.0__tar.gz → 2.50.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. {datamint-2.48.0 → datamint-2.50.0}/PKG-INFO +1 -1
  2. {datamint-2.48.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_download.py +15 -4
  3. {datamint-2.48.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_import.py +35 -32
  4. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/geometry.py +99 -0
  5. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/resource.py +36 -0
  6. {datamint-2.48.0 → datamint-2.50.0}/datamint/importers/__init__.py +2 -0
  7. datamint-2.50.0/datamint/importers/_common.py +204 -0
  8. {datamint-2.48.0 → datamint-2.50.0}/datamint/importers/coco.py +30 -5
  9. {datamint-2.48.0 → datamint-2.50.0}/datamint/importers/pascal_voc.py +41 -12
  10. {datamint-2.48.0 → datamint-2.50.0}/datamint/importers/yolo.py +34 -19
  11. datamint-2.50.0/datamint/utils/visualization.py +382 -0
  12. {datamint-2.48.0 → datamint-2.50.0}/pyproject.toml +1 -1
  13. datamint-2.48.0/datamint/importers/_common.py +0 -99
  14. datamint-2.48.0/datamint/utils/visualization.py +0 -159
  15. {datamint-2.48.0 → datamint-2.50.0}/README.md +0 -0
  16. {datamint-2.48.0 → datamint-2.50.0}/datamint/__init__.py +0 -0
  17. {datamint-2.48.0 → datamint-2.50.0}/datamint/__main__.py +0 -0
  18. {datamint-2.48.0 → datamint-2.50.0}/datamint/_repr_utils.py +0 -0
  19. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/__init__.py +0 -0
  20. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/base_api.py +0 -0
  21. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/client.py +0 -0
  22. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/dto/__init__.py +0 -0
  23. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/dto/annotation_dto.py +0 -0
  24. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/dto/inference_prompts.py +0 -0
  25. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/dto/save_results_options.py +0 -0
  26. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/endpoints/__init__.py +0 -0
  27. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/endpoints/annotations_api.py +0 -0
  28. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/endpoints/annotationsets_api.py +0 -0
  29. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/endpoints/datasetsinfo_api.py +0 -0
  30. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/endpoints/deploy_model_api.py +0 -0
  31. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/endpoints/inference_api.py +0 -0
  32. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/endpoints/model_types.py +0 -0
  33. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/endpoints/models_api.py +0 -0
  34. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/endpoints/pod_logs_api.py +0 -0
  35. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/endpoints/projects_api.py +0 -0
  36. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/endpoints/resources_api.py +0 -0
  37. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/endpoints/users_api.py +0 -0
  38. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/endpoints/validation_studies_api.py +0 -0
  39. {datamint-2.48.0 → datamint-2.50.0}/datamint/api/entity_base_api.py +0 -0
  40. {datamint-2.48.0 → datamint-2.50.0}/datamint/client_cmd_tools/__init__.py +0 -0
  41. {datamint-2.48.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_config.py +0 -0
  42. {datamint-2.48.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_example.py +0 -0
  43. {datamint-2.48.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_inference.py +0 -0
  44. {datamint-2.48.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_init.py +0 -0
  45. {datamint-2.48.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_train.py +0 -0
  46. {datamint-2.48.0 → datamint-2.50.0}/datamint/client_cmd_tools/datamint_upload.py +0 -0
  47. {datamint-2.48.0 → datamint-2.50.0}/datamint/configs.py +0 -0
  48. {datamint-2.48.0 → datamint-2.50.0}/datamint/dataset/__init__.py +0 -0
  49. {datamint-2.48.0 → datamint-2.50.0}/datamint/dataset/annotation_processor.py +0 -0
  50. {datamint-2.48.0 → datamint-2.50.0}/datamint/dataset/base.py +0 -0
  51. {datamint-2.48.0 → datamint-2.50.0}/datamint/dataset/factory.py +0 -0
  52. {datamint-2.48.0 → datamint-2.50.0}/datamint/dataset/image_dataset.py +0 -0
  53. {datamint-2.48.0 → datamint-2.50.0}/datamint/dataset/multiframe_dataset.py +0 -0
  54. {datamint-2.48.0 → datamint-2.50.0}/datamint/dataset/sliced_dataset.py +0 -0
  55. {datamint-2.48.0 → datamint-2.50.0}/datamint/dataset/sliced_video_dataset.py +0 -0
  56. {datamint-2.48.0 → datamint-2.50.0}/datamint/dataset/split_result.py +0 -0
  57. {datamint-2.48.0 → datamint-2.50.0}/datamint/dataset/video_dataset.py +0 -0
  58. {datamint-2.48.0 → datamint-2.50.0}/datamint/dataset/volume_dataset.py +0 -0
  59. {datamint-2.48.0 → datamint-2.50.0}/datamint/default_project.py +0 -0
  60. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/__init__.py +0 -0
  61. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotation_worklist.py +0 -0
  62. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/__init__.py +0 -0
  63. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/annotation.py +0 -0
  64. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/annotation_spec.py +0 -0
  65. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/base_geometry.py +0 -0
  66. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/base_segmentation.py +0 -0
  67. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/box_annotation.py +0 -0
  68. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/category_annotation.py +0 -0
  69. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/image_classification.py +0 -0
  70. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/image_segmentation.py +0 -0
  71. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/label_annotation.py +0 -0
  72. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/line_annotation.py +0 -0
  73. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/numeric_annotation.py +0 -0
  74. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/point_annotation.py +0 -0
  75. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/region_annotation.py +0 -0
  76. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/text_annotation.py +0 -0
  77. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/types.py +0 -0
  78. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/annotations/volume_segmentation.py +0 -0
  79. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/base_entity.py +0 -0
  80. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/buildlog.py +0 -0
  81. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/cache_manager.py +0 -0
  82. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/channel.py +0 -0
  83. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/datasetinfo.py +0 -0
  84. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/deployjob.py +0 -0
  85. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/inferencejob.py +0 -0
  86. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/pod.py +0 -0
  87. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/project.py +0 -0
  88. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/project_resource_split.py +0 -0
  89. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/resources/__init__.py +0 -0
  90. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/resources/dicom_resource.py +0 -0
  91. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/resources/image_resource.py +0 -0
  92. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/resources/nifti_resource.py +0 -0
  93. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/resources/video_resource.py +0 -0
  94. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/resources/volume_resource.py +0 -0
  95. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/sliced_resource.py +0 -0
  96. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/sliced_resource_base.py +0 -0
  97. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/sliced_video_resource.py +0 -0
  98. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/user.py +0 -0
  99. {datamint-2.48.0 → datamint-2.50.0}/datamint/entities/validation_study.py +0 -0
  100. {datamint-2.48.0 → datamint-2.50.0}/datamint/evaluate/__init__.py +0 -0
  101. {datamint-2.48.0 → datamint-2.50.0}/datamint/evaluate/evaluator.py +0 -0
  102. {datamint-2.48.0 → datamint-2.50.0}/datamint/evaluate/metrics/__init__.py +0 -0
  103. {datamint-2.48.0 → datamint-2.50.0}/datamint/evaluate/metrics/classification.py +0 -0
  104. {datamint-2.48.0 → datamint-2.50.0}/datamint/evaluate/metrics/detection.py +0 -0
  105. {datamint-2.48.0 → datamint-2.50.0}/datamint/evaluate/metrics/segmentation.py +0 -0
  106. {datamint-2.48.0 → datamint-2.50.0}/datamint/examples/__init__.py +0 -0
  107. {datamint-2.48.0 → datamint-2.50.0}/datamint/examples/_common.py +0 -0
  108. {datamint-2.48.0 → datamint-2.50.0}/datamint/examples/_download.py +0 -0
  109. {datamint-2.48.0 → datamint-2.50.0}/datamint/examples/bccd_dataset.py +0 -0
  110. {datamint-2.48.0 → datamint-2.50.0}/datamint/examples/busi_dataset.py +0 -0
  111. {datamint-2.48.0 → datamint-2.50.0}/datamint/examples/example_projects.py +0 -0
  112. {datamint-2.48.0 → datamint-2.50.0}/datamint/examples/fracatlas_dataset.py +0 -0
  113. {datamint-2.48.0 → datamint-2.50.0}/datamint/examples/synapse_dataset.py +0 -0
  114. {datamint-2.48.0 → datamint-2.50.0}/datamint/exceptions.py +0 -0
  115. {datamint-2.48.0 → datamint-2.50.0}/datamint/importers/_detect.py +0 -0
  116. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/__init__.py +0 -0
  117. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/benchmark.py +0 -0
  118. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/datamodule.py +0 -0
  119. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/__init__.py +0 -0
  120. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/base_trainer.py +0 -0
  121. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/classification_trainer.py +0 -0
  122. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/detection_trainer.py +0 -0
  123. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/__init__.py +0 -0
  124. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/base.py +0 -0
  125. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/classification_module.py +0 -0
  126. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/detection_modules/__init__.py +0 -0
  127. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/detection_modules/yolox_module.py +0 -0
  128. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/segmentation_module.py +0 -0
  129. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/__init__.py +0 -0
  130. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/deeplabv3plus.py +0 -0
  131. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/smp_module.py +0 -0
  132. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/transunet.py +0 -0
  133. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/unetpp.py +0 -0
  134. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/unetrpp.py +0 -0
  135. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/seg2d_trainer.py +0 -0
  136. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/seg3d_trainer.py +0 -0
  137. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/segmentation_trainer.py +0 -0
  138. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/__init__.py +0 -0
  139. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/deeplabv3plus.py +0 -0
  140. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/efficientnetv2.py +0 -0
  141. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/nnunet/__init__.py +0 -0
  142. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/nnunet/_nnunet_trainer_bridge.py +0 -0
  143. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/nnunet/data_export.py +0 -0
  144. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/nnunet/data_import.py +0 -0
  145. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/nnunet/inference_model.py +0 -0
  146. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/nnunet/trainer.py +0 -0
  147. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/transunet.py +0 -0
  148. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/unetpp.py +0 -0
  149. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/unetrpp.py +0 -0
  150. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/specialized/yolox.py +0 -0
  151. {datamint-2.48.0 → datamint-2.50.0}/datamint/lightning/trainers/vol_seg_trainer.py +0 -0
  152. {datamint-2.48.0 → datamint-2.50.0}/datamint/logging.yaml +0 -0
  153. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/__init__.py +0 -0
  154. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/artifact/__init__.py +0 -0
  155. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/artifact/datamint_artifacts_repo.py +0 -0
  156. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/data/__init__.py +0 -0
  157. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/data/datamint_dataset.py +0 -0
  158. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/env_utils.py +0 -0
  159. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/env_vars.py +0 -0
  160. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/flavors/__init__.py +0 -0
  161. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/flavors/annotation_specs.py +0 -0
  162. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/flavors/datamint_flavor.py +0 -0
  163. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/flavors/model.py +0 -0
  164. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/flavors/model_loader.py +0 -0
  165. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/flavors/model_parser.py +0 -0
  166. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/flavors/prediction_modes.py +0 -0
  167. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/flavors/prediction_router.py +0 -0
  168. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/flavors/task_type.py +0 -0
  169. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/flavors/validation.py +0 -0
  170. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/lightning/callbacks/__init__.py +0 -0
  171. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/lightning/callbacks/modelcheckpoint.py +0 -0
  172. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/models/Dockerfile.template +0 -0
  173. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/models/__init__.py +0 -0
  174. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/models/datamint_model_store.py +0 -0
  175. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/models/docker_build.py +0 -0
  176. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/models/local_inference.py +0 -0
  177. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/models/serve.py +0 -0
  178. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/models/tags.py +0 -0
  179. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/store_utils.py +0 -0
  180. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/tracking/datamint_store.py +0 -0
  181. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/tracking/default_experiment.py +0 -0
  182. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/tracking/fluent.py +0 -0
  183. {datamint-2.48.0 → datamint-2.50.0}/datamint/mlflow/tracking/offline_buffer.py +0 -0
  184. {datamint-2.48.0 → datamint-2.50.0}/datamint/types.py +0 -0
  185. {datamint-2.48.0 → datamint-2.50.0}/datamint/utils/annotation_agreement.py +0 -0
  186. {datamint-2.48.0 → datamint-2.50.0}/datamint/utils/collection_utils.py +0 -0
  187. {datamint-2.48.0 → datamint-2.50.0}/datamint/utils/date_utils.py +0 -0
  188. {datamint-2.48.0 → datamint-2.50.0}/datamint/utils/env.py +0 -0
  189. {datamint-2.48.0 → datamint-2.50.0}/datamint/utils/logging_utils.py +0 -0
  190. {datamint-2.48.0 → datamint-2.50.0}/datamint/utils/nifti_utils.py +0 -0
  191. {datamint-2.48.0 → datamint-2.50.0}/datamint/utils/torchmetrics.py +0 -0
  192. {datamint-2.48.0 → datamint-2.50.0}/datamint/utils/uncertainty.py +0 -0
  193. {datamint-2.48.0 → datamint-2.50.0}/datamint/utils/urls.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: datamint
3
- Version: 2.48.0
3
+ Version: 2.50.0
4
4
  Summary: A library for interacting with the Datamint API, designed for efficient data management, processing and Deep Learning workflows.
5
5
  Keywords: medical-imaging,dicom,nifti,pytorch,mlflow,lightning,datasets,annotation
6
6
  Author: SonanceAI
@@ -24,8 +24,9 @@ def _build_parser(subparsers: argparse._SubParsersAction | None = None) -> argpa
24
24
  'description': "Download and cache a Datamint project's dataset locally.",
25
25
  'epilog': """
26
26
  Examples:
27
- datamint download --project MyProject # cache the dataset locally
28
- datamint download --project MyProject -o ./my_data_folder # also create a browsable view
27
+ datamint download MyProject # cache the dataset locally
28
+ datamint download MyProject -o ./my_data_folder # also create a browsable view
29
+ datamint download --project MyProject # same as the first, using the --project flag
29
30
 
30
31
  More Documentation: https://sonanceai.github.io/datamint-python-api/command_line_tools.html
31
32
  """,
@@ -35,8 +36,11 @@ More Documentation: https://sonanceai.github.io/datamint-python-api/command_line
35
36
  parser = subparsers.add_parser('download', **kwargs)
36
37
  else:
37
38
  parser = argparse.ArgumentParser(**kwargs)
38
- parser.add_argument('--project', type=str, required=True,
39
+ parser.add_argument('project', nargs='?', metavar='PROJECT',
39
40
  help='Name of the Datamint project to download.')
41
+ # --project option also works
42
+ parser.add_argument('--project', dest='project_flag', type=str, metavar='PROJECT',
43
+ help='Name of the Datamint project.')
40
44
  parser.add_argument('-o', '--output', type=str, default=None,
41
45
  help='Optional folder for a browsable view of the downloaded files '
42
46
  '(symlinks into the SDK cache; requires symlink support).')
@@ -49,7 +53,14 @@ def _parse_args() -> argparse.Namespace:
49
53
  parser = _build_parser()
50
54
  import argcomplete
51
55
  argcomplete.autocomplete(parser)
52
- return parser.parse_args()
56
+ args = parser.parse_args()
57
+
58
+ if args.project is not None and args.project_flag is not None:
59
+ parser.error("Both positional project and --project flag provided. Use only one.")
60
+ args.project = args.project or args.project_flag
61
+ if args.project is None:
62
+ parser.error("Project name is required. Provide it as a positional argument or use --project flag.")
63
+ return args
53
64
 
54
65
 
55
66
  def _export_view(resources, output_dir: Path) -> None:
@@ -16,7 +16,9 @@ from datamint.importers import (
16
16
  DatasetFormat,
17
17
  PascalVOCImporter,
18
18
  YOLOImporter,
19
+ build_report,
19
20
  detect_format,
21
+ format_report,
20
22
  sniff_single_format,
21
23
  )
22
24
  from datamint.utils.logging_utils import load_cmdline_logging_config
@@ -56,7 +58,7 @@ def _build_parser(subparsers: argparse._SubParsersAction | None = None) -> argpa
56
58
  Examples:
57
59
  datamint import ./my_coco_dataset --project MyProject # auto-detect the format
58
60
  datamint import ./my_yolo_dataset --project MyProject --format yolo
59
- datamint import ./voc_dataset --project MyProject --dry-run # preview without uploading
61
+ datamint import ./voc_dataset --dry-run # preview without uploading
60
62
 
61
63
  More Documentation: https://sonanceai.github.io/datamint-python-api/command_line_tools.html
62
64
  """,
@@ -68,8 +70,9 @@ More Documentation: https://sonanceai.github.io/datamint-python-api/command_line
68
70
  parser = argparse.ArgumentParser(**kwargs)
69
71
 
70
72
  parser.add_argument('path', type=str, metavar='PATH', help='Root directory of the labeled dataset.')
71
- parser.add_argument('--project', type=str, required=True,
72
- help='Name of the Datamint project to import into. Created if it does not exist yet.')
73
+ parser.add_argument('--project', type=str, required=False,
74
+ help='Name of the Datamint project to import into. Created if it does not exist yet. '
75
+ 'Required unless --dry-run is given.')
73
76
  parser.add_argument('--format', type=str, choices=sorted(_IMPORTER_CLASSES),
74
77
  help='Annotation format. If omitted, the format is auto-detected from PATH.')
75
78
 
@@ -92,9 +95,10 @@ More Documentation: https://sonanceai.github.io/datamint-python-api/command_line
92
95
  parser.add_argument('--on-error', type=str, choices=('raise', 'skip'), default='raise',
93
96
  help='Whether to stop or skip past a single resource/annotation upload failure.')
94
97
  parser.add_argument('--dry-run', action='store_true', default=False,
95
- help='Parse and print a summary, but do not create the project or upload anything.')
98
+ help='Parse and print the report, but do not create the project or upload anything.')
96
99
  parser.add_argument('--yes', action='store_true', default=False,
97
- help='Skip the auto-detected-format confirmation prompt.')
100
+ help='Skip the confirmation prompt shown after the report when the format was '
101
+ 'auto-detected or issues were found.')
98
102
  parser.add_argument('--verbose', action='store_true', default=False, help='Print debug messages.')
99
103
 
100
104
  return parser
@@ -104,13 +108,16 @@ def _parse_args() -> argparse.Namespace:
104
108
  parser = _build_parser()
105
109
  import argcomplete
106
110
  argcomplete.autocomplete(parser)
107
- return parser.parse_args()
111
+ args = parser.parse_args()
112
+ if args.project is None and not args.dry_run:
113
+ parser.error('--project is required unless --dry-run is given.')
114
+ return args
108
115
 
109
116
 
110
- def _resolve_dataset(args: argparse.Namespace) -> tuple[DatasetFormat, dict]:
117
+ def _resolve_dataset(args: argparse.Namespace) -> tuple[DatasetFormat, dict, bool]:
111
118
  """Figure out the format + importer constructor kwargs, applying CLI overrides.
112
119
 
113
- Prompts for confirmation when the format was auto-detected (unless ``--yes``).
120
+ Returns ``(format, importer_kwargs, auto_detected)``.
114
121
  Raises ``DatamintException`` when the format/paths can't be resolved.
115
122
  """
116
123
  path = Path(args.path)
@@ -130,17 +137,6 @@ def _resolve_dataset(args: argparse.Namespace) -> tuple[DatasetFormat, dict]:
130
137
  fmt = detected.format
131
138
  base_kwargs = dict(detected.importer_kwargs)
132
139
 
133
- _USER_LOGGER.info(f"Detected a {fmt.upper()} dataset under '{path}':")
134
- for key, value in base_kwargs.items():
135
- for v in (value if isinstance(value, list) else [value]):
136
- _USER_LOGGER.info(f' {key}: {v}')
137
- if not args.yes:
138
- answer = input(f'Import as {fmt.upper()}? (y/n): ')
139
- if answer.strip().lower() != 'y':
140
- raise DatamintException(
141
- 'Aborted. Re-run with --format to choose a different format explicitly.'
142
- )
143
-
144
140
  overrides = {
145
141
  'annotations_file': args.annotations_file,
146
142
  'annotations_dir': args.annotations_dir,
@@ -171,7 +167,7 @@ def _resolve_dataset(args: argparse.Namespace) -> tuple[DatasetFormat, dict]:
171
167
  '--images-dir or --labels-dir is ambiguous. Pass both --images-dir and --labels-dir.'
172
168
  )
173
169
 
174
- return fmt, base_kwargs
170
+ return fmt, base_kwargs, args.format is None
175
171
 
176
172
 
177
173
  def main() -> None:
@@ -190,25 +186,32 @@ def main() -> None:
190
186
  if not path.is_dir():
191
187
  raise DatamintException(f"'{path}' is not a directory.")
192
188
 
193
- fmt, importer_kwargs = _resolve_dataset(args)
189
+ fmt, importer_kwargs, auto_detected = _resolve_dataset(args)
194
190
  importer = _IMPORTER_CLASSES[fmt](**importer_kwargs)
195
191
 
196
- result = importer.parse()
197
- _USER_LOGGER.info(
198
- f'Parsed {result.num_images} image(s), {result.num_boxes} box(es), '
199
- f'{len(result.class_names)} class(es): {result.class_names}'
200
- )
201
- if result.missing_images:
202
- _USER_LOGGER.warning(f'{len(result.missing_images)} referenced image(s) not found on disk.')
203
- if result.unsupported_annotations:
204
- _USER_LOGGER.warning(
205
- f'{result.unsupported_annotations} annotation(s) use an unsupported type and will be skipped.'
206
- )
192
+ try:
193
+ result = importer.parse()
194
+ except ValueError as e:
195
+ raise DatamintException(f'Could not parse the {fmt.upper()} dataset: {e}') from e
196
+
197
+ rows = build_report(fmt, result,
198
+ detected=auto_detected,
199
+ paths=importer_kwargs,
200
+ project=args.project,
201
+ dry_run=args.dry_run)
202
+ _USER_LOGGER.info(format_report(rows))
207
203
 
208
204
  if args.dry_run:
209
205
  _USER_LOGGER.info('Dry run: nothing was uploaded.')
210
206
  return
211
207
 
208
+ has_issues = bool(result.issues or result.missing_images or result.unsupported_annotations)
209
+ if not args.yes and (auto_detected or has_issues):
210
+ answer = input('Proceed? (y/n): ')
211
+ if answer.strip().lower() != 'y':
212
+ hint = ' Re-run with --format to choose a different format explicitly.' if auto_detected else ''
213
+ raise DatamintException(f'Aborted.{hint}')
214
+
212
215
  api_key = handle_api_key()
213
216
  if api_key is None:
214
217
  _USER_LOGGER.error('API key not provided. Aborting.')
@@ -10,6 +10,7 @@ from medimgkit import ViewPlane, dicom_utils, nifti_utils
10
10
  from medimgkit.dicom_utils import get_slice_orientation
11
11
  from nibabel.nifti1 import Nifti1Image
12
12
  from pydantic import BaseModel, ConfigDict, field_validator
13
+ from typing_extensions import Self
13
14
 
14
15
  CoordinateSystem: TypeAlias = Literal['pixel', 'patient']
15
16
  Point3D: TypeAlias = tuple[int | float, int | float, int | float]
@@ -97,6 +98,31 @@ def _pixel_to_patient_point(
97
98
  raise TypeError(f'Unsupported metadata type: {type(metadata)}')
98
99
 
99
100
 
101
+ def _patient_to_pixel_points(
102
+ points: Sequence[Point3D],
103
+ *,
104
+ slice_plane: ViewPlane | None = None,
105
+ metadata: pydicom.Dataset | Nifti1Image,
106
+ ) -> np.ndarray:
107
+ """(P, 3) patient points -> (P, 3) pixel points (x, y, slice index) on ``slice_plane``.
108
+
109
+ Inverts ``_pixel_to_patient_point``, so both directions follow the same convention.
110
+ """
111
+ origin, right, down = (
112
+ np.asarray(_pixel_to_patient_point(p, frame_index=0, slice_plane=slice_plane, metadata=metadata), dtype=float)
113
+ for p in [(0, 0), (1, 0), (0, 1)]
114
+ )
115
+ dx = right - origin
116
+ dy = down - origin
117
+ try:
118
+ next_slice = _pixel_to_patient_point((0, 0), frame_index=1, slice_plane=slice_plane, metadata=metadata)
119
+ dz = np.asarray(next_slice, dtype=float) - origin
120
+ except Exception:
121
+ dz = np.cross(dx, dy) # single slice
122
+ inv = np.linalg.inv(np.column_stack([dx, dy, dz]))
123
+ return (np.asarray(points, dtype=float) - origin) @ inv.T
124
+
125
+
100
126
  def _normalize_vector(vector: np.ndarray | list | tuple | None) -> Vector3D | None:
101
127
  if vector is None:
102
128
  return None
@@ -121,10 +147,40 @@ class Geometry(BaseModel):
121
147
  model_config = ConfigDict(arbitrary_types_allowed=True, extra='ignore')
122
148
 
123
149
  type: ClassVar[str]
150
+ points: tuple[Point3D, ...]
124
151
  viewPlaneNormal: Vector3D | None = None
125
152
  viewUp: Vector3D | None = None
126
153
  coordinate_system: CoordinateSystem = 'patient'
127
154
 
155
+ def to_pixel_coordinates(self,
156
+ metadata: pydicom.Dataset | Nifti1Image | None = None,
157
+ slice_plane: ViewPlane | None = None) -> Self:
158
+ """Copy with points as (x, y, slice index) on ``slice_plane`` (the native plane if None)."""
159
+ if self.coordinate_system == 'pixel':
160
+ return self.model_copy()
161
+ if metadata is None: # 2D images without geometry: patient and pixel are the same
162
+ return self.model_copy(update={'coordinate_system': 'pixel'})
163
+ points = _patient_to_pixel_points(self.points, slice_plane=slice_plane, metadata=metadata)
164
+ return self.model_copy(update={'points': tuple(_normalize_point(p) for p in points),
165
+ 'coordinate_system': 'pixel'})
166
+
167
+ def to_patient_coordinates(self,
168
+ metadata: pydicom.Dataset | Nifti1Image | None = None,
169
+ slice_plane: ViewPlane | None = None) -> Self:
170
+ """Copy with points in patient coordinates. The slice index of each point is rounded."""
171
+ if self.coordinate_system == 'patient':
172
+ return self.model_copy()
173
+ if metadata is None: # 2D images without geometry: patient and pixel are the same
174
+ return self.model_copy(update={'coordinate_system': 'patient'})
175
+ points = tuple(
176
+ _normalize_point(_pixel_to_patient_point(p, frame_index=int(round(p[2])), slice_plane=slice_plane,
177
+ metadata=metadata), allow_2d=False)
178
+ for p in self.points
179
+ )
180
+ viewPlaneNormal, viewUp = _TwoPointGeometry._extract_view_parameters(metadata)
181
+ return self.model_copy(update={'points': points, 'coordinate_system': 'patient',
182
+ 'viewPlaneNormal': viewPlaneNormal, 'viewUp': viewUp})
183
+
128
184
  def to_dict(self) -> dict[str, Any]:
129
185
  payload = self.model_dump(exclude={'type', 'coordinate_system'}, warnings='none')
130
186
  if 'points' in payload:
@@ -272,6 +328,11 @@ class _TwoPointGeometry(Geometry):
272
328
  class LineGeometry(_TwoPointGeometry):
273
329
  type: ClassVar[str] = 'line'
274
330
 
331
+ @property
332
+ def length(self) -> float:
333
+ """In pixels or mm, following ``coordinate_system``."""
334
+ return float(np.linalg.norm(np.subtract(self.point2, self.point1)))
335
+
275
336
 
276
337
  class PointGeometry(Geometry):
277
338
  points: tuple[Point3D]
@@ -365,6 +426,22 @@ class RegionGeometry(Geometry):
365
426
 
366
427
  return tuple(_normalize_point(point) for point in value)
367
428
 
429
+ @property
430
+ def length(self) -> float:
431
+ """Polyline length (perimeter if closed), in pixels or mm following ``coordinate_system``."""
432
+ pts = np.asarray(self.points, dtype=float)
433
+ if self.closed:
434
+ pts = np.vstack([pts, pts[:1]])
435
+ return float(np.linalg.norm(np.diff(pts, axis=0), axis=1).sum())
436
+
437
+ @property
438
+ def area(self) -> float:
439
+ """Area inside a closed region, in pixels² or mm² following ``coordinate_system``."""
440
+ if not self.closed:
441
+ raise ValueError('area is only defined for closed regions')
442
+ pts = np.asarray(self.points, dtype=float)
443
+ return float(np.linalg.norm(np.cross(pts, np.roll(pts, -1, axis=0)).sum(0)) / 2)
444
+
368
445
  @classmethod
369
446
  def from_coordinates(
370
447
  cls,
@@ -454,6 +531,28 @@ class BoxGeometry(Geometry):
454
531
  def point2(self) -> Point3D:
455
532
  return self.points[3]
456
533
 
534
+ @property
535
+ def xyxy(self) -> tuple[float, float, float, float]:
536
+ """(x1, y1, x2, y2) in pixels. Needs pixel coordinates."""
537
+ if self.coordinate_system != 'pixel':
538
+ raise ValueError('xyxy needs pixel coordinates, call to_pixel_coordinates(metadata) first')
539
+ pts = np.asarray(self.points, dtype=float)[:, :2]
540
+ x1, y1 = pts.min(0)
541
+ x2, y2 = pts.max(0)
542
+ return float(x1), float(y1), float(x2), float(y2)
543
+
544
+ @property
545
+ def xywh(self) -> tuple[float, float, float, float]:
546
+ """(x, y, width, height) in pixels. Needs pixel coordinates."""
547
+ x1, y1, x2, y2 = self.xyxy
548
+ return x1, y1, x2 - x1, y2 - y1
549
+
550
+ @property
551
+ def area(self) -> float:
552
+ """In pixels² or mm², following ``coordinate_system``."""
553
+ pts = np.asarray(self.points, dtype=float)
554
+ return float(np.linalg.norm(pts[1] - pts[0]) * np.linalg.norm(pts[2] - pts[0]))
555
+
457
556
  @classmethod
458
557
  def from_coordinates(
459
558
  cls,
@@ -22,6 +22,7 @@ from .cache_manager import CacheManager
22
22
 
23
23
  if TYPE_CHECKING:
24
24
  import numpy as np
25
+ from matplotlib.axes import Axes
25
26
  from medimgkit import ViewPlane
26
27
 
27
28
  from datamint.api.endpoints.resources_api import ResourcesApi
@@ -627,6 +628,41 @@ class Resource(BaseResource):
627
628
  """Open the resource in the default web browser."""
628
629
  webbrowser.open(self.url)
629
630
 
631
+ def plot_segmentations(self,
632
+ index: int | None = None,
633
+ axis: 'ViewPlane' = 'axial',
634
+ alpha: float = 0.5,
635
+ ax: 'Axes | None' = None) -> 'Axes':
636
+ """Plot one slice (or the 2D image) with all its segmentations on top.
637
+
638
+ ``index=None`` picks the slice with the biggest mask. ``axis`` is only used for volumes.
639
+ """
640
+ from datamint.utils.visualization import plot_segmentations
641
+
642
+ return plot_segmentations(self, index=index, axis=axis, alpha=alpha, ax=ax)
643
+
644
+ def plot_shapes(self,
645
+ axis: 'ViewPlane | None' = None,
646
+ index: int | None = None,
647
+ ax: 'Axes | None' = None) -> 'Axes':
648
+ """Plot one slice (or the 2D image) with its boxes, lines, points and regions.
649
+
650
+ ``axis`` is required for volumes: shapes are only shown on the plane they were drawn on.
651
+ ``index=None`` picks the slice with the most shapes.
652
+ """
653
+ from datamint.utils.visualization import plot_shapes
654
+
655
+ return plot_shapes(self, axis=axis, index=index, ax=ax)
656
+
657
+ def plot_labels(self,
658
+ index: int | None = None,
659
+ axis: 'ViewPlane' = 'axial',
660
+ ax: 'Axes | None' = None) -> 'Axes':
661
+ """Plot one slice (or the 2D image) with its categories, labels, numbers and texts listed on top."""
662
+ from datamint.utils.visualization import plot_labels
663
+
664
+ return plot_labels(self, index=index, axis=axis, ax=ax)
665
+
630
666
  @staticmethod
631
667
  def from_local_file(file_path: str | Path):
632
668
  """Create a LocalResource instance from a local file path.
@@ -1,3 +1,4 @@
1
+ from ._common import ImportIssue, build_report, format_report
1
2
  from ._detect import DatasetFormat, DetectedDataset, detect_format, sniff_single_format
2
3
  from .coco import COCOBox, COCOImporter, COCOImportResult, COCOParseResult, COCOSample
3
4
  from .pascal_voc import PascalVOCBox, PascalVOCImporter, PascalVOCImportResult, PascalVOCParseResult, PascalVOCSample
@@ -8,4 +9,5 @@ __all__ = [
8
9
  'PascalVOCImporter', 'PascalVOCParseResult', 'PascalVOCImportResult', 'PascalVOCSample', 'PascalVOCBox',
9
10
  'YOLOImporter', 'YOLOParseResult', 'YOLOImportResult', 'YOLOSample', 'YOLOBox',
10
11
  'DatasetFormat', 'DetectedDataset', 'detect_format', 'sniff_single_format',
12
+ 'ImportIssue', 'build_report', 'format_report',
11
13
  ]
@@ -0,0 +1,204 @@
1
+ import logging
2
+ import math
3
+ from collections import Counter
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Callable, Literal, Sequence
7
+
8
+ from tqdm.auto import tqdm
9
+
10
+ from datamint import Api
11
+ from datamint.entities import Project
12
+
13
+ _LOGGER = logging.getLogger(__name__)
14
+
15
+ IMAGE_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.bmp', '.tif', '.tiff', '.webp')
16
+
17
+ IssueKind = Literal['unknown_class', 'out_of_bounds', 'invalid_box', 'unknown_image', 'invalid_file']
18
+
19
+
20
+ @dataclass
21
+ class ImportIssue:
22
+ """A problem found while parsing. The affected box, annotation or file is skipped."""
23
+ kind: IssueKind
24
+ source: str
25
+ detail: str = ''
26
+
27
+
28
+ def check_box(x1: float, y1: float, x2: float, y2: float,
29
+ img_w: float | None, img_h: float | None) -> IssueKind | None:
30
+ """Return the issue kind for a pixel-space box, or None if it is valid.
31
+
32
+ The bounds check is skipped when the image size is unknown.
33
+ """
34
+ if not all(math.isfinite(v) for v in (x1, y1, x2, y2)) or x2 <= x1 or y2 <= y1:
35
+ return 'invalid_box'
36
+ if not img_w or not img_h:
37
+ return None
38
+ if x1 < 0 or y1 < 0 or x2 > img_w or y2 > img_h:
39
+ return 'out_of_bounds'
40
+ return None
41
+
42
+
43
+ def find_unreferenced_images(images_dir: Path, referenced: set[Path], recursive: bool = False) -> list[str]:
44
+ """Image files under ``images_dir`` that no annotation refers to (they are not uploaded)."""
45
+ if not images_dir.is_dir():
46
+ return []
47
+ referenced = {p.resolve() for p in referenced}
48
+ paths = images_dir.rglob('*') if recursive else images_dir.iterdir()
49
+ return sorted(str(p.relative_to(images_dir)) for p in paths
50
+ if p.suffix.lower() in IMAGE_EXTENSIONS and p.is_file() and p.resolve() not in referenced)
51
+
52
+
53
+ # --- Report ---
54
+
55
+ _FORMAT_NAMES = {'coco': 'COCO', 'pascal_voc': 'Pascal VOC', 'yolo': 'YOLO'}
56
+
57
+ _ISSUE_MESSAGES = {
58
+ 'unknown_class': 'box(es) with unknown class',
59
+ 'out_of_bounds': 'box(es) outside image bounds',
60
+ 'invalid_box': 'invalid box(es)',
61
+ 'unknown_image': 'annotation(s) referencing unknown image ids',
62
+ 'invalid_file': 'unreadable annotation file(s)',
63
+ }
64
+
65
+
66
+ def summarize_issues(result) -> list[str]:
67
+ """One line per kind of problem found while parsing."""
68
+ lines = []
69
+ if result.missing_images:
70
+ lines.append(f'{len(result.missing_images)} referenced image(s) not found on disk')
71
+ if result.unsupported_annotations:
72
+ lines.append(f'{result.unsupported_annotations} unsupported annotation(s), only boxes are imported')
73
+ for kind, n in Counter(issue.kind for issue in result.issues).items():
74
+ line = f'{n} {_ISSUE_MESSAGES[kind]}'
75
+ if kind == 'unknown_class':
76
+ line += f' {sorted({issue.detail for issue in result.issues if issue.kind == kind})}'
77
+ lines.append(line)
78
+ return lines
79
+
80
+
81
+ def build_report(fmt: str, result, *, detected: bool, paths: dict, project: str | None,
82
+ dry_run: bool) -> list[tuple[str, str]]:
83
+ """(key, value) rows describing what the import found and what it will do."""
84
+ n_empty = sum(1 for s in result.samples if not s.boxes)
85
+ splits = Counter(s.split for s in result.samples if getattr(s, 'split', None))
86
+ issues = summarize_issues(result)
87
+ verb = 'would upload' if dry_run else 'will upload'
88
+ target = f"to project '{project}' (created if missing)" if project else '(no --project given)'
89
+
90
+ rows = [('format', f"{_FORMAT_NAMES[fmt]} ({'detected' if detected else 'given'})")]
91
+ for key, value in paths.items():
92
+ if key != 'class_names':
93
+ rows.append((key, ', '.join(map(str, value)) if isinstance(value, list) else str(value)))
94
+ rows += [
95
+ ('images', f'{result.num_images:,} ({len(result.unreferenced_images):,} on disk not referenced, skipped)'),
96
+ ('labeled', f'{result.num_images - n_empty:,} ({n_empty:,} without boxes)'),
97
+ ]
98
+ if splits:
99
+ rows.append(('splits', ' · '.join(f'{name} {n:,}' for name, n in sorted(splits.items()))))
100
+ rows += [
101
+ ('boxes', f'{result.num_boxes:,}'),
102
+ ('classes', f'{len(result.class_names)} · {result.class_names}'),
103
+ ('issues', ' · '.join(issues) if issues else 'none'),
104
+ ('action', f'{verb} {result.num_images:,} image(s) and {result.num_boxes:,} box(es) {target}'),
105
+ ]
106
+ return rows
107
+
108
+
109
+ def format_report(rows: list[tuple[str, str]]) -> str:
110
+ width = max(len(key) for key, _ in rows) + 2
111
+ return '\n'.join(f'{key:<{width}}{value}' for key, value in rows)
112
+
113
+
114
+ def import_boxes_to_project(result,
115
+ project: Project | str,
116
+ api: Api | None,
117
+ *,
118
+ box_points: Callable[[object], tuple[tuple[float, float], tuple[float, float]]],
119
+ source_label: str,
120
+ tags: Sequence[str] | None,
121
+ imported_from: str,
122
+ on_error: Literal['raise', 'skip'],
123
+ progress_bar: bool,
124
+ result_cls: type,
125
+ sample_tags: Callable[[object], Sequence[str]] | None = None):
126
+ """Shared upload loop behind every ``*Importer.import_to_project()``.
127
+
128
+ ``result`` is a parse result with ``samples``, ``missing_images``, and
129
+ ``unsupported_annotations`` attributes. ``box_points`` maps a format's box
130
+ dataclass to a ``(point1, point2)`` pair for ``add_box_annotation``.
131
+ ``sample_tags`` gives extra tags per sample (e.g. its split), added to ``tags``.
132
+
133
+ """
134
+ api = api or Api()
135
+
136
+ if result.missing_images:
137
+ _LOGGER.warning(f'{len(result.missing_images)} image(s) referenced in {source_label} '
138
+ f'were not found on disk and will be skipped.')
139
+ if result.unsupported_annotations:
140
+ _LOGGER.warning(f'{result.unsupported_annotations} annotation(s) in {source_label} use an '
141
+ f'unsupported annotation type (e.g. polygon/segmentation) and were not '
142
+ f'imported; only bounding boxes are supported.')
143
+ if result.issues:
144
+ _LOGGER.warning(f'{len(result.issues)} box(es)/annotation(s) in {source_label} have issues '
145
+ f'(unknown class, invalid or out-of-bounds box, ...) and were not imported.')
146
+
147
+ # upload_resources applies one tag list to all files, so samples are uploaded in groups of equal tags
148
+ groups: dict[tuple[str, ...], list[int]] = {}
149
+ for i, sample in enumerate(result.samples):
150
+ extra = tuple(sample_tags(sample)) if sample_tags is not None else ()
151
+ groups.setdefault(extra, []).append(i)
152
+
153
+ uploaded: list = [None] * len(result.samples)
154
+ for extra, idxs in groups.items():
155
+ group_tags = list(tags or []) + list(extra)
156
+ group_ids = api.resources.upload_resources(
157
+ [str(result.samples[i].image_path) for i in idxs],
158
+ tags=group_tags or None,
159
+ publish_to=project,
160
+ on_error=on_error,
161
+ progress_bar=progress_bar,
162
+ )
163
+ for i, resource_id in zip(idxs, group_ids):
164
+ uploaded[i] = resource_id
165
+
166
+ resource_ids: list[str] = []
167
+ errors: list[tuple[str, Exception]] = []
168
+ n_boxes_uploaded = 0
169
+
170
+ iterator = zip(result.samples, uploaded)
171
+ if progress_bar:
172
+ iterator = tqdm(iterator, total=len(result.samples), desc='Uploading annotations')
173
+
174
+ for sample, resource_id in iterator:
175
+ if isinstance(resource_id, Exception):
176
+ errors.append((sample.file_name, resource_id))
177
+ continue
178
+ resource_ids.append(resource_id)
179
+
180
+ for box in sample.boxes:
181
+ point1, point2 = box_points(box)
182
+ try:
183
+ api.annotations.add_box_annotation(
184
+ point1=point1,
185
+ point2=point2,
186
+ resource=resource_id,
187
+ identifier=box.label,
188
+ imported_from=imported_from,
189
+ )
190
+ n_boxes_uploaded += 1
191
+ except (KeyboardInterrupt, SystemExit):
192
+ raise
193
+ except Exception as e:
194
+ if on_error == 'raise':
195
+ raise
196
+ errors.append((sample.file_name, e))
197
+
198
+ return result_cls(
199
+ project=project,
200
+ resource_ids=resource_ids,
201
+ n_images_uploaded=len(resource_ids),
202
+ n_boxes_uploaded=n_boxes_uploaded,
203
+ errors=errors,
204
+ )