posthog.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import json
  2. import logging
  3. import os
  4. import uuid
  5. from posthog import Posthog
  6. import embedchain
  7. from embedchain.constants import CONFIG_DIR, CONFIG_FILE
  8. class AnonymousTelemetry:
  9. def __init__(self, host="https://app.posthog.com", enabled=True):
  10. self.project_api_key = "phc_PHQDA5KwztijnSojsxJ2c1DuJd52QCzJzT2xnSGvjN2"
  11. self.host = host
  12. self.posthog = Posthog(project_api_key=self.project_api_key, host=self.host)
  13. self.user_id = self._get_user_id()
  14. self.enabled = enabled
  15. # Check if telemetry tracking is disabled via environment variable
  16. if "EC_TELEMETRY" in os.environ and os.environ["EC_TELEMETRY"].lower() not in [
  17. "1",
  18. "true",
  19. "yes",
  20. ]:
  21. self.enabled = False
  22. if not self.enabled:
  23. self.posthog.disabled = True
  24. # Silence posthog logging
  25. posthog_logger = logging.getLogger("posthog")
  26. posthog_logger.disabled = True
  27. @staticmethod
  28. def _get_user_id():
  29. os.makedirs(CONFIG_DIR, exist_ok=True)
  30. if os.path.exists(CONFIG_FILE):
  31. with open(CONFIG_FILE, "r") as f:
  32. data = json.load(f)
  33. if "user_id" in data:
  34. return data["user_id"]
  35. user_id = str(uuid.uuid4())
  36. with open(CONFIG_FILE, "w") as f:
  37. json.dump({"user_id": user_id}, f)
  38. return user_id
  39. def capture(self, event_name, properties=None):
  40. default_properties = {
  41. "version": embedchain.__version__,
  42. "language": "python",
  43. "pid": os.getpid(),
  44. }
  45. properties.update(default_properties)
  46. try:
  47. self.posthog.capture(self.user_id, event_name, properties)
  48. except Exception:
  49. logging.exception(f"Failed to send telemetry {event_name=}")