AiController.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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绘画场景生成图片,语言要求尽量优美。我会用任何语言和你交流,你会识别语言,将其翻译为英语并仅回答翻译的最终结果,不要写解释。我的第一句话是:' . $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. Log::warning('这个是SD进度信息:'.json_encode($res,256));
  381. $task->save();
  382. if ('success' == $res['data']['state']) {
  383. $path = $this->saveImage($res['data']['gen_img']);
  384. $task->sd_image = $path;
  385. $task->state = 5;
  386. $task->save();
  387. }
  388. return $this->success('操作成功', $res['data']);
  389. }
  390. /**
  391. * 获取拼音排版.
  392. *
  393. * @return \Illuminate\Http\JsonResponse
  394. */
  395. public function buildPinyin()
  396. {
  397. try {
  398. $task = TaskList::query()->where('state', 5)->inRandomOrder()->first();
  399. if (!$task) {
  400. return $this->error('暂无任务');
  401. }
  402. if (empty($file_name)) {
  403. $file_name = md5(time()) . '.jpeg';
  404. }
  405. $date = date('Ymd');
  406. $path = public_path() . '/file/images/'.$date.'/' . $file_name;
  407. $imageDir = public_path() . '/file/images/'.$date.'/';
  408. if (!is_dir($imageDir)) {
  409. mkdir($imageDir, 0755, true);
  410. }
  411. $shell = 'wkhtmltoimage --quality 50 ' . request()->getHost() . '/api/ai/Pinyin?id=' . $task->id . ' ' . $path;
  412. exec($shell, $result, $status);
  413. if ($status) {
  414. $this->exit_out('生成图片失败', ['生成图片失败' => [$shell, $result, $status]]);
  415. }
  416. $domain = request()->getScheme() . '://' . request()->getHost();
  417. $pdfPath = $domain . '/file/images/' . $date.'/'.$file_name;
  418. $task->image_path = $pdfPath;
  419. $result = $this->extracted($task);
  420. $task->pinyin_content = $result;
  421. $task->state = 6;
  422. $task->save();
  423. return Response::success($result);
  424. } catch (\Exception $exception) {
  425. LogHelper::exceptionLog($exception, $this->code);
  426. return Response::fail($exception->getMessage());
  427. }
  428. }
  429. /**
  430. * 下载PDF.
  431. *
  432. * @return \Illuminate\Http\JsonResponse
  433. */
  434. public function downloadPdf(Request $request)
  435. {
  436. try {
  437. $id = $request->input('id', 0);
  438. $task = TaskList::query()->find($id);
  439. if (!$task) {
  440. return Response::fail('没有该任务');
  441. }
  442. if (!empty($task->pdf_path)) {
  443. return Response::success(['url' => $task->pdf_path]);
  444. }
  445. if (empty($file_name)) {
  446. $file_name = md5(time()) . '.pdf';
  447. }
  448. $date = date('Ymd');
  449. $path = public_path() . '/file/pdf/' . $date.'/'.$file_name;
  450. $imageDir = public_path() . '/file/pdf/'.$date.'/';
  451. if (!is_dir($imageDir)) {
  452. mkdir($imageDir, 0755, true);
  453. }
  454. $shell = "wkhtmltopdf ' . request()->getHost() . '/api/ai/Pinyin?type=1&id=" . $task->id . "' ". "'".$path."'";
  455. exec($shell, $result, $status);
  456. if ($status) {
  457. $this->exit_out('生成PDF失败', ['生成PDF失败' => [$shell, $result, $status]]);
  458. }
  459. $domain = request()->getScheme() . '://' . request()->getHost();
  460. $pdfPath = $domain . '/file/pdf/' . $date.'/'.$file_name;
  461. $task->pdf_path = $pdfPath;
  462. $task->save();
  463. return Response::success(['url' => $pdfPath]);
  464. } catch (\Exception $exception) {
  465. LogHelper::exceptionLog($exception, $this->code);
  466. return Response::fail($exception->getMessage());
  467. }
  468. }
  469. private function splitChineseCharacters($inputString, $type = 0)
  470. {
  471. if (0 == $type) {
  472. $inputString = str_replace("\n", '', $inputString);
  473. }
  474. $inputString = str_replace('“', '', $inputString);
  475. $inputString = str_replace('”', '', $inputString);
  476. // $inputString = preg_replace('/[^\w\s-]+/u', '', $inputString);
  477. $length = mb_strlen($inputString, 'utf-8');
  478. $result = [];
  479. for ($i = 0; $i < $length; $i++) {
  480. $result[] = mb_substr($inputString, $i, 1, 'utf-8');
  481. }
  482. return $result;
  483. // return $inputString;
  484. }
  485. public function Pinyin(Request $request)
  486. {
  487. try {
  488. $id = $request->input('id');
  489. $type = $request->input('type',0);
  490. $task = TaskList::query()->find($id);
  491. $result = $this->extracted($task);
  492. return view('pdf', ['data' => $result, 'img' => $task->image,'title' => $task->title,'type' => $type]);
  493. } catch (\Exception $exception) {
  494. LogHelper::exceptionLog($exception, $this->code);
  495. return Response::fail($exception->getMessage());
  496. }
  497. }
  498. public function containsPunctuation($str)
  499. {
  500. // 定义要检测的符号
  501. $punctuation = '/[,。!、.1234567890:]/u'; // 中文逗号、中文句号、中文感叹号
  502. // 使用 preg_match 函数进行匹配
  503. return 1 === preg_match($punctuation, $str);
  504. }
  505. public function generate_pdf($html_path = '', $file_name = '')
  506. {
  507. if (empty($file_name)) {
  508. $file_name = md5(time()) . '.pdf';
  509. }
  510. $path = public_path() . '/file/pdf/' . $file_name;
  511. var_dump($path);
  512. exit;
  513. $shell = 'wkhtmltopdf --outline --minimum-font-size 9 ' . $html_path . ' ' . $path;
  514. exec($shell, $result, $status);
  515. if ($status) {
  516. $this->exit_out('生成PDF失败', ['生成PDF失败' => [$shell, $result, $status]]);
  517. }
  518. $domain = request()->getScheme() . '://' . request()->getHost();
  519. return $domain . '/file/pdf/' . $file_name;
  520. }
  521. public function exit_out($msg, $exceptionData = false, $code = 1, $data = [])
  522. {
  523. $out = ['code' => $code, 'msg' => $msg, 'data' => $data];
  524. if (false !== $exceptionData) {
  525. $this->trace([$msg => $exceptionData], 'error');
  526. }
  527. $json = json_encode($out, JSON_UNESCAPED_UNICODE);
  528. throw new ApiException($json);
  529. }
  530. public function trace($log = '', $level = 'info')
  531. {
  532. Log::log($level, $log);
  533. }
  534. /**
  535. * 保存图片.
  536. *
  537. * @return \Illuminate\Http\JsonResponse|string
  538. */
  539. private function saveImage($image_url)
  540. {
  541. $imageContent = file_get_contents($image_url);
  542. $imageDir = public_path(). '/file/sd/' . date('Ymd') . '/';
  543. $imageName = uniqid() . time() . '_image.png';
  544. $imagePath = $imageDir . $imageName;
  545. Log::warning('saveImage imageDir:'.$imageDir);
  546. if (!is_dir($imageDir)) {
  547. Log::warning('saveImage imageDir mkdir:'.$imageDir);
  548. mkdir($imageDir, 0777, true);
  549. }
  550. if (false !== $imageContent) {
  551. $savedImages = file_put_contents($imagePath, $imageContent);
  552. if (false !== $savedImages) {
  553. return request()->getHost() . '/file/sd/' . date('Ymd') . '/' . $imageName;
  554. }
  555. return false;
  556. }
  557. return false;
  558. }
  559. /**
  560. * 执行请求
  561. */
  562. private function host($postData)
  563. {
  564. $ch = curl_init();
  565. curl_setopt_array($ch, [
  566. CURLOPT_URL => 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=' . Helper::getAccessToken(),
  567. CURLOPT_RETURNTRANSFER => true,
  568. CURLOPT_POST => true,
  569. CURLOPT_POSTFIELDS => $postData,
  570. ]);
  571. $res = curl_exec($ch);
  572. curl_close($ch);
  573. return json_decode(trim($res), true);
  574. }
  575. public function extracted($result,$type = 0,$sdImage = ''): string
  576. {
  577. if ($type == 0){
  578. $inputString = $result->init_content;
  579. $sdImage = $result->sd_image;
  580. }else{
  581. $inputString = $result;
  582. }
  583. $inputString = str_replace('“', '', $inputString);
  584. $inputString = str_replace('”', '', $inputString);
  585. $inputString = str_replace('——', '', $inputString);
  586. $inputString = str_replace('—', '', $inputString);
  587. $inputStringFor = $this->splitChineseCharacters($inputString, 1);
  588. $arr = [];
  589. $i = 0;
  590. foreach ($inputStringFor as $key => $value) {
  591. if ("\n" == $value) {
  592. $arr[] = $key - $i;
  593. $i++;
  594. }
  595. }
  596. $splitCharacters = $this->splitChineseCharacters($inputString);
  597. $pinyin = Pinyin::Sentence($inputString)->toArray();
  598. $string = '';
  599. $count = 0;
  600. foreach ($pinyin as $value) {
  601. $count += mb_strlen($value);
  602. }
  603. $img = '<img style="width: 100%;height:auto;float: right;margin-right: 10px;margin-top: 10px; margin-bottom: 5px" src="https://' . $sdImage . '"/>';
  604. $stringCount = 0;
  605. foreach ($pinyin as $key => $value) {
  606. if ($this->containsPunctuation($value)) {
  607. $value = '&nbsp;';
  608. }
  609. $stringCount += mb_strlen($value);
  610. if (in_array($count - $stringCount, [158, 159, 160, 161, 162, 163]) && !strstr($string, '<img')) {
  611. $string = $string . $img;
  612. }
  613. if (in_array($key + 1, $arr)) {
  614. if ($result->is_piny){
  615. $string = $string . "<span><sup>{$value}</sup>{$splitCharacters[$key]}</span><br style='clear: both'><br style='clear: both'>";
  616. }else{
  617. $string = $string . "<span>{$splitCharacters[$key]}</span><br style='clear: both'><br style='clear: both'>";
  618. }
  619. } else {
  620. $style = '';
  621. if (in_array($key, $arr) || 0 == $key) {
  622. $style = 'style="margin-left: 5rem"';
  623. }
  624. if ($result->is_piny){
  625. $string = $string . '<span ' . $style . "><sup>{$value}</sup>{$splitCharacters[$key]}</span>";
  626. }else{
  627. $string = $string . '<span ' . $style . ">{$splitCharacters[$key]}</span>";
  628. }
  629. }
  630. // if (in_array($key + 1, $arr)) {
  631. // $string = $string . "<span><sup>{$value}</sup>{$splitCharacters[$key]}</span><br style='clear: both'><br style='clear: both'>";
  632. // } else {
  633. // $style = '';
  634. // if (in_array($key, $arr) || 0 == $key) {
  635. // $style = 'style="margin-left: 5rem"';
  636. // }
  637. // $string = $string . '<span ' . $style . "><sup>{$value}</sup>{$splitCharacters[$key]}</span>";
  638. // }
  639. }
  640. return $string;
  641. }
  642. }