third_party_pusher.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. """
  2. 第三方平台推送模块
  3. 将批次信息推送到第三方平台接口
  4. """
  5. import os
  6. import time
  7. import json
  8. import logging
  9. import threading
  10. import queue
  11. import requests
  12. from typing import Optional, Dict, Any, List, Callable
  13. from dataclasses import dataclass
  14. from datetime import datetime
  15. from pathlib import Path
  16. logger = logging.getLogger(__name__)
  17. def _normalize_timestamp(ts: float) -> float:
  18. """统一时间戳为秒。CaptureUploader 使用毫秒,其他可能使用秒。"""
  19. if ts > 1e12:
  20. return ts / 1000.0
  21. return ts
  22. def _convert_to_legacy_batch_info(new_info: Dict[str, Any]) -> Dict[str, Any]:
  23. """
  24. 把新版 CaptureUploader 生成的 batch_info 转成老版 PairedImageSaver 的字段名。
  25. 老字段包括:
  26. - panorama.local_path / panorama.oss_url
  27. - total_persons
  28. - ptz_images_count
  29. - persons(含 person_index、bbox 字典、confidence 等)
  30. """
  31. normalized_ts = _normalize_timestamp(new_info.get("timestamp", time.time()))
  32. urls = new_info.get("image_urls") or {}
  33. image_paths = new_info.get("image_paths") or []
  34. camera_type = new_info.get("camera_type", "panorama")
  35. # 优先取 marked OSS URL,兼容老代码只读取 panorama.oss_url 的行为
  36. oss_url = urls.get("marked") or urls.get("original") or None
  37. local_path = image_paths[0] if image_paths else None
  38. persons = []
  39. for i, det in enumerate(new_info.get("detections") or []):
  40. bbox = det.get("bbox", [0, 0, 0, 0])
  41. person = {
  42. "person_index": i,
  43. "bbox": {
  44. "x1": int(bbox[0]),
  45. "y1": int(bbox[1]),
  46. "x2": int(bbox[2]),
  47. "y2": int(bbox[3]),
  48. },
  49. "confidence": float(det.get("confidence", 0.0)),
  50. "camera_type": det.get("camera_type", camera_type),
  51. }
  52. ptz_position = new_info.get("ptz_position")
  53. if ptz_position:
  54. person["ptz_position"] = ptz_position
  55. persons.append(person)
  56. legacy = {
  57. "batch_id": new_info.get("batch_id", ""),
  58. "device_id": new_info.get("device_id", ""),
  59. "project_id": new_info.get("project_id", ""),
  60. "timestamp": normalized_ts,
  61. "datetime": datetime.fromtimestamp(normalized_ts).isoformat(),
  62. "panorama": {
  63. "local_path": local_path,
  64. "oss_url": oss_url,
  65. },
  66. "total_persons": len(persons),
  67. "ptz_images_count": 1 if camera_type == "ptz" else 0,
  68. "persons": persons,
  69. }
  70. return legacy
  71. @dataclass
  72. class BatchReport:
  73. """批次上报数据"""
  74. batch_id: str
  75. device_id: str
  76. project_id: str
  77. timestamp: float
  78. batch_info: Dict[str, Any] # batch_info.json 的完整内容
  79. local_path: Optional[str] = None # batch_info.json 本地路径
  80. class ThirdPartyPusher:
  81. """
  82. 第三方平台推送器
  83. 负责将批次信息推送到配置的第三方平台接口
  84. """
  85. def __init__(self, config: Dict[str, Any] = None):
  86. """
  87. 初始化第三方平台推送器
  88. Args:
  89. config: 第三方平台配置字典
  90. """
  91. from config import THIRD_PARTY_CONFIG, DEVICE_CONFIG
  92. self.config = config or THIRD_PARTY_CONFIG
  93. self.device_config = DEVICE_CONFIG
  94. # 功能开关
  95. self.enabled = self.config.get('enabled', False)
  96. # 平台配置
  97. self.platform_type = self.config.get('platform_type', 'custom')
  98. self.base_url = self.config.get('base_url', '')
  99. self.api_version = self.config.get('api_version', 'v1')
  100. # 认证配置
  101. self.auth_type = self.config.get('auth_type', 'none')
  102. self.api_key = self.config.get('api_key', '')
  103. self.api_secret = self.config.get('api_secret', '')
  104. self.oauth2_config = self.config.get('oauth2', {})
  105. # 接口路径
  106. self.endpoints = self.config.get('endpoints', {})
  107. self.batch_report_url = self.endpoints.get('batch_report', '/api/batch/report')
  108. self.heartbeat_url = self.endpoints.get('heartbeat', '/api/device/heartbeat')
  109. # 推送控制
  110. self.push_interval = self.config.get('push_interval', 1.0)
  111. self.retry_count = self.config.get('retry_count', 3)
  112. self.retry_delay = self.config.get('retry_delay', 2.0)
  113. self.timeout = self.config.get('timeout', 10)
  114. self.data_format = self.config.get('data_format', 'json')
  115. self.include_images = self.config.get('include_images', False)
  116. # OAuth2 Token
  117. self._access_token = None
  118. self._token_expires_at = 0
  119. # 上报队列
  120. self.report_queue = queue.Queue()
  121. # 工作线程
  122. self.running = False
  123. self.worker_thread = None
  124. # 统计
  125. self.stats = {
  126. 'total_reports': 0,
  127. 'success_reports': 0,
  128. 'failed_reports': 0,
  129. }
  130. self.stats_lock = threading.Lock()
  131. # 回调
  132. self.on_report_success: Optional[Callable] = None
  133. self.on_report_failed: Optional[Callable] = None
  134. # 最后上报时间
  135. self.last_report_time = 0
  136. if self.enabled:
  137. logger.info(f"[第三方平台] 推送器初始化完成: {self.base_url}")
  138. def start(self):
  139. """启动推送器"""
  140. if not self.enabled:
  141. logger.info("[第三方平台] 推送器未启用")
  142. return
  143. if self.running:
  144. return
  145. self.running = True
  146. self.worker_thread = threading.Thread(target=self._worker_loop, daemon=True)
  147. self.worker_thread.start()
  148. logger.info("[第三方平台] 推送器已启动")
  149. def stop(self):
  150. """停止推送器"""
  151. self.running = False
  152. if self.worker_thread:
  153. self.worker_thread.join(timeout=5)
  154. logger.info("[第三方平台] 推送器已停止")
  155. def _worker_loop(self):
  156. """工作线程循环"""
  157. while self.running:
  158. try:
  159. report = self.report_queue.get(timeout=1.0)
  160. self._process_report(report)
  161. except queue.Empty:
  162. continue
  163. except Exception as e:
  164. logger.error(f"[第三方平台] 处理上报错误: {e}")
  165. def _get_auth_headers(self) -> Dict[str, str]:
  166. """获取认证请求头(当前第三方接口不需要自定义 header,返回空避免 422)"""
  167. return {}
  168. def _get_oauth2_token(self) -> Optional[str]:
  169. """获取 OAuth2 Token"""
  170. # 检查现有 token 是否有效
  171. if self._access_token and time.time() < self._token_expires_at - 60:
  172. return self._access_token
  173. # 重新获取 token
  174. token_url = self.oauth2_config.get('token_url', '')
  175. client_id = self.oauth2_config.get('client_id', '')
  176. client_secret = self.oauth2_config.get('client_secret', '')
  177. scope = self.oauth2_config.get('scope', '')
  178. if not all([token_url, client_id, client_secret]):
  179. logger.error("[第三方平台] OAuth2 配置不完整")
  180. return None
  181. try:
  182. data = {
  183. 'grant_type': 'client_credentials',
  184. 'client_id': client_id,
  185. 'client_secret': client_secret,
  186. }
  187. if scope:
  188. data['scope'] = scope
  189. response = requests.post(token_url, data=data, timeout=self.timeout)
  190. if response.status_code == 200:
  191. result = response.json()
  192. self._access_token = result.get('access_token')
  193. expires_in = result.get('expires_in', 3600)
  194. self._token_expires_at = time.time() + expires_in
  195. logger.info("[第三方平台] OAuth2 Token 获取成功")
  196. return self._access_token
  197. else:
  198. logger.error(f"[第三方平台] OAuth2 Token 获取失败: {response.status_code}")
  199. return None
  200. except Exception as e:
  201. logger.error(f"[第三方平台] OAuth2 Token 请求异常: {e}")
  202. return None
  203. def _process_report(self, report: BatchReport):
  204. """处理单个上报任务"""
  205. # 检查推送间隔
  206. current_time = time.time()
  207. time_since_last = current_time - self.last_report_time
  208. if time_since_last < self.push_interval:
  209. time.sleep(self.push_interval - time_since_last)
  210. success = self._send_batch_report(report)
  211. with self.stats_lock:
  212. self.stats['total_reports'] += 1
  213. if success:
  214. self.stats['success_reports'] += 1
  215. else:
  216. self.stats['failed_reports'] += 1
  217. self.last_report_time = time.time()
  218. # 触发回调
  219. if success and self.on_report_success:
  220. try:
  221. self.on_report_success(report)
  222. except Exception as e:
  223. logger.error(f"[第三方平台] 成功回调执行错误: {e}")
  224. elif not success and self.on_report_failed:
  225. try:
  226. self.on_report_failed(report)
  227. except Exception as e:
  228. logger.error(f"[第三方平台] 失败回调执行错误: {e}")
  229. def _send_batch_report(self, report: BatchReport) -> bool:
  230. """
  231. 发送批次上报请求
  232. Args:
  233. report: 批次上报数据
  234. Returns:
  235. bool: 是否成功
  236. """
  237. if not self.base_url:
  238. logger.error("[第三方平台] 未配置 base_url")
  239. return False
  240. url = f"{self.base_url}{self.batch_report_url}"
  241. # 构建请求数据
  242. payload = self._build_payload(report)
  243. headers = self._get_auth_headers()
  244. for attempt in range(self.retry_count):
  245. try:
  246. if self.data_format == 'json':
  247. response = requests.post(
  248. url,
  249. json=payload,
  250. headers=headers,
  251. timeout=self.timeout,
  252. verify=False
  253. )
  254. else:
  255. response = requests.post(
  256. url,
  257. data=payload,
  258. headers=headers,
  259. timeout=self.timeout,
  260. verify=False
  261. )
  262. if response.status_code == 200:
  263. result = response.json()
  264. status = result.get('status', '')
  265. message = result.get('message', '')
  266. if (result.get('code') == 200 or
  267. result.get('success') == True or
  268. status in ('pending', 'success', 'accepted') or
  269. message == 'accepted'):
  270. logger.info(f"[第三方平台] 批次上报成功: {report.batch_id}, task_id={result.get('task_id')}")
  271. return True
  272. else:
  273. logger.warning(f"[第三方平台] 批次上报失败: {result.get('msg', '未知错误')}")
  274. try:
  275. logger.warning(f"[第三方平台] 响应内容: {str(result)[:500]}")
  276. except Exception:
  277. pass
  278. else:
  279. logger.warning(f"[第三方平台] 批次上报失败: HTTP {response.status_code}")
  280. try:
  281. logger.warning(f"[第三方平台] 响应内容: {response.text[:500]}")
  282. except Exception:
  283. pass
  284. if attempt < self.retry_count - 1:
  285. time.sleep(self.retry_delay)
  286. except requests.exceptions.Timeout:
  287. logger.warning(f"[第三方平台] 请求超时 (尝试 {attempt + 1}/{self.retry_count})")
  288. if attempt < self.retry_count - 1:
  289. time.sleep(self.retry_delay)
  290. except Exception as e:
  291. logger.error(f"[第三方平台] 请求异常 (尝试 {attempt + 1}/{self.retry_count}): {e}")
  292. if attempt < self.retry_count - 1:
  293. time.sleep(self.retry_delay)
  294. logger.error(f"[第三方平台] 批次上报最终失败: {report.batch_id}")
  295. return False
  296. def _build_payload(self, report: BatchReport) -> Dict[str, Any]:
  297. """
  298. 构建上报请求体
  299. Args:
  300. report: 批次上报数据
  301. Returns:
  302. Dict: 请求体字典
  303. """
  304. batch_info = report.batch_info
  305. # 根据平台类型调整格式
  306. normalized_ts = _normalize_timestamp(report.timestamp)
  307. if self.platform_type == 'jtjai':
  308. # 优先取 OSS URL,否则用本地路径
  309. urls = batch_info.get('image_urls') or {}
  310. image_url = urls.get('original') or urls.get('marked') or (batch_info.get('image_paths') or [None])[0]
  311. payload = {
  312. 'createTime': datetime.fromtimestamp(normalized_ts).strftime("%Y-%m-%d %H:%M:%S"),
  313. 'addr': f"设备{report.device_id}批次上报",
  314. 'ext1': json.dumps([image_url]),
  315. 'ext2': json.dumps({
  316. 'batchId': report.batch_id,
  317. 'deviceId': report.device_id,
  318. 'projectId': report.project_id,
  319. 'totalPersons': len(batch_info.get('detections', [])),
  320. 'ptzImagesCount': 1 if batch_info.get('camera_type') == 'ptz' else 0,
  321. 'persons': batch_info.get('detections', []),
  322. 'imageUrls': urls,
  323. })
  324. }
  325. else:
  326. # custom / 其他平台:把新版 batch_info 转回老字段名后上报,
  327. # 兼容原人体分析平台对 panorama / total_persons / persons 的解析。
  328. payload = _convert_to_legacy_batch_info(batch_info)
  329. # 统一时间戳单位为秒,避免第三方解析错误
  330. payload['timestamp'] = normalized_ts
  331. return payload
  332. def report_batch(self, batch_info: Dict[str, Any], local_path: Optional[str] = None):
  333. """
  334. 上报批次信息
  335. Args:
  336. batch_info: batch_info.json 的字典内容
  337. local_path: batch_info.json 的本地文件路径(可选)
  338. """
  339. if not self.enabled:
  340. return
  341. report = BatchReport(
  342. batch_id=batch_info.get('batch_id', ''),
  343. device_id=batch_info.get('device_id', ''),
  344. project_id=batch_info.get('project_id', ''),
  345. timestamp=batch_info.get('timestamp', time.time()),
  346. batch_info=batch_info,
  347. local_path=local_path
  348. )
  349. self.report_queue.put(report)
  350. def report_batch_sync(self, batch_info: Dict[str, Any],
  351. local_path: Optional[str] = None) -> bool:
  352. """
  353. 同步上报批次信息
  354. Args:
  355. batch_info: batch_info.json 的字典内容
  356. local_path: batch_info.json 的本地文件路径(可选)
  357. Returns:
  358. bool: 是否成功
  359. """
  360. if not self.enabled:
  361. return False
  362. report = BatchReport(
  363. batch_id=batch_info.get('batch_id', ''),
  364. device_id=batch_info.get('device_id', ''),
  365. project_id=batch_info.get('project_id', ''),
  366. timestamp=batch_info.get('timestamp', time.time()),
  367. batch_info=batch_info,
  368. local_path=local_path
  369. )
  370. return self._send_batch_report(report)
  371. def send_heartbeat(self) -> bool:
  372. """
  373. 发送心跳
  374. Returns:
  375. bool: 是否成功
  376. """
  377. if not self.enabled or not self.heartbeat_url:
  378. return False
  379. url = f"{self.base_url}{self.heartbeat_url}"
  380. payload = {
  381. 'deviceId': self.device_config.get('device_id', ''),
  382. 'projectId': self.device_config.get('project_id', ''),
  383. 'timestamp': time.time(),
  384. 'status': 'online',
  385. }
  386. headers = self._get_auth_headers()
  387. try:
  388. response = requests.post(
  389. url,
  390. json=payload,
  391. headers=headers,
  392. timeout=self.timeout,
  393. verify=False
  394. )
  395. if response.status_code == 200:
  396. logger.debug("[第三方平台] 心跳发送成功")
  397. return True
  398. else:
  399. logger.warning(f"[第三方平台] 心跳发送失败: HTTP {response.status_code}")
  400. return False
  401. except Exception as e:
  402. logger.error(f"[第三方平台] 心跳发送异常: {e}")
  403. return False
  404. def set_callbacks(self, on_success: Callable = None, on_failed: Callable = None):
  405. """
  406. 设置回调函数
  407. Args:
  408. on_success: 上报成功回调
  409. on_failed: 上报失败回调
  410. """
  411. self.on_report_success = on_success
  412. self.on_report_failed = on_failed
  413. def get_stats(self) -> Dict[str, int]:
  414. """获取统计信息"""
  415. with self.stats_lock:
  416. return self.stats.copy()
  417. def is_enabled(self) -> bool:
  418. """检查是否启用"""
  419. return self.enabled
  420. # 全局单例
  421. _third_party_pusher_instance: Optional[ThirdPartyPusher] = None
  422. _third_party_pusher_lock = threading.Lock()
  423. def get_third_party_pusher(config: Dict[str, Any] = None) -> ThirdPartyPusher:
  424. """
  425. 获取第三方平台推送器实例(单例模式,线程安全)
  426. Args:
  427. config: 第三方平台配置
  428. Returns:
  429. ThirdPartyPusher 实例
  430. """
  431. global _third_party_pusher_instance
  432. if _third_party_pusher_instance is None:
  433. with _third_party_pusher_lock:
  434. if _third_party_pusher_instance is None:
  435. _third_party_pusher_instance = ThirdPartyPusher(config)
  436. return _third_party_pusher_instance
  437. def reset_third_party_pusher():
  438. """重置第三方平台推送器实例"""
  439. global _third_party_pusher_instance
  440. with _third_party_pusher_lock:
  441. if _third_party_pusher_instance is not None:
  442. _third_party_pusher_instance.stop()
  443. _third_party_pusher_instance = None