Files
karung-counting-feedmill-se…/archive/merge_batches_20_23.py
T

77 lines
2.5 KiB
Python

import sqlite3
import shutil
from datetime import datetime
db_path = '/opt/jetson-counter/jetson_counter.db'
# 1. Backup database
backup_path = f'/opt/jetson-counter/jetson_counter.db.bak_{datetime.now().strftime("%Y%m%d_%H%M%S")}'
shutil.copy2(db_path, backup_path)
print(f"Backup created at: {backup_path}")
conn = sqlite3.connect(db_path)
cur = conn.cursor()
# Batches to merge: 20 to 23 on 2026-08-20
# IDs: 1544 (b20: 8), 1545 (b21: 30), 1546 (b22: 14), 1547 (b23: 72)
# Total count = 8 + 30 + 14 + 72 = 124
# Start time = 2026-08-20T19:56:13.676368 (from batch 20)
# End time = 2026-08-20T20:07:26.493341 (from batch 23)
# Step A: Update Batch #20 (id 1544) to contain merged total
cur.execute('''
UPDATE batches
SET count = 124,
start_time = '2026-08-20T19:56:13.676368',
end_time = '2026-08-20T20:07:26.493341'
WHERE id = 1544
''')
# Step B: Delete merged batches 21..23 (ids 1545, 1546, 1547)
cur.execute('''
DELETE FROM batches
WHERE id IN (1545, 1546, 1547)
''')
# Step C: Shift subsequent batches (batch_number > 23) down by 3
# (e.g. Batch 24 becomes 21, Batch 25 becomes 22, ... Batch 29 becomes 26)
cur.execute('''
SELECT id, batch_number FROM batches
WHERE counting_date = '2026-08-20' AND batch_number > 23
ORDER BY batch_number ASC
''')
shift_rows = cur.fetchall()
for bid, bnum in shift_rows:
new_bnum = bnum - 3
cur.execute("UPDATE batches SET batch_number = ? WHERE id = ?", (new_bnum, bid))
# Step D: Recalculate daily_summaries for 2026-08-20
cur.execute('''
SELECT SUM(count), COUNT(id)
FROM batches
WHERE counting_date = '2026-08-20' AND camera_name = 'CC1' AND object_label = 'karung-pakan'
''')
sum_row = cur.fetchone()
tot_count = sum_row[0] if sum_row[0] is not None else 0
tot_batches = sum_row[1] if sum_row[1] is not None else 0
cur.execute('''
INSERT OR REPLACE INTO daily_summaries
(counting_date, camera_name, object_label, total_count, total_batches, updated_at)
VALUES ('2026-08-20', 'CC1', 'karung-pakan', ?, ?, CURRENT_TIMESTAMP)
''', (tot_count, tot_batches))
conn.commit()
# Verify new data around batch 19..26
cur.execute("SELECT id, batch_number, count, start_time, end_time FROM batches WHERE counting_date = '2026-08-20' AND batch_number >= 19 ORDER BY batch_number ASC")
new_rows = cur.fetchall()
print("\nAfter merge 20..23:")
for r in new_rows:
print(r)
cur.execute("SELECT * FROM daily_summaries WHERE counting_date = '2026-08-20'")
print("\nDaily Summary:", cur.fetchall())
conn.close()