move_detect/server/tools/seed_demo.php
유창욱 93f896af87 fix(audit): 1.2.0 4차 재감사 — 확정 23건 전량 해소
4개 관점 병렬 감사 후 각 발견을 반증 시도해 확정. 반증 5건은 문서에 남겼다.

이번 감사의 요지: **구현도 단위테스트도 초록인데 납품 경로에서 동작하지 않는**
결함이 셋 있었다. 전부 같은 모양이다 — 테스트가 기본값이 아닌 설정을 썼거나,
값이 존재해도 되는지 결정하는 상류 허용 목록을 보지 않았다.

CRITICAL 4건:

R4-1 추락 승격이 기본 설정에서 한 번도 발화하지 않았다. link_s(3.0)를 now
기준으로 쟀는데 넘어짐은 prone_confirm_s(3.0) 지속 후 확정되므로 확정 시점에는
항상 3초 넘게 지나 있다. 다른 테스트가 전부 prone_confirm_s=0.5 를 써서
초록이었다. 착지(prone 시작) 시각과 비교하도록 고치고, 기본값 그대로 도는
회귀 테스트를 넣었다.

R4-2 max_workers:0 이 상류 두 곳에서 막혀 있었다 — 서버 규칙 경계가 [1,50]
이라 저장이 400 이고, 엣지 파서가 v<=0 으로 규칙 전체를 무효화해 같이 넣은
2인1조까지 사라졌다. 앞 커밋에서 고친 네 곳은 전부 이 둘보다 하류라 도달
불가였다.

R4-3 고소작업 프리셋(elevated)이 완전히 무동작이었다. 서버 경계에 키가 없어
400, 통과해도 엣지 파서가 침묵 삭제. 프리셋 안내문과 커밋 메시지가 시스템이
하지 않는 일을 약속하고 있었다.

R4-4 동시 다발이 한 사람을 두 명으로 셀 수 있었다. 트래커는 1초 가려짐에
트랙을 버리고 새 id 를 주고(max_age=1.0) 누운 사람은 새 트랙에서도 즉시
prone 이라 두 번째 fall 이 난다. 그러면 다친 한 사람에게 "공기호흡기 없이
진입 금지"가 나가 구조가 늦어진다 — 기능의 가치가 정반대로 뒤집힌다.
ghost 를 인원 집계에서 빼고, 거의 같은 자리의 사건은 같은 사람으로 본다.

HIGH 5건: 구역 그룹핑 사문화(엣지가 zone_id 를 안 실어 카메라가 다른 두
희생자가 절대 안 묶였다 — 밀폐공간이 정확히 그 상황), 창 미끄러짐으로 한
사고가 매 분 새 위급 건으로 쏟아지고 인원이 줄면 앞선 알림을 스스로 뒤집던
문제, 무장 미만료·forget 누락·이중 발보, 업그레이드 안내의 마이그레이션 2개
누락(신규 유형 INSERT 가 전부 DB CHECK 에 걸린다), BUILD-INFO 커밋 스탬프.

BUILD-INFO 는 1.1.0 에서 고친 R3-6 의 재발이다. 절차로 막으려다 두 번
실패했으므로 HEAD 일치를 검사하는 테스트로 막았다. README 마이그레이션
목록도 같은 이유로 테스트를 붙였다.

MEDIUM 14건 중 눈에 띄는 것: 정비 억제가 SCBA 경고를 삼켰고(허가가 발급된
그 구역·그 시간이 질식이 일어나는 자리다) 위급 3종을 억제 예외로 뺐다.
데모 시더 심각도가 제품과 7종 어긋나 fall 이 위급으로 찍혀 1.2.0 의 요점인
넘어짐/추락 구분이 데모에서 지워져 있었다 — 라벨과 달리 화면이 안 깨져
눈으로는 못 잡으므로 엣지를 단일 출처로 강제하는 테스트를 붙였다.
문서의 "17종"은 실제 20종(엣지 16 + 서버 4)으로 정정하고 신규 2종을
소개서 감지 표에 넣었다.

검증: pytest 335 passed / phpunit 269 passed. 신규 테스트 30건.
dist 는 이 커밋 이후 재생성한다(BUILD-INFO 가 HEAD 를 가리켜야 한다).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EBjuR7DW6PNNMows4KnbYU
2026-09-05 23:11:57 +09:00

389 lines
22 KiB
PHP

<?php
/**
* 데모/QA 시드 생성기.
*
* php -d extension=pdo_sqlite server/tools/seed_demo.php --days=45 --force
*
* WHY THIS EXISTS: every demo, every UI review and every regression check needs a database that
* looks like a real site — several devices, cameras with different risk profiles, an incident
* cascade (fall → no_motion on the same track), acknowledged and unacknowledged rows, false
* positives, evidence images, zones with rules, improvement actions. Building that by hand each
* time is how screens get signed off against data that never occurs in production (a single
* severity, no empty states, no long tail).
*
* SAFETY: this writes demo rows. It refuses to touch a database that already holds events
* unless --force is given, and it never runs over HTTP (see bootstrap.php). Every row it writes
* is tagged so --purge can remove exactly those rows and nothing else.
*
* Images need ext-gd. Without it the seeder still runs and the rows simply have no snapshot,
* which is itself a state worth seeing (PIPA retention purges produce it in production).
*/
declare(strict_types=1);
require __DIR__ . '/bootstrap.php';
[$cfg, $pdo] = tool_boot();
$args = tool_args($argv);
// Demo rows carry a marker in a field no real path ever writes, so --purge can target exactly
// those rows and nothing else. This is not cosmetic: a purge that matches on a plausible real
// value (an operator name, a site name) will one day be run against a production database and
// delete records nobody can reconstruct.
const DEMO_PREFIX = 'demo-'; // device_id prefix
const DEMO_ACTOR = 'demo-seed'; // created_by / reviewed_by
const DEMO_LABEL = '[데모] '; // name prefix on channels
$days = max(1, min(365, (int)($args['days'] ?? 45)));
$force = isset($args['force']);
$purge = isset($args['purge']);
$withImgs = !isset($args['no-images']) && function_exists('imagecreatetruecolor');
$snapshotDir = rtrim($cfg->snapshotDir(), '/\\');
function say(string $m): void { fwrite(STDOUT, $m . "\n"); }
// ---------------------------------------------------------------- purge
function purge(PDO $pdo, string $snapshotDir): void
{
$like = DEMO_PREFIX . '%';
// Snapshot files first: once the rows go, the uuids are unrecoverable and the jpgs would
// sit orphaned on disk forever.
$st = $pdo->prepare(
'SELECT s.file_uuid FROM move_event_snapshots s
JOIN move_events e ON e.event_id = s.event_id
WHERE e.device_id LIKE ?'
);
$st->execute([$like]);
$removed = 0;
foreach ($st->fetchAll(PDO::FETCH_COLUMN) as $uuid) {
$p = $snapshotDir . '/' . $uuid . '.jpg';
if (is_file($p) && @unlink($p)) $removed++;
}
$pdo->prepare('DELETE FROM move_event_snapshots WHERE event_id IN
(SELECT event_id FROM move_events WHERE device_id LIKE ?)')->execute([$like]);
$pdo->prepare('DELETE FROM move_events WHERE device_id LIKE ?')->execute([$like]);
$pdo->prepare('DELETE FROM move_zones WHERE device_id LIKE ?')->execute([$like]);
$pdo->prepare('DELETE FROM move_devices WHERE device_id LIKE ?')->execute([$like]);
$pdo->prepare('DELETE FROM move_cameras WHERE device_id LIKE ?')->execute([$like]);
$pdo->prepare('DELETE FROM move_device_metrics WHERE device_id LIKE ?')->execute([$like]);
$pdo->prepare("DELETE FROM move_actions WHERE created_by = ?")->execute([DEMO_ACTOR]);
// 데모 행은 반드시 DEMO_ACTOR / DEMO_PREFIX 표식으로만 식별한다.
//
// 감사 지적(A2): 예전에는 위험요인을 `reviewed_by='안전관리자' AND site='factory-a'` 로
// 지웠다. '안전관리자'는 이 제품의 기본 관리자 계정명이고 'factory-a'는 흔한 현장명이라,
// 운영 DB 에서 --purge 를 한 번 돌리면 **실제 위험성평가가 통째로 사라진다.** 표식 없는
// 행은 이제 어떤 경우에도 건드리지 않는다.
$pdo->prepare("DELETE FROM move_alert_channels WHERE name LIKE ?")->execute([DEMO_LABEL . '%']);
$pdo->prepare("DELETE FROM move_risk_controls WHERE reviewed_by = ?")->execute([DEMO_ACTOR]);
say("purged demo rows (snapshot files removed: $removed)");
}
if ($purge) { purge($pdo, $snapshotDir); if (!$force) exit(0); }
$existing = (int)$pdo->query('SELECT COUNT(*) FROM move_events')->fetchColumn();
if ($existing > 0 && !$force) {
fwrite(STDERR, "이미 이벤트 {$existing}건이 있는 DB입니다. 데모 데이터를 섞으려면 --force,\n"
. "기존 데모 행만 지우려면 --purge 를 쓰세요.\n");
exit(1);
}
// ---------------------------------------------------------------- fixtures
$now = time();
/** A workplace, not a test fixture: each camera has a different risk profile so the report,
* the ranking bars and the FP panel all have something real to say. */
$devices = [
['id' => DEMO_PREFIX . 'press', 'name' => '1공장 프레스라인', 'site' => 'factory-a',
'fps' => 24.8, 'temp' => 58.2, 'throttle' => 0, 'beat' => $now - 8],
['id' => DEMO_PREFIX . 'wh', 'name' => '1공장 자재창고', 'site' => 'factory-a',
'fps' => 23.9, 'temp' => 61.4, 'throttle' => 1, 'beat' => $now - 21],
['id' => DEMO_PREFIX . 'paint', 'name' => '2공장 도장부스', 'site' => 'factory-a',
'fps' => null, 'temp' => null, 'throttle' => null, 'beat' => $now - 5400], // offline
];
$cameras = [
DEMO_PREFIX . 'press' => ['cam-press-01', 'cam-press-02'],
DEMO_PREFIX . 'wh' => ['cam-wh-01', 'cam-wh-02'],
DEMO_PREFIX . 'paint' => ['cam-paint-01'],
];
// Per camera: how often it fires, and what it tends to fire. A press line falls; a warehouse
// has zone and occupancy traffic; a paint booth is quiet but degrades.
$profile = [
'cam-press-01' => ['weight' => 4, 'types' => ['fall', 'near_fall', 'immobility', 'ergo_report', 'no_motion']],
'cam-press-02' => ['weight' => 3, 'types' => ['near_fall', 'ergo_report', 'pinch', 'ghost']],
'cam-wh-01' => ['weight' => 2, 'types' => ['zone_warning', 'overstay', 'lone_worker']],
'cam-wh-02' => ['weight' => 3, 'types' => ['zone_restricted', 'overcapacity', 'overstay', 'zone_warning']],
'cam-paint-01' => ['weight' => 1, 'types' => ['monitoring_degraded', 'device_fault', 'zone_warning']],
];
$severityOf = [
// 심각도는 edge/events.py 의 _SEVERITY 가 단일 출처다. 여기서 다른 값을 쓰면
// 데모·스크린샷·UI 검토가 실제 제품과 다른 등급을 보여준다 — 특히 1.2.0 의
// 요점인 넘어짐(HIGH) 대 추락(CRITICAL) 구분이 데모에서 지워진다.
// tests/test_seed_demo_severity.py 가 두 표의 일치를 강제한다.
'camera_moved' => 'high', 'camera_obstructed' => 'high', 'device_fault' => 'warning',
'ergo_report' => 'info', 'fall' => 'high', 'fall_from_height' => 'critical',
'fire_smoke' => 'critical', 'ghost' => 'critical', 'immobility' => 'warning',
'lone_worker' => 'high', 'low_light' => 'warning', 'monitoring_degraded' => 'warning',
'multi_down' => 'critical', 'near_fall' => 'info', 'no_motion' => 'critical',
'overcapacity' => 'warning', 'overstay' => 'warning', 'pinch' => 'high',
'ppe_missing' => 'warning', 'proximity' => 'high', 'unacked_escalation' => 'critical',
'zone_restricted' => 'high', 'zone_warning' => 'warning',
];
$pdo->beginTransaction();
// devices + cameras
$dev = $pdo->prepare('INSERT INTO move_devices (device_id,name,site,secret,config_version,last_fps,last_temp,
last_throttle,reported_config_version,last_heartbeat_at,created_at)
VALUES (?,?,?,?,3,?,?,?,3,?,?)');
$cam = $pdo->prepare('INSERT INTO move_cameras (camera_id,device_id,name,role,created_at) VALUES (?,?,?,?,?)');
foreach ($devices as $d) {
// A demo secret that is obviously not a credential. Never a plausible-looking one: a demo
// row that looks provisioned invites someone to point a real device at it.
$dev->execute([$d['id'], $d['name'], $d['site'], 'DEMO-NOT-A-REAL-SECRET',
$d['fps'], $d['temp'], $d['throttle'], $d['beat'], $now - 86400 * 90]);
foreach ($cameras[$d['id']] as $c) {
$cam->execute([$c, $d['id'], $c, str_starts_with($c, 'cam-press') ? 'fall_critical' : 'zone', $now - 86400 * 90]);
}
}
// ---------------------------------------------------------------- events
$ins = $pdo->prepare(
'INSERT INTO move_events (event_uuid,device_id,site,camera_id,event_type,severity,track_id,zone_id,
occurred_at,duration_s,metrics_json,spatial_x,spatial_y,acknowledged_by,acknowledged_at,
false_positive_by,false_positive_at,received_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
);
$deviceOf = [];
foreach ($cameras as $devId => $list) foreach ($list as $c) $deviceOf[$c] = $devId;
$siteOf = [];
foreach ($devices as $d) $siteOf[$d['id']] = $d['site'];
$seq = 0;
$made = 0;
mt_srand(20260809); // deterministic: two runs produce the same board, so screenshots diff cleanly
function metricsFor(string $type, float $dur): ?string
{
$m = ['confidence' => round(0.72 + mt_rand(0, 260) / 1000, 2)];
if ($type === 'immobility') $m['immobility_s'] = round($dur, 1);
if ($type === 'no_motion') $m['prone_s'] = round($dur, 1);
if ($type === 'overstay') { $m['dwell_s'] = round($dur, 1); $m['limit_s'] = 1800; }
if ($type === 'lone_worker') { $m['alone_s'] = round($dur, 1); $m['workers'] = 1; $m['required'] = 2; }
if ($type === 'overcapacity'){ $m['workers'] = 5; $m['limit'] = 4; }
if ($type === 'ghost') { $m['waited_s'] = round($dur, 1); $m['last_state'] = 'FALLEN'; }
if ($type === 'fall') { $m['torso_angle'] = mt_rand(62, 88); $m['aspect_ratio'] = round(mt_rand(150, 260) / 100, 2); }
if ($type === 'ergo_report') {
$m['observed_s'] = 3600; $m['trunk_high_s'] = mt_rand(120, 900);
$m['trunk_mod_s'] = mt_rand(400, 1800); $m['arm_high_s'] = mt_rand(60, 600);
$m['squat_s'] = mt_rand(30, 400);
}
return json_encode($m, JSON_UNESCAPED_UNICODE);
}
/** One event row. Returns the inserted event_id. */
function emit(PDO $pdo, PDOStatement $ins, array $ctx): int
{
$ins->execute([
$ctx['uuid'], $ctx['device'], $ctx['site'], $ctx['camera'], $ctx['type'], $ctx['severity'],
$ctx['track'], null, $ctx['at'], $ctx['dur'], $ctx['metrics'], $ctx['x'], $ctx['y'],
$ctx['ackBy'], $ctx['ackAt'], $ctx['fpBy'], $ctx['fpAt'], (int)$ctx['at'],
]);
return (int)$pdo->lastInsertId();
}
$eventIds = []; // newest-first, for snapshot attachment
// Weighted camera picker.
$bag = [];
foreach ($profile as $c => $p) for ($i = 0; $i < $p['weight']; $i++) $bag[] = $c;
for ($d = 0; $d < $days; $d++) {
// Fewer events per day the further back we go? No — keep the rate flat but let the
// hour-of-day distribution be realistic: a day shift peak, a smaller night peak.
$perDay = mt_rand(1, 5);
for ($k = 0; $k < $perDay; $k++) {
$camera = $bag[array_rand($bag)];
$type = $profile[$camera]['types'][array_rand($profile[$camera]['types'])];
$sev = $severityOf[$type] ?? 'info';
// Shift-shaped hours: 07-17 heavy, 22-02 light, rest sparse.
$roll = mt_rand(1, 100);
$hour = $roll <= 65 ? mt_rand(7, 17) : ($roll <= 85 ? mt_rand(22, 25) % 24 : mt_rand(0, 23));
$at = $now - $d * 86400;
$at = mktime($hour, mt_rand(0, 59), mt_rand(0, 59), (int)date('n', $at), (int)date('j', $at), (int)date('Y', $at));
if ($at > $now) $at -= 86400;
$dur = match ($type) {
'immobility' => mt_rand(300, 900), 'overstay' => mt_rand(1800, 4200),
'lone_worker' => mt_rand(60, 600), 'ergo_report' => 3600,
'no_motion' => mt_rand(20, 90), default => round(mt_rand(4, 40) / 10, 1),
};
// Older events are mostly handled; recent ones mostly are not — that is what a real
// board looks like, and it is what makes the 미확인 view worth having.
$handled = $d === 0 ? mt_rand(1, 100) <= 25 : ($d <= 2 ? mt_rand(1, 100) <= 70 : mt_rand(1, 100) <= 95);
$isFp = $handled && mt_rand(1, 100) <= 14;
$seq++;
$ctx = [
'uuid' => substr(str_pad(DEMO_PREFIX . $seq, 32, '0', STR_PAD_LEFT), -32),
'device' => $deviceOf[$camera], 'site' => $siteOf[$deviceOf[$camera]], 'camera' => $camera,
'type' => $type, 'severity' => $sev, 'track' => 100 + $seq, 'at' => (float)$at, 'dur' => $dur,
'metrics' => metricsFor($type, (float)$dur),
'x' => round(mt_rand(120, 880) / 1000, 3), 'y' => round(mt_rand(200, 900) / 1000, 3),
'ackBy' => $handled ? '안전관리자' : null,
'ackAt' => $handled ? $at + mt_rand(40, 900) : null,
'fpBy' => $isFp ? '안전관리자' : null,
'fpAt' => $isFp ? $at + mt_rand(60, 1200) : null,
];
$eventIds[] = ['id' => emit($pdo, $ins, $ctx), 'camera' => $camera, 'at' => $at, 'type' => $type];
$made++;
// Incident cascade: a fall is followed by the no_motion the detector chain really emits
// seconds later, on the SAME track. This is the case the console has to render as two
// rows of one event — worth having in every demo.
if ($type === 'fall' && mt_rand(1, 100) <= 60) {
$seq++;
$ctx2 = $ctx;
$ctx2['uuid'] = substr(str_pad(DEMO_PREFIX . $seq, 32, '0', STR_PAD_LEFT), -32);
$ctx2['type'] = 'no_motion';
$ctx2['severity'] = 'critical';
$ctx2['at'] = (float)($at + mt_rand(20, 45));
$ctx2['dur'] = mt_rand(20, 60);
$ctx2['metrics'] = metricsFor('no_motion', (float)$ctx2['dur']);
$eventIds[] = ['id' => emit($pdo, $ins, $ctx2), 'camera' => $camera, 'at' => (int)$ctx2['at'], 'type' => 'no_motion'];
$made++;
}
}
}
// ---------------------------------------------------------------- zones
$zone = $pdo->prepare('INSERT INTO move_zones (zone_id,device_id,camera_id,level,polygon_json,rules_json,updated_at)
VALUES (?,?,?,?,?,?,?)');
$zone->execute([bin2hex(random_bytes(16)), DEMO_PREFIX . 'press', 'cam-press-01', 'restricted',
json_encode([[0.18, 0.30], [0.66, 0.28], [0.70, 0.82], [0.20, 0.85]]),
json_encode(['min_workers' => 2]), $now]);
$zone->execute([bin2hex(random_bytes(16)), DEMO_PREFIX . 'press', 'cam-press-02', 'pinch',
json_encode([[0.55, 0.40], [0.86, 0.42], [0.84, 0.78], [0.53, 0.76]]), null, $now]);
$zone->execute([bin2hex(random_bytes(16)), DEMO_PREFIX . 'wh', 'cam-wh-02', 'warning',
json_encode([[0.08, 0.55], [0.92, 0.52], [0.94, 0.94], [0.06, 0.96]]),
json_encode(['max_workers' => 4, 'max_dwell_s' => 1800]), $now]);
// ---------------------------------------------------------------- improvement actions
$act = $pdo->prepare('INSERT INTO move_actions (camera_id,site,note,taken_at,created_by,created_at) VALUES (?,?,?,?,?,?)');
foreach ([
['cam-press-01', '프레스 진입로 미끄럼 방지 매트 설치', 34],
['cam-wh-02', '자재창고 통로 폭 확대 · 안전선 재도색', 12],
['cam-press-02', '협착 구역 광전센서 추가 · 방호덮개 교체', 5],
] as [$c, $note, $ago]) {
$act->execute([$c, 'factory-a', $note, $now - $ago * 86400, DEMO_ACTOR, $now - $ago * 86400]);
}
// ---------------------------------------------------------------- 통보 · 규정 · 성능
// 새 화면(시스템 설정 / 안전 관리)이 빈 상태로만 시연되면 그 기능이 없는 것처럼 보인다.
// 다만 어떤 것도 실제로 발송되지 않도록, 채널은 전부 비활성으로 넣는다.
$ch = $pdo->prepare('INSERT INTO move_alert_channels (site,kind,name,config_json,min_severity,enabled,step,escalate_after_s,created_at)
VALUES (?,?,?,?,?,?,?,?,?)');
$ch->execute(['factory-a', 'local', DEMO_LABEL . '1공장 경광등',
json_encode(['gpio_pin' => 17, 'mode' => 'latch', 'hold_s' => 45, 'active_high' => false]),
'high', 0, 0, 0, $now]);
// 메일/웹훅은 enabled=0. 데모 DB 로 실수로 크론을 돌려도 아무 데도 나가지 않는다.
$ch->execute(['factory-a', 'email', DEMO_LABEL . '안전관리자 메일 (사용 안 함)',
json_encode(['to' => ['safety@example.invalid']]), 'critical', 0, 0, 0, $now]);
$ch->execute(['factory-a', 'email', DEMO_LABEL . '공장장 에스컬레이션 (사용 안 함)',
json_encode(['to' => ['plant-manager@example.invalid']]), 'critical', 0, 1, 600, $now]);
$risk = $pdo->prepare('INSERT INTO move_risk_controls (site,event_type,hazard,control,severity_rating,likelihood_rating,reviewed_by,reviewed_at,updated_at)
VALUES (?,?,?,?,?,?,?,?,?)');
foreach ([
['fall', '프레스 진입로 유압유 누유로 인한 미끄럼 전도', '미끄럼 방지 매트 · 일일 누유 점검 · AI 넘어짐 감지', 5, 3],
['pinch', '금형 교체 중 상하 금형 사이 협착', '광전센서 · 방호덮개 · 협착구역 침입 감지', 5, 2],
['zone_restricted', '가동 중 프레스 방호구역 진입', '안전문 인터록 · 제한구역 침입 감지', 4, 3],
['lone_worker', '자재창고 야간 단독 작업 중 사고 시 발견 지연', '2인 1조 편성 · 단독 작업 감지', 4, 2],
['overstay', '도장부스 장시간 체류로 인한 유기용제 노출', '체류 상한 30분 · 국소배기 점검', 3, 3],
] as [$t, $hazard, $control, $sev, $like]) {
$risk->execute(['factory-a', $t, $hazard, $control, $sev, $like, DEMO_ACTOR, $now - 30 * 86400, $now - 30 * 86400]);
}
// 성능 시계열: 24시간치. pi-a2 는 오후부터 스로틀이 걸리며 프레임률이 흘러내린다 —
// "지금 살아 있는가"와 "점점 나빠지는가"의 차이를 한눈에 보여주는 것이 이 화면의 목적이다.
$met = $pdo->prepare('INSERT INTO move_device_metrics (device_id,ts,fps,temp,throttle,queue_pending,cameras_total,cameras_erroring,errors)
VALUES (?,?,?,?,?,?,?,?,?)');
for ($i = 288; $i >= 0; $i--) { // 5분 간격 24시간
$ts = $now - $i * 300;
$phase = 1.0 - $i / 288.0; // 0 = 24시간 전, 1 = 지금
$met->execute([DEMO_PREFIX . 'press', $ts, 24.5 + mt_rand(-4, 4) / 10, 56 + mt_rand(-15, 15) / 10, 0,
mt_rand(0, 2), 2, 0, 0]);
$hot = $phase > 0.55;
$met->execute([DEMO_PREFIX . 'wh', $ts,
$hot ? 24.0 - ($phase - 0.55) * 22 : 24.0 + mt_rand(-3, 3) / 10,
$hot ? 74 + ($phase - 0.55) * 14 : 60 + mt_rand(-15, 15) / 10,
$hot ? 1 : 0, $hot ? mt_rand(0, 40) : 0, 2, 0, $hot ? mt_rand(0, 3) : 0]);
}
$pdo->commit();
say("events: $made · devices: " . count($devices) . " · cameras: " . array_sum(array_map('count', $cameras)));
say('alert channels: 3 (전부 비활성 또는 로컬) · risk controls: 5 · device metrics: 24h');
// ---------------------------------------------------------------- snapshots
if (!$withImgs) {
say('snapshots: skipped (ext-gd 없음 또는 --no-images) — 행은 "무영상" 상태로 표시됩니다.');
exit(0);
}
if (!is_dir($snapshotDir) && !@mkdir($snapshotDir, 0775, true)) {
say("snapshots: {$snapshotDir} 생성 실패 — 건너뜁니다.");
exit(0);
}
/**
* A three-frame evidence timeline per event, for the newest N events only (a demo does not
* need 200 days of jpgs, and a shared-hosting quota does not want them). The worker is drawn
* post-blur — a flat silhouette — because that is what the delivered system actually stores:
* FaceBlurrer runs before anything is written. A demo image with a recognisable face would
* misrepresent the product's privacy behaviour.
*/
function drawFrame(string $camera, int $ts, int $step, string $type): \GdImage
{
$im = imagecreatetruecolor(640, 360);
for ($y = 0; $y < 360; $y++) {
$v = (int)(44 + $y * 0.20);
imagefilledrectangle($im, 0, $y, 640, $y, imagecolorallocate($im, $v, $v + 4, $v + 10));
}
imagefilledrectangle($im, 30, 70, 210, 300, imagecolorallocate($im, 74, 80, 89));
for ($x = 250; $x < 630; $x += 42) {
imagefilledpolygon($im, [$x, 322, $x + 20, 322, $x + 4, 352, $x - 16, 352],
imagecolorallocate($im, 186, 156, 42));
}
// Falling types tilt and descend across the three frames; others just drift.
$falling = in_array($type, ['fall', 'no_motion', 'near_fall'], true);
$drop = $falling ? $step * 30 : 0;
$cx = 380 + $step * 16;
$cy = 150 + $drop;
$skin = imagecolorallocate($im, 222, 224, 228); // flat: face blur already applied
$vest = imagecolorallocate($im, 236, 176, 40);
imagefilledellipse($im, $cx, $cy, 32, 32, $skin);
imagefilledrectangle($im, $cx - 21, $cy + 15, $cx + 21, $cy + max(24, 104 - $drop), $vest);
$box = imagecolorallocate($im, 226, 62, 62);
imagesetthickness($im, 3);
imagerectangle($im, $cx - 44, $cy - 28, $cx + 50, $cy + max(34, 118 - $drop), $box);
imagestring($im, 2, 12, 12, strtoupper($camera) . ' ' . date('Y-m-d H:i:s', $ts), imagecolorallocate($im, 198, 204, 212));
return $im;
}
$snapIns = $pdo->prepare('INSERT INTO move_event_snapshots (event_id,file_uuid,content_hash,created_at) VALUES (?,?,?,?)');
usort($eventIds, fn ($a, $b) => $b['at'] <=> $a['at']);
$withEvidence = array_slice($eventIds, 0, 40);
$files = 0;
$pdo->beginTransaction();
foreach ($withEvidence as $e) {
for ($f = 0; $f < 3; $f++) {
$uuid = bin2hex(random_bytes(16));
$im = drawFrame($e['camera'], $e['at'] - (2 - $f) * 2, $f, $e['type']);
imagejpeg($im, $snapshotDir . '/' . $uuid . '.jpg', 82);
imagedestroy($im);
$snapIns->execute([$e['id'], $uuid, hash('sha256', $uuid), $e['at'] - (2 - $f) * 2]);
$files++;
}
}
$pdo->commit();
say("snapshots: {$files}개 (" . count($withEvidence) . "건에 3프레임씩) -> {$snapshotDir}");
say('완료. 데모 행만 지우려면: --purge');