Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
559 lines (489 loc) · 19.6 KB
/
Copy pathserver.py
File metadata and controls
559 lines (489 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
import os
import re
import uuid
from flask import Flask, request, jsonify, render_template, render_template_string
from pipeline import run_pipeline
import firestore_client as db
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
UPLOAD_DIR = os.path.join(BASE_DIR, "uploads")
AUDIO_DIR = os.path.join(BASE_DIR, "output")
os.makedirs(UPLOAD_DIR, exist_ok=True)
os.makedirs(AUDIO_DIR, exist_ok=True)
VALID_USER_ID = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
VALID_ROUTE = re.compile(r"^[一-鿿A-Za-z0-9]{1,8}$")
app = Flask(__name__)
PASSENGER_HTML = """
<!doctype html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>城市之眼</title>
<style>
html, body {
margin: 0; padding: 0; height: 100%; overflow: hidden;
background: #000; font-family: sans-serif; color: #fff;
}
#camera {
position: fixed; inset: 0; width: 100%; height: 100%;
object-fit: cover; background: #000;
}
#tapLayer { position: fixed; inset: 0; z-index: 5; }
#status {
position: fixed; top: 0; left: 0; right: 0; z-index: 10;
padding: 16px; text-align: center; font-size: 1.1rem;
background: rgba(0,0,0,0.55);
}
#settingsBtn {
position: fixed; top: 54px; right: 10px; z-index: 20;
padding: 10px 16px; border-radius: 20px;
background: #1976d2; color: #fff; border: none;
font-size: 1rem; font-weight: bold;
box-shadow: 0 2px 8px rgba(0,0,0,0.5);
}
#hint {
position: fixed; bottom: 40%; left: 0; right: 0; z-index: 10;
text-align: center; font-size: 1.2rem; color: rgba(255,255,255,0.85);
pointer-events: none;
}
/* ---- 校準精靈 ---- */
#wizard {
position: fixed; inset: 0; z-index: 50; background: #111;
display: flex; flex-direction: column; align-items: center; justify-content: center;
padding: 24px; text-align: center; overflow-y: auto;
}
#wizard h2 { font-size: 1.3rem; margin-bottom: 20px; }
.wizStep { display: none; width: 100%; max-width: 420px; }
.wizStep.active { display: block; }
.calBtn {
width: 100%; margin: 8px 0; padding: 18px;
font-size: 1.2rem; border-radius: 10px; border: 2px solid #666;
background: #222; color: #fff;
}
.calBtn:active { background: #444; }
.fovPreviewWrap {
position: relative; width: 100%; height: 260px; border-radius: 12px;
overflow: hidden; margin-bottom: 16px; background: #000;
}
#fovVideo { width: 100%; height: 100%; object-fit: cover; }
#fovMask {
position: absolute; inset: 0; pointer-events: none;
background: radial-gradient(circle at center, rgba(0,0,0,0) 0%, rgba(0,0,0,0) var(--r), rgba(0,0,0,0.92) var(--r));
}
input[type=range] { width: 100%; margin: 12px 0; }
#fontPreview, #themePreview {
border-radius: 10px; padding: 16px; margin: 12px 0; min-height: 50px;
}
.nextBtn {
margin-top: 16px; width: 100%; padding: 16px; font-size: 1.2rem;
background: #1976d2; color: #fff; border: none; border-radius: 10px;
}
/* ---- 全螢幕結果頁 ---- */
#resultScreen {
position: fixed; inset: 0; z-index: 40; display: none;
flex-direction: column; align-items: center; justify-content: center;
padding: 32px; text-align: center;
}
#resultText { line-height: 1.6; white-space: pre-wrap; }
#notifyBtn {
position: fixed; bottom: 0; left: 0; right: 0; z-index: 45;
padding: 20px; font-size: 1.3rem; font-weight: bold;
background: #d32f2f; color: #fff; border: none;
display: none;
}
</style>
</head>
<body>
<div id="wizard">
<div class="wizStep active" id="step1">
<h2>第一次使用,請選擇你的視覺狀況</h2>
<button class="calBtn" data-type="隧道視野">隧道視野</button>
<button class="calBtn" data-type="中心黑點">中心黑點</button>
<button class="calBtn" data-type="低視力">低視力</button>
<button class="calBtn" data-type="全盲">全盲</button>
</div>
<div class="wizStep" id="step2">
<h2>調整滑桿,直到圓圈範圍接近你看得清楚的視野</h2>
<div class="fovPreviewWrap">
<video id="fovVideo" autoplay playsinline muted></video>
<div id="fovMask" style="--r:50%;"></div>
</div>
<input type="range" id="fovSlider" min="10" max="100" value="60" />
<div id="fovLabel">目前設定:可視範圍 60%</div>
<button class="nextBtn" id="step2Next">下一步</button>
</div>
<div class="wizStep" id="step3">
<h2>調整字體大小</h2>
<div id="fontPreview">262 號公車,3 分鐘後到站</div>
<input type="range" id="fontSlider" min="20" max="64" value="32" />
<button class="nextBtn" id="step3Next">下一步</button>
</div>
<div class="wizStep" id="step4">
<h2>選擇畫面色調</h2>
<div id="themePreview">262 號公車,3 分鐘後到站</div>
<button class="calBtn" data-theme="light">白底黑字</button>
<button class="calBtn" data-theme="dark">黑底白字</button>
</div>
</div>
<video id="camera" autoplay playsinline muted></video>
<canvas id="canvas" style="display:none;"></canvas>
<div id="status">城市之眼 — 點螢幕任意處掃描</div>
<div id="hint">點一下畫面開始掃描</div>
<div id="tapLayer"></div>
<button id="settingsBtn" title="調整設定">調整視野/字體</button>
<div id="resultScreen">
<div id="resultText"></div>
</div>
<button id="notifyBtn">通知司機:本班車有視障乘客等車</button>
<audio id="player" style="display:none;"></audio>
<script>
const video = document.getElementById('camera');
const canvas = document.getElementById('canvas');
const statusEl = document.getElementById('status');
const hintEl = document.getElementById('hint');
const player = document.getElementById('player');
const tapLayer = document.getElementById('tapLayer');
const wizard = document.getElementById('wizard');
const notifyBtn = document.getElementById('notifyBtn');
const resultScreen = document.getElementById('resultScreen');
const resultText = document.getElementById('resultText');
let busy = false;
let lastRoute = null;
let profile = { impairment_type: '', visible_radius_percent: 100, font_size_px: 32, theme: 'dark', voice_enabled: true };
let chosenType = '';
function getUserId() {
let id = localStorage.getItem('user_id');
if (!id) {
id = 'u_' + Math.random().toString(36).slice(2, 10);
localStorage.setItem('user_id', id);
}
return id;
}
const userId = getUserId();
function showWizStep(id) {
document.querySelectorAll('.wizStep').forEach(s => s.classList.remove('active'));
document.getElementById(id).classList.add('active');
}
async function checkProfile() {
const res = await fetch('/api/profile?user_id=' + userId);
const data = await res.json();
if (data.exists) {
profile = Object.assign(profile, data.profile);
wizard.style.display = 'none';
initCamera();
} else {
wizard.style.display = 'flex';
showWizStep('step1');
}
}
// 設定按鈕:重新打開精靈,並帶入目前已儲存的設定值
document.getElementById('settingsBtn').addEventListener('click', async (e) => {
e.stopPropagation();
chosenType = profile.impairment_type || '隧道視野';
fovSlider.value = profile.visible_radius_percent || 60;
fovSlider.dispatchEvent(new Event('input'));
fontSlider.value = profile.font_size_px || 32;
fontSlider.dispatchEvent(new Event('input'));
wizard.style.display = 'flex';
showWizStep('step1');
try {
const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });
document.getElementById('fovVideo').srcObject = stream;
} catch (err) { /* 相機預覽非必要,忽略 */ }
});
// Step 1:障礙類型
document.querySelectorAll('#step1 .calBtn').forEach(btn => {
btn.addEventListener('click', async () => {
chosenType = btn.dataset.type;
showWizStep('step2');
try {
const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });
document.getElementById('fovVideo').srcObject = stream;
} catch (err) {
document.getElementById('fovLabel').innerText = '無法開啟相機預覽,可直接用滑桿設定';
}
});
});
// Step 2:可視範圍滑桿
const fovSlider = document.getElementById('fovSlider');
fovSlider.addEventListener('input', () => {
document.getElementById('fovMask').style.setProperty('--r', fovSlider.value + '%');
document.getElementById('fovLabel').innerText = '目前設定:可視範圍 ' + fovSlider.value + '%';
});
document.getElementById('step2Next').addEventListener('click', () => showWizStep('step3'));
// Step 3:字體大小
const fontSlider = document.getElementById('fontSlider');
fontSlider.addEventListener('input', () => {
document.getElementById('fontPreview').style.fontSize = fontSlider.value + 'px';
});
document.getElementById('step3Next').addEventListener('click', () => showWizStep('step4'));
// Step 4:色調 -> 存檔完成
document.querySelectorAll('#step4 .calBtn').forEach(btn => {
btn.addEventListener('click', async () => {
profile = {
impairment_type: chosenType,
visible_radius_percent: parseInt(fovSlider.value, 10),
font_size_px: parseInt(fontSlider.value, 10),
theme: btn.dataset.theme,
voice_enabled: true,
};
await fetch('/api/profile', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.assign({ user_id: userId }, profile)),
});
wizard.style.display = 'none';
initCamera();
});
});
function applyTheme(el) {
if (profile.theme === 'light') {
el.style.background = '#fff';
el.style.color = '#000';
} else {
el.style.background = '#000';
el.style.color = '#fff';
}
}
async function initCamera() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment' }
});
video.srcObject = stream;
} catch (err) {
statusEl.innerText = '無法開啟相機:' + err.message + '(需要 HTTPS 或 localhost)';
}
}
// 依可視範圍計算:每段顯示幾個字、停留幾秒(範圍越小,字越少、停越久)
function computePacing(text) {
const r = profile.visible_radius_percent || 100;
const charsPerChunk = Math.max(8, Math.round(0.6 * r + 8));
const secondsPerChunk = Math.max(2, Math.round(8 - r / 15));
const chunks = [];
for (let i = 0; i < text.length; i += charsPerChunk) {
chunks.push(text.slice(i, i + charsPerChunk));
}
return { chunks, secondsPerChunk };
}
function showResult(text) {
applyTheme(resultScreen);
resultText.style.fontSize = (profile.font_size_px || 32) + 'px';
resultScreen.style.display = 'flex';
const { chunks, secondsPerChunk } = computePacing(text);
let idx = 0;
resultText.innerText = chunks[0] || text;
if (chunks.length > 1) {
const timer = setInterval(() => {
idx++;
if (idx >= chunks.length) { clearInterval(timer); return; }
resultText.innerText = chunks[idx];
}, secondsPerChunk * 1000);
}
}
async function captureAndAnalyze() {
if (busy) return;
if (resultScreen.style.display === 'flex') {
resultScreen.style.display = 'none';
notifyBtn.style.display = 'none';
return;
}
busy = true;
if (navigator.vibrate) navigator.vibrate(80);
hintEl.style.display = 'none';
statusEl.innerText = '分析中...';
// 縮小到最長邊 1024px 再上傳,加快上傳與 Gemini 分析速度(辨識文字不需要原始解析度)
const MAX_DIM = 1024;
const scale = Math.min(1, MAX_DIM / Math.max(video.videoWidth, video.videoHeight));
canvas.width = Math.round(video.videoWidth * scale);
canvas.height = Math.round(video.videoHeight * scale);
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
canvas.toBlob(async (blob) => {
try {
const formData = new FormData();
formData.append('image', blob, 'scan.jpg');
formData.append('user_id', userId);
const res = await fetch('/api/analyze', { method: 'POST', body: formData });
const data = await res.json();
if (data.status !== 'success') {
statusEl.innerText = '失敗: ' + data.message;
} else {
statusEl.innerText = '點螢幕回到掃描';
showResult(data.summary);
if (profile.voice_enabled !== false) {
player.src = data.audio_url;
player.play();
}
lastRoute = data.route;
if (lastRoute) {
notifyBtn.style.display = 'block';
notifyBtn.innerText = '通知司機:' + lastRoute + ' 號公車有視障乘客等車';
}
}
} catch (err) {
statusEl.innerText = '發生錯誤: ' + err.message;
} finally {
busy = false;
}
}, 'image/jpeg', 0.9);
}
notifyBtn.addEventListener('click', async (e) => {
e.stopPropagation();
if (!lastRoute) return;
notifyBtn.innerText = '通知中...';
await fetch('/api/notify_driver', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user_id: userId, route: lastRoute, stop_name: '' }),
});
notifyBtn.innerText = '已通知司機';
if (navigator.vibrate) navigator.vibrate([50, 50, 50]);
});
tapLayer.addEventListener('click', captureAndAnalyze);
resultScreen.addEventListener('click', captureAndAnalyze);
checkProfile();
</script>
</body>
</html>
"""
DRIVER_HTML = """
<!doctype html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>司機端 — 城市之眼</title>
<style>
body { font-family: sans-serif; max-width: 480px; margin: 24px auto; padding: 0 16px; }
input, button { font-size: 1.1rem; padding: 10px; }
#alerts { margin-top: 20px; }
.alert {
background: #fff3cd; border: 1px solid #d32f2f; border-left: 6px solid #d32f2f;
padding: 14px; margin-bottom: 10px; border-radius: 6px; font-size: 1.1rem;
}
</style>
</head>
<body>
<h2>司機端 — 路線警示</h2>
<input id="routeInput" placeholder="輸入路線號碼,例如 262" />
<button id="startBtn">開始監看</button>
<div id="alerts"></div>
<script>
let route = null;
let timer = null;
async function poll() {
if (!route) return;
const res = await fetch('/api/driver_alerts?route=' + encodeURIComponent(route));
const data = await res.json();
const box = document.getElementById('alerts');
if (!data.alerts || data.alerts.length === 0) {
box.innerHTML = '<p>目前沒有警示</p>';
return;
}
box.innerHTML = data.alerts.map(a =>
`<div class="alert">${a.route} 號路線有視障乘客等車(${a.impairment_type || '未知類型'})</div>`
).join('');
}
document.getElementById('startBtn').addEventListener('click', () => {
route = document.getElementById('routeInput').value.trim();
if (!route) return;
if (timer) clearInterval(timer);
poll();
timer = setInterval(poll, 3000);
});
</script>
</body>
</html>
"""
@app.route("/")
def index():
return render_template("passenger.html")
@app.route("/passenger")
def passenger():
return render_template("passenger.html")
@app.route("/driver")
def driver():
return render_template("driver.html")
@app.route("/api/profile", methods=["GET"])
def api_get_profile():
user_id = request.args.get("user_id")
if not user_id:
return jsonify({"status": "error", "message": "缺少 user_id"}), 400
if not VALID_USER_ID.match(user_id):
return jsonify({"status": "error", "message": "user_id 格式不合法"}), 400
profile = db.get_user_profile(user_id)
if profile is None:
return jsonify({"exists": False})
return jsonify({"exists": True, "profile": profile})
@app.route("/api/profile", methods=["POST"])
def api_save_profile():
data = request.get_json(force=True)
user_id = data.get("user_id", "")
if not VALID_USER_ID.match(user_id):
return jsonify({"status": "error", "message": "user_id 格式不合法"}), 400
db.save_user_profile(
user_id=user_id,
impairment_type=data.get("impairment_type", ""),
visible_radius_percent=int(data.get("visible_radius_percent", 100)),
font_size_px=int(data.get("font_size_px", 32)),
theme=data.get("theme", "dark"),
voice_enabled=data.get("voice_enabled", True),
)
return jsonify({"status": "success"})
@app.route("/api/analyze", methods=["POST"])
def api_analyze():
file = request.files.get("image")
if not file:
return jsonify({"status": "error", "message": "缺少照片"}), 400
job_id = str(uuid.uuid4())[:8]
image_path = os.path.join(UPLOAD_DIR, f"{job_id}.jpg")
file.save(image_path)
audio_path = os.path.join(AUDIO_DIR, f"{job_id}.mp3")
try:
result = run_pipeline(image_path, audio_path)
except Exception:
print(f"[analyze] pipeline failed for job {job_id}", flush=True)
import traceback
traceback.print_exc()
return jsonify({"status": "error", "message": "辨識失敗,請再試一次"}), 500
route_match = re.search(r"\d{2,4}", result["summary"])
route = route_match.group() if route_match else None
return jsonify({
"status": "success",
"summary": result["summary"],
"audio_url": f"/audio/{job_id}.mp3",
"route": route,
})
@app.route("/api/notify_driver", methods=["POST"])
def api_notify_driver():
data = request.get_json(force=True)
user_id = data.get("user_id")
route = data.get("route")
if not route:
return jsonify({"status": "error", "message": "缺少路線號碼"}), 400
if not VALID_ROUTE.match(str(route)):
return jsonify({"status": "error", "message": "路線號碼格式不合法"}), 400
if user_id and not VALID_USER_ID.match(str(user_id)):
return jsonify({"status": "error", "message": "user_id 格式不合法"}), 400
profile = db.get_user_profile(user_id) if user_id else None
impairment_type = profile.get("impairment_type") if profile else None
db.create_bus_alert(
route=route,
stop_name=data.get("stop_name", ""),
impairment_type=impairment_type,
)
return jsonify({"status": "success"})
@app.route("/api/driver_alerts", methods=["GET"])
def api_driver_alerts():
route = request.args.get("route")
if not route:
return jsonify({"status": "error", "message": "缺少 route"}), 400
alerts = db.get_active_alerts(route)
return jsonify({"status": "success", "alerts": alerts})
@app.route("/audio/<path:filename>")
def serve_audio(filename):
return send_from_directory(AUDIO_DIR, filename)
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5001))
debug = os.environ.get("PORT") is None
app.run(host="0.0.0.0", port=port, debug=debug)