#!/usr/bin/env python # -*- coding: utf-8 -*- """Detect completed vehicle point downloads and inspect each vehicle independently.""" from __future__ import annotations import argparse import json import time from dataclasses import dataclass from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Tuple from tools.enterprise_track_point_inspection import ( Endpoint, VehicleSpec, expected_segments, inspect_vehicle, json_default, missing_segments, parse_segment_dates, read_cells, ) @dataclass(frozen=True) class DownloadTarget: spec: VehicleSpec TARGETS: Tuple[DownloadTarget, ...] = ( DownloadTarget(VehicleSpec( "anxin", "\u9102L1N275", "\u54b8\u5b81/\u5b89\u6b23", ( Endpoint("\u54b8\u5b81", ("\u54b8\u5b81",)), Endpoint("\u8d64\u58c1", ("\u8d64\u58c1",)), Endpoint("\u5929\u6d25", ("\u5929\u6d25",)), ), )), DownloadTarget(VehicleSpec( "luchang", "\u9102L53789", "\u54b8\u5b81/\u8def\u7545\u901a", ( Endpoint("\u901a\u57ce", ("\u901a\u57ce",)), Endpoint("\u5d07\u9633", ("\u5d07\u9633",)), ), )), DownloadTarget(VehicleSpec( "kaiying", "\u9102J0E858", "\u9ec4\u5188/\u51ef\u8d62", (Endpoint("\u77f3\u9996", ("\u77f3\u9996",)),), ("\u5b89\u9053\u9ea6", "\u6e56\u5317\u777f\u52e4", "\u6e56\u5317\u5229\u62d3"), )), DownloadTarget(VehicleSpec( "guangfa", "\u9102J59918", "\u9ec4\u5188/\u5e7f\u53d1", ( Endpoint("\u9ec4\u6885", ("\u9ec4\u6885",)), Endpoint("\u4e49\u4e4c", ("\u4e49\u4e4c",)), ), )), DownloadTarget(VehicleSpec( "kaixiangda", "\u9102E32721", "\u5b9c\u660c/\u51ef\u7965\u8fbe", ( Endpoint("\u679d\u6c5f", ("\u679d\u6c5f",)), Endpoint("\u7307\u4ead", ("\u7307\u4ead",)), Endpoint("\u5b9c\u90fd", ("\u5b9c\u90fd",)), Endpoint("\u4e0a\u6d77", ("\u4e0a\u6d77",)), Endpoint("\u957f\u9633", ("\u957f\u9633",)), Endpoint("\u677e\u6ecb", ("\u677e\u6ecb",)), ), )), DownloadTarget(VehicleSpec( "shengda", "\u9102E56628", "\u5b9c\u660c/\u665f\u8fbe", ( Endpoint("\u6b66\u6c49", ("\u6b66\u6c49",)), Endpoint("\u5b9c\u660c", ("\u5b9c\u660c",)), ), )), DownloadTarget(VehicleSpec( "minkun", "\u9102E57519", "\u5b9c\u660c/\u6c11\u5764", (Endpoint("\u5b9c\u660c", ("\u5b9c\u660c",)),), ("\u845b\u6d32\u575d", "\u5357\u7ad9\u8def"), )), DownloadTarget(VehicleSpec( "minkun", "\u9102E59371", "\u5b9c\u660c/\u6c11\u5764", (Endpoint("\u5b9c\u660c", ("\u5b9c\u660c",)),), ("\u845b\u6d32\u575d", "\u5357\u7ad9\u8def"), )), DownloadTarget(VehicleSpec( "heyun", "\u9102E99730", "\u5b9c\u660c/\u8a38\u8fd0", ( Endpoint("\u679d\u6c5f", ("\u679d\u6c5f",)), Endpoint("\u7307\u4ead", ("\u7307\u4ead",)), Endpoint("\u5b9c\u90fd", ("\u5b9c\u90fd",)), Endpoint("\u5e38\u5fb7", ("\u5e38\u5fb7",)), Endpoint("\u8944\u9633", ("\u8944\u9633",)), Endpoint("\u5546\u6d1b", ("\u5546\u6d1b",)), Endpoint("\u9547\u5b89", ("\u9547\u5b89",)), ), )), ) def target_files(target: DownloadTarget, work_root: Path) -> List[Path]: directory = work_root / target.spec.directory if not directory.exists(): return [] return sorted( directory.glob("*%s*.xls" % target.spec.plate), key=lambda item: (parse_segment_dates(item, "2026-09"), item.name), ) def stable_readable(paths: Sequence[Path], stable_seconds: int) -> Tuple[bool, List[str]]: errors: List[str] = [] now = time.time() for path in paths: try: if now - path.stat().st_mtime < stable_seconds: errors.append("%s is still being written" % path.name) continue with path.open("rb") as handle: handle.read(16) cells = read_cells(path) if not cells: errors.append("%s contains no readable cells" % path.name) except Exception as exc: errors.append("%s: %s" % (path.name, exc)) return not errors, errors def classify_target( target: DownloadTarget, work_root: Path, period: str, stable_seconds: int, ) -> Dict[str, Any]: paths = target_files(target, work_root) missing = missing_segments(paths, period) expected_count = len(expected_segments(period)) stable, errors = stable_readable(paths, stable_seconds) if paths else (False, []) complete = ( len(paths) == expected_count and not missing and stable and not errors ) return { "plate": target.spec.plate, "city": target.spec.profile_key, "enterprise_key": target.spec.profile_key, "directory": str(work_root / target.spec.directory), "file_count": len(paths), "expected_file_count": expected_count, "missing_segments": missing, "stable": stable, "errors": errors, "complete": complete, "files": [str(path) for path in paths], } def load_json(path: Path) -> Optional[Dict[str, Any]]: try: return json.loads(path.read_text(encoding="utf-8")) except (OSError, ValueError): return None def concise_result(result: Dict[str, Any]) -> Dict[str, Any]: points = result["points"] comparison = result["comparison"] platform = result["platform"] ledger = result["ledger"] return { "city": result["city"], "enterprise": result["enterprise"], "plate": result["plate"], "ledger_routes": result["ledger"]["route_groups"], "ledger_trips": ledger["trips"], "ledger_mileage": ledger["mileage"], "platform_mileage": platform["total_mileage"], "ledger_vs_platform_rate": comparison["ledger_vs_platform_rate"], "point_day_count": points["day_count"], "unique_point_count": points["unique_point_count"], "top_provinces": points["top_provinces"], "top_prefectures": points["top_prefectures"], "top_counties": points["top_counties"], "endpoints": points["endpoints"], "missing_days": points["missing_days"], "raw_point_distance": points["raw_distance"], "point_vs_ledger_rate": comparison["point_vs_ledger_rate"], "platform_supported_trips": comparison["platform_supported_trips"], "trip_support_rate": comparison["trip_support_rate"], } def write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text( json.dumps(payload, ensure_ascii=False, indent=2, default=json_default), encoding="utf-8", ) def main(argv: Optional[Sequence[str]] = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--period", default="2026-09") parser.add_argument("--source-root", required=True) parser.add_argument("--work-root", required=True) parser.add_argument("--output-dir", required=True) parser.add_argument("--stable-seconds", type=int, default=90) parser.add_argument("--force", action="store_true") args = parser.parse_args(argv) source_root = Path(args.source_root) work_root = Path(args.work_root) output_dir = Path(args.output_dir) output_dir.mkdir(parents=True, exist_ok=True) status: Dict[str, Any] = { "checked_at": datetime.now().isoformat(sep=" "), "targets": [], } newly_completed: List[Dict[str, Any]] = [] failed: List[Dict[str, Any]] = [] for target in TARGETS: item = classify_target(target, work_root, args.period, args.stable_seconds) result_path = output_dir / ("%s.json" % target.spec.plate) existing = load_json(result_path) if existing and not args.force: item["status"] = "DONE" item["result_file"] = str(result_path) status["targets"].append(item) continue if item["complete"]: try: result = inspect_vehicle( target.spec, source_root, work_root, args.period, ) write_json(result_path, result) item["status"] = "DONE" item["result_file"] = str(result_path) item["summary"] = concise_result(result) newly_completed.append(item["summary"]) except Exception as exc: item["status"] = "ERROR" item["error"] = str(exc) failed.append({"plate": target.spec.plate, "error": str(exc)}) elif item["errors"]: item["status"] = "ERROR" failed.append({ "plate": target.spec.plate, "errors": item["errors"], }) else: item["status"] = "WAITING" status["targets"].append(item) write_json(output_dir / "monitor_status.json", status) print(json.dumps({ "checked_at": status["checked_at"], "newly_completed": newly_completed, "failed": failed, "statuses": [ { "plate": item["plate"], "status": item["status"], "file_count": item["file_count"], "missing_segments": item["missing_segments"], } for item in status["targets"] ], }, ensure_ascii=False, indent=2, default=json_default)) return 0 if __name__ == "__main__": raise SystemExit(main())