File size: 2,649 Bytes
e176226
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Lógica pura (sin DOM): asignación de detecciones a zonas, decisión de estado y suavizado temporal.
export const STATES = {
  libre: { label: 'Libre', color: '#16a34a' },
  ocupada: { label: 'Ocupada', color: '#2563eb' },
  limpiar: { label: 'Necesita limpieza', color: '#dc2626' },
};

export function clamp01(v) { return Math.min(1, Math.max(0, v)); }

export function normalizeBox([x, y, w, h]) {
  // admite w/h negativos (arrastre hacia arriba/izquierda)
  const x1 = clamp01(Math.min(x, x + w)), y1 = clamp01(Math.min(y, y + h));
  const x2 = clamp01(Math.max(x, x + w)), y2 = clamp01(Math.max(y, y + h));
  return [x1, y1, x2 - x1, y2 - y1];
}

export function centerInZone(det, box, W, H) {
  const cx = (det.box.xmin + det.box.xmax) / 2 / W;
  const cy = (det.box.ymin + det.box.ymax) / 2 / H;
  const [x, y, w, h] = box;
  return cx >= x && cx <= x + w && cy >= y && cy <= y + h;
}

// Para cada zona: puntuación máxima de «persona» y de «vajilla» entre detecciones cuyo centro cae dentro.
export function scoreZones(detections, zones, W, H, personLabels, dishLabels) {
  const P = new Set(personLabels), D = new Set(dishLabels);
  return zones.map((z) => {
    let person = 0, dish = 0; const dishes = [];
    for (const d of detections) {
      if (!centerInZone(d, z.box, W, H)) continue;
      if (P.has(d.label)) person = Math.max(person, d.score);
      else if (D.has(d.label)) { dish = Math.max(dish, d.score); dishes.push(d); }
    }
    return { name: z.name, person, dish, dishes };
  });
}

// Regla: hay alguien -> ocupada; nadie pero vajilla/restos -> limpiar; si no -> libre.
export function decide({ person, dish }, th) {
  if (person >= th.person) return 'ocupada';
  if (dish >= th.dish) return 'limpiar';
  return 'libre';
}

// Suavizado para vídeo: el estado mostrado cambia sólo tras `k` lecturas seguidas iguales.
export function smooth(prev, raw, k = 2) {
  if (!prev) return { shown: raw, candidate: raw, streak: k, changed: true };
  if (raw === prev.shown) return { ...prev, candidate: raw, streak: k, changed: false };
  const streak = raw === prev.candidate ? prev.streak + 1 : 1;
  if (streak >= k) return { shown: raw, candidate: raw, streak, changed: true };
  return { ...prev, candidate: raw, streak, changed: false };
}

export function sampleTimes(duration, interval, maxFrames) {
  const out = [];
  for (let t = 0; t < duration - 1e-6 && out.length < maxFrames; t += interval) out.push(+t.toFixed(3));
  return out;
}

export function fitSize(w, h, maxSide) {
  const s = Math.min(1, maxSide / Math.max(w, h));
  return [Math.max(1, Math.round(w * s)), Math.max(1, Math.round(h * s))];
}