AnimeController.php 153 KB

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