1
0

telemetry.py 2.6 KB

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