telemetry.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. """Anonymous telemetry for Reflex."""
  2. from __future__ import annotations
  3. import json
  4. import multiprocessing
  5. import platform
  6. from datetime import datetime
  7. import psutil
  8. from reflex import constants
  9. from reflex.utils.prerequisites import ensure_reflex_installation_id
  10. def get_os() -> str:
  11. """Get the operating system.
  12. Returns:
  13. The operating system.
  14. """
  15. return platform.system()
  16. def get_python_version() -> str:
  17. """Get the Python version.
  18. Returns:
  19. The Python version.
  20. """
  21. return platform.python_version()
  22. def get_reflex_version() -> str:
  23. """Get the Reflex version.
  24. Returns:
  25. The Reflex version.
  26. """
  27. return constants.Reflex.VERSION
  28. def get_cpu_count() -> int:
  29. """Get the number of CPUs.
  30. Returns:
  31. The number of CPUs.
  32. """
  33. return multiprocessing.cpu_count()
  34. def get_memory() -> int:
  35. """Get the total memory in MB.
  36. Returns:
  37. The total memory in MB.
  38. """
  39. return psutil.virtual_memory().total >> 20
  40. def send(event: str, telemetry_enabled: bool | None = None) -> bool:
  41. """Send anonymous telemetry for Reflex.
  42. Args:
  43. event: The event name.
  44. telemetry_enabled: Whether to send the telemetry (If None, get from config).
  45. Returns:
  46. Whether the telemetry was sent successfully.
  47. """
  48. import httpx
  49. from reflex.config import get_config
  50. # Get the telemetry_enabled from the config if it is not specified.
  51. if telemetry_enabled is None:
  52. telemetry_enabled = get_config().telemetry_enabled
  53. # Return if telemetry is disabled.
  54. if not telemetry_enabled:
  55. return False
  56. installation_id = ensure_reflex_installation_id()
  57. if installation_id is None:
  58. return False
  59. try:
  60. with open(constants.Dirs.REFLEX_JSON) as f:
  61. reflex_json = json.load(f)
  62. project_hash = reflex_json["project_hash"]
  63. post_hog = {
  64. "api_key": "phc_JoMo0fOyi0GQAooY3UyO9k0hebGkMyFJrrCw1Gt5SGb",
  65. "event": event,
  66. "properties": {
  67. "distinct_id": installation_id,
  68. "distinct_app_id": project_hash,
  69. "user_os": get_os(),
  70. "reflex_version": get_reflex_version(),
  71. "python_version": get_python_version(),
  72. "cpu_count": get_cpu_count(),
  73. "memory": get_memory(),
  74. },
  75. "timestamp": datetime.utcnow().isoformat(),
  76. }
  77. httpx.post("https://app.posthog.com/capture/", json=post_hog)
  78. return True
  79. except Exception:
  80. return False