_hf_folder.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # coding=utf-8
  2. # Copyright 2022-present, the HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Contain helper class to retrieve/store token from/to local cache."""
  16. from pathlib import Path
  17. from typing import Optional
  18. from .. import constants
  19. from ._auth import get_token
  20. class HfFolder:
  21. # TODO: deprecate when adapted in transformers/datasets/gradio
  22. # @_deprecate_method(version="1.0", message="Use `huggingface_hub.login` instead.")
  23. @classmethod
  24. def save_token(cls, token: str) -> None:
  25. """
  26. Save token, creating folder as needed.
  27. Token is saved in the huggingface home folder. You can configure it by setting
  28. the `HF_HOME` environment variable.
  29. Args:
  30. token (`str`):
  31. The token to save to the [`HfFolder`]
  32. """
  33. path_token = Path(constants.HF_TOKEN_PATH)
  34. path_token.parent.mkdir(parents=True, exist_ok=True)
  35. path_token.write_text(token)
  36. # TODO: deprecate when adapted in transformers/datasets/gradio
  37. # @_deprecate_method(version="1.0", message="Use `huggingface_hub.get_token` instead.")
  38. @classmethod
  39. def get_token(cls) -> Optional[str]:
  40. """
  41. Get token or None if not existent.
  42. This method is deprecated in favor of [`huggingface_hub.get_token`] but is kept for backward compatibility.
  43. Its behavior is the same as [`huggingface_hub.get_token`].
  44. Returns:
  45. `str` or `None`: The token, `None` if it doesn't exist.
  46. """
  47. return get_token()
  48. # TODO: deprecate when adapted in transformers/datasets/gradio
  49. # @_deprecate_method(version="1.0", message="Use `huggingface_hub.logout` instead.")
  50. @classmethod
  51. def delete_token(cls) -> None:
  52. """
  53. Deletes the token from storage. Does not fail if token does not exist.
  54. """
  55. try:
  56. Path(constants.HF_TOKEN_PATH).unlink()
  57. except FileNotFoundError:
  58. pass