AnimeController.php 151 KB

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