calibration.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. // 标定记录判定(见 include/portcv/calibration.hpp)。
  2. //
  3. // 文件里有三块"看起来只是格式细节、实际决定校验成败"的代码,改之前先读注释:
  4. // 1) python_repr() —— 浮点数按 Python `repr()` 渲染(1e15 → "1000000000000000.0")
  5. // 2) append_number() —— 区分 JSON 整数/浮点(180 vs 180.0)
  6. // 3) append_string() —— 只转义 `"` `\` 与控制字符,非 ASCII 原样输出(ensure_ascii=False)
  7. // 三者合起来才等于 `json.dumps(..., ensure_ascii=False, sort_keys=True, separators=(",", ":"))`。
  8. #include "portcv/calibration.hpp"
  9. #include <algorithm>
  10. #include <cmath>
  11. #include <cstdio>
  12. #include <cstdlib>
  13. #include <ctime>
  14. #include <string>
  15. #include "portcv/json_lite.hpp"
  16. #include "portcv/sha256.hpp"
  17. namespace portcv {
  18. namespace {
  19. std::string trim_copy(const std::string& s) {
  20. std::size_t b = 0;
  21. std::size_t e = s.size();
  22. const auto is_space = [](char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; };
  23. while (b < e && is_space(s[b])) { ++b; }
  24. while (e > b && is_space(s[e - 1])) { --e; }
  25. return s.substr(b, e - b);
  26. }
  27. /// Python `repr(float)` 的渲染规则(shortest round-trip + 定点/科学计数取舍)。
  28. ///
  29. /// 为什么不直接用 `std::to_chars`:`to_chars(general)` 的定点/科学计数切换点与
  30. /// Python 不同(1e15 会输出 "1e+15",Python 是 "1000000000000000.0"),
  31. /// 一旦不一致,sha256 就永远不会与 Python 生成值相同。
  32. /// 这里先用 `%.{p}e` + `strtod` 找回"最短可逆有效数字",再按 Python 的规则重排。
  33. std::string python_repr(double v) {
  34. if (std::isnan(v)) { return "nan"; }
  35. if (std::isinf(v)) { return v < 0.0 ? "-inf" : "inf"; }
  36. if (v == 0.0) { return std::signbit(v) ? "-0.0" : "0.0"; }
  37. char buf[64];
  38. std::string digits;
  39. int exp10 = 0;
  40. for (int precision = 1; precision <= 17; ++precision) {
  41. std::snprintf(buf, sizeof(buf), "%.*e", precision - 1, v);
  42. if (std::strtod(buf, nullptr) != v) { continue; }
  43. const std::string text(buf);
  44. const std::size_t epos = text.find('e');
  45. std::string mantissa = text.substr(0, epos);
  46. if (!mantissa.empty() && mantissa[0] == '-') { mantissa.erase(0, 1); }
  47. digits.clear();
  48. for (char c : mantissa) {
  49. if (c != '.') { digits.push_back(c); }
  50. }
  51. exp10 = std::atoi(text.c_str() + epos + 1);
  52. break;
  53. }
  54. if (digits.empty()) { // 理论上到不了(%.16e 一定可逆);防御性兜底
  55. std::snprintf(buf, sizeof(buf), "%.17g", v);
  56. return std::string(buf);
  57. }
  58. while (digits.size() > 1 && digits.back() == '0') { digits.pop_back(); }
  59. std::string out;
  60. if (v < 0.0) { out.push_back('-'); }
  61. const int n = static_cast<int>(digits.size());
  62. if (exp10 >= -4 && exp10 < 16) { // Python:-4 <= 指数 < 16 用定点
  63. if (exp10 >= 0) {
  64. if (n <= exp10 + 1) {
  65. out += digits;
  66. out.append(static_cast<std::size_t>(exp10 + 1 - n), '0');
  67. out += ".0";
  68. } else {
  69. out += digits.substr(0, static_cast<std::size_t>(exp10 + 1));
  70. out.push_back('.');
  71. out += digits.substr(static_cast<std::size_t>(exp10 + 1));
  72. }
  73. } else {
  74. out += "0.";
  75. out.append(static_cast<std::size_t>(-exp10 - 1), '0');
  76. out += digits;
  77. }
  78. } else { // 科学计数:d[.ddd]e±NN(指数至少两位)
  79. out += digits.substr(0, 1);
  80. if (n > 1) {
  81. out.push_back('.');
  82. out += digits.substr(1);
  83. }
  84. out.push_back('e');
  85. out.push_back(exp10 < 0 ? '-' : '+');
  86. const int magnitude = exp10 < 0 ? -exp10 : exp10;
  87. if (magnitude < 10) { out.push_back('0'); }
  88. out += std::to_string(magnitude);
  89. }
  90. return out;
  91. }
  92. void append_string(std::string* out, const std::string& s) {
  93. out->push_back('"');
  94. for (const char raw_ch : s) {
  95. const unsigned char c = static_cast<unsigned char>(raw_ch);
  96. switch (c) {
  97. case '"': *out += "\\\""; break;
  98. case '\\': *out += "\\\\"; break;
  99. case '\b': *out += "\\b"; break;
  100. case '\f': *out += "\\f"; break;
  101. case '\n': *out += "\\n"; break;
  102. case '\r': *out += "\\r"; break;
  103. case '\t': *out += "\\t"; break;
  104. default:
  105. if (c < 0x20) {
  106. char esc[8];
  107. std::snprintf(esc, sizeof(esc), "\\u%04x", static_cast<unsigned>(c));
  108. *out += esc;
  109. } else {
  110. out->push_back(raw_ch); // UTF-8 原样(ensure_ascii=False)
  111. }
  112. }
  113. }
  114. out->push_back('"');
  115. }
  116. void append_number(std::string* out, const json::Value& v) {
  117. const std::string& raw = v.raw;
  118. const bool is_float = raw.find('.') != std::string::npos ||
  119. raw.find('e') != std::string::npos ||
  120. raw.find('E') != std::string::npos;
  121. if (!raw.empty() && !is_float) {
  122. // JSON 整数:按 Python 的 int 渲染(去前导 0;"-0" → "0");大整数也逐位保真
  123. const bool negative = raw[0] == '-';
  124. std::size_t first = negative ? 1u : 0u;
  125. while (first + 1 < raw.size() && raw[first] == '0') { ++first; }
  126. const std::string digits = raw.substr(first);
  127. if (negative && digits != "0") { out->push_back('-'); }
  128. *out += digits;
  129. return;
  130. }
  131. *out += python_repr(v.number);
  132. }
  133. /// 键排序:按 UTF-8 字节的**无符号**比较(= Unicode 码点序,与 Python `sort_keys` 相同)。
  134. bool key_less(const std::string& a, const std::string& b) {
  135. return std::lexicographical_compare(
  136. a.begin(), a.end(), b.begin(), b.end(),
  137. [](char x, char y) { return static_cast<unsigned char>(x) < static_cast<unsigned char>(y); });
  138. }
  139. void append_value(std::string* out, const json::Value& v, bool skip_top_sha256) {
  140. switch (v.type) {
  141. case json::Type::Null: *out += "null"; return;
  142. case json::Type::Bool: *out += v.boolean ? "true" : "false"; return;
  143. case json::Type::Number: append_number(out, v); return;
  144. case json::Type::String: append_string(out, v.text); return;
  145. case json::Type::Array: {
  146. out->push_back('[');
  147. for (std::size_t i = 0; i < v.items.size(); ++i) {
  148. if (i != 0) { out->push_back(','); }
  149. append_value(out, v.items[i], false);
  150. }
  151. out->push_back(']');
  152. return;
  153. }
  154. case json::Type::Object: {
  155. std::vector<std::size_t> order;
  156. order.reserve(v.members.size());
  157. for (std::size_t i = 0; i < v.members.size(); ++i) {
  158. if (skip_top_sha256 && v.members[i].first == "sha256") { continue; }
  159. order.push_back(i);
  160. }
  161. std::sort(order.begin(), order.end(), [&v](std::size_t a, std::size_t b) {
  162. return key_less(v.members[a].first, v.members[b].first);
  163. });
  164. out->push_back('{');
  165. for (std::size_t i = 0; i < order.size(); ++i) {
  166. if (i != 0) { out->push_back(','); }
  167. const auto& member = v.members[order[i]];
  168. append_string(out, member.first);
  169. out->push_back(':');
  170. append_value(out, member.second, false);
  171. }
  172. out->push_back('}');
  173. return;
  174. }
  175. }
  176. }
  177. } // namespace
  178. std::string canonical_json(const json::Value& record) {
  179. std::string out;
  180. append_value(&out, record, true);
  181. return out;
  182. }
  183. std::string compute_hash(const json::Value& record) { return sha256_hex(canonical_json(record)); }
  184. bool verify_hash(const json::Value& record) {
  185. const json::Value& expected = record.member("sha256");
  186. if (!expected.is_string() || expected.text.empty()) { return false; }
  187. return expected.text == compute_hash(record); // 定长十六进制,普通比较即可
  188. }
  189. std::string CalibrationStatus::reasons_text() const {
  190. std::string out;
  191. for (std::size_t i = 0; i < reasons.size(); ++i) {
  192. if (i != 0) { out.push_back(','); }
  193. out += reasons[i];
  194. }
  195. return out;
  196. }
  197. bool parse_iso8601(const std::string& text, long long* epoch_s) {
  198. if (epoch_s == nullptr) { return false; }
  199. const std::string s = trim_copy(text);
  200. if (s.size() < 10) { return false; }
  201. const auto read_int = [&s](std::size_t from, int count, int* out) {
  202. if (from + static_cast<std::size_t>(count) > s.size()) { return false; }
  203. int value = 0;
  204. for (int i = 0; i < count; ++i) {
  205. const char c = s[from + static_cast<std::size_t>(i)];
  206. if (c < '0' || c > '9') { return false; }
  207. value = value * 10 + (c - '0');
  208. }
  209. *out = value;
  210. return true;
  211. };
  212. int year = 0;
  213. int month = 0;
  214. int day = 0;
  215. if (!read_int(0, 4, &year) || s[4] != '-' || !read_int(5, 2, &month) || s[7] != '-' ||
  216. !read_int(8, 2, &day)) {
  217. return false;
  218. }
  219. std::size_t pos = 10;
  220. int hour = 0;
  221. int minute = 0;
  222. double second = 0.0;
  223. if (pos < s.size() && (s[pos] == 'T' || s[pos] == 't' || s[pos] == ' ')) {
  224. ++pos;
  225. if (!read_int(pos, 2, &hour)) { return false; }
  226. pos += 2;
  227. if (pos >= s.size() || s[pos] != ':') { return false; }
  228. ++pos;
  229. if (!read_int(pos, 2, &minute)) { return false; }
  230. pos += 2;
  231. if (pos < s.size() && s[pos] == ':') {
  232. ++pos;
  233. int whole = 0;
  234. if (!read_int(pos, 2, &whole)) { return false; }
  235. pos += 2;
  236. second = whole;
  237. if (pos < s.size() && s[pos] == '.') {
  238. ++pos;
  239. const std::size_t start = pos;
  240. double scale = 0.1;
  241. while (pos < s.size() && s[pos] >= '0' && s[pos] <= '9') {
  242. second += (s[pos] - '0') * scale;
  243. scale *= 0.1;
  244. ++pos;
  245. }
  246. if (pos == start) { return false; }
  247. }
  248. }
  249. }
  250. long long offset_s = 0;
  251. if (pos < s.size()) {
  252. if (s[pos] == 'Z' || s[pos] == 'z') {
  253. ++pos;
  254. } else if (s[pos] == '+' || s[pos] == '-') {
  255. const int sign = (s[pos] == '-') ? -1 : 1;
  256. ++pos;
  257. int off_hour = 0;
  258. int off_minute = 0;
  259. if (!read_int(pos, 2, &off_hour)) { return false; }
  260. pos += 2;
  261. if (pos < s.size() && s[pos] == ':') { ++pos; }
  262. if (pos < s.size()) {
  263. if (!read_int(pos, 2, &off_minute)) { return false; }
  264. pos += 2;
  265. }
  266. offset_s = static_cast<long long>(sign) * (off_hour * 3600 + off_minute * 60);
  267. } else {
  268. return false;
  269. }
  270. }
  271. if (pos != s.size()) { return false; }
  272. if (month < 1 || month > 12 || day < 1 || day > 31) { return false; }
  273. if (hour > 23 || minute > 59 || second >= 61.0) { return false; }
  274. // 公历日 → epoch 天数(Howard Hinnant 的 days_from_civil:纯整数、不依赖时区库)
  275. const long long y = static_cast<long long>(year) - (month <= 2 ? 1 : 0);
  276. const long long era = (y >= 0 ? y : y - 399) / 400;
  277. const long long yoe = y - era * 400;
  278. const long long doy =
  279. (153LL * (month + (month > 2 ? -3 : 9)) + 2) / 5 + static_cast<long long>(day) - 1;
  280. const long long doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
  281. const long long days = era * 146097 + doe - 719468;
  282. *epoch_s = days * 86400 + hour * 3600 + minute * 60 + static_cast<long long>(second) - offset_s;
  283. return true;
  284. }
  285. bool record_from_json(const json::Value& data, CalibrationRecord* out, std::string* error) {
  286. const auto fail = [error](const std::string& what) {
  287. if (error != nullptr) { *error = what; }
  288. return false;
  289. };
  290. if (out == nullptr) { return fail("record_from_json: 输出参数为空指针"); }
  291. if (!data.is_object()) { return fail("标定记录必须是 JSON 对象"); }
  292. for (const char* key : {"site", "camera_id", "calibrated_at"}) {
  293. const json::Value& v = data.member(key);
  294. if (!v.is_string() || trim_copy(v.text).empty()) {
  295. return fail(std::string("标定记录缺少字段: ") + key);
  296. }
  297. }
  298. CalibrationRecord record;
  299. record.site = data.member("site").text;
  300. record.camera_id = data.member("camera_id").text;
  301. record.calibrated_at = data.member("calibrated_at").text;
  302. if (!parse_iso8601(record.calibrated_at, &record.calibrated_at_s)) {
  303. return fail("calibrated_at 不是 ISO-8601 时间: " + record.calibrated_at);
  304. }
  305. const json::Value& reviewer = data.member("reviewer");
  306. record.reviewer = reviewer.is_string() ? reviewer.text : "";
  307. const json::Value& method = data.member("method");
  308. record.method = method.is_string() ? method.text : "";
  309. const json::Value& px = data.member("px_per_m");
  310. record.px_per_m = px.is_number() ? px.number : 0.0;
  311. const json::Value& box = data.member("box_height_m");
  312. record.box_height_m = box.is_number() ? box.number : 0.0;
  313. *out = record;
  314. return true;
  315. }
  316. CalibrationStatus evaluate_calibration_values(const CalibrationConfig& cfg, const CalibrationInputs& in,
  317. long long now_s) {
  318. CalibrationStatus status;
  319. status.hold = cfg.hold_on_stale;
  320. status.path = cfg.record;
  321. if (trim_copy(cfg.record).empty()) { // 未配记录 → 只看手工开关(兼容旧配置)
  322. if (cfg.stale) {
  323. status.stale = true;
  324. status.reasons.push_back("manual_stale");
  325. }
  326. return status;
  327. }
  328. if (!in.file_exists) {
  329. status.stale = true;
  330. status.reasons.push_back("missing");
  331. return status;
  332. }
  333. if (!in.json_ok || !in.record.is_object()) {
  334. status.stale = true;
  335. status.reasons.push_back("invalid:json");
  336. return status;
  337. }
  338. status.hash_ok = verify_hash(in.record);
  339. if (!status.hash_ok) { status.reasons.push_back("hash_mismatch"); }
  340. CalibrationRecord record;
  341. std::string error;
  342. if (!record_from_json(in.record, &record, &error)) {
  343. status.stale = true;
  344. status.reasons.push_back("invalid:fields"); // Python 侧同为 "invalid:*"
  345. return status;
  346. }
  347. status.record = record;
  348. status.has_record = true;
  349. const double age_days =
  350. (static_cast<double>(now_s) - static_cast<double>(record.calibrated_at_s)) / 86400.0;
  351. status.age_days = age_days;
  352. status.has_age = true;
  353. if (cfg.max_age_days > 0.0 && age_days > cfg.max_age_days) {
  354. status.reasons.push_back("expired");
  355. }
  356. if (trim_copy(record.reviewer).empty()) { status.reasons.push_back("unreviewed"); }
  357. if (record.px_per_m > 0.0 && in.run_px_per_m > 0.0) {
  358. const double tolerance = std::max(1e-6, cfg.px_per_m_tolerance);
  359. if (std::fabs(in.run_px_per_m - record.px_per_m) / record.px_per_m > tolerance) {
  360. status.reasons.push_back("px_per_m_drift");
  361. }
  362. }
  363. if (record.box_height_m > 0.0 && in.run_box_height_m > 0.0) {
  364. const double tolerance_m = std::max(1e-6, cfg.box_height_tolerance_m);
  365. if (std::fabs(in.run_box_height_m - record.box_height_m) > tolerance_m) {
  366. status.reasons.push_back("box_height_drift");
  367. }
  368. }
  369. if (cfg.stale) { status.reasons.push_back("manual_stale"); }
  370. status.stale = !status.reasons.empty();
  371. return status;
  372. }
  373. CalibrationStatus evaluate_calibration(const CalibrationConfig& cfg, double run_px_per_m,
  374. double run_box_height_m, long long now_s) {
  375. CalibrationInputs in;
  376. in.run_px_per_m = run_px_per_m;
  377. in.run_box_height_m = run_box_height_m;
  378. if (!trim_copy(cfg.record).empty()) {
  379. std::string text;
  380. std::string error;
  381. in.file_exists = json::read_file(cfg.record, &text, &error);
  382. if (in.file_exists) {
  383. in.record = json::parse(text, &error);
  384. in.json_ok = in.record.is_object();
  385. }
  386. }
  387. return evaluate_calibration_values(cfg, in, now_s);
  388. }
  389. long long epoch_now() { return static_cast<long long>(std::time(nullptr)); }
  390. std::string calibration_status_line(const CalibrationStatus& status) {
  391. char buf[512];
  392. std::string out;
  393. if (trim_copy(status.path).empty()) {
  394. std::snprintf(buf, sizeof(buf),
  395. "标定 : calibration.record=(未配置) stale=%s hold_on_stale=%d",
  396. status.stale ? "YES" : "no", status.hold ? 1 : 0);
  397. out += buf;
  398. } else {
  399. std::snprintf(buf, sizeof(buf), "标定 : calibration.record=%s stale=%s hash=%s ",
  400. status.path.c_str(), status.stale ? "YES" : "no",
  401. status.has_record ? (status.hash_ok ? "ok" : "MISMATCH") : "-");
  402. out += buf;
  403. if (status.has_age) {
  404. std::snprintf(buf, sizeof(buf), "age=%.1f天 ", status.age_days);
  405. out += buf;
  406. }
  407. std::snprintf(buf, sizeof(buf), "site=%s camera=%s reviewer=%s hold_on_stale=%d",
  408. status.has_record ? status.record.site.c_str() : "-",
  409. status.has_record ? status.record.camera_id.c_str() : "-",
  410. status.has_record
  411. ? (trim_copy(status.record.reviewer).empty() ? "(空)"
  412. : status.record.reviewer.c_str())
  413. : "-",
  414. status.hold ? 1 : 0);
  415. out += buf;
  416. }
  417. if (!status.reasons.empty()) {
  418. out += " reasons=";
  419. out += status.reasons_text();
  420. }
  421. out += "\n";
  422. return out;
  423. }
  424. } // namespace portcv