Spaces:
Sleeping

PERDYPTO commited on
Commit
8d0c3ee
·
verified ·
1 Parent(s): 25395b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -144
app.py CHANGED
@@ -1,146 +1,121 @@
1
- # app.py
2
- import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import sqlite3
4
- import threading
5
- from fastapi import FastAPI, Query
6
- from fastapi.responses import FileResponse, JSONResponse
7
- from huggingface_hub import login, list_bucket_tree, download_bucket_files
8
-
9
- DB_PATH = "github_pipeline.db"
10
- BUCKET = "PERDYPTO/db_snapshot"
11
-
12
- app = FastAPI()
13
- db_lock = threading.Lock()
14
-
15
- @app.on_event("startup")
16
- async def startup_event():
17
- if not os.path.exists(DB_PATH):
18
- print("Downloading full 3GB database from HF Bucket... (This will take a minute)")
19
- token = os.environ.get("HF_TOKEN")
20
- if token:
21
- login(token=token, add_to_git_credential=False)
22
-
23
- # Download the massive DB
24
- download_bucket_files(BUCKET, files=[("github_pipeline.db", DB_PATH)])
25
- print("✅ Database downloaded successfully!")
26
-
27
- # Create indexes to ensure web queries are instant
28
- print("Creating database indexes for fast querying...")
29
- conn = sqlite3.connect(DB_PATH)
30
- conn.execute("CREATE INDEX IF NOT EXISTS idx_meta_stars ON metadata(stars);")
31
- conn.execute("CREATE INDEX IF NOT EXISTS idx_meta_forks ON metadata(forks_count);")
32
- conn.execute("CREATE INDEX IF NOT EXISTS idx_meta_lang ON metadata(primary_language);")
33
- conn.execute("CREATE INDEX IF NOT EXISTS idx_meta_fork ON metadata(is_fork);")
34
- conn.execute("CREATE INDEX IF NOT EXISTS idx_meta_archived ON metadata(archived);")
35
- conn.commit()
36
- conn.close()
37
- print("✅ Indexes ready!")
38
- else:
39
- print("Database already exists.")
40
-
41
- def get_db():
42
- conn = sqlite3.connect(DB_PATH, check_same_thread=False, timeout=30)
43
  conn.row_factory = sqlite3.Row
44
- return conn
45
-
46
- @app.get("/")
47
- async def index():
48
- return FileResponse("static/index.html")
49
-
50
- @app.get("/api/stats")
51
- async def get_stats():
52
- db = get_db()
53
- # Overall metrics
54
- total = db.execute("SELECT COUNT(*) as c FROM metadata").fetchone()["c"]
55
- forks = db.execute("SELECT COUNT(*) as c FROM metadata WHERE is_fork = 1").fetchone()["c"]
56
- archived = db.execute("SELECT COUNT(*) as c FROM metadata WHERE archived = 1").fetchone()["c"]
57
-
58
- # Top languages
59
- langs = db.execute("""
60
- SELECT primary_language, COUNT(*) as count
61
- FROM metadata
62
- WHERE primary_language IS NOT NULL
63
- GROUP BY primary_language
64
- ORDER BY count DESC
65
- LIMIT 10
66
- """).fetchall()
67
-
68
- db.close()
69
-
70
- return JSONResponse({
71
- "total_repos": total,
72
- "total_forks": forks,
73
- "total_original": total - forks,
74
- "total_archived": archived,
75
- "top_languages": [dict(l) for l in langs]
76
- })
77
-
78
- @app.get("/api/repos")
79
- async def get_repos(
80
- min_stars: int = Query(0, ge=0),
81
- max_stars: int = Query(100000000, ge=0),
82
- is_fork: str = Query("all"), # "all", "0", "1"
83
- is_archived: str = Query("all"), # "all", "0", "1"
84
- language: str = Query("all"),
85
- search: str = Query(""),
86
- sort_by: str = Query("stars"), # "stars", "forks_count", "pushed_at"
87
- sort_dir: str = Query("desc"), # "asc", "desc"
88
- limit: int = Query(50, ge=1, le=500),
89
- offset: int = Query(0, ge=0)
90
- ):
91
- db = get_db()
92
-
93
- # Use resolved_parent_path and alias it as full_name for the frontend
94
- query = "SELECT repo_id, resolved_parent_path AS full_name, description, stars, forks_count, is_fork, archived, primary_language, pushed_at FROM metadata WHERE 1=1"
95
- count_query = "SELECT COUNT(*) FROM metadata WHERE 1=1"
96
- params = []
97
-
98
- if min_stars > 0:
99
- query += " AND stars >= ?"
100
- count_query += " AND stars >= ?"
101
- params.append(min_stars)
102
- if max_stars < 100000000:
103
- query += " AND stars <= ?"
104
- count_query += " AND stars <= ?"
105
- params.append(max_stars)
106
- if is_fork != "all":
107
- query += " AND is_fork = ?"
108
- count_query += " AND is_fork = ?"
109
- params.append(int(is_fork))
110
- if is_archived != "all":
111
- query += " AND archived = ?"
112
- count_query += " AND archived = ?"
113
- params.append(int(is_archived))
114
- if language != "all":
115
- query += " AND primary_language = ?"
116
- count_query += " AND primary_language = ?"
117
- params.append(language)
118
- if search:
119
- query += " AND (resolved_parent_path LIKE ? OR description LIKE ?)"
120
- count_query += " AND (resolved_parent_path LIKE ? OR description LIKE ?)"
121
- params.extend([f"%{search}%", f"%{search}%"])
122
-
123
- # Get total count for pagination UI
124
- total = db.execute(count_query, params).fetchone()[0]
125
-
126
- # Validate sort to prevent SQL injection
127
- allowed_sorts = ["stars", "forks_count", "pushed_at", "resolved_parent_path"]
128
- if sort_by not in allowed_sorts:
129
- sort_by = "stars"
130
- sort_dir = "ASC" if sort_dir.lower() == "asc" else "DESC"
131
-
132
- # Replace full_name with resolved_parent_path for sorting
133
- if sort_by == "resolved_parent_path":
134
- query += f" ORDER BY resolved_parent_path {sort_dir} LIMIT ? OFFSET ?"
135
- else:
136
- query += f" ORDER BY {sort_by} {sort_dir} LIMIT ? OFFSET ?"
137
-
138
- repos = db.execute(query, params + [limit, offset]).fetchall()
139
- db.close()
140
-
141
- return JSONResponse({
142
- "total_matches": total,
143
- "limit": limit,
144
- "offset": offset,
145
- "repos": [dict(r) for r in repos]
146
- })
 
1
+ """
2
+ inspect_db.py
3
+
4
+ Run this ONCE on your machine, in the same folder as github_pipeline.db
5
+ (or pass the path as an argument). It prints a full report of every table,
6
+ every column (name + type), row counts, and a sample row so you know
7
+ exactly what data you have.
8
+
9
+ Usage:
10
+ python inspect_db.py
11
+ python inspect_db.py /path/to/github_pipeline.db
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 sys
19
+ import json
20
+
21
+ DB_PATH = sys.argv[1] if len(sys.argv) > 1 else "github_pipeline.db"
22
+
23
+
24
+ def main():
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
+ if not tables:
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
+ # Row count
51
+ try:
52
+ row_count = cur.execute(f'SELECT COUNT(*) FROM "{table_name}"').fetchone()[0]
53
+ except Exception as e:
54
+ row_count = f"ERROR: {e}"
55
+ print(f"Row count: {row_count}")
56
+
57
+ # Columns (name, type, notnull, default, pk)
58
+ cols = cur.execute(f'PRAGMA table_info("{table_name}")').fetchall()
59
+ print(f"Columns ({len(cols)}):")
60
+ for c in cols:
61
+ flags = []
62
+ if c["pk"]:
63
+ flags.append("PRIMARY KEY")
64
+ if c["notnull"]:
65
+ flags.append("NOT NULL")
66
+ flag_str = f" [{', '.join(flags)}]" if flags else ""
67
+ print(f" - {c['name']:<28} {c['type'] or '(no type)':<15}{flag_str}")
68
+
69
+ # Indexes
70
+ idxs = cur.execute(f'PRAGMA index_list("{table_name}")').fetchall()
71
+ if idxs:
72
+ print(f"Indexes:")
73
+ for ix in idxs:
74
+ idx_cols = cur.execute(f'PRAGMA index_info("{ix["name"]}")').fetchall()
75
+ col_names = ", ".join(c["name"] for c in idx_cols)
76
+ print(f" - {ix['name']} ON ({col_names})")
77
+
78
+ # Sample row (first non-null-heavy row)
79
+ try:
80
+ sample = cur.execute(f'SELECT * FROM "{table_name}" LIMIT 1').fetchone()
81
+ if sample:
82
+ print("Sample row:")
83
+ sample_dict = dict(sample)
84
+ # Truncate long values for readability
85
+ for k, v in sample_dict.items():
86
+ if isinstance(v, str) and len(v) > 120:
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("=" * 70)
116
+ print("END OF REPORT — copy everything above this line back to Claude")
117
+ print("=" * 70)
118
+
119
+
120
+ if __name__ == "__main__":
121
+ main()