DeepSeekService.php 21 KB

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