AiMeasurement.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\common\service\AiMeasurementService;
  5. use app\common\service\BodyProfileService;
  6. use app\api\validate\BodyProfile as BodyProfileValidate;
  7. use think\Cache;
  8. /**
  9. * AI测量API控制器
  10. */
  11. class AiMeasurement extends Api
  12. {
  13. protected $noNeedLogin = [];
  14. protected $noNeedRight = '*';
  15. // 第三方AI服务配置
  16. private $thirdPartyApiConfig = [
  17. 'url' => 'http://85cg744gf528.vicp.fun:25085/get_bodysize',
  18. 'timeout' => 120,
  19. 'connect_timeout' => 30
  20. ];
  21. /**
  22. * 开始AI身体测量分析
  23. */
  24. public function startAnalysis()
  25. {
  26. $params = $this->request->post();
  27. // 验证必要参数
  28. if (empty($params['profile_id'])) {
  29. $this->error('档案ID不能为空');
  30. }
  31. if (empty($params['photos']) || !is_array($params['photos'])) {
  32. $this->error('请上传身体照片');
  33. }
  34. try {
  35. // 验证档案归属
  36. $profile = \app\common\model\BodyProfile::where('id', $params['profile_id'])
  37. ->where('user_id', $this->auth->id)
  38. ->find();
  39. if (!$profile) {
  40. $this->error('档案不存在');
  41. }
  42. // 检查是否有正在处理的任务
  43. $existingTask = \think\Db::table('fa_ai_measurement_task')
  44. ->where('profile_id', $params['profile_id'])
  45. ->where('status', 'in', [0, 1]) // 待处理或处理中
  46. ->find();
  47. if ($existingTask) {
  48. $this->error('该档案已有正在处理的AI测量任务,请稍后再试');
  49. }
  50. // 验证照片格式
  51. $requiredPhotos = ['front', 'side', 'back'];
  52. foreach ($requiredPhotos as $angle) {
  53. if (empty($params['photos'][$angle])) {
  54. $this->error("请上传{$angle}角度的身体照片");
  55. }
  56. }
  57. // 创建AI测量任务
  58. $taskData = [
  59. 'profile_id' => $params['profile_id'],
  60. 'user_id' => $this->auth->id,
  61. 'photos' => json_encode($params['photos']),
  62. 'params' => json_encode([
  63. 'gender' => $profile->gender,
  64. 'height' => $profile->height,
  65. 'weight' => $profile->weight
  66. ]),
  67. 'priority' => $params['priority'] ?? 5,
  68. 'status' => 0, // 待处理
  69. 'createtime' => time(),
  70. 'updatetime' => time()
  71. ];
  72. $taskId = \think\Db::table('fa_ai_measurement_task')->insertGetId($taskData);
  73. // 立即处理任务(也可以放到队列中异步处理)
  74. $this->processTask($taskId);
  75. $this->success('AI测量分析已开始', [
  76. 'task_id' => $taskId,
  77. 'estimated_time' => 30 // 预计处理时间(秒)
  78. ]);
  79. } catch (\Exception $e) {
  80. $this->error($e->getMessage());
  81. }
  82. }
  83. /**
  84. * 获取AI测量结果
  85. */
  86. public function getResult()
  87. {
  88. $taskId = $this->request->get('task_id/d');
  89. $profileId = $this->request->get('profile_id/d');
  90. if (!$taskId && !$profileId) {
  91. $this->error('任务ID或档案ID不能为空');
  92. }
  93. try {
  94. $query = \think\Db::table('fa_ai_measurement_task')
  95. ->where('user_id', $this->auth->id);
  96. if ($taskId) {
  97. $query->where('id', $taskId);
  98. } else {
  99. $query->where('profile_id', $profileId)->order('id DESC');
  100. }
  101. $task = $query->find();
  102. if (!$task) {
  103. $this->error('任务不存在');
  104. }
  105. // 根据任务状态返回不同结果
  106. switch ($task['status']) {
  107. case 0: // 待处理
  108. $this->success('任务排队中', [
  109. 'status' => 'pending',
  110. 'message' => '任务正在排队等待处理'
  111. ]);
  112. break;
  113. case 1: // 处理中
  114. $this->success('正在分析中', [
  115. 'status' => 'processing',
  116. 'message' => 'AI正在分析您的身体照片,请稍候...',
  117. 'progress' => $this->estimateProgress($task)
  118. ]);
  119. break;
  120. case 2: // 完成
  121. $result = json_decode($task['result'], true);
  122. $this->success('分析完成', [
  123. 'status' => 'completed',
  124. 'data' => $this->formatMeasurementResult($result, $task['profile_id'])
  125. ]);
  126. break;
  127. case 3: // 失败
  128. $this->success('分析失败', [
  129. 'status' => 'failed',
  130. 'message' => $task['error_message'] ?: '分析过程中出现错误',
  131. 'can_retry' => $task['attempts'] < $task['max_attempts']
  132. ]);
  133. break;
  134. default:
  135. $this->error('未知的任务状态');
  136. }
  137. } catch (\Exception $e) {
  138. $this->error($e->getMessage());
  139. }
  140. }
  141. /**
  142. * 保存AI测量结果
  143. */
  144. public function saveResult()
  145. {
  146. $params = $this->request->post();
  147. if (empty($params['task_id'])) {
  148. $this->error('任务ID不能为空');
  149. }
  150. try {
  151. // 获取任务信息
  152. $task = \think\Db::table('fa_ai_measurement_task')
  153. ->where('id', $params['task_id'])
  154. ->where('user_id', $this->auth->id)
  155. ->where('status', 2) // 只有完成的任务才能保存
  156. ->find();
  157. if (!$task) {
  158. $this->error('任务不存在或未完成');
  159. }
  160. $result = json_decode($task['result'], true);
  161. if (!$result || !isset($result['measurements'])) {
  162. $this->error('测量结果数据异常');
  163. }
  164. // 保存测量数据
  165. $measurement = AiMeasurementService::saveMeasurementResult(
  166. $task['profile_id'],
  167. $result['measurements'],
  168. json_decode($task['photos'], true),
  169. $result['confidence'] ?? null
  170. );
  171. $this->success('测量结果已保存', [
  172. 'measurement_id' => $measurement->id
  173. ]);
  174. } catch (\Exception $e) {
  175. $this->error($e->getMessage());
  176. }
  177. }
  178. /**
  179. * 重新分析
  180. */
  181. public function retryAnalysis()
  182. {
  183. $taskId = $this->request->post('task_id/d');
  184. if (!$taskId) {
  185. $this->error('任务ID不能为空');
  186. }
  187. try {
  188. $task = \think\Db::table('fa_ai_measurement_task')
  189. ->where('id', $taskId)
  190. ->where('user_id', $this->auth->id)
  191. ->where('status', 3) // 失败的任务
  192. ->find();
  193. if (!$task) {
  194. $this->error('任务不存在或不允许重试');
  195. }
  196. if ($task['attempts'] >= $task['max_attempts']) {
  197. $this->error('重试次数已达上限');
  198. }
  199. // 重置任务状态
  200. \think\Db::table('fa_ai_measurement_task')
  201. ->where('id', $taskId)
  202. ->update([
  203. 'status' => 0,
  204. 'error_message' => '',
  205. 'updatetime' => time()
  206. ]);
  207. // 重新处理任务
  208. $this->processTask($taskId);
  209. $this->success('已重新开始分析');
  210. } catch (\Exception $e) {
  211. $this->error($e->getMessage());
  212. }
  213. }
  214. /**
  215. * 获取测量字段配置
  216. */
  217. public function getMeasurementConfig()
  218. {
  219. $gender = $this->request->get('gender/d', 1);
  220. try {
  221. $config = AiMeasurementService::getMeasurementDisplayConfig($gender);
  222. $this->success('获取成功', $config);
  223. } catch (\Exception $e) {
  224. $this->error($e->getMessage());
  225. }
  226. }
  227. /**
  228. * 获取AI测量素材配置
  229. * @ApiMethod (GET)
  230. * @ApiParams (name="mode", type="string", required=false, description="模式:selfie(自拍)、helper(帮拍)、common(通用)、all(全部)")
  231. */
  232. public function getMaterialConfig()
  233. {
  234. $mode = $this->request->get('mode', 'all');
  235. // try {
  236. $config = [];
  237. switch ($mode) {
  238. case 'selfie':
  239. $config = $this->getSelfieConfig();
  240. break;
  241. case 'helper':
  242. $config = $this->getHelperConfig();
  243. break;
  244. case 'common':
  245. $config = $this->getCommonConfig();
  246. break;
  247. case 'all':
  248. default:
  249. $config = [
  250. 'selfie' => $this->getSelfieConfig(),
  251. 'helper' => $this->getHelperConfig(),
  252. 'common' => $this->getCommonConfig()
  253. ];
  254. break;
  255. }
  256. $this->success('获取成功', $config);
  257. // } catch (\Exception $e) {
  258. // $this->error($e->getMessage());
  259. // }
  260. }
  261. /**
  262. * 获取自拍模式配置
  263. */
  264. private function getSelfieConfig()
  265. {
  266. return [
  267. 'enabled' => config('site.ai_measure_selfie_enabled'),
  268. 'intro_image' => $this->formatFileUrl(config('site.ai_measure_selfie_intro_image')),
  269. // 引导教程
  270. 'tutorial' => [
  271. 'images' => $this->parseImages(config('site.ai_measure_selfie_tutorial_images')),
  272. 'video' => $this->formatFileUrl(config('site.ai_measure_selfie_tutorial_video'))
  273. ],
  274. // 陀螺仪检测
  275. 'gyroscope' => [
  276. 'voice' => $this->formatFileUrl(config('site.ai_measure_selfie_gyro_voice')),
  277. 'example' => $this->formatFileUrl(config('site.ai_measure_selfie_gyro_example'))
  278. ],
  279. // 拍摄正面
  280. 'front_shooting' => [
  281. 'frame' => $this->formatFileUrl(config('site.ai_measure_selfie_front_frame')),
  282. 'demo' => $this->formatFileUrl(config('site.ai_measure_selfie_front_demo')),
  283. 'text' => config('site.ai_measure_selfie_front_text'),
  284. 'voice' => $this->formatFileUrl(config('site.ai_measure_selfie_front_voice'))
  285. ],
  286. // 拍摄侧面
  287. 'side_shooting' => [
  288. 'frame' => $this->formatFileUrl(config('site.ai_measure_selfie_side_frame')),
  289. 'demo' => $this->formatFileUrl(config('site.ai_measure_selfie_side_demo')),
  290. 'text' => config('site.ai_measure_selfie_side_text'),
  291. 'voice' => $this->formatFileUrl(config('site.ai_measure_selfie_side_voice'))
  292. ],
  293. // 拍摄正面侧平举
  294. 'arms_shooting' => [
  295. 'frame' => $this->formatFileUrl(config('site.ai_measure_selfie_arms_frame')),
  296. 'demo' => $this->formatFileUrl(config('site.ai_measure_selfie_arms_demo')),
  297. 'text' => config('site.ai_measure_selfie_arms_text'),
  298. 'voice' => $this->formatFileUrl(config('site.ai_measure_selfie_arms_voice'))
  299. ],
  300. // 拍摄过程素材
  301. 'process_materials' => [
  302. 'countdown_voice' => $this->formatFileUrl(config('site.ai_measure_selfie_countdown_voice')),
  303. 'timer_sound' => $this->formatFileUrl(config('site.ai_measure_selfie_timer_sound')),
  304. 'complete_sound' => $this->formatFileUrl(config('site.ai_measure_selfie_complete_sound')),
  305. 'next_voice' => $this->formatFileUrl(config('site.ai_measure_selfie_next_voice')),
  306. 'finish_voice' => $this->formatFileUrl(config('site.ai_measure_selfie_finish_voice'))
  307. ]
  308. ];
  309. }
  310. /**
  311. * 获取帮拍模式配置
  312. */
  313. private function getHelperConfig()
  314. {
  315. return [
  316. 'enabled' => config('site.ai_measure_helper_enabled'),
  317. 'intro_image' => $this->formatFileUrl(config('site.ai_measure_helper_intro_image')),
  318. // 引导教程
  319. 'tutorial' => [
  320. 'images' => $this->parseImages(config('site.ai_measure_helper_tutorial_images')),
  321. 'video' => $this->formatFileUrl(config('site.ai_measure_helper_tutorial_video'))
  322. ],
  323. // 陀螺仪检测
  324. 'gyroscope' => [
  325. 'voice' => $this->formatFileUrl(config('site.ai_measure_helper_gyro_voice')),
  326. 'example' => $this->formatFileUrl(config('site.ai_measure_helper_gyro_example'))
  327. ],
  328. // 拍摄正面
  329. 'front_shooting' => [
  330. 'frame' => $this->formatFileUrl(config('site.ai_measure_helper_front_frame')),
  331. 'demo' => $this->formatFileUrl(config('site.ai_measure_helper_front_demo')),
  332. 'text' => config('site.ai_measure_helper_front_text'),
  333. 'voice' => $this->formatFileUrl(config('site.ai_measure_helper_front_voice'))
  334. ],
  335. // 拍摄侧面
  336. 'side_shooting' => [
  337. 'frame' => $this->formatFileUrl(config('site.ai_measure_helper_side_frame')),
  338. 'demo' => $this->formatFileUrl(config('site.ai_measure_helper_side_demo')),
  339. 'text' => config('site.ai_measure_helper_side_text'),
  340. 'voice' => $this->formatFileUrl(config('site.ai_measure_helper_side_voice'))
  341. ],
  342. // 拍摄正面侧平举
  343. 'arms_shooting' => [
  344. 'frame' => $this->formatFileUrl(config('site.ai_measure_helper_arms_frame')),
  345. 'demo' => $this->formatFileUrl(config('site.ai_measure_helper_arms_demo')),
  346. 'text' => config('site.ai_measure_helper_arms_text'),
  347. 'voice' => $this->formatFileUrl(config('site.ai_measure_helper_arms_voice'))
  348. ],
  349. // 拍摄过程素材
  350. 'process_materials' => [
  351. 'countdown_voice' => cdnurl(config('site.ai_measure_helper_countdown_voice')),
  352. 'timer_sound' => $this->formatFileUrl(config('site.ai_measure_helper_timer_sound')),
  353. 'complete_sound' => $this->formatFileUrl(config('site.ai_measure_helper_complete_sound')),
  354. 'next_voice' => $this->formatFileUrl(config('site.ai_measure_helper_next_voice')),
  355. 'finish_voice' => $this->formatFileUrl(config('site.ai_measure_helper_finish_voice'))
  356. ]
  357. ];
  358. }
  359. /**
  360. * 获取通用配置
  361. */
  362. private function getCommonConfig()
  363. {
  364. return [
  365. 'welcome_notice' => config('site.ai_measure_welcome_notice'),
  366. 'privacy_notice' => config('site.ai_measure_privacy_notice'),
  367. 'accuracy_disclaimer' => config('site.ai_measure_accuracy_disclaimer'),
  368. 'demo_images' => [
  369. 'front_demo' => $this->formatFileUrl(config('site.ai_measure_common_front_demo')),
  370. 'side_demo' => $this->formatFileUrl(config('site.ai_measure_common_side_demo')),
  371. 'arms_demo' => $this->formatFileUrl(config('site.ai_measure_common_arms_demo'))
  372. ]
  373. ];
  374. }
  375. /**
  376. * 格式化文件URL
  377. */
  378. private function formatFileUrl($url)
  379. {
  380. if (empty($url)) {
  381. return null;
  382. }
  383. return cdnurl($url);
  384. }
  385. /**
  386. * 解析图片集合
  387. */
  388. private function parseImages($images)
  389. {
  390. if (empty($images)) {
  391. return [];
  392. }
  393. // 如果是JSON格式的字符串,解析为数组
  394. if (is_string($images)) {
  395. $imageArray = json_decode($images, true);
  396. if (json_last_error() === JSON_ERROR_NONE && is_array($imageArray)) {
  397. $images = $imageArray;
  398. } else {
  399. // 如果不是JSON,可能是逗号分隔的字符串
  400. $images = explode(',', $images);
  401. }
  402. }
  403. if (!is_array($images)) {
  404. return [];
  405. }
  406. // 格式化每个图片URL
  407. return array_map(function($url) {
  408. return $this->formatFileUrl(trim($url));
  409. }, array_filter($images));
  410. }
  411. /**
  412. * 直接调用第三方AI测量服务
  413. * @ApiMethod (POST)
  414. * @ApiParams (name="profile_id", type="integer", required=true, description="档案ID")
  415. * @ApiParams (name="photos", type="object", required=true, description="身体照片对象")
  416. * @ApiParams (name="photos.front", type="string", required=true, description="正面照片URL")
  417. * @ApiParams (name="photos.side", type="string", required=true, description="侧面照片URL")
  418. * @ApiParams (name="photos.back", type="string", required=true, description="背面照片URL")
  419. */
  420. public function measurementDirect()
  421. {
  422. $params = $this->request->post();
  423. // 验证必要参数
  424. if (empty($params['profile_id'])) {
  425. $this->error('档案ID不能为空');
  426. }
  427. // if (empty($params['photos']) || !is_array($params['photos'])) {
  428. // $this->error('请上传身体照片');
  429. // }
  430. // try {
  431. // 验证档案归属
  432. $profile = \app\common\model\BodyProfile::where('id', $params['profile_id'])
  433. ->where('user_id', $this->auth->id)
  434. ->find();
  435. if (!$profile) {
  436. $this->error('档案不存在');
  437. }
  438. // 验证照片格式
  439. // $requiredPhotos = ['front', 'side', 'back'];
  440. // foreach ($requiredPhotos as $angle) {
  441. // if (empty($params['photos'][$angle])) {
  442. // $this->error("请上传{$angle}角度的身体照片");
  443. // }
  444. // }
  445. // 直接使用档案的
  446. $photos = $profile->body_photos_text;
  447. // 安全调用第三方AI服务 - 确保身高为数字格式
  448. $heightCm = is_numeric($profile->height) ? floatval($profile->height) : 0;
  449. $measurements = $this->safeCallThirdPartyAiService(
  450. $photos,
  451. $heightCm
  452. );
  453. // echo "<pre>";
  454. // print_r($measurements);
  455. // echo "</pre>";
  456. // exit;
  457. // 处理结果
  458. // $result = [
  459. // 'measurements' => $measurements,
  460. // 'confidence' => $measurements['_confidence'] ?? 0.8,
  461. // 'warnings' => $measurements['_warnings'] ?? []
  462. // ];
  463. // 清理内部字段
  464. // unset($result['measurements']['_confidence']);
  465. // unset($result['measurements']['_warnings']);
  466. // 格式化结果用于展示
  467. //$formattedResult = $this->formatMeasurementResult($result, $params['profile_id']);
  468. $measurements['height'] = $profile->height;
  469. $measurements['weight'] = $profile->weight;
  470. $this->success('AI测量完成', $measurements);
  471. // } catch (\Exception $e) {
  472. // $this->error($e->getMessage());
  473. // }
  474. }
  475. /**
  476. * 调用第三方AI测量接口
  477. */
  478. private function callThirdPartyAiService($photos, $height)
  479. {
  480. // 第三方API配置
  481. $apiUrl = $this->thirdPartyApiConfig['url'];
  482. try {
  483. // 准备请求数据 - 确保身高为纯数字(厘米)
  484. $heightValue = is_numeric($height) ? floatval($height) : 0;
  485. $requestData = [
  486. 'height' => $heightValue
  487. ];
  488. // 处理照片数据 - 转换为base64格式
  489. if (isset($photos['front'])) {
  490. $requestData['image1'] = $this->convertImageToBase64($photos['front']);
  491. }
  492. if (isset($photos['side'])) {
  493. $requestData['image2'] = $this->convertImageToBase64($photos['side']);
  494. }
  495. if (isset($photos['back'])) {
  496. $requestData['image3'] = $this->convertImageToBase64($photos['back']);
  497. }
  498. // 记录请求日志(不包含图片数据)
  499. // $logData = [
  500. // 'url' => $apiUrl,
  501. // 'height' => $requestData['height'],
  502. // 'image_count' => count(array_filter([
  503. // isset($requestData['image1']),
  504. // isset($requestData['image2']),
  505. // isset($requestData['image3'])
  506. // ]))
  507. // ];
  508. // 记录请求日志(包含身高和图片base64数据的前50个字符)
  509. $logData = [
  510. 'url' => $apiUrl,
  511. 'height' => $heightValue . 'cm',
  512. 'image1_preview' => isset($requestData['image1']) ? substr($requestData['image1'], 0, 50) . '...' : null,
  513. 'image2_preview' => isset($requestData['image2']) ? substr($requestData['image2'], 0, 50) . '...' : null,
  514. 'image3_preview' => isset($requestData['image3']) ? substr($requestData['image3'], 0, 50) . '...' : null,
  515. 'request_data_size' => strlen(json_encode($requestData)) . ' bytes'
  516. ];
  517. \think\Log::info('Calling third party AI service: ' . json_encode($logData));
  518. // 发送POST请求
  519. $ch = curl_init();
  520. curl_setopt_array($ch, [
  521. CURLOPT_URL => $apiUrl,
  522. CURLOPT_POST => true,
  523. CURLOPT_POSTFIELDS => json_encode($requestData),
  524. CURLOPT_RETURNTRANSFER => true,
  525. CURLOPT_TIMEOUT => $this->thirdPartyApiConfig['timeout'],
  526. CURLOPT_CONNECTTIMEOUT => $this->thirdPartyApiConfig['connect_timeout'],
  527. CURLOPT_HTTPHEADER => [
  528. 'Content-Type: application/json',
  529. 'Accept: application/json'
  530. ],
  531. CURLOPT_SSL_VERIFYPEER => false,
  532. CURLOPT_SSL_VERIFYHOST => false
  533. ]);
  534. $response = curl_exec($ch);
  535. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  536. $error = curl_error($ch);
  537. curl_close($ch);
  538. if ($error) {
  539. throw new \Exception('请求第三方AI服务失败: ' . $error);
  540. }
  541. // 处理各种HTTP错误状态
  542. if ($httpCode >= 500) {
  543. throw new \Exception('第三方AI服务内部错误: HTTP ' . $httpCode);
  544. } elseif ($httpCode >= 400) {
  545. throw new \Exception('第三方AI服务请求错误: HTTP ' . $httpCode);
  546. } elseif ($httpCode !== 200) {
  547. throw new \Exception('第三方AI服务返回异常状态: HTTP ' . $httpCode);
  548. }
  549. \think\Log::info('Third party AI service response: ' .$response);
  550. // 检查响应内容
  551. if (empty($response)) {
  552. throw new \Exception('第三方AI服务返回空响应');
  553. }
  554. $result = json_decode($response, true);
  555. if (json_last_error() !== JSON_ERROR_NONE) {
  556. throw new \Exception('第三方AI服务返回数据格式错误');
  557. }
  558. // 记录API响应信息
  559. // $responseLog = [
  560. // 'http_code' => $httpCode,
  561. // 'response_size' => strlen($response) . ' bytes',
  562. // 'has_body_size' => isset($result['body_size']),
  563. // 'body_size_fields' => isset($result['body_size']) ? array_keys($result['body_size']) : [],
  564. // 'response_preview' => substr($response, 0, 200) . '...'
  565. // ];
  566. // 处理返回的测量数据
  567. // echo "<pre>";
  568. // print_r($result);
  569. // echo "</pre>";
  570. // exit;
  571. return $this->processMeasurementData($result);
  572. } catch (\Exception $e) {
  573. // 记录错误日志
  574. \think\Log::error('Third party AI service error: ' . $e->getMessage());
  575. throw $e;
  576. }
  577. // 如果执行到这里说明没有异常处理,直接返回处理结果
  578. }
  579. /**
  580. * 安全调用第三方AI服务(带异常处理和默认返回)
  581. */
  582. private function safeCallThirdPartyAiService($photos, $height)
  583. {
  584. try {
  585. return $this->callThirdPartyAiService($photos, $height);
  586. } catch (\Exception $e) {
  587. // 记录错误日志
  588. \think\Log::error('Third party AI service error, returning default data: ' . $e->getMessage());
  589. // 返回默认的空测量数据
  590. return $this->getDefaultMeasurementData();
  591. }
  592. }
  593. /**
  594. * 获取默认的空测量数据
  595. */
  596. private function getDefaultMeasurementData()
  597. {
  598. // 返回所有映射字段的空值(使用空字符串)
  599. return [
  600. 'chest'=>'', // 净胸围 → 胸围
  601. 'waist'=>'', // 净腰围 → 腰围
  602. 'hip'=>'', // 净臀围 → 实际臀围
  603. //'thigh', // 净腿根 → 大腿围
  604. 'knee'=>'', // 净膝围 → 膝围
  605. 'calf'=>'', // 净小腿围 → 小腿围
  606. 'arm_length'=>'', // 净手臂长 → 臂长
  607. 'wrist'=>'', // 净手腕围 → 手腕围
  608. 'pants_length'=>'', // 腿长 → 腿长
  609. 'belly_belt'=>'', // 净肚围 → 肚围
  610. 'shoulder_width'=>'', // 净肩宽 → 肩宽
  611. 'leg_root'=>'', // 净腿根 → 大腿围
  612. 'neck'=>'', // 净颈围 → 颈围
  613. 'inseam'=>'', // 内腿长 → 内腿长
  614. 'upper_arm'=>'', // 净上臂围 → 上臂围
  615. 'ankle'=>'', // 净脚踝围 → 脚踝围
  616. 'waist_lower'=>'', // 净小腹围 → 下腰围
  617. 'mid_waist'=>'', // 净中腰 → 中腰围
  618. '_confidence' => 0.0,
  619. '_warnings' => ['第三方AI服务暂时不可用,返回默认数据']
  620. ];
  621. }
  622. /**
  623. * 测试接口 - 返回模拟的第三方API测量数据
  624. * @ApiMethod (POST)
  625. * @ApiParams (name="profile_id", type="integer", required=true, description="档案ID")
  626. */
  627. public function testMeasurementData()
  628. {
  629. $params = $this->request->post();
  630. // 验证必要参数
  631. if (empty($params['profile_id'])) {
  632. $this->error('档案ID不能为空');
  633. }
  634. // 验证档案归属
  635. $profile = \app\common\model\BodyProfile::where('id', $params['profile_id'])
  636. ->where('user_id', $this->auth->id)
  637. ->find();
  638. if (!$profile) {
  639. $this->error('档案不存在');
  640. }
  641. // 模拟第三方API返回的数据
  642. $mockApiResult = [
  643. "body_size" => [
  644. "datuigen" => 56.973762220946064,
  645. "duwei" => 71.86294164495045,
  646. "jiankuan" => 44.99356951672863,
  647. "jiaohuai" => 20.995062499529606,
  648. "jingwei" => 36.973537078225604,
  649. "neitui" => 67.99506048261769,
  650. "shangbi" => 23.285375591374667,
  651. "shoubichang" => 61.1834335984307,
  652. "shouwanwei" => 16.0697059847192,
  653. "tuichang" => 73.9800462219755,
  654. "tunwei" => 90.08082593388505,
  655. "xiaofu" => 70.98010845587423,
  656. "xiaotuiwei" => 37.2761443409742,
  657. "xigai" => 34.990971006868364,
  658. "xiongwei" => 81.85738385794711,
  659. "yaowei" => 72.93800974219818,
  660. "zhongyao" => 70.99945416888724
  661. ],
  662. "confidence" => 0.85
  663. ];
  664. // 处理测量数据
  665. $measurements = $this->processMeasurementData($mockApiResult);
  666. // 处理结果
  667. $result = [
  668. 'measurements' => $measurements,
  669. 'confidence' => $measurements['_confidence'] ?? 0.8,
  670. 'warnings' => $measurements['_warnings'] ?? []
  671. ];
  672. // 清理内部字段
  673. unset($result['measurements']['_confidence']);
  674. unset($result['measurements']['_warnings']);
  675. // 格式化结果用于展示
  676. $formattedResult = $this->formatMeasurementResult($result, $params['profile_id']);
  677. $this->success('测试数据返回成功', [
  678. 'original_api_data' => $mockApiResult['body_size'],
  679. 'mapped_measurements' => $result['measurements'],
  680. 'formatted_result' => $formattedResult
  681. ]);
  682. }
  683. /**
  684. * 将图片URL转换为base64格式
  685. */
  686. private function convertImageToBase64($imageUrl)
  687. {
  688. try {
  689. // 如果已经是base64格式,直接返回
  690. if (strpos($imageUrl, 'data:image') === 0) {
  691. return $imageUrl;
  692. }
  693. // 如果是相对路径,转换为绝对路径
  694. if (strpos($imageUrl, 'http') !== 0) {
  695. $imageUrl = request()->domain() . $imageUrl;
  696. }
  697. // 获取图片数据
  698. $ch = curl_init();
  699. curl_setopt_array($ch, [
  700. CURLOPT_URL => $imageUrl,
  701. CURLOPT_RETURNTRANSFER => true,
  702. CURLOPT_TIMEOUT => 30,
  703. CURLOPT_CONNECTTIMEOUT => 10,
  704. CURLOPT_FOLLOWLOCATION => true,
  705. CURLOPT_SSL_VERIFYPEER => false,
  706. CURLOPT_SSL_VERIFYHOST => false,
  707. CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
  708. CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  709. CURLOPT_HTTPHEADER => [
  710. 'Accept: image/webp,image/apng,image/*,*/*;q=0.8',
  711. 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8',
  712. 'Cache-Control: no-cache',
  713. ]
  714. ]);
  715. $imageData = curl_exec($ch);
  716. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  717. $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
  718. $curlError = curl_error($ch);
  719. $effectiveUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  720. curl_close($ch);
  721. // 详细的错误处理
  722. if ($curlError) {
  723. throw new \Exception("网络请求失败: {$curlError} (URL: {$imageUrl})");
  724. }
  725. if ($httpCode !== 200) {
  726. throw new \Exception("图片访问失败,HTTP状态码: {$httpCode} (URL: {$imageUrl})");
  727. }
  728. if (!$imageData || strlen($imageData) === 0) {
  729. throw new \Exception("图片数据为空 (URL: {$imageUrl})");
  730. }
  731. // 验证图片数据是否有效
  732. if (!@getimagesizefromstring($imageData)) {
  733. throw new \Exception("获取的数据不是有效的图片格式 (URL: {$imageUrl})");
  734. }
  735. // 确定MIME类型
  736. if (strpos($contentType, 'image/') === 0) {
  737. $mimeType = $contentType;
  738. } else {
  739. // 通过文件扩展名推断
  740. $extension = strtolower(pathinfo(parse_url($imageUrl, PHP_URL_PATH), PATHINFO_EXTENSION));
  741. $mimeTypes = [
  742. 'jpg' => 'image/jpeg',
  743. 'jpeg' => 'image/jpeg',
  744. 'png' => 'image/png',
  745. 'gif' => 'image/gif',
  746. 'webp' => 'image/webp',
  747. 'bmp' => 'image/bmp'
  748. ];
  749. $mimeType = $mimeTypes[$extension] ?? 'image/jpeg';
  750. }
  751. // 转换为base64
  752. $base64 = base64_encode($imageData);
  753. return "data:{$mimeType};base64,{$base64}";
  754. } catch (\Exception $e) {
  755. \think\Log::error('Convert image to base64 error: ' . $e->getMessage() . ' URL: ' . $imageUrl);
  756. throw new \Exception('图片转换失败: ' . $e->getMessage());
  757. }
  758. }
  759. /**
  760. * 处理第三方API返回的测量数据
  761. */
  762. private function processMeasurementData($apiResult)
  763. {
  764. // 根据第三方API的返回格式处理数据
  765. // 这里需要根据实际的API返回格式进行调整
  766. $measurements = [];
  767. try {
  768. // 假设API返回格式类似:
  769. // {
  770. // "status": "success",
  771. // "data": {
  772. // "chest": 95.5,
  773. // "waist": 75.2,
  774. // "hip": 98.7,
  775. // ...
  776. // },
  777. // "confidence": 0.85
  778. // }
  779. // 检查返回数据结构 - 可能直接包含body_size字段
  780. if (isset($apiResult['body_size'])) {
  781. $data = $apiResult['body_size'];
  782. $hasValidData = true;
  783. } elseif (isset($apiResult['status']) && $apiResult['status'] === 'success') {
  784. $data = $apiResult['data'] ?? [];
  785. $hasValidData = true;
  786. } else {
  787. // 尝试直接使用返回的数据
  788. $data = $apiResult;
  789. $hasValidData = !empty($data) && is_array($data);
  790. }
  791. if ($hasValidData) {
  792. // 映射字段名(根据第三方API返回的字段名进行映射)
  793. $fieldMapping = [
  794. 'xiongwei' => 'chest', // 净胸围 → 胸围
  795. 'yaowei' => 'waist', // 净腰围 → 腰围
  796. 'tunwei' => 'hip', // 净臀围 → 实际臀围
  797. //'datuigen' => 'thigh', // 净腿根 → 大腿围
  798. 'xigai' => 'knee', // 净膝围 → 膝围
  799. 'xiaotuiwei' => 'calf', // 净小腿围 → 小腿围
  800. 'shoubichang' => 'arm_length', // 净手臂长 → 臂长
  801. 'shouwanwei' => 'wrist', // 净手腕围 → 手腕围
  802. 'tuichang' => 'pants_length', // 腿长 → 腿长
  803. 'duwei' => 'belly_belt', // 净肚围 → 肚围
  804. 'jiankuan' => 'shoulder_width', // 净肩宽 → 肩宽
  805. 'datuigen' => 'leg_root', // 净腿根 → 大腿围
  806. 'jingwei' => 'neck', // 净颈围 → 颈围
  807. 'neitui' => 'inseam', // 内腿长 → 内腿长
  808. 'shangbi' => 'upper_arm', // 净上臂围 → 上臂围
  809. 'jiaohuai' => 'ankle', // 净脚踝围 → 脚踝围
  810. 'xiaofu' => 'waist_lower', // 净小腹围 → 下腰围
  811. 'zhongyao' => 'mid_waist', // 净中腰 → 中腰围
  812. ];
  813. foreach ($fieldMapping as $apiField => $localField) {
  814. if (isset($data[$apiField]) && is_numeric($data[$apiField])) {
  815. $measurements[$localField] = round(floatval($data[$apiField]), 1);
  816. }
  817. }
  818. // 设置置信度和警告信息
  819. $measurements['_confidence'] = $apiResult['confidence'] ?? 0.8;
  820. $measurements['_warnings'] = $apiResult['warnings'] ?? [];
  821. // 如果没有测量数据,添加默认警告
  822. if (count($measurements) === 2) { // 只有_confidence和_warnings
  823. $measurements['_warnings'][] = '第三方AI服务未返回有效的测量数据';
  824. }
  825. } else {
  826. // API返回错误
  827. $errorMsg = $apiResult['message'] ?? $apiResult['error'] ?? '第三方AI服务返回未知错误';
  828. throw new \Exception($errorMsg);
  829. }
  830. } catch (\Exception $e) {
  831. // 处理异常,返回错误信息
  832. $measurements['_confidence'] = 0;
  833. $measurements['_warnings'] = ['数据处理失败: ' . $e->getMessage()];
  834. }
  835. return $measurements;
  836. }
  837. /**
  838. * 处理AI测量任务
  839. */
  840. private function processTask($taskId)
  841. {
  842. try {
  843. // 更新任务状态为处理中
  844. \think\Db::table('fa_ai_measurement_task')
  845. ->where('id', $taskId)
  846. ->update([
  847. 'status' => 1,
  848. 'started_at' => time(),
  849. 'attempts' => \think\Db::raw('attempts + 1'),
  850. 'updatetime' => time()
  851. ]);
  852. // 获取任务详情
  853. $task = \think\Db::table('fa_ai_measurement_task')->where('id', $taskId)->find();
  854. $photos = json_decode($task['photos'], true);
  855. $params = json_decode($task['params'], true);
  856. // 安全调用第三方AI分析服务 - 确保身高为数字格式
  857. $heightCm = is_numeric($params['height']) ? floatval($params['height']) : 0;
  858. $measurements = $this->safeCallThirdPartyAiService(
  859. $photos,
  860. $heightCm
  861. );
  862. // 处理结果
  863. $result = [
  864. 'measurements' => $measurements,
  865. 'confidence' => $measurements['_confidence'] ?? 0.8,
  866. 'warnings' => $measurements['_warnings'] ?? []
  867. ];
  868. // 清理内部字段
  869. unset($result['measurements']['_confidence']);
  870. unset($result['measurements']['_warnings']);
  871. // 更新任务状态为完成
  872. \think\Db::table('fa_ai_measurement_task')
  873. ->where('id', $taskId)
  874. ->update([
  875. 'status' => 2,
  876. 'result' => json_encode($result),
  877. 'completed_at' => time(),
  878. 'updatetime' => time()
  879. ]);
  880. } catch (\Exception $e) {
  881. // 更新任务状态为失败
  882. \think\Db::table('fa_ai_measurement_task')
  883. ->where('id', $taskId)
  884. ->update([
  885. 'status' => 3,
  886. 'error_message' => $e->getMessage(),
  887. 'updatetime' => time()
  888. ]);
  889. }
  890. }
  891. /**
  892. * 估算处理进度
  893. */
  894. private function estimateProgress($task)
  895. {
  896. $startTime = $task['started_at'];
  897. $currentTime = time();
  898. $elapsedTime = $currentTime - $startTime;
  899. // 假设总处理时间为30秒
  900. $totalTime = 30;
  901. $progress = min(95, ($elapsedTime / $totalTime) * 100);
  902. return round($progress);
  903. }
  904. /**
  905. * 格式化测量结果用于展示
  906. */
  907. private function formatMeasurementResult($result, $profileId)
  908. {
  909. $profile = \app\common\model\BodyProfile::find($profileId);
  910. $measurements = $result['measurements'];
  911. // 获取显示配置
  912. $displayConfig = AiMeasurementService::getMeasurementDisplayConfig($profile->gender);
  913. // 格式化数据
  914. $formattedData = [
  915. 'profile' => [
  916. 'id' => $profile->id,
  917. 'name' => $profile->profile_name,
  918. 'gender' => $profile->gender,
  919. 'height' => $profile->height,
  920. 'weight' => $profile->weight
  921. ],
  922. 'measurements' => [],
  923. 'display_config' => $displayConfig,
  924. 'confidence' => $result['confidence'] ?? 0,
  925. 'warnings' => $result['warnings'] ?? []
  926. ];
  927. // 组织测量数据
  928. foreach ($displayConfig as $field => $config) {
  929. $value = isset($measurements[$field]) && $measurements[$field] > 0
  930. ? $measurements[$field]
  931. : null;
  932. $formattedData['measurements'][$field] = [
  933. 'label' => $config['label'],
  934. 'value' => $value,
  935. 'unit' => 'cm',
  936. 'position' => $config['position'],
  937. 'side' => $config['side']
  938. ];
  939. }
  940. // 添加基础数据表格
  941. $formattedData['basic_data'] = [
  942. ['label' => '身高', 'value' => $profile->height, 'unit' => 'cm'],
  943. ['label' => '体重', 'value' => $profile->weight, 'unit' => 'kg'],
  944. ];
  945. // 添加测量数据表格
  946. $tableData = [];
  947. $fields = array_keys($measurements);
  948. $chunks = array_chunk($fields, 2);
  949. foreach ($chunks as $chunk) {
  950. $row = [];
  951. foreach ($chunk as $field) {
  952. if (isset($displayConfig[$field])) {
  953. $row[] = [
  954. 'label' => $displayConfig[$field]['label'],
  955. 'value' => $measurements[$field] ?? null,
  956. 'unit' => 'cm'
  957. ];
  958. }
  959. }
  960. if (!empty($row)) {
  961. $tableData[] = $row;
  962. }
  963. }
  964. $formattedData['table_data'] = $tableData;
  965. return $formattedData;
  966. }
  967. }