wandb 0.18.0rc1__py3-none-macosx_10_13_x86_64.whl

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