Nottybro commited on
Commit
5e88f2c
Β·
verified Β·
1 Parent(s): f7f6efd

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +27 -23
app.py CHANGED
@@ -5,24 +5,28 @@ import gradio as gr
5
  WORKER_URL = 'https://Nottybro-pmc-worker.hf.space'
6
  POLL_SECS = 60
7
 
8
- all_sessions = {}
9
  worker_health = {'last_ok': None, 'failures': 0}
10
- state_lock = threading.Lock()
11
 
12
  def poll():
13
  while True:
14
  try:
15
- r = requests.post(f'{WORKER_URL}/api/predict',
16
- json={'fn_index': 0, 'data': []}, timeout=25)
 
 
 
 
17
  r.raise_for_status()
18
- parsed = json.loads(r.json()['data'][0])
 
19
  with state_lock:
20
  all_sessions.update(parsed)
21
  worker_health['last_ok'] = time.strftime('%H:%M:%S UTC', time.gmtime())
22
  worker_health['failures'] = 0
23
  except Exception as e:
24
- with state_lock:
25
- worker_health['failures'] += 1
26
  print(f'Poll error: {e}')
27
  time.sleep(POLL_SECS)
28
 
@@ -38,20 +42,18 @@ def _b(st):
38
 
39
  def sess_table():
40
  with state_lock:
41
- if not all_sessions:
42
- return [['Waiting for worker data...']]
43
  return [[
44
  s['session_id'], s.get('username','')[:16],
45
  _b(s.get('status','?')), s.get('run_number',0), s.get('success',0),
46
  f'p{s.get("resume_page",0)}β†’p{s.get("slice_end",0)}',
47
  (s.get('current_url') or 'β€”')[:55],
48
  (s.get('last_check') or 'β€”')[-8:],
49
- ] for _,s in sorted(all_sessions.items(), key=lambda x: int(x[0]))]
50
 
51
  def summary():
52
  with state_lock:
53
- if not all_sessions:
54
- return '⏳ Waiting for first poll from worker...'
55
  vals = list(all_sessions.values())
56
  total = len(vals)
57
  done = sum(1 for s in vals if s.get('complete'))
@@ -60,32 +62,32 @@ def summary():
60
  ok = sum(s.get('success',0) for s in vals)
61
  runs = sum(s.get('run_number',0) for s in vals)
62
  tp = sum(s.get('slice_end',0)-s.get('slice_start',0)+1 for s in vals)
63
- dp = sum(max(0, s.get('resume_page',0)-s.get('slice_start',0)) for s in vals)
64
  pct = dp/max(tp,1)*100
65
- bar = 'β–ˆ'*int(pct/5) + 'β–‘'*(20-int(pct/5))
66
  cf = worker_health['failures']
67
  last = worker_health['last_ok'] or 'never'
68
  return (
69
  f'### PMC Master Dashboard\n'
70
  f'`[{bar}] {pct:.1f}%` pages done\n\n'
71
- f'**Sessions:** {done}/{total} complete | '
72
  f'🟒 {run} running | 🟑 {q} queued | '
73
  f'βœ… **{ok:,} builds** | πŸ”„ {runs} kernel runs\n\n'
74
- f'Worker last seen: `{last}` | '
75
- f'{"⚠️ Worker unreachable!" if cf>=3 else "Worker OK"}'
76
  )
77
 
78
  def all_links():
79
  with state_lock:
80
- lines=[]
81
- for _,s in sorted(all_sessions.items(), key=lambda x: int(x[0])):
82
- for h in s.get('history',[]):
83
  lines.append(f's{s["session_id"]} r{h["run_number"]} '
84
  f'p{h.get("resume_page","?")} | {h["url"]}')
85
  return '\n'.join(lines) or 'No data yet.'
86
 
87
  R = 60
88
- with gr.Blocks(title='PMC Master') as app:
89
  gr.Markdown('# PMC Distributed Scraper β€” Master Dashboard')
90
  gr.Markdown(value=summary, every=R)
91
  gr.Dataframe(
@@ -96,6 +98,8 @@ with gr.Blocks(title='PMC Master') as app:
96
  with gr.Tab('All notebook links'):
97
  gr.Textbox(value=all_links, every=R, lines=35,
98
  interactive=False, label='Every Kaggle notebook URL')
99
- gr.Markdown(f'*Polls Worker every {POLL_SECS}s. Worker: [{WORKER_URL}]({WORKER_URL})*')
 
 
100
 
101
- app.launch()
 
5
  WORKER_URL = 'https://Nottybro-pmc-worker.hf.space'
6
  POLL_SECS = 60
7
 
8
+ all_sessions = {}
9
  worker_health = {'last_ok': None, 'failures': 0}
10
+ state_lock = threading.Lock()
11
 
12
  def poll():
13
  while True:
14
  try:
15
+ # FIX: call named endpoint /api/status instead of fn_index
16
+ r = requests.post(
17
+ f'{WORKER_URL}/api/status',
18
+ json={'data': []},
19
+ timeout=25,
20
+ )
21
  r.raise_for_status()
22
+ raw = r.json()['data'][0]
23
+ parsed = json.loads(raw)
24
  with state_lock:
25
  all_sessions.update(parsed)
26
  worker_health['last_ok'] = time.strftime('%H:%M:%S UTC', time.gmtime())
27
  worker_health['failures'] = 0
28
  except Exception as e:
29
+ with state_lock: worker_health['failures'] += 1
 
30
  print(f'Poll error: {e}')
31
  time.sleep(POLL_SECS)
32
 
 
42
 
43
  def sess_table():
44
  with state_lock:
45
+ if not all_sessions: return [['Waiting for worker data...']]
 
46
  return [[
47
  s['session_id'], s.get('username','')[:16],
48
  _b(s.get('status','?')), s.get('run_number',0), s.get('success',0),
49
  f'p{s.get("resume_page",0)}β†’p{s.get("slice_end",0)}',
50
  (s.get('current_url') or 'β€”')[:55],
51
  (s.get('last_check') or 'β€”')[-8:],
52
+ ] for _, s in sorted(all_sessions.items(), key=lambda x: int(x[0]))]
53
 
54
  def summary():
55
  with state_lock:
56
+ if not all_sessions: return '⏳ Waiting for first worker poll...'
 
57
  vals = list(all_sessions.values())
58
  total = len(vals)
59
  done = sum(1 for s in vals if s.get('complete'))
 
62
  ok = sum(s.get('success',0) for s in vals)
63
  runs = sum(s.get('run_number',0) for s in vals)
64
  tp = sum(s.get('slice_end',0)-s.get('slice_start',0)+1 for s in vals)
65
+ dp = sum(max(0,s.get('resume_page',0)-s.get('slice_start',0)) for s in vals)
66
  pct = dp/max(tp,1)*100
67
+ bar = 'β–ˆ'*int(pct/5)+'β–‘'*(20-int(pct/5))
68
  cf = worker_health['failures']
69
  last = worker_health['last_ok'] or 'never'
70
  return (
71
  f'### PMC Master Dashboard\n'
72
  f'`[{bar}] {pct:.1f}%` pages done\n\n'
73
+ f'**{done}/{total}** sessions complete | '
74
  f'🟒 {run} running | 🟑 {q} queued | '
75
  f'βœ… **{ok:,} builds** | πŸ”„ {runs} kernel runs\n\n'
76
+ f'Worker: `{last}` | '
77
+ f'{"⚠️ Worker unreachable!" if cf>=3 else "βœ… Worker OK"}'
78
  )
79
 
80
  def all_links():
81
  with state_lock:
82
+ lines = []
83
+ for _, s in sorted(all_sessions.items(), key=lambda x: int(x[0])):
84
+ for h in s.get('history', []):
85
  lines.append(f's{s["session_id"]} r{h["run_number"]} '
86
  f'p{h.get("resume_page","?")} | {h["url"]}')
87
  return '\n'.join(lines) or 'No data yet.'
88
 
89
  R = 60
90
+ with gr.Blocks(title='PMC Master') as demo:
91
  gr.Markdown('# PMC Distributed Scraper β€” Master Dashboard')
92
  gr.Markdown(value=summary, every=R)
93
  gr.Dataframe(
 
98
  with gr.Tab('All notebook links'):
99
  gr.Textbox(value=all_links, every=R, lines=35,
100
  interactive=False, label='Every Kaggle notebook URL')
101
+ gr.Markdown(
102
+ f'*Polls Worker every {POLL_SECS}s via /api/status. '
103
+ f'Worker: [{WORKER_URL}]({WORKER_URL})*')
104
 
105
+ demo.launch()