DeepSeekService.php 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  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 createScript($data) {
  715. $script_name = getProp($data, 'script_name');
  716. $uid = Site::getUid(); // 获取当前用户ID
  717. if (!$script_name) Utils::throwError('20001:剧本名称不能为空');
  718. return DB::table('mp_scripts')->insertGetId([
  719. 'script_name' => $script_name,
  720. 'user_id' => $uid,
  721. 'created_at' => date('Y-m-d H:i:s'),
  722. 'updated_at' => date('Y-m-d H:i:s')
  723. ]);
  724. }
  725. /**
  726. * 上传文件识别文字内容并与 DeepSeek 进行对话
  727. *
  728. * @param array $data 包含以下参数:
  729. * - file: 上传的文件(UploadedFile 对象)或文件路径
  730. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  731. * - model: 使用的模型(r1 或 v3,默认 v3)
  732. * @return array
  733. */
  734. public function chatWithFile($data) {
  735. // dd(handleScriptContent(''));
  736. $script_id = getProp($data, 'script_id');
  737. $file = getProp($data, 'file');
  738. $content = getProp($data, 'content', '');
  739. $bid = getProp($data, 'bid', 0);
  740. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  741. $total_episode_num = getProp($data, 'total_episode_num', 30);
  742. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。");
  743. $model = getProp($data, 'model', 'v3');
  744. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  745. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  746. if (!$script) {
  747. Utils::throwError('20003:剧本不存在');
  748. }
  749. if (!$file && !$content && !$bid) {
  750. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  751. }
  752. // 提取文件内容
  753. if ($content) {
  754. $content = filterContent($content);
  755. } elseif ($file) {
  756. $content = $this->extractFileContent($file);
  757. if (!$content) {
  758. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  759. }
  760. } elseif ($bid) {
  761. $content = $this->getContentByBid($bid);
  762. if (!$content) {
  763. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  764. }
  765. } else {
  766. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  767. }
  768. // 构建消息
  769. $messages = [
  770. [
  771. 'role' => 'system',
  772. 'content' => '你是一个专业的文档分析助手及编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间用###分隔;同时<分集剧本>要求包含“分集序号”、“场景描述”、“出场角色”和“台词内容”这几个部分。示例如下:\n\n
  773. ###故事梗概
  774. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  775. ###剧本亮点
  776. 亮点1:绝境奇药,生死一线
  777. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  778. 亮点2:结拜兄妹,化解尴尬
  779. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  780. 亮点3:纤发夺命,情愫暗涌
  781. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  782. ###人物关系
  783. 阿雪与梁萧之间存在兄妹之情。
  784. ###核心矛盾
  785. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  786. ###主体列表
  787. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  788. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  789. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  790. 阴阳球:天地异宝,能化生精气,救人于危难。
  791. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  792. ###美术风格
  793. 基础画风风格词:厚涂古风
  794. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  795. ###场景列表
  796. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  797. ###分集剧本
  798. ##分集01
  799. 分集名: 第一集
  800. 场景描述:地点、时间、场景
  801. 出场角色:男主、女主
  802. 台词内容:
  803. 女主: 女主对话
  804. 男主:男主对话
  805. 女主: 女主对话
  806. 男主: 男主对话
  807. ##分集02
  808. 分集名: 第二集
  809. 场景描述:地点、时间、场景
  810. 出场角色:男主、女主
  811. 台词内容:
  812. 女主: 女主对话
  813. 男主:男主对话
  814. 女主: 女主对话
  815. 男主: 男主对话'
  816. ],
  817. [
  818. 'role' => 'user',
  819. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  820. ]
  821. ];
  822. $post_data = [
  823. 'model' => $model,
  824. 'messages' => $messages,
  825. 'max_tokens' => 8192,
  826. 'temperature' => 0.7,
  827. 'frequency_penalty' => 0,
  828. 'presence_penalty' => 0,
  829. 'response_format' => ['type' => 'text'],
  830. 'stream' => false
  831. ];
  832. $client = new Client(['timeout' => 1200, 'verify' => false]);
  833. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  834. $response = $result->getBody()->getContents();
  835. $response_arr = json_decode($response, true);
  836. $content = '';
  837. $usage = [];
  838. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  839. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  840. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  841. }
  842. // 处理结果
  843. if ($content) {
  844. $script_arr = handleScriptContent($content);
  845. }
  846. return [
  847. 'script' => $script_arr,
  848. 'answer' => $content,
  849. 'usage' => $usage
  850. ];
  851. }
  852. public function saveScript($data) {
  853. $script_arr =getProp($data, 'script', []);
  854. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  855. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  856. $script_id = getProp($data, 'script_id');
  857. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  858. try {
  859. DB::beginTransaction();
  860. $update_data = [
  861. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  862. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  863. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  864. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  865. 'roles' => isset($script_arr['roles']) ? $script_arr['roles'] : '',
  866. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  867. 'scenes' => isset($script_arr['scenes']) ? $script_arr['scenes'] : '',
  868. 'status' => 3,
  869. 'start_episode_sequence' => $start_episode_sequence,
  870. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  871. 'episode_num' => count($script_arr['episodes']),
  872. 'updated_at' => date('Y-m-d H:i:s')
  873. ];
  874. // 保存剧本内容
  875. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  876. if (!$boolen) {
  877. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  878. Utils::throwError('20003:剧本内容保存失败');
  879. }
  880. // 保存分集内容
  881. // 删除历史分集内容
  882. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  883. $episodes = [];
  884. foreach ($script_arr['episodes'] as $episode) {
  885. $episodes[] = [
  886. 'script_id' => $script_id,
  887. 'episode_number' => $episode['episode_number'],
  888. 'title' => $episode['title'],
  889. 'content' => $episode['content'],
  890. 'created_at' => date('Y-m-d H:i:s'),
  891. 'updated_at' => date('Y-m-d H:i:s')
  892. ];
  893. }
  894. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  895. if (!$boolen2) {
  896. dLog('deepseek')->info('分集内容保存失败', $episodes);
  897. Utils::throwError('20003:分集内容保存失败');
  898. }
  899. } catch (\Exception $e) {
  900. DB::rollBack();
  901. Utils::throwError('20003:'.$e->getMessage());
  902. }
  903. DB::commit();
  904. return true;
  905. }
  906. public function getContentByBid($bid) {
  907. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  908. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  909. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  910. $content = '';
  911. foreach ($chapters as $chapter) {
  912. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  913. }
  914. return $content;
  915. }
  916. /**
  917. * 根据文件类型提取文本内容
  918. *
  919. * @param mixed $file 文件对象或文件路径
  920. * @return string
  921. */
  922. public function extractFileContent($file) {
  923. // 获取文件路径和扩展名
  924. if (is_string($file)) {
  925. $filePath = $file;
  926. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  927. } else {
  928. // Laravel UploadedFile 对象
  929. $filePath = $file->getRealPath();
  930. $extension = strtolower($file->getClientOriginalExtension());
  931. }
  932. $content = '';
  933. switch ($extension) {
  934. case 'txt':
  935. $content = $this->extractTxtContent($filePath);
  936. break;
  937. case 'pdf':
  938. $content = $this->extractPdfContent($filePath);
  939. break;
  940. case 'doc':
  941. case 'docx':
  942. $content = $this->extractWordContent($filePath);
  943. break;
  944. // case 'jpg':
  945. // case 'jpeg':
  946. // case 'png':
  947. // case 'gif':
  948. // case 'bmp':
  949. // case 'webp':
  950. // $content = $this->extractImageContent($filePath);
  951. // break;
  952. default:
  953. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  954. }
  955. return $content;
  956. }
  957. /**
  958. * 提取 TXT 文件内容
  959. */
  960. private function extractTxtContent($filePath) {
  961. if (!file_exists($filePath)) {
  962. Utils::throwError('20003:文件不存在');
  963. }
  964. $content = file_get_contents($filePath);
  965. // 尝试检测并转换编码
  966. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  967. if ($encoding && $encoding !== 'UTF-8') {
  968. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  969. }
  970. return trim($content);
  971. }
  972. /**
  973. * 提取 PDF 文件内容
  974. */
  975. private function extractPdfContent($filePath) {
  976. if (!file_exists($filePath)) {
  977. Utils::throwError('20003:文件不存在');
  978. }
  979. try {
  980. $parser = new PdfParser();
  981. $pdf = $parser->parseFile($filePath);
  982. $content = $pdf->getText();
  983. return trim($content);
  984. } catch (\Exception $e) {
  985. Log::error('PDF解析失败: ' . $e->getMessage());
  986. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  987. }
  988. }
  989. /**
  990. * 提取 Word 文件内容(支持 doc 和 docx)
  991. */
  992. private function extractWordContent($filePath) {
  993. if (!file_exists($filePath)) {
  994. Utils::throwError('20003:文件不存在');
  995. }
  996. try {
  997. $phpWord = WordIOFactory::load($filePath);
  998. $content = '';
  999. foreach ($phpWord->getSections() as $section) {
  1000. foreach ($section->getElements() as $element) {
  1001. $content .= $this->extractWordElementText($element);
  1002. }
  1003. }
  1004. return trim($content);
  1005. } catch (\Exception $e) {
  1006. Log::error('Word解析失败: ' . $e->getMessage());
  1007. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  1008. }
  1009. }
  1010. /**
  1011. * 递归提取 Word 元素中的文本
  1012. */
  1013. private function extractWordElementText($element) {
  1014. $text = '';
  1015. if (method_exists($element, 'getText')) {
  1016. $text .= $element->getText() . "\n";
  1017. } elseif (method_exists($element, 'getElements')) {
  1018. foreach ($element->getElements() as $childElement) {
  1019. $text .= $this->extractWordElementText($childElement);
  1020. }
  1021. }
  1022. return $text;
  1023. }
  1024. /**
  1025. * 提取图片内容(使用火山引擎 OCR)
  1026. */
  1027. private function extractImageContent($filePath) {
  1028. if (!file_exists($filePath)) {
  1029. Utils::throwError('20003:文件不存在');
  1030. }
  1031. try {
  1032. // 读取图片并转换为 base64
  1033. $imageData = file_get_contents($filePath);
  1034. $base64Image = base64_encode($imageData);
  1035. // 调用火山引擎 OCR 服务
  1036. $content = $this->callVolcEngineOCR($base64Image);
  1037. return trim($content);
  1038. } catch (\Exception $e) {
  1039. Log::error('图片OCR识别失败: ' . $e->getMessage());
  1040. Utils::throwError('20003:图片识别失败');
  1041. }
  1042. }
  1043. /**
  1044. * 调用火山引擎 OCR 服务识别图片文字
  1045. *
  1046. * @param string $base64Image base64 编码的图片数据
  1047. * @return string 识别的文字内容
  1048. */
  1049. private function callVolcEngineOCR($base64Image) {
  1050. $method = 'POST';
  1051. $service = 'cv';
  1052. $host = 'visual.volcengineapi.com';
  1053. $region = env('VOLC_REGION', 'cn-north-1');
  1054. $access_key = env('VOLC_AK');
  1055. $secret_key = env('VOLC_SK');
  1056. $action = 'OCRNormal';
  1057. $version = '2020-08-26';
  1058. if (!$access_key || !$secret_key) {
  1059. Utils::throwError('20003:请配置火山引擎 AK/SK');
  1060. }
  1061. // 请求体
  1062. $body = json_encode([
  1063. 'image_base64' => $base64Image
  1064. ]);
  1065. // 生成签名
  1066. $headers = $this->getVolcEngineSignHeaders(
  1067. $method, $service, $host, $region,
  1068. "Action={$action}&Version={$version}",
  1069. $access_key, $secret_key, $body
  1070. );
  1071. $client = new Client(['timeout' => 60, 'verify' => false]);
  1072. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  1073. 'headers' => $headers,
  1074. 'body' => $body
  1075. ]);
  1076. $response_arr = json_decode($response->getBody()->getContents(), true);
  1077. // 提取识别的文字
  1078. $textLines = [];
  1079. if (isset($response_arr['data']['line_texts'])) {
  1080. $textLines = $response_arr['data']['line_texts'];
  1081. } elseif (isset($response_arr['data']['ocr_infos'])) {
  1082. foreach ($response_arr['data']['ocr_infos'] as $info) {
  1083. if (isset($info['text'])) {
  1084. $textLines[] = $info['text'];
  1085. }
  1086. }
  1087. }
  1088. if (empty($textLines)) {
  1089. Log::warning('OCR识别结果为空', ['response' => $response_arr]);
  1090. return '';
  1091. }
  1092. return implode("\n", $textLines);
  1093. }
  1094. /**
  1095. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  1096. */
  1097. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  1098. $contentType = 'application/json';
  1099. $accept = 'application/json';
  1100. // 获取当前UTC时间
  1101. $t = new DateTime('now', new DateTimeZone('UTC'));
  1102. $xDate = $t->format('Ymd\THis\Z');
  1103. $dateStamp = $t->format('Ymd');
  1104. // 计算 body 的 sha256 哈希
  1105. $payloadHash = hash('sha256', $body);
  1106. // 1. 拼接规范请求串
  1107. $canonicalUri = '/';
  1108. $canonicalQueryString = $queryString;
  1109. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  1110. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  1111. $canonicalRequest = implode("\n", [
  1112. $method,
  1113. $canonicalUri,
  1114. $canonicalQueryString,
  1115. $canonicalHeaders,
  1116. $signedHeaders,
  1117. $payloadHash
  1118. ]);
  1119. // 2. 拼接待签名字符串
  1120. $algorithm = 'HMAC-SHA256';
  1121. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  1122. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  1123. $stringToSign = implode("\n", [
  1124. $algorithm,
  1125. $xDate,
  1126. $credentialScope,
  1127. $hashedCanonicalRequest
  1128. ]);
  1129. // 3. 计算签名
  1130. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  1131. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  1132. // 4. 添加签名到请求头
  1133. $authorizationHeader = sprintf(
  1134. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  1135. $algorithm,
  1136. $access_key,
  1137. $credentialScope,
  1138. $signedHeaders,
  1139. $signature
  1140. );
  1141. return [
  1142. 'Accept' => $accept,
  1143. 'Content-Type' => $contentType,
  1144. 'Host' => $host,
  1145. 'X-Date' => $xDate,
  1146. 'X-Content-Sha256'=> $payloadHash,
  1147. 'Authorization' => $authorizationHeader
  1148. ];
  1149. }
  1150. public function generateScriptWords($cid, $model = 'r1') {
  1151. ini_set('max_execution_time', 0);
  1152. if (!$cid) Utils::throwError('20003: 请选择章节!');
  1153. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  1154. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1155. $messages = [
  1156. [
  1157. 'role' => 'system',
  1158. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  1159. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  1160. 2.非对话部分请全部用旁白角色代替
  1161. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  1162. ],
  1163. [
  1164. 'role' => 'user',
  1165. 'content' => $content
  1166. ]
  1167. ];
  1168. $post_data = [
  1169. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  1170. 'messages' => $messages,
  1171. 'max_tokens' => 8192,
  1172. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  1173. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  1174. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  1175. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  1176. 'response_format' => [
  1177. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  1178. ],
  1179. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  1180. ];
  1181. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1182. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  1183. $response = $result->getBody()->getContents();
  1184. $response_arr = json_decode($response, true);
  1185. $update_data = [];
  1186. $content = '';
  1187. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  1188. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  1189. $update_data = [
  1190. 'role' => 'assistant',
  1191. 'content' => $response_arr['choices'][0]['message']['content'],
  1192. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  1193. ];
  1194. }
  1195. return $content;
  1196. }
  1197. }