PERDYPTO commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,121 +1,294 @@
|
|
| 1 |
"""
|
| 2 |
-
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
Copy the ENTIRE output back to Claude so it can build the full explorer
|
| 14 |
-
using your real schema instead of guessing.
|
| 15 |
"""
|
| 16 |
|
|
|
|
| 17 |
import sqlite3
|
| 18 |
-
import
|
| 19 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
conn = sqlite3.connect(DB_PATH)
|
| 26 |
conn.row_factory = sqlite3.Row
|
| 27 |
cur = conn.cursor()
|
| 28 |
|
| 29 |
-
print("=" * 70)
|
| 30 |
-
print(f"DATABASE REPORT: {DB_PATH}")
|
| 31 |
-
print("=" * 70)
|
| 32 |
-
|
| 33 |
-
# 1. List all tables
|
| 34 |
tables = cur.execute(
|
| 35 |
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';"
|
| 36 |
).fetchall()
|
| 37 |
|
| 38 |
-
|
| 39 |
-
print("No tables found. Is this the right database file?")
|
| 40 |
-
return
|
| 41 |
-
|
| 42 |
-
print(f"\nFound {len(tables)} table(s): {', '.join(t['name'] for t in tables)}\n")
|
| 43 |
|
| 44 |
for t in tables:
|
| 45 |
table_name = t["name"]
|
| 46 |
-
print("-" * 70)
|
| 47 |
-
print(f"TABLE: {table_name}")
|
| 48 |
-
print("-" * 70)
|
| 49 |
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
try:
|
| 52 |
row_count = cur.execute(f'SELECT COUNT(*) FROM "{table_name}"').fetchone()[0]
|
| 53 |
-
except Exception
|
| 54 |
-
row_count =
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
if
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
sample_dict[k] = v[:120] + "...(truncated)"
|
| 88 |
-
print(json.dumps(sample_dict, indent=2, default=str))
|
| 89 |
-
except Exception as e:
|
| 90 |
-
print(f"Could not fetch sample row: {e}")
|
| 91 |
-
|
| 92 |
-
# For likely-categorical text columns, show distinct value counts (cheap heuristic)
|
| 93 |
-
for c in cols:
|
| 94 |
-
col_name = c["name"]
|
| 95 |
-
col_type = (c["type"] or "").upper()
|
| 96 |
-
if "CHAR" in col_type or "TEXT" in col_type or col_type == "":
|
| 97 |
-
try:
|
| 98 |
-
distinct_count = cur.execute(
|
| 99 |
-
f'SELECT COUNT(DISTINCT "{col_name}") FROM "{table_name}"'
|
| 100 |
-
).fetchone()[0]
|
| 101 |
-
# Only show if it looks like a low-cardinality "category" column
|
| 102 |
-
if isinstance(row_count, int) and row_count > 0 and distinct_count <= 30:
|
| 103 |
-
vals = cur.execute(
|
| 104 |
-
f'SELECT DISTINCT "{col_name}" FROM "{table_name}" '
|
| 105 |
-
f'WHERE "{col_name}" IS NOT NULL LIMIT 30'
|
| 106 |
-
).fetchall()
|
| 107 |
-
val_list = [v[0] for v in vals]
|
| 108 |
-
print(f" -> '{col_name}' looks categorical ({distinct_count} distinct): {val_list}")
|
| 109 |
-
except Exception:
|
| 110 |
-
pass
|
| 111 |
-
|
| 112 |
-
print()
|
| 113 |
|
| 114 |
conn.close()
|
| 115 |
-
print("
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
app.py — dynamic GitHub pipeline explorer
|
| 3 |
|
| 4 |
+
On startup this:
|
| 5 |
+
1. Downloads the DB from the HF bucket (if not already present).
|
| 6 |
+
2. Introspects EVERY table and EVERY column that actually exists
|
| 7 |
+
(via sqlite_master + PRAGMA table_info) — nothing is hardcoded.
|
| 8 |
+
3. For text/low-cardinality columns, precomputes the distinct values
|
| 9 |
+
so the frontend can build filter dropdowns automatically.
|
| 10 |
+
4. Serves a generic API that can sort/filter/paginate/search ANY
|
| 11 |
+
table by ANY column, ascending or descending.
|
| 12 |
|
| 13 |
+
No column or table name is hardcoded anywhere below "metadata" used
|
| 14 |
+
to be hardcoded — add new tables/columns to the DB and they show up
|
| 15 |
+
automatically, with no code changes.
|
|
|
|
|
|
|
|
|
|
| 16 |
"""
|
| 17 |
|
| 18 |
+
import os
|
| 19 |
import sqlite3
|
| 20 |
+
import threading
|
| 21 |
+
from fastapi import FastAPI, Query, HTTPException
|
| 22 |
+
from fastapi.responses import FileResponse, JSONResponse
|
| 23 |
+
from huggingface_hub import login, download_bucket_files
|
| 24 |
+
|
| 25 |
+
DB_PATH = "github_pipeline.db"
|
| 26 |
+
BUCKET = "PERDYPTO/db_snapshot"
|
| 27 |
+
|
| 28 |
+
# How many distinct values a text column can have before we stop
|
| 29 |
+
# treating it as a "filterable category" (avoid dumping 50k repo names
|
| 30 |
+
# into a dropdown).
|
| 31 |
+
MAX_CATEGORY_VALUES = 200
|
| 32 |
+
|
| 33 |
+
app = FastAPI()
|
| 34 |
+
db_lock = threading.Lock()
|
| 35 |
|
| 36 |
+
# Populated once at startup by introspect_schema(). Structure:
|
| 37 |
+
# {
|
| 38 |
+
# "table_name": {
|
| 39 |
+
# "columns": [{"name": ..., "type": ..., "pk": bool}, ...],
|
| 40 |
+
# "row_count": int,
|
| 41 |
+
# "categorical": {"col_name": [val1, val2, ...], ...}
|
| 42 |
+
# },
|
| 43 |
+
# ...
|
| 44 |
+
# }
|
| 45 |
+
SCHEMA_CACHE = {}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def download_db_if_needed():
|
| 49 |
+
if os.path.exists(DB_PATH):
|
| 50 |
+
print("Database already exists.")
|
| 51 |
+
return
|
| 52 |
|
| 53 |
+
print("Downloading full database from HF Bucket... (this can take a minute)")
|
| 54 |
+
token = os.environ.get("HF_TOKEN")
|
| 55 |
+
if token:
|
| 56 |
+
login(token=token, add_to_git_credential=False)
|
| 57 |
|
| 58 |
+
download_bucket_files(BUCKET, files=[("github_pipeline.db", DB_PATH)])
|
| 59 |
+
print("✅ Database downloaded successfully!")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def introspect_schema():
|
| 63 |
+
"""Discover every table and column that actually exists in the DB,
|
| 64 |
+
and precompute helpful metadata (row counts, categorical values)."""
|
| 65 |
+
print("Introspecting database schema...")
|
| 66 |
conn = sqlite3.connect(DB_PATH)
|
| 67 |
conn.row_factory = sqlite3.Row
|
| 68 |
cur = conn.cursor()
|
| 69 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
tables = cur.execute(
|
| 71 |
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';"
|
| 72 |
).fetchall()
|
| 73 |
|
| 74 |
+
schema = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
for t in tables:
|
| 77 |
table_name = t["name"]
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
cols_raw = cur.execute(f'PRAGMA table_info("{table_name}")').fetchall()
|
| 80 |
+
columns = [
|
| 81 |
+
{"name": c["name"], "type": (c["type"] or "TEXT").upper(), "pk": bool(c["pk"])}
|
| 82 |
+
for c in cols_raw
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
try:
|
| 86 |
row_count = cur.execute(f'SELECT COUNT(*) FROM "{table_name}"').fetchone()[0]
|
| 87 |
+
except Exception:
|
| 88 |
+
row_count = 0
|
| 89 |
+
|
| 90 |
+
categorical = {}
|
| 91 |
+
for c in columns:
|
| 92 |
+
col_type = c["type"]
|
| 93 |
+
is_textish = "CHAR" in col_type or "TEXT" in col_type or col_type == ""
|
| 94 |
+
# Booleans/small ints (e.g. is_fork, archived stored as 0/1) are
|
| 95 |
+
# also useful as filters — detect low-cardinality integer cols too.
|
| 96 |
+
is_intish = "INT" in col_type
|
| 97 |
+
|
| 98 |
+
if not (is_textish or is_intish) or row_count == 0:
|
| 99 |
+
continue
|
| 100 |
+
try:
|
| 101 |
+
distinct_count = cur.execute(
|
| 102 |
+
f'SELECT COUNT(DISTINCT "{c["name"]}") FROM "{table_name}"'
|
| 103 |
+
).fetchone()[0]
|
| 104 |
+
if 0 < distinct_count <= MAX_CATEGORY_VALUES:
|
| 105 |
+
vals = cur.execute(
|
| 106 |
+
f'SELECT DISTINCT "{c["name"]}" FROM "{table_name}" '
|
| 107 |
+
f'WHERE "{c["name"]}" IS NOT NULL ORDER BY "{c["name"]}" LIMIT ?',
|
| 108 |
+
(MAX_CATEGORY_VALUES,),
|
| 109 |
+
).fetchall()
|
| 110 |
+
categorical[c["name"]] = [v[0] for v in vals]
|
| 111 |
+
except Exception:
|
| 112 |
+
pass
|
| 113 |
+
|
| 114 |
+
schema[table_name] = {
|
| 115 |
+
"columns": columns,
|
| 116 |
+
"row_count": row_count,
|
| 117 |
+
"categorical": categorical,
|
| 118 |
+
}
|
| 119 |
+
print(f" -> {table_name}: {row_count} rows, {len(columns)} columns, "
|
| 120 |
+
f"{len(categorical)} filterable columns")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
conn.close()
|
| 123 |
+
print("✅ Schema introspection complete!")
|
| 124 |
+
return schema
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@app.on_event("startup")
|
| 128 |
+
async def startup_event():
|
| 129 |
+
download_db_if_needed()
|
| 130 |
+
global SCHEMA_CACHE
|
| 131 |
+
SCHEMA_CACHE = introspect_schema()
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def get_db():
|
| 135 |
+
conn = sqlite3.connect(DB_PATH, check_same_thread=False, timeout=30)
|
| 136 |
+
conn.row_factory = sqlite3.Row
|
| 137 |
+
return conn
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _validate_table(table: str) -> dict:
|
| 141 |
+
if table not in SCHEMA_CACHE:
|
| 142 |
+
raise HTTPException(status_code=404, detail=f"Unknown table '{table}'")
|
| 143 |
+
return SCHEMA_CACHE[table]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _column_names(table: str) -> list:
|
| 147 |
+
return [c["name"] for c in SCHEMA_CACHE[table]["columns"]]
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@app.get("/")
|
| 151 |
+
async def index():
|
| 152 |
+
return FileResponse("static/index.html")
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@app.get("/api/schema")
|
| 156 |
+
async def get_schema():
|
| 157 |
+
"""Return the full discovered schema so the frontend can build itself
|
| 158 |
+
dynamically: tables, columns, types, row counts, and filter options."""
|
| 159 |
+
return JSONResponse(SCHEMA_CACHE)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
@app.get("/api/stats")
|
| 163 |
+
async def get_stats(table: str = Query(...)):
|
| 164 |
+
"""Generic overview stats for any table: total rows, and a breakdown
|
| 165 |
+
for every categorical column that was discovered (e.g. language
|
| 166 |
+
counts, fork/archived counts — whatever the table actually has)."""
|
| 167 |
+
info = _validate_table(table)
|
| 168 |
+
db = get_db()
|
| 169 |
+
|
| 170 |
+
total = info["row_count"]
|
| 171 |
+
breakdowns = {}
|
| 172 |
+
|
| 173 |
+
for col in info["categorical"].keys():
|
| 174 |
+
rows = db.execute(
|
| 175 |
+
f'SELECT "{col}" as val, COUNT(*) as count '
|
| 176 |
+
f'FROM "{table}" WHERE "{col}" IS NOT NULL '
|
| 177 |
+
f'GROUP BY "{col}" ORDER BY count DESC LIMIT 15'
|
| 178 |
+
).fetchall()
|
| 179 |
+
breakdowns[col] = [dict(r) for r in rows]
|
| 180 |
+
|
| 181 |
+
db.close()
|
| 182 |
+
|
| 183 |
+
return JSONResponse({
|
| 184 |
+
"table": table,
|
| 185 |
+
"total_rows": total,
|
| 186 |
+
"breakdowns": breakdowns,
|
| 187 |
+
})
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
from starlette.requests import Request # noqa: E402
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@app.get("/api/rows")
|
| 194 |
+
async def get_rows(
|
| 195 |
+
request: Request,
|
| 196 |
+
table: str = Query(...),
|
| 197 |
+
sort_by: str = Query(None),
|
| 198 |
+
sort_dir: str = Query("desc"),
|
| 199 |
+
search: str = Query(""),
|
| 200 |
+
search_columns: str = Query(""),
|
| 201 |
+
limit: int = Query(50, ge=1, le=1000),
|
| 202 |
+
offset: int = Query(0, ge=0),
|
| 203 |
+
):
|
| 204 |
+
info = _validate_table(table)
|
| 205 |
+
valid_cols = _column_names(table)
|
| 206 |
+
|
| 207 |
+
if sort_by and sort_by not in valid_cols:
|
| 208 |
+
raise HTTPException(status_code=400, detail=f"Unknown column '{sort_by}' for sort_by")
|
| 209 |
+
if not sort_by:
|
| 210 |
+
sort_by = valid_cols[0]
|
| 211 |
+
sort_dir = "ASC" if sort_dir.lower() == "asc" else "DESC"
|
| 212 |
+
|
| 213 |
+
where_clauses = []
|
| 214 |
+
params = []
|
| 215 |
+
|
| 216 |
+
# Free text search across text-ish columns
|
| 217 |
+
if search:
|
| 218 |
+
text_cols = [
|
| 219 |
+
c["name"] for c in info["columns"]
|
| 220 |
+
if "CHAR" in c["type"] or "TEXT" in c["type"] or c["type"] == ""
|
| 221 |
+
]
|
| 222 |
+
if search_columns:
|
| 223 |
+
requested = [c.strip() for c in search_columns.split(",") if c.strip()]
|
| 224 |
+
text_cols = [c for c in text_cols if c in requested]
|
| 225 |
+
if text_cols:
|
| 226 |
+
like_clauses = " OR ".join([f'"{c}" LIKE ?' for c in text_cols])
|
| 227 |
+
where_clauses.append(f"({like_clauses})")
|
| 228 |
+
params.extend([f"%{search}%"] * len(text_cols))
|
| 229 |
+
|
| 230 |
+
# Dynamic per-column equality filters: ?filter_<column>=<value>
|
| 231 |
+
# Supports comma-separated multi-value (IN clause) and min_/max_ range prefixes
|
| 232 |
+
# for numeric columns, e.g. ?filter_min_stars=100&filter_max_stars=5000
|
| 233 |
+
for key, value in request.query_params.items():
|
| 234 |
+
if not key.startswith("filter_") or value == "":
|
| 235 |
+
continue
|
| 236 |
+
raw = key[len("filter_"):]
|
| 237 |
+
|
| 238 |
+
if raw.startswith("min_"):
|
| 239 |
+
col = raw[4:]
|
| 240 |
+
if col in valid_cols:
|
| 241 |
+
where_clauses.append(f'"{col}" >= ?')
|
| 242 |
+
params.append(value)
|
| 243 |
+
continue
|
| 244 |
+
if raw.startswith("max_"):
|
| 245 |
+
col = raw[4:]
|
| 246 |
+
if col in valid_cols:
|
| 247 |
+
where_clauses.append(f'"{col}" <= ?')
|
| 248 |
+
params.append(value)
|
| 249 |
+
continue
|
| 250 |
+
|
| 251 |
+
col = raw
|
| 252 |
+
if col not in valid_cols:
|
| 253 |
+
continue
|
| 254 |
+
values = [v for v in value.split(",") if v != ""]
|
| 255 |
+
if not values:
|
| 256 |
+
continue
|
| 257 |
+
placeholders = ",".join(["?"] * len(values))
|
| 258 |
+
where_clauses.append(f'"{col}" IN ({placeholders})')
|
| 259 |
+
params.extend(values)
|
| 260 |
+
|
| 261 |
+
where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
|
| 262 |
+
|
| 263 |
+
db = get_db()
|
| 264 |
+
|
| 265 |
+
count_sql = f'SELECT COUNT(*) FROM "{table}" {where_sql}'
|
| 266 |
+
total = db.execute(count_sql, params).fetchone()[0]
|
| 267 |
+
|
| 268 |
+
col_list = ", ".join([f'"{c}"' for c in valid_cols])
|
| 269 |
+
row_sql = (
|
| 270 |
+
f'SELECT {col_list} FROM "{table}" {where_sql} '
|
| 271 |
+
f'ORDER BY "{sort_by}" {sort_dir} LIMIT ? OFFSET ?'
|
| 272 |
+
)
|
| 273 |
+
rows = db.execute(row_sql, params + [limit, offset]).fetchall()
|
| 274 |
+
db.close()
|
| 275 |
+
|
| 276 |
+
return JSONResponse({
|
| 277 |
+
"table": table,
|
| 278 |
+
"total_matches": total,
|
| 279 |
+
"limit": limit,
|
| 280 |
+
"offset": offset,
|
| 281 |
+
"sort_by": sort_by,
|
| 282 |
+
"sort_dir": sort_dir.lower(),
|
| 283 |
+
"columns": valid_cols,
|
| 284 |
+
"rows": [dict(r) for r in rows],
|
| 285 |
+
})
|
| 286 |
|
| 287 |
|
| 288 |
+
@app.get("/api/tables")
|
| 289 |
+
async def list_tables():
|
| 290 |
+
"""Lightweight endpoint: just table names + row counts, for quick nav."""
|
| 291 |
+
return JSONResponse({
|
| 292 |
+
name: {"row_count": data["row_count"], "column_count": len(data["columns"])}
|
| 293 |
+
for name, data in SCHEMA_CACHE.items()
|
| 294 |
+
})
|