DeepSeekService.php 21 KB

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