Files
nano-fcp/batch_store.py

643 lines
24 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Production batch persistence for the edge counter.
Persists counted objects grouped into batches (closed by idle timeout or cutoff).
"""
import json
import sqlite3
import threading
import time
from datetime import datetime, timedelta
from pathlib import Path
def ensure_batch_schema(conn):
"""Create batch tables and migrate legacy rows to separate class counters."""
cur = conn.cursor()
cur.execute(
"""
CREATE TABLE IF NOT EXISTS batches (
id INTEGER PRIMARY KEY AUTOINCREMENT,
counting_date TEXT NOT NULL,
batch_number INTEGER NOT NULL,
camera_name TEXT NOT NULL,
object_label TEXT NOT NULL,
count INTEGER NOT NULL,
sack_count INTEGER NOT NULL DEFAULT 0,
box_count INTEGER NOT NULL DEFAULT 0,
start_time TEXT NOT NULL,
end_time TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(counting_date, batch_number, camera_name, object_label)
)
"""
)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS daily_summaries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
counting_date TEXT NOT NULL,
camera_name TEXT NOT NULL,
object_label TEXT NOT NULL,
total_count INTEGER NOT NULL DEFAULT 0,
total_batches INTEGER NOT NULL DEFAULT 0,
sack_count INTEGER NOT NULL DEFAULT 0,
box_count INTEGER NOT NULL DEFAULT 0,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(counting_date, camera_name, object_label)
)
"""
)
for table in ("batches", "daily_summaries"):
columns = {row[1] for row in cur.execute(f"PRAGMA table_info({table})")}
for column in ("sack_count", "box_count"):
if column not in columns:
cur.execute(
f"ALTER TABLE {table} ADD COLUMN {column} INTEGER NOT NULL DEFAULT 0"
)
batch_columns = {row[1] for row in cur.execute("PRAGMA table_info(batches)")}
for col_name, col_type in (
("source", "TEXT"),
("fcp_batch_number", "INTEGER"),
("plate", "TEXT"),
("do_numbers", "TEXT"),
("expected_sack", "INTEGER"),
("expected_box", "INTEGER"),
):
if col_name not in batch_columns:
cur.execute(f"ALTER TABLE batches ADD COLUMN {col_name} {col_type}")
cur.execute(
"""
UPDATE batches
SET sack_count = count
WHERE object_label = 'sack' AND sack_count = 0 AND count > 0
"""
)
cur.execute(
"""
UPDATE batches
SET box_count = count
WHERE object_label = 'box' AND box_count = 0 AND count > 0
"""
)
cur.execute(
"""
UPDATE batches
SET object_label = 'sack'
WHERE object_label = 'mixed' AND sack_count > 0 AND box_count = 0
"""
)
cur.execute(
"""
UPDATE batches
SET object_label = 'box'
WHERE object_label = 'mixed' AND box_count > 0 AND sack_count = 0
"""
)
cur.execute(
"""
UPDATE daily_summaries
SET sack_count = total_count
WHERE object_label = 'sack' AND sack_count = 0 AND total_count > 0
"""
)
cur.execute(
"""
UPDATE daily_summaries
SET box_count = total_count
WHERE object_label = 'box' AND box_count = 0 AND total_count > 0
"""
)
conn.commit()
class BatchStore:
def __init__(
self,
db_path,
state_file,
camera_name,
object_label='sack',
cutoff_time='06:00',
batch_timeout=30.0,
min_object_per_batch=60,
min_duration_per_batch=60,
carry_ids=50,
batch_mode='manual',
logger=print,
):
self.db_path = db_path
self.state_file = Path(state_file)
self.camera_name = camera_name
self.object_label = object_label
self.cutoff_time_str = cutoff_time
datetime.strptime(cutoff_time, '%H:%M')
self.batch_timeout = float(batch_timeout)
self.min_object_per_batch = int(min_object_per_batch)
self.min_duration_per_batch = int(min_duration_per_batch)
self.carry_ids = int(carry_ids)
self.batch_mode = str(batch_mode).strip().lower() if batch_mode else 'manual'
self.log = logger
self.state_lock = threading.Lock()
self.batch_timer = None
self.truck_present = False
self.previous_state = None
self.shutdown_event = threading.Event()
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
self.state_file.parent.mkdir(parents=True, exist_ok=True)
self.db = sqlite3.connect(db_path, check_same_thread=False)
self._init_db()
self.current_state = self._load_state()
self.previous_state = self.current_state
def _init_db(self):
ensure_batch_schema(self.db)
def get_counting_date(self, dt=None):
if dt is None:
dt = datetime.now()
cutoff = datetime.strptime(self.cutoff_time_str, '%H:%M').time()
if cutoff.hour < 12:
if dt.time() < cutoff:
return (dt.date() - timedelta(days=1)).isoformat()
return dt.date().isoformat()
if dt.time() < cutoff:
return dt.date().isoformat()
return (dt.date() + timedelta(days=1)).isoformat()
def _normalize_batch_label(self, label=None):
raw = str(label or '').strip().lower()
if raw in ('mixed', 'all', 'both'):
return 'mixed'
if raw in ('box', '1'):
return 'box'
if raw in ('sack', '0'):
return 'sack'
default_raw = str(self.object_label or 'sack').split(',')[0].strip().lower()
return 'box' if default_raw == 'box' else 'sack'
def _normalize_item_label(self, label=None):
raw = str(label or 'sack').strip().lower()
return 'box' if raw == 'box' else 'sack'
def _load_state(self):
if not self.state_file.exists():
return None
try:
with open(self.state_file, 'r', encoding='utf-8') as f:
state = json.load(f)
legacy_label = self._normalize_batch_label(state.get('object_label'))
if 'sack_count' not in state:
state['sack_count'] = (
int(state.get('count', 0))
if legacy_label in ('sack', 'mixed')
else 0
)
if 'box_count' not in state:
state['box_count'] = (
int(state.get('count', 0)) if legacy_label == 'box' else 0
)
state['sack_count'] = int(state.get('sack_count', 0))
state['box_count'] = int(state.get('box_count', 0))
state['count'] = state['sack_count'] + state['box_count']
state['object_label'] = 'mixed'
legacy_ids = state.get('counted_event_ids', [])
state['counted_event_ids'] = [
f"{legacy_label}:{event_id}" if ':' not in str(event_id) else event_id
for event_id in legacy_ids
]
current_date = self.get_counting_date()
if state.get('counting_date') != current_date:
self.log(
f"State file belongs to previous counting day ({state.get('counting_date')}). "
'Finalizing before fresh start.'
)
self._insert_batch(
state['counting_date'],
state['batch_number'],
state['count'],
state['start_time'],
datetime.now().isoformat(),
object_label='mixed',
sack_count=state['sack_count'],
box_count=state['box_count'],
metadata=state,
)
self.state_file.unlink(missing_ok=True)
return None
self.log(
f"Resumed batch #{state['batch_number']} ({state['object_label']}) from {state['start_time']} "
f"with count={state['count']}"
)
if self.batch_mode != 'manual':
self._reset_batch_timer()
return state
except Exception as exc:
self.log(f'Failed to load state file: {exc}')
return None
def save_state(self):
if self.current_state is None:
self.state_file.unlink(missing_ok=True)
return
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):
cur = self.db.cursor()
cur.execute(
"""
SELECT COALESCE(MAX(batch_number), 0)
FROM batches
WHERE counting_date = ? AND camera_name = ?
""",
(counting_date, self.camera_name),
)
return cur.fetchone()[0] + 1
def start_new_batch(self, counting_date=None, object_label=None):
with self.state_lock:
return self._start_new_batch_locked(
counting_date=counting_date, object_label=object_label
)
def _start_new_batch_locked(self, counting_date=None, object_label=None):
if self.current_state is not None:
self.log(f'Batch #{self.current_state["batch_number"]} is already active')
return self.current_state['batch_number']
if counting_date is None:
counting_date = self.get_counting_date()
batch_number = self.get_next_batch_number(counting_date)
now = datetime.now().isoformat()
counted_ids = []
if self.previous_state is not None:
try:
counted_ids = list(self.previous_state['counted_event_ids'][-self.carry_ids:])
except (KeyError, TypeError):
counted_ids = []
self.current_state = {
'counting_date': counting_date,
'batch_number': batch_number,
'object_label': 'mixed',
'count': 0,
'sack_count': 0,
'box_count': 0,
'start_time': now,
'last_detection_time': now,
'counted_event_ids': counted_ids,
}
self.save_state()
if self.batch_mode != 'manual':
self._reset_batch_timer()
self.log(f'Started batch #{batch_number} for {counting_date} (mixed) [mode={self.batch_mode}]')
return batch_number
def update_batch_metadata(self, metadata):
if not isinstance(metadata, dict):
return
with self.state_lock:
if self.current_state is None:
return
for key in (
'source',
'fcp_batch_number',
'plate',
'do_numbers',
'expected_sack',
'expected_box',
):
if key in metadata and metadata[key] is not None:
self.current_state[key] = metadata[key]
self.save_state()
def set_truck_present(self, present):
"""Hold auto-mode batch timeout while a truck is present in the counting zone."""
present = bool(present)
with self.state_lock:
was_present = self.truck_present
self.truck_present = present
if self.batch_mode == 'manual' or self.current_state is None:
return
if present:
if self.batch_timer:
self.batch_timer.cancel()
self.batch_timer = None
elif was_present or self.batch_timer is None:
self._reset_batch_timer()
def _reset_batch_timer(self):
if self.batch_timer:
self.batch_timer.cancel()
self.batch_timer = None
if self.truck_present:
return
self.batch_timer = threading.Timer(self.batch_timeout, self._on_batch_timeout)
self.batch_timer.daemon = True
self.batch_timer.start()
def _on_batch_timeout(self):
with self.state_lock:
if self.current_state is None:
return
if self.truck_present:
self.batch_timer = None
return
self.log(
f'No {self.object_label} line crossing for {self.batch_timeout:.0f}s '
'and no truck in counting zone – closing batch (next crossing starts a new batch)'
)
self._end_batch_locked(closed_by='timeout')
def record_counted_object_crossing(self, track_id, object_label=None):
"""Record one newly counted object crossing."""
with self.state_lock:
counting_date = self.get_counting_date()
started_new = False
if self.current_state is None:
if self.batch_mode == 'manual':
# In manual mode, do not auto-start batch; wait for manual trigger
return 0, False
self._start_new_batch_locked(counting_date, object_label=object_label)
started_new = True
elif self.current_state['counting_date'] != counting_date:
prev_label = self.current_state.get('object_label')
self._end_batch_locked(closed_by='cutoff')
if self.batch_mode == 'manual':
return 0, False
self._start_new_batch_locked(counting_date, object_label=object_label or prev_label)
started_new = True
item_label = self._normalize_item_label(object_label)
event_key = f'{item_label}:{track_id}'
if event_key not in self.current_state['counted_event_ids']:
self.current_state['count'] += 1
self.current_state[f'{item_label}_count'] += 1
self.current_state['counted_event_ids'].append(event_key)
self.log(
f'Counted {item_label} (track {track_id}) | '
f'batch #{self.current_state["batch_number"]} '
f'total: {self.current_state["count"]}'
)
self.current_state['last_detection_time'] = datetime.now().isoformat()
self.save_state()
if self.batch_mode != 'manual':
self._reset_batch_timer()
return self.current_state['count'], started_new
def record_ayam_crossing(self, track_id):
return self.record_counted_object_crossing(track_id)
def end_batch(self, closed_by='manual'):
with self.state_lock:
return self._end_batch_locked(closed_by=closed_by)
def _end_batch_locked(self, closed_by='manual'):
if self.current_state is None:
return False
self.previous_state = self.current_state
state = self.current_state
batch_label = self._normalize_batch_label(state.get('object_label'))
start_time_obj = datetime.fromisoformat(state['start_time'])
end_time_obj = datetime.now()
duration_seconds = (end_time_obj - start_time_obj).total_seconds()
is_manual = (closed_by == 'manual' or self.batch_mode == 'manual')
should_discard = False
if not is_manual:
if (state['count'] < self.min_object_per_batch
or duration_seconds < self.min_duration_per_batch):
should_discard = True
if should_discard:
self.current_state = None
self.save_state()
if self.batch_timer:
self.batch_timer.cancel()
self.batch_timer = None
self.log(
f'Batch #{state["batch_number"]} ({batch_label}) discarded '
f'(count={state["count"]}, duration={duration_seconds:.0f}s, closed_by={closed_by})'
)
return False
end_time = end_time_obj.isoformat()
try:
self._insert_batch(
state['counting_date'],
state['batch_number'],
state['count'],
state['start_time'],
end_time,
object_label=batch_label,
sack_count=state.get('sack_count', 0),
box_count=state.get('box_count', 0),
metadata=state,
)
cps = state['count'] / duration_seconds if duration_seconds > 0 else 0
self.log(
f'Batch #{state["batch_number"]} ({batch_label}) ended | 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}')
return False
self.current_state = None
self.save_state()
if self.batch_timer:
self.batch_timer.cancel()
self.batch_timer = None
return True
def _insert_batch(
self,
counting_date,
batch_number,
count,
start_time,
end_time,
object_label=None,
sack_count=0,
box_count=0,
metadata=None,
):
batch_label = 'mixed'
sack_count = int(sack_count or 0)
box_count = int(box_count or 0)
if not sack_count and not box_count and count:
# Legacy caller without separate counters: trust the row label.
legacy_label = self._normalize_batch_label(object_label)
if legacy_label == 'box':
box_count = int(count)
else:
sack_count = int(count)
if sack_count > 0 and box_count > 0:
row_label = 'mixed'
elif box_count > 0 and sack_count == 0:
row_label = 'box'
elif sack_count > 0 and box_count == 0:
row_label = 'sack'
else:
row_label = batch_label
meta = metadata if isinstance(metadata, dict) else {}
do_nums = meta.get('do_numbers')
if isinstance(do_nums, (list, tuple)):
do_nums = json.dumps(list(do_nums), ensure_ascii=False)
cur = self.db.cursor()
cur.execute(
"""
INSERT INTO batches
(counting_date, batch_number, camera_name, object_label, count,
sack_count, box_count, start_time, end_time,
source, fcp_batch_number, plate, do_numbers, expected_sack, expected_box)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
counting_date,
batch_number,
self.camera_name,
row_label,
count,
sack_count,
box_count,
start_time,
end_time,
meta.get('source'),
meta.get('fcp_batch_number'),
meta.get('plate'),
do_nums,
meta.get('expected_sack'),
meta.get('expected_box'),
),
)
cur.execute(
"""
INSERT INTO daily_summaries
(counting_date, camera_name, object_label, total_count, total_batches,
sack_count, box_count)
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,
sack_count = sack_count + excluded.sack_count,
box_count = box_count + excluded.box_count,
updated_at = CURRENT_TIMESTAMP
""",
(counting_date, self.camera_name, batch_label, count, sack_count, box_count),
)
self.db.commit()
cur.execute(
"""
SELECT COALESCE(SUM(total_count), 0), COALESCE(SUM(total_batches), 0)
FROM daily_summaries
WHERE counting_date = ? AND camera_name = ?
""",
(counting_date, self.camera_name),
)
row = cur.fetchone()
if row:
self.log(
f'Daily totals for {counting_date}: {row[0]} objects across {row[1]} batch(es)'
)
def cutoff_watcher_loop(self):
while not self.shutdown_event.is_set():
time.sleep(60)
with self.state_lock:
if self.current_state is None:
continue
if self.current_state['counting_date'] != self.get_counting_date():
self.log('Daily cutoff reached – finalizing batch')
self._end_batch_locked(closed_by='cutoff')
def start_cutoff_watcher(self):
t = threading.Thread(target=self.cutoff_watcher_loop, daemon=True)
t.start()
return t
@property
def current_batch_number(self):
if self.current_state is None:
return 0
return self.current_state['batch_number']
@property
def current_batch_count(self):
if self.current_state is None:
return 0
return self.current_state['count']
@property
def current_batch_object_label(self):
if self.current_state is None:
return None
return self._normalize_batch_label(self.current_state.get('object_label'))
def get_closed_total_for_day(self, counting_date=None):
if counting_date is None:
counting_date = self.get_counting_date()
cur = self.db.cursor()
cur.execute(
"""
SELECT COALESCE(SUM(total_count), 0)
FROM daily_summaries
WHERE counting_date = ? AND camera_name = ?
""",
(counting_date, self.camera_name),
)
row = cur.fetchone()
return row[0] if row else 0
def display_total(self):
return self.get_closed_total_for_day() + self.current_batch_count
def get_status(self):
with self.state_lock:
active = self.current_state is not None
cdate = self.get_counting_date()
obj_label = (
self._normalize_batch_label(self.current_state.get('object_label'))
if active
else None
)
sack_count = self.current_state.get('sack_count', 0) if active else 0
box_count = self.current_state.get('box_count', 0) if active else 0
return {
"active": active,
"status": "running" if active else "stopped",
"batch_mode": self.batch_mode,
"batch_number": self.current_state['batch_number'] if active else None,
"object_label": obj_label,
"object_labels": ["sack", "box"] if active else [],
"next_batch_number": self.get_next_batch_number(cdate) if not active else None,
"count": self.current_state['count'] if active else 0,
"sack_count": sack_count,
"box_count": box_count,
"counts": {"sack": sack_count, "box": box_count},
"counting_date": self.current_state['counting_date'] if active else cdate,
"start_time": self.current_state['start_time'] if active else None,
"last_detection_time": self.current_state['last_detection_time'] if active else None,
"plate": self.current_state.get('plate') if active else None,
"source": self.current_state.get('source') if active else None,
"fcp_batch_number": self.current_state.get('fcp_batch_number') if active else None,
"truck_present": self.truck_present,
}
def shutdown(self):
self.shutdown_event.set()
self.end_batch(closed_by='shutdown')
if self.batch_timer:
self.batch_timer.cancel()
self.db.close()