telemetry.py 2.3 KB

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