version.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from os import environ
  2. import requests
  3. from functools import cached_property
  4. from importlib.metadata import version as get_package_version, PackageNotFoundError
  5. from subprocess import check_output, CalledProcessError, PIPE
  6. from .errors import VersionNotFoundError
  7. class VersionUtils():
  8. @cached_property
  9. def current_version(self) -> str:
  10. # Read from package manager
  11. try:
  12. return get_package_version("g4f")
  13. except PackageNotFoundError:
  14. pass
  15. # Read from docker environment
  16. version = environ.get("G4F_VERSION")
  17. if version:
  18. return version
  19. # Read from git repository
  20. try:
  21. command = ["git", "describe", "--tags", "--abbrev=0"]
  22. return check_output(command, text=True, stderr=PIPE).strip()
  23. except CalledProcessError:
  24. pass
  25. raise VersionNotFoundError("Version not found")
  26. @cached_property
  27. def latest_version(self) -> str:
  28. try:
  29. get_package_version("g4f")
  30. response = requests.get("https://pypi.org/pypi/g4f/json").json()
  31. return response["info"]["version"]
  32. except PackageNotFoundError:
  33. url = "https://api.github.com/repos/xtekky/gpt4free/releases/latest"
  34. response = requests.get(url).json()
  35. return response["tag_name"]
  36. def check_pypi_version(self) -> None:
  37. try:
  38. if self.current_version != self.latest_version:
  39. print(f'New pypi version: {self.latest_version} (current: {self.version}) | pip install -U g4f')
  40. except Exception as e:
  41. print(f'Failed to check g4f pypi version: {e}')
  42. utils = VersionUtils()