Spaces:
Sleeping

dev-strender commited on
Commit
ed17f2a
·
1 Parent(s): b850bf1

Drop supabase SDK; call REST via httpx to avoid websockets conflict

Browse files
Files changed (2) hide show
  1. blindtest/db.py +92 -102
  2. requirements.txt +0 -2
blindtest/db.py CHANGED
@@ -1,11 +1,14 @@
1
- """Supabase client wrapper for blind test storage.
 
 
 
 
2
 
3
  Env vars:
4
- SUPABASE_URL — project URL
5
  SUPABASE_KEY — anon or service_role key
6
 
7
- If either is missing the module operates in no-op mode: writes are skipped
8
- and a warning is surfaced in the UI. This keeps local development smooth.
9
  """
10
 
11
  from __future__ import annotations
@@ -14,28 +17,65 @@ import os
14
  from dataclasses import dataclass
15
  from typing import Any
16
 
17
- try:
18
- from supabase import Client, create_client
19
- _import_error: str | None = None
20
- except ImportError as _imp_exc: # pragma: no cover
21
- Client = None # type: ignore[assignment,misc]
22
- create_client = None # type: ignore[assignment]
23
- _import_error = str(_imp_exc)
24
-
25
- # Startup diagnostic — visible in HF Space logs.
26
- _url_present = bool(os.getenv("SUPABASE_URL", "").strip())
27
- _key_present = bool(os.getenv("SUPABASE_KEY", "").strip())
28
  print(
29
- f"[blindtest.db] supabase import={'ok' if create_client else 'FAIL: ' + str(_import_error)}"
30
- f" | SUPABASE_URL={'set' if _url_present else 'MISSING'}"
31
- f" | SUPABASE_KEY={'set' if _key_present else 'MISSING'}"
32
  )
33
 
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  @dataclass
36
  class RunRecord:
37
- """Minimal view of a pipeline run for UI state."""
38
-
39
  run_id: int | None
40
  pipeline_key: str
41
  output: str
@@ -44,48 +84,17 @@ class RunRecord:
44
 
45
  @dataclass
46
  class TaskRecord:
47
- """A pairwise comparison task. slot_a_run/slot_b_run are the randomized
48
- assignments shown to the evaluator; run_a_id/run_b_id are the raw IDs
49
- persisted for aggregation."""
50
-
51
  task_id: int | None
52
  article_id: int | None
53
  slot_a_run: RunRecord
54
  slot_b_run: RunRecord
55
 
56
 
57
- def _get_client() -> Any | None:
58
- url = os.getenv("SUPABASE_URL", "").strip()
59
- key = os.getenv("SUPABASE_KEY", "").strip()
60
- if not url or not key or create_client is None:
61
- return None
62
- return create_client(url, key)
63
-
64
-
65
- _client_singleton: Any | None = None
66
- _client_initialized = False
67
-
68
-
69
- def get_client() -> Any | None:
70
- """Return a cached Supabase client or None if unconfigured."""
71
- global _client_singleton, _client_initialized
72
- if not _client_initialized:
73
- _client_singleton = _get_client()
74
- _client_initialized = True
75
- return _client_singleton
76
-
77
-
78
- def is_configured() -> bool:
79
- return get_client() is not None
80
-
81
-
82
  def save_article(source_text: str) -> int | None:
83
- c = get_client()
84
- if c is None:
85
  return None
86
  try:
87
- resp = c.table("articles").insert({"source_text": source_text}).execute()
88
- data = resp.data or []
89
  return data[0]["id"] if data else None
90
  except Exception as exc:
91
  _record_error("save_article", exc)
@@ -100,20 +109,20 @@ def save_pipeline_run(
100
  output: str,
101
  processing_time_s: float,
102
  ) -> int | None:
103
- c = get_client()
104
- if c is None or article_id is None:
105
  return None
106
- row = {
107
- "article_id": article_id,
108
- "pipeline_key": pipeline_key,
109
- "prompt_key": prompt_key,
110
- "model": model,
111
- "output": output,
112
- "processing_time_s": processing_time_s,
113
- }
114
  try:
115
- resp = c.table("pipeline_runs").insert(row).execute()
116
- data = resp.data or []
 
 
 
 
 
 
 
 
 
117
  return data[0]["id"] if data else None
118
  except Exception as exc:
119
  _record_error("save_pipeline_run", exc)
@@ -125,43 +134,27 @@ def save_task(
125
  run_a_id: int | None,
126
  run_b_id: int | None,
127
  ) -> int | None:
128
- c = get_client()
129
- if c is None or article_id is None:
130
  return None
131
  try:
132
- resp = (
133
- c.table("tasks")
134
- .insert({"article_id": article_id, "run_a_id": run_a_id, "run_b_id": run_b_id})
135
- .execute()
136
  )
137
- data = resp.data or []
138
  return data[0]["id"] if data else None
139
  except Exception as exc:
140
  _record_error("save_task", exc)
141
  return None
142
 
143
 
144
- _last_error: str | None = None
145
-
146
-
147
- def last_error() -> str | None:
148
- return _last_error
149
-
150
-
151
- def _record_error(where: str, exc: Exception) -> None:
152
- global _last_error
153
- _last_error = f"{where}: {exc}"
154
- print(f"[blindtest.db] {_last_error}")
155
-
156
-
157
  def save_vote(task_id: int | None, choice: str, comment: str) -> bool:
158
- c = get_client()
159
- if c is None or task_id is None:
160
  return False
161
  try:
162
- c.table("votes").insert(
163
- {"task_id": task_id, "choice": choice, "comment": comment or None}
164
- ).execute()
 
165
  return True
166
  except Exception as exc:
167
  _record_error("save_vote", exc)
@@ -169,27 +162,24 @@ def save_vote(task_id: int | None, choice: str, comment: str) -> bool:
169
 
170
 
171
  def fetch_summary() -> list[dict]:
172
- """Return list of {winner_pipeline, wins} from the vote_summary view."""
173
- c = get_client()
174
- if c is None:
175
  return []
176
  try:
177
- resp = c.table("vote_summary").select("*").execute()
178
- return resp.data or []
179
- except Exception:
180
  return []
181
 
182
 
183
  def fetch_vote_counts() -> dict[str, int]:
184
- """Return total vote counts by choice for quick progress display."""
185
- c = get_client()
186
- if c is None:
187
  return {}
188
  try:
189
- resp = c.table("votes").select("choice").execute()
190
  counts: dict[str, int] = {}
191
- for row in resp.data or []:
192
  counts[row["choice"]] = counts.get(row["choice"], 0) + 1
193
  return counts
194
- except Exception:
 
195
  return {}
 
1
+ """Supabase REST client (via httpx) for blind-test storage.
2
+
3
+ We call PostgREST endpoints directly to avoid pulling the full `supabase`
4
+ Python SDK (which drags `realtime` → `websockets>=13`, conflicting with
5
+ gradio-client 1.3's `websockets<13` pin).
6
 
7
  Env vars:
8
+ SUPABASE_URL — project URL (e.g. https://xxx.supabase.co)
9
  SUPABASE_KEY — anon or service_role key
10
 
11
+ If either is missing, all writes become no-ops.
 
12
  """
13
 
14
  from __future__ import annotations
 
17
  from dataclasses import dataclass
18
  from typing import Any
19
 
20
+ import httpx
21
+
22
+ _URL = os.getenv("SUPABASE_URL", "").strip().rstrip("/")
23
+ _KEY = os.getenv("SUPABASE_KEY", "").strip()
24
+
25
+ _last_error: str | None = None
26
+
 
 
 
 
27
  print(
28
+ f"[blindtest.db] httpx-rest"
29
+ f" | SUPABASE_URL={'set' if _URL else 'MISSING'}"
30
+ f" | SUPABASE_KEY={'set' if _KEY else 'MISSING'}"
31
  )
32
 
33
 
34
+ def is_configured() -> bool:
35
+ return bool(_URL and _KEY)
36
+
37
+
38
+ def last_error() -> str | None:
39
+ return _last_error
40
+
41
+
42
+ def _record_error(where: str, exc: Exception) -> None:
43
+ global _last_error
44
+ _last_error = f"{where}: {exc}"
45
+ print(f"[blindtest.db] {_last_error}")
46
+
47
+
48
+ def _headers(prefer_return: bool = True) -> dict[str, str]:
49
+ h = {
50
+ "apikey": _KEY,
51
+ "Authorization": f"Bearer {_KEY}",
52
+ "Content-Type": "application/json",
53
+ }
54
+ if prefer_return:
55
+ h["Prefer"] = "return=representation"
56
+ return h
57
+
58
+
59
+ def _post(table: str, row: dict) -> list[dict]:
60
+ url = f"{_URL}/rest/v1/{table}"
61
+ with httpx.Client(timeout=10.0) as c:
62
+ resp = c.post(url, headers=_headers(True), json=row)
63
+ if resp.status_code >= 300:
64
+ raise RuntimeError(f"{resp.status_code} {resp.text}")
65
+ return resp.json() if resp.content else []
66
+
67
+
68
+ def _get(table: str, params: dict[str, str] | None = None) -> list[dict]:
69
+ url = f"{_URL}/rest/v1/{table}"
70
+ with httpx.Client(timeout=10.0) as c:
71
+ resp = c.get(url, headers=_headers(False), params=params or {})
72
+ if resp.status_code >= 300:
73
+ raise RuntimeError(f"{resp.status_code} {resp.text}")
74
+ return resp.json() if resp.content else []
75
+
76
+
77
  @dataclass
78
  class RunRecord:
 
 
79
  run_id: int | None
80
  pipeline_key: str
81
  output: str
 
84
 
85
  @dataclass
86
  class TaskRecord:
 
 
 
 
87
  task_id: int | None
88
  article_id: int | None
89
  slot_a_run: RunRecord
90
  slot_b_run: RunRecord
91
 
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  def save_article(source_text: str) -> int | None:
94
+ if not is_configured():
 
95
  return None
96
  try:
97
+ data = _post("articles", {"source_text": source_text})
 
98
  return data[0]["id"] if data else None
99
  except Exception as exc:
100
  _record_error("save_article", exc)
 
109
  output: str,
110
  processing_time_s: float,
111
  ) -> int | None:
112
+ if not is_configured() or article_id is None:
 
113
  return None
 
 
 
 
 
 
 
 
114
  try:
115
+ data = _post(
116
+ "pipeline_runs",
117
+ {
118
+ "article_id": article_id,
119
+ "pipeline_key": pipeline_key,
120
+ "prompt_key": prompt_key,
121
+ "model": model,
122
+ "output": output,
123
+ "processing_time_s": processing_time_s,
124
+ },
125
+ )
126
  return data[0]["id"] if data else None
127
  except Exception as exc:
128
  _record_error("save_pipeline_run", exc)
 
134
  run_a_id: int | None,
135
  run_b_id: int | None,
136
  ) -> int | None:
137
+ if not is_configured() or article_id is None:
 
138
  return None
139
  try:
140
+ data = _post(
141
+ "tasks",
142
+ {"article_id": article_id, "run_a_id": run_a_id, "run_b_id": run_b_id},
 
143
  )
 
144
  return data[0]["id"] if data else None
145
  except Exception as exc:
146
  _record_error("save_task", exc)
147
  return None
148
 
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  def save_vote(task_id: int | None, choice: str, comment: str) -> bool:
151
+ if not is_configured() or task_id is None:
 
152
  return False
153
  try:
154
+ _post(
155
+ "votes",
156
+ {"task_id": task_id, "choice": choice, "comment": comment or None},
157
+ )
158
  return True
159
  except Exception as exc:
160
  _record_error("save_vote", exc)
 
162
 
163
 
164
  def fetch_summary() -> list[dict]:
165
+ if not is_configured():
 
 
166
  return []
167
  try:
168
+ return _get("vote_summary", {"select": "*"})
169
+ except Exception as exc:
170
+ _record_error("fetch_summary", exc)
171
  return []
172
 
173
 
174
  def fetch_vote_counts() -> dict[str, int]:
175
+ if not is_configured():
 
 
176
  return {}
177
  try:
178
+ rows = _get("votes", {"select": "choice"})
179
  counts: dict[str, int] = {}
180
+ for row in rows:
181
  counts[row["choice"]] = counts.get(row["choice"], 0) + 1
182
  return counts
183
+ except Exception as exc:
184
+ _record_error("fetch_vote_counts", exc)
185
  return {}
requirements.txt CHANGED
@@ -8,5 +8,3 @@ huggingface_hub>=0.19,<1.0
8
  openai>=1.0
9
  python-dotenv>=1.0
10
  kss>=6.0
11
- supabase>=2.0
12
- websockets>=13
 
8
  openai>=1.0
9
  python-dotenv>=1.0
10
  kss>=6.0