wandb 0.17.0__py3-none-macosx_11_0_arm64.whl

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