AnimeController.php 144 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161
  1. <?php
  2. namespace App\Http\Controllers\Anime;
  3. use App\Transformer\Anime\AnimeTransformer;
  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\Models\MpGenerateVideoTask;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use App\Services\AIGeneration\AIVideoGenerationService;
  12. use App\Services\Anime\AnimeService;
  13. use Illuminate\Http\Request;
  14. use Illuminate\Routing\Controller as BaseController;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Redis;
  17. use Illuminate\Support\Facades\Validator;
  18. class AnimeController extends BaseController
  19. {
  20. use ApiResponse;
  21. protected $AnimeService;
  22. protected $AIImageGenerationService;
  23. protected $AIVideoGenerationService;
  24. public function __construct(
  25. AnimeService $AnimeService,
  26. AIImageGenerationService $AIImageGenerationService,
  27. AIVideoGenerationService $AIVideoGenerationService
  28. ) {
  29. $this->AnimeService = $AnimeService;
  30. $this->AIImageGenerationService = $AIImageGenerationService;
  31. $this->AIVideoGenerationService = $AIVideoGenerationService;
  32. }
  33. // 文字模型
  34. public function textModel() {
  35. $query = DB::table('mp_text_models')->where('is_enabled', 1);
  36. // 支持 model 搜索
  37. if ($model = request('model')) {
  38. $query->where('model', 'like', "%{$model}%");
  39. }
  40. // 支持 name 搜索
  41. if ($name = request('name')) {
  42. $query->where('name', 'like', "%{$name}%");
  43. }
  44. $models = $query->select('model', 'name')->get()->map(function ($value) {
  45. return (array)$value;
  46. })->toArray();
  47. return $this->success($models);
  48. }
  49. // 图片模型
  50. public function imageModel() {
  51. $query = DB::table('mp_image_models')->where('is_enabled', 1);
  52. // 支持 model 搜索
  53. if ($model = request('model')) {
  54. $query->where('model', 'like', "%{$model}%");
  55. }
  56. // 支持 name 搜索
  57. if ($name = request('name')) {
  58. $query->where('name', 'like', "%{$name}%");
  59. }
  60. $models = $query->select('model', 'name')->get()->map(function ($value) {
  61. return (array)$value;
  62. })->toArray();
  63. return $this->success($models);
  64. }
  65. // 视频模型
  66. public function videoModel() {
  67. $query = DB::table('mp_video_models')->where('is_enabled', 1);
  68. // 支持 model 搜索
  69. if ($model = request('model')) {
  70. $query->where('model', 'like', "%{$model}%");
  71. }
  72. // 支持 name 搜索
  73. if ($name = request('name')) {
  74. $query->where('name', 'like', "%{$name}%");
  75. }
  76. $models = $query->select('model', 'name')->get()->map(function ($value) {
  77. return (array)$value;
  78. })->toArray();
  79. return $this->success($models);
  80. }
  81. public function artStyleList()
  82. {
  83. $result = [
  84. [
  85. 'art_style' => '唯美真人风格',
  86. 'pic_url' => "http://zw-ai.oss-cn-hangzhou.aliyuncs.com/mp_audio/art_styles/%E5%94%AF%E7%BE%8E%E7%9C%9F%E4%BA%BA.jpg"
  87. ],
  88. [
  89. 'art_style' => '真人古风风格',
  90. 'pic_url' => "http://zw-ai.oss-cn-hangzhou.aliyuncs.com/mp_audio/art_styles/%E7%9C%9F%E4%BA%BA%E5%8F%A4%E9%A3%8E.jpg"
  91. ],
  92. [
  93. 'art_style' => '日系动漫风格',
  94. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/日系动漫风格.jpg"
  95. ],
  96. [
  97. 'art_style' => '国漫风格',
  98. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/国漫风格.jpg"
  99. ],
  100. [
  101. 'art_style' => 'Q版卡通风格',
  102. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/Q版卡通风格.jpg"
  103. ],
  104. [
  105. 'art_style' => '简约扁平风格',
  106. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/简约扁平风格.jpg"
  107. ],
  108. [
  109. 'art_style' => '古风仙侠风格',
  110. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/古风仙侠风格.jpg"
  111. ],
  112. [
  113. 'art_style' => '武侠风格',
  114. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/武侠风格.jpg"
  115. ],
  116. [
  117. 'art_style' => '新中式水墨风格',
  118. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/新中式水墨风格.jpg"
  119. ],
  120. [
  121. 'art_style' => '写实插画风格',
  122. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/写实插画风格.jpg"
  123. ],
  124. [
  125. 'art_style' => '3D卡通风格',
  126. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/3D卡通风格.jpg"
  127. ],
  128. [
  129. 'art_style' => '条漫风格',
  130. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/条漫风格.jpg"
  131. ],
  132. [
  133. 'art_style' => '赛博朋克风格',
  134. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/赛博朋克风格.jpg"
  135. ],
  136. [
  137. 'art_style' => '暗黑悬疑风格',
  138. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/暗黑悬疑风格.jpg"
  139. ],
  140. [
  141. 'art_style' => '治愈清新风格',
  142. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/治愈清新风格.jpg"
  143. ],
  144. ];
  145. return $this->success($result);
  146. }
  147. // 新建动漫
  148. public function createAnime(Request $request) {
  149. $data = $request->all();
  150. $result = $this->AnimeService->createAnime($data);
  151. return $this->success(['anime_id' => $result]);
  152. }
  153. // 编辑动漫
  154. public function editAnime(Request $request) {
  155. $data = $request->all();
  156. $result = $this->AnimeService->editAnime($data);
  157. return $this->success(['success'=>$result ? 1 : 0]);
  158. }
  159. // 删除动漫
  160. public function delAnime(Request $request) {
  161. $data = $request->all();
  162. $result = $this->AnimeService->delAnime($data);
  163. return $this->success(['success'=>$result ? 1 : 0]);
  164. }
  165. // 批量生成主体图片
  166. public function batchSetRoleImg(Request $request) {
  167. // 忽略所有超时限制
  168. set_time_limit(0);
  169. ini_set('max_execution_time', '0');
  170. $data = $request->all();
  171. $result = $this->AnimeService->batchSetRoleImg($data);
  172. return $this->success($result);
  173. }
  174. // 批量生成场景图片
  175. public function batchSetSceneImg(Request $request) {
  176. // 忽略所有超时限制
  177. set_time_limit(0);
  178. ini_set('max_execution_time', '0');
  179. $data = $request->all();
  180. $result = $this->AnimeService->batchSetSceneImg($data);
  181. return $this->success($result);
  182. }
  183. // 修改分集主体列表
  184. public function changeEpisodeRoles(Request $request) {
  185. $data = $request->all();
  186. $result = $this->AnimeService->changeEpisodeRoles($data);
  187. return $this->success(['success'=>$result ? 1 : 0]);
  188. }
  189. // 修改分集场景列表
  190. public function changeEpisodeScenes(Request $request) {
  191. $data = $request->all();
  192. $result = $this->AnimeService->changeEpisodeScenes($data);
  193. return $this->success(['success'=>$result ? 1 : 0]);
  194. }
  195. // 编辑分镜剧本
  196. public function editSegment(Request $request) {
  197. $data = $request->all();
  198. $result = $this->AnimeService->editSegment($data);
  199. return $this->success(['success'=>$result ? 1 : 0]);
  200. }
  201. // 动漫对话列表
  202. public function chatList(Request $request) {
  203. $data = $request->all();
  204. $result = $this->AnimeService->chatList($data);
  205. return $this->success($result, [new AnimeTransformer(), 'newBuildChatList']);
  206. }
  207. // 动漫对话历史记录
  208. public function chatHistory(Request $request) {
  209. $data = $request->all();
  210. $result = $this->AnimeService->chatHistory($data);
  211. return $this->success($result);
  212. }
  213. // 动漫大纲
  214. public function animeDetail(Request $request) {
  215. $data = $request->all();
  216. $result = $this->AnimeService->animeDetail($data);
  217. return $this->success($result);
  218. }
  219. // 动漫剧集
  220. public function episodeInfo(Request $request) {
  221. $data = $request->all();
  222. $result = $this->AnimeService->episodeInfo($data);
  223. return $this->success($result);
  224. }
  225. // 动漫剧集(全能模式)
  226. public function episodeInfoForAce(Request $request) {
  227. $data = $request->all();
  228. $result = $this->AnimeService->episodeInfoForAce($data);
  229. return $this->success($result);
  230. }
  231. // 分镜信息
  232. public function segmentInfo(Request $request) {
  233. $data = $request->all();
  234. $result = $this->AnimeService->segmentInfo($data);
  235. return $this->success($result);
  236. }
  237. // 复制剧集副本
  238. public function copyEpisodeVersion(Request $request) {
  239. $data = $request->all();
  240. $result = $this->AnimeService->copyEpisodeVersion($data);
  241. return $this->success($result);
  242. }
  243. // 剧集副本列表
  244. public function episodeVersions(Request $request) {
  245. $data = $request->all();
  246. $result = $this->AnimeService->episodeVersions($data);
  247. return $this->success($result);
  248. }
  249. // 绑定剧集副本
  250. public function bindEpisodeVersion(Request $request) {
  251. $data = $request->all();
  252. $result = $this->AnimeService->bindEpisodeVersion($data);
  253. return $this->success(['success' => $result ? 1 : 0]);
  254. }
  255. // 对话改图
  256. public function chatChangeImg(Request $request) {
  257. $data = $request->all();
  258. $result = $this->AnimeService->chatChangeImg($data);
  259. return $this->success(['img_url' => $result]);
  260. }
  261. public function segmentChatHistory(Request $request) {
  262. $data = $request->all();
  263. $result = $this->AnimeService->segmentChatHistory($data);
  264. return $this->success($result);
  265. }
  266. // 一键生成分镜
  267. public function batchSetSegmentPics(Request $request) {
  268. // 忽略所有超时限制
  269. set_time_limit(0);
  270. ini_set('max_execution_time', '0');
  271. $data = $request->all();
  272. $result = $this->AnimeService->batchSetSegmentPics($data);
  273. return $this->success($result);
  274. }
  275. // 重新生成分镜
  276. public function reGenerateSegment(Request $request) {
  277. // 忽略所有超时限制
  278. set_time_limit(0);
  279. ini_set('max_execution_time', '0');
  280. $data = $request->all();
  281. $result = $this->AnimeService->reGenerateSegment($data);
  282. return $this->success(['img_url'=>$result]);
  283. }
  284. // 添加分镜
  285. public function addSegment(Request $request) {
  286. // 忽略所有超时限制
  287. set_time_limit(0);
  288. ini_set('max_execution_time', '0');
  289. $data = $request->all();
  290. $result = $this->AnimeService->addSegment($data);
  291. return $this->success($result);
  292. }
  293. // 复制分镜
  294. public function copySegment(Request $request) {
  295. $data = $request->all();
  296. $result = $this->AnimeService->copySegment($data);
  297. return $this->success($result);
  298. }
  299. // 移动分镜
  300. public function moveSegment(Request $request) {
  301. $data = $request->all();
  302. $result = $this->AnimeService->moveSegment($data);
  303. return $this->success(['success'=>$result ? 1: 0]);
  304. }
  305. // 删除分镜
  306. public function delSegment(Request $request) {
  307. $data = $request->all();
  308. $result = $this->AnimeService->delSegment($data);
  309. return $this->success(['success'=>$result ? 1: 0]);
  310. }
  311. public function applySegment(Request $request) {
  312. $data = $request->all();
  313. $result = $this->AnimeService->applySegment($data);
  314. return $this->success(['success'=>$result ? 1: 0]);
  315. }
  316. // 添加片段
  317. public function addAct(Request $request) {
  318. // 忽略所有超时限制
  319. set_time_limit(0);
  320. ini_set('max_execution_time', '0');
  321. $data = $request->all();
  322. $result = $this->AnimeService->addAct($data);
  323. return $this->success($result);
  324. }
  325. // 编辑片段
  326. public function editAct(Request $request) {
  327. $data = $request->all();
  328. $result = $this->AnimeService->editAct($data);
  329. return $this->success(['success'=>$result ? 1 : 0]);
  330. }
  331. // 复制片段
  332. public function copyAct(Request $request) {
  333. $data = $request->all();
  334. $result = $this->AnimeService->copyAct($data);
  335. return $this->success($result);
  336. }
  337. // 移动片段
  338. public function moveAct(Request $request) {
  339. $data = $request->all();
  340. $result = $this->AnimeService->moveAct($data);
  341. return $this->success(['success'=>$result ? 1: 0]);
  342. }
  343. // 删除片段
  344. public function delAct(Request $request) {
  345. $data = $request->all();
  346. $result = $this->AnimeService->delAct($data);
  347. return $this->success(['success'=>$result ? 1: 0]);
  348. }
  349. // 应用片段
  350. public function applyAct(Request $request) {
  351. $data = $request->all();
  352. $result = $this->AnimeService->applyAct($data);
  353. return $this->success(['success'=>$result ? 1: 0]);
  354. }
  355. // 片段对话历史记录
  356. public function actChatHistory(Request $request) {
  357. $data = $request->all();
  358. $result = $this->AnimeService->actChatHistory($data);
  359. return $this->success($result);
  360. }
  361. // 分镜历史图片|视频
  362. public function segmentHistory(Request $request) {
  363. $data = $request->all();
  364. $result = $this->AnimeService->segmentHistory($data);
  365. return $this->success($result);
  366. }
  367. public function createSegmentVideoTask(Request $request) {
  368. $uid = Site::getUid();
  369. // 忽略所有超时限制
  370. set_time_limit(0);
  371. ini_set('max_execution_time', '0');
  372. $data = $request->all();
  373. // 验证参数
  374. $validator = Validator::make($data, [
  375. 'segment_id' => 'required|string',
  376. 'tail_frame' => 'nullable|string|max:500',
  377. ], [
  378. 'segment_id.required' => '分镜ID不能为空',
  379. 'tail_frame.max' => '尾帧描述不能超过500个字符',
  380. ]);
  381. if ($validator->fails()) {
  382. Utils::throwError('1002:' . $validator->errors()->first());
  383. }
  384. // 创建视频生成任务
  385. $result = $this->AnimeService->createSegmentVideoTask($data);
  386. $taskId = $result['task_id'];
  387. // 设置 SSE 响应头
  388. return response()->stream(function () use ($taskId, $result, $uid) {
  389. // 设置 SSE 响应头
  390. echo "data: " . json_encode([
  391. 'type' => 'init',
  392. 'data' => $result
  393. ]) . "\n\n";
  394. ob_flush();
  395. flush();
  396. $startTime = time();
  397. $maxDuration = 300; // 5分钟超时
  398. $checkInterval = 5; // 每5秒检查一次
  399. while (time() - $startTime < $maxDuration) {
  400. try {
  401. // 查询任务状态
  402. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  403. if (!$task) {
  404. echo "data: " . json_encode([
  405. 'type' => 'error',
  406. 'message' => '任务不存在'
  407. ]) . "\n\n";
  408. ob_flush();
  409. flush();
  410. break;
  411. }
  412. // 如果任务还在处理中,查询最新状态
  413. if ($task->status === 'processing') {
  414. // 根据任务类型查询不同的状态
  415. if ($task->api_type === 'jimeng') {
  416. $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
  417. } elseif ($task->api_type === 'keling') {
  418. $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
  419. } elseif ($task->api_type === 'zzengine') {
  420. $statusResult = $this->AIVideoGenerationService->queryUnifiedApiTaskStatus($task);
  421. } else {
  422. $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
  423. }
  424. if (isset($statusResult['status'])) {
  425. // 更新任务状态
  426. $task->update([
  427. 'status' => $statusResult['status'],
  428. 'result_url' => $statusResult['result_url'] ?? null,
  429. 'compressed_url' => $statusResult['compressed_url'] ?? null,
  430. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  431. 'error_message' => $statusResult['error_message'] ?? null,
  432. 'completed_at' => in_array($statusResult['status'], [
  433. 'success',
  434. 'failed'
  435. ]) ? now() : null
  436. ]);
  437. // 如果任务成功,更新分镜表
  438. if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
  439. try {
  440. DB::beginTransaction();
  441. $now = date('Y-m-d H:i:s');
  442. // 获取分镜ID
  443. $segment = DB::table('mp_episode_segments')
  444. ->where('video_task_id', $taskId)
  445. ->first();
  446. if (!$segment) {
  447. throw new \Exception('未找到对应的分镜记录');
  448. }
  449. $segmentId = $segment->segment_id;
  450. $anime_id = $segment->anime_id;
  451. $episode_number = $segment->episode_number;
  452. $tail_frame = $segment->tail_frame;
  453. // 更新分镜表
  454. $segmentUpdateData = [
  455. 'origin_video_url' => $statusResult['result_url'],
  456. 'video_task_status' => '已完成',
  457. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  458. 'current_type' => 2,
  459. 'updated_at' => $now
  460. ];
  461. $compressed_video_url = compressVideo($statusResult['result_url']);
  462. $segmentUpdateData['video_url'] = $compressed_video_url ?: $statusResult['result_url'];
  463. // 只有当video_duration存在且大于0时才更新
  464. if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
  465. $segmentUpdateData['video_duration'] = $statusResult['video_duration'];
  466. $segmentUpdateData['video_time_point_start'] = 0;
  467. // $segmentUpdateData['video_time_point_end'] = $statusResult['video_duration'];
  468. $segmentUpdateData['video_time_point_end'] = $segment->audio_duration ?? 0;
  469. }
  470. $updateResult = DB::table('mp_episode_segments')
  471. ->where('segment_id', $segmentId)
  472. ->update($segmentUpdateData);
  473. if (!$updateResult) {
  474. Utils::throwError('20003:更新分镜表失败');
  475. }
  476. // 更新分镜视频成功后新增对话记录
  477. // 保存对话记录
  478. $records = [
  479. [
  480. 'uid' => $uid,
  481. 'anime_id' => $anime_id,
  482. 'sequence' => $episode_number,
  483. 'role' => 'user',
  484. 'content' => '图片转视频',
  485. 'segment_id' => $segmentId,
  486. 'video_url' => '',
  487. 'created_at' => $now,
  488. 'updated_at' => $now
  489. ],
  490. [
  491. 'uid' => $uid,
  492. 'anime_id' => $anime_id,
  493. 'sequence' => $episode_number,
  494. 'role' => 'assistant',
  495. 'content' => $tail_frame,
  496. 'segment_id' => $segmentId,
  497. 'video_url' => $statusResult['result_url'],
  498. 'created_at' => $now,
  499. 'updated_at' => $now
  500. ]
  501. ];
  502. DB::table('mp_anime_records')->insert($records);
  503. DB::commit();
  504. } catch (\Exception $e) {
  505. DB::rollBack();
  506. $logData = [
  507. 'task_id' => $taskId,
  508. 'error' => $e->getMessage()
  509. ];
  510. dLog('anime')->error('视频任务处理失败', $logData);
  511. logDB('anime', 'error', '视频任务处理失败', $logData);
  512. }
  513. } elseif ($statusResult['status'] === 'failed') {
  514. DB::table('mp_episode_segments')
  515. ->where('video_task_id', $taskId)
  516. ->update([
  517. 'video_task_status' => '失败',
  518. 'updated_at' => date('Y-m-d H:i:s')
  519. ]);
  520. }
  521. }
  522. }
  523. // 发送当前状态
  524. echo "data: " . json_encode([
  525. 'type' => 'update',
  526. 'data' => [
  527. 'task_id' => $task->id,
  528. 'status' => $task->status,
  529. 'result_url' => $task->result_url,
  530. 'error_message' => $task->error_message,
  531. 'elapsed_time' => time() - $startTime
  532. ]
  533. ]) . "\n\n";
  534. ob_flush();
  535. flush();
  536. // 如果任务完成(成功或失败),结束连接
  537. if (in_array($task->status, [
  538. 'success',
  539. 'failed'
  540. ])) {
  541. echo "data: " . json_encode([
  542. 'type' => 'completed',
  543. 'data' => [
  544. 'task_id' => $task->id,
  545. 'status' => $task->status,
  546. 'video_url' => $task->compressed_url ?: $task->result_url,
  547. 'origin_video_url' => $task->result_url,
  548. 'last_frame_url' => $task->last_frame_url,
  549. 'error_message' => $task->error_message
  550. ]
  551. ]) . "\n\n";
  552. ob_flush();
  553. flush();
  554. break;
  555. }
  556. sleep($checkInterval);
  557. } catch (\Exception $e) {
  558. echo "data: " . json_encode([
  559. 'type' => 'error',
  560. 'message' => '查询任务状态失败: ' . $e->getMessage()
  561. ]) . "\n\n";
  562. ob_flush();
  563. flush();
  564. sleep($checkInterval);
  565. }
  566. }
  567. // 超时处理
  568. if (time() - $startTime >= $maxDuration) {
  569. echo "data: " . json_encode([
  570. 'type' => 'time_out',
  571. 'message' => '任务执行超时,请稍后查询任务状态',
  572. 'data' => [
  573. 'task_id' => $taskId
  574. ]
  575. ]) . "\n\n";
  576. ob_flush();
  577. flush();
  578. }
  579. }, 200, [
  580. 'Content-Type' => 'text/event-stream',
  581. 'Cache-Control' => 'no-cache',
  582. 'Connection' => 'keep-alive',
  583. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  584. ]);
  585. }
  586. /**
  587. * 批量生成分镜视频
  588. */
  589. public function batchSetSegmentVideos(Request $request) {
  590. // 忽略所有超时限制
  591. set_time_limit(0);
  592. ini_set('max_execution_time', '0');
  593. $data = $request->all();
  594. // 验证参数
  595. $validator = Validator::make($data, [
  596. 'anime_id' => 'required|string',
  597. 'episode_id' => 'required|integer',
  598. ], [
  599. 'anime_id.required' => '动漫对话ID不能为空',
  600. 'episode_id.required' => '剧集ID不能为空',
  601. 'episode_id.integer' => '剧集ID必须是整数',
  602. ]);
  603. if ($validator->fails()) {
  604. Utils::throwError('1002:' . $validator->errors()->first());
  605. }
  606. $animeId = $data['anime_id'];
  607. $episodeId = $data['episode_id'];
  608. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->where('anime_id', $animeId)->first();
  609. if (!$episode) Utils::throwError('20003:分集不存在');
  610. $episodeNumber = $episode->episode_number;
  611. $ratio = !empty($episode->ratio) ? $episode->ratio : '9:16';
  612. $generate_audio = getProp($data, 'generate_audio', 0);
  613. // 处理视频模型(在循环外统一处理)
  614. $model = getProp($data, 'model');
  615. if (!$model) {
  616. // 用户没有输入,从episode表获取
  617. $model = getProp($episode, 'video_model');
  618. if (!$model) {
  619. // episode表也没有,使用默认值
  620. $model = 'doubao-seedance-1-5-pro-251215';
  621. }
  622. }
  623. // 验证模型是否在可用模型表中
  624. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  625. $model = 'doubao-seedance-1-5-pro-251215';
  626. }
  627. // 获取所有分镜信息
  628. $segments = DB::table('mp_episode_segments')
  629. ->where('anime_id', $animeId)
  630. ->where('episode_id', $episodeId)
  631. ->whereNotIn('video_task_status', ['已完成', '生成中'])
  632. ->orderBy('segment_number')
  633. ->get();
  634. if ($segments->isEmpty()) {
  635. Utils::throwError('20003:未找到分镜数据');
  636. }
  637. // 批量创建视频任务
  638. $taskIds = [];
  639. $segmentTasks = [];
  640. foreach ($segments as $segment) {
  641. try {
  642. // 检查视频任务正在生成中或当前状态为视频
  643. if ($segment->video_task_status === '生成中' || (int)$segment->current_type === 2) {
  644. continue;
  645. }
  646. // 获取分镜内容
  647. $segmentContent = $segment->segment_content ?: '';
  648. $tailFrame = $segment->tail_frame ?: '';
  649. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  650. $hasDialogue = false;
  651. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  652. $dialogue = trim($dialogueMatch[1]);
  653. // 如果台词不为空且不是"无"
  654. if (!empty($dialogue) && $dialogue !== '无') {
  655. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  656. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  657. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  658. $hasDialogue = true;
  659. }
  660. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  661. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  662. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  663. if (!preg_match('/^[“]/', $dialogue)) {
  664. $dialogue = '“' . $dialogue;
  665. }
  666. if (!preg_match('/[”]$/', $dialogue)) {
  667. $dialogue .= '”';
  668. }
  669. // 将修改后的台词替换回 $segmentContent
  670. $originalDialogue = $dialogueMatch[1];
  671. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  672. }
  673. }
  674. // 检查 $segmentContent 中是否已有尾帧描述
  675. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  676. // 确定最终使用的尾帧描述(优先级:segmentContent自带 > 分镜表字段)
  677. $finalTailFrame = '';
  678. if ($contentHasTailFrame) {
  679. // segmentContent 中有尾帧描述,使用它
  680. $finalTailFrame = trim($contentTailFrameMatch[1]);
  681. } else {
  682. // segmentContent 中没有,使用分镜表中的尾帧描述
  683. $finalTailFrame = $tailFrame;
  684. }
  685. // 构建完整的提示词
  686. $fullPrompt = $segmentContent;
  687. if ($finalTailFrame && !$contentHasTailFrame) {
  688. // 只有当 segmentContent 中没有尾帧描述时才追加
  689. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  690. }
  691. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  692. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  693. $fullPrompt = trim($fullPrompt);
  694. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  695. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  696. // 智能选择视频时长
  697. // $videoDuration = $this->AnimeService->calculateOptimalVideoDuration($segmentContent, $tailFrame);
  698. $videoDuration = -1;
  699. // 构建视频生成参数
  700. $videoParams = [
  701. 'model' => $model,
  702. 'alias_segment_id' => $segment->segment_id,
  703. 'prompt' => $fullPrompt,
  704. 'video_duration' => $videoDuration,
  705. 'video_resolution' => '720P',
  706. 'seed' => -1,
  707. 'ratio' => $ratio,
  708. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  709. 'draft' => false,
  710. 'watermark' => false,
  711. 'camera_fixed' => false,
  712. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  713. ];
  714. // 如果分镜有图片,作为首帧
  715. $hasImage = !empty($segment->img_url);
  716. $hasVideo = !empty($segment->video_url);
  717. if ($hasImage) {
  718. $videoParams['first_frame_url'] = $segment->img_url;
  719. }
  720. // 构建content数组
  721. $videoParams['content'] = [
  722. [
  723. 'type' => 'text',
  724. 'text' => $videoParams['prompt'],
  725. ]
  726. ];
  727. // 如果有首帧图片,添加到content中
  728. if ($hasImage) {
  729. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  730. $videoParams['content'][] = [
  731. 'type' => 'image_url',
  732. 'image_url' => [
  733. 'url' => $videoParams['first_frame_url'],
  734. ],
  735. 'role' => 'reference_image',
  736. ];
  737. }else {
  738. $videoParams['content'][] = [
  739. 'type' => 'image_url',
  740. 'image_url' => [
  741. 'url' => $videoParams['first_frame_url'],
  742. ],
  743. 'role' => 'first_frame',
  744. ];
  745. }
  746. }
  747. // 获取配音音频URL和时长
  748. $audioUrl = $segment->audio_url ?? '';
  749. $audioDuration = $segment->audio_duration ?? 0;
  750. // 音频传入的前提:必须有至少一张图片或一个视频
  751. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  752. // 根据模型选择不同的视频生成方法
  753. if (strpos($model, 'jimeng') !== false) {
  754. // 即梦模型参数调整
  755. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  756. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 即梦使用aspect_ratio
  757. unset($videoParams['ratio']);
  758. unset($videoParams['content']); // 即梦不使用content格式
  759. $task = $this->AIVideoGenerationService->createJimengTask($videoParams);
  760. } elseif (strpos($model, 'kling') !== false) {
  761. // Keling模型参数调整
  762. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  763. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  764. unset($videoParams['ratio']);
  765. unset($videoParams['content']); // Keling不使用content格式
  766. $task = $this->AIVideoGenerationService->createKelingOmniTask($videoParams);
  767. } elseif (strpos($model, 'zhizhen') !== false) {
  768. // 智帧20等新模型使用统一API
  769. // 构建统一API参数
  770. $unifiedParams = [
  771. 'model_code' => $model,
  772. 'alias_segment_id' => $segment->segment_id,
  773. 'prompt' => trim($fullPrompt),
  774. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  775. 'video_resolution' => strtolower($videoParams['video_resolution']),
  776. 'video_ratio' => $ratio,
  777. 'seed' => -1,
  778. ];
  779. // 构建parameters参数
  780. $parameters = [
  781. 'seconds' => $unifiedParams['video_duration'],
  782. 'resolution' => $unifiedParams['video_resolution'],
  783. 'ratio' => $ratio,
  784. 'video_mode' => 'multi_image',
  785. 'mode' => 'multi_image',
  786. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  787. ];
  788. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  789. if ($hasImage) {
  790. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  791. // 只有在有图片的情况下才能添加参考音频
  792. if ($audioUrl) {
  793. $parameters['reference_audios'] = [$audioUrl];
  794. }
  795. } else {
  796. // 没有图片时,记录错误并跳过
  797. $logData = [
  798. 'segment_id' => $segment->segment_id,
  799. 'model' => $model,
  800. 'error' => '智帧20模型需要提供首帧图片'
  801. ];
  802. dLog('anime')->error('智帧20模型缺少首帧图片', $logData);
  803. logDB('anime', 'error', '智帧20模型缺少首帧图片', $logData);
  804. continue;
  805. }
  806. $unifiedParams['parameters'] = $parameters;
  807. // 调用统一API创建任务
  808. $task = $this->AIVideoGenerationService->createUnifiedApiTask($unifiedParams);
  809. } else {
  810. // Seedance模型(默认)
  811. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  812. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  813. // 添加配音音频到content中
  814. $videoParams['content'][] = [
  815. 'type' => 'audio_url',
  816. 'audio_url' => [
  817. 'url' => $audioUrl,
  818. ],
  819. 'role' => 'reference_audio',
  820. ];
  821. // 优化提示词,增加音频相关描述
  822. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  823. $videoParams['prompt'] = $audioPrompt;
  824. $videoParams['content'][0]['text'] = $audioPrompt;
  825. } else if ($audioDuration) {
  826. // 有音频时长则需将视频时长设置为比音频时长更长的整数
  827. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  828. }
  829. $task = $this->AIVideoGenerationService->createSeedanceTask($videoParams);
  830. }
  831. $taskIds[] = $task->id;
  832. // 更新分镜表的视频任务信息
  833. DB::table('mp_episode_segments')
  834. ->where('segment_id', $segment->segment_id)
  835. ->update([
  836. 'video_task_id' => $task->id,
  837. 'video_task_status' => '生成中',
  838. 'updated_at' => date('Y-m-d H:i:s')
  839. ]);
  840. $segmentTasks[] = [
  841. 'segment_id' => $segment->segment_id,
  842. 'task_id' => $task->id,
  843. 'segment_number' => $segment->segment_number,
  844. 'tail_frame' => $segment->tail_frame,
  845. 'audio_duration' => $segment->audio_duration,
  846. ];
  847. } catch (\Exception $e) {
  848. $logData = [
  849. 'segment_id' => $segment->segment_id,
  850. 'anime_id' => $animeId,
  851. 'error' => $e->getMessage(),
  852. ];
  853. dLog('anime')->error('创建分镜视频任务失败', $logData);
  854. logDB('anime', 'error', '创建分镜视频任务失败', $logData);
  855. continue;
  856. }
  857. }
  858. if (empty($taskIds)) {
  859. Utils::throwError('20003:没有需要生成视频的分镜');
  860. }
  861. // 保存模型到episode表
  862. DB::table('mp_anime_episodes')->where('id', $episodeId)->update([
  863. 'video_model' => $model,
  864. 'updated_at' => date('Y-m-d H:i:s')
  865. ]);
  866. // 记录开始时间(包含创建任务的时间)
  867. $startTime = time();
  868. $maxDuration = 1800; // 30分钟超时
  869. $uid = Site::getUid();
  870. // 设置 SSE 响应头并开始长连接
  871. return response()->stream(function () use ($taskIds, $segmentTasks, $animeId, $episodeNumber, $episodeId, $startTime, $maxDuration, $uid) {
  872. $checkInterval = 10; // 每10秒检查一次
  873. // 初始化任务数组
  874. $totalTasks = $taskIds; // 所有任务ID
  875. $completeTasks = []; // 已完成的任务ID(包含失败)
  876. $successTasks = []; // 成功的任务ID
  877. // 发送初始任务创建信息
  878. echo "data: " . json_encode([
  879. 'type' => 'init',
  880. 'total_tasks_count' => count($totalTasks),
  881. 'completed_tasks_count' => count($completeTasks),
  882. 'success_tasks_count' => count($successTasks)
  883. ]) . "\n\n";
  884. ob_flush();
  885. flush();
  886. while (time() - $startTime < $maxDuration) {
  887. try {
  888. $hasUpdate = false; // 标记是否有更新
  889. // 获取所有任务的最新状态
  890. foreach ($totalTasks as $taskId) {
  891. // 如果任务已经在完成列表中,跳过
  892. if (in_array($taskId, $completeTasks)) {
  893. continue;
  894. }
  895. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  896. if (!$task) {
  897. continue;
  898. }
  899. // 如果任务还在处理中,查询最新状态
  900. if ($task->status === 'processing') {
  901. // 根据任务类型查询不同的状态
  902. if ($task->api_type === 'jimeng') {
  903. $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
  904. } elseif ($task->api_type === 'keling') {
  905. $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
  906. } elseif ($task->api_type === 'zzengine') {
  907. $statusResult = $this->AIVideoGenerationService->queryUnifiedApiTaskStatus($task);
  908. } else {
  909. $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
  910. }
  911. if (isset($statusResult['status'])) {
  912. // 更新任务状态
  913. $task->update([
  914. 'status' => $statusResult['status'],
  915. 'result_json' => $statusResult['result_json'] ?? [],
  916. 'result_url' => $statusResult['result_url'] ?? null,
  917. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  918. 'error_message' => $statusResult['error_message'] ?? null,
  919. 'completed_at' => in_array($statusResult['status'], [
  920. 'success',
  921. 'failed'
  922. ]) ? now() : null
  923. ]);
  924. // 如果任务成功,更新分镜表
  925. if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
  926. try {
  927. DB::beginTransaction();
  928. $now = date('Y-m-d H:i:s');
  929. // 获取分镜ID
  930. $segmentId = null;
  931. foreach ($segmentTasks as $segmentTask) {
  932. if ($segmentTask['task_id'] == $taskId) {
  933. $segmentId = $segmentTask['segment_id'];
  934. $tail_frame = $segmentTask['tail_frame'];
  935. $audio_duration = $segmentTask['audio_duration'];
  936. break;
  937. }
  938. }
  939. if ($segmentId) {
  940. // 更新分镜表
  941. $segmentUpdateData = [
  942. 'origin_video_url' => $statusResult['result_url'],
  943. 'video_task_status' => '已完成',
  944. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  945. 'current_type' => 2,
  946. 'updated_at' => $now
  947. ];
  948. $compressed_video_url = compressVideo($statusResult['result_url']);
  949. $segmentUpdateData['video_url'] = $compressed_video_url ?: $statusResult['result_url'];
  950. // 只有当video_duration存在且大于0时才更新
  951. if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
  952. $segmentUpdateData['video_duration'] = $statusResult['video_duration'];
  953. $segmentUpdateData['video_time_point_start'] = 0;
  954. // $segmentUpdateData['video_time_point_end'] = $statusResult['video_duration'];
  955. $segmentUpdateData['video_time_point_end'] = $audio_duration ?? 0;
  956. }
  957. $updateResult = DB::table('mp_episode_segments')
  958. ->where('segment_id', $segmentId)
  959. ->update($segmentUpdateData);
  960. if ($updateResult) {
  961. // 更新分镜视频成功后新增对话记录
  962. $records = [
  963. [
  964. 'uid' => $uid,
  965. 'anime_id' => $animeId,
  966. 'sequence' => $episodeNumber,
  967. 'role' => 'user',
  968. 'content' => '图片转视频',
  969. 'segment_id' => $segmentId,
  970. 'video_url' => '',
  971. 'created_at' => $now,
  972. 'updated_at' => $now
  973. ],
  974. [
  975. 'uid' => $uid,
  976. 'anime_id' => $animeId,
  977. 'sequence' => $episodeNumber,
  978. 'role' => 'assistant',
  979. 'content' => $tail_frame ?? '',
  980. 'segment_id' => $segmentId,
  981. 'video_url' => $statusResult['result_url'],
  982. 'created_at' => $now,
  983. 'updated_at' => $now
  984. ]
  985. ];
  986. DB::table('mp_anime_records')->insert($records);
  987. }
  988. }
  989. DB::commit();
  990. } catch (\Exception $e) {
  991. DB::rollBack();
  992. $logData = [
  993. 'task_id' => $taskId,
  994. 'error' => $e->getMessage()
  995. ];
  996. dLog('anime')->error('视频任务处理失败', $logData);
  997. logDB('anime', 'error', '视频任务处理失败', $logData);
  998. }
  999. } elseif ($statusResult['status'] === 'failed') {
  1000. // 获取分镜ID并更新失败状态
  1001. foreach ($segmentTasks as $segmentTask) {
  1002. if ($segmentTask['task_id'] == $taskId) {
  1003. DB::table('mp_episode_segments')
  1004. ->where('segment_id', $segmentTask['segment_id'])
  1005. ->update([
  1006. 'video_task_status' => '失败',
  1007. 'updated_at' => date('Y-m-d H:i:s')
  1008. ]);
  1009. break;
  1010. }
  1011. }
  1012. }
  1013. }
  1014. }
  1015. // 检查任务是否完成(成功或失败)
  1016. if (in_array($task->status, ['success', 'failed'])) {
  1017. $completeTasks[] = $taskId;
  1018. $hasUpdate = true;
  1019. if ($task->status === 'success') {
  1020. $successTasks[] = $taskId;
  1021. }
  1022. }
  1023. }
  1024. // 如果有更新,发送update通知
  1025. if ($hasUpdate) {
  1026. echo "data: " . json_encode([
  1027. 'type' => 'update',
  1028. 'total_tasks_count' => count($totalTasks),
  1029. 'completed_tasks_count' => count($completeTasks),
  1030. 'success_tasks_count' => count($successTasks)
  1031. ]) . "\n\n";
  1032. ob_flush();
  1033. flush();
  1034. }
  1035. // 如果所有任务都完成了,结束连接
  1036. if (count($completeTasks) >= count($totalTasks)) {
  1037. // 获取所有成功任务的分镜信息
  1038. $successSegments = [];
  1039. foreach ($successTasks as $taskId) {
  1040. // 通过taskId找到对应的segmentTask
  1041. foreach ($segmentTasks as $segmentTask) {
  1042. if ($segmentTask['task_id'] == $taskId) {
  1043. $segment = DB::table('mp_episode_segments')
  1044. ->where('segment_id', $segmentTask['segment_id'])
  1045. ->select('segment_id', 'video_url')
  1046. ->first();
  1047. if ($segment && !empty($segment->video_url)) {
  1048. $successSegments[] = [
  1049. 'segment_id' => $segment->segment_id,
  1050. 'video_url' => $segment->video_url
  1051. ];
  1052. }
  1053. break;
  1054. }
  1055. }
  1056. }
  1057. echo "data: " . json_encode([
  1058. 'type' => 'completed',
  1059. 'total_tasks_count' => count($totalTasks),
  1060. 'completed_tasks_count' => count($completeTasks),
  1061. 'success_tasks_count' => count($successTasks),
  1062. 'success_segments' => $successSegments
  1063. ]) . "\n\n";
  1064. ob_flush();
  1065. flush();
  1066. break;
  1067. }
  1068. // 检查是否超时
  1069. if (time() - $startTime >= $maxDuration) {
  1070. break;
  1071. }
  1072. sleep($checkInterval);
  1073. } catch (\Exception $e) {
  1074. echo "data: " . json_encode([
  1075. 'type' => 'error',
  1076. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  1077. 'total_tasks_count' => count($totalTasks),
  1078. 'completed_tasks_count' => count($completeTasks),
  1079. 'success_tasks_count' => count($successTasks)
  1080. ]) . "\n\n";
  1081. ob_flush();
  1082. flush();
  1083. // 检查是否超时,如果超时则停止循环
  1084. if (time() - $startTime >= $maxDuration) {
  1085. break;
  1086. }
  1087. sleep($checkInterval);
  1088. }
  1089. }
  1090. // 超时处理
  1091. if (time() - $startTime >= $maxDuration) {
  1092. echo "data: " . json_encode([
  1093. 'type' => 'time_out',
  1094. 'message' => '批量视频生成已超时30分钟,停止状态查询',
  1095. 'total_tasks_count' => count($totalTasks),
  1096. 'completed_tasks_count' => count($completeTasks),
  1097. 'success_tasks_count' => count($successTasks)
  1098. ]) . "\n\n";
  1099. ob_flush();
  1100. flush();
  1101. }
  1102. }, 200, [
  1103. 'Content-Type' => 'text/event-stream',
  1104. 'Cache-Control' => 'no-cache',
  1105. 'Connection' => 'keep-alive',
  1106. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  1107. ]);
  1108. }
  1109. // 应用有声制作参数
  1110. public function applyAudioData(Request $request) {
  1111. $data = $request->all();
  1112. $result = $this->AnimeService->applyAudioData($data);
  1113. return $this->success($result);
  1114. }
  1115. // 获取分集生成图片信息
  1116. public function episodePicsInfo(Request $request) {
  1117. // 忽略所有超时限制
  1118. set_time_limit(0);
  1119. ini_set('max_execution_time', '0');
  1120. $data = $request->all();
  1121. // 获取生成器函数
  1122. $streamGenerator = $this->AnimeService->episodePicsInfo($data);
  1123. // 返回 SSE 响应
  1124. return response()->stream($streamGenerator, 200, [
  1125. 'Content-Type' => 'text/event-stream',
  1126. 'Cache-Control' => 'no-cache',
  1127. 'Connection' => 'keep-alive',
  1128. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  1129. ]);
  1130. }
  1131. public function clipSegmentVideo(Request $request) {
  1132. $data = $request->all();
  1133. $result = $this->AnimeService->clipSegmentVideo($data);
  1134. return $this->success(['success'=>$result ? 1: 0]);
  1135. }
  1136. /**
  1137. * 创建完整视频合成任务
  1138. *
  1139. * @param Request $request
  1140. * @return \Illuminate\Http\JsonResponse
  1141. */
  1142. public function createCompleteVideoTask(Request $request)
  1143. {
  1144. // 忽略所有超时限制
  1145. set_time_limit(0);
  1146. ini_set('max_execution_time', '0');
  1147. $data = $request->all();
  1148. // 验证参数
  1149. $validator = Validator::make($data, [
  1150. 'anime_id' => 'required|string',
  1151. 'episode_id' => 'required|string',
  1152. ], [
  1153. 'anime_id.required' => '请选择动漫',
  1154. 'episode_id.required' => '请选择分集',
  1155. ]);
  1156. if ($validator->fails()) {
  1157. Utils::throwError('1002:' . $validator->errors()->first());
  1158. }
  1159. try {
  1160. $result = $this->AnimeService->createCompleteVideoTask($data);
  1161. return $this->success($result);
  1162. } catch (\Exception $e) {
  1163. $logData = [
  1164. 'anime_id' => $data['anime_id'] ?? '',
  1165. 'episode_id' => $data['episode_id'] ?? '',
  1166. 'error' => $e->getMessage()
  1167. ];
  1168. dLog('anime')->error('创建完整视频合成任务失败', $logData);
  1169. logDB('anime', 'error', '创建完整视频合成任务失败', $logData);
  1170. return $this->error('20003:'.$e->getMessage());
  1171. }
  1172. }
  1173. // 文生图(通用)
  1174. public function generateImg(Request $request) {
  1175. // 忽略所有超时限制
  1176. set_time_limit(0);
  1177. ini_set('max_execution_time', '0');
  1178. $data = $request->all();
  1179. $result = $this->AnimeService->generateImg($data);
  1180. return $this->success($result);
  1181. }
  1182. /**
  1183. * 导出分集的全部图片(下载并打包)
  1184. */
  1185. public function exportEpisodeImages(Request $request) {
  1186. // 忽略所有超时限制
  1187. set_time_limit(0);
  1188. ini_set('max_execution_time', '0');
  1189. ini_set('memory_limit', '512M');
  1190. $data = $request->all();
  1191. // 验证参数
  1192. $validator = Validator::make($data, [
  1193. 'anime_id' => 'required|string',
  1194. 'episode_id' => 'required|string',
  1195. ], [
  1196. 'anime_id.required' => '动漫ID不能为空',
  1197. 'episode_id.required' => '剧集ID不能为空',
  1198. ]);
  1199. if ($validator->fails()) {
  1200. Utils::throwError('1002:' . $validator->errors()->first());
  1201. }
  1202. $animeId = $data['anime_id'];
  1203. $episodeId = $data['episode_id'];
  1204. try {
  1205. // 获取剧集信息
  1206. $episode = DB::table('mp_anime_episodes')
  1207. ->where('anime_id', $animeId)
  1208. ->where('id', $episodeId)
  1209. ->select('episode_number', 'title')
  1210. ->first();
  1211. if (!$episode) {
  1212. Utils::throwError('20003:未找到剧集信息');
  1213. }
  1214. // 获取所有分镜图片和音频
  1215. $segments = DB::table('mp_episode_segments')
  1216. ->where('anime_id', $animeId)
  1217. ->where('episode_id', $episodeId)
  1218. ->whereNotNull('img_url')
  1219. ->where('img_url', '!=', '')
  1220. ->orderBy('segment_number')
  1221. ->select('segment_id', 'segment_number', 'img_url', 'video_url', 'audio_url', 'act_number', 'act_title')
  1222. ->get();
  1223. if ($segments->isEmpty()) {
  1224. Utils::throwError('20003:该剧集暂无图片可导出');
  1225. }
  1226. // 创建临时目录
  1227. $tempDir = storage_path('app/temp/episode_images_' . time() . '_' . mt_rand(1000, 9999));
  1228. if (!file_exists($tempDir)) {
  1229. mkdir($tempDir, 0755, true);
  1230. }
  1231. // 下载图片或视频
  1232. $downloadedFiles = [];
  1233. foreach ($segments as $segment) {
  1234. try {
  1235. // 优先使用video_url,如果没有则使用img_url
  1236. $mediaUrl = !empty($segment->video_url) ? $segment->video_url : $segment->img_url;
  1237. if (empty($mediaUrl)) {
  1238. continue;
  1239. }
  1240. // 获取文件扩展名
  1241. $extension = pathinfo(parse_url($mediaUrl, PHP_URL_PATH), PATHINFO_EXTENSION);
  1242. if (empty($extension)) {
  1243. // 根据URL类型设置默认扩展名
  1244. $extension = !empty($segment->video_url) ? 'mp4' : 'jpg';
  1245. }
  1246. // 构建文件名:分镜序号.扩展名
  1247. $fileName = sprintf(
  1248. '%03d.%s',
  1249. $segment->segment_number,
  1250. $extension
  1251. );
  1252. $filePath = $tempDir . '/' . $fileName;
  1253. // 下载文件(使用file_get_contents,兼容性更好)
  1254. $context = stream_context_create([
  1255. 'http' => [
  1256. 'timeout' => 30,
  1257. 'follow_location' => 1,
  1258. 'ignore_errors' => true
  1259. ],
  1260. 'ssl' => [
  1261. 'verify_peer' => false,
  1262. 'verify_peer_name' => false
  1263. ]
  1264. ]);
  1265. $fileData = @file_get_contents($mediaUrl, false, $context);
  1266. if ($fileData !== false && !empty($fileData)) {
  1267. file_put_contents($filePath, $fileData);
  1268. $downloadedFiles[] = $filePath;
  1269. } else {
  1270. $logData = [
  1271. 'segment_id' => $segment->segment_id,
  1272. 'media_url' => $mediaUrl,
  1273. 'type' => !empty($segment->video_url) ? 'video' : 'image'
  1274. ];
  1275. dLog('anime')->warning('文件下载失败', $logData);
  1276. logDB('anime', 'warning', '文件下载失败', $logData);
  1277. }
  1278. } catch (\Exception $e) {
  1279. $logData = [
  1280. 'segment_id' => $segment->segment_id,
  1281. 'video_url' => $segment->video_url,
  1282. 'img_url' => $segment->img_url,
  1283. 'error' => $e->getMessage()
  1284. ];
  1285. dLog('anime')->error('下载文件异常', $logData);
  1286. logDB('anime', 'error', '下载文件异常', $logData);
  1287. continue;
  1288. }
  1289. }
  1290. if (empty($downloadedFiles)) {
  1291. // 清理临时目录
  1292. if (file_exists($tempDir)) {
  1293. array_map('unlink', glob("$tempDir/*"));
  1294. rmdir($tempDir);
  1295. }
  1296. Utils::throwError('20003:没有成功下载任何图片');
  1297. }
  1298. // 处理音频合成
  1299. $mergedAudioPath = null;
  1300. try {
  1301. // 检查 FFmpeg 是否可用
  1302. exec('which ffmpeg 2>&1', $ffmpegCheck, $ffmpegReturnCode);
  1303. $hasFfmpeg = ($ffmpegReturnCode === 0);
  1304. if ($hasFfmpeg) {
  1305. // 下载所有分镜的音频文件
  1306. $audioFiles = [];
  1307. foreach ($segments as $segment) {
  1308. if (!empty($segment->audio_url)) {
  1309. try {
  1310. $context = stream_context_create([
  1311. 'http' => [
  1312. 'timeout' => 30,
  1313. 'follow_location' => 1,
  1314. 'ignore_errors' => true
  1315. ],
  1316. 'ssl' => [
  1317. 'verify_peer' => false,
  1318. 'verify_peer_name' => false
  1319. ]
  1320. ]);
  1321. $audioData = @file_get_contents($segment->audio_url, false, $context);
  1322. if ($audioData !== false && !empty($audioData)) {
  1323. // 获取音频文件扩展名
  1324. $audioExtension = pathinfo(parse_url($segment->audio_url, PHP_URL_PATH), PATHINFO_EXTENSION);
  1325. if (empty($audioExtension)) {
  1326. $audioExtension = 'wav';
  1327. }
  1328. $audioFileName = sprintf('audio_%03d.%s', $segment->segment_number, $audioExtension);
  1329. $audioFilePath = $tempDir . '/' . $audioFileName;
  1330. file_put_contents($audioFilePath, $audioData);
  1331. $audioFiles[] = $audioFilePath;
  1332. } else {
  1333. $logData = [
  1334. 'segment_id' => $segment->segment_id,
  1335. 'audio_url' => $segment->audio_url
  1336. ];
  1337. dLog('anime')->warning('音频下载失败', $logData);
  1338. logDB('anime', 'warning', '音频下载失败', $logData);
  1339. }
  1340. } catch (\Exception $e) {
  1341. $logData = [
  1342. 'segment_id' => $segment->segment_id,
  1343. 'audio_url' => $segment->audio_url,
  1344. 'error' => $e->getMessage()
  1345. ];
  1346. dLog('anime')->error('下载音频异常', $logData);
  1347. logDB('anime', 'error', '下载音频异常', $logData);
  1348. }
  1349. }
  1350. }
  1351. // 如果有音频文件,则进行合成
  1352. if (!empty($audioFiles)) {
  1353. // 创建 FFmpeg concat 文件列表
  1354. $concatFile = $tempDir . '/concat.txt';
  1355. $concatContent = '';
  1356. foreach ($audioFiles as $audioFile) {
  1357. // 使用相对路径,避免路径中的特殊字符问题
  1358. $concatContent .= "file '" . basename($audioFile) . "'\n";
  1359. }
  1360. file_put_contents($concatFile, $concatContent);
  1361. // 合成音频文件
  1362. $mergedAudioPath = $tempDir . '/tts.wav';
  1363. // 使用 FFmpeg 合并音频,转换为统一的 WAV 格式
  1364. $ffmpegCommand = sprintf(
  1365. 'cd %s && ffmpeg -f concat -safe 0 -i %s -ar 44100 -ac 2 -y %s 2>&1',
  1366. escapeshellarg($tempDir),
  1367. escapeshellarg(basename($concatFile)),
  1368. escapeshellarg(basename($mergedAudioPath))
  1369. );
  1370. exec($ffmpegCommand, $ffmpegOutput, $ffmpegReturnCode);
  1371. if ($ffmpegReturnCode !== 0 || !file_exists($mergedAudioPath)) {
  1372. $logData = [
  1373. 'command' => $ffmpegCommand,
  1374. 'output' => implode("\n", $ffmpegOutput),
  1375. 'return_code' => $ffmpegReturnCode
  1376. ];
  1377. dLog('anime')->error('FFmpeg 合成音频失败', $logData);
  1378. logDB('anime', 'error', 'FFmpeg 合成音频失败', $logData);
  1379. $mergedAudioPath = null;
  1380. } else {
  1381. $logData = [
  1382. 'audio_count' => count($audioFiles),
  1383. 'output_file' => $mergedAudioPath,
  1384. 'file_size' => filesize($mergedAudioPath)
  1385. ];
  1386. dLog('anime')->info('音频合成成功', $logData);
  1387. logDB('anime', 'info', '音频合成成功', $logData);
  1388. }
  1389. // 清理临时音频文件和 concat 文件
  1390. foreach ($audioFiles as $audioFile) {
  1391. if (file_exists($audioFile)) {
  1392. @unlink($audioFile);
  1393. }
  1394. }
  1395. if (file_exists($concatFile)) {
  1396. @unlink($concatFile);
  1397. }
  1398. }
  1399. } else {
  1400. dLog('anime')->warning('FFmpeg 未安装,跳过音频合成');
  1401. logDB('anime', 'warning', 'FFmpeg 未安装,跳过音频合成', []);
  1402. }
  1403. } catch (\Exception $e) {
  1404. $logData = [
  1405. 'error' => $e->getMessage(),
  1406. 'trace' => $e->getTraceAsString()
  1407. ];
  1408. dLog('anime')->error('音频合成过程异常', $logData);
  1409. logDB('anime', 'error', '音频合成过程异常', $logData);
  1410. // 音频合成失败不影响图片导出
  1411. $mergedAudioPath = null;
  1412. }
  1413. // 创建zip文件
  1414. $zipFileName = sprintf(
  1415. '%s.zip',
  1416. $episode->title ?: '未命名'
  1417. );
  1418. $zipFilePath = storage_path('app/temp/' . $zipFileName);
  1419. $zip = new \ZipArchive();
  1420. if ($zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
  1421. // 清理临时文件
  1422. array_map('unlink', $downloadedFiles);
  1423. rmdir($tempDir);
  1424. Utils::throwError('20003:创建ZIP文件失败');
  1425. }
  1426. // 添加图片文件到zip
  1427. foreach ($downloadedFiles as $file) {
  1428. $zip->addFile($file, basename($file));
  1429. }
  1430. // 添加合成的音频文件到zip
  1431. if ($mergedAudioPath && file_exists($mergedAudioPath)) {
  1432. $zip->addFile($mergedAudioPath, 'tts.wav');
  1433. }
  1434. $zip->close();
  1435. // 清理临时图片文件
  1436. array_map('unlink', $downloadedFiles);
  1437. // 清理合成的音频文件
  1438. if ($mergedAudioPath && file_exists($mergedAudioPath)) {
  1439. @unlink($mergedAudioPath);
  1440. }
  1441. rmdir($tempDir);
  1442. // 返回文件下载响应
  1443. return response()->download($zipFilePath, $zipFileName)->deleteFileAfterSend(true);
  1444. } catch (\Exception $e) {
  1445. $logData = [
  1446. 'anime_id' => $animeId,
  1447. 'episode_id' => $episodeId,
  1448. 'error' => $e->getMessage()
  1449. ];
  1450. dLog('anime')->error('导出分集图片失败', $logData);
  1451. logDB('anime', 'error', '导出分集图片失败', $logData);
  1452. // 清理可能存在的临时文件
  1453. if (isset($tempDir) && file_exists($tempDir)) {
  1454. array_map('unlink', glob("$tempDir/*"));
  1455. rmdir($tempDir);
  1456. }
  1457. if (isset($zipFilePath) && file_exists($zipFilePath)) {
  1458. unlink($zipFilePath);
  1459. }
  1460. throw $e;
  1461. }
  1462. }
  1463. /**
  1464. * 监控分镜图片和音频生成任务进度(SSE)
  1465. */
  1466. public function monitorSegmentTasks(Request $request) {
  1467. // 忽略所有超时限制
  1468. set_time_limit(0);
  1469. ini_set('max_execution_time', '0');
  1470. $data = $request->all();
  1471. // 验证参数
  1472. $validator = Validator::make($data, [
  1473. 'anime_id' => 'required|string',
  1474. 'episode_id' => 'required|string',
  1475. ], [
  1476. 'anime_id.required' => '动漫ID不能为空',
  1477. 'episode_id.required' => '剧集ID不能为空',
  1478. ]);
  1479. if ($validator->fails()) {
  1480. Utils::throwError('1002:' . $validator->errors()->first());
  1481. }
  1482. $animeId = $data['anime_id'];
  1483. $episodeId = $data['episode_id'];
  1484. // 查询没有pic_task_id的分镜个数
  1485. $noPicTaskCount = DB::table('mp_episode_segments')
  1486. ->where('anime_id', $animeId)
  1487. ->where('episode_id', $episodeId)
  1488. ->where(function($query) {
  1489. $query->whereNull('pic_task_id')
  1490. ->orWhere('pic_task_id', '');
  1491. })
  1492. ->count('id');
  1493. // 获取所有分镜信息
  1494. $segments = DB::table('mp_episode_segments')
  1495. ->where('anime_id', $animeId)
  1496. ->where('episode_id', $episodeId)
  1497. ->where('pic_task_id', '!=', '')
  1498. ->orderBy('segment_number')
  1499. ->get();
  1500. // 判断是否有未完成的任务
  1501. $uncompleted_pic_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)
  1502. ->where('episode_id', $episodeId)->where('pic_task_id', '<>', '')->whereNotIn('pic_task_status', ['已完成', '失败'])->count('id');
  1503. // 获取dialogue和voice_type存在但audio_url不存在的分镜个数
  1504. $uncompleted_audio_count = DB::table('mp_episode_segments')
  1505. ->where('anime_id', $animeId)
  1506. ->where('episode_id', $episodeId)
  1507. ->where('dialogue', '<>', '')
  1508. ->whereNotNull('dialogue')
  1509. ->where('voice_type', '<>', '')
  1510. ->whereNotNull('voice_type')
  1511. ->where(function($query) {
  1512. $query->whereNull('audio_url')
  1513. ->orWhere('audio_url', '');
  1514. })
  1515. ->count('id');
  1516. if ($segments->isEmpty()) {
  1517. Utils::throwError('20003:未找到分镜任务数据');
  1518. }
  1519. $startTime = time();
  1520. $maxDuration = 900; // 15分钟超时
  1521. $checkInterval = 5; // 每5秒检查一次
  1522. // 设置 SSE 响应头并开始长连接
  1523. return response()->stream(function () use ($segments, $animeId, $episodeId, $startTime, $maxDuration, $checkInterval, $uncompleted_pic_count, $uncompleted_audio_count, $noPicTaskCount) {
  1524. if ($uncompleted_pic_count == 0 && $uncompleted_audio_count == 0) {
  1525. $completedCount = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episodeId)->where('pic_task_id', '<>', '')->where('pic_task_status', '已完成')->count('id');
  1526. // 获取剧集信息之前先处理视频截止时间点
  1527. $this->handleVideoTimePointEnd();
  1528. // 获取剧集信息
  1529. $episode = DB::table('mp_anime_episodes')
  1530. ->where('anime_id', $animeId)
  1531. ->where('id', $episodeId)
  1532. ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
  1533. ->first();
  1534. if ($episode) {
  1535. $episode = (array)$episode;
  1536. $episode['roles'] = json_decode($episode['roles'], true);
  1537. $episode['scenes'] = json_decode($episode['scenes'], true);
  1538. // 获取所有分镜信息
  1539. $allSegments = DB::table('mp_episode_segments')
  1540. ->where('anime_id', $animeId)
  1541. ->where('episode_id', $episodeId)
  1542. ->orderBy('segment_number')
  1543. ->select('*')
  1544. ->get()
  1545. ->map(function ($value) {
  1546. return (array)$value;
  1547. })->toArray();
  1548. // 按照episodeInfo的格式组织数据
  1549. $segmentsStructure = $this->AnimeService->buildEpisodeSegmentsStructure($allSegments);
  1550. $episode['acts'] = $segmentsStructure['acts'];
  1551. $episode['total_duration'] = $segmentsStructure['total_duration'];
  1552. }
  1553. echo "data: " . json_encode([
  1554. 'type' => 'completed',
  1555. 'data' => [
  1556. 'anime_id' => $animeId,
  1557. 'episode_id' => $episodeId,
  1558. 'completed_count' => $completedCount, // 成功完成的数量
  1559. 'processed_count' => count($segments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1560. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1561. 'total_elapsed_time' => time() - $startTime,
  1562. 'episode_info' => $episode ?? null
  1563. ]
  1564. ]) . "\n\n";
  1565. ob_flush();
  1566. flush();
  1567. return;
  1568. }
  1569. // 发送初始任务信息
  1570. echo "data: " . json_encode([
  1571. 'type' => 'init',
  1572. 'data' => [
  1573. 'anime_id' => $animeId,
  1574. 'episode_id' => $episodeId,
  1575. 'total_segments' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1576. 'start_time' => $startTime,
  1577. 'max_duration' => $maxDuration
  1578. ]
  1579. ]) . "\n\n";
  1580. ob_flush();
  1581. flush();
  1582. $completedSegments = [];
  1583. $processedSegments = []; // 记录已处理完成的分镜(成功或失败)
  1584. $notifiedSegments = []; // 记录已通知过的分镜,避免重复通知
  1585. while (time() - $startTime < $maxDuration) {
  1586. try {
  1587. $updatedImages = []; // 记录本次循环中更新的图片信息
  1588. foreach ($segments as $segment) {
  1589. $segmentId = $segment->segment_id;
  1590. $picTaskId = $segment->pic_task_id;
  1591. $audioUrl = $segment->audio_url;
  1592. // 跳过已处理完成的分镜
  1593. if (in_array($segmentId, $processedSegments)) {
  1594. continue;
  1595. }
  1596. $picCompleted = false;
  1597. $audioCompleted = false;
  1598. $picProcessed = false;
  1599. $audioProcessed = false;
  1600. // 检查图片任务状态
  1601. if ($picTaskId) {
  1602. $picTask = DB::table('mp_generate_pic_tasks')
  1603. ->where('id', $picTaskId)
  1604. ->select('status', 'result_url', 'error_message')
  1605. ->first();
  1606. if ($picTask && in_array($picTask->status, ['success', 'failed'])) {
  1607. $updateData = [
  1608. 'pic_task_status' => $picTask->status === 'success' ? '已完成' : '失败',
  1609. 'updated_at' => date('Y-m-d H:i:s')
  1610. ];
  1611. $imgUrl = '';
  1612. if ($picTask->status === 'success' && !empty($picTask->result_url)) {
  1613. // 更新分镜表的图片URL
  1614. $resultUrls = json_decode($picTask->result_url, true);
  1615. $imgUrl = is_array($resultUrls) ? $resultUrls[0] : $picTask->result_url;
  1616. $updateData['img_url'] = $imgUrl;
  1617. $picCompleted = true;
  1618. } else if ($picTask->status === 'failed') {
  1619. // 失败时清空图片URL
  1620. $updateData['img_url'] = '';
  1621. }
  1622. DB::table('mp_episode_segments')
  1623. ->where('segment_id', $segmentId)
  1624. ->update($updateData);
  1625. // 记录更新的图片信息(只有未通知过的才记录)
  1626. if (!in_array($segmentId, $notifiedSegments)) {
  1627. $updatedImages[] = [
  1628. 'segment_id' => $segmentId,
  1629. 'segment_number' => $segment->segment_number,
  1630. 'img_url' => $imgUrl,
  1631. 'status' => $picTask->status === 'success' ? 'success' : 'failed'
  1632. ];
  1633. // 标记为已通知
  1634. $notifiedSegments[] = $segmentId;
  1635. }
  1636. $picProcessed = true;
  1637. }
  1638. }
  1639. // 检查音频状态
  1640. // 获取分镜的dialogue、voice_type和audio_url信息
  1641. $segmentInfo = DB::table('mp_episode_segments')
  1642. ->where('segment_id', $segmentId)
  1643. ->select('dialogue', 'voice_type', 'audio_url')
  1644. ->first();
  1645. $needAudio = false;
  1646. $currentAudioUrl = '';
  1647. if ($segmentInfo) {
  1648. $dialogue = trim((string)getProp($segmentInfo, 'dialogue'));
  1649. $voiceType = trim((string)getProp($segmentInfo, 'voice_type'));
  1650. $currentAudioUrl = trim((string)getProp($segmentInfo, 'audio_url'));
  1651. // 如果有对话和音色类型,则需要音频
  1652. if (!empty($dialogue) && !empty($voiceType)) {
  1653. $needAudio = true;
  1654. }
  1655. }
  1656. // 判断音频状态
  1657. if ($needAudio) {
  1658. // 需要音频的情况下,检查audio_url是否有值
  1659. if (!empty($currentAudioUrl)) {
  1660. $audioCompleted = true;
  1661. $audioProcessed = true;
  1662. } else {
  1663. // 需要音频但还没有,继续等待
  1664. $audioCompleted = false;
  1665. $audioProcessed = false;
  1666. }
  1667. } else {
  1668. // 不需要音频,直接标记为已处理
  1669. $audioCompleted = false;
  1670. $audioProcessed = true;
  1671. }
  1672. // 如果图片和音频都成功完成,标记为已完成
  1673. if ($picCompleted && ($audioCompleted || !$needAudio)) {
  1674. $completedSegments[] = $segmentId;
  1675. }
  1676. // 如果图片和音频都已处理完成(成功或失败),标记为已处理
  1677. if ($picProcessed && $audioProcessed) {
  1678. $processedSegments[] = $segmentId;
  1679. }
  1680. }
  1681. // 如果有图片更新,发送具体的图片更新信息
  1682. if (!empty($updatedImages)) {
  1683. echo "data: " . json_encode([
  1684. 'type' => 'update',
  1685. 'data' => [
  1686. 'anime_id' => $animeId,
  1687. 'episode_id' => $episodeId,
  1688. 'updated_images' => $updatedImages,
  1689. 'completed_count' => count($completedSegments), // 成功完成的数量
  1690. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1691. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1692. 'elapsed_time' => time() - $startTime,
  1693. 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
  1694. ]
  1695. ]) . "\n\n";
  1696. ob_flush();
  1697. flush();
  1698. }
  1699. // 如果所有分镜都已处理完成(成功或失败),获取最终结果并结束连接
  1700. if (count($processedSegments) === count($segments)) {
  1701. // 获取剧集信息之前先处理视频截止时间点
  1702. $this->handleVideoTimePointEnd();
  1703. // 获取剧集信息
  1704. $episode = DB::table('mp_anime_episodes')
  1705. ->where('anime_id', $animeId)
  1706. ->where('id', $episodeId)
  1707. ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
  1708. ->first();
  1709. if ($episode) {
  1710. $episode = (array)$episode;
  1711. $episode['roles'] = json_decode($episode['roles'], true);
  1712. $episode['scenes'] = json_decode($episode['scenes'], true);
  1713. // 获取所有分镜信息
  1714. $allSegments = DB::table('mp_episode_segments')
  1715. ->where('anime_id', $animeId)
  1716. ->where('episode_id', $episodeId)
  1717. ->orderBy('segment_number')
  1718. ->select('*')
  1719. ->get()
  1720. ->map(function ($value) {
  1721. return (array)$value;
  1722. })->toArray();
  1723. // 按照episodeInfo的格式组织数据
  1724. $segmentsStructure = $this->AnimeService->buildEpisodeSegmentsStructure($allSegments);
  1725. $episode['acts'] = $segmentsStructure['acts'];
  1726. $episode['total_duration'] = $segmentsStructure['total_duration'];
  1727. }
  1728. echo "data: " . json_encode([
  1729. 'type' => 'completed',
  1730. 'data' => [
  1731. 'anime_id' => $animeId,
  1732. 'episode_id' => $episodeId,
  1733. 'completed_count' => count($completedSegments), // 成功完成的数量
  1734. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1735. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1736. 'total_elapsed_time' => time() - $startTime,
  1737. 'episode_info' => $episode ?? null
  1738. ]
  1739. ]) . "\n\n";
  1740. ob_flush();
  1741. flush();
  1742. break;
  1743. }
  1744. // 检查是否超时
  1745. if (time() - $startTime >= $maxDuration) {
  1746. break;
  1747. }
  1748. sleep($checkInterval);
  1749. } catch (\Exception $e) {
  1750. echo "data: " . json_encode([
  1751. 'type' => 'error',
  1752. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  1753. 'elapsed_time' => time() - $startTime,
  1754. 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
  1755. ]) . "\n\n";
  1756. ob_flush();
  1757. flush();
  1758. if (time() - $startTime >= $maxDuration) {
  1759. break;
  1760. }
  1761. sleep($checkInterval);
  1762. }
  1763. }
  1764. // 超时处理
  1765. if (time() - $startTime >= $maxDuration) {
  1766. echo "data: " . json_encode([
  1767. 'type' => 'time_out',
  1768. 'message' => '分镜任务监控已超时15分钟,停止状态查询',
  1769. 'data' => [
  1770. 'anime_id' => $animeId,
  1771. 'episode_id' => $episodeId,
  1772. 'completed_count' => count($completedSegments), // 成功完成的数量
  1773. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1774. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1775. 'total_elapsed_time' => time() - $startTime,
  1776. 'timeout_duration' => $maxDuration
  1777. ]
  1778. ]) . "\n\n";
  1779. ob_flush();
  1780. flush();
  1781. }
  1782. }, 200, [
  1783. 'Content-Type' => 'text/event-stream',
  1784. 'Cache-Control' => 'no-cache',
  1785. 'Connection' => 'keep-alive',
  1786. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  1787. ]);
  1788. }
  1789. /**
  1790. * 音频试听接口
  1791. * 创建音频任务并返回结果
  1792. */
  1793. public function previewAudio(Request $request) {
  1794. $data = $request->all();
  1795. $result = $this->AnimeService->previewAudio($data);
  1796. return $this->success($result);
  1797. }
  1798. // 角色库
  1799. public function globalProducts(Request $request) {
  1800. $data = $request->all();
  1801. $result = $this->AnimeService->globalProducts($data);
  1802. return $this->success($result);
  1803. }
  1804. // 新建角色
  1805. public function createProduct(Request $request) {
  1806. $data = $request->all();
  1807. $result = $this->AnimeService->createProduct($data);
  1808. return $this->success($result);
  1809. }
  1810. // 编辑角色
  1811. public function editProduct(Request $request) {
  1812. $data = $request->all();
  1813. $result = $this->AnimeService->editProduct($data);
  1814. return $this->success(['success' => $result ? 1 : 0]);
  1815. }
  1816. // 获取角色版本历史
  1817. public function getProductVersions(Request $request) {
  1818. $data = $request->all();
  1819. $result = $this->AnimeService->getProductVersions($data);
  1820. return $this->success($result);
  1821. }
  1822. // 恢复到指定版本
  1823. public function restoreProductVersion(Request $request) {
  1824. $data = $request->all();
  1825. $result = $this->AnimeService->restoreProductVersion($data);
  1826. return $this->success(['success' => $result ? 1 : 0]);
  1827. }
  1828. // 删除角色
  1829. public function deleteProduct(Request $request) {
  1830. $data = $request->all();
  1831. $result = $this->AnimeService->deleteProduct($data);
  1832. return $this->success(['success' => $result ? 1 : 0]);
  1833. }
  1834. // 新建文件夹
  1835. public function createFolder(Request $request) {
  1836. $data = $request->all();
  1837. $result = $this->AnimeService->createFolder($data);
  1838. return $this->success(['id' => $result]);
  1839. }
  1840. // 重命名文件夹或角色
  1841. public function renameFolder(Request $request) {
  1842. $data = $request->all();
  1843. $result = $this->AnimeService->renameFolder($data);
  1844. return $this->success(['success' => $result ? 1 : 0]);
  1845. }
  1846. // 移动角色或文件夹
  1847. public function moveProductOrFolder(Request $request) {
  1848. $data = $request->all();
  1849. $result = $this->AnimeService->moveProductOrFolder($data);
  1850. return $this->success(['success' => $result ? 1 : 0]);
  1851. }
  1852. // 获取文件夹路径(面包屑导航)
  1853. public function getFolderPath(Request $request) {
  1854. $data = $request->all();
  1855. $result = $this->AnimeService->getFolderPath($data);
  1856. return $this->success($result);
  1857. }
  1858. // 生成三视图
  1859. public function generateThreeView(Request $request) {
  1860. $data = $request->all();
  1861. $result = $this->AnimeService->generateThreeView($data);
  1862. return $this->success($result);
  1863. }
  1864. private function handleVideoTimePointEnd() {
  1865. // 处理音频时长,循环查询dub_video_task_queue列表中的任务
  1866. $queueLength = Redis::llen('dub_video_task_queue');
  1867. if ($queueLength > 0) {
  1868. $processedTaskIds = []; // 记录已处理的任务ID
  1869. // 遍历队列中的所有任务
  1870. for ($i = 0; $i < $queueLength; $i++) {
  1871. $dubTaskId = Redis::lindex('dub_video_task_queue', $i);
  1872. if (!$dubTaskId) continue;
  1873. // 查询任务状态
  1874. $dubTask = DB::table('mp_dub_video_tasks')
  1875. ->where('id', $dubTaskId)
  1876. ->first();
  1877. if (!$dubTask) {
  1878. // 任务不存在,标记为需要删除
  1879. $processedTaskIds[] = $dubTaskId;
  1880. continue;
  1881. }
  1882. // 如果任务状态是已完成
  1883. if ($dubTask->generate_status === '执行成功') {
  1884. // 获取对应的分镜信息
  1885. $segment = DB::table('mp_episode_segments')
  1886. ->where('segment_id', $dubTask->alias_segment_id)
  1887. ->first();
  1888. // 如果分镜存在且audio_duration大于0
  1889. if ($segment && isset($segment->audio_duration) && $segment->audio_duration > 0) {
  1890. // 更新video_time_point_end字段
  1891. DB::table('mp_episode_segments')
  1892. ->where('segment_id', $dubTask->alias_segment_id)
  1893. ->update([
  1894. 'video_time_point_end' => $segment->audio_duration,
  1895. 'updated_at' => date('Y-m-d H:i:s')
  1896. ]);
  1897. dLog('anime')->info('更新分镜视频截止时间点', [
  1898. 'task_id' => $dubTaskId,
  1899. 'segment_id' => $dubTask->alias_segment_id,
  1900. 'audio_duration' => $segment->audio_duration
  1901. ]);
  1902. }
  1903. // 标记为需要从队列中删除
  1904. $processedTaskIds[] = $dubTaskId;
  1905. }
  1906. }
  1907. // 从Redis列表中删除已处理的任务ID
  1908. foreach ($processedTaskIds as $taskId) {
  1909. Redis::lrem('dub_video_task_queue', 0, $taskId);
  1910. }
  1911. }
  1912. }
  1913. // 确认片段
  1914. public function confirmActs(Request $request) {
  1915. $data = $request->all();
  1916. $result = $this->AnimeService->confirmActs($data);
  1917. return $this->success($result);
  1918. }
  1919. public function createActVideoTask(Request $request) {
  1920. $uid = Site::getUid();
  1921. // 忽略所有超时限制
  1922. set_time_limit(0);
  1923. ini_set('max_execution_time', '0');
  1924. $data = $request->all();
  1925. // 创建视频生成任务
  1926. $result = $this->AnimeService->createActVideoTask($data);
  1927. $taskId = $result['task_id'];
  1928. // 设置 SSE 响应头
  1929. return response()->stream(function () use ($taskId, $result, $uid) {
  1930. // 设置 SSE 响应头
  1931. echo "data: " . json_encode([
  1932. 'type' => 'init',
  1933. 'data' => $result
  1934. ]) . "\n\n";
  1935. ob_flush();
  1936. flush();
  1937. $startTime = time();
  1938. $maxDuration = 900; // 15分钟超时
  1939. $checkInterval = 5; // 每5秒检查一次
  1940. while (time() - $startTime < $maxDuration) {
  1941. try {
  1942. // 查询任务状态
  1943. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  1944. if (!$task) {
  1945. echo "data: " . json_encode([
  1946. 'type' => 'error',
  1947. 'message' => '任务不存在'
  1948. ]) . "\n\n";
  1949. ob_flush();
  1950. flush();
  1951. break;
  1952. }
  1953. // 如果任务还在处理中,查询最新状态
  1954. if ($task->status === 'processing') {
  1955. // 根据任务类型查询不同的状态
  1956. if ($task->api_type === 'jimeng') {
  1957. $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
  1958. } elseif ($task->api_type === 'keling') {
  1959. $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
  1960. } elseif ($task->api_type === 'zzengine') {
  1961. $statusResult = $this->AIVideoGenerationService->queryUnifiedApiTaskStatus($task);
  1962. } else {
  1963. $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
  1964. }
  1965. if (isset($statusResult['status'])) {
  1966. // 更新任务状态
  1967. $task->update([
  1968. 'status' => $statusResult['status'],
  1969. 'result_url' => $statusResult['result_url'] ?? null,
  1970. 'compressed_url' => $statusResult['compressed_url'] ?? null,
  1971. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  1972. 'error_message' => $statusResult['error_message'] ?? null,
  1973. 'completed_at' => in_array($statusResult['status'], [
  1974. 'success',
  1975. 'failed'
  1976. ]) ? now() : null
  1977. ]);
  1978. // 如果任务成功,更新分镜表
  1979. if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
  1980. try {
  1981. DB::beginTransaction();
  1982. $now = date('Y-m-d H:i:s');
  1983. // 获取分镜ID
  1984. $act = DB::table('mp_episode_segments')
  1985. ->where('video_task_id', $taskId)
  1986. ->first();
  1987. if (!$act) {
  1988. throw new \Exception('未找到对应的片段记录');
  1989. }
  1990. $act_id = $act->id;
  1991. $anime_id = $act->anime_id;
  1992. $episode_number = $act->episode_number;
  1993. $act_content = $act->act_content;
  1994. // 更新分镜表
  1995. $segmentUpdateData = [
  1996. 'origin_video_url' => $statusResult['result_url'],
  1997. 'video_task_status' => '已完成',
  1998. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  1999. 'current_type' => 2,
  2000. 'updated_at' => $now
  2001. ];
  2002. $compressed_video_url = compressVideo($statusResult['result_url']);
  2003. $segmentUpdateData['video_url'] = $compressed_video_url ?: $statusResult['result_url'];
  2004. // 只有当video_duration存在且大于0时才更新
  2005. if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
  2006. $segmentUpdateData['video_duration'] = $statusResult['video_duration'];
  2007. $segmentUpdateData['video_time_point_start'] = 0;
  2008. $segmentUpdateData['video_time_point_end'] = $statusResult['video_duration'];
  2009. }
  2010. $updateResult = DB::table('mp_episode_segments')
  2011. ->where('id', $act_id)
  2012. ->update($segmentUpdateData);
  2013. if (!$updateResult) {
  2014. Utils::throwError('20003:更新分镜表失败');
  2015. }
  2016. // 更新分镜视频成功后新增对话记录
  2017. // 保存对话记录
  2018. $records = [
  2019. [
  2020. 'uid' => $uid,
  2021. 'anime_id' => $anime_id,
  2022. 'sequence' => $episode_number,
  2023. 'role' => 'user',
  2024. 'content' => '片段转视频',
  2025. 'act_id' => $act_id,
  2026. 'video_url' => '',
  2027. 'created_at' => $now,
  2028. 'updated_at' => $now
  2029. ],
  2030. [
  2031. 'uid' => $uid,
  2032. 'anime_id' => $anime_id,
  2033. 'sequence' => $episode_number,
  2034. 'role' => 'assistant',
  2035. 'content' => $act_content,
  2036. 'act_id' => $act_id,
  2037. 'video_url' => $statusResult['result_url'],
  2038. 'created_at' => $now,
  2039. 'updated_at' => $now
  2040. ]
  2041. ];
  2042. DB::table('mp_anime_records')->insert($records);
  2043. DB::commit();
  2044. } catch (\Exception $e) {
  2045. DB::rollBack();
  2046. $logData = [
  2047. 'task_id' => $taskId,
  2048. 'error' => $e->getMessage()
  2049. ];
  2050. dLog('anime')->error('视频任务处理失败', $logData);
  2051. logDB('anime', 'error', '视频任务处理失败', $logData);
  2052. }
  2053. } elseif ($statusResult['status'] === 'failed') {
  2054. DB::table('mp_episode_segments')
  2055. ->where('video_task_id', $taskId)
  2056. ->update([
  2057. 'video_task_status' => '失败',
  2058. 'updated_at' => date('Y-m-d H:i:s')
  2059. ]);
  2060. }
  2061. }
  2062. }
  2063. // 发送当前状态
  2064. echo "data: " . json_encode([
  2065. 'type' => 'update',
  2066. 'data' => [
  2067. 'task_id' => $task->id,
  2068. 'status' => $task->status,
  2069. 'result_url' => $task->result_url,
  2070. 'error_message' => $task->error_message,
  2071. 'elapsed_time' => time() - $startTime
  2072. ]
  2073. ]) . "\n\n";
  2074. ob_flush();
  2075. flush();
  2076. // 如果任务完成(成功或失败),结束连接
  2077. if (in_array($task->status, [
  2078. 'success',
  2079. 'failed'
  2080. ])) {
  2081. echo "data: " . json_encode([
  2082. 'type' => 'completed',
  2083. 'data' => [
  2084. 'task_id' => $task->id,
  2085. 'status' => $task->status,
  2086. 'video_url' => $task->compressed_url ?: $task->result_url,
  2087. 'origin_video_url' => $task->result_url,
  2088. 'last_frame_url' => $task->last_frame_url,
  2089. 'error_message' => $task->error_message
  2090. ]
  2091. ]) . "\n\n";
  2092. ob_flush();
  2093. flush();
  2094. break;
  2095. }
  2096. sleep($checkInterval);
  2097. } catch (\Exception $e) {
  2098. echo "data: " . json_encode([
  2099. 'type' => 'error',
  2100. 'message' => '查询任务状态失败: ' . $e->getMessage()
  2101. ]) . "\n\n";
  2102. ob_flush();
  2103. flush();
  2104. sleep($checkInterval);
  2105. }
  2106. }
  2107. // 超时处理
  2108. if (time() - $startTime >= $maxDuration) {
  2109. echo "data: " . json_encode([
  2110. 'type' => 'time_out',
  2111. 'message' => '任务执行超时,请稍后查询任务状态',
  2112. 'data' => [
  2113. 'task_id' => $taskId
  2114. ]
  2115. ]) . "\n\n";
  2116. ob_flush();
  2117. flush();
  2118. }
  2119. }, 200, [
  2120. 'Content-Type' => 'text/event-stream',
  2121. 'Cache-Control' => 'no-cache',
  2122. 'Connection' => 'keep-alive',
  2123. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  2124. ]);
  2125. }
  2126. /**
  2127. * 批量生成片段视频
  2128. */
  2129. public function batchSetActVideos(Request $request) {
  2130. // 忽略所有超时限制
  2131. set_time_limit(0);
  2132. ini_set('max_execution_time', '0');
  2133. $data = $request->all();
  2134. // 验证参数
  2135. $validator = Validator::make($data, [
  2136. 'anime_id' => 'required|string',
  2137. 'episode_id' => 'required|integer',
  2138. ], [
  2139. 'anime_id.required' => '动漫对话ID不能为空',
  2140. 'episode_id.required' => '剧集ID不能为空',
  2141. 'episode_id.integer' => '剧集ID必须是整数',
  2142. ]);
  2143. if ($validator->fails()) {
  2144. return response()->stream(function () use ($validator) {
  2145. echo "data: " . json_encode([
  2146. 'type' => 'error',
  2147. 'message' => $validator->errors()->first()
  2148. ]) . "\n\n";
  2149. ob_flush();
  2150. flush();
  2151. }, 200, [
  2152. 'Content-Type' => 'text/event-stream',
  2153. 'Cache-Control' => 'no-cache',
  2154. 'Connection' => 'keep-alive',
  2155. 'X-Accel-Buffering' => 'no',
  2156. ]);
  2157. }
  2158. $animeId = $data['anime_id'];
  2159. $episodeId = $data['episode_id'];
  2160. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->where('anime_id', $animeId)->first();
  2161. if (!$episode) {
  2162. return response()->stream(function () {
  2163. echo "data: " . json_encode([
  2164. 'type' => 'error',
  2165. 'message' => '分集不存在'
  2166. ]) . "\n\n";
  2167. ob_flush();
  2168. flush();
  2169. }, 200, [
  2170. 'Content-Type' => 'text/event-stream',
  2171. 'Cache-Control' => 'no-cache',
  2172. 'Connection' => 'keep-alive',
  2173. 'X-Accel-Buffering' => 'no',
  2174. ]);
  2175. }
  2176. $episodeNumber = $episode->episode_number;
  2177. $ratio = !empty($episode->ratio) ? $episode->ratio : '9:16';
  2178. $generate_audio = getProp($data, 'generate_audio', 1);
  2179. // 合并角色和场景作为products,统一字段名为product_name
  2180. $products = [];
  2181. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  2182. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  2183. // 处理角色数组
  2184. foreach ($roles as $role) {
  2185. $product = $role;
  2186. // 将role字段重命名为product_name
  2187. if (isset($product['role'])) {
  2188. $product['product_name'] = $product['role'];
  2189. unset($product['role']);
  2190. }
  2191. $product['product'] = 1; // 标记类型为角色
  2192. $products[] = $product;
  2193. }
  2194. // 处理场景数组
  2195. foreach ($scenes as $scene) {
  2196. $product = $scene;
  2197. // 将scene字段重命名为product_name
  2198. if (isset($product['scene'])) {
  2199. $product['product_name'] = $product['scene'];
  2200. unset($product['scene']);
  2201. }
  2202. $product['product'] = 2; // 标记类型为场景
  2203. $products[] = $product;
  2204. }
  2205. // 处理视频模型(在循环外统一处理)
  2206. // $model = getProp($data, 'model');
  2207. // if (!$model) {
  2208. // // 用户没有输入,从episode表获取
  2209. // $model = getProp($episode, 'video_model');
  2210. // if (!$model) {
  2211. // // episode表也没有,使用默认值
  2212. // $model = 'zhizhen-20-fast';
  2213. // }
  2214. // }
  2215. $model = 'zhizhen-20-fast'; // 使用默认值
  2216. // 验证模型是否在可用模型表中
  2217. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2218. $model = 'zhizhen-20-fast';
  2219. }
  2220. // 获取所有分镜信息
  2221. $acts = DB::table('mp_episode_segments')
  2222. ->where('anime_id', $animeId)
  2223. ->where('episode_id', $episodeId)
  2224. ->orderBy('act_number')
  2225. ->get();
  2226. if ($acts->isEmpty()) {
  2227. return response()->stream(function () {
  2228. echo "data: " . json_encode([
  2229. 'type' => 'error',
  2230. 'message' => '未找到分镜数据'
  2231. ]) . "\n\n";
  2232. ob_flush();
  2233. flush();
  2234. }, 200, [
  2235. 'Content-Type' => 'text/event-stream',
  2236. 'Cache-Control' => 'no-cache',
  2237. 'Connection' => 'keep-alive',
  2238. 'X-Accel-Buffering' => 'no',
  2239. ]);
  2240. }
  2241. foreach($acts as $act) {
  2242. $videoDuration = $act->act_duration;
  2243. if (!$videoDuration || $videoDuration <= 0) {
  2244. return response()->stream(function () {
  2245. echo "data: " . json_encode([
  2246. 'type' => 'error',
  2247. 'message' => '请检查是否有时长为空的片段'
  2248. ]) . "\n\n";
  2249. ob_flush();
  2250. flush();
  2251. }, 200, [
  2252. 'Content-Type' => 'text/event-stream',
  2253. 'Cache-Control' => 'no-cache',
  2254. 'Connection' => 'keep-alive',
  2255. 'X-Accel-Buffering' => 'no',
  2256. ]);
  2257. }
  2258. }
  2259. // 批量创建视频任务
  2260. $taskIds = [];
  2261. $actTasks = [];
  2262. foreach ($acts as $act) {
  2263. try {
  2264. // 检查视频任务正在生成中或当前状态为视频
  2265. if ($act->video_task_status === '生成中') {
  2266. $actTasks[] = [
  2267. 'act_id' => $act->id,
  2268. 'task_id' => $act->video_task_id,
  2269. 'act_number' => $act->act_number,
  2270. 'act_content' => $act->act_content,
  2271. 'audio_duration' => $act->audio_duration,
  2272. ];
  2273. continue;
  2274. }
  2275. if ((int)$act->current_type === 2) {
  2276. continue;
  2277. }
  2278. // 获取分镜内容
  2279. $actContent = $act->act_show_content ?: '';
  2280. // 构建完整的提示词
  2281. $processResult = $this->AnimeService->processActContentWithProducts($actContent, $products);
  2282. $fullPrompt = $processResult['content'];
  2283. $reference_images = $processResult['reference_images'];
  2284. $videoDuration = $act->act_duration;
  2285. // 构建视频生成参数
  2286. $videoParams = [
  2287. 'model' => $model,
  2288. 'alias_act_id' => $act->id,
  2289. 'prompt' => $fullPrompt,
  2290. 'video_duration' => $videoDuration,
  2291. 'video_resolution' => '720P',
  2292. 'seed' => -1,
  2293. 'ratio' => $ratio,
  2294. 'generate_audio' => (int)$generate_audio === 0 ? false : true,
  2295. 'draft' => false,
  2296. 'watermark' => false,
  2297. 'camera_fixed' => false,
  2298. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  2299. ];
  2300. // 如果分镜有图片,作为首帧
  2301. $hasImage = !empty($act->img_url);
  2302. $hasVideo = !empty($act->video_url);
  2303. if ($hasImage) {
  2304. $videoParams['first_frame_url'] = $act->img_url;
  2305. }
  2306. // 构建content数组
  2307. $videoParams['content'] = [
  2308. [
  2309. 'type' => 'text',
  2310. 'text' => $videoParams['prompt'],
  2311. ]
  2312. ];
  2313. // 如果有首帧图片,添加到content中
  2314. if ($hasImage) {
  2315. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  2316. $videoParams['content'][] = [
  2317. 'type' => 'image_url',
  2318. 'image_url' => [
  2319. 'url' => $videoParams['first_frame_url'],
  2320. ],
  2321. 'role' => 'reference_image',
  2322. ];
  2323. }else {
  2324. $videoParams['content'][] = [
  2325. 'type' => 'image_url',
  2326. 'image_url' => [
  2327. 'url' => $videoParams['first_frame_url'],
  2328. ],
  2329. 'role' => 'first_frame',
  2330. ];
  2331. }
  2332. }
  2333. // 获取配音音频URL和时长
  2334. $audioUrl = $act->audio_url ?? '';
  2335. $audioDuration = $act->audio_duration ?? 0;
  2336. // 音频传入的前提:必须有至少一张图片或一个视频
  2337. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  2338. // 根据模型选择不同的视频生成方法
  2339. if (strpos($model, 'jimeng') !== false) {
  2340. // 即梦模型参数调整
  2341. $videoParams['video_duration'] = $videoDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  2342. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 即梦使用aspect_ratio
  2343. unset($videoParams['ratio']);
  2344. unset($videoParams['content']); // 即梦不使用content格式
  2345. $task = $this->AIVideoGenerationService->createJimengTask($videoParams);
  2346. } elseif (strpos($model, 'kling') !== false) {
  2347. // Keling模型参数调整
  2348. $videoParams['video_duration'] = max(3, min(15, ceil($videoDuration))); // Keling支持3-15秒
  2349. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  2350. unset($videoParams['ratio']);
  2351. unset($videoParams['content']); // Keling不使用content格式
  2352. $task = $this->AIVideoGenerationService->createKelingOmniTask($videoParams);
  2353. } elseif (strpos($model, 'zhizhen') !== false) {
  2354. // 构建统一API参数
  2355. $unifiedParams = [
  2356. 'model_code' => $model,
  2357. 'alias_act_id' => $act->id,
  2358. 'prompt' => trim($fullPrompt),
  2359. 'video_duration' => $videoDuration,
  2360. 'video_resolution' => strtolower($videoParams['video_resolution']),
  2361. 'video_ratio' => $ratio,
  2362. 'seed' => -1,
  2363. ];
  2364. // 构建parameters参数
  2365. $parameters = [
  2366. 'seconds' => $unifiedParams['video_duration'],
  2367. 'resolution' => $unifiedParams['video_resolution'],
  2368. 'ratio' => $ratio,
  2369. // 'video_mode' => 'multi_image',
  2370. // 'mode' => 'multi_image',
  2371. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  2372. ];
  2373. $hasImage = false;
  2374. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  2375. if ($hasImage) {
  2376. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  2377. if (isset($videoParams['tail_frame_url'])) {
  2378. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  2379. }
  2380. } else {
  2381. // 没有图片时,记录错误日志
  2382. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  2383. 'act_id' => $act->id,
  2384. 'model' => $model
  2385. ]);
  2386. }
  2387. if ($reference_images) {
  2388. $reference_images = $this->AIImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  2389. $parameters['reference_images'] = $reference_images;
  2390. $parameters['video_mode'] = 'multi_image';
  2391. $parameters['mode'] = 'multi_image';
  2392. }
  2393. $unifiedParams['parameters'] = $parameters;
  2394. // 调用统一API创建任务
  2395. $task = $this->AIVideoGenerationService->createUnifiedApiTask($unifiedParams);
  2396. } else {
  2397. // Seedance模型(默认)
  2398. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  2399. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  2400. // 添加配音音频到content中
  2401. $videoParams['content'][] = [
  2402. 'type' => 'audio_url',
  2403. 'audio_url' => [
  2404. 'url' => $audioUrl,
  2405. ],
  2406. 'role' => 'reference_audio',
  2407. ];
  2408. // 优化提示词,增加音频相关描述
  2409. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  2410. $videoParams['prompt'] = $audioPrompt;
  2411. $videoParams['content'][0]['text'] = $audioPrompt;
  2412. } else if ($videoDuration) {
  2413. // 有音频时长则需将视频时长设置为比音频时长更长的整数
  2414. $videoParams['video_duration'] = max(4, min(12, ceil($videoDuration))); // seedance支持2-12s
  2415. }
  2416. $task = $this->AIVideoGenerationService->createSeedanceTask($videoParams);
  2417. }
  2418. $taskIds[] = $task->id;
  2419. // 更新分镜表的视频任务信息
  2420. DB::table('mp_episode_segments')
  2421. ->where('act_id', $act->id)
  2422. ->update([
  2423. 'video_task_id' => $task->id,
  2424. 'video_task_status' => '生成中',
  2425. 'updated_at' => date('Y-m-d H:i:s')
  2426. ]);
  2427. $actTasks[] = [
  2428. 'act_id' => $act->id,
  2429. 'task_id' => $task->id,
  2430. 'act_number' => $act->act_number,
  2431. 'content' => $fullPrompt,
  2432. 'audio_duration' => $act->audio_duration,
  2433. ];
  2434. } catch (\Exception $e) {
  2435. $logData = [
  2436. 'act_id' => $act->id,
  2437. 'anime_id' => $animeId,
  2438. 'error' => $e->getMessage(),
  2439. ];
  2440. dLog('anime')->error('创建分镜视频任务失败', $logData);
  2441. logDB('anime', 'error', '创建分镜视频任务失败', $logData);
  2442. continue;
  2443. }
  2444. }
  2445. if (empty($taskIds)) {
  2446. // 没有任务时,获取完整剧集信息进行验证
  2447. $episode = $this->AnimeService->episodeInfoForAce([
  2448. 'anime_id' => $animeId,
  2449. 'episode_id' => $episodeId
  2450. ]);
  2451. // 检查所有片段是否都已生成视频且current_type=2
  2452. $allActsValid = true;
  2453. $invalidActs = [];
  2454. $total_tasks_count = count($episode['acts']);
  2455. foreach ($episode['acts'] as $act) {
  2456. $videoUrl = getProp($act, 'video_url');
  2457. $currentType = getProp($act, 'current_type');
  2458. // 检查视频是否已生成
  2459. if (!$videoUrl) {
  2460. $allActsValid = false;
  2461. $invalidActs[] = [
  2462. 'act_number' => getProp($act, 'act_number'),
  2463. 'reason' => '视频未生成'
  2464. ];
  2465. continue;
  2466. }
  2467. // 检查current_type是否为2
  2468. if ($currentType != 2) {
  2469. $allActsValid = false;
  2470. $invalidActs[] = [
  2471. 'act_number' => getProp($act, 'act_number'),
  2472. 'reason' => '当前不是视频模式'
  2473. ];
  2474. }
  2475. }
  2476. // 如果所有分镜都满足条件,使用SSE格式返回完成状态
  2477. if ($allActsValid) {
  2478. return response()->stream(function () use ($episode, $total_tasks_count) {
  2479. echo "data: " . json_encode([
  2480. 'type' => 'completed',
  2481. 'total_tasks_count' => $total_tasks_count,
  2482. 'completed_tasks_count' => $total_tasks_count,
  2483. 'success_tasks_count' => $total_tasks_count,
  2484. 'episode' => $episode
  2485. ]) . "\n\n";
  2486. ob_flush();
  2487. flush();
  2488. }, 200, [
  2489. 'Content-Type' => 'text/event-stream',
  2490. 'Cache-Control' => 'no-cache',
  2491. 'Connection' => 'keep-alive',
  2492. 'X-Accel-Buffering' => 'no',
  2493. ]);
  2494. } else {
  2495. // 有未完成或不满足条件的分镜,使用SSE格式报错
  2496. $errorMsg = '存在未完成的片段:' . "\n";
  2497. foreach ($invalidActs as $invalid) {
  2498. $errorMsg .= "分镜{$invalid['act_number']}:{$invalid['reason']}\n";
  2499. }
  2500. return response()->stream(function () use ($errorMsg) {
  2501. echo "data: " . json_encode([
  2502. 'type' => 'error',
  2503. 'message' => trim($errorMsg)
  2504. ]) . "\n\n";
  2505. ob_flush();
  2506. flush();
  2507. }, 200, [
  2508. 'Content-Type' => 'text/event-stream',
  2509. 'Cache-Control' => 'no-cache',
  2510. 'Connection' => 'keep-alive',
  2511. 'X-Accel-Buffering' => 'no',
  2512. ]);
  2513. }
  2514. }
  2515. // 保存模型到episode表
  2516. DB::table('mp_anime_episodes')->where('id', $episodeId)->update([
  2517. 'video_model' => $model,
  2518. 'updated_at' => date('Y-m-d H:i:s')
  2519. ]);
  2520. // 记录开始时间(包含创建任务的时间)
  2521. $startTime = time();
  2522. $maxDuration = 3600;
  2523. $uid = Site::getUid();
  2524. // 设置 SSE 响应头并开始长连接
  2525. return response()->stream(function () use ($taskIds, $actTasks, $animeId, $episodeNumber, $episodeId, $startTime, $maxDuration, $uid) {
  2526. $checkInterval = 10; // 每10秒检查一次
  2527. // 初始化任务数组
  2528. $totalTasks = $taskIds; // 所有任务ID
  2529. $completeTasks = []; // 已完成的任务ID(包含失败)
  2530. $successTasks = []; // 成功的任务ID
  2531. // 发送初始任务创建信息
  2532. echo "data: " . json_encode([
  2533. 'type' => 'init',
  2534. 'total_tasks_count' => count($totalTasks),
  2535. 'completed_tasks_count' => count($completeTasks),
  2536. 'success_tasks_count' => count($successTasks)
  2537. ]) . "\n\n";
  2538. ob_flush();
  2539. flush();
  2540. while (time() - $startTime < $maxDuration) {
  2541. try {
  2542. $hasUpdate = false; // 标记是否有更新
  2543. // 获取所有任务的最新状态
  2544. foreach ($totalTasks as $taskId) {
  2545. // 如果任务已经在完成列表中,跳过
  2546. if (in_array($taskId, $completeTasks)) {
  2547. continue;
  2548. }
  2549. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  2550. if (!$task) {
  2551. continue;
  2552. }
  2553. // 如果任务还在处理中,查询最新状态
  2554. if ($task->status === 'processing') {
  2555. // 根据任务类型查询不同的状态
  2556. if ($task->api_type === 'jimeng') {
  2557. $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
  2558. } elseif ($task->api_type === 'keling') {
  2559. $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
  2560. } elseif ($task->api_type === 'zzengine') {
  2561. $statusResult = $this->AIVideoGenerationService->queryUnifiedApiTaskStatus($task);
  2562. } else {
  2563. $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
  2564. }
  2565. if (isset($statusResult['status'])) {
  2566. // 更新任务状态
  2567. $task->update([
  2568. 'status' => $statusResult['status'],
  2569. 'result_json' => $statusResult['result_json'] ?? [],
  2570. 'result_url' => $statusResult['result_url'] ?? null,
  2571. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  2572. 'error_message' => $statusResult['error_message'] ?? null,
  2573. 'completed_at' => in_array($statusResult['status'], [
  2574. 'success',
  2575. 'failed'
  2576. ]) ? now() : null
  2577. ]);
  2578. // 如果任务成功,更新分镜表
  2579. if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
  2580. try {
  2581. DB::beginTransaction();
  2582. $now = date('Y-m-d H:i:s');
  2583. // 获取分镜ID
  2584. $actId = null;
  2585. foreach ($actTasks as $actTask) {
  2586. if ($actTask['task_id'] == $taskId) {
  2587. $actId = $actTask['act_id'];
  2588. $content = $actTask['content'];
  2589. $audio_duration = $actTask['audio_duration'];
  2590. break;
  2591. }
  2592. }
  2593. if ($actId) {
  2594. // 更新分镜表
  2595. $actUpdateData = [
  2596. 'origin_video_url' => $statusResult['result_url'],
  2597. 'video_task_status' => '已完成',
  2598. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  2599. 'current_type' => 2,
  2600. 'updated_at' => $now
  2601. ];
  2602. $compressed_video_url = compressVideo($statusResult['result_url']);
  2603. $actUpdateData['video_url'] = $compressed_video_url ?: $statusResult['result_url'];
  2604. // 只有当video_duration存在且大于0时才更新
  2605. if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
  2606. $actUpdateData['video_duration'] = $statusResult['video_duration'];
  2607. $actUpdateData['video_time_point_start'] = 0;
  2608. $actUpdateData['video_time_point_end'] = $statusResult['video_duration'];
  2609. }
  2610. $updateResult = DB::table('mp_episode_segments')
  2611. ->where('act_id', $actId)
  2612. ->update($actUpdateData);
  2613. if ($updateResult) {
  2614. // 更新分镜视频成功后新增对话记录
  2615. $records = [
  2616. [
  2617. 'uid' => $uid,
  2618. 'anime_id' => $animeId,
  2619. 'sequence' => $episodeNumber,
  2620. 'role' => 'user',
  2621. 'content' => '片段转视频',
  2622. 'act_id' => $actId,
  2623. 'video_url' => '',
  2624. 'created_at' => $now,
  2625. 'updated_at' => $now
  2626. ],
  2627. [
  2628. 'uid' => $uid,
  2629. 'anime_id' => $animeId,
  2630. 'sequence' => $episodeNumber,
  2631. 'role' => 'assistant',
  2632. 'content' => $content ?? '',
  2633. 'act_id' => $actId,
  2634. 'video_url' => $statusResult['result_url'],
  2635. 'created_at' => $now,
  2636. 'updated_at' => $now
  2637. ]
  2638. ];
  2639. DB::table('mp_anime_records')->insert($records);
  2640. }
  2641. }
  2642. DB::commit();
  2643. } catch (\Exception $e) {
  2644. DB::rollBack();
  2645. $logData = [
  2646. 'task_id' => $taskId,
  2647. 'error' => $e->getMessage()
  2648. ];
  2649. dLog('anime')->error('视频任务处理失败', $logData);
  2650. logDB('anime', 'error', '视频任务处理失败', $logData);
  2651. }
  2652. } elseif ($statusResult['status'] === 'failed') {
  2653. // 获取分镜ID并更新失败状态
  2654. foreach ($actTasks as $actTask) {
  2655. if ($actTask['task_id'] == $taskId) {
  2656. DB::table('mp_episode_segments')
  2657. ->where('act_id', $actTask['act_id'])
  2658. ->update([
  2659. 'video_task_status' => '失败',
  2660. 'updated_at' => date('Y-m-d H:i:s')
  2661. ]);
  2662. break;
  2663. }
  2664. }
  2665. }
  2666. }
  2667. }
  2668. // 检查任务是否完成(成功或失败)
  2669. if (in_array($task->status, ['success', 'failed'])) {
  2670. $completeTasks[] = $taskId;
  2671. $hasUpdate = true;
  2672. if ($task->status === 'success') {
  2673. $successTasks[] = $taskId;
  2674. }
  2675. }
  2676. }
  2677. // 如果有更新,发送update通知
  2678. if ($hasUpdate) {
  2679. echo "data: " . json_encode([
  2680. 'type' => 'update',
  2681. 'total_tasks_count' => count($totalTasks),
  2682. 'completed_tasks_count' => count($completeTasks),
  2683. 'success_tasks_count' => count($successTasks)
  2684. ]) . "\n\n";
  2685. ob_flush();
  2686. flush();
  2687. }
  2688. // 如果所有任务都完成了,结束连接
  2689. if (count($completeTasks) >= count($totalTasks)) {
  2690. // 重新获取完整的剧集信息
  2691. $updatedEpisode = $this->AnimeService->episodeInfoForAce([
  2692. 'anime_id' => $animeId,
  2693. 'episode_id' => $episodeId
  2694. ]);
  2695. echo "data: " . json_encode([
  2696. 'type' => 'completed',
  2697. 'total_tasks_count' => count($totalTasks),
  2698. 'completed_tasks_count' => count($completeTasks),
  2699. 'success_tasks_count' => count($successTasks),
  2700. 'episode' => $updatedEpisode
  2701. ]) . "\n\n";
  2702. ob_flush();
  2703. flush();
  2704. break;
  2705. }
  2706. // 检查是否超时
  2707. if (time() - $startTime >= $maxDuration) {
  2708. break;
  2709. }
  2710. sleep($checkInterval);
  2711. } catch (\Exception $e) {
  2712. echo "data: " . json_encode([
  2713. 'type' => 'error',
  2714. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  2715. 'total_tasks_count' => count($totalTasks),
  2716. 'completed_tasks_count' => count($completeTasks),
  2717. 'success_tasks_count' => count($successTasks)
  2718. ]) . "\n\n";
  2719. ob_flush();
  2720. flush();
  2721. // 检查是否超时,如果超时则停止循环
  2722. if (time() - $startTime >= $maxDuration) {
  2723. break;
  2724. }
  2725. sleep($checkInterval);
  2726. }
  2727. }
  2728. // 超时处理
  2729. if (time() - $startTime >= $maxDuration) {
  2730. echo "data: " . json_encode([
  2731. 'type' => 'time_out',
  2732. 'message' => '批量视频生成已超时,停止状态查询',
  2733. 'total_tasks_count' => count($totalTasks),
  2734. 'completed_tasks_count' => count($completeTasks),
  2735. 'success_tasks_count' => count($successTasks)
  2736. ]) . "\n\n";
  2737. ob_flush();
  2738. flush();
  2739. }
  2740. }, 200, [
  2741. 'Content-Type' => 'text/event-stream',
  2742. 'Cache-Control' => 'no-cache',
  2743. 'Connection' => 'keep-alive',
  2744. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  2745. ]);
  2746. }
  2747. }