Spaces:
Sleeping

PERDYPTO commited on
Commit
0f70988
·
verified ·
1 Parent(s): c9d654b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +134 -40
app.py CHANGED
@@ -1,46 +1,140 @@
 
1
  import os
2
- import tempfile
3
- import time
4
- from huggingface_hub import login, create_bucket, download_bucket_files, batch_bucket_files
 
 
5
 
6
- def do_copy():
7
- print("--- Starting HF Internal Bucket Copy ---")
8
-
9
- # 1. Authenticate
10
- token = os.environ.get("HF_TOKEN")
11
- if not token:
12
- print("❌ ERROR: HF_TOKEN secret not found in Space settings!")
13
- return False
 
 
 
 
 
14
 
15
- login(token=token, add_to_git_credential=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- SOURCE_BUCKET = "PERDYPTO/db_snapshot"
18
- DEST_BUCKET = "PERDYPTO/sdafasdf-storage"
19
- FILENAME = "github_pipeline.db"
 
 
 
 
 
 
20
 
21
- print(f"Ensuring destination bucket {DEST_BUCKET} exists...")
22
- create_bucket(DEST_BUCKET, exist_ok=True)
23
 
24
- # 2. Temporary directory inside the Space's container
25
- with tempfile.TemporaryDirectory() as tmp_dir:
26
- local_file_path = os.path.join(tmp_dir, FILENAME)
27
-
28
- print(f"Downloading {FILENAME} from {SOURCE_BUCKET} into Space memory...")
29
- download_bucket_files(SOURCE_BUCKET, files=[(FILENAME, local_file_path)])
30
-
31
- print(f"Uploading {FILENAME} to {DEST_BUCKET}...")
32
- # Because of Xet deduplication, this upload will be near-instant
33
- batch_bucket_files(DEST_BUCKET, add=[(local_file_path, FILENAME)])
34
-
35
- print("✅ Copy complete successfully!")
36
- return True
37
-
38
- if __name__ == "__main__":
39
- try:
40
- do_copy()
41
- except Exception as e:
42
- print(f"❌ Copy failed: {e}")
43
-
44
- # Keep the Space running so it doesn't restart and loop the copy
45
- print("Holding Space alive for 1 hour so you can read the logs...")
46
- time.sleep(3600)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ query = "SELECT repo_id, full_name, description, stars, forks_count, is_fork, archived, primary_language, pushed_at FROM metadata WHERE 1=1"
93
+ count_query = "SELECT COUNT(*) FROM metadata WHERE 1=1"
94
+ params = []
95
+
96
+ if min_stars > 0:
97
+ query += " AND stars >= ?"
98
+ count_query += " AND stars >= ?"
99
+ params.append(min_stars)
100
+ if max_stars < 100000000:
101
+ query += " AND stars <= ?"
102
+ count_query += " AND stars <= ?"
103
+ params.append(max_stars)
104
+ if is_fork != "all":
105
+ query += " AND is_fork = ?"
106
+ count_query += " AND is_fork = ?"
107
+ params.append(int(is_fork))
108
+ if is_archived != "all":
109
+ query += " AND archived = ?"
110
+ count_query += " AND archived = ?"
111
+ params.append(int(is_archived))
112
+ if language != "all":
113
+ query += " AND primary_language = ?"
114
+ count_query += " AND primary_language = ?"
115
+ params.append(language)
116
+ if search:
117
+ query += " AND (full_name LIKE ? OR description LIKE ?)"
118
+ count_query += " AND (full_name LIKE ? OR description LIKE ?)"
119
+ params.extend([f"%{search}%", f"%{search}%"])
120
+
121
+ # Get total count for pagination UI
122
+ total = db.execute(count_query, params).fetchone()[0]
123
+
124
+ # Validate sort to prevent SQL injection
125
+ allowed_sorts = ["stars", "forks_count", "pushed_at", "full_name"]
126
+ if sort_by not in allowed_sorts:
127
+ sort_by = "stars"
128
+ sort_dir = "ASC" if sort_dir.lower() == "asc" else "DESC"
129
+
130
+ query += f" ORDER BY {sort_by} {sort_dir} LIMIT ? OFFSET ?"
131
+
132
+ repos = db.execute(query, params + [limit, offset]).fetchall()
133
+ db.close()
134
+
135
+ return JSONResponse({
136
+ "total_matches": total,
137
+ "limit": limit,
138
+ "offset": offset,
139
+ "repos": [dict(r) for r in repos]
140
+ })