#!/usr/bin/env python # -*- coding: utf-8 -*- """Import objective vehicle daily mileage and track-point observations.""" from __future__ import annotations import argparse import json import os import re import sys from pathlib import Path from typing import Any, Iterable, List, Optional, Sequence, Tuple import pymysql PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) from tools.enterprise_ledger_inspection import ( # noqa: E402 PROFILES, TrackDailyRow, parse_track_summary, source_path_hash, ) from tools.enterprise_track_point_inspection import SELECTED_VEHICLES, load_track_points # noqa: E402 def chunked(items: Sequence[Tuple[Any, ...]], size: int) -> Iterable[Sequence[Tuple[Any, ...]]]: for index in range(0, len(items), size): yield items[index:index + size] def insert_rows(cur: Any, table: str, columns: Sequence[str], rows: Sequence[Tuple[Any, ...]], batch_size: int = 1000) -> int: if not rows: return 0 sql = "INSERT INTO `%s` (%s) VALUES (%s)" % ( table, ",".join("`%s`" % column for column in columns), ",".join(["%s"] * len(columns)), ) total = 0 for batch in chunked(rows, batch_size): cur.executemany(sql, batch) total += len(batch) return total def execute_schema(conn: pymysql.connections.Connection, path: Path) -> None: statements = [item.strip() for item in path.read_text(encoding="utf-8").split(";") if item.strip()] with conn.cursor() as cur: for statement in statements: cur.execute(statement) conn.commit() SOURCE_COLUMNS = ( "report_period", "data_type", "enterprise_name", "source_path", "source_name", "source_path_hash", "source_sha256", "file_size", "sheet_name", "source_rows", ) DAILY_COLUMNS = ( "report_period", "freight_enterprise_name", "plate_no_raw", "plate_no", "track_date", "agency_name", "vehicle_label", "operator_name", "point_count", "complete_mileage", "abnormal_mileage", "total_mileage", "drift_count", "anomaly_rate", "track_text", "approved_traction_tonnage", "route_text", "trips", "straight_distance", "cargo_tons", "source_file", "source_path_hash", "source_sha256", "source_row", ) POINT_COLUMNS = ( "report_period", "unit_name", "plate_no_raw", "plate_no", "terminal_time", "receive_time", "longitude", "latitude", "speed_text", "vehicle_status", "alarm_status", "operator_name", "location_text", "province_name", "prefecture_name", "county_name", "source_file", "source_path_hash", "source_sha256", "source_row", ) def daily_row_tuple(period: str, row: TrackDailyRow) -> Tuple[Any, ...]: return ( period, row.enterprise, row.plate_no_raw or row.plate, row.plate, row.track_date, row.agency or None, row.label or None, row.operator or None, row.point_count, row.complete_mileage, row.abnormal_mileage, row.total_mileage, row.drift_count, row.anomaly_rate, row.track_text or None, row.approved_traction_tonnage, row.route or None, row.trips, row.straight_distance, row.cargo_tons, row.source_file, row.source_path_hash, row.source_sha256, row.source_row, ) def import_observations(conn: pymysql.connections.Connection, period: str, work_root: Path, schema_path: Path) -> Dict[str, Any]: execute_schema(conn, schema_path) profile_by_key = {profile.key: profile for profile in PROFILES} enterprise_names = [profile.enterprise for profile in PROFILES] daily_rows: List[Tuple[Any, ...]] = [] source_rows: List[Tuple[Any, ...]] = [] summary_files = 0 with conn.cursor() as cur: placeholders = ",".join(["%s"] * len(enterprise_names)) cur.execute( "DELETE FROM vehicle_track_point WHERE report_period=%s AND unit_name IN (" + placeholders + ")", [period] + enterprise_names, ) cur.execute( "DELETE FROM vehicle_track_daily WHERE report_period=%s AND freight_enterprise_name IN (" + placeholders + ")", [period] + enterprise_names, ) cur.execute( "DELETE FROM vehicle_track_source_file WHERE report_period=%s AND data_type='VEHICLE_DAILY_MILEAGE' " "AND enterprise_name IN (" + placeholders + ")", [period] + enterprise_names, ) cur.execute( "DELETE FROM vehicle_track_source_file WHERE report_period=%s AND data_type='VEHICLE_TRACK_POINT' " "AND enterprise_name IN (" + placeholders + ")", [period] + enterprise_names, ) for profile in PROFILES: rows, source = parse_track_summary(profile, work_root) daily_rows.extend(daily_row_tuple(period, row) for row in rows) source_rows.append(( period, "VEHICLE_DAILY_MILEAGE", profile.enterprise, source.path, Path(source.path).name, source.path_hash, source.sha256, source.size, source.sheet_name or None, len(rows), )) summary_files += 1 insert_rows(cur, "vehicle_track_source_file", SOURCE_COLUMNS, source_rows, 200) insert_rows(cur, "vehicle_track_daily", DAILY_COLUMNS, daily_rows, 1000) point_file_count = 0 point_count = 0 for spec in SELECTED_VEHICLES: profile = profile_by_key[spec.profile_key] points, audits = load_track_points(spec, work_root, period) point_source_rows = [] for audit in audits: point_source_rows.append(( period, "VEHICLE_TRACK_POINT", profile.enterprise, audit.path, Path(audit.path).name, source_path_hash(Path(audit.path)), audit.sha256, Path(audit.path).stat().st_size, "车辆轨迹明细", audit.valid_point_count, )) insert_rows(cur, "vehicle_track_source_file", SOURCE_COLUMNS, point_source_rows, 500) point_rows = [( period, point.company, point.plate_no_raw or point.plate, point.plate, point.timestamp, point.receive_time, point.longitude, point.latitude, point.speed_text or None, point.status or None, point.alarm or None, point.operator or None, point.location or None, point.province or None, point.prefecture or None, point.county or None, point.source_path, point.source_path_hash, next( audit.sha256 for audit in audits if audit.path == point.source_path ), point.source_row, ) for point in points] insert_rows(cur, "vehicle_track_point", POINT_COLUMNS, point_rows, 1000) point_file_count += len(audits) point_count += len(point_rows) conn.commit() return { "period": period, "daily_source_file_count": summary_files, "daily_row_count": len(daily_rows), "point_source_file_count": point_file_count, "point_row_count": point_count, } def main(argv: Optional[Sequence[str]] = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--period", required=True) parser.add_argument("--work-root", required=True) parser.add_argument("--schema", default=str(PROJECT_ROOT / "docs" / "sql_vehicle_track_observation.sql")) parser.add_argument("--db-host", default=os.environ.get("TRAFFIC_DB_HOST", "127.0.0.1")) parser.add_argument("--db-port", type=int, default=int(os.environ.get("TRAFFIC_DB_PORT", "3305"))) parser.add_argument("--db-user", default=os.environ.get("TRAFFIC_DB_USER", "root")) parser.add_argument("--db-password", default=os.environ.get("TRAFFIC_DB_PASSWORD", "")) parser.add_argument("--db-name", default=os.environ.get("TRAFFIC_DB_NAME", "traffic_audit")) args = parser.parse_args(argv) if not re.match(r"^\d{4}-(0[1-9]|1[0-2])$", args.period): raise SystemExit("period must use YYYY-MM") if not Path(args.work_root).is_dir(): raise SystemExit("work root not found: %s" % args.work_root) if not Path(args.schema).is_file(): raise SystemExit("schema file not found: %s" % args.schema) if not args.db_password: raise SystemExit("Set TRAFFIC_DB_PASSWORD or pass --db-password") conn = pymysql.connect( host=args.db_host, port=args.db_port, user=args.db_user, password=args.db_password, database=args.db_name, charset="utf8mb4", cursorclass=pymysql.cursors.DictCursor, autocommit=False, ) try: result = import_observations(conn, args.period, Path(args.work_root), Path(args.schema)) print(json.dumps(result, ensure_ascii=False, indent=2)) return 0 except Exception: conn.rollback() raise finally: conn.close() if __name__ == "__main__": raise SystemExit(main())