Files
sentinel-home-ai/scripts/init_db.py

126 lines
4.5 KiB
Python
Raw 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.
#!/usr/bin/env python3
"""
Sentinel Home AI - 数据库初始化脚本
执行 DDL 创建所有表,并可插入测试数据。
"""
import sys
import os
import argparse
import mysql.connector
def get_connection(host='127.0.0.1', port=3306, user='root', password=''):
"""获取 MariaDB 连接"""
return mysql.connector.connect(
host=host, port=port, user=user, password=password,
charset='utf8mb4', collation='utf8mb4_unicode_ci'
)
def execute_ddl(conn):
"""执行 DDL 脚本"""
ddl_path = os.path.join(os.path.dirname(__file__), 'ddl.sql')
with open(ddl_path, 'r', encoding='utf-8') as f:
ddl_sql = f.read()
cursor = conn.cursor()
# 按分号分割执行(简单方案,适合无存储过程的 DDL
statements = [s.strip() for s in ddl_sql.split(';') if s.strip() and not s.strip().startswith('--')]
for stmt in statements:
if stmt.upper().startswith('SELECT'):
cursor.execute(stmt)
for row in cursor.fetchall():
print(f" {row[0]}: {row[1] if len(row) > 1 else ''}")
else:
cursor.execute(stmt)
print(f" OK: {stmt[:60]}...")
conn.commit()
cursor.close()
print("\n[OK] DDL 执行完成")
def insert_test_data(conn):
"""插入测试数据"""
cursor = conn.cursor()
# 插入测试任务
cursor.execute("""
INSERT INTO process_tasks (video_path, video_url, status)
VALUES (%s, %s, %s)
""", ('/volume1/surveillance/test.mp4', 'http://100.x.x.10:8000/media/test.mp4?token=xxx', 'SUCCESS'))
task_id = cursor.lastrowid
# 插入测试事件
cursor.execute("""
INSERT INTO monitor_events (task_id, event_start_time, event_end_time, camera_name, global_summary, entities_json, compute_provider)
VALUES (%s, %s, %s, %s, %s, %s, %s)
""", (
task_id,
'2026-08-19 14:00:00',
'2026-08-19 14:30:00',
'客厅',
'客厅有人员走动,汤圆在玩积木。',
'[{"person": "人物A", "action": "在地毯上玩积木", "clothing": "黄色T恤"}]',
'["ollama"]'
))
event_id = cursor.lastrowid
# 插入测试事件明细
cursor.execute("""
INSERT INTO event_details (event_id, task_id, frame_index, frame_timestamp, camera_name, person, action, clothing, is_attention_event, source_providers)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (
event_id, task_id, 1, '2026-08-19 14:03:00', '客厅', '人物A', '在地毯上玩积木', '黄色T恤', False, '["ollama"]'
))
cursor.execute("""
INSERT INTO event_details (event_id, task_id, frame_index, frame_timestamp, camera_name, person, action, clothing, is_attention_event, source_providers)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (
event_id, task_id, 2, '2026-08-19 14:15:00', '客厅', '人物A', '看绘本', '黄色T恤', False, '["ollama"]'
))
cursor.execute("""
INSERT INTO event_details (event_id, task_id, frame_index, frame_timestamp, camera_name, person, action, clothing, is_attention_event, source_providers)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (
event_id, task_id, 3, '2026-08-19 14:25:00', '客厅', '人物A', '跌倒', '黄色T恤', True, '["ollama"]'
))
# 插入测试成员
cursor.execute("""
INSERT IGNORE INTO family_members (abstract_label, real_name, feature_description, first_seen_at)
VALUES (%s, %s, %s, %s)
""", ('人物A', None, '短发、黄色T恤、男性', '2026-08-19 14:03:00'))
conn.commit()
cursor.close()
print(f"[OK] 测试数据插入完成 (task_id={task_id}, event_id={event_id})")
def main():
parser = argparse.ArgumentParser(description='Sentinel Home AI 数据库初始化')
parser.add_argument('--host', default='127.0.0.1', help='MariaDB 主机')
parser.add_argument('--port', type=int, default=3306, help='MariaDB 端口')
parser.add_argument('--user', default='root', help='MariaDB 用户名')
parser.add_argument('--password', default='', help='MariaDB 密码')
parser.add_argument('--test-data', action='store_true', help='插入测试数据')
args = parser.parse_args()
print(f"连接 MariaDB {args.host}:{args.port} ...")
conn = get_connection(args.host, args.port, args.user, args.password)
print("执行 DDL ...")
execute_ddl(conn)
if args.test_data:
print("\n插入测试数据 ...")
insert_test_data(conn)
conn.close()
print("\n完成!")
if __name__ == '__main__':
main()