wandb 0.21.2__py3-none-macosx_12_0_arm64.whl

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 (904) hide show
  1. package_readme.md +97 -0
  2. wandb/__init__.py +248 -0
  3. wandb/__init__.pyi +1230 -0
  4. wandb/__main__.py +3 -0
  5. wandb/_iterutils.py +65 -0
  6. wandb/_pydantic/__init__.py +30 -0
  7. wandb/_pydantic/base.py +128 -0
  8. wandb/_pydantic/utils.py +80 -0
  9. wandb/_pydantic/v1_compat.py +284 -0
  10. wandb/agents/__init__.py +0 -0
  11. wandb/agents/pyagent.py +386 -0
  12. wandb/analytics/__init__.py +3 -0
  13. wandb/analytics/sentry.py +267 -0
  14. wandb/apis/__init__.py +48 -0
  15. wandb/apis/attrs.py +50 -0
  16. wandb/apis/importers/__init__.py +1 -0
  17. wandb/apis/importers/internals/internal.py +382 -0
  18. wandb/apis/importers/internals/protocols.py +103 -0
  19. wandb/apis/importers/internals/util.py +78 -0
  20. wandb/apis/importers/mlflow.py +254 -0
  21. wandb/apis/importers/validation.py +108 -0
  22. wandb/apis/importers/wandb.py +1608 -0
  23. wandb/apis/internal.py +239 -0
  24. wandb/apis/normalize.py +81 -0
  25. wandb/apis/paginator.py +138 -0
  26. wandb/apis/public/__init__.py +35 -0
  27. wandb/apis/public/api.py +2449 -0
  28. wandb/apis/public/artifacts.py +1046 -0
  29. wandb/apis/public/automations.py +85 -0
  30. wandb/apis/public/const.py +4 -0
  31. wandb/apis/public/files.py +402 -0
  32. wandb/apis/public/history.py +201 -0
  33. wandb/apis/public/integrations.py +203 -0
  34. wandb/apis/public/jobs.py +742 -0
  35. wandb/apis/public/projects.py +276 -0
  36. wandb/apis/public/query_generator.py +176 -0
  37. wandb/apis/public/registries/__init__.py +0 -0
  38. wandb/apis/public/registries/_freezable_list.py +179 -0
  39. wandb/apis/public/registries/_utils.py +138 -0
  40. wandb/apis/public/registries/registries_search.py +347 -0
  41. wandb/apis/public/registries/registry.py +358 -0
  42. wandb/apis/public/reports.py +595 -0
  43. wandb/apis/public/runs.py +1216 -0
  44. wandb/apis/public/sweeps.py +440 -0
  45. wandb/apis/public/teams.py +235 -0
  46. wandb/apis/public/users.py +177 -0
  47. wandb/apis/public/utils.py +210 -0
  48. wandb/apis/reports/__init__.py +1 -0
  49. wandb/apis/reports/v1/__init__.py +8 -0
  50. wandb/apis/reports/v2/__init__.py +8 -0
  51. wandb/apis/workspaces/__init__.py +8 -0
  52. wandb/automations/__init__.py +73 -0
  53. wandb/automations/_filters/__init__.py +40 -0
  54. wandb/automations/_filters/expressions.py +181 -0
  55. wandb/automations/_filters/operators.py +258 -0
  56. wandb/automations/_filters/run_metrics.py +330 -0
  57. wandb/automations/_generated/__init__.py +177 -0
  58. wandb/automations/_generated/create_automation.py +17 -0
  59. wandb/automations/_generated/create_generic_webhook_integration.py +43 -0
  60. wandb/automations/_generated/delete_automation.py +15 -0
  61. wandb/automations/_generated/enums.py +35 -0
  62. wandb/automations/_generated/fragments.py +358 -0
  63. wandb/automations/_generated/generic_webhook_integrations_by_entity.py +22 -0
  64. wandb/automations/_generated/get_automations.py +24 -0
  65. wandb/automations/_generated/get_automations_by_entity.py +26 -0
  66. wandb/automations/_generated/input_types.py +104 -0
  67. wandb/automations/_generated/integrations_by_entity.py +22 -0
  68. wandb/automations/_generated/operations.py +647 -0
  69. wandb/automations/_generated/slack_integrations_by_entity.py +22 -0
  70. wandb/automations/_generated/update_automation.py +17 -0
  71. wandb/automations/_utils.py +235 -0
  72. wandb/automations/_validators.py +165 -0
  73. wandb/automations/actions.py +218 -0
  74. wandb/automations/automations.py +85 -0
  75. wandb/automations/events.py +285 -0
  76. wandb/automations/integrations.py +45 -0
  77. wandb/automations/scopes.py +78 -0
  78. wandb/beta/workflows.py +324 -0
  79. wandb/bin/gpu_stats +0 -0
  80. wandb/bin/wandb-core +0 -0
  81. wandb/cli/__init__.py +0 -0
  82. wandb/cli/beta.py +175 -0
  83. wandb/cli/cli.py +2883 -0
  84. wandb/data_types.py +66 -0
  85. wandb/docker/__init__.py +290 -0
  86. wandb/docker/names.py +40 -0
  87. wandb/docker/wandb-entrypoint.sh +33 -0
  88. wandb/env.py +535 -0
  89. wandb/errors/__init__.py +17 -0
  90. wandb/errors/errors.py +40 -0
  91. wandb/errors/links.py +73 -0
  92. wandb/errors/term.py +415 -0
  93. wandb/errors/util.py +57 -0
  94. wandb/errors/warnings.py +2 -0
  95. wandb/filesync/__init__.py +0 -0
  96. wandb/filesync/dir_watcher.py +404 -0
  97. wandb/filesync/stats.py +100 -0
  98. wandb/filesync/step_checksum.py +142 -0
  99. wandb/filesync/step_prepare.py +179 -0
  100. wandb/filesync/step_upload.py +287 -0
  101. wandb/filesync/upload_job.py +142 -0
  102. wandb/integration/__init__.py +0 -0
  103. wandb/integration/catboost/__init__.py +5 -0
  104. wandb/integration/catboost/catboost.py +182 -0
  105. wandb/integration/cohere/__init__.py +3 -0
  106. wandb/integration/cohere/cohere.py +21 -0
  107. wandb/integration/cohere/resolver.py +347 -0
  108. wandb/integration/diffusers/__init__.py +3 -0
  109. wandb/integration/diffusers/autologger.py +76 -0
  110. wandb/integration/diffusers/pipeline_resolver.py +50 -0
  111. wandb/integration/diffusers/resolvers/__init__.py +9 -0
  112. wandb/integration/diffusers/resolvers/multimodal.py +881 -0
  113. wandb/integration/diffusers/resolvers/utils.py +102 -0
  114. wandb/integration/fastai/__init__.py +243 -0
  115. wandb/integration/gym/__init__.py +98 -0
  116. wandb/integration/huggingface/__init__.py +3 -0
  117. wandb/integration/huggingface/huggingface.py +18 -0
  118. wandb/integration/huggingface/resolver.py +213 -0
  119. wandb/integration/keras/__init__.py +11 -0
  120. wandb/integration/keras/callbacks/__init__.py +5 -0
  121. wandb/integration/keras/callbacks/metrics_logger.py +129 -0
  122. wandb/integration/keras/callbacks/model_checkpoint.py +188 -0
  123. wandb/integration/keras/callbacks/tables_builder.py +228 -0
  124. wandb/integration/keras/keras.py +1086 -0
  125. wandb/integration/kfp/__init__.py +6 -0
  126. wandb/integration/kfp/helpers.py +28 -0
  127. wandb/integration/kfp/kfp_patch.py +335 -0
  128. wandb/integration/kfp/wandb_logging.py +182 -0
  129. wandb/integration/langchain/__init__.py +3 -0
  130. wandb/integration/langchain/wandb_tracer.py +49 -0
  131. wandb/integration/lightgbm/__init__.py +239 -0
  132. wandb/integration/lightning/__init__.py +0 -0
  133. wandb/integration/lightning/fabric/__init__.py +3 -0
  134. wandb/integration/lightning/fabric/logger.py +763 -0
  135. wandb/integration/metaflow/__init__.py +9 -0
  136. wandb/integration/metaflow/data_pandas.py +74 -0
  137. wandb/integration/metaflow/data_pytorch.py +75 -0
  138. wandb/integration/metaflow/data_sklearn.py +76 -0
  139. wandb/integration/metaflow/errors.py +13 -0
  140. wandb/integration/metaflow/metaflow.py +327 -0
  141. wandb/integration/openai/__init__.py +3 -0
  142. wandb/integration/openai/fine_tuning.py +480 -0
  143. wandb/integration/openai/openai.py +22 -0
  144. wandb/integration/openai/resolver.py +240 -0
  145. wandb/integration/prodigy/__init__.py +3 -0
  146. wandb/integration/prodigy/prodigy.py +291 -0
  147. wandb/integration/sacred/__init__.py +117 -0
  148. wandb/integration/sagemaker/__init__.py +14 -0
  149. wandb/integration/sagemaker/auth.py +29 -0
  150. wandb/integration/sagemaker/config.py +58 -0
  151. wandb/integration/sagemaker/files.py +2 -0
  152. wandb/integration/sagemaker/resources.py +63 -0
  153. wandb/integration/sb3/__init__.py +3 -0
  154. wandb/integration/sb3/sb3.py +147 -0
  155. wandb/integration/sklearn/__init__.py +37 -0
  156. wandb/integration/sklearn/calculate/__init__.py +32 -0
  157. wandb/integration/sklearn/calculate/calibration_curves.py +125 -0
  158. wandb/integration/sklearn/calculate/class_proportions.py +68 -0
  159. wandb/integration/sklearn/calculate/confusion_matrix.py +93 -0
  160. wandb/integration/sklearn/calculate/decision_boundaries.py +40 -0
  161. wandb/integration/sklearn/calculate/elbow_curve.py +55 -0
  162. wandb/integration/sklearn/calculate/feature_importances.py +67 -0
  163. wandb/integration/sklearn/calculate/learning_curve.py +64 -0
  164. wandb/integration/sklearn/calculate/outlier_candidates.py +69 -0
  165. wandb/integration/sklearn/calculate/residuals.py +86 -0
  166. wandb/integration/sklearn/calculate/silhouette.py +118 -0
  167. wandb/integration/sklearn/calculate/summary_metrics.py +62 -0
  168. wandb/integration/sklearn/plot/__init__.py +35 -0
  169. wandb/integration/sklearn/plot/classifier.py +329 -0
  170. wandb/integration/sklearn/plot/clusterer.py +146 -0
  171. wandb/integration/sklearn/plot/regressor.py +121 -0
  172. wandb/integration/sklearn/plot/shared.py +91 -0
  173. wandb/integration/sklearn/utils.py +184 -0
  174. wandb/integration/tensorboard/__init__.py +10 -0
  175. wandb/integration/tensorboard/log.py +351 -0
  176. wandb/integration/tensorboard/monkeypatch.py +186 -0
  177. wandb/integration/tensorflow/__init__.py +5 -0
  178. wandb/integration/tensorflow/estimator_hook.py +54 -0
  179. wandb/integration/torch/__init__.py +0 -0
  180. wandb/integration/torch/wandb_torch.py +554 -0
  181. wandb/integration/ultralytics/__init__.py +11 -0
  182. wandb/integration/ultralytics/bbox_utils.py +215 -0
  183. wandb/integration/ultralytics/callback.py +528 -0
  184. wandb/integration/ultralytics/classification_utils.py +83 -0
  185. wandb/integration/ultralytics/mask_utils.py +202 -0
  186. wandb/integration/ultralytics/pose_utils.py +103 -0
  187. wandb/integration/weave/__init__.py +6 -0
  188. wandb/integration/weave/interface.py +49 -0
  189. wandb/integration/weave/weave.py +63 -0
  190. wandb/integration/xgboost/__init__.py +11 -0
  191. wandb/integration/xgboost/xgboost.py +189 -0
  192. wandb/integration/yolov8/__init__.py +0 -0
  193. wandb/integration/yolov8/yolov8.py +284 -0
  194. wandb/jupyter.py +538 -0
  195. wandb/mpmain/__init__.py +0 -0
  196. wandb/mpmain/__main__.py +1 -0
  197. wandb/old/__init__.py +0 -0
  198. wandb/old/core.py +53 -0
  199. wandb/old/settings.py +176 -0
  200. wandb/old/summary.py +438 -0
  201. wandb/plot/__init__.py +30 -0
  202. wandb/plot/bar.py +71 -0
  203. wandb/plot/confusion_matrix.py +185 -0
  204. wandb/plot/custom_chart.py +147 -0
  205. wandb/plot/histogram.py +66 -0
  206. wandb/plot/line.py +75 -0
  207. wandb/plot/line_series.py +173 -0
  208. wandb/plot/pr_curve.py +186 -0
  209. wandb/plot/roc_curve.py +163 -0
  210. wandb/plot/scatter.py +66 -0
  211. wandb/plot/utils.py +184 -0
  212. wandb/plot/viz.py +41 -0
  213. wandb/proto/__init__.py +0 -0
  214. wandb/proto/v3/__init__.py +0 -0
  215. wandb/proto/v3/wandb_base_pb2.py +55 -0
  216. wandb/proto/v3/wandb_internal_pb2.py +1728 -0
  217. wandb/proto/v3/wandb_server_pb2.py +228 -0
  218. wandb/proto/v3/wandb_settings_pb2.py +122 -0
  219. wandb/proto/v3/wandb_telemetry_pb2.py +106 -0
  220. wandb/proto/v4/__init__.py +0 -0
  221. wandb/proto/v4/wandb_base_pb2.py +30 -0
  222. wandb/proto/v4/wandb_internal_pb2.py +382 -0
  223. wandb/proto/v4/wandb_server_pb2.py +67 -0
  224. wandb/proto/v4/wandb_settings_pb2.py +47 -0
  225. wandb/proto/v4/wandb_telemetry_pb2.py +41 -0
  226. wandb/proto/v5/wandb_base_pb2.py +31 -0
  227. wandb/proto/v5/wandb_internal_pb2.py +383 -0
  228. wandb/proto/v5/wandb_server_pb2.py +68 -0
  229. wandb/proto/v5/wandb_settings_pb2.py +48 -0
  230. wandb/proto/v5/wandb_telemetry_pb2.py +42 -0
  231. wandb/proto/v6/wandb_base_pb2.py +41 -0
  232. wandb/proto/v6/wandb_internal_pb2.py +393 -0
  233. wandb/proto/v6/wandb_server_pb2.py +78 -0
  234. wandb/proto/v6/wandb_settings_pb2.py +58 -0
  235. wandb/proto/v6/wandb_telemetry_pb2.py +52 -0
  236. wandb/proto/wandb_base_pb2.py +12 -0
  237. wandb/proto/wandb_deprecated.py +59 -0
  238. wandb/proto/wandb_generate_deprecated.py +30 -0
  239. wandb/proto/wandb_generate_proto.py +49 -0
  240. wandb/proto/wandb_internal_pb2.py +18 -0
  241. wandb/proto/wandb_server_pb2.py +12 -0
  242. wandb/proto/wandb_settings_pb2.py +12 -0
  243. wandb/proto/wandb_telemetry_pb2.py +12 -0
  244. wandb/py.typed +0 -0
  245. wandb/sdk/__init__.py +37 -0
  246. wandb/sdk/artifacts/__init__.py +0 -0
  247. wandb/sdk/artifacts/_factories.py +17 -0
  248. wandb/sdk/artifacts/_generated/__init__.py +508 -0
  249. wandb/sdk/artifacts/_generated/add_aliases.py +21 -0
  250. wandb/sdk/artifacts/_generated/artifact_by_id.py +17 -0
  251. wandb/sdk/artifacts/_generated/artifact_by_name.py +22 -0
  252. wandb/sdk/artifacts/_generated/artifact_collection_membership_file_urls.py +43 -0
  253. wandb/sdk/artifacts/_generated/artifact_collection_membership_files.py +43 -0
  254. wandb/sdk/artifacts/_generated/artifact_created_by.py +47 -0
  255. wandb/sdk/artifacts/_generated/artifact_file_urls.py +22 -0
  256. wandb/sdk/artifacts/_generated/artifact_type.py +31 -0
  257. wandb/sdk/artifacts/_generated/artifact_used_by.py +43 -0
  258. wandb/sdk/artifacts/_generated/artifact_version_files.py +36 -0
  259. wandb/sdk/artifacts/_generated/artifact_via_membership_by_name.py +26 -0
  260. wandb/sdk/artifacts/_generated/create_artifact_collection_tag_assignments.py +36 -0
  261. wandb/sdk/artifacts/_generated/delete_aliases.py +21 -0
  262. wandb/sdk/artifacts/_generated/delete_artifact.py +28 -0
  263. wandb/sdk/artifacts/_generated/delete_artifact_collection_tag_assignments.py +25 -0
  264. wandb/sdk/artifacts/_generated/delete_artifact_portfolio.py +35 -0
  265. wandb/sdk/artifacts/_generated/delete_artifact_sequence.py +35 -0
  266. wandb/sdk/artifacts/_generated/enums.py +22 -0
  267. wandb/sdk/artifacts/_generated/fetch_artifact_manifest.py +38 -0
  268. wandb/sdk/artifacts/_generated/fetch_linked_artifacts.py +67 -0
  269. wandb/sdk/artifacts/_generated/fetch_registries.py +32 -0
  270. wandb/sdk/artifacts/_generated/fragments.py +459 -0
  271. wandb/sdk/artifacts/_generated/input_types.py +46 -0
  272. wandb/sdk/artifacts/_generated/link_artifact.py +27 -0
  273. wandb/sdk/artifacts/_generated/move_artifact_collection.py +35 -0
  274. wandb/sdk/artifacts/_generated/operations.py +1223 -0
  275. wandb/sdk/artifacts/_generated/project_artifact_collection.py +101 -0
  276. wandb/sdk/artifacts/_generated/project_artifact_collections.py +33 -0
  277. wandb/sdk/artifacts/_generated/project_artifact_type.py +24 -0
  278. wandb/sdk/artifacts/_generated/project_artifact_types.py +24 -0
  279. wandb/sdk/artifacts/_generated/project_artifacts.py +42 -0
  280. wandb/sdk/artifacts/_generated/registry_collections.py +34 -0
  281. wandb/sdk/artifacts/_generated/registry_versions.py +34 -0
  282. wandb/sdk/artifacts/_generated/run_input_artifacts.py +51 -0
  283. wandb/sdk/artifacts/_generated/run_output_artifacts.py +51 -0
  284. wandb/sdk/artifacts/_generated/unlink_artifact.py +25 -0
  285. wandb/sdk/artifacts/_generated/update_artifact.py +26 -0
  286. wandb/sdk/artifacts/_generated/update_artifact_portfolio.py +35 -0
  287. wandb/sdk/artifacts/_generated/update_artifact_sequence.py +35 -0
  288. wandb/sdk/artifacts/_graphql_fragments.py +19 -0
  289. wandb/sdk/artifacts/_internal_artifact.py +54 -0
  290. wandb/sdk/artifacts/_validators.py +309 -0
  291. wandb/sdk/artifacts/artifact.py +2702 -0
  292. wandb/sdk/artifacts/artifact_download_logger.py +45 -0
  293. wandb/sdk/artifacts/artifact_file_cache.py +251 -0
  294. wandb/sdk/artifacts/artifact_instance_cache.py +17 -0
  295. wandb/sdk/artifacts/artifact_manifest.py +76 -0
  296. wandb/sdk/artifacts/artifact_manifest_entry.py +258 -0
  297. wandb/sdk/artifacts/artifact_manifests/__init__.py +0 -0
  298. wandb/sdk/artifacts/artifact_manifests/artifact_manifest_v1.py +94 -0
  299. wandb/sdk/artifacts/artifact_saver.py +277 -0
  300. wandb/sdk/artifacts/artifact_state.py +13 -0
  301. wandb/sdk/artifacts/artifact_ttl.py +9 -0
  302. wandb/sdk/artifacts/exceptions.py +71 -0
  303. wandb/sdk/artifacts/staging.py +27 -0
  304. wandb/sdk/artifacts/storage_handler.py +62 -0
  305. wandb/sdk/artifacts/storage_handlers/__init__.py +0 -0
  306. wandb/sdk/artifacts/storage_handlers/azure_handler.py +214 -0
  307. wandb/sdk/artifacts/storage_handlers/gcs_handler.py +224 -0
  308. wandb/sdk/artifacts/storage_handlers/http_handler.py +114 -0
  309. wandb/sdk/artifacts/storage_handlers/local_file_handler.py +142 -0
  310. wandb/sdk/artifacts/storage_handlers/multi_handler.py +56 -0
  311. wandb/sdk/artifacts/storage_handlers/s3_handler.py +339 -0
  312. wandb/sdk/artifacts/storage_handlers/tracking_handler.py +68 -0
  313. wandb/sdk/artifacts/storage_handlers/wb_artifact_handler.py +131 -0
  314. wandb/sdk/artifacts/storage_handlers/wb_local_artifact_handler.py +74 -0
  315. wandb/sdk/artifacts/storage_layout.py +8 -0
  316. wandb/sdk/artifacts/storage_policies/__init__.py +4 -0
  317. wandb/sdk/artifacts/storage_policies/register.py +1 -0
  318. wandb/sdk/artifacts/storage_policies/wandb_storage_policy.py +580 -0
  319. wandb/sdk/artifacts/storage_policy.py +75 -0
  320. wandb/sdk/backend/__init__.py +0 -0
  321. wandb/sdk/backend/backend.py +57 -0
  322. wandb/sdk/data_types/__init__.py +0 -0
  323. wandb/sdk/data_types/_dtypes.py +914 -0
  324. wandb/sdk/data_types/_private.py +10 -0
  325. wandb/sdk/data_types/audio.py +208 -0
  326. wandb/sdk/data_types/base_types/__init__.py +0 -0
  327. wandb/sdk/data_types/base_types/json_metadata.py +55 -0
  328. wandb/sdk/data_types/base_types/media.py +339 -0
  329. wandb/sdk/data_types/base_types/wb_value.py +295 -0
  330. wandb/sdk/data_types/bokeh.py +87 -0
  331. wandb/sdk/data_types/graph.py +439 -0
  332. wandb/sdk/data_types/helper_types/__init__.py +0 -0
  333. wandb/sdk/data_types/helper_types/bounding_boxes_2d.py +327 -0
  334. wandb/sdk/data_types/helper_types/classes.py +159 -0
  335. wandb/sdk/data_types/helper_types/image_mask.py +251 -0
  336. wandb/sdk/data_types/histogram.py +107 -0
  337. wandb/sdk/data_types/html.py +165 -0
  338. wandb/sdk/data_types/image.py +974 -0
  339. wandb/sdk/data_types/molecule.py +250 -0
  340. wandb/sdk/data_types/object_3d.py +495 -0
  341. wandb/sdk/data_types/plotly.py +95 -0
  342. wandb/sdk/data_types/saved_model.py +435 -0
  343. wandb/sdk/data_types/table.py +1468 -0
  344. wandb/sdk/data_types/table_decorators.py +108 -0
  345. wandb/sdk/data_types/trace_tree.py +440 -0
  346. wandb/sdk/data_types/utils.py +260 -0
  347. wandb/sdk/data_types/video.py +303 -0
  348. wandb/sdk/integration_utils/__init__.py +0 -0
  349. wandb/sdk/integration_utils/auto_logging.py +232 -0
  350. wandb/sdk/integration_utils/data_logging.py +475 -0
  351. wandb/sdk/interface/__init__.py +0 -0
  352. wandb/sdk/interface/constants.py +4 -0
  353. wandb/sdk/interface/interface.py +1056 -0
  354. wandb/sdk/interface/interface_queue.py +40 -0
  355. wandb/sdk/interface/interface_shared.py +471 -0
  356. wandb/sdk/interface/interface_sock.py +49 -0
  357. wandb/sdk/interface/summary_record.py +67 -0
  358. wandb/sdk/internal/__init__.py +0 -0
  359. wandb/sdk/internal/_generated/__init__.py +15 -0
  360. wandb/sdk/internal/_generated/enums.py +4 -0
  361. wandb/sdk/internal/_generated/input_types.py +4 -0
  362. wandb/sdk/internal/_generated/operations.py +15 -0
  363. wandb/sdk/internal/_generated/server_features_query.py +27 -0
  364. wandb/sdk/internal/context.py +89 -0
  365. wandb/sdk/internal/datastore.py +293 -0
  366. wandb/sdk/internal/file_pusher.py +177 -0
  367. wandb/sdk/internal/file_stream.py +686 -0
  368. wandb/sdk/internal/handler.py +854 -0
  369. wandb/sdk/internal/incremental_table_util.py +53 -0
  370. wandb/sdk/internal/internal_api.py +4723 -0
  371. wandb/sdk/internal/job_builder.py +639 -0
  372. wandb/sdk/internal/profiler.py +79 -0
  373. wandb/sdk/internal/progress.py +77 -0
  374. wandb/sdk/internal/run.py +27 -0
  375. wandb/sdk/internal/sample.py +70 -0
  376. wandb/sdk/internal/sender.py +1692 -0
  377. wandb/sdk/internal/sender_config.py +203 -0
  378. wandb/sdk/internal/settings_static.py +120 -0
  379. wandb/sdk/internal/tb_watcher.py +519 -0
  380. wandb/sdk/internal/thread_local_settings.py +18 -0
  381. wandb/sdk/launch/__init__.py +15 -0
  382. wandb/sdk/launch/_launch.py +331 -0
  383. wandb/sdk/launch/_launch_add.py +255 -0
  384. wandb/sdk/launch/_project_spec.py +565 -0
  385. wandb/sdk/launch/agent/__init__.py +5 -0
  386. wandb/sdk/launch/agent/agent.py +931 -0
  387. wandb/sdk/launch/agent/config.py +296 -0
  388. wandb/sdk/launch/agent/job_status_tracker.py +55 -0
  389. wandb/sdk/launch/agent/run_queue_item_file_saver.py +39 -0
  390. wandb/sdk/launch/builder/__init__.py +0 -0
  391. wandb/sdk/launch/builder/abstract.py +156 -0
  392. wandb/sdk/launch/builder/build.py +296 -0
  393. wandb/sdk/launch/builder/context_manager.py +235 -0
  394. wandb/sdk/launch/builder/docker_builder.py +177 -0
  395. wandb/sdk/launch/builder/kaniko_builder.py +595 -0
  396. wandb/sdk/launch/builder/noop.py +58 -0
  397. wandb/sdk/launch/builder/templates/_wandb_bootstrap.py +188 -0
  398. wandb/sdk/launch/builder/templates/dockerfile.py +92 -0
  399. wandb/sdk/launch/create_job.py +541 -0
  400. wandb/sdk/launch/environment/abstract.py +29 -0
  401. wandb/sdk/launch/environment/aws_environment.py +322 -0
  402. wandb/sdk/launch/environment/azure_environment.py +105 -0
  403. wandb/sdk/launch/environment/gcp_environment.py +334 -0
  404. wandb/sdk/launch/environment/local_environment.py +65 -0
  405. wandb/sdk/launch/errors.py +13 -0
  406. wandb/sdk/launch/git_reference.py +109 -0
  407. wandb/sdk/launch/inputs/files.py +148 -0
  408. wandb/sdk/launch/inputs/internal.py +314 -0
  409. wandb/sdk/launch/inputs/manage.py +113 -0
  410. wandb/sdk/launch/inputs/schema.py +40 -0
  411. wandb/sdk/launch/loader.py +249 -0
  412. wandb/sdk/launch/registry/abstract.py +48 -0
  413. wandb/sdk/launch/registry/anon.py +29 -0
  414. wandb/sdk/launch/registry/azure_container_registry.py +124 -0
  415. wandb/sdk/launch/registry/elastic_container_registry.py +192 -0
  416. wandb/sdk/launch/registry/google_artifact_registry.py +219 -0
  417. wandb/sdk/launch/registry/local_registry.py +65 -0
  418. wandb/sdk/launch/runner/__init__.py +0 -0
  419. wandb/sdk/launch/runner/abstract.py +185 -0
  420. wandb/sdk/launch/runner/kubernetes_monitor.py +473 -0
  421. wandb/sdk/launch/runner/kubernetes_runner.py +1285 -0
  422. wandb/sdk/launch/runner/local_container.py +301 -0
  423. wandb/sdk/launch/runner/local_process.py +78 -0
  424. wandb/sdk/launch/runner/sagemaker_runner.py +424 -0
  425. wandb/sdk/launch/runner/vertex_runner.py +225 -0
  426. wandb/sdk/launch/sweeps/__init__.py +37 -0
  427. wandb/sdk/launch/sweeps/scheduler.py +739 -0
  428. wandb/sdk/launch/sweeps/scheduler_sweep.py +90 -0
  429. wandb/sdk/launch/sweeps/utils.py +324 -0
  430. wandb/sdk/launch/utils.py +746 -0
  431. wandb/sdk/launch/wandb_reference.py +138 -0
  432. wandb/sdk/lib/__init__.py +5 -0
  433. wandb/sdk/lib/apikey.py +334 -0
  434. wandb/sdk/lib/asyncio_compat.py +213 -0
  435. wandb/sdk/lib/asyncio_manager.py +252 -0
  436. wandb/sdk/lib/capped_dict.py +26 -0
  437. wandb/sdk/lib/config_util.py +101 -0
  438. wandb/sdk/lib/console_capture.py +219 -0
  439. wandb/sdk/lib/credentials.py +141 -0
  440. wandb/sdk/lib/deprecate.py +27 -0
  441. wandb/sdk/lib/disabled.py +30 -0
  442. wandb/sdk/lib/exit_hooks.py +54 -0
  443. wandb/sdk/lib/file_stream_utils.py +118 -0
  444. wandb/sdk/lib/filenames.py +64 -0
  445. wandb/sdk/lib/filesystem.py +372 -0
  446. wandb/sdk/lib/fsm.py +165 -0
  447. wandb/sdk/lib/gitlib.py +240 -0
  448. wandb/sdk/lib/gql_request.py +65 -0
  449. wandb/sdk/lib/handler_util.py +21 -0
  450. wandb/sdk/lib/hashutil.py +106 -0
  451. wandb/sdk/lib/import_hooks.py +275 -0
  452. wandb/sdk/lib/interrupt.py +37 -0
  453. wandb/sdk/lib/ipython.py +126 -0
  454. wandb/sdk/lib/json_util.py +75 -0
  455. wandb/sdk/lib/lazyloader.py +63 -0
  456. wandb/sdk/lib/module.py +72 -0
  457. wandb/sdk/lib/paths.py +106 -0
  458. wandb/sdk/lib/preinit.py +42 -0
  459. wandb/sdk/lib/printer.py +571 -0
  460. wandb/sdk/lib/printer_asyncio.py +48 -0
  461. wandb/sdk/lib/progress.py +320 -0
  462. wandb/sdk/lib/proto_util.py +90 -0
  463. wandb/sdk/lib/redirect.py +876 -0
  464. wandb/sdk/lib/retry.py +395 -0
  465. wandb/sdk/lib/run_moment.py +82 -0
  466. wandb/sdk/lib/runid.py +12 -0
  467. wandb/sdk/lib/server.py +58 -0
  468. wandb/sdk/lib/service/ipc_support.py +13 -0
  469. wandb/sdk/lib/service/service_client.py +106 -0
  470. wandb/sdk/lib/service/service_connection.py +192 -0
  471. wandb/sdk/lib/service/service_port_file.py +105 -0
  472. wandb/sdk/lib/service/service_process.py +111 -0
  473. wandb/sdk/lib/service/service_token.py +181 -0
  474. wandb/sdk/lib/sparkline.py +44 -0
  475. wandb/sdk/lib/telemetry.py +100 -0
  476. wandb/sdk/lib/timed_input.py +133 -0
  477. wandb/sdk/lib/timer.py +19 -0
  478. wandb/sdk/lib/wb_logging.py +161 -0
  479. wandb/sdk/mailbox/__init__.py +23 -0
  480. wandb/sdk/mailbox/mailbox.py +143 -0
  481. wandb/sdk/mailbox/mailbox_handle.py +132 -0
  482. wandb/sdk/mailbox/response_handle.py +99 -0
  483. wandb/sdk/mailbox/wait_with_progress.py +100 -0
  484. wandb/sdk/projects/_generated/__init__.py +47 -0
  485. wandb/sdk/projects/_generated/delete_project.py +22 -0
  486. wandb/sdk/projects/_generated/enums.py +4 -0
  487. wandb/sdk/projects/_generated/fetch_registry.py +22 -0
  488. wandb/sdk/projects/_generated/fragments.py +41 -0
  489. wandb/sdk/projects/_generated/input_types.py +13 -0
  490. wandb/sdk/projects/_generated/operations.py +88 -0
  491. wandb/sdk/projects/_generated/rename_project.py +27 -0
  492. wandb/sdk/projects/_generated/upsert_registry_project.py +27 -0
  493. wandb/sdk/verify/__init__.py +0 -0
  494. wandb/sdk/verify/verify.py +555 -0
  495. wandb/sdk/wandb_alerts.py +12 -0
  496. wandb/sdk/wandb_config.py +323 -0
  497. wandb/sdk/wandb_helper.py +54 -0
  498. wandb/sdk/wandb_init.py +1581 -0
  499. wandb/sdk/wandb_login.py +332 -0
  500. wandb/sdk/wandb_metric.py +112 -0
  501. wandb/sdk/wandb_require.py +88 -0
  502. wandb/sdk/wandb_require_helpers.py +44 -0
  503. wandb/sdk/wandb_run.py +4088 -0
  504. wandb/sdk/wandb_settings.py +2105 -0
  505. wandb/sdk/wandb_setup.py +560 -0
  506. wandb/sdk/wandb_summary.py +150 -0
  507. wandb/sdk/wandb_sweep.py +120 -0
  508. wandb/sdk/wandb_sync.py +71 -0
  509. wandb/sdk/wandb_watch.py +146 -0
  510. wandb/sklearn.py +35 -0
  511. wandb/sync/__init__.py +3 -0
  512. wandb/sync/sync.py +452 -0
  513. wandb/trigger.py +29 -0
  514. wandb/util.py +2040 -0
  515. wandb/vendor/__init__.py +0 -0
  516. wandb/vendor/gql-0.2.0/setup.py +40 -0
  517. wandb/vendor/gql-0.2.0/tests/__init__.py +0 -0
  518. wandb/vendor/gql-0.2.0/tests/starwars/__init__.py +0 -0
  519. wandb/vendor/gql-0.2.0/tests/starwars/fixtures.py +96 -0
  520. wandb/vendor/gql-0.2.0/tests/starwars/schema.py +146 -0
  521. wandb/vendor/gql-0.2.0/tests/starwars/test_dsl.py +293 -0
  522. wandb/vendor/gql-0.2.0/tests/starwars/test_query.py +355 -0
  523. wandb/vendor/gql-0.2.0/tests/starwars/test_validation.py +171 -0
  524. wandb/vendor/gql-0.2.0/tests/test_client.py +31 -0
  525. wandb/vendor/gql-0.2.0/tests/test_transport.py +89 -0
  526. wandb/vendor/gql-0.2.0/wandb_gql/__init__.py +4 -0
  527. wandb/vendor/gql-0.2.0/wandb_gql/client.py +75 -0
  528. wandb/vendor/gql-0.2.0/wandb_gql/dsl.py +152 -0
  529. wandb/vendor/gql-0.2.0/wandb_gql/gql.py +10 -0
  530. wandb/vendor/gql-0.2.0/wandb_gql/transport/__init__.py +0 -0
  531. wandb/vendor/gql-0.2.0/wandb_gql/transport/http.py +6 -0
  532. wandb/vendor/gql-0.2.0/wandb_gql/transport/local_schema.py +15 -0
  533. wandb/vendor/gql-0.2.0/wandb_gql/transport/requests.py +46 -0
  534. wandb/vendor/gql-0.2.0/wandb_gql/utils.py +21 -0
  535. wandb/vendor/graphql-core-1.1/setup.py +86 -0
  536. wandb/vendor/graphql-core-1.1/wandb_graphql/__init__.py +287 -0
  537. wandb/vendor/graphql-core-1.1/wandb_graphql/error/__init__.py +6 -0
  538. wandb/vendor/graphql-core-1.1/wandb_graphql/error/base.py +42 -0
  539. wandb/vendor/graphql-core-1.1/wandb_graphql/error/format_error.py +11 -0
  540. wandb/vendor/graphql-core-1.1/wandb_graphql/error/located_error.py +29 -0
  541. wandb/vendor/graphql-core-1.1/wandb_graphql/error/syntax_error.py +36 -0
  542. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/__init__.py +26 -0
  543. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/base.py +311 -0
  544. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executor.py +398 -0
  545. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__init__.py +0 -0
  546. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/asyncio.py +53 -0
  547. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/gevent.py +22 -0
  548. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/process.py +32 -0
  549. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/sync.py +7 -0
  550. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/thread.py +35 -0
  551. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/utils.py +6 -0
  552. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__init__.py +0 -0
  553. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/executor.py +66 -0
  554. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/fragment.py +252 -0
  555. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/resolver.py +151 -0
  556. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/utils.py +7 -0
  557. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/middleware.py +57 -0
  558. wandb/vendor/graphql-core-1.1/wandb_graphql/execution/values.py +145 -0
  559. wandb/vendor/graphql-core-1.1/wandb_graphql/graphql.py +60 -0
  560. wandb/vendor/graphql-core-1.1/wandb_graphql/language/__init__.py +0 -0
  561. wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py +1349 -0
  562. wandb/vendor/graphql-core-1.1/wandb_graphql/language/base.py +19 -0
  563. wandb/vendor/graphql-core-1.1/wandb_graphql/language/lexer.py +435 -0
  564. wandb/vendor/graphql-core-1.1/wandb_graphql/language/location.py +30 -0
  565. wandb/vendor/graphql-core-1.1/wandb_graphql/language/parser.py +779 -0
  566. wandb/vendor/graphql-core-1.1/wandb_graphql/language/printer.py +193 -0
  567. wandb/vendor/graphql-core-1.1/wandb_graphql/language/source.py +18 -0
  568. wandb/vendor/graphql-core-1.1/wandb_graphql/language/visitor.py +222 -0
  569. wandb/vendor/graphql-core-1.1/wandb_graphql/language/visitor_meta.py +82 -0
  570. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__init__.py +0 -0
  571. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/cached_property.py +17 -0
  572. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/contain_subset.py +28 -0
  573. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/default_ordered_dict.py +40 -0
  574. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/ordereddict.py +8 -0
  575. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/pair_set.py +43 -0
  576. wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/version.py +78 -0
  577. wandb/vendor/graphql-core-1.1/wandb_graphql/type/__init__.py +67 -0
  578. wandb/vendor/graphql-core-1.1/wandb_graphql/type/definition.py +619 -0
  579. wandb/vendor/graphql-core-1.1/wandb_graphql/type/directives.py +132 -0
  580. wandb/vendor/graphql-core-1.1/wandb_graphql/type/introspection.py +440 -0
  581. wandb/vendor/graphql-core-1.1/wandb_graphql/type/scalars.py +131 -0
  582. wandb/vendor/graphql-core-1.1/wandb_graphql/type/schema.py +100 -0
  583. wandb/vendor/graphql-core-1.1/wandb_graphql/type/typemap.py +145 -0
  584. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__init__.py +0 -0
  585. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/assert_valid_name.py +9 -0
  586. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_from_value.py +65 -0
  587. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_code.py +49 -0
  588. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_dict.py +24 -0
  589. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/base.py +75 -0
  590. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_ast_schema.py +291 -0
  591. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_client_schema.py +250 -0
  592. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/concat_ast.py +9 -0
  593. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/extend_schema.py +357 -0
  594. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/get_field_def.py +27 -0
  595. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/get_operation_ast.py +21 -0
  596. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/introspection_query.py +90 -0
  597. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_literal_value.py +67 -0
  598. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_value.py +66 -0
  599. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/quoted_or_list.py +21 -0
  600. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/schema_printer.py +168 -0
  601. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/suggestion_list.py +56 -0
  602. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_comparators.py +69 -0
  603. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_from_ast.py +21 -0
  604. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py +149 -0
  605. wandb/vendor/graphql-core-1.1/wandb_graphql/utils/value_from_ast.py +69 -0
  606. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/__init__.py +4 -0
  607. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__init__.py +79 -0
  608. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/arguments_of_correct_type.py +24 -0
  609. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/base.py +8 -0
  610. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/default_values_of_correct_type.py +44 -0
  611. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fields_on_correct_type.py +113 -0
  612. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fragments_on_composite_types.py +33 -0
  613. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_argument_names.py +70 -0
  614. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_directives.py +97 -0
  615. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_fragment_names.py +19 -0
  616. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_type_names.py +43 -0
  617. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/lone_anonymous_operation.py +23 -0
  618. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_fragment_cycles.py +59 -0
  619. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_undefined_variables.py +36 -0
  620. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_fragments.py +38 -0
  621. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_variables.py +37 -0
  622. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/overlapping_fields_can_be_merged.py +529 -0
  623. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/possible_fragment_spreads.py +44 -0
  624. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/provided_non_null_arguments.py +46 -0
  625. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/scalar_leafs.py +33 -0
  626. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_argument_names.py +32 -0
  627. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_fragment_names.py +28 -0
  628. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_input_field_names.py +33 -0
  629. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_operation_names.py +31 -0
  630. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_variable_names.py +27 -0
  631. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_are_input_types.py +21 -0
  632. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_in_allowed_position.py +53 -0
  633. wandb/vendor/graphql-core-1.1/wandb_graphql/validation/validation.py +158 -0
  634. wandb/vendor/promise-2.3.0/conftest.py +30 -0
  635. wandb/vendor/promise-2.3.0/setup.py +64 -0
  636. wandb/vendor/promise-2.3.0/tests/__init__.py +0 -0
  637. wandb/vendor/promise-2.3.0/tests/conftest.py +8 -0
  638. wandb/vendor/promise-2.3.0/tests/test_awaitable.py +32 -0
  639. wandb/vendor/promise-2.3.0/tests/test_awaitable_35.py +47 -0
  640. wandb/vendor/promise-2.3.0/tests/test_benchmark.py +116 -0
  641. wandb/vendor/promise-2.3.0/tests/test_complex_threads.py +23 -0
  642. wandb/vendor/promise-2.3.0/tests/test_dataloader.py +452 -0
  643. wandb/vendor/promise-2.3.0/tests/test_dataloader_awaitable_35.py +99 -0
  644. wandb/vendor/promise-2.3.0/tests/test_dataloader_extra.py +65 -0
  645. wandb/vendor/promise-2.3.0/tests/test_extra.py +670 -0
  646. wandb/vendor/promise-2.3.0/tests/test_issues.py +132 -0
  647. wandb/vendor/promise-2.3.0/tests/test_promise_list.py +70 -0
  648. wandb/vendor/promise-2.3.0/tests/test_spec.py +584 -0
  649. wandb/vendor/promise-2.3.0/tests/test_thread_safety.py +115 -0
  650. wandb/vendor/promise-2.3.0/tests/utils.py +3 -0
  651. wandb/vendor/promise-2.3.0/wandb_promise/__init__.py +38 -0
  652. wandb/vendor/promise-2.3.0/wandb_promise/async_.py +135 -0
  653. wandb/vendor/promise-2.3.0/wandb_promise/compat.py +32 -0
  654. wandb/vendor/promise-2.3.0/wandb_promise/dataloader.py +326 -0
  655. wandb/vendor/promise-2.3.0/wandb_promise/iterate_promise.py +12 -0
  656. wandb/vendor/promise-2.3.0/wandb_promise/promise.py +848 -0
  657. wandb/vendor/promise-2.3.0/wandb_promise/promise_list.py +151 -0
  658. wandb/vendor/promise-2.3.0/wandb_promise/pyutils/__init__.py +0 -0
  659. wandb/vendor/promise-2.3.0/wandb_promise/pyutils/version.py +83 -0
  660. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/__init__.py +0 -0
  661. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/asyncio.py +22 -0
  662. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/gevent.py +21 -0
  663. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/immediate.py +27 -0
  664. wandb/vendor/promise-2.3.0/wandb_promise/schedulers/thread.py +18 -0
  665. wandb/vendor/promise-2.3.0/wandb_promise/utils.py +56 -0
  666. wandb/vendor/pygments/__init__.py +90 -0
  667. wandb/vendor/pygments/cmdline.py +568 -0
  668. wandb/vendor/pygments/console.py +74 -0
  669. wandb/vendor/pygments/filter.py +74 -0
  670. wandb/vendor/pygments/filters/__init__.py +350 -0
  671. wandb/vendor/pygments/formatter.py +95 -0
  672. wandb/vendor/pygments/formatters/__init__.py +153 -0
  673. wandb/vendor/pygments/formatters/_mapping.py +85 -0
  674. wandb/vendor/pygments/formatters/bbcode.py +109 -0
  675. wandb/vendor/pygments/formatters/html.py +851 -0
  676. wandb/vendor/pygments/formatters/img.py +600 -0
  677. wandb/vendor/pygments/formatters/irc.py +182 -0
  678. wandb/vendor/pygments/formatters/latex.py +482 -0
  679. wandb/vendor/pygments/formatters/other.py +160 -0
  680. wandb/vendor/pygments/formatters/rtf.py +147 -0
  681. wandb/vendor/pygments/formatters/svg.py +153 -0
  682. wandb/vendor/pygments/formatters/terminal.py +136 -0
  683. wandb/vendor/pygments/formatters/terminal256.py +309 -0
  684. wandb/vendor/pygments/lexer.py +871 -0
  685. wandb/vendor/pygments/lexers/__init__.py +329 -0
  686. wandb/vendor/pygments/lexers/_asy_builtins.py +1645 -0
  687. wandb/vendor/pygments/lexers/_cl_builtins.py +232 -0
  688. wandb/vendor/pygments/lexers/_cocoa_builtins.py +72 -0
  689. wandb/vendor/pygments/lexers/_csound_builtins.py +1346 -0
  690. wandb/vendor/pygments/lexers/_lasso_builtins.py +5327 -0
  691. wandb/vendor/pygments/lexers/_lua_builtins.py +295 -0
  692. wandb/vendor/pygments/lexers/_mapping.py +500 -0
  693. wandb/vendor/pygments/lexers/_mql_builtins.py +1172 -0
  694. wandb/vendor/pygments/lexers/_openedge_builtins.py +2547 -0
  695. wandb/vendor/pygments/lexers/_php_builtins.py +4756 -0
  696. wandb/vendor/pygments/lexers/_postgres_builtins.py +621 -0
  697. wandb/vendor/pygments/lexers/_scilab_builtins.py +3094 -0
  698. wandb/vendor/pygments/lexers/_sourcemod_builtins.py +1163 -0
  699. wandb/vendor/pygments/lexers/_stan_builtins.py +532 -0
  700. wandb/vendor/pygments/lexers/_stata_builtins.py +419 -0
  701. wandb/vendor/pygments/lexers/_tsql_builtins.py +1004 -0
  702. wandb/vendor/pygments/lexers/_vim_builtins.py +1939 -0
  703. wandb/vendor/pygments/lexers/actionscript.py +240 -0
  704. wandb/vendor/pygments/lexers/agile.py +24 -0
  705. wandb/vendor/pygments/lexers/algebra.py +221 -0
  706. wandb/vendor/pygments/lexers/ambient.py +76 -0
  707. wandb/vendor/pygments/lexers/ampl.py +87 -0
  708. wandb/vendor/pygments/lexers/apl.py +101 -0
  709. wandb/vendor/pygments/lexers/archetype.py +318 -0
  710. wandb/vendor/pygments/lexers/asm.py +641 -0
  711. wandb/vendor/pygments/lexers/automation.py +374 -0
  712. wandb/vendor/pygments/lexers/basic.py +500 -0
  713. wandb/vendor/pygments/lexers/bibtex.py +160 -0
  714. wandb/vendor/pygments/lexers/business.py +612 -0
  715. wandb/vendor/pygments/lexers/c_cpp.py +252 -0
  716. wandb/vendor/pygments/lexers/c_like.py +541 -0
  717. wandb/vendor/pygments/lexers/capnproto.py +78 -0
  718. wandb/vendor/pygments/lexers/chapel.py +102 -0
  719. wandb/vendor/pygments/lexers/clean.py +288 -0
  720. wandb/vendor/pygments/lexers/compiled.py +34 -0
  721. wandb/vendor/pygments/lexers/configs.py +833 -0
  722. wandb/vendor/pygments/lexers/console.py +114 -0
  723. wandb/vendor/pygments/lexers/crystal.py +393 -0
  724. wandb/vendor/pygments/lexers/csound.py +366 -0
  725. wandb/vendor/pygments/lexers/css.py +689 -0
  726. wandb/vendor/pygments/lexers/d.py +251 -0
  727. wandb/vendor/pygments/lexers/dalvik.py +125 -0
  728. wandb/vendor/pygments/lexers/data.py +555 -0
  729. wandb/vendor/pygments/lexers/diff.py +165 -0
  730. wandb/vendor/pygments/lexers/dotnet.py +691 -0
  731. wandb/vendor/pygments/lexers/dsls.py +878 -0
  732. wandb/vendor/pygments/lexers/dylan.py +289 -0
  733. wandb/vendor/pygments/lexers/ecl.py +125 -0
  734. wandb/vendor/pygments/lexers/eiffel.py +65 -0
  735. wandb/vendor/pygments/lexers/elm.py +121 -0
  736. wandb/vendor/pygments/lexers/erlang.py +533 -0
  737. wandb/vendor/pygments/lexers/esoteric.py +277 -0
  738. wandb/vendor/pygments/lexers/ezhil.py +69 -0
  739. wandb/vendor/pygments/lexers/factor.py +344 -0
  740. wandb/vendor/pygments/lexers/fantom.py +250 -0
  741. wandb/vendor/pygments/lexers/felix.py +273 -0
  742. wandb/vendor/pygments/lexers/forth.py +177 -0
  743. wandb/vendor/pygments/lexers/fortran.py +205 -0
  744. wandb/vendor/pygments/lexers/foxpro.py +428 -0
  745. wandb/vendor/pygments/lexers/functional.py +21 -0
  746. wandb/vendor/pygments/lexers/go.py +101 -0
  747. wandb/vendor/pygments/lexers/grammar_notation.py +213 -0
  748. wandb/vendor/pygments/lexers/graph.py +80 -0
  749. wandb/vendor/pygments/lexers/graphics.py +553 -0
  750. wandb/vendor/pygments/lexers/haskell.py +843 -0
  751. wandb/vendor/pygments/lexers/haxe.py +936 -0
  752. wandb/vendor/pygments/lexers/hdl.py +382 -0
  753. wandb/vendor/pygments/lexers/hexdump.py +103 -0
  754. wandb/vendor/pygments/lexers/html.py +602 -0
  755. wandb/vendor/pygments/lexers/idl.py +270 -0
  756. wandb/vendor/pygments/lexers/igor.py +288 -0
  757. wandb/vendor/pygments/lexers/inferno.py +96 -0
  758. wandb/vendor/pygments/lexers/installers.py +322 -0
  759. wandb/vendor/pygments/lexers/int_fiction.py +1343 -0
  760. wandb/vendor/pygments/lexers/iolang.py +63 -0
  761. wandb/vendor/pygments/lexers/j.py +146 -0
  762. wandb/vendor/pygments/lexers/javascript.py +1525 -0
  763. wandb/vendor/pygments/lexers/julia.py +333 -0
  764. wandb/vendor/pygments/lexers/jvm.py +1573 -0
  765. wandb/vendor/pygments/lexers/lisp.py +2621 -0
  766. wandb/vendor/pygments/lexers/make.py +202 -0
  767. wandb/vendor/pygments/lexers/markup.py +595 -0
  768. wandb/vendor/pygments/lexers/math.py +21 -0
  769. wandb/vendor/pygments/lexers/matlab.py +663 -0
  770. wandb/vendor/pygments/lexers/ml.py +769 -0
  771. wandb/vendor/pygments/lexers/modeling.py +358 -0
  772. wandb/vendor/pygments/lexers/modula2.py +1561 -0
  773. wandb/vendor/pygments/lexers/monte.py +204 -0
  774. wandb/vendor/pygments/lexers/ncl.py +894 -0
  775. wandb/vendor/pygments/lexers/nimrod.py +159 -0
  776. wandb/vendor/pygments/lexers/nit.py +64 -0
  777. wandb/vendor/pygments/lexers/nix.py +136 -0
  778. wandb/vendor/pygments/lexers/oberon.py +105 -0
  779. wandb/vendor/pygments/lexers/objective.py +504 -0
  780. wandb/vendor/pygments/lexers/ooc.py +85 -0
  781. wandb/vendor/pygments/lexers/other.py +41 -0
  782. wandb/vendor/pygments/lexers/parasail.py +79 -0
  783. wandb/vendor/pygments/lexers/parsers.py +835 -0
  784. wandb/vendor/pygments/lexers/pascal.py +644 -0
  785. wandb/vendor/pygments/lexers/pawn.py +199 -0
  786. wandb/vendor/pygments/lexers/perl.py +620 -0
  787. wandb/vendor/pygments/lexers/php.py +267 -0
  788. wandb/vendor/pygments/lexers/praat.py +294 -0
  789. wandb/vendor/pygments/lexers/prolog.py +306 -0
  790. wandb/vendor/pygments/lexers/python.py +939 -0
  791. wandb/vendor/pygments/lexers/qvt.py +152 -0
  792. wandb/vendor/pygments/lexers/r.py +453 -0
  793. wandb/vendor/pygments/lexers/rdf.py +270 -0
  794. wandb/vendor/pygments/lexers/rebol.py +431 -0
  795. wandb/vendor/pygments/lexers/resource.py +85 -0
  796. wandb/vendor/pygments/lexers/rnc.py +67 -0
  797. wandb/vendor/pygments/lexers/roboconf.py +82 -0
  798. wandb/vendor/pygments/lexers/robotframework.py +560 -0
  799. wandb/vendor/pygments/lexers/ruby.py +519 -0
  800. wandb/vendor/pygments/lexers/rust.py +220 -0
  801. wandb/vendor/pygments/lexers/sas.py +228 -0
  802. wandb/vendor/pygments/lexers/scripting.py +1222 -0
  803. wandb/vendor/pygments/lexers/shell.py +794 -0
  804. wandb/vendor/pygments/lexers/smalltalk.py +195 -0
  805. wandb/vendor/pygments/lexers/smv.py +79 -0
  806. wandb/vendor/pygments/lexers/snobol.py +83 -0
  807. wandb/vendor/pygments/lexers/special.py +103 -0
  808. wandb/vendor/pygments/lexers/sql.py +681 -0
  809. wandb/vendor/pygments/lexers/stata.py +108 -0
  810. wandb/vendor/pygments/lexers/supercollider.py +90 -0
  811. wandb/vendor/pygments/lexers/tcl.py +145 -0
  812. wandb/vendor/pygments/lexers/templates.py +2283 -0
  813. wandb/vendor/pygments/lexers/testing.py +207 -0
  814. wandb/vendor/pygments/lexers/text.py +25 -0
  815. wandb/vendor/pygments/lexers/textedit.py +169 -0
  816. wandb/vendor/pygments/lexers/textfmts.py +297 -0
  817. wandb/vendor/pygments/lexers/theorem.py +458 -0
  818. wandb/vendor/pygments/lexers/trafficscript.py +54 -0
  819. wandb/vendor/pygments/lexers/typoscript.py +226 -0
  820. wandb/vendor/pygments/lexers/urbi.py +133 -0
  821. wandb/vendor/pygments/lexers/varnish.py +190 -0
  822. wandb/vendor/pygments/lexers/verification.py +111 -0
  823. wandb/vendor/pygments/lexers/web.py +24 -0
  824. wandb/vendor/pygments/lexers/webmisc.py +988 -0
  825. wandb/vendor/pygments/lexers/whiley.py +116 -0
  826. wandb/vendor/pygments/lexers/x10.py +69 -0
  827. wandb/vendor/pygments/modeline.py +44 -0
  828. wandb/vendor/pygments/plugin.py +68 -0
  829. wandb/vendor/pygments/regexopt.py +92 -0
  830. wandb/vendor/pygments/scanner.py +105 -0
  831. wandb/vendor/pygments/sphinxext.py +158 -0
  832. wandb/vendor/pygments/style.py +155 -0
  833. wandb/vendor/pygments/styles/__init__.py +80 -0
  834. wandb/vendor/pygments/styles/abap.py +29 -0
  835. wandb/vendor/pygments/styles/algol.py +63 -0
  836. wandb/vendor/pygments/styles/algol_nu.py +63 -0
  837. wandb/vendor/pygments/styles/arduino.py +98 -0
  838. wandb/vendor/pygments/styles/autumn.py +65 -0
  839. wandb/vendor/pygments/styles/borland.py +51 -0
  840. wandb/vendor/pygments/styles/bw.py +49 -0
  841. wandb/vendor/pygments/styles/colorful.py +81 -0
  842. wandb/vendor/pygments/styles/default.py +73 -0
  843. wandb/vendor/pygments/styles/emacs.py +72 -0
  844. wandb/vendor/pygments/styles/friendly.py +72 -0
  845. wandb/vendor/pygments/styles/fruity.py +42 -0
  846. wandb/vendor/pygments/styles/igor.py +29 -0
  847. wandb/vendor/pygments/styles/lovelace.py +97 -0
  848. wandb/vendor/pygments/styles/manni.py +75 -0
  849. wandb/vendor/pygments/styles/monokai.py +106 -0
  850. wandb/vendor/pygments/styles/murphy.py +80 -0
  851. wandb/vendor/pygments/styles/native.py +65 -0
  852. wandb/vendor/pygments/styles/paraiso_dark.py +125 -0
  853. wandb/vendor/pygments/styles/paraiso_light.py +125 -0
  854. wandb/vendor/pygments/styles/pastie.py +75 -0
  855. wandb/vendor/pygments/styles/perldoc.py +69 -0
  856. wandb/vendor/pygments/styles/rainbow_dash.py +89 -0
  857. wandb/vendor/pygments/styles/rrt.py +33 -0
  858. wandb/vendor/pygments/styles/sas.py +44 -0
  859. wandb/vendor/pygments/styles/stata.py +40 -0
  860. wandb/vendor/pygments/styles/tango.py +141 -0
  861. wandb/vendor/pygments/styles/trac.py +63 -0
  862. wandb/vendor/pygments/styles/vim.py +63 -0
  863. wandb/vendor/pygments/styles/vs.py +38 -0
  864. wandb/vendor/pygments/styles/xcode.py +51 -0
  865. wandb/vendor/pygments/token.py +213 -0
  866. wandb/vendor/pygments/unistring.py +217 -0
  867. wandb/vendor/pygments/util.py +388 -0
  868. wandb/vendor/watchdog_0_9_0/wandb_watchdog/__init__.py +17 -0
  869. wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py +615 -0
  870. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/__init__.py +98 -0
  871. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/api.py +369 -0
  872. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/fsevents.py +172 -0
  873. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/fsevents2.py +239 -0
  874. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify.py +218 -0
  875. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify_buffer.py +81 -0
  876. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify_c.py +575 -0
  877. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/kqueue.py +730 -0
  878. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/polling.py +145 -0
  879. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/read_directory_changes.py +133 -0
  880. wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/winapi.py +348 -0
  881. wandb/vendor/watchdog_0_9_0/wandb_watchdog/patterns.py +265 -0
  882. wandb/vendor/watchdog_0_9_0/wandb_watchdog/tricks/__init__.py +174 -0
  883. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/__init__.py +151 -0
  884. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/bricks.py +249 -0
  885. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/compat.py +29 -0
  886. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/decorators.py +198 -0
  887. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/delayed_queue.py +88 -0
  888. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/dirsnapshot.py +293 -0
  889. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/echo.py +157 -0
  890. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/event_backport.py +41 -0
  891. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/importlib2.py +40 -0
  892. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/platform.py +57 -0
  893. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/unicode_paths.py +64 -0
  894. wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/win32stat.py +123 -0
  895. wandb/vendor/watchdog_0_9_0/wandb_watchdog/version.py +28 -0
  896. wandb/vendor/watchdog_0_9_0/wandb_watchdog/watchmedo.py +577 -0
  897. wandb/wandb_agent.py +580 -0
  898. wandb/wandb_controller.py +719 -0
  899. wandb/wandb_run.py +8 -0
  900. wandb-0.21.2.dist-info/METADATA +223 -0
  901. wandb-0.21.2.dist-info/RECORD +904 -0
  902. wandb-0.21.2.dist-info/WHEEL +4 -0
  903. wandb-0.21.2.dist-info/entry_points.txt +3 -0
  904. wandb-0.21.2.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,2702 @@
1
+ """Artifact class."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import atexit
6
+ import concurrent.futures
7
+ import contextlib
8
+ import json
9
+ import logging
10
+ import multiprocessing.dummy
11
+ import os
12
+ import re
13
+ import shutil
14
+ import stat
15
+ import tempfile
16
+ import time
17
+ from collections import deque
18
+ from copy import copy
19
+ from dataclasses import dataclass
20
+ from datetime import timedelta
21
+ from functools import partial
22
+ from itertools import filterfalse
23
+ from pathlib import Path, PurePosixPath
24
+ from typing import (
25
+ IO,
26
+ TYPE_CHECKING,
27
+ Any,
28
+ Final,
29
+ Iterator,
30
+ Literal,
31
+ Sequence,
32
+ Type,
33
+ cast,
34
+ final,
35
+ )
36
+ from urllib.parse import quote, urljoin, urlparse
37
+
38
+ import requests
39
+
40
+ import wandb
41
+ from wandb import data_types, env
42
+ from wandb._iterutils import one
43
+ from wandb.apis.normalize import normalize_exceptions
44
+ from wandb.apis.public import ArtifactCollection, ArtifactFiles, Run
45
+ from wandb.apis.public.utils import gql_compat
46
+ from wandb.data_types import WBValue
47
+ from wandb.errors import CommError
48
+ from wandb.errors.errors import UnsupportedError
49
+ from wandb.errors.term import termerror, termlog, termwarn
50
+ from wandb.proto import wandb_internal_pb2 as pb
51
+ from wandb.proto.wandb_deprecated import Deprecated
52
+ from wandb.sdk import wandb_setup
53
+ from wandb.sdk.data_types._dtypes import Type as WBType
54
+ from wandb.sdk.data_types._dtypes import TypeRegistry
55
+ from wandb.sdk.internal.internal_api import Api as InternalApi
56
+ from wandb.sdk.internal.thread_local_settings import _thread_local_api_settings
57
+ from wandb.sdk.lib import filesystem, retry, runid, telemetry
58
+ from wandb.sdk.lib.deprecate import deprecate
59
+ from wandb.sdk.lib.hashutil import B64MD5, b64_to_hex_id, md5_file_b64
60
+ from wandb.sdk.lib.paths import FilePathStr, LogicalPath, StrPath, URIStr
61
+ from wandb.sdk.lib.runid import generate_id
62
+ from wandb.sdk.mailbox import MailboxHandle
63
+ from wandb.util import (
64
+ alias_is_version_index,
65
+ artifact_to_json,
66
+ fsync_open,
67
+ json_dumps_safer,
68
+ uri_from_path,
69
+ vendor_setup,
70
+ )
71
+
72
+ from ._factories import make_storage_policy
73
+ from ._generated import (
74
+ ADD_ALIASES_GQL,
75
+ ARTIFACT_BY_ID_GQL,
76
+ ARTIFACT_BY_NAME_GQL,
77
+ ARTIFACT_COLLECTION_MEMBERSHIP_FILE_URLS_GQL,
78
+ ARTIFACT_CREATED_BY_GQL,
79
+ ARTIFACT_FILE_URLS_GQL,
80
+ ARTIFACT_TYPE_GQL,
81
+ ARTIFACT_USED_BY_GQL,
82
+ ARTIFACT_VIA_MEMBERSHIP_BY_NAME_GQL,
83
+ DELETE_ALIASES_GQL,
84
+ DELETE_ARTIFACT_GQL,
85
+ FETCH_ARTIFACT_MANIFEST_GQL,
86
+ FETCH_LINKED_ARTIFACTS_GQL,
87
+ LINK_ARTIFACT_GQL,
88
+ UNLINK_ARTIFACT_GQL,
89
+ UPDATE_ARTIFACT_GQL,
90
+ ArtifactAliasInput,
91
+ ArtifactByID,
92
+ ArtifactByName,
93
+ ArtifactCollectionAliasInput,
94
+ ArtifactCollectionMembershipFileUrls,
95
+ ArtifactCreatedBy,
96
+ ArtifactFileUrls,
97
+ ArtifactFragment,
98
+ ArtifactType,
99
+ ArtifactUsedBy,
100
+ ArtifactViaMembershipByName,
101
+ FetchArtifactManifest,
102
+ FetchLinkedArtifacts,
103
+ FileUrlsFragment,
104
+ LinkArtifact,
105
+ LinkArtifactInput,
106
+ MembershipWithArtifact,
107
+ TagInput,
108
+ UpdateArtifact,
109
+ )
110
+ from ._graphql_fragments import omit_artifact_fields
111
+ from ._validators import (
112
+ LINKED_ARTIFACT_COLLECTION_TYPE,
113
+ ArtifactPath,
114
+ _LinkArtifactFields,
115
+ ensure_logged,
116
+ ensure_not_finalized,
117
+ is_artifact_registry_project,
118
+ remove_registry_prefix,
119
+ validate_aliases,
120
+ validate_artifact_name,
121
+ validate_artifact_type,
122
+ validate_metadata,
123
+ validate_tags,
124
+ validate_ttl_duration_seconds,
125
+ )
126
+ from .artifact_download_logger import ArtifactDownloadLogger
127
+ from .artifact_instance_cache import artifact_instance_cache
128
+ from .artifact_manifest import ArtifactManifest
129
+ from .artifact_manifest_entry import ArtifactManifestEntry
130
+ from .artifact_manifests.artifact_manifest_v1 import ArtifactManifestV1
131
+ from .artifact_state import ArtifactState
132
+ from .artifact_ttl import ArtifactTTL
133
+ from .exceptions import (
134
+ ArtifactNotLoggedError,
135
+ TooFewItemsError,
136
+ TooManyItemsError,
137
+ WaitTimeoutError,
138
+ )
139
+ from .staging import get_staging_dir
140
+ from .storage_handlers.gcs_handler import _GCSIsADirectoryError
141
+
142
+ reset_path = vendor_setup()
143
+
144
+ from wandb_gql import gql # noqa: E402
145
+
146
+ reset_path()
147
+
148
+ if TYPE_CHECKING:
149
+ from wandb.apis.public import RetryingClient
150
+
151
+ logger = logging.getLogger(__name__)
152
+
153
+
154
+ _MB: Final[int] = 1024 * 1024
155
+
156
+
157
+ @final
158
+ @dataclass
159
+ class _DeferredArtifactManifest:
160
+ """A lightweight wrapper around the manifest URL, used to indicate deferred loading of the actual manifest."""
161
+
162
+ url: str
163
+
164
+
165
+ class Artifact:
166
+ """Flexible and lightweight building block for dataset and model versioning.
167
+
168
+ Construct an empty W&B Artifact. Populate an artifacts contents with methods that
169
+ begin with `add`. Once the artifact has all the desired files, you can call
170
+ `run.log_artifact()` to log it.
171
+
172
+ Args:
173
+ name (str): A human-readable name for the artifact. Use the name to identify
174
+ a specific artifact in the W&B App UI or programmatically. You can
175
+ interactively reference an artifact with the `use_artifact` Public API.
176
+ A name can contain letters, numbers, underscores, hyphens, and dots.
177
+ The name must be unique across a project.
178
+ type (str): The artifact's type. Use the type of an artifact to both organize
179
+ and differentiate artifacts. You can use any string that contains letters,
180
+ numbers, underscores, hyphens, and dots. Common types include `dataset` or `model`.
181
+ Include `model` within your type string if you want to link the artifact
182
+ to the W&B Model Registry. Note that some types reserved for internal use
183
+ and cannot be set by users. Such types include `job` and types that start with `wandb-`.
184
+ description (str | None) = None: A description of the artifact. For Model or Dataset Artifacts,
185
+ add documentation for your standardized team model or dataset card. View
186
+ an artifact's description programmatically with the `Artifact.description`
187
+ attribute or programmatically with the W&B App UI. W&B renders the
188
+ description as markdown in the W&B App.
189
+ metadata (dict[str, Any] | None) = None: Additional information about an artifact. Specify metadata as a
190
+ dictionary of key-value pairs. You can specify no more than 100 total keys.
191
+ incremental: Use `Artifact.new_draft()` method instead to modify an
192
+ existing artifact.
193
+ use_as: Deprecated.
194
+ is_link: Boolean indication of if the artifact is a linked artifact(`True`) or source artifact(`False`).
195
+
196
+ Returns:
197
+ An `Artifact` object.
198
+ """
199
+
200
+ _TMP_DIR = tempfile.TemporaryDirectory("wandb-artifacts")
201
+ atexit.register(_TMP_DIR.cleanup)
202
+
203
+ def __init__(
204
+ self,
205
+ name: str,
206
+ type: str,
207
+ description: str | None = None,
208
+ metadata: dict[str, Any] | None = None,
209
+ incremental: bool = False,
210
+ use_as: str | None = None,
211
+ ) -> None:
212
+ if not re.match(r"^[a-zA-Z0-9_\-.]+$", name):
213
+ raise ValueError(
214
+ f"Artifact name may only contain alphanumeric characters, dashes, "
215
+ f"underscores, and dots. Invalid name: {name}"
216
+ )
217
+
218
+ from wandb.sdk.artifacts._internal_artifact import InternalArtifact
219
+
220
+ if incremental and not isinstance(self, InternalArtifact):
221
+ termwarn("Using experimental arg `incremental`")
222
+
223
+ # Internal.
224
+ self._client: RetryingClient | None = None
225
+
226
+ self._tmp_dir: tempfile.TemporaryDirectory | None = None
227
+ self._added_objs: dict[int, tuple[WBValue, ArtifactManifestEntry]] = {}
228
+ self._added_local_paths: dict[str, ArtifactManifestEntry] = {}
229
+ self._save_handle: MailboxHandle[pb.Result] | None = None
230
+ self._download_roots: set[str] = set()
231
+ # Set by new_draft(), otherwise the latest artifact will be used as the base.
232
+ self._base_id: str | None = None
233
+ # Properties.
234
+ self._id: str | None = None
235
+ self._client_id: str = runid.generate_id(128)
236
+ self._sequence_client_id: str = runid.generate_id(128)
237
+ self._entity: str | None = None
238
+ self._project: str | None = None
239
+ self._name: str = validate_artifact_name(name) # includes version after saving
240
+ self._version: str | None = None
241
+ self._source_entity: str | None = None
242
+ self._source_project: str | None = None
243
+ self._source_name: str = name # includes version after saving
244
+ self._source_version: str | None = None
245
+ self._source_artifact: Artifact | None = None
246
+ self._is_link: bool = False
247
+ self._type: str = validate_artifact_type(type, name)
248
+ self._description: str | None = description
249
+ self._metadata: dict[str, Any] = validate_metadata(metadata)
250
+ self._ttl_duration_seconds: int | None = None
251
+ self._ttl_is_inherited: bool = True
252
+ self._ttl_changed: bool = False
253
+ self._aliases: list[str] = []
254
+ self._saved_aliases: list[str] = []
255
+ self._tags: list[str] = []
256
+ self._saved_tags: list[str] = []
257
+ self._distributed_id: str | None = None
258
+ self._incremental: bool = incremental
259
+ if use_as is not None:
260
+ deprecate(
261
+ field_name=Deprecated.artifact__init_use_as,
262
+ warning_message=(
263
+ "`use_as` argument is deprecated and does not affect the behaviour of `wandb.Artifact()`"
264
+ ),
265
+ )
266
+ self._use_as: str | None = None
267
+ self._state: ArtifactState = ArtifactState.PENDING
268
+ self._manifest: ArtifactManifest | _DeferredArtifactManifest | None = (
269
+ ArtifactManifestV1(storage_policy=make_storage_policy())
270
+ )
271
+ self._commit_hash: str | None = None
272
+ self._file_count: int | None = None
273
+ self._created_at: str | None = None
274
+ self._updated_at: str | None = None
275
+ self._final: bool = False
276
+ self._history_step: int | None = None
277
+ self._linked_artifacts: list[Artifact] = []
278
+
279
+ # Cache.
280
+ artifact_instance_cache[self._client_id] = self
281
+
282
+ def __repr__(self) -> str:
283
+ return f"<Artifact {self.id or self.name}>"
284
+
285
+ @classmethod
286
+ def _from_id(cls, artifact_id: str, client: RetryingClient) -> Artifact | None:
287
+ if (artifact := artifact_instance_cache.get(artifact_id)) is not None:
288
+ return artifact
289
+
290
+ query = gql_compat(ARTIFACT_BY_ID_GQL, omit_fields=omit_artifact_fields())
291
+
292
+ data = client.execute(query, variable_values={"id": artifact_id})
293
+ result = ArtifactByID.model_validate(data)
294
+
295
+ if (art := result.artifact) is None:
296
+ return None
297
+
298
+ src_collection = art.artifact_sequence
299
+ src_project = src_collection.project
300
+
301
+ entity_name = src_project.entity_name if src_project else ""
302
+ project_name = src_project.name if src_project else ""
303
+
304
+ name = f"{src_collection.name}:v{art.version_index}"
305
+ return cls._from_attrs(entity_name, project_name, name, art, client)
306
+
307
+ @classmethod
308
+ def _membership_from_name(
309
+ cls,
310
+ *,
311
+ entity: str,
312
+ project: str,
313
+ name: str,
314
+ client: RetryingClient,
315
+ ) -> Artifact:
316
+ if not (api := InternalApi())._server_supports(
317
+ pb.ServerFeature.PROJECT_ARTIFACT_COLLECTION_MEMBERSHIP
318
+ ):
319
+ raise UnsupportedError(
320
+ "querying for the artifact collection membership is not supported "
321
+ "by this version of wandb server. Consider updating to the latest version."
322
+ )
323
+
324
+ query = gql_compat(
325
+ ARTIFACT_VIA_MEMBERSHIP_BY_NAME_GQL,
326
+ omit_fields=omit_artifact_fields(api=api),
327
+ )
328
+
329
+ gql_vars = {"entityName": entity, "projectName": project, "name": name}
330
+ data = client.execute(query, variable_values=gql_vars)
331
+ result = ArtifactViaMembershipByName.model_validate(data)
332
+
333
+ if not (project_attrs := result.project):
334
+ raise ValueError(f"project {project!r} not found under entity {entity!r}")
335
+
336
+ if not (acm_attrs := project_attrs.artifact_collection_membership):
337
+ entity_project = f"{entity}/{project}"
338
+ raise ValueError(
339
+ f"artifact membership {name!r} not found in {entity_project!r}"
340
+ )
341
+
342
+ target_path = ArtifactPath(prefix=entity, project=project, name=name)
343
+ return cls._from_membership(acm_attrs, target=target_path, client=client)
344
+
345
+ @classmethod
346
+ def _from_name(
347
+ cls,
348
+ *,
349
+ entity: str,
350
+ project: str,
351
+ name: str,
352
+ client: RetryingClient,
353
+ enable_tracking: bool = False,
354
+ ) -> Artifact:
355
+ if (api := InternalApi())._server_supports(
356
+ pb.ServerFeature.PROJECT_ARTIFACT_COLLECTION_MEMBERSHIP
357
+ ):
358
+ return cls._membership_from_name(
359
+ entity=entity, project=project, name=name, client=client
360
+ )
361
+
362
+ supports_enable_tracking_gql_var = api.server_project_type_introspection()
363
+ omit_vars = None if supports_enable_tracking_gql_var else {"enableTracking"}
364
+
365
+ gql_vars = {
366
+ "entityName": entity,
367
+ "projectName": project,
368
+ "name": name,
369
+ "enableTracking": enable_tracking,
370
+ }
371
+ query = gql_compat(
372
+ ARTIFACT_BY_NAME_GQL,
373
+ omit_variables=omit_vars,
374
+ omit_fields=omit_artifact_fields(api=api),
375
+ )
376
+
377
+ data = client.execute(query, variable_values=gql_vars)
378
+ result = ArtifactByName.model_validate(data)
379
+
380
+ if not (proj_attrs := result.project):
381
+ raise ValueError(f"project {project!r} not found under entity {entity!r}")
382
+
383
+ if not (art_attrs := proj_attrs.artifact):
384
+ entity_project = f"{entity}/{project}"
385
+ raise ValueError(f"artifact {name!r} not found in {entity_project!r}")
386
+
387
+ return cls._from_attrs(entity, project, name, art_attrs, client)
388
+
389
+ @classmethod
390
+ def _from_membership(
391
+ cls,
392
+ membership: MembershipWithArtifact,
393
+ target: ArtifactPath,
394
+ client: RetryingClient,
395
+ ) -> Artifact:
396
+ if not (
397
+ (collection := membership.artifact_collection)
398
+ and (name := collection.name)
399
+ and (proj := collection.project)
400
+ ):
401
+ raise ValueError("Missing artifact collection project in GraphQL response")
402
+
403
+ if is_artifact_registry_project(proj.name) and (
404
+ target.project == "model-registry"
405
+ ):
406
+ wandb.termwarn(
407
+ "This model registry has been migrated and will be discontinued. "
408
+ f"Your request was redirected to the corresponding artifact {name!r} in the new registry. "
409
+ f"Please update your paths to point to the migrated registry directly, '{proj.name}/{name}'."
410
+ )
411
+ new_entity, new_project = proj.entity_name, proj.name
412
+ else:
413
+ new_entity = cast(str, target.prefix)
414
+ new_project = cast(str, target.project)
415
+
416
+ if not (artifact := membership.artifact):
417
+ raise ValueError(f"Artifact {target.to_str()!r} not found in response")
418
+
419
+ return cls._from_attrs(new_entity, new_project, target.name, artifact, client)
420
+
421
+ @classmethod
422
+ def _from_attrs(
423
+ cls,
424
+ entity: str,
425
+ project: str,
426
+ name: str,
427
+ attrs: dict[str, Any] | ArtifactFragment,
428
+ client: RetryingClient,
429
+ aliases: list[str] | None = None,
430
+ ) -> Artifact:
431
+ # Placeholder is required to skip validation.
432
+ artifact = cls("placeholder", type="placeholder")
433
+ artifact._client = client
434
+ artifact._entity = entity
435
+ artifact._project = project
436
+ artifact._name = name
437
+
438
+ validated_attrs = ArtifactFragment.model_validate(attrs)
439
+ artifact._assign_attrs(validated_attrs, aliases)
440
+
441
+ artifact.finalize()
442
+
443
+ # Cache.
444
+ assert artifact.id is not None
445
+ artifact_instance_cache[artifact.id] = artifact
446
+ return artifact
447
+
448
+ # TODO: Eventually factor out is_link. Have to currently use it since some forms of fetching the artifact
449
+ # doesn't make it clear if the artifact is a link or not and have to manually set it.
450
+ def _assign_attrs(
451
+ self,
452
+ art: ArtifactFragment,
453
+ aliases: list[str] | None = None,
454
+ is_link: bool | None = None,
455
+ ) -> None:
456
+ """Update this Artifact's attributes using the server response."""
457
+ self._id = art.id
458
+
459
+ src_collection = art.artifact_sequence
460
+ src_project = src_collection.project
461
+
462
+ self._source_entity = src_project.entity_name if src_project else ""
463
+ self._source_project = src_project.name if src_project else ""
464
+ self._source_name = f"{src_collection.name}:v{art.version_index}"
465
+ self._source_version = f"v{art.version_index}"
466
+
467
+ self._entity = self._entity or self._source_entity
468
+ self._project = self._project or self._source_project
469
+ self._name = self._name or self._source_name
470
+
471
+ # TODO: Refactor artifact query to fetch artifact via membership instead
472
+ # and get the collection type
473
+ if is_link is None:
474
+ self._is_link = (
475
+ self._entity != self._source_entity
476
+ or self._project != self._source_project
477
+ or self._name.split(":")[0] != self._source_name.split(":")[0]
478
+ )
479
+ else:
480
+ self._is_link = is_link
481
+
482
+ self._type = art.artifact_type.name
483
+ self._description = art.description
484
+
485
+ # The future of aliases is to move all alias fetches to the membership level
486
+ # so we don't have to do the collection fetches below
487
+ if aliases:
488
+ processed_aliases = aliases
489
+ elif art.aliases:
490
+ entity = self._entity
491
+ project = self._project
492
+ collection = self._name.split(":")[0]
493
+ processed_aliases = [
494
+ art_alias.alias
495
+ for art_alias in art.aliases
496
+ if (
497
+ (coll := art_alias.artifact_collection)
498
+ and (proj := coll.project)
499
+ and proj.entity_name == entity
500
+ and proj.name == project
501
+ and coll.name == collection
502
+ )
503
+ ]
504
+ else:
505
+ processed_aliases = []
506
+
507
+ version_aliases = list(filter(alias_is_version_index, processed_aliases))
508
+ other_aliases = list(filterfalse(alias_is_version_index, processed_aliases))
509
+
510
+ try:
511
+ version = one(
512
+ version_aliases, too_short=TooFewItemsError, too_long=TooManyItemsError
513
+ )
514
+ except TooFewItemsError:
515
+ version = f"v{art.version_index}" # default to the source version
516
+ except TooManyItemsError:
517
+ msg = f"Expected at most one version alias, got {len(version_aliases)}: {version_aliases!r}"
518
+ raise ValueError(msg) from None
519
+
520
+ self._version = version
521
+ self._name = self._name if (":" in self._name) else f"{self._name}:{version}"
522
+
523
+ self._aliases = other_aliases
524
+ self._saved_aliases = copy(self._aliases)
525
+
526
+ self._tags = [tag.name for tag in (art.tags or [])]
527
+ self._saved_tags = copy(self._tags)
528
+
529
+ self._metadata = validate_metadata(art.metadata)
530
+
531
+ self._ttl_duration_seconds = validate_ttl_duration_seconds(
532
+ art.ttl_duration_seconds
533
+ )
534
+ self._ttl_is_inherited = (
535
+ True if (art.ttl_is_inherited is None) else art.ttl_is_inherited
536
+ )
537
+
538
+ self._state = ArtifactState(art.state)
539
+
540
+ self._manifest = (
541
+ _DeferredArtifactManifest(manifest.file.direct_url)
542
+ if (manifest := art.current_manifest)
543
+ else None
544
+ )
545
+
546
+ self._commit_hash = art.commit_hash
547
+ self._file_count = art.file_count
548
+ self._created_at = art.created_at
549
+ self._updated_at = art.updated_at
550
+ self._history_step = art.history_step
551
+
552
+ @ensure_logged
553
+ def new_draft(self) -> Artifact:
554
+ """Create a new draft artifact with the same content as this committed artifact.
555
+
556
+ Modifying an existing artifact creates a new artifact version known
557
+ as an "incremental artifact". The artifact returned can be extended or
558
+ modified and logged as a new version.
559
+
560
+ Returns:
561
+ An `Artifact` object.
562
+
563
+ Raises:
564
+ ArtifactNotLoggedError: If the artifact is not logged.
565
+ """
566
+ # Name, _entity and _project are set to the *source* name/entity/project:
567
+ # if this artifact is saved it must be saved to the source sequence.
568
+ artifact = Artifact(self.source_name.split(":")[0], self.type)
569
+ artifact._entity = self._source_entity
570
+ artifact._project = self._source_project
571
+ artifact._source_entity = self._source_entity
572
+ artifact._source_project = self._source_project
573
+
574
+ # This artifact's parent is the one we are making a draft from.
575
+ artifact._base_id = self.id
576
+
577
+ # We can reuse the client, and copy over all the attributes that aren't
578
+ # version-dependent and don't depend on having been logged.
579
+ artifact._client = self._client
580
+ artifact._description = self.description
581
+ artifact._metadata = self.metadata
582
+ artifact._manifest = ArtifactManifest.from_manifest_json(
583
+ self.manifest.to_manifest_json()
584
+ )
585
+ return artifact
586
+
587
+ # Properties (Python Class managed attributes).
588
+
589
+ @property
590
+ def id(self) -> str | None:
591
+ """The artifact's ID."""
592
+ if self.is_draft():
593
+ return None
594
+ assert self._id is not None
595
+ return self._id
596
+
597
+ @property
598
+ @ensure_logged
599
+ def entity(self) -> str:
600
+ """The name of the entity that the artifact collection belongs to.
601
+
602
+ If the artifact is a link, the entity will be the entity of the linked artifact.
603
+ """
604
+ assert self._entity is not None
605
+ return self._entity
606
+
607
+ @property
608
+ @ensure_logged
609
+ def project(self) -> str:
610
+ """The name of the project that the artifact collection belongs to.
611
+
612
+ If the artifact is a link, the project will be the project of the linked artifact.
613
+ """
614
+ assert self._project is not None
615
+ return self._project
616
+
617
+ @property
618
+ def name(self) -> str:
619
+ """The artifact name and version of the artifact.
620
+
621
+ A string with the format `{collection}:{alias}`. If fetched before an artifact is logged/saved, the name won't contain the alias.
622
+ If the artifact is a link, the name will be the name of the linked artifact.
623
+ """
624
+ return self._name
625
+
626
+ @property
627
+ def qualified_name(self) -> str:
628
+ """The entity/project/name of the artifact.
629
+
630
+ If the artifact is a link, the qualified name will be the qualified name of the linked artifact path.
631
+ """
632
+ return f"{self.entity}/{self.project}/{self.name}"
633
+
634
+ @property
635
+ @ensure_logged
636
+ def version(self) -> str:
637
+ """The artifact's version.
638
+
639
+ A string with the format `v{number}`.
640
+ If the artifact is a link artifact, the version will be from the linked collection.
641
+ """
642
+ assert self._version is not None
643
+ return self._version
644
+
645
+ @property
646
+ @ensure_logged
647
+ def collection(self) -> ArtifactCollection:
648
+ """The collection this artifact was retrieved from.
649
+
650
+ A collection is an ordered group of artifact versions.
651
+ If this artifact was retrieved from a portfolio / linked collection, that
652
+ collection will be returned rather than the collection
653
+ that an artifact version originated from. The collection
654
+ that an artifact originates from is known as the source sequence.
655
+ """
656
+ base_name = self.name.split(":")[0]
657
+ return ArtifactCollection(
658
+ self._client, self.entity, self.project, base_name, self.type
659
+ )
660
+
661
+ @property
662
+ @ensure_logged
663
+ def source_entity(self) -> str:
664
+ """The name of the entity of the source artifact."""
665
+ assert self._source_entity is not None
666
+ return self._source_entity
667
+
668
+ @property
669
+ @ensure_logged
670
+ def source_project(self) -> str:
671
+ """The name of the project of the source artifact."""
672
+ assert self._source_project is not None
673
+ return self._source_project
674
+
675
+ @property
676
+ def source_name(self) -> str:
677
+ """The artifact name and version of the source artifact.
678
+
679
+ A string with the format `{source_collection}:{alias}`. Before the artifact is saved,
680
+ contains only the name since the version is not yet known.
681
+ """
682
+ return self._source_name
683
+
684
+ @property
685
+ def source_qualified_name(self) -> str:
686
+ """The source_entity/source_project/source_name of the source artifact."""
687
+ return f"{self.source_entity}/{self.source_project}/{self.source_name}"
688
+
689
+ @property
690
+ @ensure_logged
691
+ def source_version(self) -> str:
692
+ """The source artifact's version.
693
+
694
+ A string with the format `v{number}`.
695
+ """
696
+ assert self._source_version is not None
697
+ return self._source_version
698
+
699
+ @property
700
+ @ensure_logged
701
+ def source_collection(self) -> ArtifactCollection:
702
+ """The artifact's source collection.
703
+
704
+ The source collection is the collection that the artifact was logged from.
705
+ """
706
+ base_name = self.source_name.split(":")[0]
707
+ return ArtifactCollection(
708
+ self._client, self.source_entity, self.source_project, base_name, self.type
709
+ )
710
+
711
+ @property
712
+ def is_link(self) -> bool:
713
+ """Boolean flag indicating if the artifact is a link artifact.
714
+
715
+ True: The artifact is a link artifact to a source artifact.
716
+ False: The artifact is a source artifact.
717
+ """
718
+ return self._is_link
719
+
720
+ @property
721
+ @ensure_logged
722
+ def linked_artifacts(self) -> list[Artifact]:
723
+ """Returns a list of all the linked artifacts of a source artifact.
724
+
725
+ If the artifact is a link artifact (`artifact.is_link == True`), it will return an empty list.
726
+ Limited to 500 results."""
727
+ if not self.is_link:
728
+ self._linked_artifacts = self._fetch_linked_artifacts()
729
+ return self._linked_artifacts
730
+
731
+ @property
732
+ @ensure_logged
733
+ def source_artifact(self) -> Artifact:
734
+ """Returns the source artifact. The source artifact is the original logged artifact.
735
+
736
+ If the artifact itself is a source artifact (`artifact.is_link == False`), it will return itself."""
737
+ if not self.is_link:
738
+ return self
739
+ if self._source_artifact is None:
740
+ if self._client is None:
741
+ raise ValueError("Client is not initialized")
742
+
743
+ try:
744
+ artifact = self._from_name(
745
+ entity=self.source_entity,
746
+ project=self.source_project,
747
+ name=self.source_name,
748
+ client=self._client,
749
+ )
750
+ self._source_artifact = artifact
751
+ except Exception as e:
752
+ raise ValueError(
753
+ f"Unable to fetch source artifact for linked artifact {self.name}"
754
+ ) from e
755
+ return self._source_artifact
756
+
757
+ @property
758
+ def type(self) -> str:
759
+ """The artifact's type. Common types include `dataset` or `model`."""
760
+ return self._type
761
+
762
+ @property
763
+ @ensure_logged
764
+ def url(self) -> str:
765
+ """
766
+ Constructs the URL of the artifact.
767
+
768
+ Returns:
769
+ str: The URL of the artifact.
770
+ """
771
+ try:
772
+ base_url = self._client.app_url # type: ignore[union-attr]
773
+ except AttributeError:
774
+ return ""
775
+
776
+ if not self.is_link:
777
+ return self._construct_standard_url(base_url)
778
+ if is_artifact_registry_project(self.project):
779
+ return self._construct_registry_url(base_url)
780
+ if self._type == "model" or self.project == "model-registry":
781
+ return self._construct_model_registry_url(base_url)
782
+ return self._construct_standard_url(base_url)
783
+
784
+ def _construct_standard_url(self, base_url: str) -> str:
785
+ if not all(
786
+ [
787
+ base_url,
788
+ self.entity,
789
+ self.project,
790
+ self._type,
791
+ self.collection.name,
792
+ self._version,
793
+ ]
794
+ ):
795
+ return ""
796
+ return urljoin(
797
+ base_url,
798
+ f"{self.entity}/{self.project}/artifacts/{quote(self._type)}/{quote(self.collection.name)}/{self._version}",
799
+ )
800
+
801
+ def _construct_registry_url(self, base_url: str) -> str:
802
+ if not all(
803
+ [
804
+ base_url,
805
+ self.entity,
806
+ self.project,
807
+ self.collection.name,
808
+ self._version,
809
+ ]
810
+ ):
811
+ return ""
812
+
813
+ try:
814
+ org, *_ = InternalApi()._fetch_orgs_and_org_entities_from_entity(
815
+ self.entity
816
+ )
817
+ except ValueError:
818
+ return ""
819
+
820
+ selection_path = quote(
821
+ f"{self.entity}/{self.project}/{self.collection.name}", safe=""
822
+ )
823
+ return urljoin(
824
+ base_url,
825
+ f"orgs/{org.display_name}/registry/{remove_registry_prefix(self.project)}?selectionPath={selection_path}&view=membership&version={self.version}",
826
+ )
827
+
828
+ def _construct_model_registry_url(self, base_url: str) -> str:
829
+ if not all(
830
+ [
831
+ base_url,
832
+ self.entity,
833
+ self.project,
834
+ self.collection.name,
835
+ self._version,
836
+ ]
837
+ ):
838
+ return ""
839
+ selection_path = quote(
840
+ f"{self.entity}/{self.project}/{self.collection.name}", safe=""
841
+ )
842
+ return urljoin(
843
+ base_url,
844
+ f"{self.entity}/registry/model?selectionPath={selection_path}&view=membership&version={self._version}",
845
+ )
846
+
847
+ @property
848
+ def description(self) -> str | None:
849
+ """A description of the artifact."""
850
+ return self._description
851
+
852
+ @description.setter
853
+ def description(self, description: str | None) -> None:
854
+ """Set the description of the artifact.
855
+
856
+ For model or dataset Artifacts, add documentation for your
857
+ standardized team model or dataset card. In the W&B UI the
858
+ description is rendered as markdown.
859
+
860
+ Editing the description will apply the changes to the source artifact and all linked artifacts associated with it.
861
+
862
+ Args:
863
+ description: Free text that offers a description of the artifact.
864
+ """
865
+ if self.is_link:
866
+ wandb.termwarn(
867
+ "Editing the description of this linked artifact will edit the description for the source artifact and it's linked artifacts as well."
868
+ )
869
+ self._description = description
870
+
871
+ @property
872
+ def metadata(self) -> dict:
873
+ """User-defined artifact metadata.
874
+
875
+ Structured data associated with the artifact.
876
+ """
877
+ return self._metadata
878
+
879
+ @metadata.setter
880
+ def metadata(self, metadata: dict) -> None:
881
+ """User-defined artifact metadata.
882
+
883
+ Metadata set this way will eventually be queryable and plottable in the UI; e.g.
884
+ the class distribution of a dataset.
885
+
886
+ Note: There is currently a limit of 100 total keys.
887
+ Editing the metadata will apply the changes to the source artifact and all linked artifacts associated with it.
888
+
889
+ Args:
890
+ metadata: Structured data associated with the artifact.
891
+ """
892
+ if self.is_link:
893
+ wandb.termwarn(
894
+ "Editing the metadata of this linked artifact will edit the metadata for the source artifact and it's linked artifacts as well."
895
+ )
896
+ self._metadata = validate_metadata(metadata)
897
+
898
+ @property
899
+ def ttl(self) -> timedelta | None:
900
+ """The time-to-live (TTL) policy of an artifact.
901
+
902
+ Artifacts are deleted shortly after a TTL policy's duration passes.
903
+ If set to `None`, the artifact deactivates TTL policies and will be not
904
+ scheduled for deletion, even if there is a team default TTL.
905
+ An artifact inherits a TTL policy from
906
+ the team default if the team administrator defines a default
907
+ TTL and there is no custom policy set on an artifact.
908
+
909
+ Raises:
910
+ ArtifactNotLoggedError: Unable to fetch inherited TTL if the
911
+ artifact has not been logged or saved.
912
+ """
913
+ if self._ttl_is_inherited and (self.is_draft() or self._ttl_changed):
914
+ raise ArtifactNotLoggedError(f"{type(self).__name__}.ttl", self)
915
+ if self._ttl_duration_seconds is None:
916
+ return None
917
+ return timedelta(seconds=self._ttl_duration_seconds)
918
+
919
+ @ttl.setter
920
+ def ttl(self, ttl: timedelta | ArtifactTTL | None) -> None:
921
+ """The time-to-live (TTL) policy of an artifact.
922
+
923
+ Artifacts are deleted shortly after a TTL policy's duration passes.
924
+ If set to `None`, the artifact has no TTL policy set and it is not
925
+ scheduled for deletion. An artifact inherits a TTL policy from
926
+ the team default if the team administrator defines a default
927
+ TTL and there is no custom policy set on an artifact.
928
+
929
+ Args:
930
+ ttl: The duration as a positive Python `datetime.timedelta` Type
931
+ that represents how long the artifact will remain active from its creation.
932
+
933
+ """
934
+ if self.type == "wandb-history":
935
+ raise ValueError("Cannot set artifact TTL for type wandb-history")
936
+
937
+ if self.is_link:
938
+ raise ValueError(
939
+ "Cannot set TTL for link artifact. "
940
+ "Unlink the artifact first then set the TTL for the source artifact"
941
+ )
942
+
943
+ self._ttl_changed = True
944
+ if isinstance(ttl, ArtifactTTL):
945
+ if ttl == ArtifactTTL.INHERIT:
946
+ self._ttl_is_inherited = True
947
+ else:
948
+ raise ValueError(f"Unhandled ArtifactTTL enum {ttl}")
949
+ else:
950
+ self._ttl_is_inherited = False
951
+ if ttl is None:
952
+ self._ttl_duration_seconds = None
953
+ else:
954
+ if ttl.total_seconds() <= 0:
955
+ raise ValueError(
956
+ f"Artifact TTL Duration has to be positive. ttl: {ttl.total_seconds()}"
957
+ )
958
+ self._ttl_duration_seconds = int(ttl.total_seconds())
959
+
960
+ @property
961
+ @ensure_logged
962
+ def aliases(self) -> list[str]:
963
+ """List of one or more semantically-friendly references or
964
+
965
+ identifying "nicknames" assigned to an artifact version.
966
+
967
+ Aliases are mutable references that you can programmatically reference.
968
+ Change an artifact's alias with the W&B App UI or programmatically.
969
+ See [Create new artifact versions](https://docs.wandb.ai/guides/artifacts/create-a-new-artifact-version)
970
+ for more information.
971
+ """
972
+ return self._aliases
973
+
974
+ @aliases.setter
975
+ @ensure_logged
976
+ def aliases(self, aliases: list[str]) -> None:
977
+ """Set the aliases associated with this artifact."""
978
+ self._aliases = validate_aliases(aliases)
979
+
980
+ @property
981
+ @ensure_logged
982
+ def tags(self) -> list[str]:
983
+ """List of one or more tags assigned to this artifact version."""
984
+ return self._tags
985
+
986
+ @tags.setter
987
+ @ensure_logged
988
+ def tags(self, tags: list[str]) -> None:
989
+ """Set the tags associated with this artifact.
990
+
991
+ Editing tags will apply the changes to the source artifact and all linked artifacts associated with it.
992
+ """
993
+ if self.is_link:
994
+ wandb.termwarn(
995
+ "Editing tags will apply the changes to the source artifact and all linked artifacts associated with it."
996
+ )
997
+ self._tags = validate_tags(tags)
998
+
999
+ @property
1000
+ def distributed_id(self) -> str | None:
1001
+ """The distributed ID of the artifact.
1002
+
1003
+ <!-- lazydoc-ignore: internal -->
1004
+ """
1005
+ return self._distributed_id
1006
+
1007
+ @distributed_id.setter
1008
+ def distributed_id(self, distributed_id: str | None) -> None:
1009
+ self._distributed_id = distributed_id
1010
+
1011
+ @property
1012
+ def incremental(self) -> bool:
1013
+ """Boolean flag indicating if the artifact is an incremental artifact.
1014
+
1015
+ <!-- lazydoc-ignore: internal -->
1016
+ """
1017
+ return self._incremental
1018
+
1019
+ @property
1020
+ def use_as(self) -> str | None:
1021
+ """Deprecated."""
1022
+ deprecate(
1023
+ field_name=Deprecated.artifact__use_as,
1024
+ warning_message=("The use_as property of Artifact is deprecated."),
1025
+ )
1026
+ return self._use_as
1027
+
1028
+ @property
1029
+ def state(self) -> str:
1030
+ """The status of the artifact. One of: "PENDING", "COMMITTED", or "DELETED"."""
1031
+ return self._state.value
1032
+
1033
+ @property
1034
+ def manifest(self) -> ArtifactManifest:
1035
+ """The artifact's manifest.
1036
+
1037
+ The manifest lists all of its contents, and can't be changed once the artifact
1038
+ has been logged.
1039
+ """
1040
+ if isinstance(self._manifest, _DeferredArtifactManifest):
1041
+ # A deferred manifest URL flags a deferred download request,
1042
+ # so fetch the manifest to override the placeholder object
1043
+ self._manifest = self._load_manifest(self._manifest.url)
1044
+ return self._manifest
1045
+
1046
+ if self._manifest is None:
1047
+ if self._client is None:
1048
+ raise RuntimeError("Client not initialized for artifact queries")
1049
+
1050
+ query = gql(FETCH_ARTIFACT_MANIFEST_GQL)
1051
+ gql_vars = {
1052
+ "entityName": self.entity,
1053
+ "projectName": self.project,
1054
+ "name": self.name,
1055
+ }
1056
+ data = self._client.execute(query, variable_values=gql_vars)
1057
+ result = FetchArtifactManifest.model_validate(data)
1058
+ if not (
1059
+ (project := result.project)
1060
+ and (artifact := project.artifact)
1061
+ and (manifest := artifact.current_manifest)
1062
+ ):
1063
+ raise ValueError("Failed to fetch artifact manifest")
1064
+ self._manifest = self._load_manifest(manifest.file.direct_url)
1065
+
1066
+ return self._manifest
1067
+
1068
+ @property
1069
+ def digest(self) -> str:
1070
+ """The logical digest of the artifact.
1071
+
1072
+ The digest is the checksum of the artifact's contents. If an artifact has the
1073
+ same digest as the current `latest` version, then `log_artifact` is a no-op.
1074
+ """
1075
+ return self.manifest.digest()
1076
+
1077
+ @property
1078
+ def size(self) -> int:
1079
+ """The total size of the artifact in bytes.
1080
+
1081
+ Includes any references tracked by this artifact.
1082
+ """
1083
+ return sum(entry.size for entry in self.manifest.entries.values() if entry.size)
1084
+
1085
+ @property
1086
+ @ensure_logged
1087
+ def commit_hash(self) -> str:
1088
+ """The hash returned when this artifact was committed."""
1089
+ assert self._commit_hash is not None
1090
+ return self._commit_hash
1091
+
1092
+ @property
1093
+ @ensure_logged
1094
+ def file_count(self) -> int:
1095
+ """The number of files (including references)."""
1096
+ assert self._file_count is not None
1097
+ return self._file_count
1098
+
1099
+ @property
1100
+ @ensure_logged
1101
+ def created_at(self) -> str:
1102
+ """Timestamp when the artifact was created."""
1103
+ assert self._created_at is not None
1104
+ return self._created_at
1105
+
1106
+ @property
1107
+ @ensure_logged
1108
+ def updated_at(self) -> str:
1109
+ """The time when the artifact was last updated."""
1110
+ assert self._created_at is not None
1111
+ return self._updated_at or self._created_at
1112
+
1113
+ @property
1114
+ @ensure_logged
1115
+ def history_step(self) -> int | None:
1116
+ """The nearest step at which history metrics were logged for the source run of the artifact.
1117
+
1118
+ Examples:
1119
+ ```python
1120
+ run = artifact.logged_by()
1121
+ if run and (artifact.history_step is not None):
1122
+ history = run.sample_history(
1123
+ min_step=artifact.history_step,
1124
+ max_step=artifact.history_step + 1,
1125
+ keys=["my_metric"],
1126
+ )
1127
+ ```
1128
+ """
1129
+ if self._history_step is None:
1130
+ return None
1131
+ return max(0, self._history_step - 1)
1132
+
1133
+ # State management.
1134
+
1135
+ def finalize(self) -> None:
1136
+ """Finalize the artifact version.
1137
+
1138
+ You cannot modify an artifact version once it is finalized because the artifact
1139
+ is logged as a specific artifact version. Create a new artifact version
1140
+ to log more data to an artifact. An artifact is automatically finalized
1141
+ when you log the artifact with `log_artifact`.
1142
+ """
1143
+ self._final = True
1144
+
1145
+ def is_draft(self) -> bool:
1146
+ """Check if artifact is not saved.
1147
+
1148
+ Returns:
1149
+ Boolean. `False` if artifact is saved. `True` if artifact is not saved.
1150
+ """
1151
+ return self._state is ArtifactState.PENDING
1152
+
1153
+ def _is_draft_save_started(self) -> bool:
1154
+ return self._save_handle is not None
1155
+
1156
+ def save(
1157
+ self,
1158
+ project: str | None = None,
1159
+ settings: wandb.Settings | None = None,
1160
+ ) -> None:
1161
+ """Persist any changes made to the artifact.
1162
+
1163
+ If currently in a run, that run will log this artifact. If not currently in a
1164
+ run, a run of type "auto" is created to track this artifact.
1165
+
1166
+ Args:
1167
+ project: A project to use for the artifact in the case that a run is not
1168
+ already in context.
1169
+ settings: A settings object to use when initializing an automatic run. Most
1170
+ commonly used in testing harness.
1171
+ """
1172
+ if self._state is not ArtifactState.PENDING:
1173
+ return self._update()
1174
+
1175
+ if self._incremental:
1176
+ with telemetry.context() as tel:
1177
+ tel.feature.artifact_incremental = True
1178
+
1179
+ if run := wandb_setup.singleton().most_recent_active_run:
1180
+ # TODO: Deprecate and encourage explicit log_artifact().
1181
+ run.log_artifact(self)
1182
+ else:
1183
+ if settings is None:
1184
+ settings = wandb.Settings(silent="true")
1185
+ with wandb.init( # type: ignore
1186
+ entity=self._source_entity,
1187
+ project=project or self._source_project,
1188
+ job_type="auto",
1189
+ settings=settings,
1190
+ ) as run:
1191
+ # redoing this here because in this branch we know we didn't
1192
+ # have the run at the beginning of the method
1193
+ if self._incremental:
1194
+ with telemetry.context(run=run) as tel:
1195
+ tel.feature.artifact_incremental = True
1196
+ run.log_artifact(self)
1197
+
1198
+ def _set_save_handle(
1199
+ self,
1200
+ save_handle: MailboxHandle[pb.Result],
1201
+ client: RetryingClient,
1202
+ ) -> None:
1203
+ self._save_handle = save_handle
1204
+ self._client = client
1205
+
1206
+ def wait(self, timeout: int | None = None) -> Artifact:
1207
+ """If needed, wait for this artifact to finish logging.
1208
+
1209
+ Args:
1210
+ timeout: The time, in seconds, to wait.
1211
+
1212
+ Returns:
1213
+ An `Artifact` object.
1214
+ """
1215
+ if self.is_draft():
1216
+ if self._save_handle is None:
1217
+ raise ArtifactNotLoggedError(type(self).wait.__qualname__, self)
1218
+
1219
+ try:
1220
+ result = self._save_handle.wait_or(timeout=timeout)
1221
+ except TimeoutError as e:
1222
+ raise WaitTimeoutError(
1223
+ "Artifact upload wait timed out, failed to fetch Artifact response"
1224
+ ) from e
1225
+
1226
+ response = result.response.log_artifact_response
1227
+ if response.error_message:
1228
+ raise ValueError(response.error_message)
1229
+ self._populate_after_save(response.artifact_id)
1230
+ return self
1231
+
1232
+ def _populate_after_save(self, artifact_id: str) -> None:
1233
+ assert self._client is not None
1234
+
1235
+ query = gql_compat(ARTIFACT_BY_ID_GQL, omit_fields=omit_artifact_fields())
1236
+
1237
+ data = self._client.execute(query, variable_values={"id": artifact_id})
1238
+ result = ArtifactByID.model_validate(data)
1239
+
1240
+ if not (artifact := result.artifact):
1241
+ raise ValueError(f"Unable to fetch artifact with id: {artifact_id!r}")
1242
+
1243
+ # _populate_after_save is only called on source artifacts, not linked artifacts
1244
+ # We have to manually set is_link because we aren't fetching the collection the artifact.
1245
+ # That requires greater refactoring for commitArtifact to return the artifact collection type.
1246
+ self._assign_attrs(artifact, is_link=False)
1247
+
1248
+ @normalize_exceptions
1249
+ def _update(self) -> None:
1250
+ """Persists artifact changes to the wandb backend."""
1251
+ if self._client is None:
1252
+ raise RuntimeError("Client not initialized for artifact mutations")
1253
+
1254
+ entity = self.entity
1255
+ project = self.project
1256
+ collection = self.name.split(":")[0]
1257
+
1258
+ aliases = None
1259
+ introspect_query = gql(
1260
+ """
1261
+ query ProbeServerAddAliasesInput {
1262
+ AddAliasesInputInfoType: __type(name: "AddAliasesInput") {
1263
+ name
1264
+ inputFields {
1265
+ name
1266
+ }
1267
+ }
1268
+ }
1269
+ """
1270
+ )
1271
+
1272
+ data = self._client.execute(introspect_query)
1273
+ if data.get("AddAliasesInputInfoType"): # wandb backend version >= 0.13.0
1274
+ alias_props = {
1275
+ "entity_name": entity,
1276
+ "project_name": project,
1277
+ "artifact_collection_name": collection,
1278
+ }
1279
+ if aliases_to_add := (set(self.aliases) - set(self._saved_aliases)):
1280
+ add_mutation = gql(ADD_ALIASES_GQL)
1281
+ add_alias_inputs = [
1282
+ ArtifactCollectionAliasInput(**alias_props, alias=alias)
1283
+ for alias in aliases_to_add
1284
+ ]
1285
+ try:
1286
+ self._client.execute(
1287
+ add_mutation,
1288
+ variable_values={
1289
+ "artifactID": self.id,
1290
+ "aliases": [a.model_dump() for a in add_alias_inputs],
1291
+ },
1292
+ )
1293
+ except CommError as e:
1294
+ raise CommError(
1295
+ "You do not have permission to add"
1296
+ f" {'at least one of the following aliases' if len(aliases_to_add) > 1 else 'the following alias'}"
1297
+ f" to this artifact: {aliases_to_add}"
1298
+ ) from e
1299
+
1300
+ if aliases_to_delete := (set(self._saved_aliases) - set(self.aliases)):
1301
+ delete_mutation = gql(DELETE_ALIASES_GQL)
1302
+ delete_alias_inputs = [
1303
+ ArtifactCollectionAliasInput(**alias_props, alias=alias)
1304
+ for alias in aliases_to_delete
1305
+ ]
1306
+ try:
1307
+ self._client.execute(
1308
+ delete_mutation,
1309
+ variable_values={
1310
+ "artifactID": self.id,
1311
+ "aliases": [a.model_dump() for a in delete_alias_inputs],
1312
+ },
1313
+ )
1314
+ except CommError as e:
1315
+ raise CommError(
1316
+ f"You do not have permission to delete"
1317
+ f" {'at least one of the following aliases' if len(aliases_to_delete) > 1 else 'the following alias'}"
1318
+ f" from this artifact: {aliases_to_delete}"
1319
+ ) from e
1320
+
1321
+ self._saved_aliases = copy(self.aliases)
1322
+
1323
+ else: # wandb backend version < 0.13.0
1324
+ aliases = [
1325
+ ArtifactAliasInput(
1326
+ artifact_collection_name=collection, alias=alias
1327
+ ).model_dump()
1328
+ for alias in self.aliases
1329
+ ]
1330
+
1331
+ omit_fields = omit_artifact_fields()
1332
+ omit_variables = set()
1333
+
1334
+ if {"ttlIsInherited", "ttlDurationSeconds"} & omit_fields:
1335
+ if self._ttl_changed:
1336
+ termwarn(
1337
+ "Server not compatible with setting Artifact TTLs, please upgrade the server to use Artifact TTL"
1338
+ )
1339
+
1340
+ omit_variables |= {"ttlDurationSeconds"}
1341
+
1342
+ tags_to_add = validate_tags(set(self.tags) - set(self._saved_tags))
1343
+ tags_to_del = validate_tags(set(self._saved_tags) - set(self.tags))
1344
+
1345
+ if {"tags"} & omit_fields:
1346
+ if tags_to_add or tags_to_del:
1347
+ termwarn(
1348
+ "Server not compatible with Artifact tags. "
1349
+ "To use Artifact tags, please upgrade the server to v0.85 or higher."
1350
+ )
1351
+
1352
+ omit_variables |= {"tagsToAdd", "tagsToDelete"}
1353
+
1354
+ mutation = gql_compat(
1355
+ UPDATE_ARTIFACT_GQL,
1356
+ omit_variables=omit_variables,
1357
+ omit_fields=omit_fields,
1358
+ )
1359
+
1360
+ gql_vars = {
1361
+ "artifactID": self.id,
1362
+ "description": self.description,
1363
+ "metadata": json_dumps_safer(self.metadata),
1364
+ "ttlDurationSeconds": self._ttl_duration_seconds_to_gql(),
1365
+ "aliases": aliases,
1366
+ "tagsToAdd": [TagInput(tag_name=t).model_dump() for t in tags_to_add],
1367
+ "tagsToDelete": [TagInput(tag_name=t).model_dump() for t in tags_to_del],
1368
+ }
1369
+
1370
+ data = self._client.execute(mutation, variable_values=gql_vars)
1371
+
1372
+ result = UpdateArtifact.model_validate(data).update_artifact
1373
+ if not (result and (artifact := result.artifact)):
1374
+ raise ValueError("Unable to parse updateArtifact response")
1375
+ self._assign_attrs(artifact)
1376
+
1377
+ self._ttl_changed = False # Reset after updating artifact
1378
+
1379
+ # Adding, removing, getting entries.
1380
+
1381
+ def __getitem__(self, name: str) -> WBValue | None:
1382
+ """Get the WBValue object located at the artifact relative `name`.
1383
+
1384
+ Args:
1385
+ name: The artifact relative name to get.
1386
+
1387
+ Returns:
1388
+ W&B object that can be logged with `run.log()` and visualized in the W&B UI.
1389
+
1390
+ Raises:
1391
+ ArtifactNotLoggedError: If the artifact isn't logged or the run is offline.
1392
+ """
1393
+ return self.get(name)
1394
+
1395
+ def __setitem__(self, name: str, item: WBValue) -> ArtifactManifestEntry:
1396
+ """Add `item` to the artifact at path `name`.
1397
+
1398
+ Args:
1399
+ name: The path within the artifact to add the object.
1400
+ item: The object to add.
1401
+
1402
+ Returns:
1403
+ The added manifest entry
1404
+
1405
+ Raises:
1406
+ ArtifactFinalizedError: You cannot make changes to the current
1407
+ artifact version because it is finalized. Log a new artifact
1408
+ version instead.
1409
+ """
1410
+ return self.add(item, name)
1411
+
1412
+ @contextlib.contextmanager
1413
+ @ensure_not_finalized
1414
+ def new_file(
1415
+ self, name: str, mode: str = "x", encoding: str | None = None
1416
+ ) -> Iterator[IO]:
1417
+ """Open a new temporary file and add it to the artifact.
1418
+
1419
+ Args:
1420
+ name: The name of the new file to add to the artifact.
1421
+ mode: The file access mode to use to open the new file.
1422
+ encoding: The encoding used to open the new file.
1423
+
1424
+ Returns:
1425
+ A new file object that can be written to. Upon closing, the file
1426
+ is automatically added to the artifact.
1427
+
1428
+ Raises:
1429
+ ArtifactFinalizedError: You cannot make changes to the current
1430
+ artifact version because it is finalized. Log a new artifact
1431
+ version instead.
1432
+ """
1433
+ overwrite: bool = "x" not in mode
1434
+
1435
+ if self._tmp_dir is None:
1436
+ self._tmp_dir = tempfile.TemporaryDirectory()
1437
+ path = os.path.join(self._tmp_dir.name, name.lstrip("/"))
1438
+
1439
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
1440
+ try:
1441
+ with fsync_open(path, mode, encoding) as f:
1442
+ yield f
1443
+ except FileExistsError:
1444
+ raise ValueError(f"File with name {name!r} already exists at {path!r}")
1445
+ except UnicodeEncodeError as e:
1446
+ termerror(
1447
+ f"Failed to open the provided file ({type(e).__name__}: {e}). Please "
1448
+ f"provide the proper encoding."
1449
+ )
1450
+ raise
1451
+
1452
+ self.add_file(
1453
+ path, name=name, policy="immutable", skip_cache=True, overwrite=overwrite
1454
+ )
1455
+
1456
+ @ensure_not_finalized
1457
+ def add_file(
1458
+ self,
1459
+ local_path: str,
1460
+ name: str | None = None,
1461
+ is_tmp: bool | None = False,
1462
+ skip_cache: bool | None = False,
1463
+ policy: Literal["mutable", "immutable"] | None = "mutable",
1464
+ overwrite: bool = False,
1465
+ ) -> ArtifactManifestEntry:
1466
+ """Add a local file to the artifact.
1467
+
1468
+ Args:
1469
+ local_path: The path to the file being added.
1470
+ name: The path within the artifact to use for the file being added.
1471
+ Defaults to the basename of the file.
1472
+ is_tmp: If true, then the file is renamed deterministically to avoid
1473
+ collisions.
1474
+ skip_cache: If `True`, do not copy files to the cache
1475
+ after uploading.
1476
+ policy: By default, set to "mutable". If set to "mutable",
1477
+ create a temporary copy of the file to prevent corruption
1478
+ during upload. If set to "immutable", disable
1479
+ protection and rely on the user not to delete or change the
1480
+ file.
1481
+ overwrite: If `True`, overwrite the file if it already exists.
1482
+
1483
+ Returns:
1484
+ The added manifest entry.
1485
+
1486
+ Raises:
1487
+ ArtifactFinalizedError: You cannot make changes to the current
1488
+ artifact version because it is finalized. Log a new artifact
1489
+ version instead.
1490
+ ValueError: Policy must be "mutable" or "immutable"
1491
+ """
1492
+ if not os.path.isfile(local_path):
1493
+ raise ValueError(f"Path is not a file: {local_path!r}")
1494
+
1495
+ name = LogicalPath(name or os.path.basename(local_path))
1496
+ digest = md5_file_b64(local_path)
1497
+
1498
+ if is_tmp:
1499
+ file_path, file_name = os.path.split(name)
1500
+ file_name_parts = file_name.split(".")
1501
+ file_name_parts[0] = b64_to_hex_id(digest)[:20]
1502
+ name = os.path.join(file_path, ".".join(file_name_parts))
1503
+
1504
+ return self._add_local_file(
1505
+ name,
1506
+ local_path,
1507
+ digest=digest,
1508
+ skip_cache=skip_cache,
1509
+ policy=policy,
1510
+ overwrite=overwrite,
1511
+ )
1512
+
1513
+ @ensure_not_finalized
1514
+ def add_dir(
1515
+ self,
1516
+ local_path: str,
1517
+ name: str | None = None,
1518
+ skip_cache: bool | None = False,
1519
+ policy: Literal["mutable", "immutable"] | None = "mutable",
1520
+ merge: bool = False,
1521
+ ) -> None:
1522
+ """Add a local directory to the artifact.
1523
+
1524
+ Args:
1525
+ local_path: The path of the local directory.
1526
+ name: The subdirectory name within an artifact. The name you
1527
+ specify appears in the W&B App UI nested by artifact's `type`.
1528
+ Defaults to the root of the artifact.
1529
+ skip_cache: If set to `True`, W&B will not copy/move files to
1530
+ the cache while uploading
1531
+ policy: By default, "mutable".
1532
+ - mutable: Create a temporary copy of the file to prevent corruption during upload.
1533
+ - immutable: Disable protection, rely on the user not to delete or change the file.
1534
+ merge: If `False` (default), throws ValueError if a file was already added in a previous add_dir call
1535
+ and its content has changed. If `True`, overwrites existing files with changed content.
1536
+ Always adds new files and never removes files. To replace an entire directory, pass a name when adding the directory
1537
+ using `add_dir(local_path, name=my_prefix)` and call `remove(my_prefix)` to remove the directory, then add it again.
1538
+
1539
+ Raises:
1540
+ ArtifactFinalizedError: You cannot make changes to the current
1541
+ artifact version because it is finalized. Log a new artifact
1542
+ version instead.
1543
+ ValueError: Policy must be "mutable" or "immutable"
1544
+ """
1545
+ if not os.path.isdir(local_path):
1546
+ raise ValueError(f"Path is not a directory: {local_path!r}")
1547
+
1548
+ termlog(
1549
+ f"Adding directory to artifact ({Path('.', local_path)})... ",
1550
+ newline=False,
1551
+ )
1552
+ start_time = time.monotonic()
1553
+
1554
+ paths: deque[tuple[str, str]] = deque()
1555
+ logical_root = name or "" # shared prefix, if any, for logical paths
1556
+ for dirpath, _, filenames in os.walk(local_path, followlinks=True):
1557
+ for fname in filenames:
1558
+ physical_path = os.path.join(dirpath, fname)
1559
+ logical_path = os.path.relpath(physical_path, start=local_path)
1560
+ logical_path = os.path.join(logical_root, logical_path)
1561
+ paths.append((logical_path, physical_path))
1562
+
1563
+ def add_manifest_file(logical_pth: str, physical_pth: str) -> None:
1564
+ self._add_local_file(
1565
+ name=logical_pth,
1566
+ path=physical_pth,
1567
+ skip_cache=skip_cache,
1568
+ policy=policy,
1569
+ overwrite=merge,
1570
+ )
1571
+
1572
+ num_threads = 8
1573
+ pool = multiprocessing.dummy.Pool(num_threads)
1574
+ pool.starmap(add_manifest_file, paths)
1575
+ pool.close()
1576
+ pool.join()
1577
+
1578
+ termlog("Done. %.1fs" % (time.monotonic() - start_time), prefix=False)
1579
+
1580
+ @ensure_not_finalized
1581
+ def add_reference(
1582
+ self,
1583
+ uri: ArtifactManifestEntry | str,
1584
+ name: StrPath | None = None,
1585
+ checksum: bool = True,
1586
+ max_objects: int | None = None,
1587
+ ) -> Sequence[ArtifactManifestEntry]:
1588
+ """Add a reference denoted by a URI to the artifact.
1589
+
1590
+ Unlike files or directories that you add to an artifact, references are not
1591
+ uploaded to W&B. For more information,
1592
+ see [Track external files](https://docs.wandb.ai/guides/artifacts/track-external-files).
1593
+
1594
+ By default, the following schemes are supported:
1595
+
1596
+ - http(s): The size and digest of the file will be inferred by the
1597
+ `Content-Length` and the `ETag` response headers returned by the server.
1598
+ - s3: The checksum and size are pulled from the object metadata.
1599
+ If bucket versioning is enabled, then the version ID is also tracked.
1600
+ - gs: The checksum and size are pulled from the object metadata. If bucket
1601
+ versioning is enabled, then the version ID is also tracked.
1602
+ - https, domain matching `*.blob.core.windows.net`
1603
+ - Azure: The checksum and size are be pulled from the blob metadata.
1604
+ If storage account versioning is enabled, then the version ID is
1605
+ also tracked.
1606
+ - file: The checksum and size are pulled from the file system. This scheme
1607
+ is useful if you have an NFS share or other externally mounted volume
1608
+ containing files you wish to track but not necessarily upload.
1609
+
1610
+ For any other scheme, the digest is just a hash of the URI and the size is left
1611
+ blank.
1612
+
1613
+ Args:
1614
+ uri: The URI path of the reference to add. The URI path can be an object
1615
+ returned from `Artifact.get_entry` to store a reference to another
1616
+ artifact's entry.
1617
+ name: The path within the artifact to place the contents of this reference.
1618
+ checksum: Whether or not to checksum the resource(s) located at the
1619
+ reference URI. Checksumming is strongly recommended as it enables
1620
+ automatic integrity validation. Disabling checksumming will speed up
1621
+ artifact creation but reference directories will not iterated through so the
1622
+ objects in the directory will not be saved to the artifact. We recommend
1623
+ setting `checksum=False` when adding reference objects, in which case
1624
+ a new version will only be created if the reference URI changes.
1625
+ max_objects: The maximum number of objects to consider when adding a
1626
+ reference that points to directory or bucket store prefix.
1627
+ By default, the maximum number of objects allowed for Amazon S3,
1628
+ GCS, Azure, and local files is 10,000,000. Other URI schemas
1629
+ do not have a maximum.
1630
+
1631
+ Returns:
1632
+ The added manifest entries.
1633
+
1634
+ Raises:
1635
+ ArtifactFinalizedError: You cannot make changes to the current
1636
+ artifact version because it is finalized. Log a new artifact
1637
+ version instead.
1638
+ """
1639
+ if name is not None:
1640
+ name = LogicalPath(name)
1641
+
1642
+ # This is a bit of a hack, we want to check if the uri is a of the type
1643
+ # ArtifactManifestEntry. If so, then recover the reference URL.
1644
+ if isinstance(uri, ArtifactManifestEntry):
1645
+ uri_str = uri.ref_url()
1646
+ elif isinstance(uri, str):
1647
+ uri_str = uri
1648
+ url = urlparse(str(uri_str))
1649
+ if not url.scheme:
1650
+ raise ValueError(
1651
+ "References must be URIs. To reference a local file, use file://"
1652
+ )
1653
+
1654
+ manifest_entries = self.manifest.storage_policy.store_reference(
1655
+ self,
1656
+ URIStr(uri_str),
1657
+ name=name,
1658
+ checksum=checksum,
1659
+ max_objects=max_objects,
1660
+ )
1661
+ for entry in manifest_entries:
1662
+ self.manifest.add_entry(entry)
1663
+
1664
+ return manifest_entries
1665
+
1666
+ @ensure_not_finalized
1667
+ def add(
1668
+ self, obj: WBValue, name: StrPath, overwrite: bool = False
1669
+ ) -> ArtifactManifestEntry:
1670
+ """Add wandb.WBValue `obj` to the artifact.
1671
+
1672
+ Args:
1673
+ obj: The object to add. Currently support one of Bokeh, JoinedTable,
1674
+ PartitionedTable, Table, Classes, ImageMask, BoundingBoxes2D,
1675
+ Audio, Image, Video, Html, Object3D
1676
+ name: The path within the artifact to add the object.
1677
+ overwrite: If True, overwrite existing objects with the same file
1678
+ path if applicable.
1679
+
1680
+ Returns:
1681
+ The added manifest entry
1682
+
1683
+ Raises:
1684
+ ArtifactFinalizedError: You cannot make changes to the current
1685
+ artifact version because it is finalized. Log a new artifact
1686
+ version instead.
1687
+ """
1688
+ name = LogicalPath(name)
1689
+
1690
+ # This is a "hack" to automatically rename tables added to
1691
+ # the wandb /media/tables directory to their sha-based name.
1692
+ # TODO: figure out a more appropriate convention.
1693
+ is_tmp_name = name.startswith("media/tables")
1694
+
1695
+ # Validate that the object is one of the correct wandb.Media types
1696
+ # TODO: move this to checking subclass of wandb.Media once all are
1697
+ # generally supported
1698
+ allowed_types = (
1699
+ data_types.Bokeh,
1700
+ data_types.JoinedTable,
1701
+ data_types.PartitionedTable,
1702
+ data_types.Table,
1703
+ data_types.Classes,
1704
+ data_types.ImageMask,
1705
+ data_types.BoundingBoxes2D,
1706
+ data_types.Audio,
1707
+ data_types.Image,
1708
+ data_types.Video,
1709
+ data_types.Html,
1710
+ data_types.Object3D,
1711
+ data_types.Molecule,
1712
+ data_types._SavedModel,
1713
+ )
1714
+ if not isinstance(obj, allowed_types):
1715
+ raise TypeError(
1716
+ f"Found object of type {obj.__class__}, expected one of:"
1717
+ f" {allowed_types}"
1718
+ )
1719
+
1720
+ obj_id = id(obj)
1721
+ if obj_id in self._added_objs:
1722
+ return self._added_objs[obj_id][1]
1723
+
1724
+ # If the object is coming from another artifact, save it as a reference
1725
+ ref_path = obj._get_artifact_entry_ref_url()
1726
+ if ref_path is not None:
1727
+ return self.add_reference(ref_path, type(obj).with_suffix(name))[0]
1728
+
1729
+ val = obj.to_json(self)
1730
+ name = obj.with_suffix(name)
1731
+ entry = self.manifest.get_entry_by_path(name)
1732
+ if (not overwrite) and (entry is not None):
1733
+ return entry
1734
+
1735
+ if is_tmp_name:
1736
+ file_path = os.path.join(self._TMP_DIR.name, str(id(self)), name)
1737
+ folder_path, _ = os.path.split(file_path)
1738
+ os.makedirs(folder_path, exist_ok=True)
1739
+ with open(file_path, "w", encoding="utf-8") as tmp_f:
1740
+ json.dump(val, tmp_f, sort_keys=True)
1741
+ else:
1742
+ filemode = "w" if overwrite else "x"
1743
+ with self.new_file(name, mode=filemode, encoding="utf-8") as f:
1744
+ json.dump(val, f, sort_keys=True)
1745
+ file_path = f.name
1746
+
1747
+ # Note, we add the file from our temp directory.
1748
+ # It will be added again later on finalize, but succeed since
1749
+ # the checksum should match
1750
+ entry = self.add_file(file_path, name, is_tmp_name)
1751
+ # We store a reference to the obj so that its id doesn't get reused.
1752
+ self._added_objs[obj_id] = (obj, entry)
1753
+ if obj._artifact_target is None:
1754
+ obj._set_artifact_target(self, entry.path)
1755
+
1756
+ if is_tmp_name:
1757
+ with contextlib.suppress(FileNotFoundError):
1758
+ os.remove(file_path)
1759
+
1760
+ return entry
1761
+
1762
+ def _add_local_file(
1763
+ self,
1764
+ name: StrPath,
1765
+ path: StrPath,
1766
+ digest: B64MD5 | None = None,
1767
+ skip_cache: bool | None = False,
1768
+ policy: Literal["mutable", "immutable"] | None = "mutable",
1769
+ overwrite: bool = False,
1770
+ ) -> ArtifactManifestEntry:
1771
+ policy = policy or "mutable"
1772
+ if policy not in ["mutable", "immutable"]:
1773
+ raise ValueError(
1774
+ f"Invalid policy {policy!r}. Policy may only be `mutable` or `immutable`."
1775
+ )
1776
+ upload_path = path
1777
+ if policy == "mutable":
1778
+ with tempfile.NamedTemporaryFile(dir=get_staging_dir(), delete=False) as f:
1779
+ staging_path = f.name
1780
+ shutil.copyfile(path, staging_path)
1781
+ # Set as read-only to prevent changes to the file during upload process
1782
+ os.chmod(staging_path, stat.S_IRUSR)
1783
+ upload_path = staging_path
1784
+
1785
+ entry = ArtifactManifestEntry(
1786
+ path=name,
1787
+ digest=digest or md5_file_b64(upload_path),
1788
+ size=os.path.getsize(upload_path),
1789
+ local_path=upload_path,
1790
+ skip_cache=skip_cache,
1791
+ )
1792
+ self.manifest.add_entry(entry, overwrite=overwrite)
1793
+ self._added_local_paths[os.fspath(path)] = entry
1794
+ return entry
1795
+
1796
+ @ensure_not_finalized
1797
+ def remove(self, item: StrPath | ArtifactManifestEntry) -> None:
1798
+ """Remove an item from the artifact.
1799
+
1800
+ Args:
1801
+ item: The item to remove. Can be a specific manifest entry
1802
+ or the name of an artifact-relative path. If the item
1803
+ matches a directory all items in that directory will be removed.
1804
+
1805
+ Raises:
1806
+ ArtifactFinalizedError: You cannot make changes to the current
1807
+ artifact version because it is finalized. Log a new artifact
1808
+ version instead.
1809
+ FileNotFoundError: If the item isn't found in the artifact.
1810
+ """
1811
+ if isinstance(item, ArtifactManifestEntry):
1812
+ self.manifest.remove_entry(item)
1813
+ return
1814
+
1815
+ path = str(PurePosixPath(item))
1816
+ if entry := self.manifest.get_entry_by_path(path):
1817
+ return self.manifest.remove_entry(entry)
1818
+
1819
+ entries = self.manifest.get_entries_in_directory(path)
1820
+ if not entries:
1821
+ raise FileNotFoundError(f"No such file or directory: {path}")
1822
+ for entry in entries:
1823
+ self.manifest.remove_entry(entry)
1824
+
1825
+ def get_path(self, name: StrPath) -> ArtifactManifestEntry:
1826
+ """Deprecated. Use `get_entry(name)`."""
1827
+ deprecate(
1828
+ field_name=Deprecated.artifact__get_path,
1829
+ warning_message="Artifact.get_path(name) is deprecated, use Artifact.get_entry(name) instead.",
1830
+ )
1831
+ return self.get_entry(name)
1832
+
1833
+ @ensure_logged
1834
+ def get_entry(self, name: StrPath) -> ArtifactManifestEntry:
1835
+ """Get the entry with the given name.
1836
+
1837
+ Args:
1838
+ name: The artifact relative name to get
1839
+
1840
+ Returns:
1841
+ A `W&B` object.
1842
+
1843
+ Raises:
1844
+ ArtifactNotLoggedError: if the artifact isn't logged or the run is offline.
1845
+ KeyError: if the artifact doesn't contain an entry with the given name.
1846
+ """
1847
+ name = LogicalPath(name)
1848
+ entry = self.manifest.entries.get(name) or self._get_obj_entry(name)[0]
1849
+ if entry is None:
1850
+ raise KeyError(f"Path not contained in artifact: {name}")
1851
+ entry._parent_artifact = self
1852
+ return entry
1853
+
1854
+ @ensure_logged
1855
+ def get(self, name: str) -> WBValue | None:
1856
+ """Get the WBValue object located at the artifact relative `name`.
1857
+
1858
+ Args:
1859
+ name: The artifact relative name to retrieve.
1860
+
1861
+ Returns:
1862
+ W&B object that can be logged with `run.log()` and
1863
+ visualized in the W&B UI.
1864
+
1865
+ Raises:
1866
+ ArtifactNotLoggedError: if the artifact isn't logged or the
1867
+ run is offline.
1868
+ """
1869
+ entry, wb_class = self._get_obj_entry(name)
1870
+ if entry is None or wb_class is None:
1871
+ return None
1872
+
1873
+ # If the entry is a reference from another artifact, then get it directly from
1874
+ # that artifact.
1875
+ if referenced_id := entry._referenced_artifact_id():
1876
+ assert self._client is not None
1877
+ artifact = self._from_id(referenced_id, client=self._client)
1878
+ assert artifact is not None
1879
+ return artifact.get(uri_from_path(entry.ref))
1880
+
1881
+ # Special case for wandb.Table. This is intended to be a short term
1882
+ # optimization. Since tables are likely to download many other assets in
1883
+ # artifact(s), we eagerly download the artifact using the parallelized
1884
+ # `artifact.download`. In the future, we should refactor the deserialization
1885
+ # pattern such that this special case is not needed.
1886
+ if wb_class == wandb.Table:
1887
+ self.download()
1888
+
1889
+ # Get the ArtifactManifestEntry
1890
+ item = self.get_entry(entry.path)
1891
+ item_path = item.download()
1892
+
1893
+ # Load the object from the JSON blob
1894
+ with open(item_path) as file:
1895
+ json_obj = json.load(file)
1896
+
1897
+ result = wb_class.from_json(json_obj, self)
1898
+ result._set_artifact_source(self, name)
1899
+ return result
1900
+
1901
+ def get_added_local_path_name(self, local_path: str) -> str | None:
1902
+ """Get the artifact relative name of a file added by a local filesystem path.
1903
+
1904
+ Args:
1905
+ local_path: The local path to resolve into an artifact relative name.
1906
+
1907
+ Returns:
1908
+ The artifact relative name.
1909
+ """
1910
+ if entry := self._added_local_paths.get(local_path):
1911
+ return entry.path
1912
+ return None
1913
+
1914
+ def _get_obj_entry(
1915
+ self, name: str
1916
+ ) -> tuple[ArtifactManifestEntry, Type[WBValue]] | tuple[None, None]: # noqa: UP006 # `type` shadows `Artifact.type`
1917
+ """Return an object entry by name, handling any type suffixes.
1918
+
1919
+ When objects are added with `.add(obj, name)`, the name is typically changed to
1920
+ include the suffix of the object type when serializing to JSON. So we need to be
1921
+ able to resolve a name, without tasking the user with appending .THING.json.
1922
+ This method returns an entry if it exists by a suffixed name.
1923
+
1924
+ Args:
1925
+ name: name used when adding
1926
+ """
1927
+ for wb_class in WBValue.type_mapping().values():
1928
+ wandb_file_name = wb_class.with_suffix(name)
1929
+ if entry := self.manifest.entries.get(wandb_file_name):
1930
+ return entry, wb_class
1931
+ return None, None
1932
+
1933
+ # Downloading.
1934
+
1935
+ @ensure_logged
1936
+ def download(
1937
+ self,
1938
+ root: StrPath | None = None,
1939
+ allow_missing_references: bool = False,
1940
+ skip_cache: bool | None = None,
1941
+ path_prefix: StrPath | None = None,
1942
+ multipart: bool | None = None,
1943
+ ) -> FilePathStr:
1944
+ """Download the contents of the artifact to the specified root directory.
1945
+
1946
+ Existing files located within `root` are not modified. Explicitly delete `root`
1947
+ before you call `download` if you want the contents of `root` to exactly match
1948
+ the artifact.
1949
+
1950
+ Args:
1951
+ root: The directory W&B stores the artifact's files.
1952
+ allow_missing_references: If set to `True`, any invalid reference paths
1953
+ will be ignored while downloading referenced files.
1954
+ skip_cache: If set to `True`, the artifact cache will be skipped when
1955
+ downloading and W&B will download each file into the default root or
1956
+ specified download directory.
1957
+ path_prefix: If specified, only files with a path that starts with the given
1958
+ prefix will be downloaded. Uses unix format (forward slashes).
1959
+ multipart: If set to `None` (default), the artifact will be downloaded
1960
+ in parallel using multipart download if individual file size is greater than
1961
+ 2GB. If set to `True` or `False`, the artifact will be downloaded in
1962
+ parallel or serially regardless of the file size.
1963
+
1964
+ Returns:
1965
+ The path to the downloaded contents.
1966
+
1967
+ Raises:
1968
+ ArtifactNotLoggedError: If the artifact is not logged.
1969
+ """
1970
+ root = FilePathStr(str(root or self._default_root()))
1971
+ self._add_download_root(root)
1972
+
1973
+ # TODO: download artifacts using core when implemented
1974
+ # if is_require_core():
1975
+ # return self._download_using_core(
1976
+ # root=root,
1977
+ # allow_missing_references=allow_missing_references,
1978
+ # skip_cache=bool(skip_cache),
1979
+ # path_prefix=path_prefix,
1980
+ # )
1981
+ return self._download(
1982
+ root=root,
1983
+ allow_missing_references=allow_missing_references,
1984
+ skip_cache=skip_cache,
1985
+ path_prefix=path_prefix,
1986
+ multipart=multipart,
1987
+ )
1988
+
1989
+ def _download_using_core(
1990
+ self,
1991
+ root: str,
1992
+ allow_missing_references: bool = False,
1993
+ skip_cache: bool = False,
1994
+ path_prefix: StrPath | None = None,
1995
+ ) -> FilePathStr:
1996
+ import pathlib
1997
+
1998
+ from wandb.sdk.backend.backend import Backend
1999
+
2000
+ # TODO: Create a special stream instead of relying on an existing run.
2001
+ if wandb.run is None:
2002
+ wl = wandb_setup.singleton()
2003
+
2004
+ stream_id = generate_id()
2005
+
2006
+ settings = wl.settings.to_proto()
2007
+ # TODO: remove this
2008
+ tmp_dir = pathlib.Path(tempfile.mkdtemp())
2009
+
2010
+ settings.sync_dir.value = str(tmp_dir)
2011
+ settings.sync_file.value = str(tmp_dir / f"{stream_id}.wandb")
2012
+ settings.files_dir.value = str(tmp_dir / "files")
2013
+ settings.run_id.value = stream_id
2014
+
2015
+ service = wl.ensure_service()
2016
+ service.inform_init(settings=settings, run_id=stream_id)
2017
+
2018
+ backend = Backend(settings=wl.settings, service=service)
2019
+ backend.ensure_launched()
2020
+
2021
+ assert backend.interface
2022
+ backend.interface._stream_id = stream_id # type: ignore
2023
+ else:
2024
+ assert wandb.run._backend
2025
+ backend = wandb.run._backend
2026
+
2027
+ assert backend.interface
2028
+ handle = backend.interface.deliver_download_artifact(
2029
+ self.id, # type: ignore
2030
+ root,
2031
+ allow_missing_references,
2032
+ skip_cache,
2033
+ path_prefix, # type: ignore
2034
+ )
2035
+ # TODO: Start the download process in the user process too, to handle reference downloads
2036
+ self._download(
2037
+ root=root,
2038
+ allow_missing_references=allow_missing_references,
2039
+ skip_cache=skip_cache,
2040
+ path_prefix=path_prefix,
2041
+ )
2042
+ result = handle.wait_or(timeout=None)
2043
+
2044
+ response = result.response.download_artifact_response
2045
+ if response.error_message:
2046
+ raise ValueError(f"Error downloading artifact: {response.error_message}")
2047
+
2048
+ return FilePathStr(root)
2049
+
2050
+ def _download(
2051
+ self,
2052
+ root: str,
2053
+ allow_missing_references: bool = False,
2054
+ skip_cache: bool | None = None,
2055
+ path_prefix: StrPath | None = None,
2056
+ multipart: bool | None = None,
2057
+ ) -> FilePathStr:
2058
+ nfiles = len(self.manifest.entries)
2059
+ size_mb = self.size / _MB
2060
+
2061
+ if log := (nfiles > 5000 or size_mb > 50):
2062
+ termlog(
2063
+ f"Downloading large artifact {self.name!r}, {size_mb:.2f}MB. {nfiles!r} files...",
2064
+ )
2065
+ start_time = time.monotonic()
2066
+
2067
+ download_logger = ArtifactDownloadLogger(nfiles=nfiles)
2068
+
2069
+ def _download_entry(
2070
+ entry: ArtifactManifestEntry,
2071
+ executor: concurrent.futures.Executor,
2072
+ api_key: str | None,
2073
+ cookies: dict | None,
2074
+ headers: dict | None,
2075
+ ) -> None:
2076
+ _thread_local_api_settings.api_key = api_key
2077
+ _thread_local_api_settings.cookies = cookies
2078
+ _thread_local_api_settings.headers = headers
2079
+
2080
+ try:
2081
+ entry.download(
2082
+ root,
2083
+ skip_cache=skip_cache,
2084
+ executor=executor,
2085
+ multipart=multipart,
2086
+ )
2087
+ except FileNotFoundError as e:
2088
+ if allow_missing_references:
2089
+ wandb.termwarn(str(e))
2090
+ return
2091
+ raise
2092
+ except _GCSIsADirectoryError as e:
2093
+ logger.debug(str(e))
2094
+ return
2095
+ download_logger.notify_downloaded()
2096
+
2097
+ with concurrent.futures.ThreadPoolExecutor(64) as executor:
2098
+ download_entry = partial(
2099
+ _download_entry,
2100
+ executor=executor,
2101
+ api_key=_thread_local_api_settings.api_key,
2102
+ cookies=_thread_local_api_settings.cookies,
2103
+ headers=_thread_local_api_settings.headers,
2104
+ )
2105
+
2106
+ batch_size = env.get_artifact_fetch_file_url_batch_size()
2107
+
2108
+ active_futures = set()
2109
+ cursor, has_more = None, True
2110
+ while has_more:
2111
+ files_page = self._fetch_file_urls(cursor=cursor, per_page=batch_size)
2112
+
2113
+ has_more = files_page.page_info.has_next_page
2114
+ cursor = files_page.page_info.end_cursor
2115
+
2116
+ # `File` nodes are formally nullable, so filter them out just in case.
2117
+ file_nodes = (e.node for e in files_page.edges if e.node)
2118
+ for node in file_nodes:
2119
+ entry = self.get_entry(node.name)
2120
+ # TODO: uncomment once artifact downloads are supported in core
2121
+ # if require_core and entry.ref is None:
2122
+ # # Handled by core
2123
+ # continue
2124
+ entry._download_url = node.direct_url
2125
+ if (not path_prefix) or entry.path.startswith(str(path_prefix)):
2126
+ active_futures.add(executor.submit(download_entry, entry))
2127
+
2128
+ # Wait for download threads to catch up.
2129
+ #
2130
+ # Extra context and observations (tonyyli):
2131
+ # - Even though the ThreadPoolExecutor limits the number of
2132
+ # concurrently-executed tasks, its internal task queue is unbounded.
2133
+ # The code below seems intended to ensure that at most `batch_size`
2134
+ # "backlogged" futures are held in memory at any given time. This seems like
2135
+ # a reasonable safeguard against unbounded memory consumption.
2136
+ #
2137
+ # - We should probably use a builtin (bounded) Queue or Semaphore here instead.
2138
+ # Consider this for a future change, or (depending on risk and risk tolerance)
2139
+ # managing this logic via asyncio instead, if viable.
2140
+ if len(active_futures) > batch_size:
2141
+ for future in concurrent.futures.as_completed(active_futures):
2142
+ future.result() # check for errors
2143
+ active_futures.remove(future)
2144
+ if len(active_futures) <= batch_size:
2145
+ break
2146
+
2147
+ # Check for errors.
2148
+ for future in concurrent.futures.as_completed(active_futures):
2149
+ future.result()
2150
+
2151
+ if log:
2152
+ # If you're wondering if we can display a `timedelta`, note that it
2153
+ # doesn't really support custom string format specifiers (compared to
2154
+ # e.g. `datetime` objs). To truncate the number of decimal places for
2155
+ # the seconds part, we manually convert/format each part below.
2156
+ dt_secs = abs(time.monotonic() - start_time)
2157
+ hrs, mins = divmod(dt_secs, 3600)
2158
+ mins, secs = divmod(mins, 60)
2159
+ termlog(
2160
+ f"Done. {int(hrs):02d}:{int(mins):02d}:{secs:04.1f} ({size_mb / dt_secs:.1f}MB/s)",
2161
+ prefix=False,
2162
+ )
2163
+ return FilePathStr(root)
2164
+
2165
+ @retry.retriable(
2166
+ retry_timedelta=timedelta(minutes=3),
2167
+ retryable_exceptions=(requests.RequestException),
2168
+ )
2169
+ def _fetch_file_urls(
2170
+ self, cursor: str | None, per_page: int = 5000
2171
+ ) -> FileUrlsFragment:
2172
+ if self._client is None:
2173
+ raise RuntimeError("Client not initialized")
2174
+
2175
+ if InternalApi()._server_supports(
2176
+ pb.ServerFeature.ARTIFACT_COLLECTION_MEMBERSHIP_FILES
2177
+ ):
2178
+ query = gql(ARTIFACT_COLLECTION_MEMBERSHIP_FILE_URLS_GQL)
2179
+ gql_vars = {
2180
+ "entityName": self.entity,
2181
+ "projectName": self.project,
2182
+ "artifactName": self.name.split(":")[0],
2183
+ "artifactVersionIndex": self.version,
2184
+ "cursor": cursor,
2185
+ "perPage": per_page,
2186
+ }
2187
+ data = self._client.execute(query, variable_values=gql_vars, timeout=60)
2188
+ result = ArtifactCollectionMembershipFileUrls.model_validate(data)
2189
+
2190
+ if not (
2191
+ (project := result.project)
2192
+ and (collection := project.artifact_collection)
2193
+ and (membership := collection.artifact_membership)
2194
+ and (files := membership.files)
2195
+ ):
2196
+ raise ValueError(f"Unable to fetch files for artifact: {self.name!r}")
2197
+ return files
2198
+ else:
2199
+ query = gql(ARTIFACT_FILE_URLS_GQL)
2200
+ gql_vars = {"id": self.id, "cursor": cursor, "perPage": per_page}
2201
+ data = self._client.execute(query, variable_values=gql_vars, timeout=60)
2202
+ result = ArtifactFileUrls.model_validate(data)
2203
+
2204
+ if not ((artifact := result.artifact) and (files := artifact.files)):
2205
+ raise ValueError(f"Unable to fetch files for artifact: {self.name!r}")
2206
+ return files
2207
+
2208
+ @ensure_logged
2209
+ def checkout(self, root: str | None = None) -> str:
2210
+ """Replace the specified root directory with the contents of the artifact.
2211
+
2212
+ WARNING: This will delete all files in `root` that are not included in the
2213
+ artifact.
2214
+
2215
+ Args:
2216
+ root: The directory to replace with this artifact's files.
2217
+
2218
+ Returns:
2219
+ The path of the checked out contents.
2220
+
2221
+ Raises:
2222
+ ArtifactNotLoggedError: If the artifact is not logged.
2223
+ """
2224
+ root = root or self._default_root(include_version=False)
2225
+
2226
+ for dirpath, _, files in os.walk(root):
2227
+ for file in files:
2228
+ full_path = os.path.join(dirpath, file)
2229
+ artifact_path = os.path.relpath(full_path, start=root)
2230
+ try:
2231
+ self.get_entry(artifact_path)
2232
+ except KeyError:
2233
+ # File is not part of the artifact, remove it.
2234
+ os.remove(full_path)
2235
+
2236
+ return self.download(root=root)
2237
+
2238
+ @ensure_logged
2239
+ def verify(self, root: str | None = None) -> None:
2240
+ """Verify that the contents of an artifact match the manifest.
2241
+
2242
+ All files in the directory are checksummed and the checksums are then
2243
+ cross-referenced against the artifact's manifest. References are not verified.
2244
+
2245
+ Args:
2246
+ root: The directory to verify. If None artifact will be downloaded to
2247
+ './artifacts/self.name/'.
2248
+
2249
+ Raises:
2250
+ ArtifactNotLoggedError: If the artifact is not logged.
2251
+ ValueError: If the verification fails.
2252
+ """
2253
+ root = root or self._default_root()
2254
+
2255
+ for dirpath, _, files in os.walk(root):
2256
+ for file in files:
2257
+ full_path = os.path.join(dirpath, file)
2258
+ artifact_path = os.path.relpath(full_path, start=root)
2259
+ try:
2260
+ self.get_entry(artifact_path)
2261
+ except KeyError:
2262
+ raise ValueError(
2263
+ f"Found file {full_path} which is not a member of artifact {self.name}"
2264
+ )
2265
+
2266
+ ref_count = 0
2267
+ for entry in self.manifest.entries.values():
2268
+ if entry.ref is None:
2269
+ if md5_file_b64(os.path.join(root, entry.path)) != entry.digest:
2270
+ raise ValueError(f"Digest mismatch for file: {entry.path}")
2271
+ else:
2272
+ ref_count += 1
2273
+ if ref_count > 0:
2274
+ termwarn(f"skipped verification of {ref_count} refs")
2275
+
2276
+ @ensure_logged
2277
+ def file(self, root: str | None = None) -> StrPath:
2278
+ """Download a single file artifact to the directory you specify with `root`.
2279
+
2280
+ Args:
2281
+ root: The root directory to store the file. Defaults to
2282
+ `./artifacts/self.name/`.
2283
+
2284
+ Returns:
2285
+ The full path of the downloaded file.
2286
+
2287
+ Raises:
2288
+ ArtifactNotLoggedError: If the artifact is not logged.
2289
+ ValueError: If the artifact contains more than one file.
2290
+ """
2291
+ if root is None:
2292
+ root = os.path.join(".", "artifacts", self.name)
2293
+
2294
+ if len(self.manifest.entries) > 1:
2295
+ raise ValueError(
2296
+ "This artifact contains more than one file, call `.download()` to get "
2297
+ 'all files or call .get_entry("filename").download()'
2298
+ )
2299
+
2300
+ return self.get_entry(list(self.manifest.entries)[0]).download(root)
2301
+
2302
+ @ensure_logged
2303
+ def files(
2304
+ self, names: list[str] | None = None, per_page: int = 50
2305
+ ) -> ArtifactFiles:
2306
+ """Iterate over all files stored in this artifact.
2307
+
2308
+ Args:
2309
+ names: The filename paths relative to the root of the artifact you wish to
2310
+ list.
2311
+ per_page: The number of files to return per request.
2312
+
2313
+ Returns:
2314
+ An iterator containing `File` objects.
2315
+
2316
+ Raises:
2317
+ ArtifactNotLoggedError: If the artifact is not logged.
2318
+ """
2319
+ return ArtifactFiles(self._client, self, names, per_page)
2320
+
2321
+ def _default_root(self, include_version: bool = True) -> FilePathStr:
2322
+ name = self.source_name if include_version else self.source_name.split(":")[0]
2323
+ root = os.path.join(env.get_artifact_dir(), name)
2324
+ # In case we're on a system where the artifact dir has a name corresponding to
2325
+ # an unexpected filesystem, we'll check for alternate roots. If one exists we'll
2326
+ # use that, otherwise we'll fall back to the system-preferred path.
2327
+ path = filesystem.check_exists(root) or filesystem.system_preferred_path(root)
2328
+ return FilePathStr(str(path))
2329
+
2330
+ def _add_download_root(self, dir_path: str) -> None:
2331
+ self._download_roots.add(os.path.abspath(dir_path))
2332
+
2333
+ def _local_path_to_name(self, file_path: str) -> str | None:
2334
+ """Convert a local file path to a path entry in the artifact."""
2335
+ abs_file_path = os.path.abspath(file_path)
2336
+ abs_file_parts = abs_file_path.split(os.sep)
2337
+ for i in range(len(abs_file_parts) + 1):
2338
+ if os.path.join(os.sep, *abs_file_parts[:i]) in self._download_roots:
2339
+ return os.path.join(*abs_file_parts[i:])
2340
+ return None
2341
+
2342
+ # Others.
2343
+
2344
+ @ensure_logged
2345
+ def delete(self, delete_aliases: bool = False) -> None:
2346
+ """Delete an artifact and its files.
2347
+
2348
+ If called on a linked artifact, only the link is deleted, and the
2349
+ source artifact is unaffected.
2350
+
2351
+ Use `artifact.unlink()` instead of `artifact.delete()` to remove a link between a source artifact and a linked artifact.
2352
+
2353
+ Args:
2354
+ delete_aliases: If set to `True`, deletes all aliases associated
2355
+ with the artifact. Otherwise, this raises an exception if
2356
+ the artifact has existing aliases. This parameter is ignored
2357
+ if the artifact is linked (a member of a portfolio collection).
2358
+
2359
+ Raises:
2360
+ ArtifactNotLoggedError: If the artifact is not logged.
2361
+ """
2362
+ if self.is_link:
2363
+ wandb.termwarn(
2364
+ "Deleting a link artifact will only unlink the artifact from the source artifact and not delete the source artifact and the data of the source artifact."
2365
+ )
2366
+ self._unlink()
2367
+ else:
2368
+ self._delete(delete_aliases)
2369
+
2370
+ @normalize_exceptions
2371
+ def _delete(self, delete_aliases: bool = False) -> None:
2372
+ if self._client is None:
2373
+ raise RuntimeError("Client not initialized for artifact mutations")
2374
+
2375
+ mutation = gql(DELETE_ARTIFACT_GQL)
2376
+ gql_vars = {"artifactID": self.id, "deleteAliases": delete_aliases}
2377
+
2378
+ self._client.execute(mutation, variable_values=gql_vars)
2379
+
2380
+ @normalize_exceptions
2381
+ def link(self, target_path: str, aliases: list[str] | None = None) -> Artifact:
2382
+ """Link this artifact to a portfolio (a promoted collection of artifacts).
2383
+
2384
+ Args:
2385
+ target_path: The path to the portfolio inside a project.
2386
+ The target path must adhere to one of the following
2387
+ schemas `{portfolio}`, `{project}/{portfolio}` or
2388
+ `{entity}/{project}/{portfolio}`.
2389
+ To link the artifact to the Model Registry, rather than to a generic
2390
+ portfolio inside a project, set `target_path` to the following
2391
+ schema `{"model-registry"}/{Registered Model Name}` or
2392
+ `{entity}/{"model-registry"}/{Registered Model Name}`.
2393
+ aliases: A list of strings that uniquely identifies the artifact
2394
+ inside the specified portfolio.
2395
+
2396
+ Raises:
2397
+ ArtifactNotLoggedError: If the artifact is not logged.
2398
+
2399
+ Returns:
2400
+ The linked artifact.
2401
+ """
2402
+ from wandb import Api
2403
+
2404
+ if self.is_link:
2405
+ wandb.termwarn(
2406
+ "Linking to a link artifact will result in directly linking to the source artifact of that link artifact."
2407
+ )
2408
+
2409
+ if self._client is None:
2410
+ raise ValueError("Client not initialized for artifact mutations")
2411
+
2412
+ # Save the artifact first if necessary
2413
+ if self.is_draft():
2414
+ if not self._is_draft_save_started():
2415
+ self.save(project=self.source_project)
2416
+
2417
+ # Wait until the artifact is committed before trying to link it.
2418
+ self.wait()
2419
+
2420
+ api = InternalApi()
2421
+ settings = api.settings()
2422
+
2423
+ target = ArtifactPath.from_str(target_path).with_defaults(
2424
+ project=settings.get("project") or "uncategorized",
2425
+ )
2426
+
2427
+ # Parse the entity (first part of the path) appropriately,
2428
+ # depending on whether we're linking to a registry
2429
+ if target.project and is_artifact_registry_project(target.project):
2430
+ # In a Registry linking, the entity is used to fetch the organization of the artifact
2431
+ # therefore the source artifact's entity is passed to the backend
2432
+ org = target.prefix or settings.get("organization") or ""
2433
+ target.prefix = api._resolve_org_entity_name(self.source_entity, org)
2434
+ else:
2435
+ target = target.with_defaults(prefix=self.source_entity)
2436
+
2437
+ # Prepare the validated GQL input, send it
2438
+ alias_inputs = [
2439
+ ArtifactAliasInput(artifact_collection_name=target.name, alias=a)
2440
+ for a in (aliases or [])
2441
+ ]
2442
+ gql_input = LinkArtifactInput(
2443
+ artifact_id=self.id,
2444
+ artifact_portfolio_name=target.name,
2445
+ entity_name=target.prefix,
2446
+ project_name=target.project,
2447
+ aliases=alias_inputs,
2448
+ )
2449
+ gql_vars = {"input": gql_input.model_dump(exclude_none=True)}
2450
+
2451
+ # Newer server versions can return `artifactMembership` directly in the response,
2452
+ # avoiding the need to re-fetch the linked artifact at the end.
2453
+ if api._server_supports(
2454
+ pb.ServerFeature.ARTIFACT_MEMBERSHIP_IN_LINK_ARTIFACT_RESPONSE
2455
+ ):
2456
+ omit_fragments = set()
2457
+ else:
2458
+ # FIXME: Make `gql_compat` omit nested fragment definitions recursively (but safely)
2459
+ omit_fragments = {
2460
+ "MembershipWithArtifact",
2461
+ "ArtifactFragment",
2462
+ "ArtifactFragmentWithoutAliases",
2463
+ }
2464
+
2465
+ gql_op = gql_compat(LINK_ARTIFACT_GQL, omit_fragments=omit_fragments)
2466
+ data = self._client.execute(gql_op, variable_values=gql_vars)
2467
+ result = LinkArtifact.model_validate(data).link_artifact
2468
+
2469
+ # Newer server versions can return artifactMembership directly in the response
2470
+ if result and (membership := result.artifact_membership):
2471
+ return self._from_membership(membership, target=target, client=self._client)
2472
+
2473
+ # Fallback to old behavior, which requires re-fetching the linked artifact to return it
2474
+ if not (result and (version_idx := result.version_index) is not None):
2475
+ raise ValueError("Unable to parse linked artifact version from response")
2476
+
2477
+ link_name = f"{target.to_str()}:v{version_idx}"
2478
+ return Api(overrides={"entity": self.source_entity})._artifact(link_name)
2479
+
2480
+ @ensure_logged
2481
+ def unlink(self) -> None:
2482
+ """Unlink this artifact if it is currently a member of a promoted collection of artifacts.
2483
+
2484
+ Raises:
2485
+ ArtifactNotLoggedError: If the artifact is not logged.
2486
+ ValueError: If the artifact is not linked, in other words,
2487
+ it is not a member of a portfolio collection.
2488
+ """
2489
+ # Fail early if this isn't a linked artifact to begin with
2490
+ if not self.is_link:
2491
+ raise ValueError(
2492
+ f"Artifact {self.qualified_name!r} is not a linked artifact and cannot be unlinked. "
2493
+ f"To delete it, use {self.delete.__qualname__!r} instead."
2494
+ )
2495
+
2496
+ self._unlink()
2497
+
2498
+ @normalize_exceptions
2499
+ def _unlink(self) -> None:
2500
+ if self._client is None:
2501
+ raise RuntimeError("Client not initialized for artifact mutations")
2502
+
2503
+ mutation = gql(UNLINK_ARTIFACT_GQL)
2504
+ gql_vars = {"artifactID": self.id, "artifactPortfolioID": self.collection.id}
2505
+
2506
+ try:
2507
+ self._client.execute(mutation, variable_values=gql_vars)
2508
+ except CommError as e:
2509
+ raise CommError(
2510
+ f"You do not have permission to unlink the artifact {self.qualified_name}"
2511
+ ) from e
2512
+
2513
+ @ensure_logged
2514
+ def used_by(self) -> list[Run]:
2515
+ """Get a list of the runs that have used this artifact and its linked artifacts.
2516
+
2517
+ Returns:
2518
+ A list of `Run` objects.
2519
+
2520
+ Raises:
2521
+ ArtifactNotLoggedError: If the artifact is not logged.
2522
+ """
2523
+ if self._client is None:
2524
+ raise RuntimeError("Client not initialized for artifact queries")
2525
+
2526
+ query = gql(ARTIFACT_USED_BY_GQL)
2527
+ gql_vars = {"id": self.id}
2528
+ data = self._client.execute(query, variable_values=gql_vars)
2529
+ result = ArtifactUsedBy.model_validate(data)
2530
+
2531
+ if (
2532
+ (artifact := result.artifact)
2533
+ and (used_by := artifact.used_by)
2534
+ and (edges := used_by.edges)
2535
+ ):
2536
+ run_nodes = (e.node for e in edges)
2537
+ return [
2538
+ Run(self._client, proj.entity_name, proj.name, run.name)
2539
+ for run in run_nodes
2540
+ if (proj := run.project)
2541
+ ]
2542
+ return []
2543
+
2544
+ @ensure_logged
2545
+ def logged_by(self) -> Run | None:
2546
+ """Get the W&B run that originally logged the artifact.
2547
+
2548
+ Returns:
2549
+ The name of the W&B run that originally logged the artifact.
2550
+
2551
+ Raises:
2552
+ ArtifactNotLoggedError: If the artifact is not logged.
2553
+ """
2554
+ if self._client is None:
2555
+ raise RuntimeError("Client not initialized for artifact queries")
2556
+
2557
+ query = gql(ARTIFACT_CREATED_BY_GQL)
2558
+ gql_vars = {"id": self.id}
2559
+ data = self._client.execute(query, variable_values=gql_vars)
2560
+ result = ArtifactCreatedBy.model_validate(data)
2561
+
2562
+ if (
2563
+ (artifact := result.artifact)
2564
+ and (creator := artifact.created_by)
2565
+ and (name := creator.name)
2566
+ and (project := creator.project)
2567
+ ):
2568
+ return Run(self._client, project.entity_name, project.name, name)
2569
+ return None
2570
+
2571
+ @ensure_logged
2572
+ def json_encode(self) -> dict[str, Any]:
2573
+ """Returns the artifact encoded to the JSON format.
2574
+
2575
+ Returns:
2576
+ A `dict` with `string` keys representing attributes of the artifact.
2577
+ """
2578
+ return artifact_to_json(self)
2579
+
2580
+ @staticmethod
2581
+ def _expected_type(
2582
+ entity_name: str, project_name: str, name: str, client: RetryingClient
2583
+ ) -> str | None:
2584
+ """Returns the expected type for a given artifact name and project."""
2585
+ query = gql(ARTIFACT_TYPE_GQL)
2586
+ gql_vars = {
2587
+ "entityName": entity_name,
2588
+ "projectName": project_name,
2589
+ "name": name if (":" in name) else f"{name}:latest",
2590
+ }
2591
+ data = client.execute(query, variable_values=gql_vars)
2592
+ result = ArtifactType.model_validate(data)
2593
+
2594
+ if (
2595
+ (project := result.project)
2596
+ and (artifact := project.artifact)
2597
+ and (artifact_type := artifact.artifact_type)
2598
+ ):
2599
+ return artifact_type.name
2600
+ return None
2601
+
2602
+ def _load_manifest(self, url: str) -> ArtifactManifest:
2603
+ with requests.get(url) as response:
2604
+ response.raise_for_status()
2605
+ return ArtifactManifest.from_manifest_json(response.json())
2606
+
2607
+ def _ttl_duration_seconds_to_gql(self) -> int | None:
2608
+ # Set artifact ttl value to ttl_duration_seconds if the user set a value
2609
+ # otherwise use ttl_status to indicate the backend INHERIT(-1) or DISABLED(-2) when the TTL is None
2610
+ # When ttl_change = None its a no op since nothing changed
2611
+ INHERIT = -1 # noqa: N806
2612
+ DISABLED = -2 # noqa: N806
2613
+
2614
+ if not self._ttl_changed:
2615
+ return None
2616
+ if self._ttl_is_inherited:
2617
+ return INHERIT
2618
+ return self._ttl_duration_seconds or DISABLED
2619
+
2620
+ def _fetch_linked_artifacts(self) -> list[Artifact]:
2621
+ """Fetches all linked artifacts from the server."""
2622
+ if self.id is None:
2623
+ raise ValueError(
2624
+ "Unable to find any artifact memberships for artifact without an ID"
2625
+ )
2626
+ if self._client is None:
2627
+ raise ValueError("Client is not initialized")
2628
+ response = self._client.execute(
2629
+ gql_compat(FETCH_LINKED_ARTIFACTS_GQL),
2630
+ variable_values={"artifactID": self.id},
2631
+ )
2632
+ result = FetchLinkedArtifacts.model_validate(response)
2633
+
2634
+ if not (
2635
+ (artifact := result.artifact)
2636
+ and (memberships := artifact.artifact_memberships)
2637
+ and (membership_edges := memberships.edges)
2638
+ ):
2639
+ raise ValueError("Unable to find any artifact memberships for artifact")
2640
+
2641
+ linked_artifacts: deque[Artifact] = deque()
2642
+ linked_nodes = (
2643
+ node
2644
+ for edge in membership_edges
2645
+ if (
2646
+ (node := edge.node)
2647
+ and (col := node.artifact_collection)
2648
+ and (col.typename__ == LINKED_ARTIFACT_COLLECTION_TYPE)
2649
+ )
2650
+ )
2651
+ for node in linked_nodes:
2652
+ # Trick for O(1) membership check that maintains order
2653
+ alias_names = dict.fromkeys(a.alias for a in node.aliases)
2654
+ version = f"v{node.version_index}"
2655
+ aliases = (
2656
+ [*alias_names, version]
2657
+ if version not in alias_names
2658
+ else [*alias_names]
2659
+ )
2660
+
2661
+ if not (
2662
+ node
2663
+ and (col := node.artifact_collection)
2664
+ and (proj := col.project)
2665
+ and (proj.entity_name and proj.name)
2666
+ ):
2667
+ raise ValueError("Unable to fetch fields for linked artifact")
2668
+
2669
+ link_fields = _LinkArtifactFields(
2670
+ entity_name=proj.entity_name,
2671
+ project_name=proj.name,
2672
+ name=f"{col.name}:{version}",
2673
+ version=version,
2674
+ aliases=aliases,
2675
+ )
2676
+ link = self._create_linked_artifact_using_source_artifact(link_fields)
2677
+ linked_artifacts.append(link)
2678
+ return list(linked_artifacts)
2679
+
2680
+ def _create_linked_artifact_using_source_artifact(
2681
+ self,
2682
+ link_fields: _LinkArtifactFields,
2683
+ ) -> Artifact:
2684
+ """Copies the source artifact to a linked artifact."""
2685
+ linked_artifact = copy(self)
2686
+ linked_artifact._version = link_fields.version
2687
+ linked_artifact._aliases = link_fields.aliases
2688
+ linked_artifact._saved_aliases = copy(link_fields.aliases)
2689
+ linked_artifact._name = link_fields.name
2690
+ linked_artifact._entity = link_fields.entity_name
2691
+ linked_artifact._project = link_fields.project_name
2692
+ linked_artifact._is_link = link_fields.is_link
2693
+ linked_artifact._linked_artifacts = link_fields.linked_artifacts
2694
+ return linked_artifact
2695
+
2696
+
2697
+ class _ArtifactVersionType(WBType):
2698
+ name = "artifactVersion"
2699
+ types = [Artifact]
2700
+
2701
+
2702
+ TypeRegistry.add(_ArtifactVersionType)