DeepSeekService.php 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Facade\Site;
  5. use App\Libs\Utils;
  6. use GuzzleHttp\Client;
  7. use DateTime;
  8. use DateTimeZone;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. use Illuminate\Support\Facades\Redis;
  12. use OSS\Core\OssException;
  13. use OSS\OssClient;
  14. use Smalot\PdfParser\Parser as PdfParser;
  15. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  16. class DeepSeekService
  17. {
  18. private $url;
  19. private $api_key;
  20. private $client;
  21. private $headers;
  22. public function __construct() {
  23. $this->url = 'https://api.deepseek.com/chat/completions';
  24. $this->api_key = env('DEEPSEEK_API_KEY');
  25. $this->headers = [
  26. 'Authorization' => 'Bearer '.$this->api_key,
  27. 'Content-Type' => 'application/json; charset=UTF-8'
  28. ];
  29. }
  30. // 与推理模型对话
  31. public function chatWithReasoner($data) {
  32. $content = getProp($data, 'content');
  33. $model = getProp($data, 'model', 'r1');
  34. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  35. // 获取可选情感(根据音色可支持情感选)
  36. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  37. $emotion_list = [];
  38. foreach ($timbre_emotion as $emotion) {
  39. $tmp = explode(',', $emotion);
  40. $emotion_list = array_merge($emotion_list, $tmp);
  41. }
  42. $emotion_list = array_unique($emotion_list);
  43. $emotion_str = implode('、', $emotion_list);
  44. // // 获取可选情感
  45. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  46. // $emotion_str = implode('、', $emotion_list);
  47. // 是否启用情感
  48. $enable_emotion = getProp($data, 'enable_emotion', 0);
  49. if ($enable_emotion) {
  50. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  51. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  52. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  53. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  54. }else {
  55. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  56. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  57. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  58. }
  59. $messages = [
  60. [
  61. 'role' => 'system',
  62. 'content' => $sys_content
  63. ],
  64. [
  65. 'role' => 'user',
  66. 'content' => $content
  67. ]
  68. ];
  69. $post_data = [
  70. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  71. 'messages' => $messages,
  72. 'max_tokens' => 8192,
  73. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  74. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  75. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  76. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  77. 'response_format' => [
  78. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  79. ],
  80. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  81. ];
  82. $client = new Client(['timeout' => 1200, 'verify' => false]);
  83. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  84. $response = $result->getBody()->getContents();
  85. $response_arr = json_decode($response, true);
  86. $update_data = [];
  87. $content = '';
  88. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  89. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  90. $update_data = [
  91. 'role' => 'assistant',
  92. 'content' => $response_arr['choices'][0]['message']['content'],
  93. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  94. ];
  95. }
  96. // 处理获取到的剧本数据
  97. $script_content = handleScriptWords($content, $enable_emotion);
  98. $result = [
  99. 'origin_content' => $content,
  100. 'roles' => getProp($script_content, 'roles'),
  101. 'words' => getProp($script_content, 'words'),
  102. ];
  103. return $result;
  104. }
  105. public function resetParagraphAudio($data) {
  106. $bid = getProp($data, 'bid');
  107. $cid = getProp($data, 'cid');
  108. $version_id = getProp($data, 'version_id');
  109. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  110. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  111. 'generate_status' => '待制作',
  112. 'updated_at' => date('Y-m-d H:i:s')
  113. ]);
  114. }
  115. public function saveParagraphAudio($data) {
  116. $bid = getProp($data, 'bid');
  117. $cid = getProp($data, 'cid');
  118. $version_id = getProp($data, 'version_id');
  119. $sequence = getProp($data, 'sequence');
  120. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  121. // 获取所有情感
  122. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  123. $emotion_list = array_flip($emotion_list);
  124. // 获取音色支持情感
  125. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  126. $timbre_emotion = explode(',', $timbre_emotion);
  127. $emotion = getProp($data, 'emotion');
  128. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  129. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  130. $list = [
  131. 'bid' => $bid,
  132. 'cid' => $cid,
  133. 'version_id' => $version_id,
  134. 'sequence' => $sequence,
  135. 'role' => getProp($data, 'role'),
  136. 'gender' => getProp($data, 'gender'),
  137. 'text' => trim(getProp($data, 'text')),
  138. 'emotion' => $emotion,
  139. 'emotion_type' => $emotion_type,
  140. 'voice_type' => getProp($data, 'voice_type'),
  141. 'voice_name' => getProp($data, 'voice_name'),
  142. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  143. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  144. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  145. 'pitch' => getProp($data, 'pitch', 0),
  146. // 'paragraph_audio_url' => '',
  147. 'generate_status' => '制作中',
  148. 'error_msg' => '',
  149. 'updated_at' => date('Y-m-d H:i:s')
  150. ];
  151. $continue = false;
  152. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  153. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  154. $list['generate_status'] = '制作成功';
  155. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  156. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  157. $continue = true;
  158. }
  159. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  160. if ($id) {
  161. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  162. }else {
  163. $list['created_at'] = date('Y-m-d H:i:s');
  164. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  165. $boolen = $id ? true : false;
  166. }
  167. // 如果更新成功则加入查询队列
  168. if ($boolen) {
  169. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  170. Redis::sadd($redis_key, $id);
  171. }
  172. if ($boolen && !$continue) {
  173. $boolen = false;
  174. $client = new Client(['timeout' => 300, 'verify' => false]);
  175. // 根据ID通过API通知合成音频
  176. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  177. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  178. $response = $result->getBody()->getContents();
  179. $response_arr = json_decode($response, true);
  180. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  181. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  182. Log::info('通知火山生成段落音频失败: '.$error_msg);
  183. Utils::throwError('20003:通知火山生成段落音频失败');
  184. }
  185. $boolen = true;
  186. }
  187. return $boolen;
  188. }
  189. public function insertAudioEffect($data) {
  190. $audio_id = getProp($data, 'audio_id');
  191. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  192. $bid = getProp($chapter_audio, 'bid');
  193. $version_id = getProp($chapter_audio, 'version_id');
  194. $cid = getProp($chapter_audio, 'cid');
  195. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  196. $audio_effect_json = getProp($data, 'audio_effect_json');
  197. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  198. try {
  199. DB::beginTransaction();
  200. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  201. if (!$count) {
  202. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  203. }else {
  204. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  205. }
  206. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  207. 'audio_effect_status' => '添加中',
  208. 'audio_effect_json' => $audio_effect_json,
  209. 'updated_at' => date('Y-m-d H:i:s')
  210. ]);
  211. if (!$boolen1) {
  212. DB::rollBack();
  213. Utils::throwError('20003:更新生成数据失败');
  214. }
  215. $id = DB::table('mp_audio_tasks')->insertGetId([
  216. 'audio_id' => $audio_id,
  217. 'generate_status' => '执行中',
  218. 'generate_json' => json_encode([], 256),
  219. 'bid' => $bid,
  220. 'book_name' => getProp($chapter_audio, 'book_name'),
  221. 'version_id' => $version_id,
  222. 'version_name' => getProp($chapter_audio, 'version_name'),
  223. 'cid' => $cid,
  224. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  225. 'task_name' => $task_name,
  226. 'created_at' => date('Y-m-d H:i:s'),
  227. 'updated_at' => date('Y-m-d H:i:s')
  228. ]);
  229. if (!$id) {
  230. DB::rollBack();
  231. Utils::throwError('20003:创建任务失败');
  232. }
  233. }catch (\Exception $e) {
  234. DB::rollBack();
  235. Utils::throwError('20003:'.$e->getMessage());
  236. }
  237. DB::commit();
  238. $client = new Client(['timeout' => 300, 'verify' => false]);
  239. // 根据ID通过API通知合成音频
  240. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  241. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  242. $response = $result->getBody()->getContents();
  243. $response_arr = json_decode($response, true);
  244. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  245. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  246. Log::info('通知火山插入音效失败: '.$error_msg);
  247. Utils::throwError('20003:通知火山插入音效失败');
  248. }
  249. return true;
  250. }
  251. public function insertBgm($data) {
  252. $audio_id = getProp($data, 'audio_id');
  253. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  254. $bid = getProp($chapter_audio, 'bid');
  255. $version_id = getProp($chapter_audio, 'version_id');
  256. $cid = getProp($chapter_audio, 'cid');
  257. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  258. $bgm_json = getProp($data, 'bgm_json');
  259. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  260. if (!$bgm_json) {
  261. $bgm_json = getProp($data, 'audio_effect_json');
  262. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  263. }
  264. try {
  265. DB::beginTransaction();
  266. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  267. if (!$count) {
  268. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  269. }else {
  270. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  271. }
  272. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  273. 'bgm_status' => '添加中',
  274. 'bgm_json' => $bgm_json,
  275. 'updated_at' => date('Y-m-d H:i:s')
  276. ]);
  277. if (!$boolen1) {
  278. DB::rollBack();
  279. Utils::throwError('20003:更新生成数据失败');
  280. }
  281. $id = DB::table('mp_audio_tasks')->insertGetId([
  282. 'audio_id' => $audio_id,
  283. 'generate_status' => '执行中',
  284. 'generate_json' => json_encode([], 256),
  285. 'bid' => $bid,
  286. 'book_name' => getProp($chapter_audio, 'book_name'),
  287. 'version_id' => $version_id,
  288. 'version_name' => getProp($chapter_audio, 'version_name'),
  289. 'cid' => $cid,
  290. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  291. 'task_name' => $task_name,
  292. 'created_at' => date('Y-m-d H:i:s'),
  293. 'updated_at' => date('Y-m-d H:i:s')
  294. ]);
  295. if (!$id) {
  296. DB::rollBack();
  297. Utils::throwError('20003:创建任务失败');
  298. }
  299. }catch (\Exception $e) {
  300. DB::rollBack();
  301. Utils::throwError('20003:'.$e->getMessage());
  302. }
  303. DB::commit();
  304. $client = new Client(['timeout' => 300, 'verify' => false]);
  305. // 根据ID通过API通知合成音频
  306. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  307. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  308. $response = $result->getBody()->getContents();
  309. $response_arr = json_decode($response, true);
  310. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  311. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  312. Log::info('通知火山插入bgm失败: '.$error_msg);
  313. Utils::throwError('20003:通知火山插入bgm失败');
  314. }
  315. return true;
  316. }
  317. public function getParagraphAudios($data) {
  318. $bid = getProp($data, 'bid');
  319. $cid = getProp($data, 'cid');
  320. $version_id = getProp($data, 'version_id');
  321. $sequence = getProp($data, 'sequence');
  322. // 获取已生成的音频
  323. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  324. if ($sequence) $query->where('sequence', $sequence);
  325. $paragraph_audios = $query->orderBy('sequence')->get();
  326. $result = [];
  327. foreach($paragraph_audios as $item) {
  328. $result[] = [
  329. 'sequence' => getProp($item, 'sequence'),
  330. 'role' => getProp($item, 'role'),
  331. 'gender' => getProp($item, 'gender'),
  332. 'text' => trim(getProp($item, 'text')),
  333. 'emotion' => getProp($item, 'emotion'),
  334. 'emotion_type' => getProp($item, 'emotion_type'),
  335. 'voice_type' => getProp($item, 'voice_type'),
  336. 'voice_name' => getProp($item, 'voice_name'),
  337. 'speed_ratio' => getProp($item, 'speed_ratio'),
  338. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  339. 'emotion_scale' => getProp($item, 'emotion_scale'),
  340. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  341. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  342. ];
  343. }
  344. return $result;
  345. }
  346. // 新增合成任务
  347. public function addGenerateTask($data) {
  348. $bid = getProp($data, 'bid');
  349. $cid = getProp($data, 'cid');
  350. $version_id = getProp($data, 'version_id');
  351. $generate_json = getProp($data, 'generate_json');
  352. // 获取已生成的音频
  353. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  354. $paragraph_list = [];
  355. foreach($paragraph_audios as $item) {
  356. $paragraph_list[getProp($item, 'sequence')] = [
  357. 'role' => getProp($item, 'role'),
  358. 'gender' => getProp($item, 'gender'),
  359. 'text' => trim(getProp($item, 'text')),
  360. 'emotion' => getProp($item, 'emotion'),
  361. 'emotion_type' => getProp($item, 'emotion_type'),
  362. 'voice_type' => getProp($item, 'voice_type'),
  363. 'voice_name' => getProp($item, 'voice_name'),
  364. 'speed_ratio' => getProp($item, 'speed_ratio'),
  365. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  366. 'emotion_scale' => getProp($item, 'emotion_scale'),
  367. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  368. ];
  369. }
  370. // 更新角色-音色信息
  371. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  372. $existed_role_info = json_decode($existed_role_info, true);
  373. if (!$existed_role_info) $existed_role_info = [];
  374. // 获取情感信息
  375. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  376. $emotion_list = array_flip($emotion_list);
  377. // 获取音色对应情感组
  378. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  379. $timbre_emotion_list = [];
  380. foreach($timbre_emotions as $item) {
  381. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  382. }
  383. // 构造生成音频的json
  384. $words = json_decode($generate_json, true);
  385. // 最终合成前的参数组
  386. $mp_chapter_paragraph_audios = [];
  387. $sequence = 1;
  388. $complete_paragraph_sequences = [];
  389. foreach($words as &$word) {
  390. if (!isset($word['text']) || !isset($word['emotion']) || !isset($word['voice_type']) || !isset($word['voice_name']) || !isset($word['speed_ratio']) || !isset($word['loudness_ratio']) || !isset($word['emotion_scale'])) Utils::throwError('20003:参数格式有误');
  391. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  392. $role = getProp($word, 'role');
  393. $word['gender'] = (int)$word['gender'];
  394. // 判断音色对应情感是否支持,不支持则调整为中性
  395. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  396. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  397. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  398. if (isset($emotion_list[getProp($word, 'emotion')])) {
  399. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  400. }else {
  401. $word['emotion'] = '中性';
  402. $word['emotion_type'] = 'neutral';
  403. }
  404. $existed_role_info[$role] = [
  405. 'timbre_type' => $word['voice_type'],
  406. 'timbre_name' => $word['voice_name'],
  407. 'emotion' => $word['emotion'],
  408. 'emotion_type' => $word['emotion_type'],
  409. 'speed_ratio' => $word['speed_ratio'],
  410. 'loudness_ratio'=> $word['loudness_ratio'],
  411. 'emotion_scale' => $word['emotion_scale'],
  412. 'pitch' => $word['pitch']
  413. ];
  414. $word['paragraph_audio_url'] = '';
  415. // 判断生成参数是否相同,相同则直接使用已生成的音频
  416. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  417. // 如果音频存在并且参数都未改变则使用已生成的音频
  418. if (getProp($paragraph, 'paragraph_audio_url')) {
  419. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  420. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  421. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  422. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  423. // {
  424. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  425. // }
  426. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  427. }
  428. $tmp = $word;
  429. // 组装章节分句音频数据
  430. // $tmp['sequence'] = getProp($word, 'sequence');
  431. // $tmp['text'] = getProp($word, 'text');
  432. // $tmp['emotion'] = getProp($word, 'emotion');
  433. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  434. // $tmp['voice_name'] = getProp($word, 'voice_name');
  435. // $tmp['voice_type'] = getProp($word, 'voice_type');
  436. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  437. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  438. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  439. $tmp['bid'] = $bid;
  440. $tmp['version_id'] = $version_id;
  441. $tmp['cid'] = $cid;
  442. $tmp['sequence'] = $sequence;
  443. $tmp['created_at'] = date('Y-m-d H:i:s');
  444. $tmp['updated_at'] = date('Y-m-d H:i:s');
  445. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  446. $mp_chapter_paragraph_audios[] = $tmp;
  447. $complete_paragraph_sequences[] = $sequence;
  448. $sequence++;
  449. }
  450. $generate_json = json_encode($words, 256);
  451. // 判断是否有未生成字幕的段落
  452. $no_subtitle_sequences = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->whereIn('sequence', $complete_paragraph_sequences)->whereNull('subtitle_info')->pluck('sequence')->toArray();
  453. if ($no_subtitle_sequences) {
  454. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  455. }
  456. try {
  457. DB::beginTransaction();
  458. $role_info = json_encode($existed_role_info, 256);
  459. $boolen = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->update(['role_info' => $role_info, 'updated_at' => date('Y-m-d H:i:s')]);
  460. if (!$boolen) {
  461. DB::rollBack();
  462. Utils::throwError('20003:更新角色信息失败');
  463. }
  464. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  465. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  466. if (!$count) {
  467. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  468. }else {
  469. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  470. }
  471. $boolen1 = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->update(['generate_status'=>'制作中', 'generate_json' => $generate_json, 'updated_at' => date('Y-m-d H:i:s')]);
  472. if (!$boolen1) {
  473. DB::rollBack();
  474. Utils::throwError('20003:更新生成数据失败');
  475. }
  476. $id = DB::table('mp_audio_tasks')->insertGetId([
  477. 'audio_id' => getProp($chapter_audio, 'id'),
  478. 'generate_status' => '执行中',
  479. 'generate_json' => $generate_json,
  480. 'bid' => $bid,
  481. 'book_name' => getProp($chapter_audio, 'book_name'),
  482. 'version_id' => $version_id,
  483. 'version_name' => getProp($chapter_audio, 'version_name'),
  484. 'cid' => $cid,
  485. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  486. 'task_name' => $task_name,
  487. 'created_at' => date('Y-m-d H:i:s'),
  488. 'updated_at' => date('Y-m-d H:i:s')
  489. ]);
  490. if (!$id) {
  491. DB::rollBack();
  492. Utils::throwError('20003:创建任务失败');
  493. }
  494. // 删除不在段落序号范围内的其他数据
  495. if ($complete_paragraph_sequences) {
  496. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  497. }
  498. // // 删除章节分句音频数据并重新插入
  499. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  500. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  501. // if (!$boolen3) {
  502. // DB::rollBack();
  503. // Utils::throwError('20003:更新章节分句音频失败');
  504. // }
  505. } catch (\Exception $e) {
  506. DB::rollBack();
  507. Utils::throwError('20003:'.$e->getMessage());
  508. }
  509. DB::commit();
  510. // 通知火山生成音频
  511. $client = new Client(['timeout' => 300, 'verify' => false]);
  512. // 根据ID通过API通知合成音频
  513. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  514. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  515. $response = $result->getBody()->getContents();
  516. $response_arr = json_decode($response, true);
  517. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  518. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  519. Log::info('通知火山生成音频失败: '.$error_msg);
  520. Utils::throwError('20003:通知火山生成音频失败');
  521. }
  522. return true;
  523. }
  524. public function timbreList($data) {
  525. $gender = getProp($data, 'gender');
  526. $timbre_name = getProp($data, 'voice_name');
  527. $category_id = getProp($data, 'category_id');
  528. $query = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_name as voice_name', 'timbre_type as voice_type', 'gender', 'language', 'emotion', 'label', 'first_category_id', 'first_category_name', 'second_category_id', 'second_category_name', 'third_category_id', 'third_category_name', 'audio_url');
  529. if ($gender) {
  530. $query->where('gender', $gender);
  531. }
  532. if ($timbre_name) {
  533. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  534. }
  535. if ($category_id) {
  536. $query->where(function ($query) use ($category_id) {
  537. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  538. });
  539. }
  540. $list = $query->get()->map(function ($value) {
  541. $value = (array)$value;
  542. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  543. return $value;
  544. })->toArray();
  545. return $list;
  546. }
  547. // 生成火山临时token
  548. public function setStsToken() {
  549. // ************* 配置参数 *************
  550. $method = 'GET';
  551. $service = 'sts';
  552. $host = 'open.volcengineapi.com';
  553. $region = env('VOLC_REGION');
  554. $endpoint = 'https://open.volcengineapi.com';
  555. // $endpoint = 'https://tos-cn-beijing.volces.com';
  556. $access_key = env('VOLC_AK');
  557. $secret_key = env('VOLC_SK');
  558. // 获取缓存中的token,如果没有则请求接口
  559. $token = Redis::get('volc_sts_token');
  560. if (!$token) {
  561. // 查询参数
  562. $query_parameters = [
  563. 'Action' => 'AssumeRole',
  564. 'RoleSessionName' => 'user@zw',
  565. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  566. 'Version' => '2018-01-01'
  567. ];
  568. // 生成URL编码的查询字符串
  569. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  570. // 获取签名头信息
  571. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  572. // 构建完整URL
  573. $request_url = $endpoint . '?' . $request_parameters;
  574. $client = new Client(['verify' => false]);
  575. $response = $client->get($request_url, ['headers' => $headers]);
  576. $response_arr = json_decode($response->getBody()->getContents(), true);
  577. $result = [
  578. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  579. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  580. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  581. 'Region' => env('VOLC_REGION'),
  582. 'Endpoint' => env('VOLC_END_POINT'),
  583. 'Bucket' => env('VOLC_BUCKET'),
  584. ];
  585. // 缓存token
  586. Redis::setex('volc_sts_token', 3000, json_encode($result));
  587. return $result;
  588. } else {
  589. return json_decode($token, true);
  590. }
  591. // $response = $response['Response'];
  592. // $access_key = $response['Credentials']['AccessKeyId'];
  593. // $secret_key = $response['Credentials']['AccessKeySecret'];
  594. // $security_token = $response['Credentials']['SecurityToken'];
  595. // $expiration = $response['Credentials']['Expiration'];
  596. // dd($response_arr);
  597. }
  598. public function emotionGroups($data) {
  599. $id = getProp($data, 'group_id');
  600. $group_name = getProp($data, 'group_name');
  601. $voice_type = getProp($data, 'voice_type');
  602. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  603. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  604. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  605. if ($group_name) {
  606. $query->where('group_name', 'like', "%{$group_name}%");
  607. }
  608. if ($id) {
  609. $query->where('id', $id);
  610. }
  611. if ($voice_type) {
  612. $query->where('voice_type', $voice_type);
  613. }
  614. return $query->orderBy('id')->get()->map(function ($value) {
  615. return (array)$value;
  616. })->toArray();
  617. }
  618. private function sign($key, $msg) {
  619. return hash_hmac('sha256', $msg, $key, true);
  620. }
  621. // 生成签名密钥
  622. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  623. $kDate = $this->sign($key, $dateStamp);
  624. $kRegion = $this->sign($kDate, $regionName);
  625. $kService = $this->sign($kRegion, $serviceName);
  626. $kSigning = $this->sign($kService, 'request');
  627. return $kSigning;
  628. }
  629. // 获取签名头信息
  630. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  631. $contenttype = 'application/x-www-form-urlencoded';
  632. $accept = 'application/json';
  633. // 获取当前UTC时间
  634. $t = new DateTime('now', new DateTimeZone('UTC'));
  635. $xdate = $t->format('Ymd\THis\Z');
  636. $datestamp = $t->format('Ymd');
  637. // 1. 拼接规范请求串
  638. $canonical_uri = '/';
  639. $canonical_querystring = $request_parameters;
  640. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  641. $signed_headers = 'content-type;host;x-date';
  642. // 空请求体的SHA256哈希
  643. $payload_hash = hash('sha256', '');
  644. $canonical_request = implode("\n", [
  645. $method,
  646. $canonical_uri,
  647. $canonical_querystring,
  648. $canonical_headers,
  649. $signed_headers,
  650. $payload_hash
  651. ]);
  652. // 2. 拼接待签名字符串
  653. $algorithm = 'HMAC-SHA256';
  654. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  655. $hashed_canonical_request = hash('sha256', $canonical_request);
  656. $string_to_sign = implode("\n", [
  657. $algorithm,
  658. $xdate,
  659. $credential_scope,
  660. $hashed_canonical_request
  661. ]);
  662. // 3. 计算签名
  663. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  664. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  665. // 4. 添加签名到请求头
  666. $authorization_header = sprintf(
  667. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  668. $algorithm,
  669. $access_key,
  670. $credential_scope,
  671. $signed_headers,
  672. $signature
  673. );
  674. return [
  675. 'Accept' => $accept,
  676. 'Content-Type' => $contenttype,
  677. 'X-Date' => $xdate,
  678. 'Authorization' => $authorization_header
  679. ];
  680. }
  681. // 文字合成语音(火山引擎)
  682. public function tts($data) {
  683. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  684. $headers = [
  685. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  686. 'Content-Type' => 'application/json; charset=UTF-8'
  687. ];
  688. $post_data = [
  689. 'app' => [
  690. 'appid' => env('VOLC_APPID'),
  691. 'token' => env('VOLC_TOKEN'),
  692. 'cluster' => 'volcano_tts'
  693. ],
  694. 'user' => [
  695. 'uid' => 'mp_audio'
  696. ],
  697. // 'audio' => [
  698. // 'voice_type' =>
  699. // ],
  700. ];
  701. }
  702. public function scriptList($data) {
  703. $script_id = getProp($data, 'script_id');
  704. $script_name = getProp($data, 'script_name');
  705. $query = DB::table('mp_scripts')->where('is_deleted', 0)->select('*');
  706. if ($script_id) {
  707. $query->where('id', $script_id);
  708. }
  709. if ($script_name) {
  710. $query->where('script_name', 'like', "%{$script_name}%");
  711. }
  712. return $query->orderBy('created_at', 'desc')->paginate(12);
  713. }
  714. public function scriptInfo($data) {
  715. $script_id = getProp($data, 'script_id');
  716. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  717. ->selectRaw('id as script_id, script_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_sequence, end_episode_sequence, episode_num, remark, created_at')->first();
  718. if (!$script) Utils::throwError('20003:该剧本不存在!');
  719. $script = (array)$script;
  720. $status_arr =[
  721. '1' => '待创作',
  722. '2' => '解析中',
  723. '3' => '解析完成',
  724. '4' => '解析失败',
  725. ];
  726. $script['status_info'] = isset($status_arr[$script['status']]) ? $status_arr[$script['status']] : '';
  727. $script['roles'] = json_decode($script['roles']);
  728. $script['scenes'] = json_decode($script['scenes']);
  729. // 获取分集信息
  730. $episodes = DB::table('mp_script_episodes')->where('script_id', $script_id)->orderBy('episode_number')
  731. ->select('id', 'episode_number', 'title', 'content')
  732. ->get()->map(function ($value) {
  733. return (array)$value;
  734. })->toArray();
  735. $script['episodes'] = $episodes;
  736. return $script;
  737. }
  738. public function createScript($data) {
  739. $script_name = getProp($data, 'script_name');
  740. $uid = Site::getUid(); // 获取当前用户ID
  741. if (!$script_name) Utils::throwError('20001:剧本名称不能为空');
  742. return DB::table('mp_scripts')->insertGetId([
  743. 'script_name' => $script_name,
  744. 'user_id' => $uid,
  745. 'created_at' => date('Y-m-d H:i:s'),
  746. 'updated_at' => date('Y-m-d H:i:s')
  747. ]);
  748. }
  749. /**
  750. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  751. *
  752. * @param array $data 包含以下参数:
  753. * - file: 上传的文件(UploadedFile 对象)或文件路径
  754. * - question: 用户问题(可选)
  755. * - model: 使用的模型(r1 或 v3,默认 v3)
  756. * @return \Generator 返回生成器,用于流式输出
  757. */
  758. public function chatWithFileStream($data) {
  759. $script_id = getProp($data, 'script_id');
  760. $file = getProp($data, 'file');
  761. $content = getProp($data, 'content', '');
  762. $bid = getProp($data, 'bid', 0);
  763. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  764. $total_episode_num = getProp($data, 'total_episode_num', 30);
  765. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。");
  766. $model = getProp($data, 'model', 'r1');
  767. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  768. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  769. if (!$script) {
  770. Utils::throwError('20003:剧本不存在');
  771. }
  772. if (!$file && !$content && !$bid) {
  773. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  774. }
  775. // 提取文件内容
  776. if ($content) {
  777. $content = filterContent($content);
  778. } elseif ($file) {
  779. $content = $this->extractFileContent($file);
  780. if (!$content) {
  781. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  782. }
  783. } elseif ($bid) {
  784. $content = $this->getContentByBid($bid);
  785. if (!$content) {
  786. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  787. }
  788. } else {
  789. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  790. }
  791. // 构建消息
  792. $messages = [
  793. [
  794. 'role' => 'system',
  795. 'content' => '你是一个专业的文档分析助手及编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间用###分隔;同时<分集剧本>要求包含"分集序号"、"场景描述"、"出场角色"和"台词内容"这几个部分。示例如下:\n\n
  796. ###故事梗概
  797. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒"问心刺",气息奄奄。少年梁萧心急如焚,用奇珍"阴阳球"稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出"问心刺",竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  798. ###剧本亮点
  799. 亮点1:绝境奇药,生死一线
  800. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将"阴阳球"塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  801. 亮点2:结拜兄妹,化解尴尬
  802. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句"我……我愿意的"带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  803. 亮点3:纤发夺命,情愫暗涌
  804. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当"问心刺"被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  805. ###人物关系
  806. 阿雪与梁萧之间存在兄妹之情。
  807. ###核心矛盾
  808. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出"问心刺",竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  809. ###主体列表
  810. 阿雪-病重:身中奇毒"问心刺",气息奄奄,面色苍白,身体虚弱。
  811. 阿雪-羞涩:经"阴阳球"救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  812. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  813. 阴阳球:天地异宝,能化生精气,救人于危难。
  814. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  815. ###美术风格
  816. 基础画风风格词:厚涂古风
  817. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出"阴阳球"的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  818. ###场景列表
  819. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  820. ###分集剧本
  821. ##分集01
  822. 分集名: 第一集
  823. 场景描述:地点、时间、场景
  824. 出场角色:男主、女主
  825. 台词内容:
  826. 女主: 女主对话
  827. 男主:男主对话
  828. 女主: 女主对话
  829. 男主: 男主对话
  830. ##分集02
  831. 分集名: 第二集
  832. 场景描述:地点、时间、场景
  833. 出场角色:男主、女主
  834. 台词内容:
  835. 女主: 女主对话
  836. 男主:男主对话
  837. 女主: 女主对话
  838. 男主: 男主对话'
  839. ],
  840. [
  841. 'role' => 'user',
  842. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  843. ]
  844. ];
  845. $post_data = [
  846. 'model' => $model,
  847. 'messages' => $messages,
  848. 'max_tokens' => 8192,
  849. 'temperature' => 0.7,
  850. 'frequency_penalty' => 0,
  851. 'presence_penalty' => 0,
  852. 'response_format' => ['type' => 'text'],
  853. 'stream' => true // 启用流式输出
  854. ];
  855. $client = new Client(['timeout' => 1200, 'verify' => false]);
  856. $response = $client->post($this->url, [
  857. 'json' => $post_data,
  858. 'headers' => $this->headers,
  859. 'stream' => true // 启用流式响应
  860. ]);
  861. $body = $response->getBody();
  862. $fullContent = '';
  863. $fullReasoningContent = '';
  864. $usage = [];
  865. $buffer = '';
  866. Log::info('开始读取 DeepSeek 流式响应');
  867. // 逐行读取流式响应
  868. while (!$body->eof()) {
  869. $chunk = $body->read(1024); // 每次读取 1KB
  870. $buffer .= $chunk;
  871. // 按行分割
  872. $lines = explode("\n", $buffer);
  873. // 保留最后一个不完整的行
  874. $buffer = array_pop($lines);
  875. foreach ($lines as $line) {
  876. $line = trim($line);
  877. // 跳过空行
  878. if (empty($line)) {
  879. continue;
  880. }
  881. Log::info('收到原始行数据', ['line' => $line]);
  882. // 检查是否是 SSE 数据行
  883. if (strpos($line, 'data: ') !== 0) {
  884. Log::warning('非 SSE 数据行', ['line' => $line]);
  885. continue;
  886. }
  887. $data = substr($line, 6); // 移除 "data: " 前缀
  888. if ($data === '[DONE]') {
  889. Log::info('收到结束标记');
  890. break 2; // 跳出两层循环
  891. }
  892. try {
  893. $json = json_decode($data, true);
  894. if (json_last_error() !== JSON_ERROR_NONE) {
  895. Log::warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  896. continue;
  897. }
  898. Log::info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  899. if (isset($json['choices'][0]['delta'])) {
  900. $delta = $json['choices'][0]['delta'];
  901. // 处理思维链内容(仅 deepseek-reasoner 模型)
  902. // 注释掉以下内容则不返回d思维链内容
  903. if (isset($delta['reasoning_content'])) {
  904. $fullReasoningContent .= $delta['reasoning_content'];
  905. Log::info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  906. yield [
  907. 'type' => 'reasoning',
  908. 'content' => $delta['reasoning_content'],
  909. 'full_reasoning' => $fullReasoningContent
  910. ];
  911. }
  912. // 处理最终回答内容
  913. if (isset($delta['content'])) {
  914. $fullContent .= $delta['content'];
  915. Log::info('输出回答内容', ['length' => strlen($delta['content'])]);
  916. yield [
  917. 'type' => 'content',
  918. 'content' => $delta['content'],
  919. 'full_content' => $fullContent
  920. ];
  921. }
  922. }
  923. // 获取使用统计信息
  924. if (isset($json['usage'])) {
  925. $usage = $json['usage'];
  926. Log::info('收到使用统计', ['usage' => $usage]);
  927. }
  928. } catch (\Exception $e) {
  929. Log::error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  930. continue;
  931. }
  932. }
  933. }
  934. Log::info('流式读取完成', [
  935. 'content_length' => strlen($fullContent),
  936. 'reasoning_length' => strlen($fullReasoningContent)
  937. ]);
  938. // 处理完整内容并返回最终结果
  939. $script_arr = [];
  940. if ($fullContent) {
  941. $script_arr = handleScriptContent($fullContent);
  942. }
  943. yield [
  944. 'type' => 'done',
  945. 'script' => $script_arr,
  946. 'answer' => $fullContent,
  947. 'reasoning' => $fullReasoningContent,
  948. 'usage' => $usage
  949. ];
  950. }
  951. /**
  952. * 上传文件识别文字内容并与 DeepSeek 进行对话
  953. *
  954. * @param array $data 包含以下参数:
  955. * - file: 上传的文件(UploadedFile 对象)或文件路径
  956. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  957. * - model: 使用的模型(r1 或 v3,默认 v3)
  958. * @return array
  959. */
  960. public function chatWithFile($data) {
  961. // dd(handleScriptContent(''));
  962. $script_id = getProp($data, 'script_id');
  963. $file = getProp($data, 'file');
  964. $content = getProp($data, 'content', '');
  965. $bid = getProp($data, 'bid', 0);
  966. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  967. $total_episode_num = getProp($data, 'total_episode_num', 30);
  968. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。");
  969. $model = getProp($data, 'model', 'v3');
  970. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  971. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  972. if (!$script) {
  973. Utils::throwError('20003:剧本不存在');
  974. }
  975. if (!$file && !$content && !$bid) {
  976. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  977. }
  978. // 提取文件内容
  979. if ($content) {
  980. $content = filterContent($content);
  981. } elseif ($file) {
  982. $content = $this->extractFileContent($file);
  983. if (!$content) {
  984. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  985. }
  986. } elseif ($bid) {
  987. $content = $this->getContentByBid($bid);
  988. if (!$content) {
  989. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  990. }
  991. } else {
  992. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  993. }
  994. // 构建消息
  995. $messages = [
  996. [
  997. 'role' => 'system',
  998. 'content' => '你是一个专业的文档分析助手及编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间用###分隔;同时<分集剧本>要求包含“分集序号”、“场景描述”、“出场角色”和“台词内容”这几个部分。示例如下:\n\n
  999. ###故事梗概
  1000. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1001. ###剧本亮点
  1002. 亮点1:绝境奇药,生死一线
  1003. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  1004. 亮点2:结拜兄妹,化解尴尬
  1005. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  1006. 亮点3:纤发夺命,情愫暗涌
  1007. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  1008. ###人物关系
  1009. 阿雪与梁萧之间存在兄妹之情。
  1010. ###核心矛盾
  1011. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1012. ###主体列表
  1013. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  1014. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  1015. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  1016. 阴阳球:天地异宝,能化生精气,救人于危难。
  1017. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  1018. ###美术风格
  1019. 基础画风风格词:厚涂古风
  1020. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  1021. ###场景列表
  1022. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  1023. ###分集剧本
  1024. ##分集01
  1025. 分集名: 第一集
  1026. 场景描述:地点、时间、场景
  1027. 出场角色:男主、女主
  1028. 台词内容:
  1029. 女主: 女主对话
  1030. 男主:男主对话
  1031. 女主: 女主对话
  1032. 男主: 男主对话
  1033. ##分集02
  1034. 分集名: 第二集
  1035. 场景描述:地点、时间、场景
  1036. 出场角色:男主、女主
  1037. 台词内容:
  1038. 女主: 女主对话
  1039. 男主:男主对话
  1040. 女主: 女主对话
  1041. 男主: 男主对话'
  1042. ],
  1043. [
  1044. 'role' => 'user',
  1045. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1046. ]
  1047. ];
  1048. $post_data = [
  1049. 'model' => $model,
  1050. 'messages' => $messages,
  1051. 'max_tokens' => 8192,
  1052. 'temperature' => 0.7,
  1053. 'frequency_penalty' => 0,
  1054. 'presence_penalty' => 0,
  1055. 'response_format' => ['type' => 'text'],
  1056. 'stream' => false
  1057. ];
  1058. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1059. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  1060. $response = $result->getBody()->getContents();
  1061. $response_arr = json_decode($response, true);
  1062. $content = '';
  1063. $usage = [];
  1064. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  1065. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  1066. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  1067. }
  1068. // 处理结果
  1069. if ($content) {
  1070. $script_arr = handleScriptContent($content);
  1071. }
  1072. return [
  1073. 'script' => $script_arr,
  1074. 'answer' => $content,
  1075. 'usage' => $usage
  1076. ];
  1077. }
  1078. public function saveScript($data) {
  1079. $script_arr =getProp($data, 'script', []);
  1080. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  1081. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1082. $script_id = getProp($data, 'script_id');
  1083. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  1084. try {
  1085. DB::beginTransaction();
  1086. $update_data = [
  1087. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1088. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1089. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1090. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1091. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], true) : '',
  1092. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1093. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], true) : '',
  1094. 'status' => 3,
  1095. 'start_episode_sequence' => $start_episode_sequence,
  1096. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  1097. 'episode_num' => count($script_arr['episodes']),
  1098. 'updated_at' => date('Y-m-d H:i:s')
  1099. ];
  1100. // 保存剧本内容
  1101. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  1102. if (!$boolen) {
  1103. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  1104. Utils::throwError('20003:剧本内容保存失败');
  1105. }
  1106. // 保存分集内容
  1107. // 删除历史分集内容
  1108. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  1109. $episodes = [];
  1110. foreach ($script_arr['episodes'] as $episode) {
  1111. $episodes[] = [
  1112. 'script_id' => $script_id,
  1113. 'episode_number' => $episode['episode_number'],
  1114. 'title' => $episode['title'],
  1115. 'content' => $episode['content'],
  1116. 'created_at' => date('Y-m-d H:i:s'),
  1117. 'updated_at' => date('Y-m-d H:i:s')
  1118. ];
  1119. }
  1120. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1121. if (!$boolen2) {
  1122. dLog('deepseek')->info('分集内容保存失败', $episodes);
  1123. Utils::throwError('20003:分集内容保存失败');
  1124. }
  1125. } catch (\Exception $e) {
  1126. DB::rollBack();
  1127. Utils::throwError('20003:'.$e->getMessage());
  1128. }
  1129. DB::commit();
  1130. return true;
  1131. }
  1132. public function getContentByBid($bid) {
  1133. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  1134. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  1135. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  1136. $content = '';
  1137. foreach ($chapters as $chapter) {
  1138. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  1139. }
  1140. return $content;
  1141. }
  1142. /**
  1143. * 根据文件类型提取文本内容
  1144. *
  1145. * @param mixed $file 文件对象或文件路径
  1146. * @return string
  1147. */
  1148. public function extractFileContent($file) {
  1149. // 获取文件路径和扩展名
  1150. if (is_string($file)) {
  1151. $filePath = $file;
  1152. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  1153. } else {
  1154. // Laravel UploadedFile 对象
  1155. $filePath = $file->getRealPath();
  1156. $extension = strtolower($file->getClientOriginalExtension());
  1157. }
  1158. $content = '';
  1159. switch ($extension) {
  1160. case 'txt':
  1161. $content = $this->extractTxtContent($filePath);
  1162. break;
  1163. case 'pdf':
  1164. $content = $this->extractPdfContent($filePath);
  1165. break;
  1166. case 'doc':
  1167. case 'docx':
  1168. $content = $this->extractWordContent($filePath);
  1169. break;
  1170. // case 'jpg':
  1171. // case 'jpeg':
  1172. // case 'png':
  1173. // case 'gif':
  1174. // case 'bmp':
  1175. // case 'webp':
  1176. // $content = $this->extractImageContent($filePath);
  1177. // break;
  1178. default:
  1179. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  1180. }
  1181. return $content;
  1182. }
  1183. /**
  1184. * 提取 TXT 文件内容
  1185. */
  1186. private function extractTxtContent($filePath) {
  1187. if (!file_exists($filePath)) {
  1188. Utils::throwError('20003:文件不存在');
  1189. }
  1190. $content = file_get_contents($filePath);
  1191. // 尝试检测并转换编码
  1192. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  1193. if ($encoding && $encoding !== 'UTF-8') {
  1194. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  1195. }
  1196. return trim($content);
  1197. }
  1198. /**
  1199. * 提取 PDF 文件内容
  1200. */
  1201. private function extractPdfContent($filePath) {
  1202. if (!file_exists($filePath)) {
  1203. Utils::throwError('20003:文件不存在');
  1204. }
  1205. try {
  1206. $parser = new PdfParser();
  1207. $pdf = $parser->parseFile($filePath);
  1208. $content = $pdf->getText();
  1209. return trim($content);
  1210. } catch (\Exception $e) {
  1211. Log::error('PDF解析失败: ' . $e->getMessage());
  1212. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  1213. }
  1214. }
  1215. /**
  1216. * 提取 Word 文件内容(支持 doc 和 docx)
  1217. */
  1218. private function extractWordContent($filePath) {
  1219. if (!file_exists($filePath)) {
  1220. Utils::throwError('20003:文件不存在');
  1221. }
  1222. try {
  1223. $phpWord = WordIOFactory::load($filePath);
  1224. $content = '';
  1225. foreach ($phpWord->getSections() as $section) {
  1226. foreach ($section->getElements() as $element) {
  1227. $content .= $this->extractWordElementText($element);
  1228. }
  1229. }
  1230. return trim($content);
  1231. } catch (\Exception $e) {
  1232. Log::error('Word解析失败: ' . $e->getMessage());
  1233. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  1234. }
  1235. }
  1236. /**
  1237. * 递归提取 Word 元素中的文本
  1238. */
  1239. private function extractWordElementText($element) {
  1240. $text = '';
  1241. if (method_exists($element, 'getText')) {
  1242. $text .= $element->getText() . "\n";
  1243. } elseif (method_exists($element, 'getElements')) {
  1244. foreach ($element->getElements() as $childElement) {
  1245. $text .= $this->extractWordElementText($childElement);
  1246. }
  1247. }
  1248. return $text;
  1249. }
  1250. /**
  1251. * 提取图片内容(使用火山引擎 OCR)
  1252. */
  1253. private function extractImageContent($filePath) {
  1254. if (!file_exists($filePath)) {
  1255. Utils::throwError('20003:文件不存在');
  1256. }
  1257. try {
  1258. // 读取图片并转换为 base64
  1259. $imageData = file_get_contents($filePath);
  1260. $base64Image = base64_encode($imageData);
  1261. // 调用火山引擎 OCR 服务
  1262. $content = $this->callVolcEngineOCR($base64Image);
  1263. return trim($content);
  1264. } catch (\Exception $e) {
  1265. Log::error('图片OCR识别失败: ' . $e->getMessage());
  1266. Utils::throwError('20003:图片识别失败');
  1267. }
  1268. }
  1269. /**
  1270. * 调用火山引擎 OCR 服务识别图片文字
  1271. *
  1272. * @param string $base64Image base64 编码的图片数据
  1273. * @return string 识别的文字内容
  1274. */
  1275. private function callVolcEngineOCR($base64Image) {
  1276. $method = 'POST';
  1277. $service = 'cv';
  1278. $host = 'visual.volcengineapi.com';
  1279. $region = env('VOLC_REGION', 'cn-north-1');
  1280. $access_key = env('VOLC_AK');
  1281. $secret_key = env('VOLC_SK');
  1282. $action = 'OCRNormal';
  1283. $version = '2020-08-26';
  1284. if (!$access_key || !$secret_key) {
  1285. Utils::throwError('20003:请配置火山引擎 AK/SK');
  1286. }
  1287. // 请求体
  1288. $body = json_encode([
  1289. 'image_base64' => $base64Image
  1290. ]);
  1291. // 生成签名
  1292. $headers = $this->getVolcEngineSignHeaders(
  1293. $method, $service, $host, $region,
  1294. "Action={$action}&Version={$version}",
  1295. $access_key, $secret_key, $body
  1296. );
  1297. $client = new Client(['timeout' => 60, 'verify' => false]);
  1298. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  1299. 'headers' => $headers,
  1300. 'body' => $body
  1301. ]);
  1302. $response_arr = json_decode($response->getBody()->getContents(), true);
  1303. // 提取识别的文字
  1304. $textLines = [];
  1305. if (isset($response_arr['data']['line_texts'])) {
  1306. $textLines = $response_arr['data']['line_texts'];
  1307. } elseif (isset($response_arr['data']['ocr_infos'])) {
  1308. foreach ($response_arr['data']['ocr_infos'] as $info) {
  1309. if (isset($info['text'])) {
  1310. $textLines[] = $info['text'];
  1311. }
  1312. }
  1313. }
  1314. if (empty($textLines)) {
  1315. Log::warning('OCR识别结果为空', ['response' => $response_arr]);
  1316. return '';
  1317. }
  1318. return implode("\n", $textLines);
  1319. }
  1320. /**
  1321. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  1322. */
  1323. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  1324. $contentType = 'application/json';
  1325. $accept = 'application/json';
  1326. // 获取当前UTC时间
  1327. $t = new DateTime('now', new DateTimeZone('UTC'));
  1328. $xDate = $t->format('Ymd\THis\Z');
  1329. $dateStamp = $t->format('Ymd');
  1330. // 计算 body 的 sha256 哈希
  1331. $payloadHash = hash('sha256', $body);
  1332. // 1. 拼接规范请求串
  1333. $canonicalUri = '/';
  1334. $canonicalQueryString = $queryString;
  1335. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  1336. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  1337. $canonicalRequest = implode("\n", [
  1338. $method,
  1339. $canonicalUri,
  1340. $canonicalQueryString,
  1341. $canonicalHeaders,
  1342. $signedHeaders,
  1343. $payloadHash
  1344. ]);
  1345. // 2. 拼接待签名字符串
  1346. $algorithm = 'HMAC-SHA256';
  1347. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  1348. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  1349. $stringToSign = implode("\n", [
  1350. $algorithm,
  1351. $xDate,
  1352. $credentialScope,
  1353. $hashedCanonicalRequest
  1354. ]);
  1355. // 3. 计算签名
  1356. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  1357. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  1358. // 4. 添加签名到请求头
  1359. $authorizationHeader = sprintf(
  1360. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  1361. $algorithm,
  1362. $access_key,
  1363. $credentialScope,
  1364. $signedHeaders,
  1365. $signature
  1366. );
  1367. return [
  1368. 'Accept' => $accept,
  1369. 'Content-Type' => $contentType,
  1370. 'Host' => $host,
  1371. 'X-Date' => $xDate,
  1372. 'X-Content-Sha256'=> $payloadHash,
  1373. 'Authorization' => $authorizationHeader
  1374. ];
  1375. }
  1376. public function generateScriptWords($cid, $model = 'r1') {
  1377. ini_set('max_execution_time', 0);
  1378. if (!$cid) Utils::throwError('20003: 请选择章节!');
  1379. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  1380. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1381. $messages = [
  1382. [
  1383. 'role' => 'system',
  1384. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  1385. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  1386. 2.非对话部分请全部用旁白角色代替
  1387. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  1388. ],
  1389. [
  1390. 'role' => 'user',
  1391. 'content' => $content
  1392. ]
  1393. ];
  1394. $post_data = [
  1395. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  1396. 'messages' => $messages,
  1397. 'max_tokens' => 8192,
  1398. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  1399. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  1400. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  1401. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  1402. 'response_format' => [
  1403. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  1404. ],
  1405. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  1406. ];
  1407. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1408. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  1409. $response = $result->getBody()->getContents();
  1410. $response_arr = json_decode($response, true);
  1411. $update_data = [];
  1412. $content = '';
  1413. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  1414. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  1415. $update_data = [
  1416. 'role' => 'assistant',
  1417. 'content' => $response_arr['choices'][0]['message']['content'],
  1418. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  1419. ];
  1420. }
  1421. return $content;
  1422. }
  1423. }