posthog.py 1.9 KB

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