DeepSeekService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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\Redis;
  11. use OSS\Core\OssException;
  12. use OSS\OssClient;
  13. class DeepSeekService
  14. {
  15. private $url;
  16. private $api_key;
  17. private $client;
  18. private $headers;
  19. public function __construct() {
  20. $this->url = 'https://api.deepseek.com/chat/completions';
  21. $this->api_key = env('DEEPSEEK_API_KEY');
  22. $this->client = new Client();
  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. set_time_limit(0);
  31. ini_set('max_execution_time', 0);
  32. $content = getProp($data, 'content');
  33. $model = getProp($data, 'model', 'r1');
  34. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  35. // 是否启用情感
  36. $enable_emotion = getProp($data, 'enable_emotion', 0);
  37. if ($enable_emotion) {
  38. $sys_content = '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  39. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  40. 2.非对话部分请全部用旁白角色代替
  41. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语';
  42. }else {
  43. $sys_content = '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  44. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  45. 2.非对话部分请全部用旁白角色代替';
  46. }
  47. $messages = [
  48. [
  49. 'role' => 'system',
  50. 'content' => $sys_content
  51. ],
  52. [
  53. 'role' => 'user',
  54. 'content' => $content
  55. ]
  56. ];
  57. $post_data = [
  58. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  59. 'messages' => $messages,
  60. 'max_tokens' => 8192,
  61. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  62. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  63. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  64. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  65. 'response_format' => [
  66. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  67. ],
  68. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  69. ];
  70. $result = $this->client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  71. $response = $result->getBody()->getContents();
  72. $response_arr = json_decode($response, true);
  73. $update_data = [];
  74. $content = '';
  75. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  76. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  77. $update_data = [
  78. 'role' => 'assistant',
  79. 'content' => $response_arr['choices'][0]['message']['content'],
  80. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  81. ];
  82. }
  83. // 处理获取到的剧本数据
  84. $script_content = handleScriptWords($content);
  85. $result = [
  86. 'origin_content' => $content,
  87. 'roles' => getProp($script_content, 'roles'),
  88. 'words' => getProp($script_content, 'words'),
  89. ];
  90. return $result;
  91. }
  92. // 新增合成任务
  93. public function addGenerateTask($data) {
  94. $bid = getProp($data, 'bid');
  95. $cid = getProp($data, 'cid');
  96. $version_id = getProp($data, 'version_id');
  97. $generate_json = getProp($data, 'generate_json');
  98. // 更新角色-音色信息
  99. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  100. $existed_role_info = json_decode($existed_role_info, true);
  101. if ($existed_role_info) $existed_roles = array_keys($existed_role_info);
  102. else $existed_roles = [];
  103. // 获取情感信息
  104. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  105. $emotion_list = array_flip($emotion_list);
  106. // 构造生成音频的json
  107. $words = json_decode($generate_json, true);
  108. foreach($words as &$word) {
  109. 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:参数格式有误');
  110. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name']) || !($word['speed_ratio']) || !($word['loudness_ratio']) || !($word['emotion_scale'])) Utils::throwError('20003:参数不得为空');
  111. $role = getProp($word, 'role');
  112. $word['gender'] = (int)$word['gender'];
  113. if (isset($emotion_list[getProp($word, 'emotion')])) { // 如果有对应情感则赋值,没有则默认为中性(neutral)
  114. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  115. }else {
  116. $word['emotion'] = '中性';
  117. $word['emotion_type'] = 'neutral';
  118. }
  119. if (!in_array($role, $existed_roles)) {
  120. $existed_role_info[$role] = [
  121. 'timbre_type' => $word['voice_type'],
  122. 'timbre_name' => $word['voice_name'],
  123. ];
  124. }
  125. // $word['voice_name'] = $role_timbre[$role]['timbre_name'];
  126. // $word['voice_type'] = $role_timbre[$role]['timbre_type'];
  127. // $word['speed_ratio'] = mt_rand(9,11)/10;
  128. // $word['loudness_ratio'] = mt_rand(5,12)/10;
  129. // $word['emotion_scale'] = mt_rand(1,5);
  130. }
  131. $generate_json = json_encode($words, 256);
  132. try {
  133. DB::beginTransaction();
  134. $role_info = json_encode($existed_role_info, 256);
  135. $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')]);
  136. if (!$boolen) {
  137. DB::rollBack();
  138. Utils::throwError('20003:更新角色信息失败');
  139. }
  140. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  141. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  142. if (!$count) {
  143. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  144. }else {
  145. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  146. }
  147. $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')]);
  148. if (!$boolen1) {
  149. DB::rollBack();
  150. Utils::throwError('20003:更新生成数据失败');
  151. }
  152. $boolen2 = DB::table('mp_audio_tasks')->insert([
  153. 'audio_id' => getProp($chapter_audio, 'id'),
  154. 'status' => '执行中',
  155. 'generate_json' => $generate_json,
  156. 'bid' => $bid,
  157. 'book_name' => getProp($chapter_audio, 'book_name'),
  158. 'version_id' => $version_id,
  159. 'version_name' => getProp($chapter_audio, 'version_name'),
  160. 'cid' => $cid,
  161. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  162. 'task_name' => $task_name,
  163. 'created_at' => date('Y-m-d H:i:s'),
  164. 'updated_at' => date('Y-m-d H:i:s')
  165. ]);
  166. if (!$boolen2) {
  167. DB::rollBack();
  168. Utils::throwError('20003:创建任务失败');
  169. }
  170. } catch (\Exception $e) {
  171. DB::rollBack();
  172. Utils::throwError('20003:'.$e->getMessage());
  173. }
  174. DB::commit();
  175. return true;
  176. }
  177. public function timbreList($data) {
  178. $gender = getProp($data, 'gender');
  179. $timbre_name = getProp($data, 'timbre_name');
  180. $query = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_name as voice_name', 'timbre_type as voice_type', 'gender');
  181. if ($gender) {
  182. $query->where('gender', $gender);
  183. }
  184. if ($timbre_name) {
  185. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  186. }
  187. $list = $query->get()->map(function ($value) {
  188. $value = (array)$value;
  189. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  190. return $value;
  191. })->toArray();
  192. return $list;
  193. }
  194. // 生成火山临时token
  195. public function setStsToken() {
  196. // ************* 配置参数 *************
  197. $method = 'GET';
  198. $service = 'sts';
  199. $host = 'open.volcengineapi.com';
  200. $region = env('VOLC_REGION');
  201. $endpoint = 'https://open.volcengineapi.com';
  202. // $endpoint = 'https://tos-cn-beijing.volces.com';
  203. $access_key = env('VOLC_AK');
  204. $secret_key = env('VOLC_SK');
  205. // 获取缓存中的token,如果没有则请求接口
  206. $token = Redis::get('volc_sts_token');
  207. if (!$token) {
  208. // 查询参数
  209. $query_parameters = [
  210. 'Action' => 'AssumeRole',
  211. 'RoleSessionName' => 'user@zw',
  212. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  213. 'Version' => '2018-01-01'
  214. ];
  215. // 生成URL编码的查询字符串
  216. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  217. // 获取签名头信息
  218. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  219. // 构建完整URL
  220. $request_url = $endpoint . '?' . $request_parameters;
  221. $client = new Client(['verify' => false]);
  222. $response = $client->get($request_url, ['headers' => $headers]);
  223. $response_arr = json_decode($response->getBody()->getContents(), true);
  224. $result = [
  225. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  226. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  227. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  228. 'Region' => env('VOLC_REGION'),
  229. 'Endpoint' => env('VOLC_END_POINT'),
  230. 'Bucket' => env('VOLC_BUCKET'),
  231. ];
  232. // 缓存token
  233. Redis::setex('volc_sts_token', 3000, json_encode($result));
  234. return $result;
  235. } else {
  236. return json_decode($token, true);
  237. }
  238. // $response = $response['Response'];
  239. // $access_key = $response['Credentials']['AccessKeyId'];
  240. // $secret_key = $response['Credentials']['AccessKeySecret'];
  241. // $security_token = $response['Credentials']['SecurityToken'];
  242. // $expiration = $response['Credentials']['Expiration'];
  243. // dd($response_arr);
  244. }
  245. private function sign($key, $msg) {
  246. return hash_hmac('sha256', $msg, $key, true);
  247. }
  248. // 生成签名密钥
  249. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  250. $kDate = $this->sign($key, $dateStamp);
  251. $kRegion = $this->sign($kDate, $regionName);
  252. $kService = $this->sign($kRegion, $serviceName);
  253. $kSigning = $this->sign($kService, 'request');
  254. return $kSigning;
  255. }
  256. // 获取签名头信息
  257. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  258. $contenttype = 'application/x-www-form-urlencoded';
  259. $accept = 'application/json';
  260. // 获取当前UTC时间
  261. $t = new DateTime('now', new DateTimeZone('UTC'));
  262. $xdate = $t->format('Ymd\THis\Z');
  263. $datestamp = $t->format('Ymd');
  264. // 1. 拼接规范请求串
  265. $canonical_uri = '/';
  266. $canonical_querystring = $request_parameters;
  267. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  268. $signed_headers = 'content-type;host;x-date';
  269. // 空请求体的SHA256哈希
  270. $payload_hash = hash('sha256', '');
  271. $canonical_request = implode("\n", [
  272. $method,
  273. $canonical_uri,
  274. $canonical_querystring,
  275. $canonical_headers,
  276. $signed_headers,
  277. $payload_hash
  278. ]);
  279. // 2. 拼接待签名字符串
  280. $algorithm = 'HMAC-SHA256';
  281. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  282. $hashed_canonical_request = hash('sha256', $canonical_request);
  283. $string_to_sign = implode("\n", [
  284. $algorithm,
  285. $xdate,
  286. $credential_scope,
  287. $hashed_canonical_request
  288. ]);
  289. // 3. 计算签名
  290. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  291. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  292. // 4. 添加签名到请求头
  293. $authorization_header = sprintf(
  294. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  295. $algorithm,
  296. $access_key,
  297. $credential_scope,
  298. $signed_headers,
  299. $signature
  300. );
  301. return [
  302. 'Accept' => $accept,
  303. 'Content-Type' => $contenttype,
  304. 'X-Date' => $xdate,
  305. 'Authorization' => $authorization_header
  306. ];
  307. }
  308. // 文字合成语音(火山引擎)
  309. public function tts($data) {
  310. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  311. $headers = [
  312. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  313. 'Content-Type' => 'application/json; charset=UTF-8'
  314. ];
  315. $post_data = [
  316. 'app' => [
  317. 'appid' => env('VOLC_APPID'),
  318. 'token' => env('VOLC_TOKEN'),
  319. 'cluster' => 'volcano_tts'
  320. ],
  321. 'user' => [
  322. 'uid' => 'mp_audio'
  323. ],
  324. // 'audio' => [
  325. // 'voice_type' =>
  326. // ],
  327. ];
  328. }
  329. public function generateScriptWords($cid, $model = 'r1') {
  330. ini_set('max_execution_time', 0);
  331. if (!$cid) Utils::throwError('20003: 请选择章节!');
  332. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  333. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  334. $messages = [
  335. [
  336. 'role' => 'system',
  337. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  338. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  339. 2.非对话部分请全部用旁白角色代替
  340. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  341. ],
  342. [
  343. 'role' => 'user',
  344. 'content' => $content
  345. ]
  346. ];
  347. $post_data = [
  348. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  349. 'messages' => $messages,
  350. 'max_tokens' => 8192,
  351. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  352. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  353. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  354. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  355. 'response_format' => [
  356. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  357. ],
  358. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  359. ];
  360. $result = $this->client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  361. $response = $result->getBody()->getContents();
  362. $response_arr = json_decode($response, true);
  363. $update_data = [];
  364. $content = '';
  365. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  366. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  367. $update_data = [
  368. 'role' => 'assistant',
  369. 'content' => $response_arr['choices'][0]['message']['content'],
  370. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  371. ];
  372. }
  373. return $content;
  374. }
  375. }