forked from zakaria/zenai-apc-ngoro
update batch rules
This commit is contained in:
1 parent
31922e1e1f
commit
85e3e07153
12 files changed
+3085
-1648
No files matched your search
+125
-44
@@ -4,6 +4,7 @@ Mirrors frigate-counter SQLite schema + current_batch.json contract.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
@@ -41,6 +42,7 @@ class BatchStore:
|
||||
self.ignore_batch_label_timeout = float(ignore_batch_label_timeout)
|
||||
self.min_object_per_batch = int(min_object_per_batch)
|
||||
self.min_duration_per_batch = int(min_duration_per_batch)
|
||||
self.main_batch_min_count = int(os.getenv("MAIN_BATCH_MIN_COUNT", "700"))
|
||||
self.carry_ids = int(carry_ids)
|
||||
self.log = logger
|
||||
self.on_batch_closed = on_batch_closed
|
||||
@@ -129,22 +131,34 @@ class BatchStore:
|
||||
)
|
||||
st_count = state.get('count', 0)
|
||||
if st_count >= self.min_object_per_batch:
|
||||
is_main = st_count >= self.main_batch_min_count
|
||||
if is_main:
|
||||
bn = str(self.get_next_main_batch_number(state['counting_date']))
|
||||
else:
|
||||
prev_main = self.get_last_main_batch_number(state['counting_date']) or 1
|
||||
letter = self.get_next_sub_batch_letter(state['counting_date'], prev_main)
|
||||
bn = f"{prev_main}{letter}"
|
||||
self._insert_batch(
|
||||
state['counting_date'],
|
||||
state['batch_number'],
|
||||
bn,
|
||||
st_count,
|
||||
state['start_time'],
|
||||
datetime.now().isoformat(),
|
||||
status='VALID',
|
||||
is_main=is_main,
|
||||
)
|
||||
elif st_count > 1:
|
||||
elif st_count >= 1:
|
||||
prev_main = self.get_last_main_batch_number(state['counting_date']) or 1
|
||||
letter = self.get_next_sub_batch_letter(state['counting_date'], prev_main)
|
||||
bn = f"{prev_main}{letter}"
|
||||
self._insert_batch(
|
||||
state['counting_date'],
|
||||
state['batch_number'],
|
||||
bn,
|
||||
st_count,
|
||||
state['start_time'],
|
||||
datetime.now().isoformat(),
|
||||
status='PARTIAL',
|
||||
is_main=False,
|
||||
)
|
||||
self.state_file.unlink(missing_ok=True)
|
||||
return None
|
||||
@@ -165,17 +179,68 @@ class BatchStore:
|
||||
with open(self.state_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(self.current_state, f, indent=2, ensure_ascii=False)
|
||||
|
||||
def get_next_batch_number(self, counting_date):
|
||||
def get_last_main_batch_number(self, counting_date):
|
||||
cur = self.db.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(MAX(batch_number), 0)
|
||||
SELECT batch_number
|
||||
FROM batches
|
||||
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
|
||||
AND count >= ?
|
||||
ORDER BY id DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
(counting_date, self.camera_name, self.object_label),
|
||||
(counting_date, self.camera_name, self.object_label, self.main_batch_min_count),
|
||||
)
|
||||
return cur.fetchone()[0] + 1
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
m = re.match(r"^(\d+)", str(row[0]))
|
||||
return int(m.group(1)) if m else None
|
||||
return None
|
||||
|
||||
def get_next_main_batch_number(self, counting_date):
|
||||
cur = self.db.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(MAX(CAST(batch_number AS INTEGER)), 0)
|
||||
FROM batches
|
||||
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
|
||||
AND count >= ?
|
||||
""",
|
||||
(counting_date, self.camera_name, self.object_label, self.main_batch_min_count),
|
||||
)
|
||||
val = cur.fetchone()[0]
|
||||
return val + 1
|
||||
|
||||
def get_next_sub_batch_letter(self, counting_date, main_batch_num):
|
||||
cur = self.db.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT batch_number
|
||||
FROM batches
|
||||
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
|
||||
AND (batch_number = ? OR batch_number LIKE ?)
|
||||
""",
|
||||
(counting_date, self.camera_name, self.object_label, str(main_batch_num), f"{main_batch_num}%"),
|
||||
)
|
||||
prefix = str(main_batch_num)
|
||||
letters = []
|
||||
for (b,) in cur.fetchall():
|
||||
b_str = str(b)
|
||||
if b_str.startswith(prefix) and len(b_str) > len(prefix):
|
||||
suffix = b_str[len(prefix):]
|
||||
if suffix.isalpha():
|
||||
letters.append(suffix.lower())
|
||||
if not letters:
|
||||
return 'a'
|
||||
letters.sort()
|
||||
last = letters[-1]
|
||||
if last == 'z':
|
||||
return 'aa'
|
||||
return chr(ord(last) + 1)
|
||||
|
||||
def get_next_batch_number(self, counting_date):
|
||||
return self.get_next_main_batch_number(counting_date)
|
||||
|
||||
def start_new_batch(self, counting_date):
|
||||
batch_number = self.get_next_batch_number(counting_date)
|
||||
@@ -304,7 +369,7 @@ class BatchStore:
|
||||
state['count'] < self.min_object_per_batch
|
||||
or duration_seconds < self.min_duration_per_batch
|
||||
)
|
||||
is_partial = not is_valid and state['count'] > 1
|
||||
is_partial = not is_valid and state['count'] >= 1
|
||||
|
||||
if not is_valid and not is_partial:
|
||||
self.current_state = None
|
||||
@@ -334,6 +399,24 @@ class BatchStore:
|
||||
self.log(f'on_batch_closed error: {exc}')
|
||||
return False
|
||||
|
||||
# Determine standalone main batch vs sub batch merged into preceding main batch
|
||||
prev_main = self.get_last_main_batch_number(state['counting_date'])
|
||||
|
||||
# Rule: Sub-batch does not apply to the first batch of the day
|
||||
if prev_main is None:
|
||||
is_main = True
|
||||
final_batch_number = "1"
|
||||
elif state['count'] >= self.main_batch_min_count:
|
||||
is_main = True
|
||||
final_batch_number = str(self.get_next_main_batch_number(state['counting_date']))
|
||||
else:
|
||||
is_main = False
|
||||
letter = self.get_next_sub_batch_letter(state['counting_date'], prev_main)
|
||||
final_batch_number = f"{prev_main}{letter}"
|
||||
|
||||
state['batch_number'] = final_batch_number
|
||||
batch_id = f"{state['counting_date']}-{final_batch_number}"
|
||||
|
||||
status = 'VALID' if is_valid else 'PARTIAL'
|
||||
end_time = end_time_obj.isoformat()
|
||||
try:
|
||||
@@ -344,17 +427,19 @@ class BatchStore:
|
||||
state['start_time'],
|
||||
end_time,
|
||||
status=status,
|
||||
is_main=is_main,
|
||||
)
|
||||
cps = state['count'] / duration_seconds if duration_seconds > 0 else 0
|
||||
kind = "MAIN" if is_main else "CHILD"
|
||||
if is_valid:
|
||||
self.log(
|
||||
f'Batch #{state["batch_number"]} ended | count={state["count"]} | '
|
||||
f'Batch #{state["batch_number"]} ended ({kind}) | count={state["count"]} | '
|
||||
f'duration={duration_seconds:.0f}s | cps={cps:.3f} | closed_by={closed_by}'
|
||||
)
|
||||
else:
|
||||
self.log(
|
||||
f'Batch #{state["batch_number"]} ended (PARTIAL) | count={state["count"]} | '
|
||||
f'duration={duration_seconds:.0f}s | cps={cps:.3f} | closed_by={closed_by} (excluded from daily KPIs)'
|
||||
f'Batch #{state["batch_number"]} ended ({kind}, PARTIAL) | count={state["count"]} | '
|
||||
f'duration={duration_seconds:.0f}s | cps={cps:.3f} | closed_by={closed_by}'
|
||||
)
|
||||
except Exception as exc:
|
||||
self.log(f'Failed to persist batch: {exc}')
|
||||
@@ -370,6 +455,7 @@ class BatchStore:
|
||||
"ok": True,
|
||||
"status": status,
|
||||
"is_partial": is_partial,
|
||||
"is_main": is_main,
|
||||
"batch_id": batch_id,
|
||||
"counting_date": state["counting_date"],
|
||||
"batch_number": state["batch_number"],
|
||||
@@ -436,7 +522,7 @@ class BatchStore:
|
||||
self.db.commit()
|
||||
return cur.rowcount > 0
|
||||
|
||||
def _insert_batch(self, counting_date, batch_number, count, start_time, end_time, status='VALID'):
|
||||
def _insert_batch(self, counting_date, batch_number, count, start_time, end_time, status='VALID', is_main=True):
|
||||
cur = self.db.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
@@ -444,41 +530,36 @@ class BatchStore:
|
||||
(counting_date, batch_number, camera_name, object_label, count, start_time, end_time, status)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(counting_date, batch_number, self.camera_name, self.object_label, count, start_time, end_time, status),
|
||||
(counting_date, str(batch_number), self.camera_name, self.object_label, count, start_time, end_time, status),
|
||||
)
|
||||
if status == 'VALID':
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO daily_summaries
|
||||
(counting_date, camera_name, object_label, total_count, total_batches)
|
||||
VALUES (?, ?, ?, ?, 1)
|
||||
ON CONFLICT(counting_date, camera_name, object_label)
|
||||
DO UPDATE SET
|
||||
total_count = total_count + excluded.total_count,
|
||||
total_batches = total_batches + excluded.total_batches,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
""",
|
||||
(counting_date, self.camera_name, self.object_label, count),
|
||||
)
|
||||
self.db.commit()
|
||||
inc_batches = 1 if is_main else 0
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO daily_summaries
|
||||
(counting_date, camera_name, object_label, total_count, total_batches)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(counting_date, camera_name, object_label)
|
||||
DO UPDATE SET
|
||||
total_count = total_count + excluded.total_count,
|
||||
total_batches = total_batches + excluded.total_batches,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
""",
|
||||
(counting_date, self.camera_name, self.object_label, count, inc_batches),
|
||||
)
|
||||
self.db.commit()
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT total_count, total_batches
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
|
||||
""",
|
||||
(counting_date, self.camera_name, self.object_label),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
self.log(
|
||||
f'Daily totals for {counting_date}: {row[0]} objects across {row[1]} batch(es)'
|
||||
)
|
||||
else:
|
||||
self.db.commit()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT total_count, total_batches
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ? AND camera_name = ? AND object_label = ?
|
||||
""",
|
||||
(counting_date, self.camera_name, self.object_label),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
self.log(
|
||||
f'Batch #{batch_number} saved as PARTIAL ({count} objects) - excluded from daily_summaries'
|
||||
f'Daily totals for {counting_date}: {row[0]} objects across {row[1]} main batch(es)'
|
||||
)
|
||||
|
||||
def cutoff_watcher_loop(self):
|
||||
|
||||
+677
-175
File diff suppressed because it is too large.
Load diff
Whitespace-only changes.
@@ -24,7 +24,7 @@ PUBLIC_BASE = os.getenv(
|
||||
os.getenv("MOTIONEYE_INGEST_URL", f"http://127.0.0.1:{PORT}"),
|
||||
).rstrip("/")
|
||||
|
||||
BATCH_ID_RE = re.compile(r"^\d{4}-\d{2}-\d{2}-\d+$")
|
||||
BATCH_ID_RE = re.compile(r"^\d{4}-\d{2}-\d{2}-\d+[a-zA-Z]?$")
|
||||
|
||||
app = Flask(__name__)
|
||||
MEDIA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
Whitespace-only changes.
@@ -86,7 +86,7 @@ LIVE_JPEG_QUALITY = int(os.getenv("RECOUNT_LIVE_JPEG_QUALITY", "60"))
|
||||
PLAYBACK_SPEED = float(os.getenv("RECOUNT_PLAYBACK_SPEED", "0"))
|
||||
RECOUNT_START_COUNT = int(os.getenv("RECOUNT_START_COUNT", "1"))
|
||||
|
||||
BATCH_ID_RE = re.compile(r"^\d{4}-\d{2}-\d{2}-\d+$")
|
||||
BATCH_ID_RE = re.compile(r"^\d{4}-\d{2}-\d{2}-\d+[a-zA-Z]?$")
|
||||
|
||||
_lock = threading.Lock()
|
||||
_cancel = threading.Event()
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
import re
|
||||
import sqlite3
|
||||
|
||||
BATCH_ID_RE = re.compile(r"^(\d{4}-\d{2}-\d{2})-\d+$")
|
||||
BATCH_ID_RE = re.compile(r"^(\d{4}-\d{2}-\d{2})-\d+[a-zA-Z]?$")
|
||||
|
||||
|
||||
def active_counting_dates(conn: sqlite3.Connection, limit: int = 3, table: str = "batches") -> list[str]:
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import sys
|
||||
import os
|
||||
sys.path.insert(0, "/opt/apc-ngoro")
|
||||
|
||||
import re
|
||||
import requests
|
||||
|
||||
# 1. Test BATCH_ID_RE across modules
|
||||
from recount_engine.app import BATCH_ID_RE as RECOUNT_RE
|
||||
from retention_utils import BATCH_ID_RE as RETENTION_RE
|
||||
from motioneye_ingest.app import BATCH_ID_RE as INGEST_RE
|
||||
from counter_dashboard import _parse_batch_id, _lookup_batch, _resolve_remote_batch_id
|
||||
|
||||
print("Testing BATCH_ID_RE in recount_engine...")
|
||||
assert RECOUNT_RE.match("2026-11-02-15a"), "recount_engine failed on 15a"
|
||||
assert RECOUNT_RE.match("2026-11-02-15"), "recount_engine failed on 15"
|
||||
assert RECOUNT_RE.match("2026-11-02-1b"), "recount_engine failed on 1b"
|
||||
print("recount_engine BATCH_ID_RE: OK")
|
||||
|
||||
print("Testing BATCH_ID_RE in retention_utils...")
|
||||
assert RETENTION_RE.match("2026-11-02-15a"), "retention_utils failed on 15a"
|
||||
assert RETENTION_RE.match("2026-11-02-15"), "retention_utils failed on 15"
|
||||
print("retention_utils BATCH_ID_RE: OK")
|
||||
|
||||
print("Testing BATCH_ID_RE in motioneye_ingest...")
|
||||
assert INGEST_RE.match("2026-11-02-15a"), "motioneye_ingest failed on 15a"
|
||||
assert INGEST_RE.match("2026-11-02-15"), "motioneye_ingest failed on 15"
|
||||
print("motioneye_ingest BATCH_ID_RE: OK")
|
||||
|
||||
# 2. Test _parse_batch_id and _lookup_batch for Batch 15a
|
||||
date_part, num_part = _parse_batch_id("2026-11-02-15a")
|
||||
assert date_part == "2026-11-02", f"Expected 2026-11-02, got {date_part}"
|
||||
assert num_part == "15a", f"Expected 15a, got {num_part}"
|
||||
print(f"_parse_batch_id('2026-11-02-15a'): OK ({date_part}, {num_part})")
|
||||
|
||||
batch = _lookup_batch("2026-11-02", "15a")
|
||||
assert batch is not None, "Batch 15a not found in DB!"
|
||||
assert batch["count"] == 3, f"Expected 3 chickens in batch 15a, got {batch['count']}"
|
||||
print(f"_lookup_batch('2026-11-02', '15a'): OK (id={batch['id']}, count={batch['count']}, video_url={batch['video_url']})")
|
||||
|
||||
# 3. Test _resolve_remote_batch_id
|
||||
remote_bid = _resolve_remote_batch_id("2026-11-02-15a", batch)
|
||||
print(f"_resolve_remote_batch_id('2026-11-02-15a'): {remote_bid}")
|
||||
assert re.match(r"^\d{4}-\d{2}-\d{2}-\d+$", remote_bid), f"Remote bid {remote_bid} is not purely numeric!"
|
||||
assert remote_bid == "2026-11-02-16", f"Expected 2026-11-02-16 from video URL, got {remote_bid}"
|
||||
|
||||
# 4. Test fallback without video_url
|
||||
fallback_bid = _resolve_remote_batch_id("2026-11-02-15a", None)
|
||||
print(f"Fallback without batch row: {fallback_bid}")
|
||||
assert re.match(r"^\d{4}-\d{2}-\d{2}-\d+$", fallback_bid), f"Fallback bid {fallback_bid} not numeric!"
|
||||
assert fallback_bid == "2026-11-02-1501", f"Expected 2026-11-02-1501, got {fallback_bid}"
|
||||
|
||||
# 5. Test NanoPi 2 acceptance with remote_bid
|
||||
print(f"Testing NanoPi 2 start endpoint with remote_bid={remote_bid}...")
|
||||
url = "http://192.168.192.16:8765/api/v1/recount/start"
|
||||
payload = {
|
||||
"batch_id": remote_bid,
|
||||
"video_url": batch["video_url"],
|
||||
"original_count": batch["count"],
|
||||
}
|
||||
resp = requests.post(url, json=payload, timeout=10)
|
||||
print(f"NanoPi 2 response: HTTP {resp.status_code} -> {resp.text}")
|
||||
assert resp.status_code in (200, 201, 409), f"Unexpected status: {resp.status_code}"
|
||||
data = resp.json()
|
||||
if resp.status_code in (200, 201):
|
||||
assert data.get("success") is True
|
||||
print("NanoPi 2 successfully accepted recount job for Batch 15a video!")
|
||||
elif resp.status_code == 409:
|
||||
print("NanoPi 2 returned 409 (another job currently running or adopting), which is valid handling.")
|
||||
|
||||
print("\nALL AUTOMATED TESTS PASSED!")
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Renumber all child batches (< 700 count) across all dates in apc_ngoro.db:
|
||||
- Rule 1: Sub-batch does not apply to the first batch of any day (always Batch 1).
|
||||
- Rule 2: Sub-batches receive explicit letter suffixes (1a, 1b, 2a, etc.).
|
||||
- Subsequent main batches are sequentially numbered (1, 2, 3, ...).
|
||||
- Reconciles daily_summaries.total_batches for all dates.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
import sys
|
||||
|
||||
DB_PATH = os.getenv("DB_PATH", "/opt/apc-ngoro/apc_ngoro.db")
|
||||
THRESHOLD = int(os.getenv("MAIN_BATCH_MIN_COUNT", "700"))
|
||||
|
||||
def relabel_date(cur, target_date):
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, batch_number, count, status
|
||||
FROM batches
|
||||
WHERE counting_date = ?
|
||||
ORDER BY start_time ASC, id ASC
|
||||
""",
|
||||
(target_date,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
if not rows:
|
||||
return 0, 0
|
||||
|
||||
main_counter = 0
|
||||
prev_main = None
|
||||
child_letter = 'a'
|
||||
planned = []
|
||||
|
||||
for idx, (row_id, b_num, count, status) in enumerate(rows):
|
||||
b_str = str(b_num).strip()
|
||||
has_letter = bool(re.search(r"[a-zA-Z]", b_str))
|
||||
|
||||
# Rule 1: Sub-batch does not apply to the first batch of the day
|
||||
if idx == 0:
|
||||
is_child = False
|
||||
else:
|
||||
is_child = has_letter or (count < THRESHOLD)
|
||||
|
||||
if not is_child:
|
||||
main_counter += 1
|
||||
prev_main = main_counter
|
||||
child_letter = 'a'
|
||||
planned.append((row_id, b_num, str(main_counter), count, status, "MAIN"))
|
||||
else:
|
||||
assigned_main = prev_main if prev_main is not None else 1
|
||||
label = f"{assigned_main}{child_letter}"
|
||||
child_letter = chr(ord(child_letter) + 1)
|
||||
planned.append((row_id, b_num, label, count, status, "SUB"))
|
||||
|
||||
# Phase 1: Temporary unique placeholder to prevent SQLite UNIQUE constraint collision
|
||||
for row_id, old_bn, new_bn, count, status, kind in planned:
|
||||
cur.execute(
|
||||
"UPDATE batches SET batch_number = ? WHERE id = ?",
|
||||
(f"tmp_{row_id}", row_id),
|
||||
)
|
||||
|
||||
# Phase 2: Assign final planned batch numbers
|
||||
for row_id, old_bn, new_bn, count, status, kind in planned:
|
||||
cur.execute(
|
||||
"UPDATE batches SET batch_number = ? WHERE id = ?",
|
||||
(new_bn, row_id),
|
||||
)
|
||||
|
||||
# Phase 3: Reconcile daily_summaries
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE daily_summaries
|
||||
SET total_count = (
|
||||
SELECT COALESCE(SUM(count), 0) FROM batches
|
||||
WHERE counting_date = ? AND status IN ('VALID', 'PARTIAL', 'PARSIAL')
|
||||
),
|
||||
total_batches = ?,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE counting_date = ?
|
||||
""",
|
||||
(target_date, main_counter, target_date),
|
||||
)
|
||||
return len(planned), main_counter
|
||||
|
||||
def main():
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
cur = conn.cursor()
|
||||
try:
|
||||
cur.execute("SELECT DISTINCT counting_date FROM batches ORDER BY counting_date ASC")
|
||||
dates = [r[0] for r in cur.fetchall()]
|
||||
print(f"Starting relabeling across {len(dates)} dates (THRESHOLD={THRESHOLD})...")
|
||||
|
||||
total_batches_processed = 0
|
||||
for d in dates:
|
||||
batch_count, main_count = relabel_date(cur, d)
|
||||
total_batches_processed += batch_count
|
||||
print(f"[{d}] Processed {batch_count} batches -> {main_count} Main batches")
|
||||
|
||||
conn.commit()
|
||||
print(f"\nSuccessfully migrated {total_batches_processed} batches across {len(dates)} dates!")
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
print(f"ERROR: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Renumber child batches (< 700 count) with letter suffixes (e.g. 15a)
|
||||
and re-sequence subsequent main batches sequentially.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
import sys
|
||||
|
||||
DB_PATH = os.getenv("DB_PATH", "/opt/apc-ngoro/apc_ngoro.db")
|
||||
THRESHOLD = int(os.getenv("MAIN_BATCH_MIN_COUNT", "700"))
|
||||
|
||||
def relabel_date(conn, target_date):
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, batch_number, count, status
|
||||
FROM batches
|
||||
WHERE counting_date = ?
|
||||
ORDER BY id ASC
|
||||
""",
|
||||
(target_date,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
if not rows:
|
||||
print(f"No batches found for {target_date}")
|
||||
return
|
||||
|
||||
main_counter = 0
|
||||
prev_main = None
|
||||
child_letter = 'a'
|
||||
planned = []
|
||||
|
||||
for row_id, b_num, count, status in rows:
|
||||
b_str = str(b_num).strip()
|
||||
has_letter = bool(re.search(r"[a-zA-Z]", b_str))
|
||||
is_child = has_letter or (count < THRESHOLD)
|
||||
|
||||
if not is_child:
|
||||
main_counter += 1
|
||||
prev_main = main_counter
|
||||
child_letter = 'a'
|
||||
planned.append((row_id, b_num, str(main_counter), count, status, "MAIN"))
|
||||
else:
|
||||
assigned_main = prev_main if prev_main is not None else 1
|
||||
label = f"{assigned_main}{child_letter}"
|
||||
child_letter = chr(ord(child_letter) + 1)
|
||||
planned.append((row_id, b_num, label, count, status, "CHILD"))
|
||||
|
||||
# To avoid unique constraint collisions during batch_number updates:
|
||||
# First assign all rows to a temporary unique placeholder
|
||||
for row_id, old_bn, new_bn, count, status, kind in planned:
|
||||
cur.execute(
|
||||
"UPDATE batches SET batch_number = ? WHERE id = ?",
|
||||
(f"tmp_{row_id}", row_id),
|
||||
)
|
||||
|
||||
# Now assign the final planned batch numbers
|
||||
for row_id, old_bn, new_bn, count, status, kind in planned:
|
||||
cur.execute(
|
||||
"UPDATE batches SET batch_number = ? WHERE id = ?",
|
||||
(new_bn, row_id),
|
||||
)
|
||||
print(f"[{target_date}] ID {row_id}: #{old_bn} -> #{new_bn} ({count} ekor, {status}, {kind})")
|
||||
|
||||
# Update daily_summaries for this date
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE daily_summaries
|
||||
SET total_count = (
|
||||
SELECT COALESCE(SUM(count), 0) FROM batches
|
||||
WHERE counting_date = ? AND status IN ('VALID', 'PARTIAL', 'PARSIAL')
|
||||
),
|
||||
total_batches = ?,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE counting_date = ?
|
||||
""",
|
||||
(target_date, main_counter, target_date),
|
||||
)
|
||||
conn.commit()
|
||||
print(f"Updated {target_date}: {len(planned)} batches re-labeled, total main batches = {main_counter}")
|
||||
|
||||
def main():
|
||||
date_arg = sys.argv[1] if len(sys.argv) > 1 else "2026-11-02"
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
try:
|
||||
relabel_date(conn, date_arg)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -512,6 +512,18 @@
|
||||
color: var(--green); font-family: var(--mono); font-size: 11px; font-weight: 700;
|
||||
}
|
||||
.badge-complete .bdot { width: 8px; height: 8px; border-radius: 50%; background: var(--green); }
|
||||
.status-badge {
|
||||
padding: 2px 6px; border-radius: 6px;
|
||||
font-size: 10px; font-weight: 700; white-space: nowrap;
|
||||
background: var(--green-bg); border: 1px solid var(--green); color: var(--green);
|
||||
display: inline-block;
|
||||
}
|
||||
.status-badge.warn {
|
||||
background: var(--yellow-bg); border-color: var(--yellow); color: var(--yellow);
|
||||
}
|
||||
.status-badge.info {
|
||||
background: var(--blue-bg); border-color: var(--blue); color: var(--blue-btn);
|
||||
}
|
||||
.link-detail {
|
||||
color: var(--text); font-size: 11px; font-weight: 600; cursor: pointer;
|
||||
min-height: var(--touch-min); display: inline-flex; align-items: center;
|
||||
@@ -628,12 +640,13 @@
|
||||
letter-spacing: 0.02em;
|
||||
background: rgba(0,0,0,0.18);
|
||||
}
|
||||
.modal-table th:nth-child(1), .modal-table td:nth-child(1) { width: 14%; }
|
||||
.modal-table th:nth-child(2), .modal-table td:nth-child(2) { width: 16%; }
|
||||
.modal-table th:nth-child(3), .modal-table td:nth-child(3),
|
||||
.modal-table th:nth-child(4), .modal-table td:nth-child(4) { width: 18%; }
|
||||
.modal-table th:nth-child(1), .modal-table td:nth-child(1) { width: 13%; }
|
||||
.modal-table th:nth-child(2), .modal-table td:nth-child(2) { width: 13%; }
|
||||
.modal-table th:nth-child(3), .modal-table td:nth-child(3) { width: 14%; }
|
||||
.modal-table th:nth-child(4), .modal-table td:nth-child(4),
|
||||
.modal-table th:nth-child(5), .modal-table td:nth-child(5) { width: 16%; }
|
||||
.modal-table th:nth-child(6), .modal-table td:nth-child(6) { width: 18%; }
|
||||
.modal-table th:nth-child(6), .modal-table td:nth-child(6) { width: 14%; }
|
||||
.modal-table th:nth-child(7), .modal-table td:nth-child(7) { width: 14%; }
|
||||
.modal-table .mono { font-family: var(--mono); font-weight: 600; }
|
||||
.modal-aside {
|
||||
border: 1px solid var(--border);
|
||||
@@ -972,6 +985,7 @@
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Batch #</th>
|
||||
<th>Tipe</th>
|
||||
<th>Total</th>
|
||||
<th>Mulai</th>
|
||||
<th>Selesai</th>
|
||||
@@ -1293,7 +1307,7 @@ async function loadRecentBatches() {
|
||||
container.innerHTML = batches.map(b => `
|
||||
<div class="recent-card">
|
||||
<div class="recent-head">
|
||||
<span class="recent-batch">B-${String(b.batch_number).padStart(4,'0')}</span>
|
||||
<span class="recent-batch">B-${String(b.batch_number).padStart(4,'0')}${b.is_child ? ' <span class="status-badge warn" style="font-size:9px;padding:1px 5px;margin-left:4px;">SUB</span>' : ''}</span>
|
||||
<span class="recent-date">${formatDateID(b.date)}</span>
|
||||
</div>
|
||||
<div class="recent-count">${b.count.toLocaleString('id-ID')}</div>
|
||||
@@ -1461,20 +1475,43 @@ async function showDayDetail(date) {
|
||||
document.getElementById('modal-avg').textContent = data.avg_duration_minutes;
|
||||
|
||||
const batches = data.batches || [];
|
||||
document.getElementById('modal-table-body').innerHTML = batches.length
|
||||
? batches.map(b => {
|
||||
const pct = total > 0 ? (b.count / total) * 100 : 0;
|
||||
return `
|
||||
const totalDuration = batches.reduce((acc, b) => acc + (b.duration_minutes || 0), 0);
|
||||
const mainCount = batches.filter(b => !b.is_child).length;
|
||||
const subCount = batches.filter(b => b.is_child).length;
|
||||
|
||||
let tableHtml = '';
|
||||
if (batches.length) {
|
||||
tableHtml = batches.map(b => {
|
||||
const pct = total > 0 ? (b.count / total) * 100 : 0;
|
||||
const isChild = b.is_child || false;
|
||||
const badgeType = b.batch_type || (isChild ? 'Sub' : 'Main');
|
||||
const badgeClass = isChild ? 'status-badge warn' : 'status-badge info';
|
||||
return `
|
||||
<tr>
|
||||
<td class="mono">#${b.batch_number}</td>
|
||||
<td><span class="${badgeClass}" style="font-size: 10px; padding: 2px 6px;">${badgeType}</span></td>
|
||||
<td class="mono">${b.count.toLocaleString('id-ID')}</td>
|
||||
<td>${formatTime(b.start_time)}</td>
|
||||
<td>${formatTime(b.end_time)}</td>
|
||||
<td>${b.duration_minutes} menit</td>
|
||||
<td class="mono">${pct.toFixed(1)}%</td>
|
||||
</tr>`;
|
||||
}).join('')
|
||||
: `<tr><td colspan="6" class="modal-empty">Tidak ada batch pada tanggal ini</td></tr>`;
|
||||
}).join('');
|
||||
|
||||
tableHtml += `
|
||||
<tr style="background: rgba(22,130,178,0.12); font-weight: 700; border-top: 2px solid var(--border-accent);">
|
||||
<td class="mono" style="font-weight:700;">TOTAL</td>
|
||||
<td><span class="status-badge info" style="font-size: 10px; padding: 2px 6px;">${mainCount} Main, ${subCount} Sub</span></td>
|
||||
<td class="mono" style="font-weight:700; color: #38bdf8;">${total.toLocaleString('id-ID')}</td>
|
||||
<td style="font-size:10px; color:var(--text-muted);">${batches[0] ? formatTime(batches[0].start_time) : '--'}</td>
|
||||
<td style="font-size:10px; color:var(--text-muted);">${batches[batches.length - 1] ? formatTime(batches[batches.length - 1].end_time) : '--'}</td>
|
||||
<td style="font-weight:700;">${Math.round(totalDuration)} menit</td>
|
||||
<td class="mono" style="font-weight:700;">100%</td>
|
||||
</tr>`;
|
||||
} else {
|
||||
tableHtml = `<tr><td colspan="7" class="modal-empty">Tidak ada batch pada tanggal ini</td></tr>`;
|
||||
}
|
||||
document.getElementById('modal-table-body').innerHTML = tableHtml;
|
||||
|
||||
document.getElementById('modal-share-list').innerHTML = batches.length
|
||||
? batches.map(b => {
|
||||
@@ -1482,7 +1519,7 @@ async function showDayDetail(date) {
|
||||
return `
|
||||
<div class="modal-share-row">
|
||||
<div class="modal-share-meta">
|
||||
<span class="label">Batch #${b.batch_number}</span>
|
||||
<span class="label">Batch #${b.batch_number}${b.is_child ? ' (Sub)' : ''}</span>
|
||||
<span class="pct">${b.count.toLocaleString('id-ID')} · ${pct.toFixed(1)}%</span>
|
||||
</div>
|
||||
<div class="modal-share-bar"><div class="modal-share-fill" style="width:${pct.toFixed(1)}%"></div></div>
|
||||
|
||||
+1955
-1413
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user