posthog.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. def _get_user_id(self):
  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. logger.exception(f"Failed to send telemetry {event_name=}")