| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357 |
- <?php
- namespace App\Services\DeepSeek;
- use App\Consts\ErrorConst;
- use App\Facade\Site;
- use App\Libs\Utils;
- use GuzzleHttp\Client;
- use DateTime;
- use DateTimeZone;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Redis;
- use OSS\Core\OssException;
- use OSS\OssClient;
- use Smalot\PdfParser\Parser as PdfParser;
- use PhpOffice\PhpWord\IOFactory as WordIOFactory;
- class DeepSeekService
- {
- private $url;
- private $api_key;
- private $client;
- private $headers;
- public function __construct() {
- $this->url = 'https://api.deepseek.com/chat/completions';
- $this->api_key = env('DEEPSEEK_API_KEY');
- $this->headers = [
- 'Authorization' => 'Bearer '.$this->api_key,
- 'Content-Type' => 'application/json; charset=UTF-8'
- ];
- }
- // 与推理模型对话
- public function chatWithReasoner($data) {
- $content = getProp($data, 'content');
- $model = getProp($data, 'model', 'r1');
- $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
- // 获取可选情感(根据音色可支持情感选)
- $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
- $emotion_list = [];
- foreach ($timbre_emotion as $emotion) {
- $tmp = explode(',', $emotion);
- $emotion_list = array_merge($emotion_list, $tmp);
- }
- $emotion_list = array_unique($emotion_list);
- $emotion_str = implode('、', $emotion_list);
- // // 获取可选情感
- // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
- // $emotion_str = implode('、', $emotion_list);
- // 是否启用情感
- $enable_emotion = getProp($data, 'enable_emotion', 0);
- if ($enable_emotion) {
- $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
- 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
- 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
- 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
- }else {
- $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
- 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
- 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
- }
-
- $messages = [
- [
- 'role' => 'system',
- 'content' => $sys_content
- ],
- [
- 'role' => 'user',
- 'content' => $content
- ]
- ];
- $post_data = [
- 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
- 'messages' => $messages,
- 'max_tokens' => 8192,
- 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
- // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
- 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
- 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
- 'response_format' => [
- 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
- ],
- 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
- ];
- $client = new Client(['timeout' => 1200, 'verify' => false]);
- $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- $update_data = [];
- $content = '';
- if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
- $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
- $update_data = [
- 'role' => 'assistant',
- 'content' => $response_arr['choices'][0]['message']['content'],
- 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
- ];
- }
- // 处理获取到的剧本数据
- $script_content = handleScriptWords($content, $enable_emotion);
- $result = [
- 'origin_content' => $content,
- 'roles' => getProp($script_content, 'roles'),
- 'words' => getProp($script_content, 'words'),
- ];
- return $result;
- }
- public function resetParagraphAudio($data) {
- $bid = getProp($data, 'bid');
- $cid = getProp($data, 'cid');
- $version_id = getProp($data, 'version_id');
-
- if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
- return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
- 'generate_status' => '待制作',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- public function saveParagraphAudio($data) {
- $bid = getProp($data, 'bid');
- $cid = getProp($data, 'cid');
- $version_id = getProp($data, 'version_id');
- $sequence = getProp($data, 'sequence');
- $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
- // 获取所有情感
- $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
- $emotion_list = array_flip($emotion_list);
- // 获取音色支持情感
- $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
- $timbre_emotion = explode(',', $timbre_emotion);
- $emotion = getProp($data, 'emotion');
- if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
- $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
- $list = [
- 'bid' => $bid,
- 'cid' => $cid,
- 'version_id' => $version_id,
- 'sequence' => $sequence,
- 'role' => getProp($data, 'role'),
- 'gender' => getProp($data, 'gender'),
- 'text' => trim(getProp($data, 'text')),
- 'emotion' => $emotion,
- 'emotion_type' => $emotion_type,
- 'voice_type' => getProp($data, 'voice_type'),
- 'voice_name' => getProp($data, 'voice_name'),
- 'speed_ratio' => getProp($data, 'speed_ratio', 0),
- 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($data, 'emotion_scale', 4),
- 'pitch' => getProp($data, 'pitch', 0),
- // 'paragraph_audio_url' => '',
- 'generate_status' => '制作中',
- 'error_msg' => '',
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- $continue = false;
- // 判断是否含有中文、数字或英文,如果没有则跳过合成
- if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
- $list['generate_status'] = '制作成功';
- $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
- $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
- $continue = true;
- }
- // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
- if ($id) {
- $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
- }else {
- $list['created_at'] = date('Y-m-d H:i:s');
- $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
- $boolen = $id ? true : false;
- }
- // 如果更新成功则加入查询队列
- if ($boolen) {
- $redis_key = "select-{$bid}-{$version_id}-{$cid}";
- Redis::sadd($redis_key, $id);
- }
- if ($boolen && !$continue) {
- $boolen = false;
- $client = new Client(['timeout' => 300, 'verify' => false]);
- // 根据ID通过API通知合成音频
- // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
- $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- Log::info('通知火山生成段落音频失败: '.$error_msg);
- Utils::throwError('20003:通知火山生成段落音频失败');
- }
- $boolen = true;
- }
- return $boolen;
- }
- public function insertAudioEffect($data) {
- $audio_id = getProp($data, 'audio_id');
- $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
- $bid = getProp($chapter_audio, 'bid');
- $version_id = getProp($chapter_audio, 'version_id');
- $cid = getProp($chapter_audio, 'cid');
- if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
- $audio_effect_json = getProp($data, 'audio_effect_json');
- if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
- try {
- DB::beginTransaction();
-
- $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
- if (!$count) {
- $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
- }else {
- $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
- }
- $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
- 'audio_effect_status' => '添加中',
- 'audio_effect_json' => $audio_effect_json,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$boolen1) {
- DB::rollBack();
- Utils::throwError('20003:更新生成数据失败');
- }
- $id = DB::table('mp_audio_tasks')->insertGetId([
- 'audio_id' => $audio_id,
- 'generate_status' => '执行中',
- 'generate_json' => json_encode([], 256),
- 'bid' => $bid,
- 'book_name' => getProp($chapter_audio, 'book_name'),
- 'version_id' => $version_id,
- 'version_name' => getProp($chapter_audio, 'version_name'),
- 'cid' => $cid,
- 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
- 'task_name' => $task_name,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- if (!$id) {
- DB::rollBack();
- Utils::throwError('20003:创建任务失败');
- }
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
-
- $client = new Client(['timeout' => 300, 'verify' => false]);
- // 根据ID通过API通知合成音频
- // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
- $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- Log::info('通知火山插入音效失败: '.$error_msg);
- Utils::throwError('20003:通知火山插入音效失败');
- }
-
- return true;
- }
- public function insertBgm($data) {
- $audio_id = getProp($data, 'audio_id');
- $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
- $bid = getProp($chapter_audio, 'bid');
- $version_id = getProp($chapter_audio, 'version_id');
- $cid = getProp($chapter_audio, 'cid');
- if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
- $bgm_json = getProp($data, 'bgm_json');
- if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
- if (!$bgm_json) {
- $bgm_json = getProp($data, 'audio_effect_json');
- if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
- }
- try {
- DB::beginTransaction();
-
- $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
- if (!$count) {
- $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
- }else {
- $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
- }
- $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
- 'bgm_status' => '添加中',
- 'bgm_json' => $bgm_json,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$boolen1) {
- DB::rollBack();
- Utils::throwError('20003:更新生成数据失败');
- }
- $id = DB::table('mp_audio_tasks')->insertGetId([
- 'audio_id' => $audio_id,
- 'generate_status' => '执行中',
- 'generate_json' => json_encode([], 256),
- 'bid' => $bid,
- 'book_name' => getProp($chapter_audio, 'book_name'),
- 'version_id' => $version_id,
- 'version_name' => getProp($chapter_audio, 'version_name'),
- 'cid' => $cid,
- 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
- 'task_name' => $task_name,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- if (!$id) {
- DB::rollBack();
- Utils::throwError('20003:创建任务失败');
- }
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
-
- $client = new Client(['timeout' => 300, 'verify' => false]);
- // 根据ID通过API通知合成音频
- // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
- $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- Log::info('通知火山插入bgm失败: '.$error_msg);
- Utils::throwError('20003:通知火山插入bgm失败');
- }
-
- return true;
- }
- public function getParagraphAudios($data) {
- $bid = getProp($data, 'bid');
- $cid = getProp($data, 'cid');
- $version_id = getProp($data, 'version_id');
- $sequence = getProp($data, 'sequence');
- // 获取已生成的音频
- $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
- if ($sequence) $query->where('sequence', $sequence);
- $paragraph_audios = $query->orderBy('sequence')->get();
- $result = [];
- foreach($paragraph_audios as $item) {
- $result[] = [
- 'sequence' => getProp($item, 'sequence'),
- 'role' => getProp($item, 'role'),
- 'gender' => getProp($item, 'gender'),
- 'text' => trim(getProp($item, 'text')),
- 'emotion' => getProp($item, 'emotion'),
- 'emotion_type' => getProp($item, 'emotion_type'),
- 'voice_type' => getProp($item, 'voice_type'),
- 'voice_name' => getProp($item, 'voice_name'),
- 'speed_ratio' => getProp($item, 'speed_ratio'),
- 'loudness_ratio' => getProp($item, 'loudness_ratio'),
- 'emotion_scale' => getProp($item, 'emotion_scale'),
- 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
- 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
- ];
- }
- return $result;
- }
- // 新增合成任务
- public function addGenerateTask($data) {
- $bid = getProp($data, 'bid');
- $cid = getProp($data, 'cid');
- $version_id = getProp($data, 'version_id');
- $generate_json = getProp($data, 'generate_json');
- // 获取已生成的音频
- $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
- $paragraph_list = [];
- foreach($paragraph_audios as $item) {
- $paragraph_list[getProp($item, 'sequence')] = [
- 'role' => getProp($item, 'role'),
- 'gender' => getProp($item, 'gender'),
- 'text' => trim(getProp($item, 'text')),
- 'emotion' => getProp($item, 'emotion'),
- 'emotion_type' => getProp($item, 'emotion_type'),
- 'voice_type' => getProp($item, 'voice_type'),
- 'voice_name' => getProp($item, 'voice_name'),
- 'speed_ratio' => getProp($item, 'speed_ratio'),
- 'loudness_ratio' => getProp($item, 'loudness_ratio'),
- 'emotion_scale' => getProp($item, 'emotion_scale'),
- 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
- ];
- }
- // 更新角色-音色信息
- $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
- $existed_role_info = json_decode($existed_role_info, true);
- if (!$existed_role_info) $existed_role_info = [];
- // 获取情感信息
- $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
- $emotion_list = array_flip($emotion_list);
- // 获取音色对应情感组
- $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
- $timbre_emotion_list = [];
- foreach($timbre_emotions as $item) {
- $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
- }
- // 构造生成音频的json
- $words = json_decode($generate_json, true);
- // 最终合成前的参数组
- $mp_chapter_paragraph_audios = [];
- $sequence = 1;
- $complete_paragraph_sequences = [];
- foreach($words as &$word) {
- 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:参数格式有误');
- if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
- $role = getProp($word, 'role');
- $word['gender'] = (int)$word['gender'];
- // 判断音色对应情感是否支持,不支持则调整为中性
- $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
- if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
- // 如果有对应情感则赋值,没有则默认为中性(neutral)
- if (isset($emotion_list[getProp($word, 'emotion')])) {
- $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
- }else {
- $word['emotion'] = '中性';
- $word['emotion_type'] = 'neutral';
- }
- $existed_role_info[$role] = [
- 'timbre_type' => $word['voice_type'],
- 'timbre_name' => $word['voice_name'],
- 'emotion' => $word['emotion'],
- 'emotion_type' => $word['emotion_type'],
- 'speed_ratio' => $word['speed_ratio'],
- 'loudness_ratio'=> $word['loudness_ratio'],
- 'emotion_scale' => $word['emotion_scale'],
- 'pitch' => $word['pitch']
- ];
- $word['paragraph_audio_url'] = '';
- // 判断生成参数是否相同,相同则直接使用已生成的音频
- $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
- // 如果音频存在并且参数都未改变则使用已生成的音频
- if (getProp($paragraph, 'paragraph_audio_url')) {
- // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
- // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
- // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
- // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
- // {
- // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
- // }
- $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
- }
- $tmp = $word;
- // 组装章节分句音频数据
- // $tmp['sequence'] = getProp($word, 'sequence');
- // $tmp['text'] = getProp($word, 'text');
- // $tmp['emotion'] = getProp($word, 'emotion');
- // $tmp['emotion_type'] = getProp($word, 'emotion_type');
- // $tmp['voice_name'] = getProp($word, 'voice_name');
- // $tmp['voice_type'] = getProp($word, 'voice_type');
- // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
- // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
- // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
- $tmp['bid'] = $bid;
- $tmp['version_id'] = $version_id;
- $tmp['cid'] = $cid;
- $tmp['sequence'] = $sequence;
- $tmp['created_at'] = date('Y-m-d H:i:s');
- $tmp['updated_at'] = date('Y-m-d H:i:s');
- if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
- $mp_chapter_paragraph_audios[] = $tmp;
- $complete_paragraph_sequences[] = $sequence;
- $sequence++;
- }
- $generate_json = json_encode($words, 256);
- // 判断是否有未生成字幕的段落
- $no_subtitle_sequences = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->whereIn('sequence', $complete_paragraph_sequences)->whereNull('subtitle_info')->pluck('sequence')->toArray();
- if ($no_subtitle_sequences) {
- Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
- }
- try {
- DB::beginTransaction();
- $role_info = json_encode($existed_role_info, 256);
- $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')]);
- if (!$boolen) {
- DB::rollBack();
- Utils::throwError('20003:更新角色信息失败');
- }
- $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
- $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
- if (!$count) {
- $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
- }else {
- $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
- }
- $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')]);
- if (!$boolen1) {
- DB::rollBack();
- Utils::throwError('20003:更新生成数据失败');
- }
- $id = DB::table('mp_audio_tasks')->insertGetId([
- 'audio_id' => getProp($chapter_audio, 'id'),
- 'generate_status' => '执行中',
- 'generate_json' => $generate_json,
- 'bid' => $bid,
- 'book_name' => getProp($chapter_audio, 'book_name'),
- 'version_id' => $version_id,
- 'version_name' => getProp($chapter_audio, 'version_name'),
- 'cid' => $cid,
- 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
- 'task_name' => $task_name,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- if (!$id) {
- DB::rollBack();
- Utils::throwError('20003:创建任务失败');
- }
- // 删除不在段落序号范围内的其他数据
- if ($complete_paragraph_sequences) {
- DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
- }
- // // 删除章节分句音频数据并重新插入
- // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
- // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
- // if (!$boolen3) {
- // DB::rollBack();
- // Utils::throwError('20003:更新章节分句音频失败');
- // }
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- // 通知火山生成音频
- $client = new Client(['timeout' => 300, 'verify' => false]);
- // 根据ID通过API通知合成音频
- // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
- $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- Log::info('通知火山生成音频失败: '.$error_msg);
- Utils::throwError('20003:通知火山生成音频失败');
- }
- return true;
- }
- public function timbreList($data) {
- $gender = getProp($data, 'gender');
- $timbre_name = getProp($data, 'voice_name');
- $category_id = getProp($data, 'category_id');
-
- $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');
- if ($gender) {
- $query->where('gender', $gender);
- }
- if ($timbre_name) {
- $query->where('timbre_name', 'like', "%{$timbre_name}%");
- }
- if ($category_id) {
- $query->where(function ($query) use ($category_id) {
- $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
- });
- }
- $list = $query->get()->map(function ($value) {
- $value = (array)$value;
- $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
- return $value;
- })->toArray();
- return $list;
- }
- // 生成火山临时token
- public function setStsToken() {
- // ************* 配置参数 *************
- $method = 'GET';
- $service = 'sts';
- $host = 'open.volcengineapi.com';
- $region = env('VOLC_REGION');
- $endpoint = 'https://open.volcengineapi.com';
- // $endpoint = 'https://tos-cn-beijing.volces.com';
- $access_key = env('VOLC_AK');
- $secret_key = env('VOLC_SK');
- // 获取缓存中的token,如果没有则请求接口
- $token = Redis::get('volc_sts_token');
- if (!$token) {
- // 查询参数
- $query_parameters = [
- 'Action' => 'AssumeRole',
- 'RoleSessionName' => 'user@zw',
- 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
- 'Version' => '2018-01-01'
- ];
- // 生成URL编码的查询字符串
- $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
- // 获取签名头信息
- $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
- // 构建完整URL
- $request_url = $endpoint . '?' . $request_parameters;
- $client = new Client(['verify' => false]);
- $response = $client->get($request_url, ['headers' => $headers]);
- $response_arr = json_decode($response->getBody()->getContents(), true);
- $result = [
- 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
- 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
- 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
- 'Region' => env('VOLC_REGION'),
- 'Endpoint' => env('VOLC_END_POINT'),
- 'Bucket' => env('VOLC_BUCKET'),
- ];
- // 缓存token
- Redis::setex('volc_sts_token', 3000, json_encode($result));
- return $result;
- } else {
- return json_decode($token, true);
- }
-
- // $response = $response['Response'];
- // $access_key = $response['Credentials']['AccessKeyId'];
- // $secret_key = $response['Credentials']['AccessKeySecret'];
- // $security_token = $response['Credentials']['SecurityToken'];
- // $expiration = $response['Credentials']['Expiration'];
- // dd($response_arr);
- }
- public function emotionGroups($data) {
- $id = getProp($data, 'group_id');
- $group_name = getProp($data, 'group_name');
- $voice_type = getProp($data, 'voice_type');
- $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
- 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
- 'pitch', 'generate_status', 'audio_url', 'error_msg');
- if ($group_name) {
- $query->where('group_name', 'like', "%{$group_name}%");
- }
- if ($id) {
- $query->where('id', $id);
- }
- if ($voice_type) {
- $query->where('voice_type', $voice_type);
- }
- return $query->orderBy('id')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
- }
- private function sign($key, $msg) {
- return hash_hmac('sha256', $msg, $key, true);
- }
-
- // 生成签名密钥
- private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
- $kDate = $this->sign($key, $dateStamp);
- $kRegion = $this->sign($kDate, $regionName);
- $kService = $this->sign($kRegion, $serviceName);
- $kSigning = $this->sign($kService, 'request');
- return $kSigning;
- }
- // 获取签名头信息
- private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
- $contenttype = 'application/x-www-form-urlencoded';
- $accept = 'application/json';
-
- // 获取当前UTC时间
- $t = new DateTime('now', new DateTimeZone('UTC'));
- $xdate = $t->format('Ymd\THis\Z');
- $datestamp = $t->format('Ymd');
-
- // 1. 拼接规范请求串
- $canonical_uri = '/';
- $canonical_querystring = $request_parameters;
- $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
- $signed_headers = 'content-type;host;x-date';
-
- // 空请求体的SHA256哈希
- $payload_hash = hash('sha256', '');
-
- $canonical_request = implode("\n", [
- $method,
- $canonical_uri,
- $canonical_querystring,
- $canonical_headers,
- $signed_headers,
- $payload_hash
- ]);
-
- // 2. 拼接待签名字符串
- $algorithm = 'HMAC-SHA256';
- $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
- $hashed_canonical_request = hash('sha256', $canonical_request);
-
- $string_to_sign = implode("\n", [
- $algorithm,
- $xdate,
- $credential_scope,
- $hashed_canonical_request
- ]);
-
- // 3. 计算签名
- $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
- $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
-
- // 4. 添加签名到请求头
- $authorization_header = sprintf(
- '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
- $algorithm,
- $access_key,
- $credential_scope,
- $signed_headers,
- $signature
- );
-
- return [
- 'Accept' => $accept,
- 'Content-Type' => $contenttype,
- 'X-Date' => $xdate,
- 'Authorization' => $authorization_header
- ];
- }
- // 文字合成语音(火山引擎)
- public function tts($data) {
- $url = 'https://openspeech.bytedance.com/api/v1/tts';
- $headers = [
- 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
- 'Content-Type' => 'application/json; charset=UTF-8'
- ];
- $post_data = [
- 'app' => [
- 'appid' => env('VOLC_APPID'),
- 'token' => env('VOLC_TOKEN'),
- 'cluster' => 'volcano_tts'
- ],
- 'user' => [
- 'uid' => 'mp_audio'
- ],
- // 'audio' => [
- // 'voice_type' =>
- // ],
- ];
- }
- public function scriptList($data) {
- $script_id = getProp($data, 'script_id');
- $script_name = getProp($data, 'script_name');
-
- $query = DB::table('mp_scripts')->where('is_deleted', 0)->select('*');
- if ($script_id) {
- $query->where('id', $script_id);
- }
- if ($script_name) {
- $query->where('script_name', 'like', "%{$script_name}%");
- }
- return $query->orderBy('created_at', 'desc')->paginate(12);
- }
- public function createScript($data) {
- $script_name = getProp($data, 'script_name');
- $uid = Site::getUid(); // 获取当前用户ID
- if (!$script_name) Utils::throwError('20001:剧本名称不能为空');
- return DB::table('mp_scripts')->insertGetId([
- 'script_name' => $script_name,
- 'user_id' => $uid,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- /**
- * 上传文件识别文字内容并与 DeepSeek 进行对话
- *
- * @param array $data 包含以下参数:
- * - file: 上传的文件(UploadedFile 对象)或文件路径
- * - question: 用户问题(可选,默认为"请总结这个文件的内容")
- * - model: 使用的模型(r1 或 v3,默认 v3)
- * @return array
- */
- public function chatWithFile($data) {
- // dd(handleScriptContent(''));
- $script_id = getProp($data, 'script_id');
- $file = getProp($data, 'file');
- $content = getProp($data, 'content', '');
- $bid = getProp($data, 'bid', 0);
- $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
- $total_episode_num = getProp($data, 'total_episode_num', 30);
- $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。");
- $model = getProp($data, 'model', 'v3');
- $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
- $script = DB::table('mp_scripts')->where('id', $script_id)->first();
- if (!$script) {
- Utils::throwError('20003:剧本不存在');
- }
- if (!$file && !$content && !$bid) {
- Utils::throwError('20003:请上传文件或选择书籍或输入内容');
- }
- // 提取文件内容
- if ($content) {
- $content = filterContent($content);
- } elseif ($file) {
- $content = $this->extractFileContent($file);
- if (!$content) {
- Utils::throwError('20003:无法提取文件内容,请检查文件格式');
- }
- } elseif ($bid) {
- $content = $this->getContentByBid($bid);
- if (!$content) {
- Utils::throwError('20003:无法获取书籍内容,请检查书籍');
- }
- } else {
- Utils::throwError('20003:请上传文件或选择书籍或输入内容');
- }
- // 构建消息
- $messages = [
- [
- 'role' => 'system',
- 'content' => '你是一个专业的文档分析助手及编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间用###分隔;同时<分集剧本>要求包含“分集序号”、“场景描述”、“出场角色”和“台词内容”这几个部分。示例如下:\n\n
- ###故事梗概
- 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
- ###剧本亮点
- 亮点1:绝境奇药,生死一线
- 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
- 亮点2:结拜兄妹,化解尴尬
- 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
- 亮点3:纤发夺命,情愫暗涌
- 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
- ###人物关系
- 阿雪与梁萧之间存在兄妹之情。
- ###核心矛盾
- 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
- ###主体列表
- 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
- 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
- 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
- 阴阳球:天地异宝,能化生精气,救人于危难。
- 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
- ###美术风格
- 基础画风风格词:厚涂古风
- 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
- ###场景列表
- 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
- ###分集剧本
- ##分集01
- 分集名: 第一集
- 场景描述:地点、时间、场景
- 出场角色:男主、女主
- 台词内容:
- 女主: 女主对话
- 男主:男主对话
- 女主: 女主对话
- 男主: 男主对话
- ##分集02
- 分集名: 第二集
- 场景描述:地点、时间、场景
- 出场角色:男主、女主
- 台词内容:
- 女主: 女主对话
- 男主:男主对话
- 女主: 女主对话
- 男主: 男主对话'
- ],
- [
- 'role' => 'user',
- 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
- ]
- ];
- $post_data = [
- 'model' => $model,
- 'messages' => $messages,
- 'max_tokens' => 8192,
- 'temperature' => 0.7,
- 'frequency_penalty' => 0,
- 'presence_penalty' => 0,
- 'response_format' => ['type' => 'text'],
- 'stream' => false
- ];
- $client = new Client(['timeout' => 1200, 'verify' => false]);
- $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- $content = '';
- $usage = [];
- if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
- $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
- $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
- }
- // 处理结果
- if ($content) {
- $script_arr = handleScriptContent($content);
- }
- return [
- 'script' => $script_arr,
- 'answer' => $content,
- 'usage' => $usage
- ];
- }
- public function saveScript($data) {
- $script_arr =getProp($data, 'script', []);
- if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
- $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
- $script_id = getProp($data, 'script_id');
- if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
- try {
- DB::beginTransaction();
- $update_data = [
- 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
- 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
- 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
- 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
- 'roles' => isset($script_arr['roles']) ? $script_arr['roles'] : '',
- 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
- 'scenes' => isset($script_arr['scenes']) ? $script_arr['scenes'] : '',
- 'status' => 3,
- 'start_episode_sequence' => $start_episode_sequence,
- 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
- 'episode_num' => count($script_arr['episodes']),
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- // 保存剧本内容
- $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
- if (!$boolen) {
- dLog('deepseek')->info('剧本内容保存失败', $update_data);
- Utils::throwError('20003:剧本内容保存失败');
- }
-
- // 保存分集内容
- // 删除历史分集内容
- $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
-
- $episodes = [];
- foreach ($script_arr['episodes'] as $episode) {
- $episodes[] = [
- 'script_id' => $script_id,
- 'episode_number' => $episode['episode_number'],
- 'title' => $episode['title'],
- 'content' => $episode['content'],
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- }
- $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
- if (!$boolen2) {
- dLog('deepseek')->info('分集内容保存失败', $episodes);
- Utils::throwError('20003:分集内容保存失败');
- }
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- return true;
- }
- public function getContentByBid($bid) {
- $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
- ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
- ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
- $content = '';
- foreach ($chapters as $chapter) {
- $content .= $chapter->content . PHP_EOL . PHP_EOL;
- }
- return $content;
- }
- /**
- * 根据文件类型提取文本内容
- *
- * @param mixed $file 文件对象或文件路径
- * @return string
- */
- public function extractFileContent($file) {
- // 获取文件路径和扩展名
- if (is_string($file)) {
- $filePath = $file;
- $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
- } else {
- // Laravel UploadedFile 对象
- $filePath = $file->getRealPath();
- $extension = strtolower($file->getClientOriginalExtension());
- }
- $content = '';
- switch ($extension) {
- case 'txt':
- $content = $this->extractTxtContent($filePath);
- break;
- case 'pdf':
- $content = $this->extractPdfContent($filePath);
- break;
- case 'doc':
- case 'docx':
- $content = $this->extractWordContent($filePath);
- break;
- // case 'jpg':
- // case 'jpeg':
- // case 'png':
- // case 'gif':
- // case 'bmp':
- // case 'webp':
- // $content = $this->extractImageContent($filePath);
- // break;
- default:
- Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
- }
- return $content;
- }
- /**
- * 提取 TXT 文件内容
- */
- private function extractTxtContent($filePath) {
- if (!file_exists($filePath)) {
- Utils::throwError('20003:文件不存在');
- }
- $content = file_get_contents($filePath);
- // 尝试检测并转换编码
- $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
- if ($encoding && $encoding !== 'UTF-8') {
- $content = mb_convert_encoding($content, 'UTF-8', $encoding);
- }
- return trim($content);
- }
- /**
- * 提取 PDF 文件内容
- */
- private function extractPdfContent($filePath) {
- if (!file_exists($filePath)) {
- Utils::throwError('20003:文件不存在');
- }
- try {
- $parser = new PdfParser();
- $pdf = $parser->parseFile($filePath);
- $content = $pdf->getText();
- return trim($content);
- } catch (\Exception $e) {
- Log::error('PDF解析失败: ' . $e->getMessage());
- Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
- }
- }
- /**
- * 提取 Word 文件内容(支持 doc 和 docx)
- */
- private function extractWordContent($filePath) {
- if (!file_exists($filePath)) {
- Utils::throwError('20003:文件不存在');
- }
- try {
- $phpWord = WordIOFactory::load($filePath);
- $content = '';
- foreach ($phpWord->getSections() as $section) {
- foreach ($section->getElements() as $element) {
- $content .= $this->extractWordElementText($element);
- }
- }
- return trim($content);
- } catch (\Exception $e) {
- Log::error('Word解析失败: ' . $e->getMessage());
- Utils::throwError('20003:Word解析失败,请确保文件格式正确');
- }
- }
- /**
- * 递归提取 Word 元素中的文本
- */
- private function extractWordElementText($element) {
- $text = '';
- if (method_exists($element, 'getText')) {
- $text .= $element->getText() . "\n";
- } elseif (method_exists($element, 'getElements')) {
- foreach ($element->getElements() as $childElement) {
- $text .= $this->extractWordElementText($childElement);
- }
- }
- return $text;
- }
- /**
- * 提取图片内容(使用火山引擎 OCR)
- */
- private function extractImageContent($filePath) {
- if (!file_exists($filePath)) {
- Utils::throwError('20003:文件不存在');
- }
- try {
- // 读取图片并转换为 base64
- $imageData = file_get_contents($filePath);
- $base64Image = base64_encode($imageData);
- // 调用火山引擎 OCR 服务
- $content = $this->callVolcEngineOCR($base64Image);
- return trim($content);
- } catch (\Exception $e) {
- Log::error('图片OCR识别失败: ' . $e->getMessage());
- Utils::throwError('20003:图片识别失败');
- }
- }
- /**
- * 调用火山引擎 OCR 服务识别图片文字
- *
- * @param string $base64Image base64 编码的图片数据
- * @return string 识别的文字内容
- */
- private function callVolcEngineOCR($base64Image) {
- $method = 'POST';
- $service = 'cv';
- $host = 'visual.volcengineapi.com';
- $region = env('VOLC_REGION', 'cn-north-1');
- $access_key = env('VOLC_AK');
- $secret_key = env('VOLC_SK');
- $action = 'OCRNormal';
- $version = '2020-08-26';
- if (!$access_key || !$secret_key) {
- Utils::throwError('20003:请配置火山引擎 AK/SK');
- }
- // 请求体
- $body = json_encode([
- 'image_base64' => $base64Image
- ]);
- // 生成签名
- $headers = $this->getVolcEngineSignHeaders(
- $method, $service, $host, $region,
- "Action={$action}&Version={$version}",
- $access_key, $secret_key, $body
- );
- $client = new Client(['timeout' => 60, 'verify' => false]);
- $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
- 'headers' => $headers,
- 'body' => $body
- ]);
- $response_arr = json_decode($response->getBody()->getContents(), true);
- // 提取识别的文字
- $textLines = [];
- if (isset($response_arr['data']['line_texts'])) {
- $textLines = $response_arr['data']['line_texts'];
- } elseif (isset($response_arr['data']['ocr_infos'])) {
- foreach ($response_arr['data']['ocr_infos'] as $info) {
- if (isset($info['text'])) {
- $textLines[] = $info['text'];
- }
- }
- }
- if (empty($textLines)) {
- Log::warning('OCR识别结果为空', ['response' => $response_arr]);
- return '';
- }
- return implode("\n", $textLines);
- }
- /**
- * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
- */
- private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
- $contentType = 'application/json';
- $accept = 'application/json';
-
- // 获取当前UTC时间
- $t = new DateTime('now', new DateTimeZone('UTC'));
- $xDate = $t->format('Ymd\THis\Z');
- $dateStamp = $t->format('Ymd');
-
- // 计算 body 的 sha256 哈希
- $payloadHash = hash('sha256', $body);
-
- // 1. 拼接规范请求串
- $canonicalUri = '/';
- $canonicalQueryString = $queryString;
- $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
- $signedHeaders = 'content-type;host;x-content-sha256;x-date';
-
- $canonicalRequest = implode("\n", [
- $method,
- $canonicalUri,
- $canonicalQueryString,
- $canonicalHeaders,
- $signedHeaders,
- $payloadHash
- ]);
-
- // 2. 拼接待签名字符串
- $algorithm = 'HMAC-SHA256';
- $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
- $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
-
- $stringToSign = implode("\n", [
- $algorithm,
- $xDate,
- $credentialScope,
- $hashedCanonicalRequest
- ]);
-
- // 3. 计算签名
- $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
- $signature = hash_hmac('sha256', $stringToSign, $signingKey);
-
- // 4. 添加签名到请求头
- $authorizationHeader = sprintf(
- '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
- $algorithm,
- $access_key,
- $credentialScope,
- $signedHeaders,
- $signature
- );
-
- return [
- 'Accept' => $accept,
- 'Content-Type' => $contentType,
- 'Host' => $host,
- 'X-Date' => $xDate,
- 'X-Content-Sha256'=> $payloadHash,
- 'Authorization' => $authorizationHeader
- ];
- }
- public function generateScriptWords($cid, $model = 'r1') {
- ini_set('max_execution_time', 0);
- if (!$cid) Utils::throwError('20003: 请选择章节!');
- $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
- $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
-
- $messages = [
- [
- 'role' => 'system',
- 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
- 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
- 2.非对话部分请全部用旁白角色代替
- 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
- ],
- [
- 'role' => 'user',
- 'content' => $content
- ]
- ];
- $post_data = [
- 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
- 'messages' => $messages,
- 'max_tokens' => 8192,
- 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
- // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
- 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
- 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
- 'response_format' => [
- 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
- ],
- 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
- ];
- $client = new Client(['timeout' => 1200, 'verify' => false]);
- $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- $update_data = [];
- $content = '';
- if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
- $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
- $update_data = [
- 'role' => 'assistant',
- 'content' => $response_arr['choices'][0]['message']['content'],
- 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
- ];
- }
- return $content;
- }
- }
|