DeepSeekService.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. class DeepSeekService
  15. {
  16. private $url;
  17. private $api_key;
  18. private $client;
  19. private $headers;
  20. public function __construct() {
  21. $this->url = 'https://api.deepseek.com/chat/completions';
  22. $this->api_key = env('DEEPSEEK_API_KEY');
  23. $this->headers = [
  24. 'Authorization' => 'Bearer '.$this->api_key,
  25. 'Content-Type' => 'application/json; charset=UTF-8'
  26. ];
  27. }
  28. // 与推理模型对话
  29. public function chatWithReasoner($data) {
  30. $content = getProp($data, 'content');
  31. $model = getProp($data, 'model', 'r1');
  32. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  33. // 获取可选情感(根据音色可支持情感选)
  34. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  35. $emotion_list = [];
  36. foreach ($timbre_emotion as $emotion) {
  37. $tmp = explode(',', $emotion);
  38. $emotion_list = array_merge($emotion_list, $tmp);
  39. }
  40. $emotion_list = array_unique($emotion_list);
  41. $emotion_str = implode('、', $emotion_list);
  42. // // 获取可选情感
  43. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  44. // $emotion_str = implode('、', $emotion_list);
  45. // 是否启用情感
  46. $enable_emotion = getProp($data, 'enable_emotion', 0);
  47. if ($enable_emotion) {
  48. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  49. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  50. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  51. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  52. }else {
  53. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  54. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  55. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  56. }
  57. $messages = [
  58. [
  59. 'role' => 'system',
  60. 'content' => $sys_content
  61. ],
  62. [
  63. 'role' => 'user',
  64. 'content' => $content
  65. ]
  66. ];
  67. $post_data = [
  68. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  69. 'messages' => $messages,
  70. 'max_tokens' => 8192,
  71. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  72. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  73. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  74. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  75. 'response_format' => [
  76. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  77. ],
  78. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  79. ];
  80. $client = new Client(['timeout' => 1200, 'verify' => false]);
  81. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  82. $response = $result->getBody()->getContents();
  83. $response_arr = json_decode($response, true);
  84. $update_data = [];
  85. $content = '';
  86. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  87. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  88. $update_data = [
  89. 'role' => 'assistant',
  90. 'content' => $response_arr['choices'][0]['message']['content'],
  91. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  92. ];
  93. }
  94. // 处理获取到的剧本数据
  95. $script_content = handleScriptWords($content, $enable_emotion);
  96. $result = [
  97. 'origin_content' => $content,
  98. 'roles' => getProp($script_content, 'roles'),
  99. 'words' => getProp($script_content, 'words'),
  100. ];
  101. return $result;
  102. }
  103. public function resetParagraphAudio($data) {
  104. $bid = getProp($data, 'bid');
  105. $cid = getProp($data, 'cid');
  106. $version_id = getProp($data, 'version_id');
  107. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  108. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  109. 'generate_status' => '待制作',
  110. 'updated_at' => date('Y-m-d H:i:s')
  111. ]);
  112. }
  113. public function saveParagraphAudio($data) {
  114. $bid = getProp($data, 'bid');
  115. $cid = getProp($data, 'cid');
  116. $version_id = getProp($data, 'version_id');
  117. $sequence = getProp($data, 'sequence');
  118. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  119. // 获取所有情感
  120. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  121. $emotion_list = array_flip($emotion_list);
  122. // 获取音色支持情感
  123. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  124. $timbre_emotion = explode(',', $timbre_emotion);
  125. $emotion = getProp($data, 'emotion');
  126. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  127. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  128. $list = [
  129. 'bid' => $bid,
  130. 'cid' => $cid,
  131. 'version_id' => $version_id,
  132. 'sequence' => $sequence,
  133. 'role' => getProp($data, 'role'),
  134. 'gender' => getProp($data, 'gender'),
  135. 'text' => trim(getProp($data, 'text')),
  136. 'emotion' => $emotion,
  137. 'emotion_type' => $emotion_type,
  138. 'voice_type' => getProp($data, 'voice_type'),
  139. 'voice_name' => getProp($data, 'voice_name'),
  140. 'speed_ratio' => getProp($data, 'speed_ratio'),
  141. 'loudness_ratio'=> getProp($data, 'loudness_ratio'),
  142. 'emotion_scale' => getProp($data, 'emotion_scale'),
  143. // 'paragraph_audio_url' => '',
  144. 'generate_status' => '制作中',
  145. 'error_msg' => '',
  146. 'updated_at' => date('Y-m-d H:i:s')
  147. ];
  148. $continue = false;
  149. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  150. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  151. $list['generate_status'] = '制作成功';
  152. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  153. $continue = true;
  154. }
  155. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  156. if ($id) {
  157. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  158. }else {
  159. $list['created_at'] = date('Y-m-d H:i:s');
  160. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  161. $boolen = $id ? true : false;
  162. }
  163. // 如果更新成功则加入查询队列
  164. if ($boolen) {
  165. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  166. Redis::sadd($redis_key, $id);
  167. }
  168. if ($boolen && !$continue) {
  169. $boolen = false;
  170. $client = new Client(['timeout' => 300, 'verify' => false]);
  171. // 根据ID通过API通知合成音频
  172. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  173. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  174. $response = $result->getBody()->getContents();
  175. $response_arr = json_decode($response, true);
  176. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  177. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  178. Log::info('通知火山生成段落音频失败: '.$error_msg);
  179. Utils::throwError('20003:通知火山生成段落音频失败');
  180. }
  181. $boolen = true;
  182. }
  183. return $boolen;
  184. }
  185. // 新增合成任务
  186. public function addGenerateTask($data) {
  187. $bid = getProp($data, 'bid');
  188. $cid = getProp($data, 'cid');
  189. $version_id = getProp($data, 'version_id');
  190. $generate_json = getProp($data, 'generate_json');
  191. // 获取已生成的音频
  192. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  193. $paragraph_list = [];
  194. foreach($paragraph_audios as $item) {
  195. $paragraph_list[getProp($item, 'sequence')] = [
  196. 'role' => getProp($item, 'role'),
  197. 'gender' => getProp($item, 'gender'),
  198. 'text' => trim(getProp($item, 'text')),
  199. 'emotion' => getProp($item, 'emotion'),
  200. 'emotion_type' => getProp($item, 'emotion_type'),
  201. 'voice_type' => getProp($item, 'voice_type'),
  202. 'voice_name' => getProp($item, 'voice_name'),
  203. 'speed_ratio' => getProp($item, 'speed_ratio'),
  204. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  205. 'emotion_scale' => getProp($item, 'emotion_scale'),
  206. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  207. ];
  208. }
  209. // 更新角色-音色信息
  210. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  211. $existed_role_info = json_decode($existed_role_info, true);
  212. if (!$existed_role_info) $existed_role_info = [];
  213. // 获取情感信息
  214. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  215. $emotion_list = array_flip($emotion_list);
  216. // 获取音色对应情感组
  217. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  218. $timbre_emotion_list = [];
  219. foreach($timbre_emotions as $item) {
  220. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  221. }
  222. // 构造生成音频的json
  223. $words = json_decode($generate_json, true);
  224. // 最终合成前的参数组
  225. $mp_chapter_paragraph_audios = [];
  226. $sequence = 1;
  227. foreach($words as &$word) {
  228. 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:参数格式有误');
  229. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  230. $role = getProp($word, 'role');
  231. $word['gender'] = (int)$word['gender'];
  232. // 判断音色对应情感是否支持,不支持则调整为中性
  233. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  234. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  235. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  236. if (isset($emotion_list[getProp($word, 'emotion')])) {
  237. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  238. }else {
  239. $word['emotion'] = '中性';
  240. $word['emotion_type'] = 'neutral';
  241. }
  242. $existed_role_info[$role] = [
  243. 'timbre_type' => $word['voice_type'],
  244. 'timbre_name' => $word['voice_name'],
  245. ];
  246. $word['paragraph_audio_url'] = '';
  247. // 判断生成参数是否相同,相同则直接使用已生成的音频
  248. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  249. // 如果音频存在并且参数都未改变则使用已生成的音频
  250. if (getProp($paragraph, 'paragraph_audio_url')) {
  251. if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  252. getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  253. getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  254. getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  255. {
  256. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  257. }
  258. }
  259. $tmp = $word;
  260. // 组装章节分句音频数据
  261. // $tmp['sequence'] = getProp($word, 'sequence');
  262. // $tmp['text'] = getProp($word, 'text');
  263. // $tmp['emotion'] = getProp($word, 'emotion');
  264. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  265. // $tmp['voice_name'] = getProp($word, 'voice_name');
  266. // $tmp['voice_type'] = getProp($word, 'voice_type');
  267. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  268. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  269. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  270. $tmp['bid'] = $bid;
  271. $tmp['version_id'] = $version_id;
  272. $tmp['cid'] = $cid;
  273. $tmp['sequence'] = $sequence;
  274. $tmp['created_at'] = date('Y-m-d H:i:s');
  275. $tmp['updated_at'] = date('Y-m-d H:i:s');
  276. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  277. $mp_chapter_paragraph_audios[] = $tmp;
  278. $sequence++;
  279. }
  280. $generate_json = json_encode($words, 256);
  281. try {
  282. DB::beginTransaction();
  283. $role_info = json_encode($existed_role_info, 256);
  284. $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')]);
  285. if (!$boolen) {
  286. DB::rollBack();
  287. Utils::throwError('20003:更新角色信息失败');
  288. }
  289. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  290. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  291. if (!$count) {
  292. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  293. }else {
  294. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  295. }
  296. $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')]);
  297. if (!$boolen1) {
  298. DB::rollBack();
  299. Utils::throwError('20003:更新生成数据失败');
  300. }
  301. $id = DB::table('mp_audio_tasks')->insertGetId([
  302. 'audio_id' => getProp($chapter_audio, 'id'),
  303. 'generate_status' => '执行中',
  304. 'generate_json' => $generate_json,
  305. 'bid' => $bid,
  306. 'book_name' => getProp($chapter_audio, 'book_name'),
  307. 'version_id' => $version_id,
  308. 'version_name' => getProp($chapter_audio, 'version_name'),
  309. 'cid' => $cid,
  310. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  311. 'task_name' => $task_name,
  312. 'created_at' => date('Y-m-d H:i:s'),
  313. 'updated_at' => date('Y-m-d H:i:s')
  314. ]);
  315. if (!$id) {
  316. DB::rollBack();
  317. Utils::throwError('20003:创建任务失败');
  318. }
  319. // // 删除章节分句音频数据并重新插入
  320. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  321. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  322. // if (!$boolen3) {
  323. // DB::rollBack();
  324. // Utils::throwError('20003:更新章节分句音频失败');
  325. // }
  326. } catch (\Exception $e) {
  327. DB::rollBack();
  328. Utils::throwError('20003:'.$e->getMessage());
  329. }
  330. DB::commit();
  331. // 通知火山生成音频
  332. $client = new Client(['timeout' => 300, 'verify' => false]);
  333. // 根据ID通过API通知合成音频
  334. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  335. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  336. $response = $result->getBody()->getContents();
  337. $response_arr = json_decode($response, true);
  338. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  339. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  340. Log::info('通知火山生成音频失败: '.$error_msg);
  341. Utils::throwError('20003:通知火山生成音频失败');
  342. }
  343. return true;
  344. }
  345. public function timbreList($data) {
  346. $gender = getProp($data, 'gender');
  347. $timbre_name = getProp($data, 'voice_name');
  348. $category_id = getProp($data, 'category_id');
  349. $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');
  350. if ($gender) {
  351. $query->where('gender', $gender);
  352. }
  353. if ($timbre_name) {
  354. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  355. }
  356. if ($category_id) {
  357. $query->where(function ($query) use ($category_id) {
  358. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  359. });
  360. }
  361. $list = $query->get()->map(function ($value) {
  362. $value = (array)$value;
  363. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  364. return $value;
  365. })->toArray();
  366. return $list;
  367. }
  368. // 生成火山临时token
  369. public function setStsToken() {
  370. // ************* 配置参数 *************
  371. $method = 'GET';
  372. $service = 'sts';
  373. $host = 'open.volcengineapi.com';
  374. $region = env('VOLC_REGION');
  375. $endpoint = 'https://open.volcengineapi.com';
  376. // $endpoint = 'https://tos-cn-beijing.volces.com';
  377. $access_key = env('VOLC_AK');
  378. $secret_key = env('VOLC_SK');
  379. // 获取缓存中的token,如果没有则请求接口
  380. $token = Redis::get('volc_sts_token');
  381. if (!$token) {
  382. // 查询参数
  383. $query_parameters = [
  384. 'Action' => 'AssumeRole',
  385. 'RoleSessionName' => 'user@zw',
  386. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  387. 'Version' => '2018-01-01'
  388. ];
  389. // 生成URL编码的查询字符串
  390. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  391. // 获取签名头信息
  392. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  393. // 构建完整URL
  394. $request_url = $endpoint . '?' . $request_parameters;
  395. $client = new Client(['verify' => false]);
  396. $response = $client->get($request_url, ['headers' => $headers]);
  397. $response_arr = json_decode($response->getBody()->getContents(), true);
  398. $result = [
  399. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  400. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  401. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  402. 'Region' => env('VOLC_REGION'),
  403. 'Endpoint' => env('VOLC_END_POINT'),
  404. 'Bucket' => env('VOLC_BUCKET'),
  405. ];
  406. // 缓存token
  407. Redis::setex('volc_sts_token', 3000, json_encode($result));
  408. return $result;
  409. } else {
  410. return json_decode($token, true);
  411. }
  412. // $response = $response['Response'];
  413. // $access_key = $response['Credentials']['AccessKeyId'];
  414. // $secret_key = $response['Credentials']['AccessKeySecret'];
  415. // $security_token = $response['Credentials']['SecurityToken'];
  416. // $expiration = $response['Credentials']['Expiration'];
  417. // dd($response_arr);
  418. }
  419. private function sign($key, $msg) {
  420. return hash_hmac('sha256', $msg, $key, true);
  421. }
  422. // 生成签名密钥
  423. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  424. $kDate = $this->sign($key, $dateStamp);
  425. $kRegion = $this->sign($kDate, $regionName);
  426. $kService = $this->sign($kRegion, $serviceName);
  427. $kSigning = $this->sign($kService, 'request');
  428. return $kSigning;
  429. }
  430. // 获取签名头信息
  431. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  432. $contenttype = 'application/x-www-form-urlencoded';
  433. $accept = 'application/json';
  434. // 获取当前UTC时间
  435. $t = new DateTime('now', new DateTimeZone('UTC'));
  436. $xdate = $t->format('Ymd\THis\Z');
  437. $datestamp = $t->format('Ymd');
  438. // 1. 拼接规范请求串
  439. $canonical_uri = '/';
  440. $canonical_querystring = $request_parameters;
  441. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  442. $signed_headers = 'content-type;host;x-date';
  443. // 空请求体的SHA256哈希
  444. $payload_hash = hash('sha256', '');
  445. $canonical_request = implode("\n", [
  446. $method,
  447. $canonical_uri,
  448. $canonical_querystring,
  449. $canonical_headers,
  450. $signed_headers,
  451. $payload_hash
  452. ]);
  453. // 2. 拼接待签名字符串
  454. $algorithm = 'HMAC-SHA256';
  455. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  456. $hashed_canonical_request = hash('sha256', $canonical_request);
  457. $string_to_sign = implode("\n", [
  458. $algorithm,
  459. $xdate,
  460. $credential_scope,
  461. $hashed_canonical_request
  462. ]);
  463. // 3. 计算签名
  464. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  465. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  466. // 4. 添加签名到请求头
  467. $authorization_header = sprintf(
  468. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  469. $algorithm,
  470. $access_key,
  471. $credential_scope,
  472. $signed_headers,
  473. $signature
  474. );
  475. return [
  476. 'Accept' => $accept,
  477. 'Content-Type' => $contenttype,
  478. 'X-Date' => $xdate,
  479. 'Authorization' => $authorization_header
  480. ];
  481. }
  482. // 文字合成语音(火山引擎)
  483. public function tts($data) {
  484. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  485. $headers = [
  486. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  487. 'Content-Type' => 'application/json; charset=UTF-8'
  488. ];
  489. $post_data = [
  490. 'app' => [
  491. 'appid' => env('VOLC_APPID'),
  492. 'token' => env('VOLC_TOKEN'),
  493. 'cluster' => 'volcano_tts'
  494. ],
  495. 'user' => [
  496. 'uid' => 'mp_audio'
  497. ],
  498. // 'audio' => [
  499. // 'voice_type' =>
  500. // ],
  501. ];
  502. }
  503. public function generateScriptWords($cid, $model = 'r1') {
  504. ini_set('max_execution_time', 0);
  505. if (!$cid) Utils::throwError('20003: 请选择章节!');
  506. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  507. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  508. $messages = [
  509. [
  510. 'role' => 'system',
  511. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  512. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  513. 2.非对话部分请全部用旁白角色代替
  514. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  515. ],
  516. [
  517. 'role' => 'user',
  518. 'content' => $content
  519. ]
  520. ];
  521. $post_data = [
  522. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  523. 'messages' => $messages,
  524. 'max_tokens' => 8192,
  525. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  526. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  527. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  528. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  529. 'response_format' => [
  530. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  531. ],
  532. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  533. ];
  534. $client = new Client(['timeout' => 1200, 'verify' => false]);
  535. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  536. $response = $result->getBody()->getContents();
  537. $response_arr = json_decode($response, true);
  538. $update_data = [];
  539. $content = '';
  540. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  541. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  542. $update_data = [
  543. 'role' => 'assistant',
  544. 'content' => $response_arr['choices'][0]['message']['content'],
  545. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  546. ];
  547. }
  548. return $content;
  549. }
  550. }