AiController.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. <?php
  2. namespace App\Http\Controllers\V1\Ai;
  3. use App\Auth;
  4. use App\libs\helpers\Curl;
  5. use App\Http\Controllers\V1\Controller;
  6. use App\libs\helpers\Helper;
  7. use App\libs\helpers\LogHelper;
  8. use App\libs\helpers\Response;
  9. use App\Models\Config;
  10. use App\Models\Keyword;
  11. use App\Models\TaskList;
  12. use App\Models\User;
  13. use App\Models\UserRole;
  14. use Illuminate\Http\Request;
  15. use Illuminate\Support\Facades\Log;
  16. use App\Exceptions\ApiException;
  17. use Overtrue\Pinyin\Pinyin;
  18. class AiController extends Controller
  19. {
  20. public $code = '_Ai';
  21. /**
  22. * 用户提交任务
  23. */
  24. public function submitTask(Request $request): \Illuminate\Http\JsonResponse
  25. {
  26. try {
  27. (int) $plot = Config::query()->where('key', 'plot')->value('value');
  28. if (!$plot) {
  29. return Response::fail('系统错误,请联系管理员#');
  30. }
  31. if (Auth::$user->diamond < $plot) {
  32. return Response::fail('钻石不够了,请先充值');
  33. }
  34. $roleId = $request->post('roleId', 0);
  35. if ($roleId) {
  36. $role = UserRole::query()->find($roleId);
  37. if (!$role) {
  38. return Response::fail('没有该角色');
  39. }
  40. } else {
  41. $role = UserRole::query()->create([
  42. 'user_id' => Auth::$userId,
  43. 'name' => $request->post('name', ''),
  44. 'sex' => $request->post('sex', ''),
  45. 'age' => $request->post('age', ''),
  46. 'star' => $request->post('star', ''),
  47. 'level' => $request->post('level', ''),
  48. ]);
  49. if (!$role) {
  50. return Response::fail('提交失败,请稍后再试!');
  51. }
  52. }
  53. User::query()->where('id', Auth::$userId)->decrement('diamond', $plot);
  54. $task = TaskList::query()->create([
  55. 'user_id' => Auth::$userId,
  56. 'role_id' => $role->id,
  57. 'image' => $request->post('image', ''),
  58. 'surplus_diamond' => Auth::$user->diamond - $plot,
  59. 'nickname' => 'AI绘本生成',
  60. 'plot' => $plot,
  61. 'is_piny' => $request->post('pinYin', 1),
  62. ]);
  63. if (!$task) {
  64. return Response::fail('任务提交失败');
  65. }
  66. return Response::success(['id' => $task->id], '提交成功,请稍等');
  67. } catch (\Exception $exception) {
  68. LogHelper::exceptionLog($exception, $this->code);
  69. return Response::fail($exception->getMessage());
  70. }
  71. }
  72. /**
  73. * 获取任务详情.
  74. *
  75. * @return \Illuminate\Http\JsonResponse
  76. */
  77. public function getTaskDetail(Request $request)
  78. {
  79. try {
  80. $id = $request->get('id', 0);
  81. return Response::success(TaskList::query()->where('user_id', Auth::$userId)->find($id));
  82. } catch (\Exception $exception) {
  83. LogHelper::exceptionLog($exception, $this->code);
  84. return Response::fail($exception->getMessage());
  85. }
  86. }
  87. /**
  88. * 获取字数
  89. *
  90. * @param $level
  91. * @return int|mixed
  92. */
  93. private function getBuildCountString($level = 1){
  94. $string = Config::query()->where('key','class_count')->first()->toArray();
  95. foreach ($string['value'] ?? [] as $value){
  96. if ($level == $value['lv']){
  97. return $value['count'];
  98. }
  99. }
  100. return 200;
  101. }
  102. // /**
  103. // * 生成故事.
  104. // */
  105. // public function buildStory(Request $request): \Illuminate\Http\JsonResponse
  106. // {
  107. // try {
  108. // $task = TaskList::query()->with('role')->where('state', 0)->inRandomOrder()->first();
  109. // if (!$task) {
  110. // return Response::fail('暂无任务');
  111. // }
  112. // $key = [];
  113. // // $keyword = Keyword::query()->pluck('keyword');
  114. // // foreach ($keyword as $value) {
  115. // // $key[] = $value;
  116. // // }
  117. // // $keyword = implode(',', $key);
  118. // $keyword = Config::query()->where('key','prompt_gushi')->value('value');
  119. // $task->state = 1;
  120. // $task->save();
  121. // Log::warning('这个是当前的次数:'.$this->getBuildCountString($task->level));
  122. // $prompt = "一个{$task->role->sex},叫{$task->role->name},{$task->role->age}岁。{$keyword},要求不低于{$this->getBuildCountString($task->role->level)}字。备注:不要加什么特殊符号只需要正常的逗号句号叹号这些。如果有英语的地方翻译为中文";
  123. // $messages[] = ['role' => 'user', 'content' => $prompt];
  124. // $data = [
  125. // 'messages' => $messages,
  126. // ];
  127. // $postData = json_encode($data);
  128. // $complete = $this->host($postData);
  129. // $task->init_content = $complete['result'];
  130. // $task->save();
  131. // return Response::success($complete);
  132. // } catch (\Exception $exception) {
  133. // LogHelper::exceptionLog($exception, $this->code);
  134. // return Response::fail($exception->getMessage());
  135. // }
  136. // }
  137. /**
  138. * 获取图生文
  139. *
  140. * @param $imageUrl
  141. * @return string
  142. * @throws \Exception
  143. */
  144. public function setImageToText($imageUrl = 'http://zhengda.oss-cn-chengdu.aliyuncs.com/hb/images/AeP5fMFqeutOOcyMsfCaSnMmMFMqW6GRO2ZOOzSW.jpg'){
  145. $url = 'https://api.zhishuyun.com/midjourney/describe?token=9f4df24de4004f1a9a0c88e5e0989503&version=2.0';
  146. $result = Curl::requestCurl($url,'POST',[ "accept:application/json","content-type:application/json"],json_encode([
  147. 'image_url' => $imageUrl
  148. ]));
  149. $result = json_decode($result,true);
  150. return $result['descriptions'][0] ?? '';
  151. }
  152. /**
  153. * 生成故事.
  154. */
  155. public function buildStory(): \Illuminate\Http\JsonResponse
  156. {
  157. try {
  158. $task = TaskList::query()->with('role')->where('state', 0)->inRandomOrder()->first();
  159. if (!$task) {
  160. return Response::fail('暂无任务');
  161. }
  162. $key = [];
  163. // $keyword = Keyword::query()->pluck('keyword');
  164. // foreach ($keyword as $value) {
  165. // $key[] = $value;
  166. // }
  167. // $keyword = implode(',', $key);
  168. $keyword = Config::query()->where('key', 'prompt_gushi')->value('value');
  169. $task->state = 1;
  170. $task->save();
  171. Log::warning('这个是当前的次数:' . $this->getBuildCountString($task->level));
  172. $imageToText = $this->setImageToText($task->image);
  173. $prompt = "一个{$task->role->sex},叫{$task->role->name},{$task->role->age}岁。".$imageToText."{$keyword},要求不低于{$this->getBuildCountString($task->role->level)}字。备注:不要加什么特殊符号与英文之类的任何非中文字符串,包括不能出现数字与拼音字母这些。只需要正常的逗号句号叹号这些。如果有英语的地方翻译为中文";
  174. $messages[] = ['role' => 'user', 'content' => $prompt];
  175. $data = [
  176. 'messages' => $messages,
  177. ];
  178. $postData = json_encode($data);
  179. $complete = $this->host($postData);
  180. $task->init_content = $complete['result'];
  181. $task->image_to_text = $imageToText;
  182. $task->save();
  183. return Response::success($complete);
  184. } catch (\Exception $exception) {
  185. LogHelper::exceptionLog($exception, $this->code);
  186. return Response::fail($exception->getMessage());
  187. }
  188. }
  189. // /**
  190. // * 获取图生文
  191. // *
  192. // * @param $imageUrl
  193. // * @return string
  194. // * @throws \Exception
  195. // */
  196. // public function setImageToText($imageUrl = 'http://zhengda.oss-cn-chengdu.aliyuncs.com/hb/images/AeP5fMFqeutOOcyMsfCaSnMmMFMqW6GRO2ZOOzSW.jpg'){
  197. // $url = 'https://api.zhishuyun.com/midjourney/describe?token=04c7db50869a476883183510db23011a&version=2.0';
  198. // $result = Curl::requestCurl($url,'POST',[ "accept:application/json","content-type:application/json"],json_encode([
  199. // 'image_url' => $imageUrl
  200. // ]));
  201. // $result = json_decode($result,true);
  202. // return $result['descriptions'][0] ?? '';
  203. // }
  204. // /**
  205. // * 生成故事.
  206. // */
  207. // public function buildStory(Request $request): \Illuminate\Http\JsonResponse
  208. // {
  209. // try {
  210. // $task = TaskList::query()->with('role')->where('state', 0)->inRandomOrder()->first();
  211. // if (!$task) {
  212. // return Response::fail('暂无任务');
  213. // }
  214. // $key = [];
  215. // // $keyword = Keyword::query()->pluck('keyword');
  216. // // foreach ($keyword as $value) {
  217. // // $key[] = $value;
  218. // // }
  219. // // $keyword = implode(',', $key);
  220. // $keyword = Config::query()->where('key', 'prompt_gushi')->value('value');
  221. // $task->state = 1;
  222. // $task->save();
  223. // Log::warning('这个是当前的次数:' . $this->getBuildCountString($task->level));
  224. // $imageToText = $this->setImageToText($task->image);
  225. // $prompt = "一个{$task->role->sex},叫{$task->role->name},{$task->role->age}岁。".$imageToText."{$keyword},要求不低于{$this->getBuildCountString($task->role->level)}字。备注:不要加什么特殊符号只需要正常的逗号句号叹号这些。";
  226. // $messages[] = ['role' => 'user', 'content' => $prompt];
  227. // $data = [
  228. // 'messages' => $messages,
  229. // ];
  230. // $postData = json_encode($data);
  231. // $complete = $this->host($postData);
  232. // $task->init_content = $complete['result'];
  233. // $task->save();
  234. // return Response::success($complete);
  235. // } catch (\Exception $exception) {
  236. // LogHelper::exceptionLog($exception, $this->code);
  237. // return Response::fail($exception->getMessage());
  238. // }
  239. // }
  240. /**
  241. * 生成标题.
  242. *
  243. * @return \Illuminate\Http\JsonResponse
  244. */
  245. public function buildTitle()
  246. {
  247. try {
  248. $task = TaskList::query()->with('role')->where('state', 1)->inRandomOrder()->first();
  249. if (!$task) {
  250. return Response::fail('暂无任务');
  251. }
  252. $task->state = 2;
  253. $task->save();
  254. $prompt = $task->init_content . '。将这段童话故事生成一个标题,标题不能有特殊符号,只需要纯文字标题即可,不需要其他任何文字,标题文字控制在10个字以内。不能超过10个字';
  255. $messages[] = ['role' => 'user', 'content' => $prompt];
  256. $data = [
  257. 'messages' => $messages,
  258. ];
  259. $postData = json_encode($data);
  260. $complete = $this->host($postData);
  261. // $task->state = 2;
  262. $task->title = $complete['result'];
  263. $task->save();
  264. return Response::success($complete);
  265. } catch (\Exception $exception) {
  266. LogHelper::exceptionLog($exception, $this->code);
  267. return Response::fail($exception->getMessage());
  268. }
  269. }
  270. /**
  271. * 生成关键词.
  272. *
  273. * @return \Illuminate\Http\JsonResponse
  274. */
  275. public function buildKeyword()
  276. {
  277. try {
  278. $task = TaskList::query()->with('role')->where('state', 2)->inRandomOrder()->first();
  279. if (!$task) {
  280. return Response::fail('暂无任务');
  281. }
  282. $keyword = Config::query()->where('key','prompt_keyword')->value('value');
  283. $prompt = $task->init_content . $keyword;
  284. $messages[] = ['role' => 'user', 'content' => $prompt];
  285. $data = [
  286. 'messages' => $messages,
  287. ];
  288. $task->state = 3;
  289. $task->save();
  290. $postData = json_encode($data);
  291. $complete = $this->host($postData);
  292. // $task->state = 3;
  293. $task->keyword = $complete['result'];
  294. $task->save();
  295. return Response::success($complete);
  296. } catch (\Exception $exception) {
  297. LogHelper::exceptionLog($exception, $this->code);
  298. return Response::fail($exception->getMessage());
  299. }
  300. }
  301. /**
  302. * 翻译英文.
  303. */
  304. private function toEnglish($prompt)
  305. {
  306. $keyword = Config::query()->where('key','prompt_style')->value('value');
  307. $prompt = $prompt . $keyword;
  308. $promptTo = '我希望你能担任英语翻译、拼写校对和修辞改进的角色。我会将翻译的结果用于如stable diffusion、midjourney等绘画场景生成图片,语言要求尽量优美。我会用任何语言和你交流,你会识别语言,将其翻译为英语并仅回答翻译的最终结果,不要写解释。我的第一句话是:' . $prompt . '。请立刻翻译,不要回复其它内容。';
  309. $messages[] = ['role' => 'user', 'content' => $promptTo];
  310. $data = [
  311. 'messages' => $messages,
  312. ];
  313. $postData = json_encode($data);
  314. $complete = $this->host($postData);
  315. return $complete['result'];
  316. }
  317. /**
  318. * 提交sd生成插图.
  319. *
  320. * @return \Illuminate\Http\JsonResponse
  321. */
  322. public function buildSd()
  323. {
  324. try {
  325. $task = TaskList::query()->with('role')->where('state', 3)->inRandomOrder()->first();
  326. if (!$task) {
  327. return Response::fail('暂无任务');
  328. }
  329. $task->state = 4;
  330. $task->save();
  331. $keyword = $this->toEnglish($task->keyword);
  332. $param = ['name' => '甜瓜(动漫风格)',
  333. 'init_image' => '',
  334. 'prompt' => $keyword,
  335. 'width' => '512',
  336. 'height' => '512',
  337. 'guidance_scale' => '7',
  338. 'samples' => '1',
  339. 'model_id' => '3',
  340. 'scheduler' => 'DDPMScheduler',
  341. 'type' => 'text2img',
  342. 'num_inference_steps' => '30',
  343. 'keywords' => $keyword,
  344. ];
  345. $result = (new Helper())->opensd($param);
  346. $result = json_decode($result, true);
  347. Log::warning('这个是SD回调信息:'.json_encode($result,256));
  348. if(isset($result['data']['id'])){
  349. $task->sd_id = $result['data']['id'];
  350. }else{
  351. $task->state = 3;
  352. }
  353. $task->save();
  354. return Response::success($result['data']);
  355. } catch (\Exception $exception) {
  356. LogHelper::exceptionLog($exception, $this->code);
  357. return Response::fail($exception->getMessage());
  358. }
  359. }
  360. /**
  361. * 查询生成进度.
  362. *
  363. * @return \Illuminate\Http\JsonResponse
  364. */
  365. public function getOpensdDetail()
  366. {
  367. $task = TaskList::query()->where('state', 4)->inRandomOrder()->first();
  368. if (!$task) {
  369. return $this->error('暂无任务');
  370. }
  371. $res = (new Helper())->opensdDetail($task->sd_id);
  372. $res = @json_decode($res, true);
  373. if (200 != $res['code']) {
  374. return Response::fail($res['msg']);
  375. }
  376. if ('fail' == $res['data']['state']) {
  377. $task->state = 3;
  378. $task->desc = $res['data']['fail_reason'];
  379. }
  380. $task->save();
  381. if ('success' == $res['data']['state']) {
  382. $path = $this->saveImage($res['data']['gen_img']);
  383. $task->sd_image = $path;
  384. $task->state = 5;
  385. $task->save();
  386. }
  387. return $this->success('操作成功', $res['data']);
  388. }
  389. /**
  390. * 获取拼音排版.
  391. *
  392. * @return \Illuminate\Http\JsonResponse
  393. */
  394. public function buildPinyin()
  395. {
  396. try {
  397. $task = TaskList::query()->where('state', 5)->inRandomOrder()->first();
  398. if (!$task) {
  399. return $this->error('暂无任务');
  400. }
  401. if (empty($file_name)) {
  402. $file_name = md5(time()) . '.jpeg';
  403. }
  404. $date = date('Ymd');
  405. $path = public_path() . '/file/images/'.$date.'/' . $file_name;
  406. $imageDir = public_path() . '/file/images/'.$date.'/';
  407. if (!is_dir($imageDir)) {
  408. mkdir($imageDir, 0755, true);
  409. }
  410. $shell = 'wkhtmltoimage --quality 50 https://hb.swdz.com/api/ai/Pinyin?id=' . $task->id . ' ' . $path;
  411. exec($shell, $result, $status);
  412. if ($status) {
  413. $this->exit_out('生成图片失败', ['生成图片失败' => [$shell, $result, $status]]);
  414. }
  415. $domain = request()->getScheme() . '://' . request()->getHost();
  416. $pdfPath = $domain . '/file/images/' . $date.'/'.$file_name;
  417. $task->image_path = $pdfPath;
  418. $result = $this->extracted($task);
  419. $task->pinyin_content = $result;
  420. $task->state = 6;
  421. $task->save();
  422. return Response::success($result);
  423. } catch (\Exception $exception) {
  424. LogHelper::exceptionLog($exception, $this->code);
  425. return Response::fail($exception->getMessage());
  426. }
  427. }
  428. /**
  429. * 下载PDF.
  430. *
  431. * @return \Illuminate\Http\JsonResponse
  432. */
  433. public function downloadPdf(Request $request)
  434. {
  435. try {
  436. $id = $request->input('id', 0);
  437. $task = TaskList::query()->find($id);
  438. if (!$task) {
  439. return Response::fail('没有该任务');
  440. }
  441. if (!empty($task->pdf_path)) {
  442. return Response::success(['url' => $task->pdf_path]);
  443. }
  444. if (empty($file_name)) {
  445. $file_name = md5(time()) . '.pdf';
  446. }
  447. $date = date('Ymd');
  448. $path = public_path() . '/file/pdf/' . $date.'/'.$file_name;
  449. $imageDir = public_path() . '/file/pdf/'.$date.'/';
  450. if (!is_dir($imageDir)) {
  451. mkdir($imageDir, 0755, true);
  452. }
  453. $shell = "wkhtmltopdf 'https://hb.swdz.com/api/ai/Pinyin?type=1&id=" . $task->id . "' ". "'".$path."'";
  454. exec($shell, $result, $status);
  455. if ($status) {
  456. $this->exit_out('生成PDF失败', ['生成PDF失败' => [$shell, $result, $status]]);
  457. }
  458. $domain = request()->getScheme() . '://' . request()->getHost();
  459. $pdfPath = $domain . '/file/pdf/' . $date.'/'.$file_name;
  460. $task->pdf_path = $pdfPath;
  461. $task->save();
  462. return Response::success(['url' => $pdfPath]);
  463. } catch (\Exception $exception) {
  464. LogHelper::exceptionLog($exception, $this->code);
  465. return Response::fail($exception->getMessage());
  466. }
  467. }
  468. private function splitChineseCharacters($inputString, $type = 0)
  469. {
  470. if (0 == $type) {
  471. $inputString = str_replace("\n", '', $inputString);
  472. }
  473. $inputString = str_replace('“', '', $inputString);
  474. $inputString = str_replace('”', '', $inputString);
  475. // $inputString = preg_replace('/[^\w\s-]+/u', '', $inputString);
  476. $length = mb_strlen($inputString, 'utf-8');
  477. $result = [];
  478. for ($i = 0; $i < $length; $i++) {
  479. $result[] = mb_substr($inputString, $i, 1, 'utf-8');
  480. }
  481. return $result;
  482. // return $inputString;
  483. }
  484. public function Pinyin(Request $request)
  485. {
  486. try {
  487. $id = $request->input('id');
  488. $type = $request->input('type',0);
  489. $task = TaskList::query()->find($id);
  490. $result = $this->extracted($task);
  491. return view('pdf', ['data' => $result, 'img' => $task->image,'title' => $task->title,'type' => $type]);
  492. } catch (\Exception $exception) {
  493. LogHelper::exceptionLog($exception, $this->code);
  494. return Response::fail($exception->getMessage());
  495. }
  496. }
  497. public function containsPunctuation($str)
  498. {
  499. // 定义要检测的符号
  500. $punctuation = '/[,。!、.1234567890:]/u'; // 中文逗号、中文句号、中文感叹号
  501. // 使用 preg_match 函数进行匹配
  502. return 1 === preg_match($punctuation, $str);
  503. }
  504. public function generate_pdf($html_path = '', $file_name = '')
  505. {
  506. if (empty($file_name)) {
  507. $file_name = md5(time()) . '.pdf';
  508. }
  509. $path = public_path() . '/file/pdf/' . $file_name;
  510. var_dump($path);
  511. exit;
  512. $shell = 'wkhtmltopdf --outline --minimum-font-size 9 ' . $html_path . ' ' . $path;
  513. exec($shell, $result, $status);
  514. if ($status) {
  515. $this->exit_out('生成PDF失败', ['生成PDF失败' => [$shell, $result, $status]]);
  516. }
  517. $domain = request()->getScheme() . '://' . request()->getHost();
  518. return $domain . '/file/pdf/' . $file_name;
  519. }
  520. public function exit_out($msg, $exceptionData = false, $code = 1, $data = [])
  521. {
  522. $out = ['code' => $code, 'msg' => $msg, 'data' => $data];
  523. if (false !== $exceptionData) {
  524. $this->trace([$msg => $exceptionData], 'error');
  525. }
  526. $json = json_encode($out, JSON_UNESCAPED_UNICODE);
  527. throw new ApiException($json);
  528. }
  529. public function trace($log = '', $level = 'info')
  530. {
  531. Log::log($level, $log);
  532. }
  533. /**
  534. * 保存图片.
  535. *
  536. * @return \Illuminate\Http\JsonResponse|string
  537. */
  538. private function saveImage($image_url)
  539. {
  540. $imageContent = file_get_contents($image_url);
  541. $imageDir = $_SERVER['DOCUMENT_ROOT'] . '/file/sd/' . date('Ymd') . '/';
  542. $imageName = uniqid() . time() . '_image.png';
  543. $imagePath = $imageDir . $imageName;
  544. if (!is_dir($imageDir)) {
  545. mkdir($imageDir, 0777, true);
  546. }
  547. if (false !== $imageContent) {
  548. $savedImages = file_put_contents($imagePath, $imageContent);
  549. if (false !== $savedImages) {
  550. return request()->getHost(). '/file/sd/' . date('Ymd') . '/' . $imageName;
  551. }
  552. return false;
  553. }
  554. return false;
  555. }
  556. /**
  557. * 执行请求
  558. */
  559. private function host($postData)
  560. {
  561. $ch = curl_init();
  562. curl_setopt_array($ch, [
  563. CURLOPT_URL => 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=' . Helper::getAccessToken(),
  564. CURLOPT_RETURNTRANSFER => true,
  565. CURLOPT_POST => true,
  566. CURLOPT_POSTFIELDS => $postData,
  567. ]);
  568. $res = curl_exec($ch);
  569. curl_close($ch);
  570. return json_decode(trim($res), true);
  571. }
  572. public function extracted($result,$type = 0,$sdImage = ''): string
  573. {
  574. if ($type == 0){
  575. $inputString = $result->init_content;
  576. $sdImage = $result->sd_image;
  577. }else{
  578. $inputString = $result;
  579. }
  580. $inputString = str_replace('“', '', $inputString);
  581. $inputString = str_replace('”', '', $inputString);
  582. $inputString = str_replace('——', '', $inputString);
  583. $inputString = str_replace('—', '', $inputString);
  584. $inputStringFor = $this->splitChineseCharacters($inputString, 1);
  585. $arr = [];
  586. $i = 0;
  587. foreach ($inputStringFor as $key => $value) {
  588. if ("\n" == $value) {
  589. $arr[] = $key - $i;
  590. $i++;
  591. }
  592. }
  593. $splitCharacters = $this->splitChineseCharacters($inputString);
  594. $pinyin = Pinyin::Sentence($inputString)->toArray();
  595. $string = '';
  596. $count = 0;
  597. foreach ($pinyin as $value) {
  598. $count += mb_strlen($value);
  599. }
  600. $img = '<img style="width: 100%;height:auto;float: right;margin-right: 10px;margin-top: 10px; margin-bottom: 5px" src="https://' . $sdImage . '"/>';
  601. $stringCount = 0;
  602. foreach ($pinyin as $key => $value) {
  603. if ($this->containsPunctuation($value)) {
  604. $value = '&nbsp;';
  605. }
  606. $stringCount += mb_strlen($value);
  607. if (in_array($count - $stringCount, [158, 159, 160, 161, 162, 163]) && !strstr($string, '<img')) {
  608. $string = $string . $img;
  609. }
  610. if (in_array($key + 1, $arr)) {
  611. if ($result->is_piny){
  612. $string = $string . "<span><sup>{$value}</sup>{$splitCharacters[$key]}</span><br style='clear: both'><br style='clear: both'>";
  613. }else{
  614. $string = $string . "<span>{$splitCharacters[$key]}</span><br style='clear: both'><br style='clear: both'>";
  615. }
  616. } else {
  617. $style = '';
  618. if (in_array($key, $arr) || 0 == $key) {
  619. $style = 'style="margin-left: 5rem"';
  620. }
  621. if ($result->is_piny){
  622. $string = $string . '<span ' . $style . "><sup>{$value}</sup>{$splitCharacters[$key]}</span>";
  623. }else{
  624. $string = $string . '<span ' . $style . ">{$splitCharacters[$key]}</span>";
  625. }
  626. }
  627. // if (in_array($key + 1, $arr)) {
  628. // $string = $string . "<span><sup>{$value}</sup>{$splitCharacters[$key]}</span><br style='clear: both'><br style='clear: both'>";
  629. // } else {
  630. // $style = '';
  631. // if (in_array($key, $arr) || 0 == $key) {
  632. // $style = 'style="margin-left: 5rem"';
  633. // }
  634. // $string = $string . '<span ' . $style . "><sup>{$value}</sup>{$splitCharacters[$key]}</span>";
  635. // }
  636. }
  637. return $string;
  638. }
  639. }