Spaces:
Sleeping

PERDYPTO commited on
Commit
3d033ab
·
verified ·
1 Parent(s): 81558c6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -277
app.py CHANGED
@@ -1,301 +1,95 @@
1
- """
2
- setup_db.py — run this ONCE (and again only when the source data changes)
3
-
4
- Pipeline, in order:
5
- 1. Download the raw DB from your HF bucket (skips if already present locally).
6
- 2. Inspect it: list every table, every column + type, row counts.
7
- Prints a full report to your terminal AND saves it to db_report.txt.
8
- 3. Build indexes on every table, on every column worth indexing
9
- (numeric/date columns for range queries + sorting, and reasonably
10
- low-cardinality text columns for filtering). Skips columns that
11
- already have an index. Skips huge free-text columns (e.g. long
12
- descriptions) since indexing those is expensive and useless for
13
- equality/range filtering.
14
- 4. Upload the newly-indexed DB back to the SAME HF bucket path,
15
- overwriting the original — so every future run (including your
16
- actual app.py) downloads an already-indexed DB and never has to
17
- do this again.
18
-
19
- After this finishes, paste the contents of db_report.txt back to Claude
20
- so app.py can be built against your real schema.
21
-
22
- Usage:
23
- python setup_db.py
24
- """
25
-
26
  import os
27
  import sqlite3
28
- import time
29
-
30
- from huggingface_hub import login, download_bucket_files
31
-
32
- DB_PATH = "github_pipeline.db"
33
- BUCKET = "PERDYPTO/db_snapshot"
34
- REMOTE_FILENAME = "github_pipeline.db" # path/filename inside the bucket
35
- REPORT_PATH = "db_report.txt"
36
-
37
- # Columns wider than this (avg text length) are skipped for indexing —
38
- # indexing a huge free-text "description" column is slow to build,
39
- # bloats the DB, and doesn't help equality/range filters anyway.
40
- MAX_AVG_LEN_FOR_INDEX = 200
41
-
42
- # A column is treated as "low-cardinality enough to filter on" if it has
43
- # at most this many distinct values. Only used for reporting/heuristics,
44
- # NOT to skip indexing (we index all numeric/date/short-text columns
45
- # regardless of cardinality, since indexes help sorting too).
46
- CATEGORY_CARDINALITY_CAP = 500
47
-
48
-
49
- def step1_download():
50
- print("=" * 70)
51
- print("STEP 1 — DOWNLOAD")
52
- print("=" * 70)
53
- if os.path.exists(DB_PATH):
54
- print(f"'{DB_PATH}' already exists locally, skipping download.")
55
- return
56
-
57
- token = os.environ.get("HF_TOKEN")
58
- if token:
59
- login(token=token, add_to_git_credential=False)
60
- else:
61
- print("WARNING: no HF_TOKEN env var found — this may fail if the bucket is private.")
62
-
63
- t0 = time.time()
64
- download_bucket_files(BUCKET, files=[(REMOTE_FILENAME, DB_PATH)])
65
- print(f"✅ Downloaded in {time.time() - t0:.1f}s")
66
-
67
-
68
- def step2_inspect(conn) -> list:
69
- print()
70
- print("=" * 70)
71
- print("STEP 2 — INSPECT")
72
- print("=" * 70)
73
-
74
- cur = conn.cursor()
75
- tables = cur.execute(
76
- "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';"
77
- ).fetchall()
78
-
79
- report_lines = []
80
-
81
- def out(line=""):
82
- print(line)
83
- report_lines.append(line)
84
-
85
- out(f"DATABASE: {DB_PATH}")
86
- out(f"Found {len(tables)} table(s): {', '.join(t[0] for t in tables)}")
87
- out()
88
-
89
- table_infos = []
90
 
91
- for (table_name,) in tables:
92
- out("-" * 70)
93
- out(f"TABLE: {table_name}")
94
- out("-" * 70)
95
 
96
- row_count = cur.execute(f'SELECT COUNT(*) FROM "{table_name}"').fetchone()[0]
97
- out(f"Row count: {row_count:,}")
98
 
99
- cols = cur.execute(f'PRAGMA table_info("{table_name}")').fetchall()
100
- # cols: cid, name, type, notnull, dflt_value, pk
101
- col_infos = []
102
- out(f"Columns ({len(cols)}):")
103
- for c in cols:
104
- cid, name, ctype, notnull, dflt, pk = c
105
- ctype = (ctype or "TEXT").upper()
106
- flags = []
107
- if pk:
108
- flags.append("PRIMARY KEY")
109
- if notnull:
110
- flags.append("NOT NULL")
111
- out(f" - {name:<28} {ctype:<12}{' [' + ', '.join(flags) + ']' if flags else ''}")
112
- col_infos.append({"name": name, "type": ctype, "pk": bool(pk)})
113
 
114
- existing_idx = cur.execute(f'PRAGMA index_list("{table_name}")').fetchall()
115
- existing_idx_cols = set()
116
- if existing_idx:
117
- out("Existing indexes:")
118
- for ix in existing_idx:
119
- idx_name = ix[1]
120
- idx_cols = cur.execute(f'PRAGMA index_info("{idx_name}")').fetchall()
121
- names = [ic[2] for ic in idx_cols]
122
- existing_idx_cols.update(names)
123
- out(f" - {idx_name} ON ({', '.join(names)})")
124
 
125
- # Sample cardinality + avg length for text columns (cheap-ish;
126
- # for very large tables this is still a scan per column, so we
127
- # only do it for reporting purposes here, once, as part of setup —
128
- # never at app runtime).
129
- out("Column stats:")
130
- for c in col_infos:
131
- name, ctype = c["name"], c["type"]
132
- is_textish = "CHAR" in ctype or "TEXT" in ctype or ctype == ""
133
- is_numeric = "INT" in ctype or "REAL" in ctype or "FLOA" in ctype or "DOUB" in ctype
134
- avg_len = None
135
- distinct = None
136
- if row_count > 0:
137
- try:
138
- if is_textish:
139
- avg_len = cur.execute(
140
- f'SELECT AVG(LENGTH("{name}")) FROM "{table_name}"'
141
- ).fetchone()[0]
142
- distinct = cur.execute(
143
- f'SELECT COUNT(DISTINCT "{name}") FROM "{table_name}"'
144
- ).fetchone()[0]
145
- except Exception as e:
146
- out(f" - {name}: (stat error: {e})")
147
- continue
148
- extra = []
149
- if avg_len is not None:
150
- extra.append(f"avg_len={avg_len:.0f}")
151
- if distinct is not None:
152
- extra.append(f"distinct={distinct:,}")
153
- out(f" - {name}: {', '.join(extra) if extra else '(empty table)'}")
154
- c["avg_len"] = avg_len
155
- c["distinct"] = distinct
156
- c["is_textish"] = is_textish
157
- c["is_numeric"] = is_numeric
158
- c["already_indexed"] = name in existing_idx_cols
159
 
160
- out()
161
- table_infos.append({
162
- "table": table_name,
163
- "row_count": row_count,
164
- "columns": col_infos,
165
- })
 
 
 
 
 
166
 
167
- with open(REPORT_PATH, "w") as f:
168
- f.write("\n".join(report_lines))
169
- out(f"(Full report also saved to {REPORT_PATH})")
170
-
171
- return table_infos
172
-
173
-
174
- def step3_index(conn, table_infos):
175
- print()
176
- print("=" * 70)
177
- print("STEP 3 — INDEX")
178
- print("=" * 70)
179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  cur = conn.cursor()
181
- created = 0
182
- skipped = 0
183
 
184
- for t in table_infos:
185
- table_name = t["table"]
186
- if t["row_count"] == 0:
187
- print(f" Skipping '{table_name}' (empty table).")
188
- continue
189
 
190
- for c in t["columns"]:
191
- name = c["name"]
 
192
 
193
- if c.get("already_indexed") or c.get("pk"):
194
- skipped += 1
195
- continue
 
196
 
197
- # Skip wide free-text columns — indexing them is expensive
198
- # and useless for equality/range filtering (e.g. long
199
- # descriptions, READMEs, commit messages).
200
- if c.get("is_textish") and c.get("avg_len") and c["avg_len"] > MAX_AVG_LEN_FOR_INDEX:
201
- print(f" Skipping {table_name}.{name} (avg text length "
202
- f"{c['avg_len']:.0f} > {MAX_AVG_LEN_FOR_INDEX}, not index-worthy)")
203
- skipped += 1
204
- continue
205
 
206
- # Skip columns that are entirely unique free text with no
207
- # apparent structure AND not numeric (heuristic safety net;
208
- # numeric/date columns are always worth indexing for range
209
- # queries and sorting regardless of cardinality).
210
- idx_name = f"idx_{table_name}_{name}"
211
- t0 = time.time()
212
  try:
213
  cur.execute(
214
- f'CREATE INDEX IF NOT EXISTS "{idx_name}" ON "{table_name}"("{name}")'
215
  )
216
- conn.commit()
217
- created += 1
218
- print(f" ✅ Indexed {table_name}.{name} ({time.time() - t0:.1f}s)")
219
- except Exception as e:
220
- print(f" ⚠️ Could not index {table_name}.{name}: {e}")
221
-
222
- print(f"\nDone. Created {created} new indexes, skipped {skipped} "
223
- f"(already indexed / not index-worthy).")
224
-
225
-
226
- def step4_upload():
227
- print()
228
- print("=" * 70)
229
- print("STEP 4 — UPLOAD INDEXED DB BACK TO HF BUCKET")
230
- print("=" * 70)
231
-
232
- token = os.environ.get("HF_TOKEN")
233
- if token:
234
- login(token=token, add_to_git_credential=False)
235
-
236
- # huggingface_hub's exact upload function name/signature varies by
237
- # version. Try the most likely candidates in order and tell you
238
- # clearly which one worked (or if none did, so you can upload
239
- # manually with `huggingface-cli upload` instead).
240
- import huggingface_hub as hfh
241
-
242
- attempts = []
243
 
244
- if hasattr(hfh, "upload_bucket_files"):
245
- attempts.append(("upload_bucket_files", lambda: hfh.upload_bucket_files(
246
- BUCKET, files=[(DB_PATH, REMOTE_FILENAME)]
247
- )))
248
- if hasattr(hfh, "upload_file"):
249
- attempts.append(("upload_file", lambda: hfh.upload_file(
250
- path_or_fileobj=DB_PATH,
251
- path_in_repo=REMOTE_FILENAME,
252
- repo_id=BUCKET,
253
- repo_type="dataset",
254
- )))
255
- if hasattr(hfh, "HfApi"):
256
- api = hfh.HfApi()
257
- attempts.append(("HfApi().upload_file", lambda: api.upload_file(
258
- path_or_fileobj=DB_PATH,
259
- path_in_repo=REMOTE_FILENAME,
260
- repo_id=BUCKET,
261
- repo_type="dataset",
262
- )))
263
-
264
- if not attempts:
265
- print("⚠️ Could not find a known upload function in your huggingface_hub install.")
266
- print(f" Upload '{DB_PATH}' to '{BUCKET}' manually, e.g.:")
267
- print(f" huggingface-cli upload {BUCKET} {DB_PATH} {REMOTE_FILENAME} --repo-type dataset")
268
- return
269
-
270
- for fn_name, fn in attempts:
271
- try:
272
- print(f"Trying huggingface_hub.{fn_name}() ...")
273
- fn()
274
- print(f"✅ Uploaded indexed DB back to '{BUCKET}' via {fn_name}!")
275
- return
276
- except Exception as e:
277
- print(f" {fn_name} failed: {e}")
278
-
279
- print("⚠️ All upload attempts failed. Upload manually with:")
280
- print(f" huggingface-cli upload {BUCKET} {DB_PATH} {REMOTE_FILENAME} --repo-type dataset")
281
-
282
-
283
- def main():
284
- step1_download()
285
-
286
- conn = sqlite3.connect(DB_PATH)
287
- table_infos = step2_inspect(conn)
288
- step3_index(conn, table_infos)
289
  conn.close()
290
-
291
- step4_upload()
292
-
293
- print()
294
- print("=" * 70)
295
- print("ALL DONE")
296
- print("=" * 70)
297
- print(f"Paste the contents of '{REPORT_PATH}' back to Claude so it can")
298
- print("build app.py against your real schema.")
 
299
 
300
 
301
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import sqlite3
3
+ import tempfile
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ from huggingface_hub import HfApi, list_bucket_tree, download_bucket_files, batch_bucket_files
 
 
 
6
 
7
+ TOKEN = os.environ["HF_TOKEN"]
 
8
 
9
+ SOURCE_BUCKET = "PERDYPTO/db_snapshot"
10
+ BACKUP_BUCKET = "PERDYPTO/sdafasdf-storage"
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ api = HfApi(token=TOKEN)
 
 
 
 
 
 
 
 
 
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ def find_db_file(bucket: str) -> str:
16
+ """Find the first .sqlite/.db/.sqlite3 file in the bucket (searches all prefixes)."""
17
+ candidates = []
18
+ for item in list_bucket_tree(bucket, token=TOKEN):
19
+ if item["type"] == "file" and item["path"].lower().endswith((".db", ".sqlite", ".sqlite3")):
20
+ candidates.append(item["path"])
21
+ if not candidates:
22
+ raise FileNotFoundError(f"No .db/.sqlite/.sqlite3 file found in bucket '{bucket}'")
23
+ if len(candidates) > 1:
24
+ print(f"[warn] multiple db files found in {bucket}: {candidates}. Using the first one.")
25
+ return candidates[0]
26
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ def main():
29
+ # 1. Backup: server-side copy from source bucket to backup bucket (no re-download needed)
30
+ print(f"[backup] copying hf://buckets/{SOURCE_BUCKET} -> hf://buckets/{BACKUP_BUCKET}")
31
+ api.copy_files(
32
+ f"hf://buckets/{SOURCE_BUCKET}",
33
+ f"hf://buckets/{BACKUP_BUCKET}",
34
+ )
35
+ print("[backup] done")
36
+
37
+ # 2. Locate and download the sqlite db from the source bucket
38
+ remote_db_path = find_db_file(SOURCE_BUCKET)
39
+ print(f"[download] found db at hf://buckets/{SOURCE_BUCKET}/{remote_db_path}")
40
+
41
+ workdir = tempfile.mkdtemp()
42
+ local_db_path = os.path.join(workdir, os.path.basename(remote_db_path))
43
+
44
+ download_bucket_files(
45
+ SOURCE_BUCKET,
46
+ [(remote_db_path, local_db_path)],
47
+ token=TOKEN,
48
+ )
49
+ print(f"[download] saved to {local_db_path}")
50
+
51
+ # 3. Index the db: create an index on every column of every table (skip if it already exists)
52
+ conn = sqlite3.connect(local_db_path)
53
  cur = conn.cursor()
 
 
54
 
55
+ cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
56
+ tables = [row[0] for row in cur.fetchall()]
 
 
 
57
 
58
+ print("=" * 60)
59
+ print(f"DATABASE SCHEMA: {len(tables)} table(s) found")
60
+ print("=" * 60)
61
 
62
+ for table in tables:
63
+ cur.execute(f'PRAGMA table_info("{table}")')
64
+ cols = cur.fetchall() # (cid, name, type, notnull, dflt_value, pk)
65
+ col_names = [c[1] for c in cols]
66
 
67
+ print(f"\nTable: {table}")
68
+ print(f" Column count: {len(col_names)}")
69
+ print(f" Columns: {', '.join(col_names)}")
 
 
 
 
 
70
 
71
+ for col_name in col_names:
72
+ index_name = f"idx_{table}_{col_name}"
 
 
 
 
73
  try:
74
  cur.execute(
75
+ f'CREATE INDEX IF NOT EXISTS "{index_name}" ON "{table}" ("{col_name}")'
76
  )
77
+ print(f" [index] ensured {index_name}")
78
+ except sqlite3.OperationalError as e:
79
+ print(f" [index] skipped {index_name}: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ conn.commit()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  conn.close()
83
+ print("=" * 60)
84
+
85
+ # 4. Upload the indexed db back to the source bucket (overwrite in place)
86
+ print(f"[upload] pushing indexed db back to hf://buckets/{SOURCE_BUCKET}/{remote_db_path}")
87
+ batch_bucket_files(
88
+ SOURCE_BUCKET,
89
+ add=[(local_db_path, remote_db_path)],
90
+ token=TOKEN,
91
+ )
92
+ print("[upload] done")
93
 
94
 
95
  if __name__ == "__main__":