DeepSeekController.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. <?php
  2. namespace App\Http\Controllers\DeepSeek;
  3. use App\Transformer\DeepSeek\DeepSeekTransformer;
  4. use App\Facade\Site;
  5. use App\Consts\ErrorConst;
  6. use App\Exceptions\ApiException;
  7. use App\Libs\ApiResponse;
  8. use App\Libs\Utils;
  9. use App\Services\DeepSeek\DeepSeekService;
  10. use App\Services\TaskCenterService;
  11. use Illuminate\Http\Request;
  12. use Illuminate\Routing\Controller as BaseController;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Redis;
  15. use Illuminate\Support\Facades\Validator;
  16. class DeepSeekController extends BaseController
  17. {
  18. use ApiResponse;
  19. protected $deepseekService;
  20. protected $taskCenterService;
  21. public function __construct(
  22. DeepSeekService $deepseekService,
  23. TaskCenterService $taskCenterService
  24. ) {
  25. $this->deepseekService = $deepseekService;
  26. $this->taskCenterService = $taskCenterService;
  27. }
  28. /**
  29. * 可选供应商
  30. *
  31. * @param Request $request
  32. * @return mixed
  33. */
  34. public function chatWithReasoner(Request $request) {
  35. // 忽略所有超时限制
  36. set_time_limit(0);
  37. ini_set('max_execution_time', '0');
  38. $data = $request->all();
  39. $result = $this->deepseekService->chatWithReasoner($data);
  40. return $this->success($result);
  41. }
  42. /**
  43. * 音色列表
  44. *
  45. * @param Request $request
  46. * @return mixed
  47. */
  48. public function timbreList(Request $request) {
  49. $data = $request->all();
  50. $result = $this->deepseekService->timbreList($data);
  51. return $this->success($result);
  52. }
  53. // 重置段落音频状态
  54. public function resetParagraphAudio(Request $request) {
  55. $data = $request->all();
  56. $result = $this->deepseekService->resetParagraphAudio($data);
  57. return $this->success(['success'=>$result ? 1 : 0]);
  58. }
  59. // 保存段落音频
  60. public function saveParagraphAudio(Request $request) {
  61. $data = $request->all();
  62. $result = $this->deepseekService->saveParagraphAudio($data);
  63. return $this->success(['success'=>$result ? 1 : 0]);
  64. }
  65. // 保存段落音频
  66. public function insertAudioEffect(Request $request) {
  67. $data = $request->all();
  68. $result = $this->deepseekService->insertAudioEffect($data);
  69. return $this->success(['success'=>$result ? 1 : 0]);
  70. }
  71. // 保存段落音频
  72. public function insertBgm(Request $request) {
  73. $data = $request->all();
  74. $result = $this->deepseekService->insertBgm($data);
  75. return $this->success(['success'=>$result ? 1 : 0]);
  76. }
  77. /**
  78. * 获取段落视频
  79. */
  80. public function paragraphAudios(Request $request) {
  81. $data = $request->all();
  82. $result = $this->deepseekService->getParagraphAudios($data);
  83. return $this->success($result);
  84. }
  85. /**
  86. * 新增合成任务
  87. *
  88. * @param Request $request
  89. * @return mixed
  90. */
  91. public function addGenerateTask(Request $request) {
  92. $data = $request->all();
  93. $result = $this->deepseekService->addGenerateTask($data);
  94. return $this->success(['success'=>$result ? 1 : 0]);
  95. }
  96. // 获取火山临时token
  97. public function setStsToken(Request $request) {
  98. $data = $request->all();
  99. $result = $this->deepseekService->setStsToken($data);
  100. return $this->success($result);
  101. }
  102. public function sseLink(Request $request) {
  103. $data = $request->all();
  104. $bid = getProp($data, 'bid');
  105. $version_id = getProp($data, 'version_id');
  106. $cid = getProp($data, 'cid');
  107. // 禁用输出缓冲
  108. while (ob_get_level()) ob_end_clean();
  109. // 设置SSE所需的HTTP头
  110. header('Content-Type: text/event-stream');
  111. header('Cache-Control: no-cache');
  112. header('Connection: keep-alive');
  113. header('X-Accel-Buffering: no'); // 防止Nginx缓冲
  114. // 允许跨域请求(根据需求设置)
  115. header('Access-Control-Allow-Origin: *');
  116. header('Access-Control-Allow-Credentials: true');
  117. // 设置脚本执行时间无限
  118. set_time_limit(0);
  119. // 手动刷新输出缓冲区
  120. ob_implicit_flush(true);
  121. if(ob_get_level()>0) ob_flush();
  122. flush();
  123. // 客户端ID(用于多用户区分)
  124. $clientId = $_SERVER['REMOTE_ADDR'] . ':' . $_SERVER['REMOTE_PORT'];
  125. $lastEventId = isset($_SERVER['HTTP_LAST_EVENT_ID']) ? intval($_SERVER['HTTP_LAST_EVENT_ID']) : 0;
  126. // dd($clientId, $lastEventId);
  127. // 发送初始欢迎消息
  128. $this->sendEvent([
  129. // 'message' => "欢迎使用SSE服务! 你的客户端ID: {$clientId}",
  130. // 'type' => 'info',
  131. // 'timestamp' => date('H:i:s')
  132. 'code' => 0,
  133. 'msg' => "已连接! 你的客户端ID: {$clientId}",
  134. 'data' => [],
  135. ]);
  136. if (!$bid && !$version_id && !$cid) {
  137. $this->sendEvent([
  138. // 'message' => '参数异常',
  139. // 'type' => 'error',
  140. // 'timestamp' => date('H:i:s')
  141. 'code' => -1,
  142. 'msg' => "参数异常",
  143. 'data' => [],
  144. ]);
  145. }
  146. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  147. // 主循环 - 定期发送数据
  148. while (true) {
  149. // 检查客户端是否断开连接
  150. if (connection_aborted()) {
  151. exit();
  152. }
  153. // 判断是否有待更新数据,有则查询
  154. $ids = Redis::smembers($redis_key);
  155. if (count($ids) > 0) {
  156. $count = DB::table('mp_chapter_paragraph_audios')->whereIn('id', $ids)->where(function($query) {
  157. return $query->where('generate_status', '!=', '制作中')->orWhere('error_msg', '!=', '');
  158. })->count('id');
  159. // 如果有更新数据,则发送消息
  160. if ($count > 0) {
  161. // 查询更新后的信息
  162. $paragraph_urls = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)
  163. ->where('cid', $cid)->where(function($query) {
  164. return $query->where('generate_status', '!=', '制作中')->orWhere('error_msg', '!=', '');
  165. })->select('id', 'sequence', 'generate_status', 'paragraph_audio_url', 'error_msg')
  166. ->get()->map(function ($value) {
  167. return (array)$value;
  168. })->toArray();
  169. $rem_ids = [];
  170. foreach ($paragraph_urls as $item) {
  171. $rem_ids[] = getProp($item, 'id');
  172. }
  173. // 发送消息
  174. $this->sendEvent([
  175. 'code' => 0,
  176. 'msg' => "",
  177. 'data' => $paragraph_urls,
  178. // 'message' => '数据更新',
  179. // 'type' => 'update',
  180. // 'timestamp' => date('H:i:s')
  181. ]);
  182. // 删除有数据的id
  183. Redis::srem($redis_key, $rem_ids);
  184. }
  185. }
  186. // 等待1秒
  187. sleep(1);
  188. }
  189. }
  190. private function sendEvent($data, $event = null, $id = null) {
  191. // // 事件ID
  192. // if ($id !== null) {
  193. // echo "id: {$id}\n";
  194. // }
  195. // 事件类型
  196. if ($event !== null) {
  197. echo "event: {$event}\n";
  198. }
  199. // 数据部分(JSON格式)
  200. echo "data: " . json_encode($data) . "\n\n";
  201. // 立即发送数据
  202. if(ob_get_level()>0) ob_flush();
  203. flush();
  204. }
  205. public function emotionGroups(Request $request) {
  206. $data = $request->all();
  207. $result = $this->deepseekService->emotionGroups($data);
  208. return $this->success($result);
  209. }
  210. /**
  211. * 剧本列表
  212. *
  213. * @param Request $request
  214. * @return mixed
  215. */
  216. public function scriptList(Request $request) {
  217. $data = $request->all();
  218. $result = $this->deepseekService->scriptList($data);
  219. return $this->success($result, [new DeepSeekTransformer(), 'newBuildScriptList']);
  220. }
  221. public function scripts(Request $request) {
  222. $data = $request->all();
  223. $result = $this->deepseekService->scripts($data);
  224. return $this->success($result);
  225. }
  226. // 剧本详情
  227. public function scriptInfo(Request $request) {
  228. $data = $request->all();
  229. $result = $this->deepseekService->scriptInfo($data);
  230. return $this->success($result);
  231. }
  232. /**
  233. * 创建剧本
  234. *
  235. * @param Request $request
  236. * @return mixed
  237. */
  238. public function createScript(Request $request) {
  239. $data = $request->all();
  240. $result = $this->deepseekService->createScript($data);
  241. return $this->success(['script_id' => $result]);
  242. }
  243. // 编辑剧本
  244. public function editScript(Request $request) {
  245. $data = $request->all();
  246. $result = $this->deepseekService->editScript($data);
  247. return $this->success(['success' => $result ? 1 : 0]);
  248. }
  249. // 删除剧本
  250. public function delScript(Request $request) {
  251. $data = $request->all();
  252. $result = $this->deepseekService->delScript($data);
  253. return $this->success(['success' => $result ? 1 : 0]);
  254. }
  255. /**
  256. * 创建分集组
  257. *
  258. * @param Request $request
  259. * @return mixed
  260. */
  261. public function createEpisode(Request $request) {
  262. $data = $request->all();
  263. $result = $this->deepseekService->createEpisode($data);
  264. return $this->success(['group_id' => $result]);
  265. }
  266. // 编辑剧本
  267. public function editEpisode(Request $request) {
  268. $data = $request->all();
  269. $result = $this->deepseekService->editEpisode($data);
  270. return $this->success(['success' => $result ? 1 : 0]);
  271. }
  272. // 删除剧本
  273. public function delEpisode(Request $request) {
  274. $data = $request->all();
  275. $result = $this->deepseekService->delEpisode($data);
  276. return $this->success(['success' => $result ? 1 : 0]);
  277. }
  278. /**
  279. * 与DeepSeek对话(带文件上传)
  280. * @param Request $request
  281. * @return mixed
  282. * @throws ApiException
  283. */
  284. public function chatWithFile(Request $request) {
  285. // 忽略所有超时限制
  286. set_time_limit(0);
  287. ini_set('max_execution_time', '0');
  288. $data = $request->all();
  289. $result = $this->deepseekService->chatWithFile($data);
  290. return $this->success($result);
  291. }
  292. /**
  293. * 与DeepSeek对话(带文件上传 - 流式输出版本)
  294. * @param Request $request
  295. * @return \Symfony\Component\HttpFoundation\StreamedResponse
  296. * @throws ApiException
  297. */
  298. public function chatWithFileStream(Request $request) {
  299. // 忽略所有超时限制
  300. set_time_limit(0);
  301. ini_set('max_execution_time', '0');
  302. $data = $request->all();
  303. return response()->stream(function () use ($data) {
  304. // 禁用所有输出缓冲
  305. if (ob_get_level()) {
  306. ob_end_clean();
  307. }
  308. // 设置输出缓冲为关闭
  309. ini_set('output_buffering', 'off');
  310. ini_set('zlib.output_compression', 'off');
  311. // 立即刷新
  312. if (function_exists('apache_setenv')) {
  313. apache_setenv('no-gzip', '1');
  314. }
  315. try {
  316. $generator = $this->deepseekService->chatWithFileStream($data);
  317. foreach ($generator as $chunk) {
  318. // 发送 SSE 格式的数据
  319. $jsonData = json_encode($chunk, JSON_UNESCAPED_UNICODE);
  320. echo "data: {$jsonData}\n\n";
  321. // 强制刷新输出缓冲区
  322. if (ob_get_level() > 0) {
  323. ob_flush();
  324. }
  325. flush();
  326. // 检查客户端是否断开连接
  327. if (connection_aborted()) {
  328. break;
  329. }
  330. }
  331. // 发送结束标记
  332. echo "data: [DONE]\n\n";
  333. if (ob_get_level() > 0) {
  334. ob_flush();
  335. }
  336. flush();
  337. } catch (\Exception $e) {
  338. // 发送错误信息
  339. $error = [
  340. 'type' => 'error',
  341. 'msg' => $e->getMessage(),
  342. 'code' => $e->getCode()
  343. ];
  344. $jsonError = json_encode($error, JSON_UNESCAPED_UNICODE);
  345. echo "data: {$jsonError}\n\n";
  346. if (ob_get_level() > 0) {
  347. ob_flush();
  348. }
  349. flush();
  350. }
  351. }, 200, [
  352. 'Content-Type' => 'text/event-stream',
  353. 'Cache-Control' => 'no-cache',
  354. 'Connection' => 'keep-alive',
  355. 'X-Accel-Buffering' => 'no', // 防止 Nginx 缓冲
  356. 'Access-Control-Allow-Origin' => '*',
  357. 'Access-Control-Allow-Credentials' => 'true'
  358. ]);
  359. }
  360. public function generateEpisodes(Request $request) {
  361. // 忽略所有超时限制
  362. set_time_limit(0);
  363. ini_set('max_execution_time', '0');
  364. $data = $request->all();
  365. return response()->stream(function () use ($data) {
  366. // 禁用所有输出缓冲
  367. if (ob_get_level()) {
  368. ob_end_clean();
  369. }
  370. // 设置输出缓冲为关闭
  371. ini_set('output_buffering', 'off');
  372. ini_set('zlib.output_compression', 'off');
  373. // 立即刷新
  374. if (function_exists('apache_setenv')) {
  375. apache_setenv('no-gzip', '1');
  376. }
  377. try {
  378. $generator = $this->deepseekService->generateEpisodes($data);
  379. foreach ($generator as $chunk) {
  380. // 发送 SSE 格式的数据
  381. $jsonData = json_encode($chunk, JSON_UNESCAPED_UNICODE);
  382. echo "data: {$jsonData}\n\n";
  383. // 强制刷新输出缓冲区
  384. if (ob_get_level() > 0) {
  385. ob_flush();
  386. }
  387. flush();
  388. // 检查客户端是否断开连接
  389. if (connection_aborted()) {
  390. break;
  391. }
  392. }
  393. // 发送结束标记
  394. echo "data: [DONE]\n\n";
  395. if (ob_get_level() > 0) {
  396. ob_flush();
  397. }
  398. flush();
  399. } catch (\Exception $e) {
  400. // 发送错误信息
  401. $error = [
  402. 'type' => 'error',
  403. 'msg' => $e->getMessage(),
  404. 'code' => $e->getCode()
  405. ];
  406. $jsonError = json_encode($error, JSON_UNESCAPED_UNICODE);
  407. echo "data: {$jsonError}\n\n";
  408. if (ob_get_level() > 0) {
  409. ob_flush();
  410. }
  411. flush();
  412. }
  413. }, 200, [
  414. 'Content-Type' => 'text/event-stream',
  415. 'Cache-Control' => 'no-cache',
  416. 'Connection' => 'keep-alive',
  417. 'X-Accel-Buffering' => 'no', // 防止 Nginx 缓冲
  418. 'Access-Control-Allow-Origin' => '*',
  419. 'Access-Control-Allow-Credentials' => 'true'
  420. ]);
  421. }
  422. public function getEpisodeContent(Request $request) {
  423. $data = $request->all();
  424. $result = $this->deepseekService->getEpisodeContent($data);
  425. return $this->success($result);
  426. }
  427. // 保存剧本
  428. public function saveEpisodeContent(Request $request) {
  429. $data = $request->all();
  430. $result = $this->deepseekService->saveEpisodeContent($data);
  431. return $this->success(['success'=>$result ? 1 : 0]);
  432. }
  433. // 导出剧本
  434. public function exportScript(Request $request) {
  435. $data = $request->all();
  436. // 验证必要参数
  437. if (empty($data['script_id'])) {
  438. return $this->error('20003:缺少剧本ID参数');
  439. }
  440. // 直接调用导出服务,该方法会直接输出文件并退出
  441. $this->deepseekService->exportScript($data);
  442. }
  443. public function getBookContent(Request $request) {
  444. $data = $request->all();
  445. // 直接调用导出服务,该方法会直接输出文件并退出
  446. $result = $this->deepseekService->getBookContent($data);
  447. return $this->success($result);
  448. }
  449. public function createGenerateText(Request $request) {
  450. // 忽略所有超时限制
  451. set_time_limit(0);
  452. ini_set('max_execution_time', '0');
  453. $data = $request->all();
  454. $result = $this->deepseekService->createGenerateText($data);
  455. return $this->success($result);
  456. }
  457. /**
  458. * 通用文生文(非流式版本)
  459. * @param Request $request
  460. * @return mixed
  461. */
  462. public function newGenerateText(Request $request) {
  463. // 忽略所有超时限制
  464. set_time_limit(0);
  465. ini_set('max_execution_time', '0');
  466. $data = $request->all();
  467. // stream=1 + script_id:剧本资产生成走异步任务模式(worker 执行,SSE 每 10s 轮询推送,最长 30 分钟)
  468. if ((int)getProp($data, 'stream', 0) === 1 && (int)getProp($data, 'script_id', 0) > 0) {
  469. $taskId = $this->deepseekService->createScriptGenerateAsyncTask($data);
  470. $uid = (int)\App\Facade\Site::getUid();
  471. return response()->stream(function () use ($taskId, $uid) {
  472. if (ob_get_level()) {
  473. ob_end_clean();
  474. }
  475. ini_set('output_buffering', 'off');
  476. ini_set('zlib.output_compression', 'off');
  477. if (function_exists('apache_setenv')) {
  478. apache_setenv('no-gzip', '1');
  479. }
  480. $push = function (array $chunk) {
  481. echo "data: " . json_encode($chunk, JSON_UNESCAPED_UNICODE) . "\n\n";
  482. if (ob_get_level() > 0) {
  483. ob_flush();
  484. }
  485. flush();
  486. };
  487. // SSE 轮询:每 10s 查询一次任务状态与新增 chunks,最长等待 30 分钟
  488. $deadline = time() + 1800;
  489. $lastSeq = -1;
  490. $terminalPushed = false;
  491. try {
  492. while (time() < $deadline) {
  493. if (connection_aborted()) {
  494. // 浏览器断开:停止推送,后台 worker 继续执行并落库
  495. return;
  496. }
  497. $poll = $this->deepseekService->pollScriptGenerateTask($taskId, $uid, $lastSeq);
  498. if (!$poll['found']) {
  499. $push([
  500. 'type' => 'error',
  501. 'message' => '生成任务不存在或无权访问',
  502. ]);
  503. return;
  504. }
  505. foreach ($poll['chunks'] as $chunk) {
  506. $push($chunk);
  507. $lastSeq++;
  508. if (isset($chunk['type']) && in_array($chunk['type'], ['done', 'error'])) {
  509. $terminalPushed = true;
  510. }
  511. }
  512. $status = (string)getProp($poll, 'status', '');
  513. // 任务已结束:补齐可能尚未写入的 done/error chunk 后关闭连接
  514. if (in_array($status, ['success', 'failed'])) {
  515. $waitRound = 0;
  516. while (!$terminalPushed && $waitRound < 3) {
  517. sleep(3);
  518. $waitRound++;
  519. $pollRetry = $this->deepseekService->pollScriptGenerateTask($taskId, $uid, $lastSeq);
  520. foreach ($pollRetry['chunks'] as $chunk) {
  521. $push($chunk);
  522. $lastSeq++;
  523. if (isset($chunk['type']) && in_array($chunk['type'], ['done', 'error'])) {
  524. $terminalPushed = true;
  525. }
  526. }
  527. }
  528. if (!$terminalPushed && $status === 'failed') {
  529. $push([
  530. 'type' => 'error',
  531. 'message' => (string)getProp($poll, 'error_message', '') !== ''
  532. ? (string)getProp($poll, 'error_message', '')
  533. : '内容生成失败',
  534. ]);
  535. }
  536. return;
  537. }
  538. // 未完成:每 10s 轮询一次
  539. sleep(10);
  540. }
  541. // 30 分钟未完成:向前端提示超时,任务继续在后台执行
  542. $push([
  543. 'type' => 'error',
  544. 'message' => '生成超时,任务仍在后台继续执行,请稍后查看任务列表',
  545. ]);
  546. } catch (\Throwable $e) {
  547. $push([
  548. 'type' => 'error',
  549. 'message' => $e->getMessage(),
  550. ]);
  551. }
  552. }, 200, [
  553. 'Content-Type' => 'text/event-stream',
  554. 'Cache-Control' => 'no-cache',
  555. 'Connection' => 'keep-alive',
  556. 'X-Accel-Buffering' => 'no',
  557. ]);
  558. }
  559. // stream=1:SSE 流式输出(格式与 generateText 一致:yield type=content/reasoning/done)
  560. if ((int)getProp($data, 'stream', 0) === 1) {
  561. return response()->stream(function () use ($data) {
  562. if (ob_get_level()) {
  563. ob_end_clean();
  564. }
  565. ini_set('output_buffering', 'off');
  566. ini_set('zlib.output_compression', 'off');
  567. if (function_exists('apache_setenv')) {
  568. apache_setenv('no-gzip', '1');
  569. }
  570. try {
  571. $result = $this->deepseekService->newGenerateText($data);
  572. foreach ($result as $chunk) {
  573. echo "data: " . json_encode($chunk, JSON_UNESCAPED_UNICODE) . "\n\n";
  574. if (ob_get_level() > 0) {
  575. ob_flush();
  576. }
  577. flush();
  578. if (connection_aborted()) {
  579. break;
  580. }
  581. }
  582. } catch (\Throwable $e) {
  583. echo "data: " . json_encode([
  584. 'type' => 'error',
  585. 'message' => $e->getMessage(),
  586. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  587. if (ob_get_level() > 0) {
  588. ob_flush();
  589. }
  590. flush();
  591. }
  592. }, 200, [
  593. 'Content-Type' => 'text/event-stream',
  594. 'Cache-Control' => 'no-cache',
  595. 'Connection' => 'keep-alive',
  596. 'X-Accel-Buffering' => 'no',
  597. ]);
  598. }
  599. $result = $this->deepseekService->newGenerateText($data);
  600. return $this->success($result);
  601. }
  602. /**
  603. * 获取剧本资产生成任务列表
  604. * @param Request $request
  605. * @return mixed
  606. */
  607. public function getScriptGenerateTasks(Request $request) {
  608. $data = $request->all();
  609. $result = $this->deepseekService->getScriptGenerateTasks($data);
  610. return $this->success($result, [new DeepSeekTransformer(), 'newBuildScriptGenerateTaskList']);
  611. }
  612. // 保存剧本沟通记录
  613. public function saveScriptChatHistory(Request $request) {
  614. $data = $request->all();
  615. $result = $this->deepseekService->saveScriptChatHistory($data);
  616. return $this->success(['success'=>$result ? 1 : 0]);
  617. }
  618. /**
  619. * 获取剧本的历史对话记录
  620. * @param Request $request
  621. * @return mixed
  622. */
  623. public function getScriptChatHistory(Request $request) {
  624. $data = $request->all();
  625. $result = $this->deepseekService->getScriptChatHistory($data);
  626. return $this->success($result);
  627. }
  628. // 新建对话
  629. public function addChat(Request $request) {
  630. // 忽略所有超时限制
  631. set_time_limit(0);
  632. ini_set('max_execution_time', '0');
  633. $data = $request->all();
  634. return response()->stream(function () use ($data) {
  635. // 禁用所有输出缓冲
  636. if (ob_get_level()) {
  637. ob_end_clean();
  638. }
  639. // 设置输出缓冲为关闭
  640. ini_set('output_buffering', 'off');
  641. ini_set('zlib.output_compression', 'off');
  642. // 立即刷新
  643. if (function_exists('apache_setenv')) {
  644. apache_setenv('no-gzip', '1');
  645. }
  646. try {
  647. $generator = $this->deepseekService->addChat($data);
  648. foreach ($generator as $chunk) {
  649. // 发送 SSE 格式的数据
  650. $jsonData = json_encode($chunk, JSON_UNESCAPED_UNICODE);
  651. echo "data: {$jsonData}\n\n";
  652. // 强制刷新输出缓冲区
  653. if (ob_get_level() > 0) {
  654. ob_flush();
  655. }
  656. flush();
  657. // 检查客户端是否断开连接
  658. if (connection_aborted()) {
  659. break;
  660. }
  661. }
  662. // 发送结束标记
  663. echo "data: [DONE]\n\n";
  664. if (ob_get_level() > 0) {
  665. ob_flush();
  666. }
  667. flush();
  668. } catch (\Exception $e) {
  669. // 发送错误信息
  670. $error = [
  671. 'type' => 'error',
  672. 'msg' => $e->getMessage(),
  673. 'code' => $e->getCode()
  674. ];
  675. $jsonError = json_encode($error, JSON_UNESCAPED_UNICODE);
  676. echo "data: {$jsonError}\n\n";
  677. if (ob_get_level() > 0) {
  678. ob_flush();
  679. }
  680. flush();
  681. }
  682. }, 200, [
  683. 'Content-Type' => 'text/event-stream',
  684. 'Cache-Control' => 'no-cache',
  685. 'Connection' => 'keep-alive',
  686. 'X-Accel-Buffering' => 'no', // 防止 Nginx 缓冲
  687. 'Access-Control-Allow-Origin' => '*',
  688. 'Access-Control-Allow-Credentials' => 'true'
  689. ]);
  690. }
  691. // 调整大纲
  692. public function reGenerateAnime(Request $request) {
  693. // 忽略所有超时限制
  694. set_time_limit(0);
  695. ini_set('max_execution_time', '0');
  696. $data = $request->all();
  697. return response()->stream(function () use ($data) {
  698. // 禁用所有输出缓冲
  699. if (ob_get_level()) {
  700. ob_end_clean();
  701. }
  702. // 设置输出缓冲为关闭
  703. ini_set('output_buffering', 'off');
  704. ini_set('zlib.output_compression', 'off');
  705. // 立即刷新
  706. if (function_exists('apache_setenv')) {
  707. apache_setenv('no-gzip', '1');
  708. }
  709. try {
  710. $generator = $this->deepseekService->reGenerateAnime($data);
  711. foreach ($generator as $chunk) {
  712. // 发送 SSE 格式的数据
  713. $jsonData = json_encode($chunk, JSON_UNESCAPED_UNICODE);
  714. echo "data: {$jsonData}\n\n";
  715. // 强制刷新输出缓冲区
  716. if (ob_get_level() > 0) {
  717. ob_flush();
  718. }
  719. flush();
  720. // 检查客户端是否断开连接
  721. if (connection_aborted()) {
  722. break;
  723. }
  724. }
  725. // 发送结束标记
  726. echo "data: [DONE]\n\n";
  727. if (ob_get_level() > 0) {
  728. ob_flush();
  729. }
  730. flush();
  731. } catch (\Exception $e) {
  732. // 发送错误信息
  733. $error = [
  734. 'type' => 'error',
  735. 'msg' => $e->getMessage(),
  736. 'code' => $e->getCode()
  737. ];
  738. $jsonError = json_encode($error, JSON_UNESCAPED_UNICODE);
  739. echo "data: {$jsonError}\n\n";
  740. if (ob_get_level() > 0) {
  741. ob_flush();
  742. }
  743. flush();
  744. }
  745. }, 200, [
  746. 'Content-Type' => 'text/event-stream',
  747. 'Cache-Control' => 'no-cache',
  748. 'Connection' => 'keep-alive',
  749. 'X-Accel-Buffering' => 'no', // 防止 Nginx 缓冲
  750. 'Access-Control-Allow-Origin' => '*',
  751. 'Access-Control-Allow-Credentials' => 'true'
  752. ]);
  753. }
  754. public function chat(Request $request) {
  755. // 忽略所有超时限制
  756. set_time_limit(0);
  757. ini_set('max_execution_time', '0');
  758. $data = $request->all();
  759. return response()->stream(function () use ($data) {
  760. // 禁用所有输出缓冲
  761. if (ob_get_level()) {
  762. ob_end_clean();
  763. }
  764. // 设置输出缓冲为关闭
  765. ini_set('output_buffering', 'off');
  766. ini_set('zlib.output_compression', 'off');
  767. // 立即刷新
  768. if (function_exists('apache_setenv')) {
  769. apache_setenv('no-gzip', '1');
  770. }
  771. try {
  772. $generator = $this->deepseekService->chat($data);
  773. foreach ($generator as $chunk) {
  774. // 发送 SSE 格式的数据
  775. $jsonData = json_encode($chunk, JSON_UNESCAPED_UNICODE);
  776. echo "data: {$jsonData}\n\n";
  777. // 强制刷新输出缓冲区
  778. if (ob_get_level() > 0) {
  779. ob_flush();
  780. }
  781. flush();
  782. // 检查客户端是否断开连接
  783. if (connection_aborted()) {
  784. break;
  785. }
  786. }
  787. // 发送结束标记
  788. echo "data: [DONE]\n\n";
  789. if (ob_get_level() > 0) {
  790. ob_flush();
  791. }
  792. flush();
  793. } catch (\Exception $e) {
  794. // 发送错误信息
  795. $error = [
  796. 'type' => 'error',
  797. 'msg' => $e->getMessage(),
  798. 'code' => $e->getCode()
  799. ];
  800. $jsonError = json_encode($error, JSON_UNESCAPED_UNICODE);
  801. echo "data: {$jsonError}\n\n";
  802. if (ob_get_level() > 0) {
  803. ob_flush();
  804. }
  805. flush();
  806. }
  807. }, 200, [
  808. 'Content-Type' => 'text/event-stream',
  809. 'Cache-Control' => 'no-cache',
  810. 'Connection' => 'keep-alive',
  811. 'X-Accel-Buffering' => 'no', // 防止 Nginx 缓冲
  812. 'Access-Control-Allow-Origin' => '*',
  813. 'Access-Control-Allow-Credentials' => 'true'
  814. ]);
  815. }
  816. // 新建对话
  817. public function addChatForAce(Request $request) {
  818. // 忽略所有超时限制
  819. set_time_limit(0);
  820. ini_set('max_execution_time', '0');
  821. $data = $request->all();
  822. return response()->stream(function () use ($data) {
  823. // 禁用所有输出缓冲
  824. if (ob_get_level()) {
  825. ob_end_clean();
  826. }
  827. // 设置输出缓冲为关闭
  828. ini_set('output_buffering', 'off');
  829. ini_set('zlib.output_compression', 'off');
  830. // 立即刷新
  831. if (function_exists('apache_setenv')) {
  832. apache_setenv('no-gzip', '1');
  833. }
  834. try {
  835. $generator = $this->deepseekService->addChatForAce($data);
  836. foreach ($generator as $chunk) {
  837. // 发送 SSE 格式的数据
  838. $jsonData = json_encode($chunk, JSON_UNESCAPED_UNICODE);
  839. echo "data: {$jsonData}\n\n";
  840. // 强制刷新输出缓冲区
  841. if (ob_get_level() > 0) {
  842. ob_flush();
  843. }
  844. flush();
  845. // 检查客户端是否断开连接
  846. if (connection_aborted()) {
  847. break;
  848. }
  849. }
  850. // 发送结束标记
  851. echo "data: [DONE]\n\n";
  852. if (ob_get_level() > 0) {
  853. ob_flush();
  854. }
  855. flush();
  856. } catch (\Exception $e) {
  857. // 发送错误信息
  858. $error = [
  859. 'type' => 'error',
  860. 'msg' => $e->getMessage(),
  861. 'code' => $e->getCode()
  862. ];
  863. $jsonError = json_encode($error, JSON_UNESCAPED_UNICODE);
  864. echo "data: {$jsonError}\n\n";
  865. if (ob_get_level() > 0) {
  866. ob_flush();
  867. }
  868. flush();
  869. }
  870. }, 200, [
  871. 'Content-Type' => 'text/event-stream',
  872. 'Cache-Control' => 'no-cache',
  873. 'Connection' => 'keep-alive',
  874. 'X-Accel-Buffering' => 'no', // 防止 Nginx 缓冲
  875. 'Access-Control-Allow-Origin' => '*',
  876. 'Access-Control-Allow-Credentials' => 'true'
  877. ]);
  878. }
  879. // 调整大纲
  880. public function reGenerateAnimeForAce(Request $request) {
  881. // 忽略所有超时限制
  882. set_time_limit(0);
  883. ini_set('max_execution_time', '0');
  884. $data = $request->all();
  885. return response()->stream(function () use ($data) {
  886. // 禁用所有输出缓冲
  887. if (ob_get_level()) {
  888. ob_end_clean();
  889. }
  890. // 设置输出缓冲为关闭
  891. ini_set('output_buffering', 'off');
  892. ini_set('zlib.output_compression', 'off');
  893. // 立即刷新
  894. if (function_exists('apache_setenv')) {
  895. apache_setenv('no-gzip', '1');
  896. }
  897. try {
  898. $generator = $this->deepseekService->reGenerateAnimeForAce($data);
  899. foreach ($generator as $chunk) {
  900. // 发送 SSE 格式的数据
  901. $jsonData = json_encode($chunk, JSON_UNESCAPED_UNICODE);
  902. echo "data: {$jsonData}\n\n";
  903. // 强制刷新输出缓冲区
  904. if (ob_get_level() > 0) {
  905. ob_flush();
  906. }
  907. flush();
  908. // 检查客户端是否断开连接
  909. if (connection_aborted()) {
  910. break;
  911. }
  912. }
  913. // 发送结束标记
  914. echo "data: [DONE]\n\n";
  915. if (ob_get_level() > 0) {
  916. ob_flush();
  917. }
  918. flush();
  919. } catch (\Exception $e) {
  920. // 发送错误信息
  921. $error = [
  922. 'type' => 'error',
  923. 'msg' => $e->getMessage(),
  924. 'code' => $e->getCode()
  925. ];
  926. $jsonError = json_encode($error, JSON_UNESCAPED_UNICODE);
  927. echo "data: {$jsonError}\n\n";
  928. if (ob_get_level() > 0) {
  929. ob_flush();
  930. }
  931. flush();
  932. }
  933. }, 200, [
  934. 'Content-Type' => 'text/event-stream',
  935. 'Cache-Control' => 'no-cache',
  936. 'Connection' => 'keep-alive',
  937. 'X-Accel-Buffering' => 'no', // 防止 Nginx 缓冲
  938. 'Access-Control-Allow-Origin' => '*',
  939. 'Access-Control-Allow-Credentials' => 'true'
  940. ]);
  941. }
  942. public function chatForAce(Request $request) {
  943. // 忽略所有超时限制
  944. set_time_limit(0);
  945. ini_set('max_execution_time', '0');
  946. $data = $request->all();
  947. return response()->stream(function () use ($data) {
  948. // 禁用所有输出缓冲
  949. if (ob_get_level()) {
  950. ob_end_clean();
  951. }
  952. // 设置输出缓冲为关闭
  953. ini_set('output_buffering', 'off');
  954. ini_set('zlib.output_compression', 'off');
  955. // 立即刷新
  956. if (function_exists('apache_setenv')) {
  957. apache_setenv('no-gzip', '1');
  958. }
  959. try {
  960. $generator = $this->deepseekService->chatForAce($data);
  961. foreach ($generator as $chunk) {
  962. // 发送 SSE 格式的数据
  963. $jsonData = json_encode($chunk, JSON_UNESCAPED_UNICODE);
  964. echo "data: {$jsonData}\n\n";
  965. // 强制刷新输出缓冲区
  966. if (ob_get_level() > 0) {
  967. ob_flush();
  968. }
  969. flush();
  970. // 检查客户端是否断开连接
  971. if (connection_aborted()) {
  972. break;
  973. }
  974. }
  975. // 发送结束标记
  976. echo "data: [DONE]\n\n";
  977. if (ob_get_level() > 0) {
  978. ob_flush();
  979. }
  980. flush();
  981. } catch (\Exception $e) {
  982. // 发送错误信息
  983. $error = [
  984. 'type' => 'error',
  985. 'msg' => $e->getMessage(),
  986. 'code' => $e->getCode()
  987. ];
  988. $jsonError = json_encode($error, JSON_UNESCAPED_UNICODE);
  989. echo "data: {$jsonError}\n\n";
  990. if (ob_get_level() > 0) {
  991. ob_flush();
  992. }
  993. flush();
  994. }
  995. }, 200, [
  996. 'Content-Type' => 'text/event-stream',
  997. 'Cache-Control' => 'no-cache',
  998. 'Connection' => 'keep-alive',
  999. 'X-Accel-Buffering' => 'no', // 防止 Nginx 缓冲
  1000. 'Access-Control-Allow-Origin' => '*',
  1001. 'Access-Control-Allow-Credentials' => 'true'
  1002. ]);
  1003. }
  1004. // 对话改图
  1005. public function chatChangeImg(Request $request) {
  1006. $data = $request->all();
  1007. $result = $this->deepseekService->chatChangeImg($data);
  1008. return $this->success($result);
  1009. }
  1010. /**
  1011. * 通用文生文接口 - 流式输出
  1012. * @param Request $request
  1013. * @return \Symfony\Component\HttpFoundation\StreamedResponse
  1014. */
  1015. public function generateText(Request $request) {
  1016. // 忽略所有超时限制
  1017. set_time_limit(0);
  1018. ini_set('max_execution_time', '0');
  1019. $data = $request->all();
  1020. // 处理上传的图片文件
  1021. if ($request->hasFile('images')) {
  1022. $data['images'] = $request->file('images');
  1023. } else if ($request->hasFile('image')) {
  1024. // 支持单张图片
  1025. $data['images'] = [$request->file('image')];
  1026. }
  1027. // 处理上传的视频文件(仅 Gemini 模型支持)
  1028. if ($request->hasFile('videos')) {
  1029. $data['videos'] = $request->file('videos');
  1030. } else if ($request->hasFile('video')) {
  1031. $data['videos'] = [$request->file('video')];
  1032. }
  1033. return response()->stream(function () use ($data) {
  1034. // 禁用所有输出缓冲
  1035. if (ob_get_level()) {
  1036. ob_end_clean();
  1037. }
  1038. // 设置输出缓冲为关闭
  1039. ini_set('output_buffering', 'off');
  1040. ini_set('zlib.output_compression', 'off');
  1041. // 立即刷新
  1042. if (function_exists('apache_setenv')) {
  1043. apache_setenv('no-gzip', '1');
  1044. }
  1045. try {
  1046. // 构建可序列化的参数快照(剔除上传文件对象)
  1047. $paramsSnapshot = $data;
  1048. unset($paramsSnapshot['images'], $paramsSnapshot['videos']);
  1049. // 创建任务中心记录(文字任务直接更新任务结果)
  1050. $taskCenter = $this->taskCenterService->createTask('text', [
  1051. 'title' => '文生文',
  1052. 'prompt' => getProp($data, 'prompt', ''),
  1053. 'params' => json_encode($paramsSnapshot, JSON_UNESCAPED_UNICODE),
  1054. ]);
  1055. $taskCenterId = $taskCenter->id;
  1056. $generator = $this->deepseekService->generateText($data);
  1057. $fullContent = '';
  1058. $firstChunk = true;
  1059. foreach ($generator as $chunk) {
  1060. // 第一条消息附加任务中心ID(不改变原消息结构和输出顺序)
  1061. if ($firstChunk) {
  1062. $chunk['task_center_id'] = $taskCenterId;
  1063. $firstChunk = false;
  1064. }
  1065. // 累积完整文本内容
  1066. if (isset($chunk['type']) && $chunk['type'] === 'content') {
  1067. $fullContent .= (string)getProp($chunk, 'content', '');
  1068. }
  1069. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  1070. $fullContent = (string)getProp($chunk, 'full_content', $fullContent);
  1071. }
  1072. // 发送 SSE 格式的数据
  1073. $jsonData = json_encode($chunk, JSON_UNESCAPED_UNICODE);
  1074. echo "data: {$jsonData}\n\n";
  1075. // 强制刷新输出缓冲区
  1076. if (ob_get_level() > 0) {
  1077. ob_flush();
  1078. }
  1079. flush();
  1080. // 检查客户端是否断开连接
  1081. if (connection_aborted()) {
  1082. break;
  1083. }
  1084. }
  1085. // 发送结束标记
  1086. echo "data: [DONE]\n\n";
  1087. if (ob_get_level() > 0) {
  1088. ob_flush();
  1089. }
  1090. flush();
  1091. // 文字任务直接更新任务中心结果
  1092. $this->taskCenterService->updateTask($taskCenterId, [
  1093. 'status' => 'success',
  1094. 'result' => $fullContent,
  1095. 'error_message' => null,
  1096. ]);
  1097. } catch (\Exception $e) {
  1098. // 任务失败,更新任务中心状态(任务中心记录可能未创建成功)
  1099. if (isset($taskCenterId)) {
  1100. $this->taskCenterService->updateTask($taskCenterId, [
  1101. 'status' => 'failed',
  1102. 'error_message' => $e->getMessage(),
  1103. ]);
  1104. }
  1105. // 发送错误信息
  1106. $error = [
  1107. 'type' => 'error',
  1108. 'msg' => $e->getMessage(),
  1109. 'code' => $e->getCode()
  1110. ];
  1111. $jsonError = json_encode($error, JSON_UNESCAPED_UNICODE);
  1112. echo "data: {$jsonError}\n\n";
  1113. if (ob_get_level() > 0) {
  1114. ob_flush();
  1115. }
  1116. flush();
  1117. }
  1118. }, 200, [
  1119. 'Content-Type' => 'text/event-stream',
  1120. 'Cache-Control' => 'no-cache',
  1121. 'Connection' => 'keep-alive',
  1122. 'X-Accel-Buffering' => 'no', // 防止 Nginx 缓冲
  1123. 'Access-Control-Allow-Origin' => '*',
  1124. 'Access-Control-Allow-Credentials' => 'true'
  1125. ]);
  1126. }
  1127. /**
  1128. * 重新生成分段剧本
  1129. * @param Request $request
  1130. * @return mixed
  1131. */
  1132. public function regenerateSegmentScript(Request $request) {
  1133. // 忽略所有超时限制
  1134. set_time_limit(0);
  1135. ini_set('max_execution_time', '0');
  1136. $data = $request->all();
  1137. $result = $this->deepseekService->regenerateSegmentScript($data);
  1138. return $this->success($result);
  1139. }
  1140. /**
  1141. * 保存剧集片段(预览确认模式使用):删除旧数据并保存新数据
  1142. * @param Request $request
  1143. * @return mixed
  1144. */
  1145. public function saveEpisodeActs(Request $request) {
  1146. // 忽略所有超时限制
  1147. set_time_limit(0);
  1148. ini_set('max_execution_time', '0');
  1149. $data = $request->all();
  1150. $result = $this->deepseekService->saveEpisodeActs($data);
  1151. return $this->success($result);
  1152. }
  1153. /**
  1154. * 批量生成多个分集
  1155. * @param Request $request
  1156. * @return mixed
  1157. */
  1158. public function batchGenerateEpisodes(Request $request) {
  1159. $data = $request->all();
  1160. $result = $this->deepseekService->batchGenerateEpisodes($data);
  1161. return $this->success($result);
  1162. }
  1163. /**
  1164. * 获取批量生成任务状态
  1165. * @param Request $request
  1166. * @return mixed
  1167. */
  1168. public function getBatchGenerationTaskStatus(Request $request) {
  1169. $data = $request->all();
  1170. $result = $this->deepseekService->getBatchGenerationTaskStatus($data);
  1171. return $this->success($result);
  1172. }
  1173. }