AnimeController.php 141 KB

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