telemetry.py 2.7 KB

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