DeepSeekService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Redis;
  9. use OSS\Core\OssException;
  10. use OSS\OssClient;
  11. class DeepSeekService
  12. {
  13. private $url;
  14. private $api_key;
  15. private $client;
  16. private $headers;
  17. public function __construct() {
  18. $this->url = 'https://api.deepseek.com/chat/completions';
  19. $this->api_key = env('DEEPSEEK_API_KEY');
  20. $this->client = new Client();
  21. $this->headers = [
  22. 'Authorization' => 'Bearer '.$this->api_key,
  23. 'Content-Type' => 'application/json; charset=UTF-8'
  24. ];
  25. }
  26. // 与推理模型对话
  27. public function chatWithReasoner($data) {
  28. ini_set('max_execution_time', 0);
  29. $content = getProp($data, 'content');
  30. $model = getProp($data, 'model', 'r1');
  31. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  32. $messages = [
  33. [
  34. 'role' => 'system',
  35. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  36. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  37. 2.非对话部分请全部用旁白角色代替
  38. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  39. ],
  40. [
  41. 'role' => 'user',
  42. 'content' => $content
  43. ]
  44. ];
  45. $post_data = [
  46. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  47. 'messages' => $messages,
  48. 'max_tokens' => 8192,
  49. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  50. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  51. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  52. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  53. 'response_format' => [
  54. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  55. ],
  56. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  57. ];
  58. $result = $this->client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  59. $response = $result->getBody()->getContents();
  60. $response_arr = json_decode($response, true);
  61. $update_data = [];
  62. $content = '';
  63. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  64. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  65. $update_data = [
  66. 'role' => 'assistant',
  67. 'content' => $response_arr['choices'][0]['message']['content'],
  68. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  69. ];
  70. }
  71. // 处理获取到的剧本数据
  72. $script_content = handleScriptWords($content);
  73. $result = [
  74. 'origin_content' => $content,
  75. 'roles' => getProp($script_content, 'roles'),
  76. 'words' => getProp($script_content, 'words'),
  77. ];
  78. return $result;
  79. }
  80. // 新增合成任务
  81. public function addGenerateTask($data) {
  82. $bid = getProp($data, 'bid');
  83. $cid = getProp($data, 'cid');
  84. $version_id = getProp($data, 'version_id');
  85. $generate_json = getProp($data, 'generate_json');
  86. // 更新角色-音色信息
  87. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  88. $existed_role_info = json_decode($existed_role_info, true);
  89. if ($existed_role_info) $existed_roles = array_keys($existed_role_info);
  90. else $existed_roles = [];
  91. // 获取情感信息
  92. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  93. $emotion_list = array_flip($emotion_list);
  94. // 构造生成音频的json
  95. $words = json_decode($generate_json, true);
  96. foreach($words as &$word) {
  97. 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:参数格式有误');
  98. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name']) || !($word['speed_ratio']) || !($word['loudness_ratio']) || !($word['emotion_scale'])) Utils::throwError('20003:参数不得为空');
  99. $role = getProp($word, 'role');
  100. $word['gender'] = (int)$word['gender'];
  101. if (isset($emotion_list[getProp($word, 'emotion')])) { // 如果有对应情感则赋值,没有则默认为中性(neutral)
  102. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  103. }else {
  104. $word['emotion'] = '中性';
  105. $word['emotion_type'] = 'neutral';
  106. }
  107. if (!in_array($role, $existed_roles)) {
  108. $existed_role_info[$role] = [
  109. 'timbre_type' => $word['voice_type'],
  110. 'timbre_name' => $word['voice_name'],
  111. ];
  112. }
  113. // $word['voice_name'] = $role_timbre[$role]['timbre_name'];
  114. // $word['voice_type'] = $role_timbre[$role]['timbre_type'];
  115. // $word['speed_ratio'] = mt_rand(9,11)/10;
  116. // $word['loudness_ratio'] = mt_rand(5,12)/10;
  117. // $word['emotion_scale'] = mt_rand(1,5);
  118. }
  119. $generate_json = json_encode($words, 256);
  120. try {
  121. DB::beginTransaction();
  122. $role_info = json_encode($existed_role_info, 256);
  123. $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')]);
  124. if (!$boolen) {
  125. DB::rollBack();
  126. Utils::throwError('20003:更新角色信息失败');
  127. }
  128. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  129. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  130. if (!$count) {
  131. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  132. }else {
  133. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  134. }
  135. $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')]);
  136. if (!$boolen1) {
  137. DB::rollBack();
  138. Utils::throwError('20003:更新生成数据失败');
  139. }
  140. $boolen2 = DB::table('mp_audio_tasks')->insert([
  141. 'audio_id' => getProp($chapter_audio, 'id'),
  142. 'status' => '执行中',
  143. 'generate_json' => $generate_json,
  144. 'bid' => $bid,
  145. 'book_name' => getProp($chapter_audio, 'book_name'),
  146. 'version_id' => $version_id,
  147. 'version_name' => getProp($chapter_audio, 'version_name'),
  148. 'cid' => $cid,
  149. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  150. 'task_name' => $task_name,
  151. 'created_at' => date('Y-m-d H:i:s'),
  152. 'updated_at' => date('Y-m-d H:i:s')
  153. ]);
  154. if (!$boolen2) {
  155. DB::rollBack();
  156. Utils::throwError('20003:创建任务失败');
  157. }
  158. } catch (\Exception $e) {
  159. DB::rollBack();
  160. Utils::throwError('20003:'.$e->getMessage());
  161. }
  162. DB::commit();
  163. return true;
  164. }
  165. public function timbreList($data) {
  166. $gender = getProp($data, 'gender');
  167. $timbre_name = getProp($data, 'timbre_name');
  168. $query = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_name as voice_name', 'timbre_type as voice_type', 'gender');
  169. if ($gender) {
  170. $query->where('gender', $gender);
  171. }
  172. if ($timbre_name) {
  173. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  174. }
  175. $list = $query->get()->map(function ($value) {
  176. $value = (array)$value;
  177. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  178. return $value;
  179. })->toArray();
  180. return $list;
  181. }
  182. // 文字合成语音(火山引擎)
  183. public function tts($data) {
  184. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  185. $headers = [
  186. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  187. 'Content-Type' => 'application/json; charset=UTF-8'
  188. ];
  189. $post_data = [
  190. 'app' => [
  191. 'appid' => env('VOLC_APPID'),
  192. 'token' => env('VOLC_TOKEN'),
  193. 'cluster' => 'volcano_tts'
  194. ],
  195. 'user' => [
  196. 'uid' => 'mp_audio'
  197. ],
  198. // 'audio' => [
  199. // 'voice_type' =>
  200. // ],
  201. ];
  202. }
  203. public function generateScriptWords($cid, $model = 'r1') {
  204. ini_set('max_execution_time', 0);
  205. if (!$cid) Utils::throwError('20003: 请选择章节!');
  206. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  207. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  208. $messages = [
  209. [
  210. 'role' => 'system',
  211. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  212. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  213. 2.非对话部分请全部用旁白角色代替
  214. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  215. ],
  216. [
  217. 'role' => 'user',
  218. 'content' => $content
  219. ]
  220. ];
  221. $post_data = [
  222. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  223. 'messages' => $messages,
  224. 'max_tokens' => 8192,
  225. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  226. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  227. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  228. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  229. 'response_format' => [
  230. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  231. ],
  232. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  233. ];
  234. $result = $this->client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  235. $response = $result->getBody()->getContents();
  236. $response_arr = json_decode($response, true);
  237. $update_data = [];
  238. $content = '';
  239. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  240. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  241. $update_data = [
  242. 'role' => 'assistant',
  243. 'content' => $response_arr['choices'][0]['message']['content'],
  244. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  245. ];
  246. }
  247. return $content;
  248. }
  249. }