datamint 2.47.0__tar.gz → 2.49.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.47.0 → datamint-2.49.0}/PKG-INFO +1 -1
  2. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/endpoints/resources_api.py +1 -1
  3. {datamint-2.47.0 → datamint-2.49.0}/datamint/client_cmd_tools/datamint_import.py +44 -31
  4. {datamint-2.47.0 → datamint-2.49.0}/datamint/importers/__init__.py +2 -0
  5. datamint-2.49.0/datamint/importers/_common.py +204 -0
  6. {datamint-2.47.0 → datamint-2.49.0}/datamint/importers/_detect.py +41 -11
  7. {datamint-2.47.0 → datamint-2.49.0}/datamint/importers/coco.py +30 -5
  8. {datamint-2.47.0 → datamint-2.49.0}/datamint/importers/pascal_voc.py +41 -12
  9. datamint-2.49.0/datamint/importers/yolo.py +247 -0
  10. {datamint-2.47.0 → datamint-2.49.0}/pyproject.toml +1 -1
  11. datamint-2.47.0/datamint/importers/_common.py +0 -86
  12. datamint-2.47.0/datamint/importers/yolo.py +0 -204
  13. {datamint-2.47.0 → datamint-2.49.0}/README.md +0 -0
  14. {datamint-2.47.0 → datamint-2.49.0}/datamint/__init__.py +0 -0
  15. {datamint-2.47.0 → datamint-2.49.0}/datamint/__main__.py +0 -0
  16. {datamint-2.47.0 → datamint-2.49.0}/datamint/_repr_utils.py +0 -0
  17. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/__init__.py +0 -0
  18. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/base_api.py +0 -0
  19. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/client.py +0 -0
  20. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/dto/__init__.py +0 -0
  21. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/dto/annotation_dto.py +0 -0
  22. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/dto/inference_prompts.py +0 -0
  23. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/dto/save_results_options.py +0 -0
  24. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/endpoints/__init__.py +0 -0
  25. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/endpoints/annotations_api.py +0 -0
  26. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/endpoints/annotationsets_api.py +0 -0
  27. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/endpoints/datasetsinfo_api.py +0 -0
  28. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/endpoints/deploy_model_api.py +0 -0
  29. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/endpoints/inference_api.py +0 -0
  30. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/endpoints/model_types.py +0 -0
  31. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/endpoints/models_api.py +0 -0
  32. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/endpoints/pod_logs_api.py +0 -0
  33. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/endpoints/projects_api.py +0 -0
  34. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/endpoints/users_api.py +0 -0
  35. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/endpoints/validation_studies_api.py +0 -0
  36. {datamint-2.47.0 → datamint-2.49.0}/datamint/api/entity_base_api.py +0 -0
  37. {datamint-2.47.0 → datamint-2.49.0}/datamint/client_cmd_tools/__init__.py +0 -0
  38. {datamint-2.47.0 → datamint-2.49.0}/datamint/client_cmd_tools/datamint_config.py +0 -0
  39. {datamint-2.47.0 → datamint-2.49.0}/datamint/client_cmd_tools/datamint_download.py +0 -0
  40. {datamint-2.47.0 → datamint-2.49.0}/datamint/client_cmd_tools/datamint_example.py +0 -0
  41. {datamint-2.47.0 → datamint-2.49.0}/datamint/client_cmd_tools/datamint_inference.py +0 -0
  42. {datamint-2.47.0 → datamint-2.49.0}/datamint/client_cmd_tools/datamint_init.py +0 -0
  43. {datamint-2.47.0 → datamint-2.49.0}/datamint/client_cmd_tools/datamint_train.py +0 -0
  44. {datamint-2.47.0 → datamint-2.49.0}/datamint/client_cmd_tools/datamint_upload.py +0 -0
  45. {datamint-2.47.0 → datamint-2.49.0}/datamint/configs.py +0 -0
  46. {datamint-2.47.0 → datamint-2.49.0}/datamint/dataset/__init__.py +0 -0
  47. {datamint-2.47.0 → datamint-2.49.0}/datamint/dataset/annotation_processor.py +0 -0
  48. {datamint-2.47.0 → datamint-2.49.0}/datamint/dataset/base.py +0 -0
  49. {datamint-2.47.0 → datamint-2.49.0}/datamint/dataset/factory.py +0 -0
  50. {datamint-2.47.0 → datamint-2.49.0}/datamint/dataset/image_dataset.py +0 -0
  51. {datamint-2.47.0 → datamint-2.49.0}/datamint/dataset/multiframe_dataset.py +0 -0
  52. {datamint-2.47.0 → datamint-2.49.0}/datamint/dataset/sliced_dataset.py +0 -0
  53. {datamint-2.47.0 → datamint-2.49.0}/datamint/dataset/sliced_video_dataset.py +0 -0
  54. {datamint-2.47.0 → datamint-2.49.0}/datamint/dataset/split_result.py +0 -0
  55. {datamint-2.47.0 → datamint-2.49.0}/datamint/dataset/video_dataset.py +0 -0
  56. {datamint-2.47.0 → datamint-2.49.0}/datamint/dataset/volume_dataset.py +0 -0
  57. {datamint-2.47.0 → datamint-2.49.0}/datamint/default_project.py +0 -0
  58. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/__init__.py +0 -0
  59. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotation_worklist.py +0 -0
  60. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/__init__.py +0 -0
  61. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/annotation.py +0 -0
  62. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/annotation_spec.py +0 -0
  63. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/base_geometry.py +0 -0
  64. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/base_segmentation.py +0 -0
  65. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/box_annotation.py +0 -0
  66. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/category_annotation.py +0 -0
  67. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/geometry.py +0 -0
  68. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/image_classification.py +0 -0
  69. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/image_segmentation.py +0 -0
  70. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/label_annotation.py +0 -0
  71. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/line_annotation.py +0 -0
  72. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/numeric_annotation.py +0 -0
  73. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/point_annotation.py +0 -0
  74. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/region_annotation.py +0 -0
  75. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/text_annotation.py +0 -0
  76. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/types.py +0 -0
  77. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/annotations/volume_segmentation.py +0 -0
  78. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/base_entity.py +0 -0
  79. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/buildlog.py +0 -0
  80. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/cache_manager.py +0 -0
  81. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/channel.py +0 -0
  82. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/datasetinfo.py +0 -0
  83. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/deployjob.py +0 -0
  84. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/inferencejob.py +0 -0
  85. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/pod.py +0 -0
  86. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/project.py +0 -0
  87. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/project_resource_split.py +0 -0
  88. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/resource.py +0 -0
  89. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/resources/__init__.py +0 -0
  90. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/resources/dicom_resource.py +0 -0
  91. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/resources/image_resource.py +0 -0
  92. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/resources/nifti_resource.py +0 -0
  93. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/resources/video_resource.py +0 -0
  94. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/resources/volume_resource.py +0 -0
  95. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/sliced_resource.py +0 -0
  96. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/sliced_resource_base.py +0 -0
  97. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/sliced_video_resource.py +0 -0
  98. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/user.py +0 -0
  99. {datamint-2.47.0 → datamint-2.49.0}/datamint/entities/validation_study.py +0 -0
  100. {datamint-2.47.0 → datamint-2.49.0}/datamint/evaluate/__init__.py +0 -0
  101. {datamint-2.47.0 → datamint-2.49.0}/datamint/evaluate/evaluator.py +0 -0
  102. {datamint-2.47.0 → datamint-2.49.0}/datamint/evaluate/metrics/__init__.py +0 -0
  103. {datamint-2.47.0 → datamint-2.49.0}/datamint/evaluate/metrics/classification.py +0 -0
  104. {datamint-2.47.0 → datamint-2.49.0}/datamint/evaluate/metrics/detection.py +0 -0
  105. {datamint-2.47.0 → datamint-2.49.0}/datamint/evaluate/metrics/segmentation.py +0 -0
  106. {datamint-2.47.0 → datamint-2.49.0}/datamint/examples/__init__.py +0 -0
  107. {datamint-2.47.0 → datamint-2.49.0}/datamint/examples/_common.py +0 -0
  108. {datamint-2.47.0 → datamint-2.49.0}/datamint/examples/_download.py +0 -0
  109. {datamint-2.47.0 → datamint-2.49.0}/datamint/examples/bccd_dataset.py +0 -0
  110. {datamint-2.47.0 → datamint-2.49.0}/datamint/examples/busi_dataset.py +0 -0
  111. {datamint-2.47.0 → datamint-2.49.0}/datamint/examples/example_projects.py +0 -0
  112. {datamint-2.47.0 → datamint-2.49.0}/datamint/examples/fracatlas_dataset.py +0 -0
  113. {datamint-2.47.0 → datamint-2.49.0}/datamint/examples/synapse_dataset.py +0 -0
  114. {datamint-2.47.0 → datamint-2.49.0}/datamint/exceptions.py +0 -0
  115. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/__init__.py +0 -0
  116. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/benchmark.py +0 -0
  117. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/datamodule.py +0 -0
  118. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/__init__.py +0 -0
  119. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/base_trainer.py +0 -0
  120. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/classification_trainer.py +0 -0
  121. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/detection_trainer.py +0 -0
  122. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/lightning_modules/__init__.py +0 -0
  123. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/lightning_modules/base.py +0 -0
  124. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/lightning_modules/classification_module.py +0 -0
  125. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/lightning_modules/detection_modules/__init__.py +0 -0
  126. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/lightning_modules/detection_modules/yolox_module.py +0 -0
  127. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/lightning_modules/segmentation_module.py +0 -0
  128. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/__init__.py +0 -0
  129. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/deeplabv3plus.py +0 -0
  130. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/smp_module.py +0 -0
  131. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/transunet.py +0 -0
  132. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/unetpp.py +0 -0
  133. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/lightning_modules/segmentation_modules/unetrpp.py +0 -0
  134. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/seg2d_trainer.py +0 -0
  135. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/seg3d_trainer.py +0 -0
  136. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/segmentation_trainer.py +0 -0
  137. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/specialized/__init__.py +0 -0
  138. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/specialized/deeplabv3plus.py +0 -0
  139. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/specialized/efficientnetv2.py +0 -0
  140. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/specialized/nnunet/__init__.py +0 -0
  141. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/specialized/nnunet/_nnunet_trainer_bridge.py +0 -0
  142. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/specialized/nnunet/data_export.py +0 -0
  143. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/specialized/nnunet/data_import.py +0 -0
  144. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/specialized/nnunet/inference_model.py +0 -0
  145. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/specialized/nnunet/trainer.py +0 -0
  146. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/specialized/transunet.py +0 -0
  147. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/specialized/unetpp.py +0 -0
  148. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/specialized/unetrpp.py +0 -0
  149. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/specialized/yolox.py +0 -0
  150. {datamint-2.47.0 → datamint-2.49.0}/datamint/lightning/trainers/vol_seg_trainer.py +0 -0
  151. {datamint-2.47.0 → datamint-2.49.0}/datamint/logging.yaml +0 -0
  152. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/__init__.py +0 -0
  153. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/artifact/__init__.py +0 -0
  154. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/artifact/datamint_artifacts_repo.py +0 -0
  155. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/data/__init__.py +0 -0
  156. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/data/datamint_dataset.py +0 -0
  157. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/env_utils.py +0 -0
  158. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/env_vars.py +0 -0
  159. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/flavors/__init__.py +0 -0
  160. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/flavors/annotation_specs.py +0 -0
  161. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/flavors/datamint_flavor.py +0 -0
  162. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/flavors/model.py +0 -0
  163. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/flavors/model_loader.py +0 -0
  164. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/flavors/model_parser.py +0 -0
  165. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/flavors/prediction_modes.py +0 -0
  166. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/flavors/prediction_router.py +0 -0
  167. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/flavors/task_type.py +0 -0
  168. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/flavors/validation.py +0 -0
  169. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/lightning/callbacks/__init__.py +0 -0
  170. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/lightning/callbacks/modelcheckpoint.py +0 -0
  171. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/models/Dockerfile.template +0 -0
  172. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/models/__init__.py +0 -0
  173. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/models/datamint_model_store.py +0 -0
  174. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/models/docker_build.py +0 -0
  175. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/models/local_inference.py +0 -0
  176. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/models/serve.py +0 -0
  177. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/models/tags.py +0 -0
  178. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/store_utils.py +0 -0
  179. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/tracking/datamint_store.py +0 -0
  180. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/tracking/default_experiment.py +0 -0
  181. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/tracking/fluent.py +0 -0
  182. {datamint-2.47.0 → datamint-2.49.0}/datamint/mlflow/tracking/offline_buffer.py +0 -0
  183. {datamint-2.47.0 → datamint-2.49.0}/datamint/types.py +0 -0
  184. {datamint-2.47.0 → datamint-2.49.0}/datamint/utils/annotation_agreement.py +0 -0
  185. {datamint-2.47.0 → datamint-2.49.0}/datamint/utils/collection_utils.py +0 -0
  186. {datamint-2.47.0 → datamint-2.49.0}/datamint/utils/date_utils.py +0 -0
  187. {datamint-2.47.0 → datamint-2.49.0}/datamint/utils/env.py +0 -0
  188. {datamint-2.47.0 → datamint-2.49.0}/datamint/utils/logging_utils.py +0 -0
  189. {datamint-2.47.0 → datamint-2.49.0}/datamint/utils/nifti_utils.py +0 -0
  190. {datamint-2.47.0 → datamint-2.49.0}/datamint/utils/torchmetrics.py +0 -0
  191. {datamint-2.47.0 → datamint-2.49.0}/datamint/utils/uncertainty.py +0 -0
  192. {datamint-2.47.0 → datamint-2.49.0}/datamint/utils/urls.py +0 -0
  193. {datamint-2.47.0 → datamint-2.49.0}/datamint/utils/visualization.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: datamint
3
- Version: 2.47.0
3
+ Version: 2.49.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
@@ -637,7 +637,7 @@ class ResourcesApi(CreatableEntityApi[Resource], DeletableEntityApi[Resource]):
637
637
  await self.annotations_api._upload_segmentations_async(
638
638
  resource_id,
639
639
  file_path=f,
640
- name=name,
640
+ name=self.annotations_api.standardize_segmentation_names(name),
641
641
  frame_index=frame_index,
642
642
  transpose_segmentation=transpose_segmentation,
643
643
  model_id=model_name,
@@ -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,16 +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
- _USER_LOGGER.info(f' {key}: {value}')
136
- if not args.yes:
137
- answer = input(f'Import as {fmt.upper()}? (y/n): ')
138
- if answer.strip().lower() != 'y':
139
- raise DatamintException(
140
- 'Aborted. Re-run with --format to choose a different format explicitly.'
141
- )
142
-
143
140
  overrides = {
144
141
  'annotations_file': args.annotations_file,
145
142
  'annotations_dir': args.annotations_dir,
@@ -161,7 +158,16 @@ def _resolve_dataset(args: argparse.Namespace) -> tuple[DatasetFormat, dict]:
161
158
  f'Pass {flags} explicitly.'
162
159
  )
163
160
 
164
- return fmt, base_kwargs
161
+ if fmt == 'yolo':
162
+ n_images, n_labels = (len(v) if isinstance(v, list) else 1
163
+ for v in (base_kwargs['images_dir'], base_kwargs['labels_dir']))
164
+ if n_images != n_labels:
165
+ raise DatamintException(
166
+ f'Detected {max(n_images, n_labels)} YOLO splits under \'{path}\', so a single '
167
+ '--images-dir or --labels-dir is ambiguous. Pass both --images-dir and --labels-dir.'
168
+ )
169
+
170
+ return fmt, base_kwargs, args.format is None
165
171
 
166
172
 
167
173
  def main() -> None:
@@ -180,25 +186,32 @@ def main() -> None:
180
186
  if not path.is_dir():
181
187
  raise DatamintException(f"'{path}' is not a directory.")
182
188
 
183
- fmt, importer_kwargs = _resolve_dataset(args)
189
+ fmt, importer_kwargs, auto_detected = _resolve_dataset(args)
184
190
  importer = _IMPORTER_CLASSES[fmt](**importer_kwargs)
185
191
 
186
- result = importer.parse()
187
- _USER_LOGGER.info(
188
- f'Parsed {result.num_images} image(s), {result.num_boxes} box(es), '
189
- f'{len(result.class_names)} class(es): {result.class_names}'
190
- )
191
- if result.missing_images:
192
- _USER_LOGGER.warning(f'{len(result.missing_images)} referenced image(s) not found on disk.')
193
- if result.unsupported_annotations:
194
- _USER_LOGGER.warning(
195
- f'{result.unsupported_annotations} annotation(s) use an unsupported type and will be skipped.'
196
- )
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))
197
203
 
198
204
  if args.dry_run:
199
205
  _USER_LOGGER.info('Dry run: nothing was uploaded.')
200
206
  return
201
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
+
202
215
  api_key = handle_api_key()
203
216
  if api_key is None:
204
217
  _USER_LOGGER.error('API key not provided. Aborting.')
@@ -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
+ )
@@ -15,6 +15,7 @@ from typing import Literal
15
15
  DatasetFormat = Literal['coco', 'yolo', 'pascal_voc']
16
16
 
17
17
  _IMAGE_DIR_NAMES = {'images', 'image', 'imgs', 'jpegimages', 'img'}
18
+ _LABEL_DIR_NAMES = {'labels', 'label'}
18
19
 
19
20
 
20
21
  @dataclass
@@ -22,7 +23,7 @@ class DetectedDataset:
22
23
  """Result of a format sniff: which format, and the constructor kwargs
23
24
  to feed the matching ``*Importer``."""
24
25
  format: DatasetFormat
25
- importer_kwargs: dict[str, Path] = field(default_factory=dict)
26
+ importer_kwargs: dict[str, Path | list[Path]] = field(default_factory=dict)
26
27
 
27
28
 
28
29
  def _find_dir(root: Path, names: set[str]) -> Path | None:
@@ -61,19 +62,48 @@ def sniff_pascal_voc(root: Path) -> DetectedDataset | None:
61
62
  return None
62
63
 
63
64
 
65
+ def _is_yolo_labels_dir(path: Path) -> bool:
66
+ txt_paths = [p for p in sorted(path.glob('*.txt')) if p.name != 'classes.txt']
67
+ for txt_path in txt_paths[:5]:
68
+ values = txt_path.read_text().split()
69
+ # YOLO box line: class cx cy w h
70
+ if values and len(values) % 5 == 0:
71
+ return True
72
+ return False
73
+
74
+
75
+ def _yolo_images_dir(labels_dir: Path) -> Path:
76
+ """Swap the last ``labels`` component of the path for its sibling images dir
77
+ (``train/labels`` -> ``train/images``, ``labels/train`` -> ``images/train``)."""
78
+ parts = labels_dir.parts
79
+ for i in reversed(range(len(parts))):
80
+ if parts[i].lower() not in _LABEL_DIR_NAMES:
81
+ continue
82
+ for sibling in sorted(Path(*parts[:i]).iterdir()):
83
+ candidate = sibling.joinpath(*parts[i + 1:])
84
+ if sibling.is_dir() and sibling.name.lower() in _IMAGE_DIR_NAMES and candidate.is_dir():
85
+ return candidate
86
+ break
87
+ return labels_dir.parent / 'images'
88
+
89
+
64
90
  def sniff_yolo(root: Path) -> DetectedDataset | None:
65
- """Look for a ``labels/`` dir of YOLO ``.txt`` files (class + 4 normalized floats)."""
66
- labels_dir = _find_dir(root, {'labels', 'label'})
67
- if labels_dir is None:
68
- return None
69
- txt_paths = [p for p in sorted(labels_dir.glob('*.txt')) if p.name != 'classes.txt']
70
- if not txt_paths:
71
- return None
72
- if not any(len(p.read_text().split()) % 5 == 0 and p.read_text().strip() for p in txt_paths[:5]):
91
+ """Look for ``labels/`` dirs of YOLO ``.txt`` files (class + 4 normalized floats).
92
+
93
+ Every split (``train``, ``valid``, ``test``, ...) is picked up, each paired with its images dir.
94
+ """
95
+ labels_dirs = [p for p in sorted(root.rglob('*'))
96
+ if p.is_dir()
97
+ and any(part.lower() in _LABEL_DIR_NAMES for part in p.relative_to(root).parts)
98
+ and _is_yolo_labels_dir(p)]
99
+ if not labels_dirs:
73
100
  return None
74
101
 
75
- images_dir = _find_dir(root, _IMAGE_DIR_NAMES) or labels_dir.parent / 'images'
76
- kwargs: dict[str, Path] = {'images_dir': images_dir, 'labels_dir': labels_dir}
102
+ images_dirs = [_yolo_images_dir(p) for p in labels_dirs]
103
+ kwargs: dict[str, Path | list[Path]] = {
104
+ 'images_dir': images_dirs[0] if len(images_dirs) == 1 else images_dirs,
105
+ 'labels_dir': labels_dirs[0] if len(labels_dirs) == 1 else labels_dirs,
106
+ }
77
107
 
78
108
  data_yaml = next(root.glob('*.yaml'), None) or next(root.glob('*.yml'), None)
79
109
  if data_yaml is not None:
@@ -7,6 +7,7 @@ from datamint import Api
7
7
  from datamint.entities import Project
8
8
 
9
9
  from . import _common
10
+ from ._common import ImportIssue
10
11
 
11
12
 
12
13
  @dataclass
@@ -31,6 +32,8 @@ class COCOParseResult:
31
32
  class_names: list[str]
32
33
  missing_images: list[str]
33
34
  unsupported_annotations: int
35
+ issues: list[ImportIssue] = field(default_factory=list)
36
+ unreferenced_images: list[str] = field(default_factory=list)
34
37
 
35
38
  @property
36
39
  def num_images(self) -> int:
@@ -63,9 +66,12 @@ class COCOImporter:
63
66
 
64
67
  Cached after the first call; pass ``force=True`` to reparse.
65
68
 
69
+ Annotations with an unknown category/image id or an invalid/out-of-bounds
70
+ box are skipped and recorded in ``issues``. The bounds check needs the
71
+ image ``width``/``height`` in the JSON and is skipped without them.
72
+
66
73
  Raises:
67
- ValueError: If the file is structurally invalid (missing required
68
- keys, or an annotation references an unknown category/image id).
74
+ ValueError: If the file is structurally invalid (missing required keys).
69
75
  """
70
76
  if self._result is not None and not force:
71
77
  return self._result
@@ -78,14 +84,17 @@ class COCOImporter:
78
84
  raise ValueError(f"Invalid COCO file: missing required key '{key}'.")
79
85
 
80
86
  categories = {cat['id']: cat['name'] for cat in data['categories']}
87
+ source = self.annotations_file.name
81
88
 
82
89
  images_by_id: dict[int, tuple[str, Path]] = {}
90
+ sizes_by_id: dict[int, tuple[float | None, float | None]] = {}
83
91
  missing_images: list[str] = []
84
92
  samples_by_id: dict[int, COCOSample] = {}
85
93
  for img in data['images']:
86
94
  file_name = img['file_name']
87
95
  image_path = self.images_dir / file_name
88
96
  images_by_id[img['id']] = (file_name, image_path)
97
+ sizes_by_id[img['id']] = (img.get('width'), img.get('height'))
89
98
  if not image_path.exists():
90
99
  missing_images.append(file_name)
91
100
  continue
@@ -93,16 +102,19 @@ class COCOImporter:
93
102
 
94
103
  used_class_names: set[str] = set()
95
104
  unsupported_annotations = 0
105
+ issues: list[ImportIssue] = []
96
106
  for ann in data['annotations']:
97
107
  image_id = ann['image_id']
98
108
  if image_id not in images_by_id:
99
- raise ValueError(f"Annotation {ann.get('id')} references unknown image_id {image_id}.")
109
+ issues.append(ImportIssue('unknown_image', source, str(image_id)))
110
+ continue
100
111
  if image_id not in samples_by_id:
101
112
  continue # image file missing on disk, already recorded above
102
113
 
103
114
  category_id = ann['category_id']
104
115
  if category_id not in categories:
105
- raise ValueError(f"Annotation {ann.get('id')} references unknown category_id {category_id}.")
116
+ issues.append(ImportIssue('unknown_class', source, str(category_id)))
117
+ continue
106
118
 
107
119
  bbox = ann.get('bbox')
108
120
  if bbox is None:
@@ -111,16 +123,29 @@ class COCOImporter:
111
123
  unsupported_annotations += 1
112
124
  continue
113
125
 
114
- x, y, width, height = bbox
126
+ try:
127
+ x, y, width, height = (float(v) for v in bbox)
128
+ except (TypeError, ValueError):
129
+ issues.append(ImportIssue('invalid_box', source, str(ann.get('id'))))
130
+ continue
131
+
132
+ issue = _common.check_box(x, y, x + width, y + height, *sizes_by_id[image_id])
133
+ if issue is not None:
134
+ issues.append(ImportIssue(issue, source, str(ann.get('id'))))
135
+ continue
136
+
115
137
  label = categories[category_id]
116
138
  samples_by_id[image_id].boxes.append(COCOBox(label=label, x=x, y=y, width=width, height=height))
117
139
  used_class_names.add(label)
118
140
 
141
+ referenced = {image_path for _, image_path in images_by_id.values()}
119
142
  self._result = COCOParseResult(
120
143
  samples=list(samples_by_id.values()),
121
144
  class_names=sorted(used_class_names),
122
145
  missing_images=missing_images,
123
146
  unsupported_annotations=unsupported_annotations,
147
+ issues=issues,
148
+ unreferenced_images=_common.find_unreferenced_images(self.images_dir, referenced, recursive=True),
124
149
  )
125
150
  return self._result
126
151
 
@@ -7,6 +7,7 @@ from datamint import Api
7
7
  from datamint.entities import Project
8
8
 
9
9
  from . import _common
10
+ from ._common import ImportIssue
10
11
 
11
12
 
12
13
  @dataclass
@@ -32,6 +33,8 @@ class PascalVOCParseResult:
32
33
  class_names: list[str]
33
34
  missing_images: list[str]
34
35
  unsupported_annotations: int
36
+ issues: list[ImportIssue] = field(default_factory=list)
37
+ unreferenced_images: list[str] = field(default_factory=list)
35
38
 
36
39
  @property
37
40
  def num_images(self) -> int:
@@ -51,6 +54,14 @@ class PascalVOCImportResult:
51
54
  errors: list[tuple[str, Exception]] = field(default_factory=list)
52
55
 
53
56
 
57
+ def _read_size(root: ET.Element) -> tuple[float | None, float | None]:
58
+ """Image (width, height) from the ``size`` element, or (None, None) if missing/invalid."""
59
+ try:
60
+ return float(root.findtext('size/width')), float(root.findtext('size/height'))
61
+ except (TypeError, ValueError):
62
+ return None, None
63
+
64
+
54
65
  class PascalVOCImporter:
55
66
  """Parse a Pascal VOC-format annotations directory and upload it to a Datamint project.
56
67
 
@@ -67,9 +78,12 @@ class PascalVOCImporter:
67
78
 
68
79
  Cached after the first call; pass ``force=True`` to reparse.
69
80
 
81
+ XML files that can't be read or have no ``filename``, and invalid or
82
+ out-of-bounds boxes, are skipped and recorded in ``issues``. The bounds
83
+ check needs the ``size`` element and is skipped without it.
84
+
70
85
  Raises:
71
- ValueError: If ``annotations_dir`` doesn't exist, or an XML file is
72
- missing its required ``filename`` element.
86
+ ValueError: If ``annotations_dir`` doesn't exist.
73
87
  """
74
88
  if self._result is not None and not force:
75
89
  return self._result
@@ -81,19 +95,28 @@ class PascalVOCImporter:
81
95
  missing_images: list[str] = []
82
96
  used_class_names: set[str] = set()
83
97
  unsupported_annotations = 0
98
+ issues: list[ImportIssue] = []
99
+ referenced: set[Path] = set()
84
100
 
85
101
  for xml_path in sorted(self.annotations_dir.glob('*.xml')):
86
- root = ET.parse(xml_path).getroot()
102
+ try:
103
+ root = ET.parse(xml_path).getroot()
104
+ except ET.ParseError:
105
+ issues.append(ImportIssue('invalid_file', xml_path.name))
106
+ continue
87
107
 
88
108
  file_name = root.findtext('filename', default='').strip()
89
109
  if not file_name:
90
- raise ValueError(f"Invalid Pascal VOC annotation '{xml_path}': missing required element 'filename'.")
110
+ issues.append(ImportIssue('invalid_file', xml_path.name, "missing 'filename'"))
111
+ continue
91
112
 
92
113
  image_path = self.images_dir / file_name
114
+ referenced.add(image_path)
93
115
  if not image_path.exists():
94
116
  missing_images.append(file_name)
95
117
  continue
96
118
 
119
+ img_w, img_h = _read_size(root)
97
120
  sample = PascalVOCSample(image_path=image_path, file_name=file_name)
98
121
  for obj in root.findall('object'):
99
122
  label = obj.findtext('name', default='').strip()
@@ -106,15 +129,19 @@ class PascalVOCImporter:
106
129
  # incomplete object entry skip it
107
130
  continue
108
131
 
132
+ try:
133
+ x1, y1, x2, y2 = (float(bb.findtext(k)) for k in ('xmin', 'ymin', 'xmax', 'ymax'))
134
+ except (TypeError, ValueError):
135
+ issues.append(ImportIssue('invalid_box', xml_path.name, label))
136
+ continue
137
+
138
+ issue = _common.check_box(x1, y1, x2, y2, img_w, img_h)
139
+ if issue is not None:
140
+ issues.append(ImportIssue(issue, xml_path.name, label))
141
+ continue
142
+
109
143
  difficult = obj.findtext('difficult', default='0').strip() == '1'
110
- sample.boxes.append(PascalVOCBox(
111
- label=label,
112
- x1=float(bb.findtext('xmin')),
113
- y1=float(bb.findtext('ymin')),
114
- x2=float(bb.findtext('xmax')),
115
- y2=float(bb.findtext('ymax')),
116
- difficult=difficult,
117
- ))
144
+ sample.boxes.append(PascalVOCBox(label=label, x1=x1, y1=y1, x2=x2, y2=y2, difficult=difficult))
118
145
  used_class_names.add(label)
119
146
 
120
147
  samples.append(sample)
@@ -124,6 +151,8 @@ class PascalVOCImporter:
124
151
  class_names=sorted(used_class_names),
125
152
  missing_images=missing_images,
126
153
  unsupported_annotations=unsupported_annotations,
154
+ issues=issues,
155
+ unreferenced_images=_common.find_unreferenced_images(self.images_dir, referenced),
127
156
  )
128
157
  return self._result
129
158