AiMeasurement.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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 (POST)
  230. * @ApiParams (name="profile_id", type="integer", required=true, description="档案ID")
  231. * @ApiParams (name="photos", type="object", required=true, description="身体照片对象")
  232. * @ApiParams (name="photos.front", type="string", required=true, description="正面照片URL")
  233. * @ApiParams (name="photos.side", type="string", required=true, description="侧面照片URL")
  234. * @ApiParams (name="photos.back", type="string", required=true, description="背面照片URL")
  235. */
  236. public function measurementDirect()
  237. {
  238. $params = $this->request->post();
  239. // 验证必要参数
  240. if (empty($params['profile_id'])) {
  241. $this->error('档案ID不能为空');
  242. }
  243. if (empty($params['photos']) || !is_array($params['photos'])) {
  244. $this->error('请上传身体照片');
  245. }
  246. // try {
  247. // 验证档案归属
  248. $profile = \app\common\model\BodyProfile::where('id', $params['profile_id'])
  249. ->where('user_id', $this->auth->id)
  250. ->find();
  251. if (!$profile) {
  252. $this->error('档案不存在');
  253. }
  254. // 验证照片格式
  255. $requiredPhotos = ['front', 'side', 'back'];
  256. foreach ($requiredPhotos as $angle) {
  257. if (empty($params['photos'][$angle])) {
  258. $this->error("请上传{$angle}角度的身体照片");
  259. }
  260. }
  261. // 安全调用第三方AI服务 - 确保身高为数字格式
  262. $heightCm = is_numeric($profile->height) ? floatval($profile->height) : 0;
  263. $measurements = $this->safeCallThirdPartyAiService(
  264. $params['photos'],
  265. $heightCm
  266. );
  267. // echo "<pre>";
  268. // print_r($measurements);
  269. // echo "</pre>";
  270. // exit;
  271. // 处理结果
  272. // $result = [
  273. // 'measurements' => $measurements,
  274. // 'confidence' => $measurements['_confidence'] ?? 0.8,
  275. // 'warnings' => $measurements['_warnings'] ?? []
  276. // ];
  277. // 清理内部字段
  278. // unset($result['measurements']['_confidence']);
  279. // unset($result['measurements']['_warnings']);
  280. // 格式化结果用于展示
  281. //$formattedResult = $this->formatMeasurementResult($result, $params['profile_id']);
  282. $this->success('AI测量完成', $measurements);
  283. // } catch (\Exception $e) {
  284. // $this->error($e->getMessage());
  285. // }
  286. }
  287. /**
  288. * 调用第三方AI测量接口
  289. */
  290. private function callThirdPartyAiService($photos, $height)
  291. {
  292. // 第三方API配置
  293. $apiUrl = $this->thirdPartyApiConfig['url'];
  294. try {
  295. // 准备请求数据 - 确保身高为纯数字(厘米)
  296. $heightValue = is_numeric($height) ? floatval($height) : 0;
  297. $requestData = [
  298. 'height' => $heightValue
  299. ];
  300. // 处理照片数据 - 转换为base64格式
  301. if (isset($photos['front'])) {
  302. $requestData['image1'] = $this->convertImageToBase64($photos['front']);
  303. }
  304. if (isset($photos['side'])) {
  305. $requestData['image2'] = $this->convertImageToBase64($photos['side']);
  306. }
  307. if (isset($photos['back'])) {
  308. $requestData['image3'] = $this->convertImageToBase64($photos['back']);
  309. }
  310. // 记录请求日志(不包含图片数据)
  311. // $logData = [
  312. // 'url' => $apiUrl,
  313. // 'height' => $requestData['height'],
  314. // 'image_count' => count(array_filter([
  315. // isset($requestData['image1']),
  316. // isset($requestData['image2']),
  317. // isset($requestData['image3'])
  318. // ]))
  319. // ];
  320. // 记录请求日志(包含身高和图片base64数据的前50个字符)
  321. $logData = [
  322. 'url' => $apiUrl,
  323. 'height' => $heightValue . 'cm',
  324. 'image1_preview' => isset($requestData['image1']) ? substr($requestData['image1'], 0, 50) . '...' : null,
  325. 'image2_preview' => isset($requestData['image2']) ? substr($requestData['image2'], 0, 50) . '...' : null,
  326. 'image3_preview' => isset($requestData['image3']) ? substr($requestData['image3'], 0, 50) . '...' : null,
  327. 'request_data_size' => strlen(json_encode($requestData)) . ' bytes'
  328. ];
  329. \think\Log::info('Calling third party AI service: ' . json_encode($logData));
  330. // 发送POST请求
  331. $ch = curl_init();
  332. curl_setopt_array($ch, [
  333. CURLOPT_URL => $apiUrl,
  334. CURLOPT_POST => true,
  335. CURLOPT_POSTFIELDS => json_encode($requestData),
  336. CURLOPT_RETURNTRANSFER => true,
  337. CURLOPT_TIMEOUT => $this->thirdPartyApiConfig['timeout'],
  338. CURLOPT_CONNECTTIMEOUT => $this->thirdPartyApiConfig['connect_timeout'],
  339. CURLOPT_HTTPHEADER => [
  340. 'Content-Type: application/json',
  341. 'Accept: application/json'
  342. ],
  343. CURLOPT_SSL_VERIFYPEER => false,
  344. CURLOPT_SSL_VERIFYHOST => false
  345. ]);
  346. $response = curl_exec($ch);
  347. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  348. $error = curl_error($ch);
  349. curl_close($ch);
  350. if ($error) {
  351. throw new \Exception('请求第三方AI服务失败: ' . $error);
  352. }
  353. // 处理各种HTTP错误状态
  354. if ($httpCode >= 500) {
  355. throw new \Exception('第三方AI服务内部错误: HTTP ' . $httpCode);
  356. } elseif ($httpCode >= 400) {
  357. throw new \Exception('第三方AI服务请求错误: HTTP ' . $httpCode);
  358. } elseif ($httpCode !== 200) {
  359. throw new \Exception('第三方AI服务返回异常状态: HTTP ' . $httpCode);
  360. }
  361. // 检查响应内容
  362. if (empty($response)) {
  363. throw new \Exception('第三方AI服务返回空响应');
  364. }
  365. $result = json_decode($response, true);
  366. if (json_last_error() !== JSON_ERROR_NONE) {
  367. throw new \Exception('第三方AI服务返回数据格式错误');
  368. }
  369. // 记录API响应信息
  370. $responseLog = [
  371. 'http_code' => $httpCode,
  372. 'response_size' => strlen($response) . ' bytes',
  373. 'has_body_size' => isset($result['body_size']),
  374. 'body_size_fields' => isset($result['body_size']) ? array_keys($result['body_size']) : [],
  375. 'response_preview' => substr($response, 0, 200) . '...'
  376. ];
  377. \think\Log::info('Third party AI service response: ' . json_encode($responseLog));
  378. // 处理返回的测量数据
  379. // echo "<pre>";
  380. // print_r($result);
  381. // echo "</pre>";
  382. // exit;
  383. return $this->processMeasurementData($result);
  384. } catch (\Exception $e) {
  385. // 记录错误日志
  386. \think\Log::error('Third party AI service error: ' . $e->getMessage());
  387. throw $e;
  388. }
  389. // 如果执行到这里说明没有异常处理,直接返回处理结果
  390. }
  391. /**
  392. * 安全调用第三方AI服务(带异常处理和默认返回)
  393. */
  394. private function safeCallThirdPartyAiService($photos, $height)
  395. {
  396. try {
  397. return $this->callThirdPartyAiService($photos, $height);
  398. } catch (\Exception $e) {
  399. // 记录错误日志
  400. \think\Log::error('Third party AI service error, returning default data: ' . $e->getMessage());
  401. // 返回默认的空测量数据
  402. return $this->getDefaultMeasurementData();
  403. }
  404. }
  405. /**
  406. * 获取默认的空测量数据
  407. */
  408. private function getDefaultMeasurementData()
  409. {
  410. // 返回所有映射字段的空值(使用空字符串)
  411. return [
  412. 'waist' => '', // 腰围
  413. 'thigh' => '', // 大腿围
  414. 'neck' => '', // 颈围
  415. 'knee' => '', // 膝围
  416. 'chest' => '', // 胸围
  417. 'calf' => '', // 小腿围
  418. 'leg_length' => '', // 腿长
  419. 'hip' => '', // 臀围
  420. 'inner_leg' => '', // 内腿长
  421. 'hip_actual' => '', // 实际臀围
  422. 'waist_lower' => '', // 下腰围
  423. 'shoulder_width' => '', // 肩宽
  424. 'arm_length' => '', // 臂长
  425. 'wrist' => '', // 手腕围
  426. 'upper_arm' => '', // 上臂围
  427. 'mid_waist' => '', // 中腰围
  428. 'ankle' => '', // 脚踝围
  429. '_confidence' => 0.0,
  430. '_warnings' => ['第三方AI服务暂时不可用,返回默认数据']
  431. ];
  432. }
  433. /**
  434. * 测试接口 - 返回模拟的第三方API测量数据
  435. * @ApiMethod (POST)
  436. * @ApiParams (name="profile_id", type="integer", required=true, description="档案ID")
  437. */
  438. public function testMeasurementData()
  439. {
  440. $params = $this->request->post();
  441. // 验证必要参数
  442. if (empty($params['profile_id'])) {
  443. $this->error('档案ID不能为空');
  444. }
  445. // 验证档案归属
  446. $profile = \app\common\model\BodyProfile::where('id', $params['profile_id'])
  447. ->where('user_id', $this->auth->id)
  448. ->find();
  449. if (!$profile) {
  450. $this->error('档案不存在');
  451. }
  452. // 模拟第三方API返回的数据
  453. $mockApiResult = [
  454. "body_size" => [
  455. "datuigen" => 56.973762220946064,
  456. "duwei" => 71.86294164495045,
  457. "jiankuan" => 44.99356951672863,
  458. "jiaohuai" => 20.995062499529606,
  459. "jingwei" => 36.973537078225604,
  460. "neitui" => 67.99506048261769,
  461. "shangbi" => 23.285375591374667,
  462. "shoubichang" => 61.1834335984307,
  463. "shouwanwei" => 16.0697059847192,
  464. "tuichang" => 73.9800462219755,
  465. "tunwei" => 90.08082593388505,
  466. "xiaofu" => 70.98010845587423,
  467. "xiaotuiwei" => 37.2761443409742,
  468. "xigai" => 34.990971006868364,
  469. "xiongwei" => 81.85738385794711,
  470. "yaowei" => 72.93800974219818,
  471. "zhongyao" => 70.99945416888724
  472. ],
  473. "confidence" => 0.85
  474. ];
  475. // 处理测量数据
  476. $measurements = $this->processMeasurementData($mockApiResult);
  477. // 处理结果
  478. $result = [
  479. 'measurements' => $measurements,
  480. 'confidence' => $measurements['_confidence'] ?? 0.8,
  481. 'warnings' => $measurements['_warnings'] ?? []
  482. ];
  483. // 清理内部字段
  484. unset($result['measurements']['_confidence']);
  485. unset($result['measurements']['_warnings']);
  486. // 格式化结果用于展示
  487. $formattedResult = $this->formatMeasurementResult($result, $params['profile_id']);
  488. $this->success('测试数据返回成功', [
  489. 'original_api_data' => $mockApiResult['body_size'],
  490. 'mapped_measurements' => $result['measurements'],
  491. 'formatted_result' => $formattedResult
  492. ]);
  493. }
  494. /**
  495. * 将图片URL转换为base64格式
  496. */
  497. private function convertImageToBase64($imageUrl)
  498. {
  499. try {
  500. // 如果已经是base64格式,直接返回
  501. if (strpos($imageUrl, 'data:image') === 0) {
  502. return $imageUrl;
  503. }
  504. // 如果是相对路径,转换为绝对路径
  505. if (strpos($imageUrl, 'http') !== 0) {
  506. $imageUrl = request()->domain() . $imageUrl;
  507. }
  508. // 获取图片数据
  509. $ch = curl_init();
  510. curl_setopt_array($ch, [
  511. CURLOPT_URL => $imageUrl,
  512. CURLOPT_RETURNTRANSFER => true,
  513. CURLOPT_TIMEOUT => 30,
  514. CURLOPT_CONNECTTIMEOUT => 10,
  515. CURLOPT_FOLLOWLOCATION => true,
  516. CURLOPT_SSL_VERIFYPEER => false,
  517. CURLOPT_SSL_VERIFYHOST => false,
  518. CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
  519. CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  520. CURLOPT_HTTPHEADER => [
  521. 'Accept: image/webp,image/apng,image/*,*/*;q=0.8',
  522. 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8',
  523. 'Cache-Control: no-cache',
  524. ]
  525. ]);
  526. $imageData = curl_exec($ch);
  527. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  528. $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
  529. $curlError = curl_error($ch);
  530. $effectiveUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  531. curl_close($ch);
  532. // 详细的错误处理
  533. if ($curlError) {
  534. throw new \Exception("网络请求失败: {$curlError} (URL: {$imageUrl})");
  535. }
  536. if ($httpCode !== 200) {
  537. throw new \Exception("图片访问失败,HTTP状态码: {$httpCode} (URL: {$imageUrl})");
  538. }
  539. if (!$imageData || strlen($imageData) === 0) {
  540. throw new \Exception("图片数据为空 (URL: {$imageUrl})");
  541. }
  542. // 验证图片数据是否有效
  543. if (!@getimagesizefromstring($imageData)) {
  544. throw new \Exception("获取的数据不是有效的图片格式 (URL: {$imageUrl})");
  545. }
  546. // 确定MIME类型
  547. if (strpos($contentType, 'image/') === 0) {
  548. $mimeType = $contentType;
  549. } else {
  550. // 通过文件扩展名推断
  551. $extension = strtolower(pathinfo(parse_url($imageUrl, PHP_URL_PATH), PATHINFO_EXTENSION));
  552. $mimeTypes = [
  553. 'jpg' => 'image/jpeg',
  554. 'jpeg' => 'image/jpeg',
  555. 'png' => 'image/png',
  556. 'gif' => 'image/gif',
  557. 'webp' => 'image/webp',
  558. 'bmp' => 'image/bmp'
  559. ];
  560. $mimeType = $mimeTypes[$extension] ?? 'image/jpeg';
  561. }
  562. // 转换为base64
  563. $base64 = base64_encode($imageData);
  564. return "data:{$mimeType};base64,{$base64}";
  565. } catch (\Exception $e) {
  566. \think\Log::error('Convert image to base64 error: ' . $e->getMessage() . ' URL: ' . $imageUrl);
  567. throw new \Exception('图片转换失败: ' . $e->getMessage());
  568. }
  569. }
  570. /**
  571. * 处理第三方API返回的测量数据
  572. */
  573. private function processMeasurementData($apiResult)
  574. {
  575. // 根据第三方API的返回格式处理数据
  576. // 这里需要根据实际的API返回格式进行调整
  577. $measurements = [];
  578. try {
  579. // 假设API返回格式类似:
  580. // {
  581. // "status": "success",
  582. // "data": {
  583. // "chest": 95.5,
  584. // "waist": 75.2,
  585. // "hip": 98.7,
  586. // ...
  587. // },
  588. // "confidence": 0.85
  589. // }
  590. // 检查返回数据结构 - 可能直接包含body_size字段
  591. if (isset($apiResult['body_size'])) {
  592. $data = $apiResult['body_size'];
  593. $hasValidData = true;
  594. } elseif (isset($apiResult['status']) && $apiResult['status'] === 'success') {
  595. $data = $apiResult['data'] ?? [];
  596. $hasValidData = true;
  597. } else {
  598. // 尝试直接使用返回的数据
  599. $data = $apiResult;
  600. $hasValidData = !empty($data) && is_array($data);
  601. }
  602. if ($hasValidData) {
  603. // 映射字段名(根据第三方API返回的字段名进行映射)
  604. $fieldMapping = [
  605. 'yaowei' => 'waist', // 净腰围 → 腰围
  606. 'datuigen' => 'thigh', // 净腿根 → 大腿围
  607. 'jingwei' => 'neck', // 净颈围 → 颈围
  608. 'xigai' => 'knee', // 净膝围 → 膝围
  609. 'xiongwei' => 'chest', // 净胸围 → 胸围
  610. 'xiaotuiwei' => 'calf', // 净小腿围 → 小腿围
  611. 'tuichang' => 'leg_length', // 腿长 → 腿长
  612. 'duwei' => 'hip', // 净肚围 → 臀围
  613. 'neitui' => 'inner_leg', // 内腿长 → 内腿长
  614. 'tunwei' => 'hip_actual', // 净臀围 → 实际臀围
  615. 'xiaofu' => 'waist_lower', // 净小腹围 → 下腰围
  616. 'jiankuan' => 'shoulder_width', // 净肩宽 → 肩宽
  617. 'shoubichang' => 'arm_length', // 净手臂长 → 臂长
  618. 'shouwanwei' => 'wrist', // 净手腕围 → 手腕围
  619. 'shangbi' => 'upper_arm', // 净上臂围 → 上臂围
  620. 'zhongyao' => 'mid_waist', // 净中腰 → 中腰围
  621. 'jiaohuai' => 'ankle', // 净脚踝围 → 脚踝围
  622. ];
  623. foreach ($fieldMapping as $apiField => $localField) {
  624. if (isset($data[$apiField]) && is_numeric($data[$apiField])) {
  625. $measurements[$localField] = round(floatval($data[$apiField]), 1);
  626. }
  627. }
  628. // 设置置信度和警告信息
  629. $measurements['_confidence'] = $apiResult['confidence'] ?? 0.8;
  630. $measurements['_warnings'] = $apiResult['warnings'] ?? [];
  631. // 如果没有测量数据,添加默认警告
  632. if (count($measurements) === 2) { // 只有_confidence和_warnings
  633. $measurements['_warnings'][] = '第三方AI服务未返回有效的测量数据';
  634. }
  635. } else {
  636. // API返回错误
  637. $errorMsg = $apiResult['message'] ?? $apiResult['error'] ?? '第三方AI服务返回未知错误';
  638. throw new \Exception($errorMsg);
  639. }
  640. } catch (\Exception $e) {
  641. // 处理异常,返回错误信息
  642. $measurements['_confidence'] = 0;
  643. $measurements['_warnings'] = ['数据处理失败: ' . $e->getMessage()];
  644. }
  645. return $measurements;
  646. }
  647. /**
  648. * 处理AI测量任务
  649. */
  650. private function processTask($taskId)
  651. {
  652. try {
  653. // 更新任务状态为处理中
  654. \think\Db::table('fa_ai_measurement_task')
  655. ->where('id', $taskId)
  656. ->update([
  657. 'status' => 1,
  658. 'started_at' => time(),
  659. 'attempts' => \think\Db::raw('attempts + 1'),
  660. 'updatetime' => time()
  661. ]);
  662. // 获取任务详情
  663. $task = \think\Db::table('fa_ai_measurement_task')->where('id', $taskId)->find();
  664. $photos = json_decode($task['photos'], true);
  665. $params = json_decode($task['params'], true);
  666. // 安全调用第三方AI分析服务 - 确保身高为数字格式
  667. $heightCm = is_numeric($params['height']) ? floatval($params['height']) : 0;
  668. $measurements = $this->safeCallThirdPartyAiService(
  669. $photos,
  670. $heightCm
  671. );
  672. // 处理结果
  673. $result = [
  674. 'measurements' => $measurements,
  675. 'confidence' => $measurements['_confidence'] ?? 0.8,
  676. 'warnings' => $measurements['_warnings'] ?? []
  677. ];
  678. // 清理内部字段
  679. unset($result['measurements']['_confidence']);
  680. unset($result['measurements']['_warnings']);
  681. // 更新任务状态为完成
  682. \think\Db::table('fa_ai_measurement_task')
  683. ->where('id', $taskId)
  684. ->update([
  685. 'status' => 2,
  686. 'result' => json_encode($result),
  687. 'completed_at' => time(),
  688. 'updatetime' => time()
  689. ]);
  690. } catch (\Exception $e) {
  691. // 更新任务状态为失败
  692. \think\Db::table('fa_ai_measurement_task')
  693. ->where('id', $taskId)
  694. ->update([
  695. 'status' => 3,
  696. 'error_message' => $e->getMessage(),
  697. 'updatetime' => time()
  698. ]);
  699. }
  700. }
  701. /**
  702. * 估算处理进度
  703. */
  704. private function estimateProgress($task)
  705. {
  706. $startTime = $task['started_at'];
  707. $currentTime = time();
  708. $elapsedTime = $currentTime - $startTime;
  709. // 假设总处理时间为30秒
  710. $totalTime = 30;
  711. $progress = min(95, ($elapsedTime / $totalTime) * 100);
  712. return round($progress);
  713. }
  714. /**
  715. * 格式化测量结果用于展示
  716. */
  717. private function formatMeasurementResult($result, $profileId)
  718. {
  719. $profile = \app\common\model\BodyProfile::find($profileId);
  720. $measurements = $result['measurements'];
  721. // 获取显示配置
  722. $displayConfig = AiMeasurementService::getMeasurementDisplayConfig($profile->gender);
  723. // 格式化数据
  724. $formattedData = [
  725. 'profile' => [
  726. 'id' => $profile->id,
  727. 'name' => $profile->profile_name,
  728. 'gender' => $profile->gender,
  729. 'height' => $profile->height,
  730. 'weight' => $profile->weight
  731. ],
  732. 'measurements' => [],
  733. 'display_config' => $displayConfig,
  734. 'confidence' => $result['confidence'] ?? 0,
  735. 'warnings' => $result['warnings'] ?? []
  736. ];
  737. // 组织测量数据
  738. foreach ($displayConfig as $field => $config) {
  739. $value = isset($measurements[$field]) && $measurements[$field] > 0
  740. ? $measurements[$field]
  741. : null;
  742. $formattedData['measurements'][$field] = [
  743. 'label' => $config['label'],
  744. 'value' => $value,
  745. 'unit' => 'cm',
  746. 'position' => $config['position'],
  747. 'side' => $config['side']
  748. ];
  749. }
  750. // 添加基础数据表格
  751. $formattedData['basic_data'] = [
  752. ['label' => '身高', 'value' => $profile->height, 'unit' => 'cm'],
  753. ['label' => '体重', 'value' => $profile->weight, 'unit' => 'kg'],
  754. ];
  755. // 添加测量数据表格
  756. $tableData = [];
  757. $fields = array_keys($measurements);
  758. $chunks = array_chunk($fields, 2);
  759. foreach ($chunks as $chunk) {
  760. $row = [];
  761. foreach ($chunk as $field) {
  762. if (isset($displayConfig[$field])) {
  763. $row[] = [
  764. 'label' => $displayConfig[$field]['label'],
  765. 'value' => $measurements[$field] ?? null,
  766. 'unit' => 'cm'
  767. ];
  768. }
  769. }
  770. if (!empty($row)) {
  771. $tableData[] = $row;
  772. }
  773. }
  774. $formattedData['table_data'] = $tableData;
  775. return $formattedData;
  776. }
  777. }