money-rain commited on
Commit
a3ef094
·
verified ·
1 Parent(s): c5c765e

Upload 8 files

Browse files
frontend/__pycache__/app.cpython-312.pyc CHANGED
Binary files a/frontend/__pycache__/app.cpython-312.pyc and b/frontend/__pycache__/app.cpython-312.pyc differ
 
frontend/app.py CHANGED
@@ -1,36 +1,56 @@
1
- from flask import Flask, jsonify, send_from_directory, request
 
2
  import logging
3
  import os
4
- import sqlite3
5
  from werkzeug.serving import WSGIRequestHandler
6
 
7
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
8
  ROOT_DIR = os.path.dirname(BASE_DIR)
9
 
10
 
11
- def get_db_path():
12
  bucket = os.getenv('BUCKET_PATH')
13
  if bucket:
14
- return os.path.join(os.path.abspath(bucket), 'rain_metrics.db')
15
- return os.path.join(ROOT_DIR, 'rain_metrics.db')
16
 
17
 
18
- DB_PATH = get_db_path()
 
 
19
 
20
  app = Flask(__name__, static_folder='static', static_url_path='')
21
 
22
 
23
- def get_rain_stats(db_path):
 
 
 
 
 
 
 
 
24
  try:
25
- conn = sqlite3.connect(db_path)
26
- c = conn.cursor()
27
- c.execute('SELECT days FROM rain_stats WHERE id=1')
28
- row = c.fetchone()
29
- conn.close()
30
- days = int(row[0]) if row else 0
31
- return {'days': days, 'volume_cm3': days * 50}
 
 
32
  except Exception:
33
- return {'days': 0, 'volume_cm3': 0}
 
 
 
 
 
 
 
34
 
35
 
36
  @app.route('/')
@@ -40,20 +60,17 @@ def index():
40
 
41
  @app.route('/stats')
42
  def stats():
43
- return jsonify(get_rain_stats(DB_PATH))
44
-
45
-
46
- @app.route('/reset', methods=['POST'])
47
- def reset():
48
- try:
49
- conn = sqlite3.connect(DB_PATH)
50
- c = conn.cursor()
51
- c.execute('UPDATE rain_stats SET days = 0 WHERE id=1')
52
- conn.commit()
53
- conn.close()
54
- return jsonify({'ok': True, 'stats': get_rain_stats(DB_PATH)})
55
- except Exception as e:
56
- return jsonify({'ok': False, 'error': str(e)}), 500
57
 
58
 
59
  class QuietHandler(WSGIRequestHandler):
 
1
+ from flask import Flask, jsonify, send_from_directory
2
+ import json
3
  import logging
4
  import os
5
+ import time
6
  from werkzeug.serving import WSGIRequestHandler
7
 
8
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
9
  ROOT_DIR = os.path.dirname(BASE_DIR)
10
 
11
 
12
+ def get_bucket_base():
13
  bucket = os.getenv('BUCKET_PATH')
14
  if bucket:
15
+ return os.path.abspath(bucket)
16
+ return ROOT_DIR
17
 
18
 
19
+ def get_stats_path():
20
+ return os.path.join(get_bucket_base(), 'rain_stats.json')
21
+
22
 
23
  app = Flask(__name__, static_folder='static', static_url_path='')
24
 
25
 
26
+ def get_rain_stats():
27
+ """Stats globales (toutes pluies) + session (depuis le dernier démarrage du Space)."""
28
+ default = {
29
+ 'total_claims': 0,
30
+ 'session_claims': 0,
31
+ 'session_start': None,
32
+ 'last_claim': None,
33
+ 'last_position': None
34
+ }
35
  try:
36
+ with open(get_stats_path(), encoding='utf-8') as f:
37
+ data = json.load(f)
38
+ return {
39
+ 'total_claims': int(data.get('total_claims', 0)),
40
+ 'session_claims': int(data.get('session_claims', 0)),
41
+ 'session_start': data.get('session_start'),
42
+ 'last_claim': data.get('last_claim'),
43
+ 'last_position': data.get('last_position')
44
+ }
45
  except Exception:
46
+ return default
47
+
48
+
49
+ def format_uptime(seconds):
50
+ seconds = int(seconds)
51
+ h, rem = divmod(seconds, 3600)
52
+ m, s = divmod(rem, 60)
53
+ return f'{h}h {m:02d}m {s:02d}s'
54
 
55
 
56
  @app.route('/')
 
60
 
61
  @app.route('/stats')
62
  def stats():
63
+ data = get_rain_stats()
64
+ uptime = 0
65
+ if data.get('session_start'):
66
+ try:
67
+ start_ts = time.mktime(time.strptime(data['session_start'], '%Y-%m-%d %H:%M:%S'))
68
+ uptime = time.time() - start_ts
69
+ except Exception:
70
+ uptime = 0
71
+ data['uptime'] = format_uptime(uptime)
72
+ data['now'] = time.strftime('%Y-%m-%d %H:%M:%S')
73
+ return jsonify(data)
 
 
 
74
 
75
 
76
  class QuietHandler(WSGIRequestHandler):
frontend/static/index.html CHANGED
@@ -3,28 +3,58 @@
3
  <head>
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
- <title>Interface Météo — Compteur de pluie</title>
7
  <style>
8
- body { font-family: Arial, sans-serif; background:#111; color:#eee; display:flex; align-items:center; justify-content:center; height:100vh; margin:0 }
9
- .card { background:#1f1f1f; padding:24px; border-radius:8px; width:420px; box-shadow:0 6px 18px rgba(0,0,0,0.4) }
10
- h1 { margin:0 0 8px 0; font-size:20px }
11
- .stat { font-size:36px; margin:12px 0; }
12
- button { background:#2d9f3f; color:white; border:none; padding:10px 16px; border-radius:6px; cursor:pointer }
13
- button:active { transform:translateY(1px) }
14
- .muted { color:#aaa; font-size:13px }
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  </style>
16
  </head>
17
  <body>
18
- <div class="card">
19
- <h1>Station Météo (Demo)</h1>
20
- <div>Nombre de jours de pluie</div>
21
- <div id="days" class="stat">0</div>
22
- <div>Volume de pluie (cm³)</div>
23
- <div id="volume" class="stat">0</div>
24
- <div style="display:flex;gap:8px;align-items:center;margin-top:12px">
25
- <button id="reset">Réinitialiser le compteur</button>
26
- <div class="muted">Mise à jour en temps réel (polling 1s)</div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  </div>
 
 
28
  </div>
29
  <script src="main.js"></script>
30
  </body>
 
3
  <head>
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Collecteur de Pluie Aviator</title>
7
  <style>
8
+ :root { --bg:#0d1117; --card:#161b22; --border:#30363d; --green:#2ea043; --accent:#58a6ff; --red:#f85149; }
9
+ * { box-sizing:border-box }
10
+ body { font-family:system-ui, Arial, sans-serif; background:var(--bg); color:#e6edf3; margin:0; padding:20px; display:flex; justify-content:center }
11
+ .wrap { width:100%; max-width:720px }
12
+ h1 { font-size:22px; margin:0 0 4px 0; display:flex; align-items:center; gap:10px }
13
+ .status { display:inline-block; padding:2px 10px; border-radius:12px; font-size:12px; font-weight:600 }
14
+ .status.on { background:rgba(46,160,67,.15); color:var(--green); border:1px solid var(--green) }
15
+ .status.off { background:rgba(248,81,73,.15); color:var(--red); border:1px solid var(--red) }
16
+ .muted { color:#8b949e; font-size:13px }
17
+ .grid { display:grid; grid-template-columns:1fr 1fr; gap:16px; margin-top:20px }
18
+ .card { background:var(--card); border:1px solid var(--border); border-radius:10px; padding:18px }
19
+ .card h2 { font-size:13px; text-transform:uppercase; letter-spacing:1px; color:#8b949e; margin:0 0 14px 0 }
20
+ .big { font-size:42px; font-weight:700; margin:0 }
21
+ .big.green { color:var(--green) }
22
+ .big.blue { color:var(--accent) }
23
+ .row { display:flex; justify-content:space-between; padding:6px 0; border-bottom:1px dashed #21262d; font-size:14px }
24
+ .row:last-child { border-bottom:none }
25
+ .row .lbl { color:#8b949e }
26
+ .row .val { font-weight:600 }
27
+ .footer { margin-top:20px; color:#484f58; font-size:12px; text-align:center }
28
  </style>
29
  </head>
30
  <body>
31
+ <div class="wrap">
32
+ <h1>☔ Collecteur de Pluie Aviator <span id="status" class="status on">ACTIF</span></h1>
33
+ <div class="muted" id="clock">--</div>
34
+
35
+ <div class="grid">
36
+ <div class="card">
37
+ <h2>Session actuelle (depuis le dernier démarrage)</h2>
38
+ <div id="session_claims" class="big green">0</div>
39
+ <div class="muted">pluies récupérées</div>
40
+ <div style="margin-top:12px">
41
+ <div class="row"><span class="lbl">Démarrage</span><span class="val" id="session_start">-</span></div>
42
+ <div class="row"><span class="lbl">Uptime</span><span class="val" id="uptime">-</span></div>
43
+ </div>
44
+ </div>
45
+
46
+ <div class="card">
47
+ <h2>Statistiques globales</h2>
48
+ <div id="total_claims" class="big blue">0</div>
49
+ <div class="muted">pluies au total</div>
50
+ <div style="margin-top:12px">
51
+ <div class="row"><span class="lbl">Dernière pluie</span><span class="val" id="last_claim">-</span></div>
52
+ <div class="row"><span class="lbl">Position du clic</span><span class="val" id="last_position">-</span></div>
53
+ </div>
54
+ </div>
55
  </div>
56
+
57
+ <div class="footer">Mise à jour automatique toutes les 2 secondes · Space Hugging Face</div>
58
  </div>
59
  <script src="main.js"></script>
60
  </body>
frontend/static/main.js CHANGED
@@ -1,29 +1,33 @@
1
- const daysEl = document.getElementById('days')
2
- const volumeEl = document.getElementById('volume')
3
- const resetBtn = document.getElementById('reset')
 
 
 
 
 
 
 
4
 
5
- async function fetchStats(){
6
- try{
7
  const res = await fetch('/stats')
8
  const data = await res.json()
9
- daysEl.textContent = data.days
10
- volumeEl.textContent = data.volume_cm3
11
- }catch(e){
12
- console.error(e)
 
 
 
 
 
 
 
 
 
13
  }
14
  }
15
 
16
- resetBtn.addEventListener('click', async ()=>{
17
- try{
18
- const res = await fetch('/reset', {method: 'POST'})
19
- const data = await res.json()
20
- if(data.ok){
21
- daysEl.textContent = data.stats.days
22
- volumeEl.textContent = data.stats.volume_cm3
23
- }
24
- }catch(e){console.error(e)}
25
- })
26
-
27
- // poll every second
28
  fetchStats()
29
- setInterval(fetchStats, 1000)
 
1
+ const els = {
2
+ status: document.getElementById('status'),
3
+ clock: document.getElementById('clock'),
4
+ session_claims: document.getElementById('session_claims'),
5
+ session_start: document.getElementById('session_start'),
6
+ uptime: document.getElementById('uptime'),
7
+ total_claims: document.getElementById('total_claims'),
8
+ last_claim: document.getElementById('last_claim'),
9
+ last_position: document.getElementById('last_position'),
10
+ }
11
 
12
+ async function fetchStats() {
13
+ try {
14
  const res = await fetch('/stats')
15
  const data = await res.json()
16
+ els.session_claims.textContent = data.session_claims ?? 0
17
+ els.total_claims.textContent = data.total_claims ?? 0
18
+ els.session_start.textContent = data.session_start ?? '-'
19
+ els.uptime.textContent = data.uptime ?? '-'
20
+ els.last_claim.textContent = data.last_claim ?? '-'
21
+ els.last_position.textContent = data.last_position ?? '-'
22
+ els.clock.textContent = 'Dernière mise à jour : ' + (data.now ?? '-')
23
+ els.status.textContent = 'ACTIF'
24
+ els.status.className = 'status on'
25
+ } catch (e) {
26
+ els.status.textContent = 'INDISPONIBLE'
27
+ els.status.className = 'status off'
28
+ els.clock.textContent = 'Serveur injoignable'
29
  }
30
  }
31
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  fetchStats()
33
+ setInterval(fetchStats, 2000)
rain_collector.py CHANGED
@@ -1,4 +1,5 @@
1
  #!/usr/bin/env python3
 
2
  import os
3
  import time
4
  from dotenv import load_dotenv
@@ -202,6 +203,51 @@ def session_probe(context):
202
 
203
  CLAIM_SELECTOR = '.btn.claim-btn, button.claim-btn, .claim-btn'
204
  POSITIONS_FILE = 'claim_positions.txt'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
 
207
  def log_claim_position(page):
@@ -229,6 +275,7 @@ def log_claim_position(page):
229
  print(f'📍 Claim visible à ({cx:.0f},{cy:.0f}) | {box["width"]:.0f}x{box["height"]:.0f} | {ts}')
230
  with open(os.path.join(get_bucket_base(), POSITIONS_FILE), 'a') as f:
231
  f.write(f'{ts} x={cx:.0f} y={cy:.0f} w={box["width"]:.0f} h={box["height"]:.0f}\n')
 
232
  return
233
  except Exception:
234
  continue
@@ -322,6 +369,7 @@ def run_session(playwright, phone, password):
322
  def main():
323
  phone, password = load_environment()
324
  ensure_session_dir()
 
325
 
326
  with sync_playwright() as playwright:
327
  run_session(playwright, phone, password)
 
1
  #!/usr/bin/env python3
2
+ import json
3
  import os
4
  import time
5
  from dotenv import load_dotenv
 
203
 
204
  CLAIM_SELECTOR = '.btn.claim-btn, button.claim-btn, .claim-btn'
205
  POSITIONS_FILE = 'claim_positions.txt'
206
+ STATS_FILE = 'rain_stats.json'
207
+
208
+
209
+ def get_stats_path():
210
+ return os.path.join(get_bucket_base(), STATS_FILE)
211
+
212
+
213
+ def init_stats():
214
+ """Crée/réinitialise les stats au démarrage du collector (session = depuis ce boot)."""
215
+ default = {
216
+ 'total_claims': 0,
217
+ 'session_claims': 0,
218
+ 'session_start': time.strftime('%Y-%m-%d %H:%M:%S'),
219
+ 'last_claim': None,
220
+ 'last_position': None
221
+ }
222
+ try:
223
+ if os.path.exists(get_stats_path()):
224
+ with open(get_stats_path(), encoding='utf-8') as f:
225
+ data = json.load(f)
226
+ data['session_claims'] = 0
227
+ data['session_start'] = default['session_start']
228
+ else:
229
+ data = default
230
+ with open(get_stats_path(), 'w', encoding='utf-8') as f:
231
+ json.dump(data, f, ensure_ascii=False, indent=2)
232
+ return data
233
+ except Exception as exc:
234
+ print(f'⚠️ Impossible d\'initialiser les stats : {exc}')
235
+ return default
236
+
237
+
238
+ def record_claim(cx, cy):
239
+ """Enregistre une pluie récupérée (global + session) dans rain_stats.json."""
240
+ try:
241
+ with open(get_stats_path(), encoding='utf-8') as f:
242
+ data = json.load(f)
243
+ data['total_claims'] = int(data.get('total_claims', 0)) + 1
244
+ data['session_claims'] = int(data.get('session_claims', 0)) + 1
245
+ data['last_claim'] = time.strftime('%Y-%m-%d %H:%M:%S')
246
+ data['last_position'] = f'({cx:.0f},{cy:.0f})'
247
+ with open(get_stats_path(), 'w', encoding='utf-8') as f:
248
+ json.dump(data, f, ensure_ascii=False, indent=2)
249
+ except Exception:
250
+ pass
251
 
252
 
253
  def log_claim_position(page):
 
275
  print(f'📍 Claim visible à ({cx:.0f},{cy:.0f}) | {box["width"]:.0f}x{box["height"]:.0f} | {ts}')
276
  with open(os.path.join(get_bucket_base(), POSITIONS_FILE), 'a') as f:
277
  f.write(f'{ts} x={cx:.0f} y={cy:.0f} w={box["width"]:.0f} h={box["height"]:.0f}\n')
278
+ record_claim(cx, cy)
279
  return
280
  except Exception:
281
  continue
 
369
  def main():
370
  phone, password = load_environment()
371
  ensure_session_dir()
372
+ init_stats()
373
 
374
  with sync_playwright() as playwright:
375
  run_session(playwright, phone, password)