DeepSeekService.php 31 KB

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