AnimeController.php 140 KB

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