Nottybro commited on
Commit
7f19e5b
Β·
verified Β·
1 Parent(s): f74c009

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +363 -0
app.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os, json, time, random, threading, re, requests
3
+ from pathlib import Path
4
+ from datetime import datetime, timezone
5
+ from requests.auth import HTTPBasicAuth
6
+ import gradio as gr
7
+
8
+ KAGGLE_ACCOUNTS = [
9
+ {
10
+ "username": "nottybro",
11
+ "key": "5b1c2985d5d05f371d7a1d3ba409ed03"
12
+ },
13
+ {
14
+ "username": "imimpossible",
15
+ "key": "bd568e036e37d24f561659be3b4d5ff8"
16
+ },
17
+ {
18
+ "username": "krushnadere07",
19
+ "key": "72209a69ef19fa5e2c2372f0c3674832"
20
+ },
21
+ {
22
+ "username": "rajendradere",
23
+ "key": "4ca458e96a6eee4b07dff0059ca40026"
24
+ },
25
+ {
26
+ "username": "thataiguy1",
27
+ "key": "a12c3cfae7e3ba004969bd6b09a1eec2"
28
+ },
29
+ {
30
+ "username": "rajendradere12",
31
+ "key": "95d3ea851c26b4210d52098cc8e83aa5"
32
+ },
33
+ {
34
+ "username": "newsaipaper",
35
+ "key": "b7fdd1b83643eea700548a6b04ff1df0"
36
+ },
37
+ {
38
+ "username": "nofundaidev",
39
+ "key": "5eedd744cf221bf7d639410337e77b6f"
40
+ },
41
+ {
42
+ "username": "qnottytbro",
43
+ "key": "168dcd9a4f4b1da5d37b457076c66383"
44
+ },
45
+ {
46
+ "username": "prathemeshdere",
47
+ "key": "6f5e5ebb76d071aaae137a1f93b5a30a"
48
+ },
49
+ {
50
+ "username": "rajendradere56",
51
+ "key": "fd253729e913b83689b9586ad1717dc3"
52
+ },
53
+ {
54
+ "username": "gpbermuda1807j",
55
+ "key": "2d6c86c00c0f39071b1665e61b2cd237"
56
+ },
57
+ {
58
+ "username": "wigipsda",
59
+ "key": "6c6dff12481ab96a044a34983f09b2fb"
60
+ },
61
+ {
62
+ "username": "krushnadere",
63
+ "key": "0fc03734136f6c047cfbfd7334221f88"
64
+ },
65
+ {
66
+ "username": "prathameshdere",
67
+ "key": "10bc47218a53ee33771d732d2be8f08c"
68
+ }
69
+ ]
70
+ TOTAL_SESSIONS = 15
71
+ TOTAL_PMC_PAGES = 6435
72
+ PAGES_PER_SESSION = TOTAL_PMC_PAGES // TOTAL_SESSIONS
73
+ KAGGLE_API = 'https://www.kaggle.com/api/v1'
74
+ SCRAPER_TEMPLATE = Path('scraper_template.py')
75
+ PUSH_GAP_MIN = 20
76
+ PUSH_GAP_MAX = 30
77
+ MONITOR_SECS = 5 * 60
78
+
79
+ sessions = {}
80
+ state_lock = threading.Lock()
81
+ push_lock = threading.Lock()
82
+ last_push_t = 0.0
83
+ log_lines = []
84
+
85
+ def log(msg):
86
+ ts = datetime.now(timezone.utc).strftime('%H:%M:%S')
87
+ ln = f'[{ts}] {msg}'
88
+ print(ln)
89
+ with state_lock:
90
+ log_lines.append(ln)
91
+ if len(log_lines) > 400: log_lines.pop(0)
92
+
93
+ def _now(): return datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
94
+ def _slug(sid, run): return f'pmc-s{sid}-r{run}'
95
+ def _kurl(user, slug): return f'https://www.kaggle.com/code/{user}/{slug}'
96
+ def _auth(acc): return HTTPBasicAuth(acc['username'], acc['key'])
97
+
98
+ for i, acc in enumerate(KAGGLE_ACCOUNTS):
99
+ sid = i
100
+ ss = 1 + sid * PAGES_PER_SESSION
101
+ se = ss + PAGES_PER_SESSION - 1
102
+ if sid == TOTAL_SESSIONS - 1: se = TOTAL_PMC_PAGES
103
+ sessions[sid] = {
104
+ 'session_id': sid, 'username': acc['username'], 'key': acc['key'],
105
+ 'slice_start': ss, 'slice_end': se,
106
+ 'current_slug': None, 'current_url': None, 'run_number': 0,
107
+ 'status': 'idle', 'last_check': None, 'last_push': None,
108
+ 'resume_page': 0, 'success': 0, 'skip': 0, 'fail': 0,
109
+ 'complete': False, 'error_msg': '', 'history': [],
110
+ }
111
+
112
+ def kstatus(acc, slug):
113
+ try:
114
+ r = requests.get(f'{KAGGLE_API}/kernels/{acc["username"]}/{slug}',
115
+ auth=_auth(acc), timeout=20)
116
+ if r.status_code == 404: return 'not_found'
117
+ r.raise_for_status()
118
+ return r.json().get('currentRunningVersion', {}).get('status', 'unknown')
119
+ except Exception as e: return f'api_error:{str(e)[:50]}'
120
+
121
+ def klog(acc, slug):
122
+ try:
123
+ r = requests.get(f'{KAGGLE_API}/kernels/{acc["username"]}/{slug}/output',
124
+ auth=_auth(acc), timeout=30, params={'startLine':0,'pageSize':500})
125
+ r.raise_for_status()
126
+ return r.json().get('log', '')
127
+ except Exception as e: log(f'Log err {slug}: {e}'); return ''
128
+
129
+ def extract_state(raw):
130
+ m = re.findall(r'##RUN_STATE##(.+?)##RUN_STATE##', raw, re.DOTALL)
131
+ if not m: return None
132
+ try: return json.loads(m[-1].strip())
133
+ except: return None
134
+
135
+ def push(acc, sid, run_num, resume_page):
136
+ global last_push_t
137
+ if not SCRAPER_TEMPLATE.exists():
138
+ return False, '', 'scraper_template.py missing'
139
+ with push_lock:
140
+ gap = random.uniform(PUSH_GAP_MIN, PUSH_GAP_MAX)
141
+ elapsed = time.time() - last_push_t
142
+ if elapsed < gap:
143
+ w = gap - elapsed
144
+ log(f'Push gap: waiting {w:.1f}s')
145
+ time.sleep(w)
146
+ slug = _slug(sid, run_num)
147
+ run_id = f's{sid}-r{run_num}'
148
+ url = _kurl(acc['username'], slug)
149
+ tmpl = SCRAPER_TEMPLATE.read_text(encoding='utf-8')
150
+ script = (tmpl
151
+ .replace('__SESSION_ID__', str(sid))
152
+ .replace('__RESUME_FROM_PAGE__', str(resume_page))
153
+ .replace("'__RUN_ID__'", f"'{run_id}'")
154
+ .replace('__TOTAL_SESSIONS__', str(TOTAL_SESSIONS)))
155
+ script = (f'# PMC v13.0 | {run_id} | resume={resume_page} | '
156
+ f'seed={random.randint(10000,99999)}\n' + script)
157
+ try:
158
+ payload = {
159
+ 'id': f'{acc["username"]}/{slug}',
160
+ 'title': f'PMC {run_id}',
161
+ 'language': 'python', 'kernelType': 'script',
162
+ 'isPrivate': False, 'enableGpu': False, 'enableInternet': True,
163
+ 'datasetDataSources': [], 'kernelDataSources': [],
164
+ 'categoryIds': [], 'text': script,
165
+ }
166
+ r = requests.post(f'{KAGGLE_API}/kernels/push',
167
+ auth=_auth(acc), json=payload, timeout=60)
168
+ r.raise_for_status()
169
+ last_push_t = time.time()
170
+ log(f'Pushed {slug} β†’ {url}')
171
+ return True, slug, url
172
+ except Exception as e:
173
+ err = str(e)[:200]; log(f'Push fail {slug}: {err}')
174
+ return False, '', err
175
+
176
+ RESTART_ON = {'complete','error','cancelAcknowledged','failed'}
177
+ RUNNING_ON = {'running','queued','inQueue'}
178
+
179
+ def handle(sid):
180
+ with state_lock:
181
+ if sessions[sid]['complete']: return
182
+ s = sessions[sid]
183
+ acc = {'username': s['username'], 'key': s['key']}
184
+ slug = s['current_slug']
185
+
186
+ if slug is None:
187
+ with state_lock:
188
+ rn = sessions[sid]['run_number'] + 1
189
+ rp = sessions[sid]['resume_page']
190
+ sessions[sid].update({'run_number': rn, 'status': 'pushing'})
191
+ ok, ns, url = push(acc, sid, rn, rp)
192
+ with state_lock:
193
+ if ok:
194
+ sessions[sid].update({'current_slug': ns, 'current_url': url,
195
+ 'status': 'queued', 'last_push': _now(), 'error_msg': ''})
196
+ sessions[sid]['history'].append(
197
+ {'run_number': rn, 'slug': ns, 'url': url,
198
+ 'pushed_at': _now(), 'resume_page': rp})
199
+ else:
200
+ sessions[sid].update({'status': 'push_failed', 'error_msg': url})
201
+ return
202
+
203
+ ks = kstatus(acc, slug)
204
+ now = _now()
205
+ with state_lock:
206
+ sessions[sid]['last_check'] = now
207
+ sessions[sid]['status'] = ks
208
+ if ks in RUNNING_ON: return
209
+
210
+ raw = klog(acc, slug)
211
+ state = extract_state(raw)
212
+
213
+ with state_lock:
214
+ if state:
215
+ sessions[sid]['success'] += state.get('success', 0)
216
+ sessions[sid]['skip'] += state.get('skip', 0)
217
+ sessions[sid]['fail'] += state.get('fail', 0)
218
+ next_page = state.get('next_resume_page')
219
+ is_done = state.get('complete', False)
220
+ reason = state.get('stop_reason', 'unknown')
221
+ else:
222
+ cur = sessions[sid].get('resume_page') or sessions[sid]['slice_start']
223
+ next_page = cur + 100
224
+ is_done = next_page > sessions[sid]['slice_end']
225
+ reason = 'no_state_in_log'
226
+ log(f'WARNING: no state in log for {slug}, est next={next_page}')
227
+ for h in sessions[sid]['history']:
228
+ if h['slug'] == slug:
229
+ h.update({'stopped_at': now, 'stop_reason': reason})
230
+ if state: h['last_page'] = state.get('last_completed_page')
231
+ break
232
+ if is_done:
233
+ sessions[sid].update({'complete': True, 'status': 'done'})
234
+ log(f'Session {sid} COMPLETE!'); return
235
+ sessions[sid]['resume_page'] = next_page
236
+
237
+ with state_lock:
238
+ rn = sessions[sid]['run_number'] + 1
239
+ sessions[sid].update({'run_number': rn, 'status': 'pushing'})
240
+ log(f's{sid}: {reason} β†’ restart at page {next_page} (run #{rn})')
241
+ ok, ns, url = push(acc, sid, rn, next_page)
242
+ with state_lock:
243
+ if ok:
244
+ sessions[sid].update({'current_slug': ns, 'current_url': url,
245
+ 'status': 'queued', 'last_push': now, 'error_msg': ''})
246
+ sessions[sid]['history'].append(
247
+ {'run_number': rn, 'slug': ns, 'url': url,
248
+ 'pushed_at': now, 'resume_page': next_page})
249
+ else:
250
+ sessions[sid].update({'status': 'push_failed', 'error_msg': url})
251
+
252
+ def monitor():
253
+ log(f'Monitor started β€” {len(KAGGLE_ACCOUNTS)} sessions')
254
+ threading.Thread(target=lambda:[handle(s) for s in sessions], daemon=True).start()
255
+ while True:
256
+ time.sleep(MONITOR_SECS)
257
+ for sid in list(sessions):
258
+ try: handle(sid)
259
+ except Exception as e: log(f'Monitor err s{sid}: {e}')
260
+
261
+ threading.Thread(target=monitor, daemon=True).start()
262
+
263
+ BADGE = {'idle':'βšͺ idle','pushing':'πŸ”„ pushing','queued':'🟑 queued',
264
+ 'inQueue':'🟑 queued','running':'🟒 running','complete':'βœ… complete',
265
+ 'done':'🏁 DONE','error':'πŸ”΄ error','push_failed':'πŸ”΄ push failed',
266
+ 'not_found':'βšͺ not found'}
267
+
268
+ def _b(st):
269
+ for k,v in BADGE.items():
270
+ if k in st: return v
271
+ return f'❓ {st}'
272
+
273
+ def sess_table():
274
+ with state_lock:
275
+ return [[s['session_id'], s['username'][:16], _b(s['status']),
276
+ s['run_number'], s['success'],
277
+ f'p{s["resume_page"]}β†’p{s["slice_end"]}',
278
+ (s['current_url'] or 'β€”')[:55],
279
+ (s['last_check'] or 'β€”')[-8:]]
280
+ for _,s in sorted(sessions.items())]
281
+
282
+ def hist_table():
283
+ with state_lock:
284
+ rows=[]
285
+ for _,s in sorted(sessions.items()):
286
+ for h in reversed(s['history'][-3:]):
287
+ rows.append([s['session_id'], h['run_number'], h['slug'],
288
+ h.get('resume_page','?'), h.get('last_page','?'),
289
+ h.get('stop_reason','?')[:25],
290
+ h.get('pushed_at','?')[-8:],
291
+ h.get('stopped_at','β€”')[-8:], h['url']])
292
+ return rows
293
+
294
+ def all_links():
295
+ with state_lock:
296
+ lines=[]
297
+ for _,s in sorted(sessions.items()):
298
+ for h in s['history']:
299
+ lines.append(f's{s["session_id"]} r{h["run_number"]} '
300
+ f'p{h.get("resume_page","?")} {h["url"]}')
301
+ return '\n'.join(lines) or 'No kernels pushed yet.'
302
+
303
+ def get_log():
304
+ with state_lock: return '\n'.join(log_lines[-80:])
305
+
306
+ def summary():
307
+ with state_lock:
308
+ ok = sum(s['success'] for s in sessions.values())
309
+ done = sum(1 for s in sessions.values() if s['complete'])
310
+ run = sum(1 for s in sessions.values() if 'running' in s['status'])
311
+ q = sum(1 for s in sessions.values() if 'queue' in s['status'].lower())
312
+ return (f'**{done}/{len(sessions)} sessions complete** | '
313
+ f'🟒 {run} running 🟑 {q} queued | βœ… {ok:,} builds scraped')
314
+
315
+ def get_api():
316
+ with state_lock:
317
+ return json.dumps({str(sid): {
318
+ 'session_id': s['session_id'], 'username': s['username'],
319
+ 'status': s['status'], 'run_number': s['run_number'],
320
+ 'current_url': s['current_url'], 'resume_page': s['resume_page'],
321
+ 'success': s['success'], 'skip': s['skip'], 'fail': s['fail'],
322
+ 'complete': s['complete'], 'last_check': s['last_check'],
323
+ 'slice_start': s['slice_start'], 'slice_end': s['slice_end'],
324
+ 'history': s['history'],
325
+ } for sid,s in sessions.items()}, indent=2)
326
+
327
+ def force_restart(sid_str):
328
+ try: sid=int(sid_str.strip())
329
+ except: return 'Invalid session ID'
330
+ if sid not in sessions: return f'Session {sid} not found'
331
+ with state_lock: sessions[sid]['current_slug']=None
332
+ threading.Thread(target=handle,args=(sid,),daemon=True).start()
333
+ return f'Restart triggered for session {sid}'
334
+
335
+ R=60
336
+ with gr.Blocks(title='PMC Worker') as app:
337
+ gr.Markdown(f'## PMC Worker β€” {len(KAGGLE_ACCOUNTS)} sessions | Auto-refresh {R}s')
338
+ gr.Markdown(value=summary, every=R)
339
+ with gr.Tabs():
340
+ with gr.Tab('Sessions'):
341
+ gr.Dataframe(
342
+ headers=['Sess','Account','Status','Runs','Built',
343
+ 'Progress','Current notebook','Last check'],
344
+ value=sess_table, every=R, interactive=False, wrap=True)
345
+ with gr.Row():
346
+ sid_in=gr.Textbox(label='Session ID',scale=1)
347
+ rb=gr.Button('Force restart',scale=1)
348
+ ro=gr.Textbox(label='Result',scale=3,interactive=False)
349
+ rb.click(force_restart,inputs=sid_in,outputs=ro)
350
+ with gr.Tab('History'):
351
+ gr.Dataframe(
352
+ headers=['Sess','Run','Slug','Resume pg','Last pg',
353
+ 'Stop reason','Pushed','Stopped','URL'],
354
+ value=hist_table, every=R, interactive=False, wrap=True)
355
+ with gr.Tab('All links'):
356
+ gr.Textbox(value=all_links, every=R, lines=30,
357
+ interactive=False, label='Every notebook URL ever pushed')
358
+ with gr.Tab('Log'):
359
+ gr.Textbox(value=get_log, every=15, lines=30,
360
+ interactive=False, label='Live log')
361
+ gr.Textbox(value=get_api, every=R, visible=False, label='api')
362
+
363
+ app.launch()