PERDYPTO commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,11 @@
|
|
| 1 |
import os
|
| 2 |
import sqlite3
|
| 3 |
import tempfile
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
from fastapi import FastAPI
|
| 8 |
from huggingface_hub import download_bucket_files, batch_bucket_files
|
| 9 |
|
| 10 |
TOKEN = os.environ["HF_TOKEN"]
|
|
@@ -12,12 +13,66 @@ TOKEN = os.environ["HF_TOKEN"]
|
|
| 12 |
SOURCE_BUCKET = "PERDYPTO/db_snapshot"
|
| 13 |
DB_PATH_IN_BUCKET = "github_pipeline.db"
|
| 14 |
|
| 15 |
-
app = FastAPI()
|
|
|
|
| 16 |
_status = {"state": "starting"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
workdir = tempfile.mkdtemp()
|
| 22 |
local_db_path = os.path.join(workdir, os.path.basename(DB_PATH_IN_BUCKET))
|
| 23 |
|
|
@@ -29,42 +84,31 @@ def main():
|
|
| 29 |
)
|
| 30 |
print(f"[download] saved to {local_db_path}")
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
cols = cur.fetchall() # (cid, name, type, notnull, dflt_value, pk)
|
| 46 |
-
col_names = [c[1] for c in cols]
|
| 47 |
-
|
| 48 |
-
print(f"\nTable: {table}")
|
| 49 |
-
print(f" Column count: {len(col_names)}")
|
| 50 |
-
print(f" Columns: {', '.join(col_names)}")
|
| 51 |
-
|
| 52 |
-
for col_name in col_names:
|
| 53 |
-
index_name = f"idx_{table}_{col_name}"
|
| 54 |
-
try:
|
| 55 |
-
cur.execute(
|
| 56 |
-
f'CREATE INDEX IF NOT EXISTS "{index_name}" ON "{table}" ("{col_name}")'
|
| 57 |
-
)
|
| 58 |
-
print(f" [index] ensured {index_name}")
|
| 59 |
-
except sqlite3.OperationalError as e:
|
| 60 |
-
print(f" [index] skipped {index_name}: {e}")
|
| 61 |
-
|
| 62 |
-
conn.commit()
|
| 63 |
-
conn.close()
|
| 64 |
-
print("=" * 60)
|
| 65 |
-
|
| 66 |
-
# 3. Upload the indexed db back to the bucket (overwrite in place)
|
| 67 |
-
print(f"[upload] pushing indexed db back to hf://buckets/{SOURCE_BUCKET}/{DB_PATH_IN_BUCKET}")
|
| 68 |
batch_bucket_files(
|
| 69 |
SOURCE_BUCKET,
|
| 70 |
add=[(local_db_path, DB_PATH_IN_BUCKET)],
|
|
@@ -72,12 +116,18 @@ def main():
|
|
| 72 |
)
|
| 73 |
print("[upload] done")
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
@app.on_event("startup")
|
| 77 |
def on_startup():
|
| 78 |
try:
|
| 79 |
-
|
| 80 |
-
_status["state"] = "
|
| 81 |
except Exception as e:
|
| 82 |
_status["state"] = f"error: {e}"
|
| 83 |
print(f"[fatal] {e}")
|
|
@@ -85,8 +135,435 @@ def on_startup():
|
|
| 85 |
|
| 86 |
@app.get("/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
|
| 91 |
if __name__ == "__main__":
|
| 92 |
-
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import sqlite3
|
| 3 |
import tempfile
|
| 4 |
+
import threading
|
| 5 |
+
from typing import Optional
|
| 6 |
|
| 7 |
+
from fastapi import FastAPI, Query, HTTPException
|
| 8 |
+
from fastapi.responses import HTMLResponse, JSONResponse
|
|
|
|
| 9 |
from huggingface_hub import download_bucket_files, batch_bucket_files
|
| 10 |
|
| 11 |
TOKEN = os.environ["HF_TOKEN"]
|
|
|
|
| 13 |
SOURCE_BUCKET = "PERDYPTO/db_snapshot"
|
| 14 |
DB_PATH_IN_BUCKET = "github_pipeline.db"
|
| 15 |
|
| 16 |
+
app = FastAPI(title="GitHub Pipeline DB API")
|
| 17 |
+
|
| 18 |
_status = {"state": "starting"}
|
| 19 |
+
_lock = threading.Lock()
|
| 20 |
+
|
| 21 |
+
# In-memory sqlite connection, shared across requests (check_same_thread=False
|
| 22 |
+
# because FastAPI may serve requests from different threads).
|
| 23 |
+
_conn: Optional[sqlite3.Connection] = None
|
| 24 |
+
|
| 25 |
+
# Columns that are safe to sort/filter by. Built dynamically from the actual
|
| 26 |
+
# schema at load time so this stays correct even if the DB shape changes.
|
| 27 |
+
_metadata_columns: list[str] = []
|
| 28 |
+
_repo_ids_columns: list[str] = []
|
| 29 |
+
|
| 30 |
+
# The "joined" view we expose to the API: repo_ids + metadata on repo_id.
|
| 31 |
+
JOIN_SQL = """
|
| 32 |
+
FROM repo_ids r
|
| 33 |
+
LEFT JOIN metadata m ON m.repo_id = r.repo_id
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
# Whitelisted sortable/filterable fields -> actual SQL column expression.
|
| 37 |
+
# Populated after load_db_into_ram() inspects the schema.
|
| 38 |
+
FIELD_MAP: dict[str, str] = {}
|
| 39 |
|
| 40 |
+
# Fields that are boolean-ish (0/1) and get exposed as true/false filters.
|
| 41 |
+
BOOL_FIELDS = {"archived", "disabled", "is_fork", "is_template"}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _load_db_bytes_to_memory(local_db_path: str) -> sqlite3.Connection:
|
| 45 |
+
"""Load a sqlite file fully into an in-memory sqlite database."""
|
| 46 |
+
disk_conn = sqlite3.connect(local_db_path)
|
| 47 |
+
mem_conn = sqlite3.connect(":memory:", check_same_thread=False)
|
| 48 |
+
disk_conn.backup(mem_conn)
|
| 49 |
+
disk_conn.close()
|
| 50 |
+
return mem_conn
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def build_field_map(conn: sqlite3.Connection):
|
| 54 |
+
global _metadata_columns, _repo_ids_columns, FIELD_MAP
|
| 55 |
+
cur = conn.cursor()
|
| 56 |
|
| 57 |
+
cur.execute('PRAGMA table_info("repo_ids")')
|
| 58 |
+
_repo_ids_columns = [c[1] for c in cur.fetchall()]
|
| 59 |
+
|
| 60 |
+
cur.execute('PRAGMA table_info("metadata")')
|
| 61 |
+
_metadata_columns = [c[1] for c in cur.fetchall()]
|
| 62 |
+
|
| 63 |
+
fmap = {}
|
| 64 |
+
for c in _repo_ids_columns:
|
| 65 |
+
fmap[c] = f"r.{c}"
|
| 66 |
+
for c in _metadata_columns:
|
| 67 |
+
if c == "repo_id":
|
| 68 |
+
continue # avoid clobbering r.repo_id
|
| 69 |
+
fmap[c] = f"m.{c}"
|
| 70 |
+
FIELD_MAP = fmap
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def refresh_db():
|
| 74 |
+
"""Download the db from the HF bucket and load it fully into RAM."""
|
| 75 |
+
global _conn
|
| 76 |
workdir = tempfile.mkdtemp()
|
| 77 |
local_db_path = os.path.join(workdir, os.path.basename(DB_PATH_IN_BUCKET))
|
| 78 |
|
|
|
|
| 84 |
)
|
| 85 |
print(f"[download] saved to {local_db_path}")
|
| 86 |
|
| 87 |
+
print("[load] loading db fully into RAM (:memory:)")
|
| 88 |
+
new_conn = _load_db_bytes_to_memory(local_db_path)
|
| 89 |
+
build_field_map(new_conn)
|
| 90 |
+
|
| 91 |
+
with _lock:
|
| 92 |
+
_conn = new_conn
|
| 93 |
+
|
| 94 |
+
print("[load] db is now in memory and ready to serve")
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
os.remove(local_db_path)
|
| 98 |
+
os.rmdir(workdir)
|
| 99 |
+
except OSError:
|
| 100 |
+
pass
|
| 101 |
+
|
| 102 |
|
| 103 |
+
def push_db_back(conn: sqlite3.Connection):
|
| 104 |
+
"""Optional: persist the in-memory db back to disk then upload to bucket."""
|
| 105 |
+
workdir = tempfile.mkdtemp()
|
| 106 |
+
local_db_path = os.path.join(workdir, os.path.basename(DB_PATH_IN_BUCKET))
|
| 107 |
+
disk_conn = sqlite3.connect(local_db_path)
|
| 108 |
+
conn.backup(disk_conn)
|
| 109 |
+
disk_conn.close()
|
| 110 |
+
|
| 111 |
+
print(f"[upload] pushing db back to hf://buckets/{SOURCE_BUCKET}/{DB_PATH_IN_BUCKET}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
batch_bucket_files(
|
| 113 |
SOURCE_BUCKET,
|
| 114 |
add=[(local_db_path, DB_PATH_IN_BUCKET)],
|
|
|
|
| 116 |
)
|
| 117 |
print("[upload] done")
|
| 118 |
|
| 119 |
+
try:
|
| 120 |
+
os.remove(local_db_path)
|
| 121 |
+
os.rmdir(workdir)
|
| 122 |
+
except OSError:
|
| 123 |
+
pass
|
| 124 |
+
|
| 125 |
|
| 126 |
@app.on_event("startup")
|
| 127 |
def on_startup():
|
| 128 |
try:
|
| 129 |
+
refresh_db()
|
| 130 |
+
_status["state"] = "ready"
|
| 131 |
except Exception as e:
|
| 132 |
_status["state"] = f"error: {e}"
|
| 133 |
print(f"[fatal] {e}")
|
|
|
|
| 135 |
|
| 136 |
@app.get("/")
|
| 137 |
def health():
|
| 138 |
+
return {
|
| 139 |
+
"status": _status,
|
| 140 |
+
"endpoints": {
|
| 141 |
+
"/api/query": "Configurable query endpoint. See /api/schema for available fields.",
|
| 142 |
+
"/api/schema": "Lists all filterable/sortable fields and table columns.",
|
| 143 |
+
"/api/refresh": "POST — re-download the db from the bucket into RAM.",
|
| 144 |
+
"/dashboard": "HTML dashboard UI for browsing the data.",
|
| 145 |
+
},
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
@app.get("/api/schema")
|
| 150 |
+
def schema():
|
| 151 |
+
if _conn is None:
|
| 152 |
+
raise HTTPException(503, "db not loaded yet")
|
| 153 |
+
return {
|
| 154 |
+
"repo_ids_columns": _repo_ids_columns,
|
| 155 |
+
"metadata_columns": _metadata_columns,
|
| 156 |
+
"queryable_fields": sorted(FIELD_MAP.keys()),
|
| 157 |
+
"boolean_fields": sorted(BOOL_FIELDS & set(FIELD_MAP.keys())),
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _get_conn() -> sqlite3.Connection:
|
| 162 |
+
if _conn is None:
|
| 163 |
+
raise HTTPException(503, "db not loaded yet")
|
| 164 |
+
return _conn
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@app.get("/api/query")
|
| 168 |
+
def query(
|
| 169 |
+
sort_by: str = Query("stars", description="Field to sort by, e.g. stars, forks_count, watchers_count, repo_id"),
|
| 170 |
+
order: str = Query("desc", pattern="^(?i)(asc|desc)$", description="asc or desc"),
|
| 171 |
+
limit: int = Query(10, ge=1, le=1000, description="Number of rows to return"),
|
| 172 |
+
offset: int = Query(0, ge=0),
|
| 173 |
+
language: Optional[str] = Query(None, description="Filter by primary_language, e.g. Python"),
|
| 174 |
+
is_fork: Optional[bool] = Query(None, description="Filter forks: true/false"),
|
| 175 |
+
archived: Optional[bool] = Query(None, description="Filter archived repos: true/false"),
|
| 176 |
+
disabled: Optional[bool] = Query(None, description="Filter disabled repos: true/false"),
|
| 177 |
+
is_template: Optional[bool] = Query(None, description="Filter template repos: true/false"),
|
| 178 |
+
status: Optional[str] = Query(None, description="Filter by repo_ids.status"),
|
| 179 |
+
min_stars: Optional[int] = Query(None, description="Minimum stars"),
|
| 180 |
+
max_stars: Optional[int] = Query(None, description="Maximum stars"),
|
| 181 |
+
search: Optional[str] = Query(None, description="Substring search in repo_path/description"),
|
| 182 |
+
):
|
| 183 |
+
"""
|
| 184 |
+
Fully configurable query endpoint over repo_ids + metadata (joined on repo_id).
|
| 185 |
+
|
| 186 |
+
Examples:
|
| 187 |
+
/api/query?sort_by=stars&order=desc&limit=10 -> top 10 most starred
|
| 188 |
+
/api/query?sort_by=stars&order=asc&limit=10 -> top 10 least starred
|
| 189 |
+
/api/query?sort_by=stars&order=desc&limit=10&language=Python -> top 10 starred Python repos
|
| 190 |
+
/api/query?is_fork=false&archived=false&sort_by=forks_count -> non-fork, non-archived, by forks
|
| 191 |
+
/api/query?sort_by=watchers_count&order=asc&limit=5 -> bottom 5 by watchers
|
| 192 |
+
"""
|
| 193 |
+
conn = _get_conn()
|
| 194 |
+
|
| 195 |
+
if sort_by not in FIELD_MAP:
|
| 196 |
+
raise HTTPException(400, f"invalid sort_by '{sort_by}'. See /api/schema for valid fields.")
|
| 197 |
+
|
| 198 |
+
order_sql = "ASC" if order.lower() == "asc" else "DESC"
|
| 199 |
+
sort_col = FIELD_MAP[sort_by]
|
| 200 |
+
|
| 201 |
+
where = []
|
| 202 |
+
params: list = []
|
| 203 |
+
|
| 204 |
+
if language:
|
| 205 |
+
where.append("m.primary_language = ?")
|
| 206 |
+
params.append(language)
|
| 207 |
+
if is_fork is not None:
|
| 208 |
+
where.append("m.is_fork = ?")
|
| 209 |
+
params.append(1 if is_fork else 0)
|
| 210 |
+
if archived is not None:
|
| 211 |
+
where.append("m.archived = ?")
|
| 212 |
+
params.append(1 if archived else 0)
|
| 213 |
+
if disabled is not None:
|
| 214 |
+
where.append("m.disabled = ?")
|
| 215 |
+
params.append(1 if disabled else 0)
|
| 216 |
+
if is_template is not None:
|
| 217 |
+
where.append("m.is_template = ?")
|
| 218 |
+
params.append(1 if is_template else 0)
|
| 219 |
+
if status:
|
| 220 |
+
where.append("r.status = ?")
|
| 221 |
+
params.append(status)
|
| 222 |
+
if min_stars is not None:
|
| 223 |
+
where.append("m.stars >= ?")
|
| 224 |
+
params.append(min_stars)
|
| 225 |
+
if max_stars is not None:
|
| 226 |
+
where.append("m.stars <= ?")
|
| 227 |
+
params.append(max_stars)
|
| 228 |
+
if search:
|
| 229 |
+
where.append("(r.repo_path LIKE ? OR m.description LIKE ?)")
|
| 230 |
+
like = f"%{search}%"
|
| 231 |
+
params.extend([like, like])
|
| 232 |
+
|
| 233 |
+
where_sql = f"WHERE {' AND '.join(where)}" if where else ""
|
| 234 |
+
|
| 235 |
+
select_cols = [f"r.{c}" for c in _repo_ids_columns] + [
|
| 236 |
+
f"m.{c}" for c in _metadata_columns if c != "repo_id"
|
| 237 |
+
]
|
| 238 |
+
select_sql = ", ".join(select_cols)
|
| 239 |
+
|
| 240 |
+
sql = f"""
|
| 241 |
+
SELECT {select_sql}
|
| 242 |
+
{JOIN_SQL}
|
| 243 |
+
{where_sql}
|
| 244 |
+
ORDER BY {sort_col} {order_sql} NULLS LAST
|
| 245 |
+
LIMIT ? OFFSET ?
|
| 246 |
+
"""
|
| 247 |
+
params.extend([limit, offset])
|
| 248 |
+
|
| 249 |
+
cur = conn.cursor()
|
| 250 |
+
try:
|
| 251 |
+
cur.execute(sql, params)
|
| 252 |
+
except sqlite3.OperationalError:
|
| 253 |
+
# Older sqlite may not support NULLS LAST; retry without it.
|
| 254 |
+
sql = sql.replace("NULLS LAST", "")
|
| 255 |
+
cur.execute(sql, params)
|
| 256 |
+
|
| 257 |
+
col_names = [d[0] for d in cur.description]
|
| 258 |
+
rows = [dict(zip(col_names, row)) for row in cur.fetchall()]
|
| 259 |
+
|
| 260 |
+
return {
|
| 261 |
+
"count": len(rows),
|
| 262 |
+
"sort_by": sort_by,
|
| 263 |
+
"order": order_sql,
|
| 264 |
+
"filters": {
|
| 265 |
+
"language": language,
|
| 266 |
+
"is_fork": is_fork,
|
| 267 |
+
"archived": archived,
|
| 268 |
+
"disabled": disabled,
|
| 269 |
+
"is_template": is_template,
|
| 270 |
+
"status": status,
|
| 271 |
+
"min_stars": min_stars,
|
| 272 |
+
"max_stars": max_stars,
|
| 273 |
+
"search": search,
|
| 274 |
+
},
|
| 275 |
+
"results": rows,
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
@app.get("/api/languages")
|
| 280 |
+
def languages():
|
| 281 |
+
"""List distinct primary_language values with counts, for building UI filters."""
|
| 282 |
+
conn = _get_conn()
|
| 283 |
+
cur = conn.cursor()
|
| 284 |
+
cur.execute(
|
| 285 |
+
"""
|
| 286 |
+
SELECT m.primary_language AS language, COUNT(*) AS count
|
| 287 |
+
FROM metadata m
|
| 288 |
+
WHERE m.primary_language IS NOT NULL AND m.primary_language != ''
|
| 289 |
+
GROUP BY m.primary_language
|
| 290 |
+
ORDER BY count DESC
|
| 291 |
+
"""
|
| 292 |
+
)
|
| 293 |
+
return {"languages": [{"language": r[0], "count": r[1]} for r in cur.fetchall()]}
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
@app.get("/api/stats")
|
| 297 |
+
def stats():
|
| 298 |
+
conn = _get_conn()
|
| 299 |
+
cur = conn.cursor()
|
| 300 |
+
cur.execute("SELECT COUNT(*) FROM repo_ids")
|
| 301 |
+
total_repos = cur.fetchone()[0]
|
| 302 |
+
cur.execute("SELECT COUNT(*) FROM metadata")
|
| 303 |
+
total_metadata = cur.fetchone()[0]
|
| 304 |
+
cur.execute("SELECT COUNT(*) FROM metadata WHERE is_fork = 1")
|
| 305 |
+
forks = cur.fetchone()[0]
|
| 306 |
+
cur.execute("SELECT COUNT(*) FROM metadata WHERE archived = 1")
|
| 307 |
+
archived = cur.fetchone()[0]
|
| 308 |
+
return {
|
| 309 |
+
"total_repos": total_repos,
|
| 310 |
+
"total_metadata_rows": total_metadata,
|
| 311 |
+
"forks": forks,
|
| 312 |
+
"archived": archived,
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
@app.post("/api/refresh")
|
| 317 |
+
def refresh():
|
| 318 |
+
"""Re-download the db from the bucket into RAM (does not touch the bucket)."""
|
| 319 |
+
try:
|
| 320 |
+
refresh_db()
|
| 321 |
+
_status["state"] = "ready"
|
| 322 |
+
return {"status": "ok", "state": _status["state"]}
|
| 323 |
+
except Exception as e:
|
| 324 |
+
_status["state"] = f"error: {e}"
|
| 325 |
+
raise HTTPException(500, str(e))
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
@app.post("/api/push")
|
| 329 |
+
def push():
|
| 330 |
+
"""Persist current in-memory db state back to the HF bucket."""
|
| 331 |
+
conn = _get_conn()
|
| 332 |
+
try:
|
| 333 |
+
push_db_back(conn)
|
| 334 |
+
return {"status": "ok"}
|
| 335 |
+
except Exception as e:
|
| 336 |
+
raise HTTPException(500, str(e))
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
DASHBOARD_HTML = """
|
| 340 |
+
<!DOCTYPE html>
|
| 341 |
+
<html lang="en">
|
| 342 |
+
<head>
|
| 343 |
+
<meta charset="UTF-8">
|
| 344 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 345 |
+
<title>GitHub Pipeline DB Explorer</title>
|
| 346 |
+
<style>
|
| 347 |
+
:root {
|
| 348 |
+
--bg: #0d1117;
|
| 349 |
+
--panel: #161b22;
|
| 350 |
+
--border: #30363d;
|
| 351 |
+
--text: #c9d1d9;
|
| 352 |
+
--muted: #8b949e;
|
| 353 |
+
--accent: #58a6ff;
|
| 354 |
+
}
|
| 355 |
+
* { box-sizing: border-box; }
|
| 356 |
+
body {
|
| 357 |
+
margin: 0;
|
| 358 |
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
|
| 359 |
+
background: var(--bg);
|
| 360 |
+
color: var(--text);
|
| 361 |
+
padding: 24px;
|
| 362 |
+
}
|
| 363 |
+
h1 { font-size: 20px; margin-bottom: 4px; }
|
| 364 |
+
p.sub { color: var(--muted); margin-top: 0; margin-bottom: 20px; font-size: 13px; }
|
| 365 |
+
.panel {
|
| 366 |
+
background: var(--panel);
|
| 367 |
+
border: 1px solid var(--border);
|
| 368 |
+
border-radius: 8px;
|
| 369 |
+
padding: 16px;
|
| 370 |
+
margin-bottom: 16px;
|
| 371 |
+
}
|
| 372 |
+
.controls {
|
| 373 |
+
display: flex;
|
| 374 |
+
flex-wrap: wrap;
|
| 375 |
+
gap: 12px;
|
| 376 |
+
align-items: flex-end;
|
| 377 |
+
}
|
| 378 |
+
.field { display: flex; flex-direction: column; gap: 4px; }
|
| 379 |
+
.field label { font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.03em; }
|
| 380 |
+
select, input {
|
| 381 |
+
background: #010409;
|
| 382 |
+
border: 1px solid var(--border);
|
| 383 |
+
color: var(--text);
|
| 384 |
+
padding: 6px 8px;
|
| 385 |
+
border-radius: 6px;
|
| 386 |
+
font-size: 13px;
|
| 387 |
+
}
|
| 388 |
+
button {
|
| 389 |
+
background: var(--accent);
|
| 390 |
+
color: #041424;
|
| 391 |
+
border: none;
|
| 392 |
+
padding: 8px 16px;
|
| 393 |
+
border-radius: 6px;
|
| 394 |
+
font-weight: 600;
|
| 395 |
+
cursor: pointer;
|
| 396 |
+
font-size: 13px;
|
| 397 |
+
}
|
| 398 |
+
button:hover { opacity: 0.9; }
|
| 399 |
+
table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
| 400 |
+
th, td {
|
| 401 |
+
text-align: left;
|
| 402 |
+
padding: 8px 10px;
|
| 403 |
+
border-bottom: 1px solid var(--border);
|
| 404 |
+
white-space: nowrap;
|
| 405 |
+
max-width: 320px;
|
| 406 |
+
overflow: hidden;
|
| 407 |
+
text-overflow: ellipsis;
|
| 408 |
+
}
|
| 409 |
+
th { color: var(--muted); font-weight: 600; position: sticky; top: 0; background: var(--panel); }
|
| 410 |
+
tr:hover { background: #1c2128; }
|
| 411 |
+
.stats { display: flex; gap: 24px; flex-wrap: wrap; }
|
| 412 |
+
.stat { }
|
| 413 |
+
.stat .num { font-size: 22px; font-weight: 700; color: var(--accent); }
|
| 414 |
+
.stat .label { font-size: 11px; color: var(--muted); text-transform: uppercase; }
|
| 415 |
+
.table-wrap { overflow: auto; max-height: 60vh; }
|
| 416 |
+
a { color: var(--accent); text-decoration: none; }
|
| 417 |
+
.badge { display:inline-block; padding: 2px 6px; border-radius: 4px; font-size: 11px; background:#21262d; color: var(--muted); }
|
| 418 |
+
</style>
|
| 419 |
+
</head>
|
| 420 |
+
<body>
|
| 421 |
+
|
| 422 |
+
<h1>GitHub Pipeline DB Explorer</h1>
|
| 423 |
+
<p class="sub">Live view over the indexed sqlite db loaded in RAM. Powered by <code>/api/query</code>.</p>
|
| 424 |
+
|
| 425 |
+
<div class="panel stats" id="stats">Loading stats...</div>
|
| 426 |
+
|
| 427 |
+
<div class="panel">
|
| 428 |
+
<div class="controls">
|
| 429 |
+
<div class="field">
|
| 430 |
+
<label>Sort by</label>
|
| 431 |
+
<select id="sortBy">
|
| 432 |
+
<option value="stars">Stars</option>
|
| 433 |
+
<option value="forks_count">Forks</option>
|
| 434 |
+
<option value="watchers_count">Watchers</option>
|
| 435 |
+
<option value="pushed_at">Last pushed</option>
|
| 436 |
+
<option value="num_files">Num files</option>
|
| 437 |
+
<option value="repo_id">Repo ID</option>
|
| 438 |
+
</select>
|
| 439 |
+
</div>
|
| 440 |
+
<div class="field">
|
| 441 |
+
<label>Order</label>
|
| 442 |
+
<select id="order">
|
| 443 |
+
<option value="desc">Highest first</option>
|
| 444 |
+
<option value="asc">Lowest first</option>
|
| 445 |
+
</select>
|
| 446 |
+
</div>
|
| 447 |
+
<div class="field">
|
| 448 |
+
<label>Limit</label>
|
| 449 |
+
<input id="limit" type="number" value="10" min="1" max="1000">
|
| 450 |
+
</div>
|
| 451 |
+
<div class="field">
|
| 452 |
+
<label>Language</label>
|
| 453 |
+
<select id="language"><option value="">Any</option></select>
|
| 454 |
+
</div>
|
| 455 |
+
<div class="field">
|
| 456 |
+
<label>Fork</label>
|
| 457 |
+
<select id="isFork">
|
| 458 |
+
<option value="">Any</option>
|
| 459 |
+
<option value="true">Forks only</option>
|
| 460 |
+
<option value="false">Non-forks only</option>
|
| 461 |
+
</select>
|
| 462 |
+
</div>
|
| 463 |
+
<div class="field">
|
| 464 |
+
<label>Archived</label>
|
| 465 |
+
<select id="archived">
|
| 466 |
+
<option value="">Any</option>
|
| 467 |
+
<option value="true">Archived only</option>
|
| 468 |
+
<option value="false">Non-archived only</option>
|
| 469 |
+
</select>
|
| 470 |
+
</div>
|
| 471 |
+
<div class="field">
|
| 472 |
+
<label>Search</label>
|
| 473 |
+
<input id="search" type="text" placeholder="repo path / description">
|
| 474 |
+
</div>
|
| 475 |
+
<button onclick="loadData()">Run query</button>
|
| 476 |
+
</div>
|
| 477 |
+
</div>
|
| 478 |
+
|
| 479 |
+
<div class="panel">
|
| 480 |
+
<div class="table-wrap">
|
| 481 |
+
<table id="resultsTable">
|
| 482 |
+
<thead><tr id="tableHead"></tr></thead>
|
| 483 |
+
<tbody id="tableBody"><tr><td>Loading...</td></tr></tbody>
|
| 484 |
+
</table>
|
| 485 |
+
</div>
|
| 486 |
+
</div>
|
| 487 |
+
|
| 488 |
+
<p class="sub">Direct API access: <a href="/api/query?sort_by=stars&order=desc&limit=10">/api/query</a> · <a href="/api/schema">/api/schema</a> · <a href="/api/languages">/api/languages</a></p>
|
| 489 |
+
|
| 490 |
+
<script>
|
| 491 |
+
async function loadStats() {
|
| 492 |
+
const res = await fetch('/api/stats');
|
| 493 |
+
const data = await res.json();
|
| 494 |
+
document.getElementById('stats').innerHTML = `
|
| 495 |
+
<div class="stat"><div class="num">${data.total_repos}</div><div class="label">Total repos</div></div>
|
| 496 |
+
<div class="stat"><div class="num">${data.total_metadata_rows}</div><div class="label">With metadata</div></div>
|
| 497 |
+
<div class="stat"><div class="num">${data.forks}</div><div class="label">Forks</div></div>
|
| 498 |
+
<div class="stat"><div class="num">${data.archived}</div><div class="label">Archived</div></div>
|
| 499 |
+
`;
|
| 500 |
+
}
|
| 501 |
+
|
| 502 |
+
async function loadLanguages() {
|
| 503 |
+
const res = await fetch('/api/languages');
|
| 504 |
+
const data = await res.json();
|
| 505 |
+
const sel = document.getElementById('language');
|
| 506 |
+
data.languages.forEach(l => {
|
| 507 |
+
const opt = document.createElement('option');
|
| 508 |
+
opt.value = l.language;
|
| 509 |
+
opt.textContent = `${l.language} (${l.count})`;
|
| 510 |
+
sel.appendChild(opt);
|
| 511 |
+
});
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
async function loadData() {
|
| 515 |
+
const params = new URLSearchParams();
|
| 516 |
+
params.set('sort_by', document.getElementById('sortBy').value);
|
| 517 |
+
params.set('order', document.getElementById('order').value);
|
| 518 |
+
params.set('limit', document.getElementById('limit').value || 10);
|
| 519 |
+
|
| 520 |
+
const lang = document.getElementById('language').value;
|
| 521 |
+
if (lang) params.set('language', lang);
|
| 522 |
+
|
| 523 |
+
const isFork = document.getElementById('isFork').value;
|
| 524 |
+
if (isFork) params.set('is_fork', isFork);
|
| 525 |
+
|
| 526 |
+
const archived = document.getElementById('archived').value;
|
| 527 |
+
if (archived) params.set('archived', archived);
|
| 528 |
+
|
| 529 |
+
const search = document.getElementById('search').value;
|
| 530 |
+
if (search) params.set('search', search);
|
| 531 |
+
|
| 532 |
+
const res = await fetch('/api/query?' + params.toString());
|
| 533 |
+
const data = await res.json();
|
| 534 |
+
renderTable(data.results);
|
| 535 |
+
}
|
| 536 |
+
|
| 537 |
+
function renderTable(rows) {
|
| 538 |
+
const head = document.getElementById('tableHead');
|
| 539 |
+
const body = document.getElementById('tableBody');
|
| 540 |
+
if (!rows.length) {
|
| 541 |
+
head.innerHTML = '';
|
| 542 |
+
body.innerHTML = '<tr><td>No results</td></tr>';
|
| 543 |
+
return;
|
| 544 |
+
}
|
| 545 |
+
const cols = Object.keys(rows[0]);
|
| 546 |
+
head.innerHTML = cols.map(c => `<th>${c}</th>`).join('');
|
| 547 |
+
body.innerHTML = rows.map(r =>
|
| 548 |
+
'<tr>' + cols.map(c => `<td title="${(r[c] ?? '')}">${(r[c] ?? '')}</td>`).join('') + '</tr>'
|
| 549 |
+
).join('');
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
loadStats();
|
| 553 |
+
loadLanguages();
|
| 554 |
+
loadData();
|
| 555 |
+
</script>
|
| 556 |
+
|
| 557 |
+
</body>
|
| 558 |
+
</html>
|
| 559 |
+
"""
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
@app.get("/dashboard", response_class=HTMLResponse)
|
| 563 |
+
def dashboard():
|
| 564 |
+
return HTMLResponse(content=DASHBOARD_HTML)
|
| 565 |
|
| 566 |
|
| 567 |
if __name__ == "__main__":
|
| 568 |
+
import uvicorn
|
| 569 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|