JustQuiteMadMax commited on
Commit
fba7f09
·
verified ·
1 Parent(s): 2536b39

Upload analytics.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. analytics.py +61 -0
analytics.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ import datetime as dt
4
+ import sys
5
+ from typing import Optional
6
+
7
+ from supabase import create_client, Client
8
+
9
+
10
+ def _utc_now_iso() -> str:
11
+ return dt.datetime.now(dt.timezone.utc).isoformat()
12
+
13
+
14
+ class AnalyticsLogger:
15
+ """
16
+ Simple Supabase logger for:
17
+ - Sessions (id: uuid, created_at: timestamptz)
18
+ - Chats (id: uuid, session_id: uuid, timestamp: timestamptz, user: text, answer: text)
19
+ """
20
+
21
+ def __init__(self):
22
+ url = os.getenv("SUPABASE_URL")
23
+ key = os.getenv("SUPABASE_KEY")
24
+ if not url or not key:
25
+ raise RuntimeError("Missing SUPABASE_URL or SUPABASE_KEY env var.")
26
+ self.client: Client = create_client(url, key)
27
+ self.session_id: Optional[str] = None
28
+
29
+ def start_session(self, model_id: str) -> str:
30
+ """
31
+ Creates a session row and returns the session UUID (string).
32
+ """
33
+ sid = str(uuid.uuid4())
34
+ payload = {"id": sid, "created_at": _utc_now_iso(), "model_id": model_id}
35
+ try:
36
+ self.client.table("Sessions").insert(payload).execute()
37
+ self.session_id = sid
38
+ return sid
39
+ except Exception as e:
40
+ print(f"[AnalyticsLogger] Failed to start session: {e}", file=sys.stderr)
41
+ raise e
42
+
43
+ def log_interaction(self, user: str, answer: str, ts_iso: Optional[str] = None) -> None:
44
+ """
45
+ Inserts a single chat interaction.
46
+ """
47
+ if not self.session_id:
48
+ raise ValueError("Session not started. Call start_session() first.")
49
+ session_id = self.session_id
50
+
51
+ chat_payload = {
52
+ "id": str(uuid.uuid4()),
53
+ "session_id": session_id,
54
+ "timestamp": ts_iso or _utc_now_iso(),
55
+ "user": user,
56
+ "answer": answer,
57
+ }
58
+ try:
59
+ self.client.table("Chats").insert(chat_payload).execute()
60
+ except Exception as e:
61
+ print(f"[AnalyticsLogger] Failed to log interaction: {e}", file=sys.stderr)