posthog.py 2.0 KB

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