AnimeService.php 520 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Exceptions\ApiException;
  6. use App\Facade\Site;
  7. use App\Libs\Utils;
  8. use App\Models\MpGeneratePicTask;
  9. use App\Models\MpTaskCenter;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use App\Services\AIGeneration\AIVideoGenerationService;
  12. use App\Services\DeepSeek\DeepSeekService;
  13. use App\Services\PointsService;
  14. use App\Services\TaskCenterService;
  15. use Dflydev\DotAccessData\Util;
  16. use GuzzleHttp\Client;
  17. use Illuminate\Support\Facades\DB;
  18. use Illuminate\Support\Facades\Log;
  19. use Illuminate\Support\Facades\Redis;
  20. use OSS\Core\OssException;
  21. use OSS\OssClient;
  22. use PhpOffice\PhpSpreadsheet\IOFactory;
  23. class AnimeService
  24. {
  25. protected $aiImageGenerationService;
  26. protected $aiVideoGenerationService;
  27. protected $DeepSeekService;
  28. protected $pointsService;
  29. protected $taskCenterService;
  30. private $url;
  31. private $api_key;
  32. private $headers;
  33. public function __construct(
  34. AIImageGenerationService $aiImageGenerationService,
  35. AIVideoGenerationService $aiVideoGenerationService,
  36. DeepSeekService $DeepSeekService,
  37. PointsService $pointsService,
  38. TaskCenterService $taskCenterService
  39. ) {
  40. $this->aiImageGenerationService = $aiImageGenerationService;
  41. $this->aiVideoGenerationService = $aiVideoGenerationService;
  42. $this->DeepSeekService = $DeepSeekService;
  43. $this->pointsService = $pointsService;
  44. $this->taskCenterService = $taskCenterService;
  45. $this->url = 'https://api.deepseek.com/chat/completions';
  46. $this->api_key = env('DEEPSEEK_API_KEY');
  47. $this->headers = [
  48. 'Authorization' => 'Bearer '.$this->api_key,
  49. 'Content-Type' => 'application/json; charset=UTF-8'
  50. ];
  51. }
  52. /**
  53. * 构建统一的分镜数据结构(episodeInfo格式)
  54. * @param array $segments 分镜数据数组
  55. * @return array 返回包含acts和total_duration的数组
  56. */
  57. public function buildEpisodeSegmentsStructure($segments) {
  58. $acts = [];
  59. $totalDuration = 0; // 初始化总时长
  60. foreach($segments as $segment) {
  61. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  62. $videoDuration = getProp($segment, 'video_duration');
  63. $audioDuration = getProp($segment, 'audio_duration');
  64. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  65. $totalDuration += floatval($videoDuration);
  66. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  67. $totalDuration += floatval($audioDuration);
  68. } else {
  69. $totalDuration += 5; // 默认5秒
  70. }
  71. $segment_content = getProp($segment, 'segment_content');
  72. // 判断是否有尾帧描述,如果有则去掉这部分内容
  73. if (strpos($segment_content, '尾帧') !== false) {
  74. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  75. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  76. }
  77. // 构建分镜信息
  78. $segmentInfo = [
  79. 'segment_id' => getProp($segment, 'segment_id'),
  80. 'segment_number' => getProp($segment, 'segment_number'),
  81. 'segment_content' => $segment_content,
  82. 'description' => getProp($segment, 'description'),
  83. 'composition' => getProp($segment, 'composition'),
  84. 'camera_movement' => getProp($segment, 'camera_movement'),
  85. 'voice_actor' => getProp($segment, 'voice_actor'),
  86. 'dialogue' => getProp($segment, 'dialogue'),
  87. 'frame_type' => getProp($segment, 'frame_type'),
  88. 'scene' => getProp($segment, 'scene'),
  89. 'characters' => getProp($segment, 'characters'),
  90. 'tail_frame' => getProp($segment, 'tail_frame'),
  91. 'emotion' => getProp($segment, 'emotion'),
  92. 'emotion_type' => getProp($segment, 'emotion_type'),
  93. 'gender' => getProp($segment, 'gender'),
  94. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  95. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  96. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  97. 'pitch' => getProp($segment, 'pitch'),
  98. 'voice_name' => getProp($segment, 'voice_name'),
  99. 'voice_type' => getProp($segment, 'voice_type'),
  100. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  101. 'img_url' => getProp($segment, 'img_url'),
  102. 'audio_url' => getProp($segment, 'audio_url'),
  103. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  104. 'video_url' => getProp($segment, 'video_url'),
  105. 'video_duration' => getProp($segment, 'video_duration', 0),
  106. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  107. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  108. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  109. 'current_type' => getProp($segment, 'current_type'),
  110. ];
  111. $actNumber = getProp($segment, 'act_number');
  112. if (isset($acts[$actNumber])) {
  113. $acts[$actNumber]['segments'][] = $segmentInfo;
  114. } else {
  115. $acts[$actNumber] = [
  116. 'act_number' => $actNumber,
  117. 'act_title' => getProp($segment, 'act_title'),
  118. 'act_duration' => getProp($segment, 'act_duration'),
  119. 'segments' => [$segmentInfo]
  120. ];
  121. }
  122. }
  123. return [
  124. 'acts' => array_values($acts),
  125. 'total_duration' => intval(round($totalDuration))
  126. ];
  127. }
  128. /**
  129. * 构建统一的分段数据结构(episodeInfoForAce格式)
  130. * @param array $segments 分段数据数组
  131. * @return array 返回包含acts和total_duration的数组
  132. */
  133. public function buildEpisodeActsStructureForAce($segments) {
  134. $acts = [];
  135. $totalDuration = 0; // 初始化总时长
  136. foreach($segments as $segment) {
  137. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  138. $videoDuration = getProp($segment, 'video_duration');
  139. $actDuration = getProp($segment, 'act_duration');
  140. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  141. $totalDuration += floatval($videoDuration);
  142. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  143. $totalDuration += floatval($actDuration);
  144. } else {
  145. $totalDuration += 5; // 默认5秒
  146. }
  147. // 构建分镜信息
  148. $segmentInfo = [
  149. 'act_id' => getProp($segment, 'id'),
  150. 'act_number' => getProp($segment, 'act_number'),
  151. 'act_title' => getProp($segment, 'act_title'),
  152. 'act_duration' => getProp($segment, 'act_duration'),
  153. 'act_content' => getProp($segment, 'act_content'),
  154. 'video_url' => getProp($segment, 'video_url'),
  155. 'video_duration' => getProp($segment, 'video_duration', 0),
  156. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  157. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  158. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  159. 'current_type' => getProp($segment, 'current_type'),
  160. ];
  161. $acts[] = $segmentInfo;
  162. }
  163. return [
  164. 'acts' => array_values($acts),
  165. 'total_duration' => intval(round($totalDuration))
  166. ];
  167. }
  168. /**
  169. * 验证画面比例是否有效
  170. * @param string $ratio 画面比例
  171. * @return bool
  172. */
  173. public function validateRatio($ratio) {
  174. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  175. }
  176. /**
  177. * 获取画面比例对应的宽高
  178. * @param string $ratio 画面比例
  179. * @return array ['width' => int, 'height' => int]
  180. * @throws \Exception
  181. */
  182. private function getRatioDimensions($ratio) {
  183. if ($ratio && !$this->validateRatio($ratio)) {
  184. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  185. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  186. }
  187. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  188. }
  189. public function createAnime($data) {
  190. $uid = Site::getUid();
  191. $cpid = Site::getCpid();
  192. $input_art_style = getProp($data, 'art_style');
  193. $file = getProp($data, 'file');
  194. $content = getProp($data, 'content', '');
  195. $bid = getProp($data, 'bid', 0);
  196. $script_id = getProp($data, 'script_id', 0);
  197. $ace_mode = getProp($data, 'ace_mode', 0);
  198. $extra_products = getProp($data, 'products', []);
  199. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  200. if (!is_array($extra_products)) {
  201. Utils::throwError('20003:传入的资产格式不正确');
  202. }
  203. // 替换美术风格
  204. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  205. // 提取文件内容
  206. if ($file) {
  207. $content = $this->DeepSeekService->extractFileContent($file);
  208. if (!$content) {
  209. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  210. }
  211. } elseif ($script_id) {
  212. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  213. if (!$content) {
  214. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  215. }
  216. } elseif ($bid) {
  217. $content = $this->DeepSeekService->getContentByBid($bid);
  218. if (!$content) {
  219. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  220. }
  221. } elseif ($content) {
  222. $content = filterContent($content);
  223. }else {
  224. $content = '';
  225. }
  226. $anime_data = [
  227. 'user_id' => $uid,
  228. 'cpid' => $cpid,
  229. 'anime_name' => '新剧本策划',
  230. 'is_multi' => getProp($data, 'is_multi', 1),
  231. 'content' => $content,
  232. 'art_style_type' => $input_art_style,
  233. 'ace_mode' => $ace_mode,
  234. 'script_id' => $script_id,
  235. 'extra_products' => json_encode($extra_products, 256),
  236. 'created_at' => date('Y-m-d H:i:s'),
  237. 'updated_at' => date('Y-m-d H:i:s'),
  238. ];
  239. // 处理文本模型
  240. $model = getProp($data, 'model');
  241. if (!$model) {
  242. // 用户没有输入,使用默认值
  243. $model = 'deepseek-v4-pro';
  244. }
  245. // 验证模型是否在可用模型表中
  246. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  247. $model = 'deepseek-v4-pro';
  248. }
  249. $anime_data['model'] = $model;
  250. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  251. return DB::table('mp_animes')->insertGetId($anime_data);
  252. }
  253. public function chatList($data) {
  254. $uid = Site::getUid();
  255. $anime_name = getProp($data, 'anime_name');
  256. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  257. if ($anime_name) {
  258. $query->where('anime_name', 'like', "%$anime_name%");
  259. }
  260. return $query->orderBy('id', 'desc')->paginate();
  261. }
  262. public function chatHistory($data) {
  263. $anime_id = getProp($data, 'anime_id');
  264. $sequence = getProp($data, 'sequence', 0);
  265. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  266. $query = DB::table('mp_anime_records as ar')->leftJoin('mp_anime_episodes as ae', 'ar.episode_id', '=', 'ae.id')->where('ar.anime_id', $anime_id)
  267. ->where('ar.sequence', $sequence)->where('segment_id', 0)->where('act_id', 0)->select('ar.role', 'ar.content', 'ar.created_at', 'ar.episode_id', 'ae.title as episode_title', 'ae.created_at as episode_created_at');
  268. return $query->orderBy('ar.id')->get()->map(function ($value) {
  269. $value = (array)$value;
  270. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  271. $value['created_at'] = transDate($value['created_at']);
  272. $value['episode_created_at'] = transDate($value['episode_created_at']);
  273. return $value;
  274. })->toArray();
  275. }
  276. public function batchSetRoleImg($data) {
  277. $episode_id = getProp($data, 'episode_id');
  278. if (!$episode_id) Utils::throwError('1002:请选择分集');
  279. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  280. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  281. $art_style = getProp($episode, 'art_style');
  282. $anime_id = getProp($episode, 'anime_id');
  283. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  284. $art_style_type = getProp($anime, 'art_style_type');
  285. $character_prefix = '';
  286. $scene_prefix = '';
  287. if ($art_style_type) {
  288. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  289. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  290. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  291. }
  292. foreach ($roles as &$role) {
  293. $role_name = getProp($role, 'role');
  294. if ($role_name == '旁白') continue;
  295. // 优先使用 pic_prompt,如果没有则使用 description
  296. $pic_prompt = getProp($role, 'pic_prompt');
  297. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  298. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  299. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  300. // 参考图地址
  301. $ref_img_url = getProp($role, 'url');
  302. if ($ref_img_url) continue; // 已有图片则跳过
  303. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  304. try {
  305. $params = [
  306. 'prompt' => $description,
  307. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  308. ];
  309. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  310. $task_id = $task->id;
  311. if (!$task_id) {
  312. Utils::throwError("20003:角色({$role_name})生成图片失败");
  313. }
  314. $role['task_id'] = $task_id;
  315. $role['task_status'] = 'processing';
  316. } catch (\Exception $e) {
  317. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  318. Utils::throwError("20003:" . $e->getMessage());
  319. }
  320. }
  321. // 保存角色信息
  322. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  323. 'roles' => json_encode($roles, 256),
  324. 'generate_status' => '执行中',
  325. 'generate_at' => date('Y-m-d H:i:s'),
  326. 'updated_at' => date('Y-m-d H:i:s')
  327. ]);
  328. if (!$boolen) {
  329. Utils::throwError('20003:保存角色信息失败');
  330. }
  331. return $boolen;
  332. }
  333. public function batchSetSceneImg($data) {
  334. $episode_id = getProp($data, 'episode_id');
  335. if (!$episode_id) Utils::throwError('1002:请选择分集');
  336. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  337. $scenes = json_decode(getProp($episode, 'scenes'), true);
  338. $art_style = getProp($episode, 'art_style');
  339. $target_scene = getProp($data, 'target_scene');
  340. $anime_id = getProp($episode, 'anime_id');
  341. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  342. $art_style_type = getProp($anime, 'art_style_type');
  343. $character_prefix = '';
  344. $scene_prefix = '';
  345. if ($art_style_type) {
  346. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  347. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  348. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  349. }
  350. foreach ($scenes as &$scene) {
  351. $scene_name = getProp($scene, 'scene');
  352. if ($scene_name != $target_scene) continue;
  353. // 优先使用 pic_prompt,如果没有则使用 description
  354. $pic_prompt = getProp($scene, 'pic_prompt');
  355. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  356. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  357. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  358. // 参考图地址
  359. $ref_img_url = getProp($scene, 'url');
  360. if ($ref_img_url) continue; // 已有图片则跳过
  361. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  362. try {
  363. $params = [
  364. 'prompt' => $description,
  365. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  366. ];
  367. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  368. $task_id = $task->id;
  369. if (!$task_id) {
  370. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  371. }
  372. $scene['task_id'] = $task_id;
  373. $scene['task_status'] = 'processing';
  374. } catch (\Exception $e) {
  375. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  376. Utils::throwError("20003:" . $e->getMessage());
  377. }
  378. }
  379. // 保存场景信息
  380. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  381. 'scenes' => json_encode($scenes, 256),
  382. 'generate_status' => '执行中',
  383. 'generate_at' => date('Y-m-d H:i:s'),
  384. 'updated_at' => date('Y-m-d H:i:s')
  385. ]);
  386. if (!$boolen) {
  387. Utils::throwError('20003:保存角色信息失败');
  388. }
  389. return $boolen;
  390. }
  391. public function editAnime($data) {
  392. $anime_id = getProp($data, 'anime_id');
  393. $anime_name = trim(getProp($data, 'anime_name'));
  394. // 确认对话名称唯一性
  395. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  396. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  397. }
  398. if (!$anime_id || !$anime_name) {
  399. Utils::throwError('20003:参数异常');
  400. }
  401. return DB::table('mp_animes')->where('id', $anime_id)->update([
  402. 'anime_name' => $anime_name,
  403. 'updated_at' => date('Y-m-d H:i:s')
  404. ]);
  405. // $script_arr =getProp($data, 'script', []);
  406. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  407. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  408. // $anime_id = getProp($data, 'anime_id');
  409. // try {
  410. // DB::beginTransaction();
  411. // $table_data = [
  412. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  413. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  414. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  415. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  416. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  417. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  418. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  419. // 'status' => 3,
  420. // 'start_episode_sequence' => $start_episode_sequence,
  421. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  422. // 'episode_num' => count($script_arr['episodes']),
  423. // 'updated_at' => date('Y-m-d H:i:s')
  424. // ];
  425. // // 保存剧本内容
  426. // if (!empty($anime_id)) {
  427. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  428. // if (!$boolen) {
  429. // dLog('anime')->info('对话保存失败', $table_data);
  430. // Utils::throwError('20003:对话保存失败');
  431. // }
  432. // }else {
  433. // $table['created_at'] = $table_data['updated_at'];
  434. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  435. // if (!$anime_id) {
  436. // dLog('anime')->info('对话保存失败', $table_data);
  437. // Utils::throwError('20003:对话保存失败');
  438. // }
  439. // }
  440. // // 保存分集内容
  441. // // 删除历史分集内容
  442. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  443. // $episodes = [];
  444. // $sequence = 1;
  445. // foreach ($script_arr['episodes'] as $episode) {
  446. // $segment_number = 1;
  447. // foreach($episode['segments'] as $segment) {
  448. // $episodes[] = [
  449. // 'anime_id' => $anime_id,
  450. // 'episode_number' => $episode['episode_number'],
  451. // 'title' => $episode['title'],
  452. // // 'content' => $episode['content'],
  453. // 'content' => '',
  454. // 'segment_number' => $segment_number,
  455. // 'segment_content' => $segment['segment_content'],
  456. // 'sequence' => $sequence,
  457. // 'created_at' => date('Y-m-d H:i:s'),
  458. // 'updated_at' => date('Y-m-d H:i:s')
  459. // ];
  460. // $sequence++;
  461. // $segment_number++;
  462. // }
  463. // }
  464. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  465. // if (!$boolen2) {
  466. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  467. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  468. // Utils::throwError('20003:分集内容保存失败');
  469. // }
  470. // } catch (\Exception $e) {
  471. // DB::rollBack();
  472. // Utils::throwError('20003:'.$e->getMessage());
  473. // }
  474. // DB::commit();
  475. // return true;
  476. }
  477. public function delAnime($data) {
  478. $anime_id = getProp($data, 'anime_id');
  479. if (!$anime_id) {
  480. Utils::throwError('20003:请选择剧本');
  481. }
  482. return DB::table('mp_animes')->where('id', $anime_id)->update([
  483. 'is_deleted' => 1,
  484. 'updated_at' => date('Y-m-d H:i:s')
  485. ]);
  486. }
  487. public function animeDetail($data) {
  488. $uid = Site::getUid();
  489. $anime_id = getProp($data, 'anime_id');
  490. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  491. ->selectRaw('id as anime_id, anime_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, remark, generate_status, created_at, ace_mode, end_episode_sequence')->first();
  492. if (!$anime) Utils::throwError('20003:权限不足');
  493. $anime = (array)$anime;
  494. $anime['roles'] = json_decode($anime['roles']);
  495. $anime['scenes'] = json_decode($anime['scenes']);
  496. // 获取分集信息
  497. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  498. ->select('id as episode_id', 'episode_number', 'title', 'is_generated', DB::raw("(select es.img_url from mp_episode_segments as es where es.episode_id = mp_anime_episodes.id order by es.segment_number limit 1) as first_frame_url"))
  499. ->orderBy('episode_number')->get()->map(function ($value) {
  500. return (array)$value;
  501. })->toArray();
  502. $anime['episodes'] = $episodes;
  503. // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
  504. $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
  505. $episodeTasks = DB::table('mp_batch_episode_generation_details')
  506. ->where('anime_id', $anime_id)
  507. ->whereIn('status', ['pending', 'processing', 'failed']) // 只获取待生成/生成中任务,已完成或失败的不显示
  508. ->orderBy('episode_number')
  509. ->get()
  510. ->map(function ($task) use ($episodeNumbers) {
  511. if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
  512. return null;
  513. }
  514. return [
  515. 'episode_number' => (int)$task->episode_number,
  516. 'status' => $task->status,
  517. 'error_message' => $task->status == 'failed' ? $task->error_message : '',
  518. ];
  519. })
  520. ->filter()
  521. ->values()
  522. ->toArray();
  523. $anime['episode_tasks'] = $episodeTasks;
  524. return $anime;
  525. }
  526. public function episodeInfo($data) {
  527. $uid = Site::getUid();
  528. $anime_id = getProp($data, 'anime_id');
  529. $episode_id = getProp($data, 'episode_id');
  530. if (!$anime_id || !$episode_id) {
  531. Utils::throwError('1002:请选择剧集');
  532. }
  533. // 验证用户权限
  534. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  535. if (!$anime) Utils::throwError('20003:权限不足');
  536. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->first();
  537. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  538. $episode = (array)$episode;
  539. $episode['roles'] = json_decode($episode['roles'], true);
  540. // foreach($episode['roles'] as &$item) {
  541. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  542. // }
  543. $episode['scenes'] = json_decode($episode['scenes'], true);
  544. // foreach($episode['scenes'] as &$item) {
  545. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  546. // }
  547. // 获取分镜信息
  548. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  549. ->select('*')->get()->map(function ($value) {
  550. return (array)$value;
  551. })->toArray();
  552. // 使用公共方法构建分镜结构
  553. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  554. $episode['acts'] = $segmentsStructure['acts'];
  555. $episode['total_duration'] = $segmentsStructure['total_duration'];
  556. return $episode;
  557. }
  558. public function episodeInfoForAce($data) {
  559. $anime_id = getProp($data, 'anime_id');
  560. $episode_id = getProp($data, 'episode_id');
  561. if (!$anime_id || !$episode_id) {
  562. Utils::throwError('1002:请选择剧集');
  563. }
  564. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'props', 'is_generated')->first();
  565. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  566. $episode = (array)$episode;
  567. $episode['roles'] = json_decode($episode['roles'], true);
  568. // foreach($episode['roles'] as &$item) {
  569. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  570. // }
  571. $episode['scenes'] = json_decode($episode['scenes'], true);
  572. // foreach($episode['scenes'] as &$item) {
  573. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  574. // }
  575. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  576. // 获取分镜信息
  577. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  578. ->select('*')->get()->map(function ($value) {
  579. return (array)$value;
  580. })->toArray();
  581. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  582. $episode['acts'] = $segmentsStructure['acts'];
  583. $episode['total_duration'] = $segmentsStructure['total_duration'];
  584. // 获取mp_animes表中的视频参数
  585. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  586. $episode['video_params'] = [
  587. 'video_model' => getProp($anime, 'video_model'),
  588. 'video_resolution' => getProp($anime, 'video_resolution'),
  589. 'ratio' => getProp($anime, 'video_ratio'),
  590. ];
  591. return $episode;
  592. }
  593. public function segmentInfo($data) {
  594. $uid = Site::getUid();
  595. $segment_id = getProp($data, 'segment_id');
  596. if (!$segment_id) {
  597. Utils::throwError('1002:请选择分镜');
  598. }
  599. // 获取分镜信息
  600. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  601. // 验证用户权限
  602. if ($segment) {
  603. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  604. if (!$anime) Utils::throwError('20003:权限不足');
  605. }
  606. $result = [
  607. 'segment_id' => getProp($segment, 'segment_id'),
  608. 'segment_number' => getProp($segment, 'segment_number'),
  609. 'segment_content' => getProp($segment, 'segment_content'),
  610. 'description' => getProp($segment, 'description'),
  611. 'composition' => getProp($segment, 'composition'),
  612. 'camera_movement' => getProp($segment, 'camera_movement'),
  613. 'voice_actor' => getProp($segment, 'voice_actor'),
  614. 'dialogue' => getProp($segment, 'dialogue'),
  615. 'frame_type' => getProp($segment, 'frame_type'),
  616. 'scene' => getProp($segment, 'scene'),
  617. 'characters' => getProp($segment, 'characters'),
  618. 'tail_frame' => getProp($segment, 'tail_frame'),
  619. 'emotion' => getProp($segment, 'emotion'),
  620. 'emotion_type' => getProp($segment, 'emotion_type'),
  621. 'gender' => getProp($segment, 'gender'),
  622. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  623. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  624. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  625. 'pitch' => getProp($segment, 'pitch'),
  626. 'voice_name' => getProp($segment, 'voice_name'),
  627. 'voice_type' => getProp($segment, 'voice_type'),
  628. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  629. 'img_url' => getProp($segment, 'img_url'),
  630. 'video_url' => getProp($segment, 'video_url'),
  631. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  632. ];
  633. return $result;
  634. }
  635. public function copyEpisodeVersion($data) {
  636. $episode_id = getProp($data, 'episode_id');
  637. $uid = Site::getUid();
  638. $cpid = Site::getCpid();
  639. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  640. if (!$episode) Utils::throwError('20003:该剧集不存在');
  641. $episode = (array)$episode;
  642. $anime_id = $episode['anime_id'];
  643. $episode_number = $episode['episode_number'];
  644. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  645. $sequence = $count + 1;
  646. unset($episode['id']);
  647. $now = date('Y-m-d H:i:s');
  648. $episode['created_at'] = $now;
  649. $episode['updated_at'] = $now;
  650. $episode['is_default'] = 1;
  651. // 获取版本中含有"(副本"字样的个数
  652. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  653. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  654. $episode['sequence'] = $sequence;
  655. $episode['is_generated'] = 0;
  656. $episode['cpid'] = $cpid;
  657. // 获取ace_mode
  658. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  659. try {
  660. DB::beginTransaction();
  661. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  662. // 新增副本
  663. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  664. if (!$new_episode_id) {
  665. Utils::throwError('20003:创建副本失败!');
  666. }
  667. // 获取分镜数据并准备插入
  668. $segments_for_insert = DB::table('mp_episode_segments')
  669. ->select('anime_id', 'episode_number', 'act_number', 'act_title', 'act_duration', 'act_content', 'segment_number', 'segment_content', 'description', 'composition', 'camera_movement', 'voice_actor', 'dialogue', 'frame_type', 'scene', 'characters', 'tail_frame', 'voice_name', 'voice_type', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  670. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  671. $item = (array)$item;
  672. $item['episode_id'] = $new_episode_id;
  673. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  674. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  675. return $item;
  676. })->toArray();
  677. // 写入分镜数据
  678. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  679. if (!$boolen2) {
  680. Utils::throwError('20003:写入分镜数据失败!');
  681. }
  682. // 写入对话历史
  683. $records = [
  684. [
  685. 'uid' => $uid,
  686. 'anime_id' => $anime_id,
  687. 'role' => 'user',
  688. 'content' => '创建副本',
  689. 'sequence' => $episode_number,
  690. 'episode_id' => $new_episode_id,
  691. 'created_at' => $now,
  692. 'updated_at' => $now
  693. ],
  694. [
  695. 'uid' => $uid,
  696. 'anime_id' => $anime_id,
  697. 'role' => 'assistant',
  698. 'content' => '好的,已为您创建副本',
  699. 'sequence' => $episode_number,
  700. 'episode_id' => $new_episode_id,
  701. 'created_at' => $now,
  702. 'updated_at' => $now
  703. ]
  704. ];
  705. $boolen3 = DB::table('mp_anime_records')->insert($records);
  706. if (!$boolen3) {
  707. Utils::throwError('20003:对话记录保存失败');
  708. }
  709. }catch (\Exception $e) {
  710. DB::rollBack();
  711. Utils::throwError('20003:'.$e->getMessage());
  712. }
  713. DB::commit();
  714. // 构建与 episodeInfo 方法一致的返回数据结构
  715. $result = [
  716. 'episode_id' => $new_episode_id,
  717. 'anime_id' => $anime_id,
  718. 'episode_number' => $episode_number,
  719. 'title' => $episode['title'],
  720. 'intro' => $episode['intro'],
  721. 'art_style' => $episode['art_style'],
  722. 'roles' => json_decode($episode['roles'], true),
  723. 'scenes' => json_decode($episode['scenes'], true),
  724. 'is_generated' => (int)$episode['is_generated']
  725. ];
  726. if ((int)$ace_mode === 1) {
  727. // 获取分镜信息
  728. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  729. ->select('*')->get()->map(function ($value) {
  730. return (array)$value;
  731. })->toArray();
  732. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  733. }else {
  734. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  735. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  736. }
  737. $result['acts'] = $segmentsStructure['acts'];
  738. $result['total_duration'] = $segmentsStructure['total_duration'];
  739. return $result;
  740. }
  741. public function episodeVersions($data) {
  742. $anime_id = getProp($data, 'anime_id');
  743. $episode_id = getProp($data, 'episode_id');
  744. if (!$anime_id || !$episode_id) {
  745. Utils::throwError('1002:请选择剧集');
  746. }
  747. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  748. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->select('id as episode_id', 'anime_id', 'episode_number', 'sequence', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->orderBy('sequence', 'desc')->get()->map(function($value) {
  749. return (array)$value;
  750. })->toArray();
  751. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  752. foreach($episodes as &$episode) {
  753. $episode['version'] = 'V'.$episode['sequence'];
  754. $episode['roles'] = json_decode($episode['roles'], true);
  755. $episode['scenes'] = json_decode($episode['scenes'], true);
  756. // 获取分镜信息
  757. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  758. ->select('*')->get()->map(function ($value) {
  759. return (array)$value;
  760. })->toArray();
  761. // 使用公共方法构建分镜结构
  762. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  763. $episode['acts'] = $segmentsStructure['acts'];
  764. $episode['total_duration'] = $segmentsStructure['total_duration'];
  765. }
  766. return $episodes;
  767. }
  768. public function bindEpisodeVersion($data) {
  769. $episode_id = getProp($data, 'episode_id');
  770. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  771. if (!$episode) Utils::throwError('20003:该剧集不存在');
  772. $episode = (array)$episode;
  773. if ((int)$episode['is_default'] === 1) return true;
  774. try {
  775. DB::beginTransaction();
  776. // 移除is_default标志
  777. $boolen = DB::table('mp_anime_episodes')->where('anime_id', $episode['anime_id'])->where('episode_number', $episode['episode_number'])->update(['is_default' => 0, 'updated_at'=>date('Y-m-d H:i:s')]);
  778. if (!$boolen) {
  779. Utils::throwError('20003:更新失败!');
  780. }
  781. // 绑定副本
  782. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  783. if (!$boolen2) {
  784. Utils::throwError('20003:绑定失败!');
  785. }
  786. }catch (\Exception $e) {
  787. DB::rollBack();
  788. Utils::throwError('20003:'.$e->getMessage());
  789. }
  790. DB::commit();
  791. return true;
  792. }
  793. public function chatChangeImg($data) {
  794. $segment_id = getProp($data, 'segment_id');
  795. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  796. $prompt = getProp($data, 'prompt');
  797. if (!$prompt || !$segment_id) {
  798. Utils::throwError('1002:请输入提示词,并且选择分镜');
  799. }
  800. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  801. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  802. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  803. else $ref_img_url = '';
  804. // $ref_img_url = '';
  805. if (empty($prompt)) {
  806. if (empty($ref_img_url)) {
  807. $prompt = getProp($segment, 'segment_content');
  808. }else {
  809. $prompt = '请根据图片生成';
  810. }
  811. }
  812. $anime_id = getProp($segment, 'anime_id');
  813. $episode_id = getProp($segment, 'episode_id');
  814. $episode_number = getProp($segment, 'episode_number');
  815. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  816. $ratio = getProp($data, 'ratio');
  817. if (!$ratio) {
  818. $ratio = getProp($episode, 'ratio');
  819. if (!$ratio) $ratio = '9:16';
  820. }
  821. $art_style = getProp($episode, 'art_style');
  822. if ($art_style) {
  823. $prompt = "美术风格:{$art_style}\n{$prompt}";
  824. }
  825. $dimensions = $this->getRatioDimensions($ratio);
  826. $width = $dimensions['width'];
  827. $height = $dimensions['height'];
  828. try {
  829. $params = [
  830. 'alias_segment_id' => $segment_id,
  831. 'prompt' => $prompt,
  832. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  833. 'width' => $width,
  834. 'height' => $height
  835. ];
  836. // 优化提示词(不要生成字幕)
  837. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  838. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  839. $task_id = $task->id;
  840. if (!$task_id) {
  841. Utils::throwError("20003:生成图片失败");
  842. }
  843. // 更新任务ID
  844. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update(['pic_task_id' => $task_id, 'pic_task_status' => '生成中', 'updated_at' => date('Y-m-d H:i:s')]);
  845. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  846. } catch (\Exception $e) {
  847. Utils::throwError("20003:" . $e->getMessage());
  848. }
  849. // 创建任务之后先暂停10s等待异步任务完成
  850. sleep(10);
  851. $img_url = $this->loopGetPicTaskResult($task_id);
  852. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  853. // 图片生成后新增对话记录
  854. try {
  855. $uid = Site::getUid();
  856. $now = date('Y-m-d H:i:s');
  857. // 使用AI反推图片提示词
  858. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  859. // 保存对话记录
  860. $records = [
  861. [
  862. 'uid' => $uid,
  863. 'anime_id' => $anime_id,
  864. 'sequence' => $episode_number,
  865. 'role' => 'user',
  866. 'content' => $prompt,
  867. 'segment_id' => $segment_id,
  868. 'pic_task_id' => $task_id,
  869. 'image_url' => '',
  870. 'created_at' => $now,
  871. 'updated_at' => $now
  872. ],
  873. [
  874. 'uid' => $uid,
  875. 'anime_id' => $anime_id,
  876. 'sequence' => $episode_number,
  877. 'role' => 'assistant',
  878. 'content' => $pic_prompt,
  879. 'segment_id' => $segment_id,
  880. 'pic_task_id' => $task_id,
  881. 'image_url' => $img_url,
  882. 'created_at' => $now,
  883. 'updated_at' => $now
  884. ]
  885. ];
  886. DB::table('mp_anime_records')->insert($records);
  887. } catch (\Exception $e) {
  888. // 记录日志但不影响主流程
  889. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  890. 'segment_id' => $segment_id,
  891. 'img_url' => $img_url
  892. ]);
  893. logDB('anime', 'error', '保存对话记录失败', [
  894. 'segment_id' => $segment_id,
  895. 'img_url' => $img_url,
  896. 'error' => $e->getMessage()
  897. ]);
  898. }
  899. return $img_url;
  900. }
  901. public function segmentChatHistory($data) {
  902. $segment_id = getProp($data, 'segment_id');
  903. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  904. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'video_task_id', 'pic_task_id', 'created_at');
  905. $chat = $query->orderBy('id')->get()->map(function ($value) {
  906. $value = (array)$value;
  907. $value['created_at'] = transDate($value['created_at']);
  908. return $value;
  909. })->toArray();
  910. // 获取历史图片
  911. $url = [];
  912. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  913. foreach($pic_history as $task) {
  914. $result_url = getProp($task, 'result_url');
  915. if (is_json($result_url)) {
  916. $url = array_merge($url, json_decode($result_url, true));
  917. }else {
  918. $url[] = $result_url;
  919. }
  920. }
  921. // 获取历史视频
  922. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  923. foreach($video_history as $task) {
  924. $result_url = getProp($task, 'compressed_url');
  925. if (is_json($result_url)) {
  926. $url = array_merge($url, json_decode($result_url, true));
  927. }else {
  928. $url[] = $result_url;
  929. }
  930. }
  931. return compact('chat', 'url');
  932. }
  933. public function changeEpisodeRoles($data) {
  934. $anime_id = getProp($data, 'anime_id');
  935. $episode_id = getProp($data, 'episode_id');
  936. $target_roles = getProp($data, 'roles');
  937. // 删除标志优先取最外层入参 is_deleted,兼容角色对象内部(roles.is_deleted)的传参
  938. $is_deleted = getProp($data, 'is_deleted', getProp($target_roles, 'is_deleted', 0));
  939. // 控制字段不随角色内容写入分集roles存储
  940. if (is_array($target_roles)) {
  941. unset($target_roles['is_deleted']);
  942. }
  943. // 参数验证
  944. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  945. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  946. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  947. // 验证剧集是否存在
  948. $episode = DB::table('mp_anime_episodes')
  949. ->where('anime_id', $anime_id)
  950. ->where('id', $episode_id)
  951. ->first();
  952. if (!$episode) Utils::throwError('20003:该剧集不存在');
  953. $roles = json_decode(getProp($episode, 'roles'), true);
  954. // 获取anime信息,检查是否有关联的script_id
  955. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  956. if (!$anime) Utils::throwError('20003:动漫不存在');
  957. $script_id = getProp($anime, 'script_id');
  958. $episode_number = getProp($episode, 'episode_number', 1);
  959. $uid = Site::getUid();
  960. $cpid = Site::getCpid();
  961. try {
  962. $target_role_name = getProp($target_roles, 'role');
  963. if (empty($target_role_name)) {
  964. Utils::throwError('20003:角色名称不能为空');
  965. }
  966. // 如果是删除操作
  967. if ($is_deleted == 1) {
  968. // 从角色列表中移除该角色
  969. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  970. return getProp($role, 'role') !== $target_role_name;
  971. }));
  972. // 更新角色列表
  973. $result = DB::table('mp_anime_episodes')
  974. ->where('anime_id', $anime_id)
  975. ->where('id', $episode_id)
  976. ->update([
  977. 'roles' => json_encode($roles, 256),
  978. 'updated_at' => date('Y-m-d H:i:s')
  979. ]);
  980. if ($result === false) {
  981. Utils::throwError('20003:删除角色失败');
  982. }
  983. } else {
  984. // 新增或更新操作
  985. $role_found = false;
  986. $is_new_role = false;
  987. // 查找并更新已存在的角色
  988. foreach($roles as &$role) {
  989. if (getProp($role, 'role') === $target_role_name) {
  990. $role = $target_roles;
  991. $role_found = true;
  992. break;
  993. }
  994. }
  995. // 如果角色不存在,则新增
  996. if (!$role_found) {
  997. $roles[] = $target_roles;
  998. $is_new_role = true;
  999. }
  1000. // 更新角色列表
  1001. $result = DB::table('mp_anime_episodes')
  1002. ->where('anime_id', $anime_id)
  1003. ->where('id', $episode_id)
  1004. ->update([
  1005. 'roles' => json_encode($roles, 256),
  1006. 'updated_at' => date('Y-m-d H:i:s')
  1007. ]);
  1008. if ($result === false) {
  1009. Utils::throwError('20003:更新角色列表失败');
  1010. }
  1011. // 同步更新分镜表中对应主体的音色信息
  1012. $voice_name = getProp($target_roles, 'voice_name');
  1013. $voice_type = getProp($target_roles, 'voice_type');
  1014. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  1015. DB::table('mp_episode_segments')
  1016. ->where('anime_id', $anime_id)
  1017. ->where('episode_id', $episode_id)
  1018. ->where('voice_actor', $target_role_name)
  1019. ->update([
  1020. 'voice_name' => $voice_name,
  1021. 'voice_type' => $voice_type,
  1022. 'voice_audio_url' => $voice_audio_url,
  1023. 'updated_at' => date('Y-m-d H:i:s')
  1024. ]);
  1025. // 如果有关联的script_id,则同步到mp_products表
  1026. if ($script_id) {
  1027. // 查询剧本信息
  1028. $script = DB::table('mp_scripts')
  1029. ->where('id', $script_id)
  1030. ->where('is_deleted', 0)
  1031. ->first();
  1032. if ($script) {
  1033. $script_name = $script->script_name ?? 'script_' . $script_id;
  1034. $product_name = getProp($target_roles, 'role');
  1035. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1036. $url = getProp($target_roles, 'url', '');
  1037. $product_type = 1; // 1=角色
  1038. // 查找或创建以script_name命名的文件夹
  1039. $folder = DB::table('mp_products')
  1040. ->where('cpid', $cpid)
  1041. ->where('type', 2) // 文件夹类型
  1042. ->where('product', $product_type) // 角色类型
  1043. ->where('product_name', $script_name)
  1044. ->where('parent_id', 0)
  1045. ->where('is_deleted', 0)
  1046. ->first();
  1047. if (!$folder) {
  1048. // 创建文件夹
  1049. $folder_id = DB::table('mp_products')->insertGetId([
  1050. 'user_id' => $uid,
  1051. 'cpid' => $cpid,
  1052. 'type' => 2, // 文件夹
  1053. 'product' => $product_type, // 角色类型
  1054. 'parent_id' => 0,
  1055. 'level' => 1,
  1056. 'product_name' => $script_name,
  1057. 'sort_order' => time(),
  1058. 'is_deleted' => 0,
  1059. 'created_at' => date('Y-m-d H:i:s'),
  1060. 'updated_at' => date('Y-m-d H:i:s')
  1061. ]);
  1062. } else {
  1063. $folder_id = $folder->id;
  1064. }
  1065. // 查找该文件夹下是否已存在同名资产
  1066. $existing_product = DB::table('mp_products')
  1067. ->where('cpid', $cpid)
  1068. ->where('type', 1) // 资产类型
  1069. ->where('product', $product_type)
  1070. ->where('parent_id', $folder_id)
  1071. ->where('product_name', $product_name)
  1072. ->where('is_deleted', 0)
  1073. ->first();
  1074. if ($existing_product) {
  1075. // 更新已存在的资产
  1076. $updateData = [
  1077. 'pic_task_status' => '生成成功',
  1078. ];
  1079. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1080. if ($url) $updateData['url'] = $url;
  1081. // 处理versions字段
  1082. $versions = getProp($target_roles, 'versions', []);
  1083. if ($versions && is_array($versions)) {
  1084. $updateData['versions'] = json_encode($versions, 256);
  1085. }
  1086. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1087. DB::table('mp_products')
  1088. ->where('id', $existing_product->id)
  1089. ->update($updateData);
  1090. $product_id = $existing_product->id;
  1091. } else {
  1092. // 创建新资产
  1093. $versions = getProp($target_roles, 'versions', []);
  1094. $product_id = DB::table('mp_products')->insertGetId([
  1095. 'user_id' => $uid,
  1096. 'cpid' => $cpid,
  1097. 'type' => 1, // 资产
  1098. 'product' => $product_type, // 角色
  1099. 'parent_id' => $folder_id,
  1100. 'level' => 2,
  1101. 'product_name' => $product_name,
  1102. 'url' => $url,
  1103. 'pic_prompt' => $pic_prompt,
  1104. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1105. 'sort_order' => time(),
  1106. 'is_deleted' => 0,
  1107. 'pic_task_status' => '生成成功',
  1108. 'created_at' => date('Y-m-d H:i:s'),
  1109. 'updated_at' => date('Y-m-d H:i:s')
  1110. ]);
  1111. }
  1112. // 建立或更新绑定关系
  1113. $existing_mapping = DB::table('mp_script_product_mappings')
  1114. ->where('script_id', $script_id)
  1115. ->where('product_id', $product_id)
  1116. ->where('episode_number', $episode_number)
  1117. ->first();
  1118. if (!$existing_mapping) {
  1119. // 创建绑定关系
  1120. DB::table('mp_script_product_mappings')->insert([
  1121. 'script_id' => $script_id,
  1122. 'product_id' => $product_id,
  1123. 'episode_number' => $episode_number,
  1124. 'created_at' => date('Y-m-d H:i:s'),
  1125. 'updated_at' => date('Y-m-d H:i:s')
  1126. ]);
  1127. }
  1128. }
  1129. }
  1130. }
  1131. } catch (\Exception $e) {
  1132. dLog('anime')->error('更新剧集角色失败', [
  1133. 'anime_id' => $anime_id,
  1134. 'episode_id' => $episode_id,
  1135. 'error' => $e->getMessage()
  1136. ]);
  1137. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1138. }
  1139. return true;
  1140. }
  1141. public function changeEpisodeScenes($data) {
  1142. $anime_id = getProp($data, 'anime_id');
  1143. $episode_id = getProp($data, 'episode_id');
  1144. $target_scenes = getProp($data, 'scenes');
  1145. // 删除标志优先取最外层入参 is_deleted,兼容场景对象内部(scenes.is_deleted)的传参
  1146. $is_deleted = getProp($data, 'is_deleted', getProp($target_scenes, 'is_deleted', 0));
  1147. // 控制字段不随场景内容写入分集scenes存储
  1148. if (is_array($target_scenes)) {
  1149. unset($target_scenes['is_deleted']);
  1150. }
  1151. // 参数验证
  1152. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1153. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1154. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1155. // 验证剧集是否存在
  1156. $episode = DB::table('mp_anime_episodes')
  1157. ->where('anime_id', $anime_id)
  1158. ->where('id', $episode_id)
  1159. ->first();
  1160. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1161. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1162. // 获取anime信息,检查是否有关联的script_id
  1163. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1164. if (!$anime) Utils::throwError('20003:动漫不存在');
  1165. $script_id = getProp($anime, 'script_id');
  1166. $episode_number = getProp($episode, 'episode_number', 1);
  1167. $uid = Site::getUid();
  1168. $cpid = Site::getCpid();
  1169. try {
  1170. $target_scene_name = getProp($target_scenes, 'scene');
  1171. if (empty($target_scene_name)) {
  1172. Utils::throwError('20003:场景名称不能为空');
  1173. }
  1174. // 如果是删除操作
  1175. if ($is_deleted == 1) {
  1176. // 从场景列表中移除该场景
  1177. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1178. return getProp($scene, 'scene') !== $target_scene_name;
  1179. }));
  1180. // 更新场景列表
  1181. $result = DB::table('mp_anime_episodes')
  1182. ->where('anime_id', $anime_id)
  1183. ->where('id', $episode_id)
  1184. ->update([
  1185. 'scenes' => json_encode($scenes, 256),
  1186. 'updated_at' => date('Y-m-d H:i:s')
  1187. ]);
  1188. if ($result === false) {
  1189. Utils::throwError('20003:删除场景失败');
  1190. }
  1191. } else {
  1192. // 新增或更新操作
  1193. $scene_found = false;
  1194. $is_new_scene = false;
  1195. // 查找并更新已存在的场景
  1196. foreach($scenes as &$scene) {
  1197. if (getProp($scene, 'scene') === $target_scene_name) {
  1198. $scene = $target_scenes;
  1199. $scene_found = true;
  1200. break;
  1201. }
  1202. }
  1203. // 如果场景不存在,则新增
  1204. if (!$scene_found) {
  1205. $scenes[] = $target_scenes;
  1206. $is_new_scene = true;
  1207. }
  1208. // 更新场景列表
  1209. $result = DB::table('mp_anime_episodes')
  1210. ->where('anime_id', $anime_id)
  1211. ->where('id', $episode_id)
  1212. ->update([
  1213. 'scenes' => json_encode($scenes, 256),
  1214. 'updated_at' => date('Y-m-d H:i:s')
  1215. ]);
  1216. if ($result === false) {
  1217. Utils::throwError('20003:更新场景列表失败');
  1218. }
  1219. // 如果有关联的script_id,则同步到mp_products表
  1220. if ($script_id) {
  1221. // 查询剧本信息
  1222. $script = DB::table('mp_scripts')
  1223. ->where('id', $script_id)
  1224. ->where('is_deleted', 0)
  1225. ->first();
  1226. if ($script) {
  1227. $script_name = $script->script_name ?? 'script_' . $script_id;
  1228. $product_name = getProp($target_scenes, 'scene');
  1229. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1230. $url = getProp($target_scenes, 'url', '');
  1231. $product_type = 2; // 2=场景
  1232. // 查找或创建以script_name命名的文件夹
  1233. $folder = DB::table('mp_products')
  1234. ->where('cpid', $cpid)
  1235. ->where('type', 2) // 文件夹类型
  1236. ->where('product', $product_type) // 场景类型
  1237. ->where('product_name', $script_name)
  1238. ->where('parent_id', 0)
  1239. ->where('is_deleted', 0)
  1240. ->first();
  1241. if (!$folder) {
  1242. // 创建文件夹
  1243. $folder_id = DB::table('mp_products')->insertGetId([
  1244. 'user_id' => $uid,
  1245. 'cpid' => $cpid,
  1246. 'type' => 2, // 文件夹
  1247. 'product' => $product_type, // 场景类型
  1248. 'parent_id' => 0,
  1249. 'level' => 1,
  1250. 'product_name' => $script_name,
  1251. 'sort_order' => time(),
  1252. 'is_deleted' => 0,
  1253. 'created_at' => date('Y-m-d H:i:s'),
  1254. 'updated_at' => date('Y-m-d H:i:s')
  1255. ]);
  1256. } else {
  1257. $folder_id = $folder->id;
  1258. }
  1259. // 查找该文件夹下是否已存在同名资产
  1260. $existing_product = DB::table('mp_products')
  1261. ->where('cpid', $cpid)
  1262. ->where('type', 1) // 资产类型
  1263. ->where('product', $product_type)
  1264. ->where('parent_id', $folder_id)
  1265. ->where('product_name', $product_name)
  1266. ->where('is_deleted', 0)
  1267. ->first();
  1268. if ($existing_product) {
  1269. // 更新已存在的资产
  1270. $updateData = [
  1271. 'pic_task_status' => '生成成功'
  1272. ];
  1273. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1274. if ($url) $updateData['url'] = $url;
  1275. // 处理versions字段
  1276. $versions = getProp($target_scenes, 'versions', []);
  1277. if ($versions && is_array($versions)) {
  1278. $updateData['versions'] = json_encode($versions, 256);
  1279. }
  1280. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1281. DB::table('mp_products')
  1282. ->where('id', $existing_product->id)
  1283. ->update($updateData);
  1284. $product_id = $existing_product->id;
  1285. } else {
  1286. // 创建新资产
  1287. $versions = getProp($target_scenes, 'versions', []);
  1288. $product_id = DB::table('mp_products')->insertGetId([
  1289. 'user_id' => $uid,
  1290. 'cpid' => $cpid,
  1291. 'type' => 1, // 资产
  1292. 'product' => $product_type, // 场景
  1293. 'parent_id' => $folder_id,
  1294. 'level' => 2,
  1295. 'product_name' => $product_name,
  1296. 'url' => $url,
  1297. 'pic_prompt' => $pic_prompt,
  1298. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1299. 'sort_order' => time(),
  1300. 'is_deleted' => 0,
  1301. 'pic_task_status' => '生成成功',
  1302. 'created_at' => date('Y-m-d H:i:s'),
  1303. 'updated_at' => date('Y-m-d H:i:s')
  1304. ]);
  1305. }
  1306. // 建立或更新绑定关系
  1307. $existing_mapping = DB::table('mp_script_product_mappings')
  1308. ->where('script_id', $script_id)
  1309. ->where('product_id', $product_id)
  1310. ->where('episode_number', $episode_number)
  1311. ->first();
  1312. if (!$existing_mapping) {
  1313. // 创建绑定关系
  1314. DB::table('mp_script_product_mappings')->insert([
  1315. 'script_id' => $script_id,
  1316. 'product_id' => $product_id,
  1317. 'episode_number' => $episode_number,
  1318. 'created_at' => date('Y-m-d H:i:s'),
  1319. 'updated_at' => date('Y-m-d H:i:s')
  1320. ]);
  1321. }
  1322. }
  1323. }
  1324. }
  1325. } catch (\Exception $e) {
  1326. dLog('anime')->error('更新剧集场景失败', [
  1327. 'anime_id' => $anime_id,
  1328. 'episode_id' => $episode_id,
  1329. 'error' => $e->getMessage()
  1330. ]);
  1331. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1332. }
  1333. return true;
  1334. }
  1335. public function changeEpisodeProps($data) {
  1336. $anime_id = getProp($data, 'anime_id');
  1337. $episode_id = getProp($data, 'episode_id');
  1338. $target_props = getProp($data, 'props');
  1339. // 删除标志优先取最外层入参 is_deleted,兼容道具对象内部(props.is_deleted)的传参
  1340. $is_deleted = getProp($data, 'is_deleted', getProp($target_props, 'is_deleted', 0));
  1341. // 控制字段不随道具内容写入分集props存储
  1342. if (is_array($target_props)) {
  1343. unset($target_props['is_deleted']);
  1344. }
  1345. // 参数验证
  1346. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1347. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1348. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1349. // 验证剧集是否存在
  1350. $episode = DB::table('mp_anime_episodes')
  1351. ->where('anime_id', $anime_id)
  1352. ->where('id', $episode_id)
  1353. ->first();
  1354. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1355. $props = json_decode(getProp($episode, 'props'), true);
  1356. // 获取anime信息,检查是否有关联的script_id
  1357. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1358. if (!$anime) Utils::throwError('20003:动漫不存在');
  1359. $script_id = getProp($anime, 'script_id');
  1360. $episode_number = getProp($episode, 'episode_number', 1);
  1361. $uid = Site::getUid();
  1362. $cpid = Site::getCpid();
  1363. try {
  1364. $target_prop_name = getProp($target_props, 'prop');
  1365. if (empty($target_prop_name)) {
  1366. Utils::throwError('20003:道具名称不能为空');
  1367. }
  1368. // 如果是删除操作
  1369. if ($is_deleted == 1) {
  1370. // 从道具列表中移除该道具
  1371. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1372. return getProp($prop, 'prop') !== $target_prop_name;
  1373. }));
  1374. // 更新道具列表
  1375. $result = DB::table('mp_anime_episodes')
  1376. ->where('anime_id', $anime_id)
  1377. ->where('id', $episode_id)
  1378. ->update([
  1379. 'props' => json_encode($props, 256),
  1380. 'updated_at' => date('Y-m-d H:i:s')
  1381. ]);
  1382. if ($result === false) {
  1383. Utils::throwError('20003:删除道具失败');
  1384. }
  1385. } else {
  1386. // 新增或更新操作
  1387. $prop_found = false;
  1388. $is_new_prop = false;
  1389. // 查找并更新已存在的道具
  1390. foreach($props as &$prop) {
  1391. if (getProp($prop, 'prop') === $target_prop_name) {
  1392. $prop = $target_props;
  1393. $prop_found = true;
  1394. break;
  1395. }
  1396. }
  1397. // 如果道具不存在,则新增
  1398. if (!$prop_found) {
  1399. $props[] = $target_props;
  1400. $is_new_prop = true;
  1401. }
  1402. // 更新道具列表
  1403. $result = DB::table('mp_anime_episodes')
  1404. ->where('anime_id', $anime_id)
  1405. ->where('id', $episode_id)
  1406. ->update([
  1407. 'props' => json_encode($props, 256),
  1408. 'updated_at' => date('Y-m-d H:i:s')
  1409. ]);
  1410. if ($result === false) {
  1411. Utils::throwError('20003:更新道具列表失败');
  1412. }
  1413. // 如果有关联的script_id,则同步到mp_products表
  1414. if ($script_id) {
  1415. // 查询剧本信息
  1416. $script = DB::table('mp_scripts')
  1417. ->where('id', $script_id)
  1418. ->where('is_deleted', 0)
  1419. ->first();
  1420. if ($script) {
  1421. $script_name = $script->script_name ?? 'script_' . $script_id;
  1422. $product_name = getProp($target_props, 'prop');
  1423. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1424. $url = getProp($target_props, 'url', '');
  1425. $product_type = 3; // 3=道具
  1426. // 查找或创建以script_name命名的文件夹
  1427. $folder = DB::table('mp_products')
  1428. ->where('cpid', $cpid)
  1429. ->where('type', 2) // 文件夹类型
  1430. ->where('product', $product_type) // 道具类型
  1431. ->where('product_name', $script_name)
  1432. ->where('parent_id', 0)
  1433. ->where('is_deleted', 0)
  1434. ->first();
  1435. if (!$folder) {
  1436. // 创建文件夹
  1437. $folder_id = DB::table('mp_products')->insertGetId([
  1438. 'user_id' => $uid,
  1439. 'cpid' => $cpid,
  1440. 'type' => 2, // 文件夹
  1441. 'product' => $product_type, // 道具类型
  1442. 'parent_id' => 0,
  1443. 'level' => 1,
  1444. 'product_name' => $script_name,
  1445. 'sort_order' => time(),
  1446. 'is_deleted' => 0,
  1447. 'created_at' => date('Y-m-d H:i:s'),
  1448. 'updated_at' => date('Y-m-d H:i:s')
  1449. ]);
  1450. } else {
  1451. $folder_id = $folder->id;
  1452. }
  1453. // 查找该文件夹下是否已存在同名资产
  1454. $existing_product = DB::table('mp_products')
  1455. ->where('cpid', $cpid)
  1456. ->where('type', 1) // 资产类型
  1457. ->where('product', $product_type)
  1458. ->where('parent_id', $folder_id)
  1459. ->where('product_name', $product_name)
  1460. ->where('is_deleted', 0)
  1461. ->first();
  1462. if ($existing_product) {
  1463. // 更新已存在的资产
  1464. $updateData = [
  1465. 'pic_task_status' => '生成成功'
  1466. ];
  1467. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1468. if ($url) $updateData['url'] = $url;
  1469. // 处理versions字段
  1470. $versions = getProp($target_props, 'versions', []);
  1471. if ($versions && is_array($versions)) {
  1472. $updateData['versions'] = json_encode($versions, 256);
  1473. }
  1474. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1475. DB::table('mp_products')
  1476. ->where('id', $existing_product->id)
  1477. ->update($updateData);
  1478. $product_id = $existing_product->id;
  1479. } else {
  1480. // 创建新资产
  1481. $versions = getProp($target_props, 'versions', []);
  1482. $product_id = DB::table('mp_products')->insertGetId([
  1483. 'user_id' => $uid,
  1484. 'cpid' => $cpid,
  1485. 'type' => 1, // 资产
  1486. 'product' => $product_type, // 道具
  1487. 'parent_id' => $folder_id,
  1488. 'level' => 2,
  1489. 'product_name' => $product_name,
  1490. 'url' => $url,
  1491. 'pic_prompt' => $pic_prompt,
  1492. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1493. 'sort_order' => time(),
  1494. 'is_deleted' => 0,
  1495. 'pic_task_status' => '生成成功',
  1496. 'created_at' => date('Y-m-d H:i:s'),
  1497. 'updated_at' => date('Y-m-d H:i:s')
  1498. ]);
  1499. }
  1500. // 建立或更新绑定关系
  1501. $existing_mapping = DB::table('mp_script_product_mappings')
  1502. ->where('script_id', $script_id)
  1503. ->where('product_id', $product_id)
  1504. ->where('episode_number', $episode_number)
  1505. ->first();
  1506. if (!$existing_mapping) {
  1507. // 创建绑定关系
  1508. DB::table('mp_script_product_mappings')->insert([
  1509. 'script_id' => $script_id,
  1510. 'product_id' => $product_id,
  1511. 'episode_number' => $episode_number,
  1512. 'created_at' => date('Y-m-d H:i:s'),
  1513. 'updated_at' => date('Y-m-d H:i:s')
  1514. ]);
  1515. }
  1516. }
  1517. }
  1518. }
  1519. } catch (\Exception $e) {
  1520. dLog('anime')->error('更新剧集道具失败', [
  1521. 'anime_id' => $anime_id,
  1522. 'episode_id' => $episode_id,
  1523. 'error' => $e->getMessage()
  1524. ]);
  1525. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1526. }
  1527. return true;
  1528. }
  1529. public function editSegment($data) {
  1530. $segment_id = getProp($data, 'segment_id');
  1531. $segment_content = getProp($data, 'segment_content');
  1532. $image_url = getProp($data, 'image_url');
  1533. $video_url = getProp($data, 'video_url');
  1534. // 参数验证
  1535. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1536. // 验证分镜是否存在
  1537. $segment = DB::table('mp_episode_segments')
  1538. ->where('segment_id', $segment_id)
  1539. ->first();
  1540. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1541. $dubTaskId = 0;
  1542. try {
  1543. DB::beginTransaction();
  1544. // 准备更新数据
  1545. $update_data = [
  1546. 'updated_at' => date('Y-m-d H:i:s')
  1547. ];
  1548. if ($segment_content) {
  1549. // 先将segment_content赋值到update_data
  1550. $update_data['segment_content'] = $segment_content;
  1551. // 使用现有方法分析segment_content,提取各个字段
  1552. $this->handleSegmentContent($update_data);
  1553. // 如果有对话内容,创建视频配音合成任务
  1554. $dialogue = getProp($update_data, 'dialogue');
  1555. if (!empty($dialogue)) {
  1556. $now = date('Y-m-d H:i:s');
  1557. $generate_json = [
  1558. 'text' => $dialogue,
  1559. 'role' => getProp($update_data, 'voice_actor'),
  1560. 'voice_type' => getProp($update_data, 'voice_type'),
  1561. 'voice_name' => getProp($update_data, 'voice_name'),
  1562. 'emotion' => getProp($update_data, 'emotion'),
  1563. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1564. 'gender' => getProp($update_data, 'gender'),
  1565. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1566. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1567. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1568. 'pitch' => getProp($update_data, 'pitch', 0),
  1569. ];
  1570. // 插入视频配音合成任务
  1571. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1572. 'alias_segment_id' => $segment_id,
  1573. 'generate_status' => '执行中',
  1574. 'audio_url' => '',
  1575. 'generate_json' => json_encode($generate_json, 256),
  1576. 'created_at' => $now,
  1577. 'updated_at' => $now,
  1578. ]);
  1579. if (!$dubTaskId) {
  1580. Utils::throwError('20003:创建配音任务失败!');
  1581. }
  1582. $update_data['audio_url'] = '';
  1583. } else {
  1584. // dialogue为空时,直接写入默认音频信息
  1585. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1586. $update_data['audio_duration'] = 2.0;
  1587. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1588. }
  1589. }
  1590. if ($image_url) {
  1591. $update_data['img_url'] = $image_url;
  1592. // 同时写入一个简单的图片生成任务
  1593. $pic_task = [
  1594. 'alias_segment_id' => $segment_id,
  1595. 'ref_img_url' => json_encode([]),
  1596. 'status' => 'success',
  1597. 'result_url' => json_encode([$image_url], 256),
  1598. 'model' => '',
  1599. 'created_at' => date('Y-m-d H:i:s'),
  1600. 'updated_at' => date('Y-m-d H:i:s'),
  1601. ];
  1602. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1603. }
  1604. if ($video_url) {
  1605. $update_data['origin_video_url'] = $video_url;
  1606. $compressed_video_url = compressVideo($video_url);
  1607. $update_data['current_type'] = 2;
  1608. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1609. // 同时写入一个简单的视频生成任务
  1610. $video_task = [
  1611. 'alias_segment_id' => $segment_id,
  1612. 'status' => 'success',
  1613. 'result_url' => $update_data['origin_video_url'],
  1614. 'compressed_url' => $update_data['video_url'],
  1615. 'created_at' => date('Y-m-d H:i:s'),
  1616. 'updated_at' => date('Y-m-d H:i:s'),
  1617. ];
  1618. DB::table('mp_generate_video_tasks')->insert($video_task);
  1619. }
  1620. // 更新分镜信息
  1621. $result = DB::table('mp_episode_segments')
  1622. ->where('segment_id', $segment_id)
  1623. ->update($update_data);
  1624. if ($result === false) {
  1625. Utils::throwError('20003:更新分镜剧本失败');
  1626. }
  1627. DB::commit();
  1628. // 如果有创建音频生成任务则调用API
  1629. if ($dubTaskId) {
  1630. // 请求远程服务器执行生成
  1631. $client = new Client(['timeout' => 300, 'verify' => false]);
  1632. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1633. $response = $result->getBody()->getContents();
  1634. $response_arr = json_decode($response, true);
  1635. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1636. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1637. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1638. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1639. Utils::throwError('20003:火山生成音频失败');
  1640. }
  1641. }
  1642. return true;
  1643. } catch (\Exception $e) {
  1644. DB::rollBack();
  1645. dLog('anime')->error('更新分镜剧本失败', [
  1646. 'segment_id' => $segment_id,
  1647. 'error' => $e->getMessage()
  1648. ]);
  1649. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1650. }
  1651. }
  1652. public function batchSetSegmentPics($data) {
  1653. $anime_id = getProp($data, 'anime_id');
  1654. $episode_id = getProp($data, 'episode_id');
  1655. $ratio = getProp($data, 'ratio');
  1656. $dimensions = $this->getRatioDimensions($ratio);
  1657. $width = $dimensions['width'];
  1658. $height = $dimensions['height'];
  1659. if (!$anime_id || !$episode_id) {
  1660. Utils::throwError('1002:请选择剧集');
  1661. }
  1662. // 获取剧集信息
  1663. $episode = DB::table('mp_anime_episodes')
  1664. ->where('anime_id', $anime_id)
  1665. ->where('id', $episode_id)
  1666. ->where('is_default', 1)
  1667. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1668. ->first();
  1669. if (!$episode) {
  1670. Utils::throwError('20003:该剧集不存在');
  1671. }
  1672. $model = getProp($data, 'model');
  1673. if (!$model) {
  1674. $model = getProp($episode, 'image_model');
  1675. if (!$model) {
  1676. // episode表也没有,使用默认值
  1677. $model = 'gpt-image-2';
  1678. }
  1679. }
  1680. // 验证模型是否在可用模型表中
  1681. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1682. $model = 'gpt-image-2';
  1683. }
  1684. $roles = json_decode(getProp($episode, 'roles'), true);
  1685. if (!$roles) {
  1686. Utils::throwError('20003:角色信息格式错误');
  1687. }
  1688. // 构建角色名称到参考图的映射
  1689. $role_map = [];
  1690. foreach ($roles as $role) {
  1691. $role_name = getProp($role, 'role');
  1692. $role_url = getProp($role, 'url');
  1693. if (!empty($role_name) && !empty($role_url)) {
  1694. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1695. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1696. // $role_map[$base_name] = $role_url;
  1697. // 同时保存完整名称的映射
  1698. $role_map[$role_name] = $role_url;
  1699. }
  1700. }
  1701. $scenes = json_decode(getProp($episode, 'roles'), true);
  1702. if (!$scenes) {
  1703. Utils::throwError('20003:场景信息格式错误');
  1704. }
  1705. // 构建角色名称到参考图的映射
  1706. $scene_map = [];
  1707. foreach ($scenes as $scene) {
  1708. $scene_name = getProp($scene, 'scene');
  1709. $scene_url = getProp($scene, 'url');
  1710. if (!empty($scene_name) && !empty($scene_url)) {
  1711. $scene_map[$scene_name] = $scene_url;
  1712. }
  1713. }
  1714. // 获取所有分镜信息
  1715. $segments = DB::table('mp_episode_segments')
  1716. ->where('anime_id', $anime_id)
  1717. ->where('episode_id', $episode_id)
  1718. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1719. ->orderBy('segment_number')
  1720. ->get()
  1721. ->toArray();
  1722. if (empty($segments)) {
  1723. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1724. }
  1725. // 保存图片比例
  1726. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1727. $updated_segments = [];
  1728. $failed_segments = [];
  1729. // 批量为每个分镜生成图片任务
  1730. foreach ($segments as $segment) {
  1731. $segment_id = $segment->segment_id;
  1732. $segment_content = $segment->segment_content;
  1733. if (empty($segment_content)) {
  1734. $failed_segments[] = [
  1735. 'segment_id' => $segment_id,
  1736. 'error' => '分镜内容为空'
  1737. ];
  1738. continue;
  1739. }
  1740. try {
  1741. $dubTaskId = 0;
  1742. // 解析分镜内容,提取画面描述作为主要提示词
  1743. $prompt = $segment_content;
  1744. $ref_img_urls = [];
  1745. // 分镜场景
  1746. $scene = getProp($segment, 'scene');
  1747. $matched_scene = '';
  1748. if (isset($scene_map[$scene])) {
  1749. $img_index = count($ref_img_urls) + 1;
  1750. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1751. $ref_img_urls[] = $scene_map[$scene];
  1752. $matched_scene = $scene;
  1753. }
  1754. // 分镜角色
  1755. $characters = getProp($segment, 'characters');
  1756. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1757. $roles = explode(',', $characters);
  1758. // 从分镜内容中提取涉及的角色
  1759. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1760. // 获取匹配角色的参考图
  1761. foreach ($segment_characters as $character) {
  1762. if (isset($role_map[$character])) {
  1763. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1764. $img_index = count($ref_img_urls) + 1;
  1765. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1766. $ref_img_urls[] = $role_map[$character];
  1767. }
  1768. }
  1769. // 如果没有找到匹配的角色参考图,不使用参考图
  1770. if (empty($ref_img_urls)) {
  1771. $ref_img_urls = [];
  1772. }
  1773. // 准备生成任务参数
  1774. $params = [
  1775. 'model' => $model,
  1776. 'alias_segment_id' => $segment_id,
  1777. 'prompt' => $prompt,
  1778. 'ref_img_urls' => $ref_img_urls,
  1779. 'width' => $width,
  1780. 'height' => $height,
  1781. ];
  1782. // 优化提示词(不要生成字幕)
  1783. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1784. // $task_id = mt_rand(100000, 999999);
  1785. // 调用AI图片生成服务
  1786. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1787. $task_id = $task->id;
  1788. if (!$task_id) {
  1789. $failed_segments[] = [
  1790. 'segment_id' => $segment_id,
  1791. 'error' => '创建生成任务失败'
  1792. ];
  1793. continue;
  1794. }
  1795. $update_data = [
  1796. 'pic_task_id' => $task_id,
  1797. 'pic_task_status' => '生成中',
  1798. 'audio_url' => '',
  1799. 'updated_at' => date('Y-m-d H:i:s')
  1800. ];
  1801. // 如果有对话内容,创建视频配音合成任务
  1802. $dialogue = getProp($segment, 'dialogue');
  1803. if (!empty($dialogue)) {
  1804. $now = date('Y-m-d H:i:s');
  1805. $generate_json = [
  1806. 'text' => $dialogue,
  1807. 'role' => getProp($segment, 'voice_actor'),
  1808. 'voice_type' => getProp($segment, 'voice_type'),
  1809. 'voice_name' => getProp($segment, 'voice_name'),
  1810. 'emotion' => getProp($segment, 'emotion'),
  1811. 'emotion_type' => getProp($segment, 'emotion_type'),
  1812. 'gender' => getProp($segment, 'gender'),
  1813. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1814. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1815. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1816. 'pitch' => getProp($segment, 'pitch', 0),
  1817. ];
  1818. // 插入视频配音合成任务
  1819. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1820. 'alias_segment_id' => $segment_id,
  1821. 'generate_status' => '执行中',
  1822. 'audio_url' => '',
  1823. 'generate_json' => json_encode($generate_json, 256),
  1824. 'created_at' => $now,
  1825. 'updated_at' => $now,
  1826. ]);
  1827. if (!$dubTaskId) {
  1828. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1829. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1830. // Utils::throwError('20003:创建配音任务失败!');
  1831. }
  1832. } else {
  1833. // dialogue为空时,直接写入默认音频信息到分镜表
  1834. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1835. $update_data['audio_duration'] = 2.0;
  1836. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1837. }
  1838. // 更新分镜的任务信息
  1839. $update_result = DB::table('mp_episode_segments')
  1840. ->where('segment_id', $segment_id)
  1841. ->update($update_data);
  1842. // 如果是第一集的首帧图片,则存入待更新数组
  1843. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1844. Redis::sadd('anime_first_frame_urls', $segment_id);
  1845. }
  1846. if ($update_result) {
  1847. $updated_segments[] = [
  1848. 'segment_id' => $segment_id,
  1849. 'task_id' => $task_id,
  1850. 'status' => '生成中',
  1851. 'matched_scenes' => $matched_scene,
  1852. 'matched_roles' => $segment_characters,
  1853. 'ref_urls_count' => count($ref_img_urls)
  1854. ];
  1855. } else {
  1856. $failed_segments[] = [
  1857. 'segment_id' => $segment_id,
  1858. 'error' => '更新分镜任务状态失败'
  1859. ];
  1860. }
  1861. if ($dubTaskId) {
  1862. sleep(1);
  1863. // 请求远程服务器执行生成
  1864. $client = new Client(['timeout' => 300, 'verify' => false]);
  1865. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1866. $response = $result->getBody()->getContents();
  1867. $response_arr = json_decode($response, true);
  1868. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1869. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1870. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1871. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1872. }
  1873. }
  1874. } catch (\Exception $e) {
  1875. $failed_segments[] = [
  1876. 'segment_id' => $segment_id,
  1877. 'error' => $e->getMessage()
  1878. ];
  1879. }
  1880. }
  1881. // 更新剧集生成状态
  1882. if (!empty($updated_segments)) {
  1883. DB::table('mp_anime_episodes')
  1884. ->where('id', $episode_id)
  1885. ->update([
  1886. 'is_generated' => 1,
  1887. 'updated_at' => date('Y-m-d H:i:s')
  1888. ]);
  1889. }
  1890. return [
  1891. 'success_count' => count($updated_segments),
  1892. 'failed_count' => count($failed_segments),
  1893. 'success_segments' => $updated_segments,
  1894. 'failed_segments' => $failed_segments,
  1895. 'total_segments' => count($segments)
  1896. ];
  1897. }
  1898. public function reGenerateSegment($data) {
  1899. $segment_id = getProp($data, 'segment_id');
  1900. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1901. $anime_id = getProp($segment, 'anime_id');
  1902. $episode_id = getProp($segment, 'episode_id');
  1903. $episode_number = getProp($segment, 'episode_number');
  1904. $segment_content = getProp($data, 'segment_content');
  1905. $ratio = getProp($data, 'ratio');
  1906. if (!$ratio) {
  1907. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1908. if (!$ratio) $ratio = '9:16';
  1909. }
  1910. $dimensions = $this->getRatioDimensions($ratio);
  1911. $width = $dimensions['width'];
  1912. $height = $dimensions['height'];
  1913. if (!$anime_id || !$episode_id) {
  1914. Utils::throwError('1002:请选择分镜');
  1915. }
  1916. // 使用文生文模型重新解析segment_content
  1917. if (!empty($segment_content)) {
  1918. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1919. }
  1920. // 获取动漫的角色信息(包含参考图)
  1921. $anime = DB::table('mp_animes')
  1922. ->where('id', $anime_id)
  1923. ->select('roles', 'scenes')
  1924. ->first();
  1925. if (!$anime || !$anime->roles) {
  1926. Utils::throwError('20003:未找到角色信息');
  1927. }
  1928. $roles = json_decode($anime->roles, true);
  1929. if (!$roles) {
  1930. Utils::throwError('20003:角色信息格式错误');
  1931. }
  1932. // 构建角色名称到参考图的映射
  1933. $role_map = [];
  1934. foreach ($roles as $role) {
  1935. $role_name = getProp($role, 'role');
  1936. $role_url = getProp($role, 'url');
  1937. if (!empty($role_name) && !empty($role_url)) {
  1938. $role_map[$role_name] = $role_url;
  1939. }
  1940. }
  1941. $scenes = json_decode($anime->scenes, true);
  1942. if (!$scenes) {
  1943. Utils::throwError('20003:角色信息格式错误');
  1944. }
  1945. // 构建角色名称到参考图的映射
  1946. $scene_map = [];
  1947. foreach ($scenes as $scene) {
  1948. $scene_name = getProp($scene, 'scene');
  1949. $scene_url = getProp($scene, 'url');
  1950. if (!empty($scene_name) && !empty($scene_url)) {
  1951. $scene_map[$scene_name] = $scene_url;
  1952. }
  1953. }
  1954. $segment_id = $segment->segment_id;
  1955. $original_segment_content = $segment->segment_content;
  1956. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1957. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1958. if (empty($final_segment_content)) {
  1959. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1960. }
  1961. try {
  1962. $dubTaskId = 0;
  1963. // 分镜剧本数组
  1964. $update_data = [
  1965. 'segment_content' => $final_segment_content,
  1966. 'pic_task_status' => '生成中',
  1967. 'updated_at' => date('Y-m-d H:i:s')
  1968. ];
  1969. // 解析分镜内容,提取画面描述作为主要提示词
  1970. $prompt = $final_segment_content;
  1971. $ref_img_urls = [];
  1972. // 分镜场景
  1973. $scene = getProp($data, 'scene');
  1974. if ($scene) {
  1975. $matched_scene = '';
  1976. if (isset($scene_map[$scene])) {
  1977. $img_index = count($ref_img_urls) + 1;
  1978. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1979. $ref_img_urls[] = $scene_map[$scene];
  1980. $matched_scene = $scene;
  1981. }
  1982. $update_data['scene'] = $scene;
  1983. }
  1984. // 分镜角色
  1985. $characters = getProp($data, 'characters');
  1986. if ($characters) {
  1987. $update_data['characters'] = $characters;
  1988. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1989. $characters = explode(',', $characters);
  1990. // 从分镜内容中提取涉及的角色
  1991. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1992. // 获取匹配角色的参考图
  1993. foreach ($segment_characters as $character) {
  1994. if (isset($role_map[$character])) {
  1995. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1996. $img_index = count($ref_img_urls) + 1;
  1997. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1998. $ref_img_urls[] = $role_map[$character];
  1999. }
  2000. }
  2001. }
  2002. // 如果没有找到匹配的角色参考图,不使用参考图
  2003. if (empty($ref_img_urls)) {
  2004. $ref_img_urls = [];
  2005. }
  2006. // 准备生成任务参数
  2007. $params = [
  2008. 'alias_segment_id' => $segment_id,
  2009. 'prompt' => $prompt,
  2010. 'ref_img_urls' => $ref_img_urls,
  2011. 'width' => $width,
  2012. 'height' => $height,
  2013. ];
  2014. // 优化提示词(不要生成字幕)
  2015. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  2016. // 调用AI图片生成服务
  2017. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2018. $task_id = $task->id;
  2019. if (!$task_id) {
  2020. Utils::throwError('20003:创建生成任务失败!');
  2021. }
  2022. $update_data['pic_task_id'] = $task_id;
  2023. // 更新分镜剧本信息
  2024. $this->handleSegmentContent($update_data);
  2025. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2026. if ($segment_content) {
  2027. $dialogue = getProp($update_data, 'dialogue');
  2028. if (!empty($dialogue)) {
  2029. $now = date('Y-m-d H:i:s');
  2030. $generate_json = [
  2031. 'text' => $dialogue,
  2032. 'role' => getProp($update_data, 'voice_actor'),
  2033. 'voice_type' => getProp($update_data, 'voice_type'),
  2034. 'voice_name' => getProp($update_data, 'voice_name'),
  2035. 'emotion' => getProp($update_data, 'emotion'),
  2036. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2037. 'gender' => getProp($update_data, 'gender'),
  2038. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2039. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2040. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2041. 'pitch' => getProp($update_data, 'pitch', 0),
  2042. ];
  2043. // 插入视频配音合成任务
  2044. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2045. 'alias_segment_id' => $segment_id,
  2046. 'generate_status' => '执行中',
  2047. 'audio_url' => '',
  2048. 'generate_json' => json_encode($generate_json, 256),
  2049. 'created_at' => date('Y-m-d H:i:s'),
  2050. 'updated_at' => date('Y-m-d H:i:s'),
  2051. ]);
  2052. if (!$dubTaskId) {
  2053. Utils::throwError('20003:创建配音任务失败!');
  2054. }
  2055. $update_data['audio_url'] = '';
  2056. } else {
  2057. // dialogue为空时,直接写入默认音频信息
  2058. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2059. $update_data['audio_duration'] = 2.0;
  2060. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2061. }
  2062. }
  2063. $boolen = DB::table('mp_episode_segments')
  2064. ->where('segment_id', $segment_id)
  2065. ->update($update_data);
  2066. // 如果是第一集的首帧图片,则存入待更新数组
  2067. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2068. Redis::sadd('anime_first_frame_urls', $segment_id);
  2069. }
  2070. if ($dubTaskId) {
  2071. // 请求远程服务器执行生成
  2072. $client = new Client(['timeout' => 300, 'verify' => false]);
  2073. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2074. $response = $result->getBody()->getContents();
  2075. $response_arr = json_decode($response, true);
  2076. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2077. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2078. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2079. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2080. Utils::throwError('20003:火山生成音频失败');
  2081. }
  2082. }
  2083. } catch (\Exception $e) {
  2084. $failed_segments[] = [
  2085. 'segment_id' => $segment_id,
  2086. 'error' => $e->getMessage()
  2087. ];
  2088. }
  2089. // 创建任务之后先暂停10s等待异步任务完成
  2090. sleep(10);
  2091. $img_url = $this->loopGetPicTaskResult($task_id);
  2092. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2093. // 图片生成后新增对话记录
  2094. try {
  2095. $uid = Site::getUid();
  2096. $now = date('Y-m-d H:i:s');
  2097. // 使用AI反推图片提示词
  2098. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2099. // 保存对话记录
  2100. $records = [
  2101. [
  2102. 'uid' => $uid,
  2103. 'anime_id' => $anime_id,
  2104. 'sequence' => $episode_number,
  2105. 'role' => 'user',
  2106. 'content' => '重新生成',
  2107. 'segment_id' => $segment_id,
  2108. 'pic_task_id' => $task_id,
  2109. 'image_url' => '',
  2110. 'created_at' => $now,
  2111. 'updated_at' => $now
  2112. ],
  2113. [
  2114. 'uid' => $uid,
  2115. 'anime_id' => $anime_id,
  2116. 'sequence' => $episode_number,
  2117. 'role' => 'assistant',
  2118. 'content' => $pic_prompt,
  2119. 'segment_id' => $segment_id,
  2120. 'pic_task_id' => $task_id,
  2121. 'image_url' => $img_url,
  2122. 'created_at' => $now,
  2123. 'updated_at' => $now
  2124. ]
  2125. ];
  2126. DB::table('mp_anime_records')->insert($records);
  2127. } catch (\Exception $e) {
  2128. // 记录日志但不影响主流程
  2129. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2130. 'segment_id' => $segment_id,
  2131. 'img_url' => $img_url
  2132. ]);
  2133. }
  2134. return $img_url;
  2135. }
  2136. public function addSegment($data) {
  2137. $prev_segment_id = getProp($data, 'prev_segment_id');
  2138. $img_url = getProp($data, 'img_url');
  2139. $video_url = getProp($data, 'video_url');
  2140. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2141. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2142. $anime_id = getProp($segment, 'anime_id');
  2143. $episode_id = getProp($segment, 'episode_id');
  2144. $episode_number = getProp($segment, 'episode_number');
  2145. $segment_number = getProp($segment, 'segment_number');
  2146. $new_segment_number = $segment_number + 1;
  2147. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2148. // 分镜剧本数组
  2149. $insert_data = [
  2150. 'anime_id' => $anime_id,
  2151. 'episode_id' => $episode_id,
  2152. 'episode_number' => $episode_number,
  2153. 'act_number' => getProp($segment, 'act_number'),
  2154. 'act_title' => getProp($segment, 'act_title'),
  2155. 'segment_id' => $segment_id,
  2156. 'segment_number' => $new_segment_number,
  2157. 'segment_content' => '',
  2158. 'img_url' => '',
  2159. 'video_url' => '',
  2160. 'created_at' => date('Y-m-d H:i:s'),
  2161. 'updated_at' => date('Y-m-d H:i:s')
  2162. ];
  2163. if ($img_url) $insert_data['img_url'] = $img_url;
  2164. if ($video_url) {
  2165. $insert_data['origin_video_url'] = $video_url;
  2166. $insert_data['current_type'] = 2;
  2167. $compressed_video_url = compressVideo($video_url);
  2168. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2169. }
  2170. try {
  2171. DB::beginTransaction();
  2172. // 先更新序号
  2173. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2174. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2175. if (!$id) {
  2176. Utils::throwError('20003:新增分镜失败!');
  2177. }
  2178. }catch (\Exception $e) {
  2179. DB::rollBack();
  2180. Utils::throwError('20003:'.$e->getMessage());
  2181. }
  2182. DB::commit();
  2183. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2184. $segment = $segment ? (array)$segment : [];
  2185. return $segment;
  2186. // 以下代码暂弃用
  2187. $anime_id = getProp($segment, 'anime_id');
  2188. $episode_id = getProp($segment, 'episode_id');
  2189. $episode_number = getProp($segment, 'episode_number');
  2190. $segment_number = getProp($segment, 'segment_number');
  2191. $segment_content = getProp($data, 'segment_content');
  2192. $img_url = getProp($data, 'img_url');
  2193. $video_url = getProp($data, 'video_url');
  2194. $ratio = getProp($data, 'ratio');
  2195. $dimensions = $this->getRatioDimensions($ratio);
  2196. $width = $dimensions['width'];
  2197. $height = $dimensions['height'];
  2198. if (!$anime_id || !$episode_id) {
  2199. Utils::throwError('1002:请选择分镜');
  2200. }
  2201. // 使用文生文模型重新解析segment_content
  2202. if (!empty($segment_content)) {
  2203. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2204. }
  2205. // 获取动漫的角色信息(包含参考图)
  2206. $anime = DB::table('mp_animes')
  2207. ->where('id', $anime_id)
  2208. ->select('roles', 'scenes')
  2209. ->first();
  2210. if (!$anime || !$anime->roles) {
  2211. Utils::throwError('20003:未找到角色信息');
  2212. }
  2213. $roles = json_decode($anime->roles, true);
  2214. if (!$roles) {
  2215. Utils::throwError('20003:角色信息格式错误');
  2216. }
  2217. // 构建角色名称到参考图的映射
  2218. $role_map = [];
  2219. foreach ($roles as $role) {
  2220. $role_name = getProp($role, 'role');
  2221. $role_url = getProp($role, 'url');
  2222. if (!empty($role_name) && !empty($role_url)) {
  2223. $role_map[$role_name] = $role_url;
  2224. }
  2225. }
  2226. $scenes = json_decode($anime->scenes, true);
  2227. if (!$scenes) {
  2228. Utils::throwError('20003:角色信息格式错误');
  2229. }
  2230. // 构建角色名称到参考图的映射
  2231. $scene_map = [];
  2232. foreach ($scenes as $scene) {
  2233. $scene_name = getProp($scene, 'scene');
  2234. $scene_url = getProp($scene, 'url');
  2235. if (!empty($scene_name) && !empty($scene_url)) {
  2236. $scene_map[$scene_name] = $scene_url;
  2237. }
  2238. }
  2239. $segment_id = $segment->segment_id;
  2240. $original_segment_content = $segment->segment_content;
  2241. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2242. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2243. if (empty($final_segment_content)) {
  2244. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2245. }
  2246. try {
  2247. $dubTaskId = 0;
  2248. DB::beginTransaction();
  2249. $new_segment_number = $segment_number + 1;
  2250. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2251. // 分镜剧本数组
  2252. $insert_data = [
  2253. 'anime_id' => $anime_id,
  2254. 'episode_id' => $episode_id,
  2255. 'episode_number' => $episode_number,
  2256. 'act_number' => getProp($segment, 'act_number'),
  2257. 'act_title' => getProp($segment, 'act_title'),
  2258. 'segment_id' => $segment_id,
  2259. 'segment_number' => $new_segment_number,
  2260. 'segment_content' => $final_segment_content,
  2261. 'img_url' => $img_url,
  2262. 'video_url' => $video_url,
  2263. 'created_at' => date('Y-m-d H:i:s'),
  2264. 'updated_at' => date('Y-m-d H:i:s')
  2265. ];
  2266. // 更新分镜剧本信息
  2267. $this->handleSegmentContent($insert_data);
  2268. // 如果有对话内容,创建视频配音合成任务
  2269. $dialogue = getProp($insert_data, 'dialogue');
  2270. if (!empty($dialogue)) {
  2271. $now = date('Y-m-d H:i:s');
  2272. $generate_json = [
  2273. 'text' => $dialogue,
  2274. 'role' => getProp($insert_data, 'voice_actor'),
  2275. 'voice_type' => getProp($insert_data, 'voice_type'),
  2276. 'voice_name' => getProp($insert_data, 'voice_name'),
  2277. 'emotion' => getProp($insert_data, 'emotion'),
  2278. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2279. 'gender' => getProp($insert_data, 'gender'),
  2280. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2281. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2282. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2283. 'pitch' => getProp($insert_data, 'pitch', 0),
  2284. ];
  2285. // 插入视频配音合成任务
  2286. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2287. 'alias_segment_id' => $segment_id,
  2288. 'generate_status' => '执行中',
  2289. 'audio_url' => '',
  2290. 'generate_json' => json_encode($generate_json, 256),
  2291. 'created_at' => $now,
  2292. 'updated_at' => $now,
  2293. ]);
  2294. if (!$dubTaskId) {
  2295. Utils::throwError('20003:创建配音任务失败!');
  2296. }
  2297. $insert_data['audio_url'] = '';
  2298. } else {
  2299. // dialogue为空时,直接写入默认音频信息
  2300. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2301. $insert_data['audio_duration'] = 2.0;
  2302. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2303. }
  2304. // 如果没有上传图片则使用当前描述进行生成
  2305. if (!$img_url) {
  2306. // 解析分镜内容,提取画面描述作为主要提示词
  2307. $prompt = $final_segment_content;
  2308. $ref_img_urls = [];
  2309. // 分镜场景
  2310. $scene = getProp($insert_data, 'scene');
  2311. if ($scene) {
  2312. $matched_scene = '';
  2313. if (isset($scene_map[$scene])) {
  2314. $img_index = count($ref_img_urls) + 1;
  2315. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2316. $ref_img_urls[] = $scene_map[$scene];
  2317. $matched_scene = $scene;
  2318. }
  2319. $update_data['scene'] = $scene;
  2320. }
  2321. // 分镜角色
  2322. $characters = getProp($insert_data, 'characters');
  2323. if ($characters) {
  2324. $update_data['characters'] = $characters;
  2325. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2326. $characters = explode(',', $characters);
  2327. // 从分镜内容中提取涉及的角色
  2328. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2329. // 获取匹配角色的参考图
  2330. foreach ($segment_characters as $character) {
  2331. if (isset($role_map[$character])) {
  2332. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2333. $img_index = count($ref_img_urls) + 1;
  2334. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2335. $ref_img_urls[] = $role_map[$character];
  2336. }
  2337. }
  2338. }
  2339. // 如果没有找到匹配的角色参考图,不使用参考图
  2340. if (empty($ref_img_urls)) {
  2341. $ref_img_urls = [];
  2342. }
  2343. // 准备生成任务参数
  2344. $params = [
  2345. 'alias_segment_id' => $segment_id,
  2346. 'prompt' => $prompt,
  2347. 'ref_img_urls' => $ref_img_urls,
  2348. 'width' => $width,
  2349. 'height' => $height,
  2350. ];
  2351. // 调用AI图片生成服务
  2352. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2353. $task_id = $task->id;
  2354. // $task_id = 'whatever';
  2355. if (!$task_id) {
  2356. Utils::throwError('20003:创建生成任务失败!');
  2357. }
  2358. $insert_data['pic_task_status'] = '生成中';
  2359. $insert_data['pic_task_id'] = $task_id;
  2360. }
  2361. // 先更新序号
  2362. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2363. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2364. if (!$boolen) {
  2365. Utils::throwError('20003:新增分镜失败!');
  2366. }
  2367. // 如果是第一集的首帧图片,则存入待更新数组
  2368. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2369. Redis::sadd('anime_first_frame_urls', $segment_id);
  2370. }
  2371. if ($dubTaskId) {
  2372. // 请求远程服务器执行生成
  2373. $client = new Client(['timeout' => 300, 'verify' => false]);
  2374. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2375. $response = $result->getBody()->getContents();
  2376. $response_arr = json_decode($response, true);
  2377. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2378. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2379. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2380. Utils::throwError('20003:火山生成音频失败');
  2381. }
  2382. }
  2383. } catch (\Exception $e) {
  2384. DB::rollBack();
  2385. Utils::throwError('20003:'.$e->getMessage());
  2386. }
  2387. DB::commit();
  2388. // 创建任务之后先暂停10s等待异步任务完成
  2389. sleep(10);
  2390. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2391. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2392. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2393. $segment = $segment ? (array)$segment : [];
  2394. return $segment;
  2395. }
  2396. public function copySegment($data) {
  2397. $segment_id = getProp($data, 'segment_id');
  2398. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2399. if (!$segment) Utils::throwError('20003:请选择分镜');
  2400. $anime_id = getProp($segment, 'anime_id');
  2401. $episode_id = getProp($segment, 'episode_id');
  2402. $episode_number = getProp($segment, 'episode_number');
  2403. $segment_number = getProp($segment, 'segment_number');
  2404. $new_segment_id = 0;
  2405. try {
  2406. DB::beginTransaction();
  2407. $segment = (array)$segment;
  2408. unset($segment['id']);
  2409. $segment['segment_number'] += 1;
  2410. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2411. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2412. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2413. // 更新其他分镜序号
  2414. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2415. // 复制分镜
  2416. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2417. if (!$id) {
  2418. Utils::throwError('20003:复制分镜失败');
  2419. }
  2420. }catch (\Exception $e) {
  2421. DB::rollBack();
  2422. Utils::throwError('20003:'.$e->getMessage());
  2423. }
  2424. DB::commit();
  2425. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2426. $segment = $segment ? (array)$segment : [];
  2427. return $segment;
  2428. }
  2429. public function moveSegment($data) {
  2430. $segment_id = getProp($data, 'segment_id');
  2431. $target_segment_id = getProp($data, 'target_segment_id');
  2432. // 获取源分镜信息
  2433. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2434. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2435. // 获取目标分镜信息
  2436. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2437. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2438. $anime_id = getProp($source_segment, 'anime_id');
  2439. $episode_id = getProp($source_segment, 'episode_id');
  2440. $episode_number = getProp($source_segment, 'episode_number');
  2441. $source_segment_number = getProp($source_segment, 'segment_number');
  2442. $target_segment_number = getProp($target_segment, 'segment_number');
  2443. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2444. $target_anime_id = getProp($target_segment, 'anime_id');
  2445. $target_episode_number = getProp($target_segment, 'episode_number');
  2446. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2447. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2448. }
  2449. // 如果源分镜和目标分镜相同,无需移动
  2450. if ($source_segment_number == $target_segment_number) {
  2451. return true;
  2452. }
  2453. try {
  2454. DB::beginTransaction();
  2455. if ($source_segment_number < $target_segment_number) {
  2456. // 向后移动:源分镜移动到目标分镜之后
  2457. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2458. DB::table('mp_episode_segments')
  2459. ->where('anime_id', $anime_id)
  2460. ->where('episode_id', $episode_id)
  2461. ->where('segment_number', '>', $source_segment_number)
  2462. ->where('segment_number', '<=', $target_segment_number)
  2463. ->decrement('segment_number');
  2464. // 2. 将源分镜移动到目标分镜之后
  2465. $new_segment_number = $target_segment_number;
  2466. } else {
  2467. // 向前移动:源分镜移动到目标分镜之后
  2468. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2469. DB::table('mp_episode_segments')
  2470. ->where('anime_id', $anime_id)
  2471. ->where('episode_id', $episode_id)
  2472. ->where('segment_number', '>', $target_segment_number)
  2473. ->where('segment_number', '<', $source_segment_number)
  2474. ->increment('segment_number');
  2475. // 2. 将源分镜移动到目标分镜之后
  2476. $new_segment_number = $target_segment_number + 1;
  2477. }
  2478. // 3. 更新源分镜的序号
  2479. $update_result = DB::table('mp_episode_segments')
  2480. ->where('segment_id', $segment_id)
  2481. ->update([
  2482. 'segment_number' => $new_segment_number,
  2483. 'updated_at' => date('Y-m-d H:i:s')
  2484. ]);
  2485. if (!$update_result) {
  2486. Utils::throwError('20003:更新分镜序号失败');
  2487. }
  2488. DB::commit();
  2489. return true;
  2490. } catch (\Exception $e) {
  2491. DB::rollBack();
  2492. Utils::throwError('20003:' . $e->getMessage());
  2493. }
  2494. }
  2495. public function delSegment($data) {
  2496. $segment_id = getProp($data, 'segment_id');
  2497. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2498. if (!$segment) Utils::throwError('20003:请选择分镜');
  2499. $anime_id = getProp($segment, 'anime_id');
  2500. $episode_id = getProp($segment, 'episode_id');
  2501. $episode_number = getProp($segment, 'episode_number');
  2502. $segment_number = getProp($segment, 'segment_number');
  2503. try {
  2504. DB::beginTransaction();
  2505. // 删除分镜
  2506. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2507. if (!$boolen) {
  2508. Utils::throwError('20003:删除分镜失败');
  2509. }
  2510. // 更新其他分镜序号
  2511. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2512. }catch (\Exception $e) {
  2513. DB::rollBack();
  2514. Utils::throwError('20003:'.$e->getMessage());
  2515. }
  2516. DB::commit();
  2517. return true;
  2518. }
  2519. public function applySegment($data) {
  2520. $segment_id = getProp($data, 'segment_id');
  2521. $url = getProp($data, 'url');
  2522. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2523. if (!$url) Utils::throwError('20003:URL不能为空');
  2524. // 获取URL的文件扩展名
  2525. $urlPath = parse_url($url, PHP_URL_PATH);
  2526. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2527. // 定义图片和视频的扩展名
  2528. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2529. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2530. // 判断是图片还是视频
  2531. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2532. if (in_array($extension, $imageExtensions)) {
  2533. // 图片类型
  2534. $updateData['img_url'] = $url;
  2535. $updateData['current_type'] = 1;
  2536. } elseif (in_array($extension, $videoExtensions)) {
  2537. // 视频类型
  2538. $updateData['video_url'] = $url;
  2539. $updateData['current_type'] = 2;
  2540. } else {
  2541. Utils::throwError('20003:不支持的文件类型');
  2542. }
  2543. // 更新分镜表
  2544. $result = DB::table('mp_episode_segments')
  2545. ->where('segment_id', $segment_id)
  2546. ->update($updateData);
  2547. if (!$result) {
  2548. Utils::throwError('20003:更新分镜失败');
  2549. }
  2550. return true;
  2551. }
  2552. public function segmentHistory($data) {
  2553. $segment_id = getProp($data, 'segment_id');
  2554. // 获取历史图片
  2555. $pics = [];
  2556. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2557. foreach($pic_history as $task) {
  2558. $result_url = getProp($task, 'result_url');
  2559. if (is_json($result_url)) {
  2560. $pics = array_merge($pics, json_decode($result_url, true));
  2561. }else {
  2562. $pics[] = $result_url;
  2563. }
  2564. }
  2565. // 获取历史视频
  2566. $videos = [];
  2567. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2568. foreach($video_history as $task) {
  2569. $result_url = getProp($task, 'result_url');
  2570. if (is_json($result_url)) {
  2571. $videos = array_merge($videos, json_decode($result_url, true));
  2572. }else {
  2573. $videos[] = $result_url;
  2574. }
  2575. }
  2576. return compact('pics', 'videos');
  2577. }
  2578. public function addAct($data) {
  2579. $prev_act_id = getProp($data, 'prev_act_id');
  2580. $act_title = getProp($data, 'act_title', '');
  2581. $act_content = getProp($data, 'act_content', '');
  2582. $act_duration = getProp($data, 'act_duration', 5);
  2583. $video_url = getProp($data, 'video_url');
  2584. // 根据prev_act_id获取记录
  2585. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2586. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2587. $anime_id = getProp($prev_segment, 'anime_id');
  2588. $episode_id = getProp($prev_segment, 'episode_id');
  2589. $episode_number = getProp($prev_segment, 'episode_number');
  2590. $prev_act_number = getProp($prev_segment, 'act_number');
  2591. // 获取新的act_number
  2592. $new_act_number = $prev_act_number + 1;
  2593. try {
  2594. DB::beginTransaction();
  2595. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2596. DB::table('mp_episode_segments')
  2597. ->where('anime_id', $anime_id)
  2598. ->where('episode_id', $episode_id)
  2599. ->where('act_number', '>', $prev_act_number)
  2600. ->increment('act_number');
  2601. // 插入新片段记录
  2602. $insert_data = [
  2603. 'anime_id' => $anime_id,
  2604. 'episode_id' => $episode_id,
  2605. 'episode_number' => $episode_number,
  2606. 'act_number' => $new_act_number,
  2607. 'created_at' => date('Y-m-d H:i:s'),
  2608. 'updated_at' => date('Y-m-d H:i:s')
  2609. ];
  2610. if ($act_title) {
  2611. $insert_data['act_title'] = $act_title;
  2612. }
  2613. if ($act_content) {
  2614. $insert_data['act_content'] = $act_content;
  2615. }
  2616. if ($act_duration) {
  2617. $insert_data['act_duration'] = $act_duration;
  2618. }
  2619. if ($video_url) {
  2620. $insert_data['origin_video_url'] = $video_url;
  2621. $insert_data['current_type'] = 2;
  2622. $compressed_video_url = compressVideo($video_url);
  2623. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2624. }
  2625. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2626. if (!$id) {
  2627. Utils::throwError('20003:新增片段失败!');
  2628. }
  2629. DB::commit();
  2630. }catch (\Exception $e) {
  2631. DB::rollBack();
  2632. Utils::throwError('20003:'.$e->getMessage());
  2633. }
  2634. $segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
  2635. $segment = $segment ? (array)$segment : [];
  2636. return $segment;
  2637. }
  2638. public function editAct($data) {
  2639. $act_id = getProp($data, 'act_id');
  2640. $act_content = getProp($data, 'act_content');
  2641. $act_duration = getProp($data, 'act_duration');
  2642. $act_title = getProp($data, 'act_title');
  2643. $image_url = getProp($data, 'image_url');
  2644. $video_url = getProp($data, 'video_url');
  2645. // 参数验证
  2646. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2647. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2648. $segment = DB::table('mp_episode_segments')
  2649. ->where('id', $act_id)
  2650. ->first();
  2651. if (!$segment) Utils::throwError('20003:该片段不存在');
  2652. try {
  2653. DB::beginTransaction();
  2654. // 准备更新数据
  2655. $update_data = [
  2656. 'updated_at' => date('Y-m-d H:i:s')
  2657. ];
  2658. // 更新act相关字段
  2659. if (!empty($act_content)) {
  2660. $update_data['act_show_content'] = $act_content;
  2661. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2662. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2663. $shot_counter = 0;
  2664. $update_data['act_show_content'] = preg_replace_callback(
  2665. '/【(?:镜头|分镜)(\d+)】/u',
  2666. function($matches) use (&$shot_counter) {
  2667. $shot_counter++;
  2668. return '【镜头' . $shot_counter . '】';
  2669. },
  2670. $update_data['act_show_content']
  2671. );
  2672. }
  2673. if (!empty($act_duration)) {
  2674. $update_data['act_duration'] = $act_duration;
  2675. }
  2676. if (!empty($act_title)) {
  2677. $update_data['act_title'] = $act_title;
  2678. }
  2679. // 处理图片上传
  2680. if ($image_url) {
  2681. $update_data['img_url'] = $image_url;
  2682. $update_data['current_type'] = 1;
  2683. // 同时写入一个图片生成任务记录
  2684. if ($act_id) {
  2685. $pic_task = [
  2686. 'alias_act_id' => $act_id,
  2687. 'ref_img_url' => json_encode([]),
  2688. 'status' => 'success',
  2689. 'result_url' => json_encode([$image_url], 256),
  2690. 'model' => '',
  2691. 'created_at' => date('Y-m-d H:i:s'),
  2692. 'updated_at' => date('Y-m-d H:i:s'),
  2693. ];
  2694. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2695. }
  2696. }
  2697. // 处理视频上传
  2698. if ($video_url) {
  2699. $update_data['origin_video_url'] = $video_url;
  2700. $compressed_video_url = compressVideo($video_url);
  2701. $update_data['current_type'] = 2;
  2702. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2703. // 同时写入一个视频生成任务记录
  2704. if ($act_id) {
  2705. $video_task = [
  2706. 'alias_act_id' => $act_id,
  2707. 'status' => 'success',
  2708. 'result_url' => $update_data['origin_video_url'],
  2709. 'compressed_url' => $update_data['video_url'],
  2710. 'created_at' => date('Y-m-d H:i:s'),
  2711. 'updated_at' => date('Y-m-d H:i:s'),
  2712. ];
  2713. DB::table('mp_generate_video_tasks')->insert($video_task);
  2714. }
  2715. }
  2716. // 更新片段信息
  2717. $result = DB::table('mp_episode_segments')
  2718. ->where('id', $act_id)
  2719. ->update($update_data);
  2720. if ($result === false) {
  2721. Utils::throwError('20003:更新片段失败');
  2722. }
  2723. DB::commit();
  2724. // 返回新复制的记录
  2725. $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,act_show_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $act_id)->first();
  2726. $new_segment = (array)$new_segment;
  2727. return $new_segment;
  2728. } catch (\Exception $e) {
  2729. DB::rollBack();
  2730. dLog('anime')->error('更新片段失败', [
  2731. 'act_id' => $act_id,
  2732. 'error' => $e->getMessage()
  2733. ]);
  2734. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2735. }
  2736. }
  2737. public function copyAct($data) {
  2738. $act_id = getProp($data, 'act_id');
  2739. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2740. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2741. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2742. $anime_id = getProp($source_segment, 'anime_id');
  2743. $episode_id = getProp($source_segment, 'episode_id');
  2744. $episode_number = getProp($source_segment, 'episode_number');
  2745. $act_number = getProp($source_segment, 'act_number');
  2746. try {
  2747. DB::beginTransaction();
  2748. // 新act的编号
  2749. $new_act_number = $act_number + 1;
  2750. // 更新后续所有act的act_number
  2751. DB::table('mp_episode_segments')
  2752. ->where('anime_id', $anime_id)
  2753. ->where('episode_id', $episode_id)
  2754. ->where('act_number', '>', $act_number)
  2755. ->increment('act_number');
  2756. // 复制该片段记录
  2757. $segment_data = (array)$source_segment;
  2758. unset($segment_data['id']);
  2759. $segment_data['video_url'] = '';
  2760. $segment_data['video_task_id'] = '';
  2761. $segment_data['video_task_status'] = '';
  2762. $segment_data['act_number'] = $new_act_number;
  2763. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2764. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2765. if (!$id) {
  2766. Utils::throwError('20003:复制片段失败');
  2767. }
  2768. DB::commit();
  2769. }catch (\Exception $e) {
  2770. DB::rollBack();
  2771. Utils::throwError('20003:'.$e->getMessage());
  2772. }
  2773. // 返回新复制的记录
  2774. $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,act_show_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
  2775. $new_segment = $new_segment ? (array)$new_segment : [];
  2776. $new_segment['act_id'] = $id;
  2777. return $new_segment;
  2778. }
  2779. public function moveAct($data) {
  2780. $act_id = getProp($data, 'act_id');
  2781. $target_act_id = getProp($data, 'target_act_id');
  2782. // 获取源片段信息
  2783. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2784. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2785. // 获取目标片段信息
  2786. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2787. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2788. $anime_id = getProp($source_segment, 'anime_id');
  2789. $episode_id = getProp($source_segment, 'episode_id');
  2790. $source_act_number = getProp($source_segment, 'act_number');
  2791. $target_act_number = getProp($target_segment, 'act_number');
  2792. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2793. $target_anime_id = getProp($target_segment, 'anime_id');
  2794. $target_episode_id = getProp($target_segment, 'episode_id');
  2795. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2796. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2797. }
  2798. // 如果源片段和目标片段相同,无需移动
  2799. if ($source_act_number == $target_act_number) {
  2800. return true;
  2801. }
  2802. try {
  2803. DB::beginTransaction();
  2804. if ($source_act_number < $target_act_number) {
  2805. // 向后移动:源片段移动到目标片段之后
  2806. // 1. 将源片段和目标片段之间的所有片段编号减1
  2807. DB::table('mp_episode_segments')
  2808. ->where('anime_id', $anime_id)
  2809. ->where('episode_id', $episode_id)
  2810. ->where('act_number', '>', $source_act_number)
  2811. ->where('act_number', '<=', $target_act_number)
  2812. ->decrement('act_number');
  2813. // 2. 将源片段移动到目标片段之后
  2814. $new_act_number = $target_act_number;
  2815. } else {
  2816. // 向前移动:源片段移动到目标片段之后
  2817. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2818. DB::table('mp_episode_segments')
  2819. ->where('anime_id', $anime_id)
  2820. ->where('episode_id', $episode_id)
  2821. ->where('act_number', '>', $target_act_number)
  2822. ->where('act_number', '<', $source_act_number)
  2823. ->increment('act_number');
  2824. // 2. 将源片段移动到目标片段之后
  2825. $new_act_number = $target_act_number + 1;
  2826. }
  2827. // 3. 更新源片段的编号
  2828. $update_result = DB::table('mp_episode_segments')
  2829. ->where('id', $act_id)
  2830. ->update([
  2831. 'act_number' => $new_act_number,
  2832. 'updated_at' => date('Y-m-d H:i:s')
  2833. ]);
  2834. if (!$update_result) {
  2835. Utils::throwError('20003:更新片段编号失败');
  2836. }
  2837. DB::commit();
  2838. return true;
  2839. } catch (\Exception $e) {
  2840. DB::rollBack();
  2841. Utils::throwError('20003:' . $e->getMessage());
  2842. }
  2843. }
  2844. public function delAct($data) {
  2845. $act_id = getProp($data, 'act_id');
  2846. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2847. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2848. if (!$segment) Utils::throwError('20003:请选择片段');
  2849. $anime_id = getProp($segment, 'anime_id');
  2850. $episode_id = getProp($segment, 'episode_id');
  2851. $act_number = getProp($segment, 'act_number');
  2852. try {
  2853. DB::beginTransaction();
  2854. // 删除该片段记录
  2855. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2856. if (!$deleted) {
  2857. Utils::throwError('20003:删除片段失败');
  2858. }
  2859. // 更新后续act的编号
  2860. DB::table('mp_episode_segments')
  2861. ->where('anime_id', $anime_id)
  2862. ->where('episode_id', $episode_id)
  2863. ->where('act_number', '>', $act_number)
  2864. ->decrement('act_number');
  2865. DB::commit();
  2866. }catch (\Exception $e) {
  2867. DB::rollBack();
  2868. Utils::throwError('20003:'.$e->getMessage());
  2869. }
  2870. return true;
  2871. }
  2872. public function applyAct($data) {
  2873. $act_id = getProp($data, 'act_id');
  2874. $url = getProp($data, 'url');
  2875. if (!$act_id) Utils::throwError('20003:请选择片段');
  2876. if (!$url) Utils::throwError('20003:URL不能为空');
  2877. // 获取URL的文件扩展名
  2878. $urlPath = parse_url($url, PHP_URL_PATH);
  2879. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2880. // 定义图片和视频的扩展名
  2881. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2882. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2883. // 判断是图片还是视频
  2884. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2885. if (in_array($extension, $imageExtensions)) {
  2886. // 图片类型
  2887. $updateData['img_url'] = $url;
  2888. $updateData['current_type'] = 1;
  2889. } elseif (in_array($extension, $videoExtensions)) {
  2890. // 视频类型
  2891. $updateData['video_url'] = $url;
  2892. $updateData['current_type'] = 2;
  2893. } else {
  2894. Utils::throwError('20003:不支持的文件类型');
  2895. }
  2896. // 更新片段记录(全能模式下每个act只有一条记录)
  2897. $result = DB::table('mp_episode_segments')
  2898. ->where('id', $act_id)
  2899. ->update($updateData);
  2900. if (!$result) {
  2901. Utils::throwError('20003:更新片段失败');
  2902. }
  2903. return true;
  2904. }
  2905. public function actChatHistory($data) {
  2906. $act_id = getProp($data, 'act_id');
  2907. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2908. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'video_task_id', 'pic_task_id', 'reference_images', 'created_at');
  2909. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2910. $value = (array)$value;
  2911. $value['created_at'] = transDate($value['created_at']);
  2912. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2913. else $value['reference_images'] = [];
  2914. return $value;
  2915. })->toArray();
  2916. // 获取历史图片
  2917. $url = [];
  2918. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2919. foreach($pic_history as $task) {
  2920. $result_url = getProp($task, 'result_url');
  2921. if (is_json($result_url)) {
  2922. $url = array_merge($url, json_decode($result_url, true));
  2923. }else {
  2924. $url[] = $result_url;
  2925. }
  2926. }
  2927. // 获取历史视频
  2928. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2929. foreach($video_history as $task) {
  2930. $result_url = getProp($task, 'result_url');
  2931. if (is_json($result_url)) {
  2932. $url = array_merge($url, json_decode($result_url, true));
  2933. }else {
  2934. $url[] = $result_url;
  2935. }
  2936. }
  2937. // 获取资产库
  2938. $products = [];
  2939. // 通过act_id查询片段信息获取episode_id
  2940. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2941. if ($segment) {
  2942. $episode_id = getProp($segment, 'episode_id');
  2943. // 查询剧集信息获取roles、scenes和extra_products
  2944. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2945. if ($episode) {
  2946. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2947. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2948. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2949. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2950. // 先合并roles、scenes和props
  2951. // 处理角色数组
  2952. foreach ($roles as $role) {
  2953. $product = $role;
  2954. // 将role字段重命名为product_name
  2955. if (is_array($product) && !empty($product['role'] ?? null)) {
  2956. $product['product_name'] = $product['role'];
  2957. unset($product['role']);
  2958. $product['product'] = 1; // 标记类型为角色
  2959. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2960. }
  2961. }
  2962. // 处理场景数组
  2963. foreach ($scenes as $scene) {
  2964. $product = $scene;
  2965. // 将scene字段重命名为product_name
  2966. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2967. $product['product_name'] = $product['scene'];
  2968. unset($product['scene']);
  2969. $product['product'] = 2; // 标记类型为场景
  2970. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2971. }
  2972. }
  2973. // 处理道具数组
  2974. foreach ($props as $prop) {
  2975. $product = $prop;
  2976. // 将prop字段重命名为product_name
  2977. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2978. $product['product_name'] = $product['prop'];
  2979. unset($product['prop']);
  2980. $product['product'] = 3; // 标记类型为道具
  2981. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2982. }
  2983. }
  2984. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2985. foreach ($extra_products as $extra_product) {
  2986. $product_name = getProp($extra_product, 'product_name');
  2987. if ($product_name) {
  2988. $products[$product_name] = $extra_product; // 覆盖同名数据
  2989. }
  2990. }
  2991. // 重新索引数组(去除key)
  2992. $products = array_values($products);
  2993. }
  2994. }
  2995. // 获取执行中的任务
  2996. $tasks = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->whereNotIn('status', ['success', 'failed'])->select('id as task_id', 'alias_act_id', 'prompt', 'ref_image_url', 'status')->orderBy('id')->get()->map(function($value) {
  2997. $value = (array)$value;
  2998. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2999. else $value['ref_image_url'] = [];
  3000. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  3001. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  3002. if (!empty($value['prompt'])) {
  3003. $prompt = $value['prompt'];
  3004. // 查找第一个【镜头】的位置
  3005. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  3006. // 从【镜头】开始截取
  3007. $prompt = substr($prompt, $matches[0][1]);
  3008. }
  3009. // 去除所有<图片X>格式的标记(X可以是任意数字)
  3010. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  3011. $value['prompt'] = $prompt;
  3012. }
  3013. return $value;
  3014. })->toArray();
  3015. return compact('chat', 'url', 'products', 'tasks');
  3016. }
  3017. public function applyAudioData($data) {
  3018. $segment_id = getProp($data, 'segment_id');
  3019. $global_data = getProp($data, 'global_data');
  3020. $segment_data = getProp($data, 'segment_data');
  3021. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3022. $global_data = is_array($global_data) ? $global_data : [];
  3023. $segment_data = is_array($segment_data) ? $segment_data : [];
  3024. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3025. $dialogue_item = null;
  3026. foreach ($global_data as $key => $item) {
  3027. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3028. $dialogue_item = $item;
  3029. unset($global_data[$key]);
  3030. break;
  3031. }
  3032. }
  3033. if ($dialogue_item) {
  3034. $segment_data[] = $dialogue_item;
  3035. }
  3036. // 特殊参数: audio_url,audio_duration,subtitle_info
  3037. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3038. // 如果不是全部存在,则仍需创建音频任务
  3039. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3040. $special_update_data = [];
  3041. $has_all_special_params = false;
  3042. // 从segment_data中提取特殊参数
  3043. $filtered_segment_data = [];
  3044. foreach ($segment_data as $item) {
  3045. $field_name = trim((string)getProp($item, 'name'));
  3046. if (in_array($field_name, $special_fields)) {
  3047. $special_update_data[$field_name] = getProp($item, 'value');
  3048. } else {
  3049. // 非特殊参数保留,继续后续处理
  3050. $filtered_segment_data[] = $item;
  3051. }
  3052. }
  3053. // 检查是否三个特殊参数都存在
  3054. if (count($special_update_data) === 3 &&
  3055. isset($special_update_data['audio_url']) &&
  3056. isset($special_update_data['audio_duration']) &&
  3057. isset($special_update_data['subtitle_info'])) {
  3058. $has_all_special_params = true;
  3059. // 立即更新到当前分镜
  3060. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3061. DB::table('mp_episode_segments')
  3062. ->where('segment_id', $segment_id)
  3063. ->update($special_update_data);
  3064. }
  3065. // 使用过滤后的segment_data继续处理其他参数
  3066. $segment_data = $filtered_segment_data;
  3067. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3068. $global_update_data = [];
  3069. $segment_update_data = [];
  3070. $global_voice_type = '';
  3071. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3072. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3073. $episode_id = getProp($target_segment, 'episode_id');
  3074. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3075. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3076. if (!$episode) Utils::throwError('20003:分集不存在');
  3077. foreach ($global_data as $item) {
  3078. $field_name = trim((string)getProp($item, 'name'));
  3079. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3080. continue;
  3081. }
  3082. $global_update_data[$field_name] = getProp($item, 'value');
  3083. if ($field_name === 'voice_type') {
  3084. $global_voice_type = trim((string)getProp($item, 'value'));
  3085. }
  3086. }
  3087. foreach ($segment_data as $item) {
  3088. $field_name = trim((string)getProp($item, 'name'));
  3089. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3090. continue;
  3091. }
  3092. $segment_update_data[$field_name] = getProp($item, 'value');
  3093. }
  3094. if ($global_voice_type) {
  3095. $timbre_info = DB::table('mp_timbres')
  3096. ->where('timbre_type', $global_voice_type)
  3097. ->select('audio_url', 'timbre_name')
  3098. ->first();
  3099. if ($timbre_info) {
  3100. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3101. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3102. }
  3103. }
  3104. try {
  3105. DB::beginTransaction();
  3106. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3107. $segment_ids_to_create_task = [];
  3108. $segments_data = [];
  3109. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3110. if (!empty($global_update_data)) {
  3111. // 如果角色不存在,则只更新当前分镜
  3112. if (!$target_voice_actor) {
  3113. // 只处理当前分镜
  3114. $affected_segments = DB::table('mp_episode_segments')
  3115. ->where('segment_id', $segment_id)
  3116. ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3117. ->get();
  3118. } else {
  3119. // 获取该角色的所有分镜
  3120. $affected_segments = DB::table('mp_episode_segments')
  3121. ->where('episode_id', $episode_id)
  3122. ->where('voice_actor', $target_voice_actor)
  3123. ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3124. ->get();
  3125. }
  3126. foreach ($affected_segments as $seg) {
  3127. $seg = (array)$seg;
  3128. $sid = getProp($seg, 'segment_id');
  3129. // 检查参数是否发生变化
  3130. $has_changed = false;
  3131. foreach ($global_update_data as $field => $new_value) {
  3132. $old_value = getProp($seg, $field);
  3133. if ($old_value != $new_value) {
  3134. $has_changed = true;
  3135. break;
  3136. }
  3137. }
  3138. if ($has_changed) {
  3139. $segment_ids_to_create_task[] = $sid;
  3140. $segments_data[$sid] = $seg;
  3141. }
  3142. }
  3143. // 只有在有变化的分镜时才更新
  3144. if (!empty($segment_ids_to_create_task)) {
  3145. $global_segment_update_data = $global_update_data;
  3146. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3147. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3148. DB::table('mp_episode_segments')
  3149. ->where('episode_id', $episode_id)
  3150. ->where('voice_actor', $target_voice_actor)
  3151. ->whereIn('segment_id', $segment_ids_to_create_task)
  3152. ->update($global_segment_update_data);
  3153. }
  3154. if ($global_voice_type) {
  3155. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3156. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3157. $roles_updated = false;
  3158. foreach ($episode_roles as &$role) {
  3159. // 通过 role 字段匹配角色名,而不是 voice_name
  3160. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3161. continue;
  3162. }
  3163. $role['voice_type'] = $global_voice_type;
  3164. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3165. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3166. $roles_updated = true;
  3167. }
  3168. unset($role);
  3169. if ($roles_updated) {
  3170. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3171. 'roles' => json_encode($episode_roles, 256),
  3172. 'updated_at' => date('Y-m-d H:i:s'),
  3173. ]);
  3174. }
  3175. }
  3176. }
  3177. // 如果有单个分镜更新,检查是否有变化
  3178. if (!empty($segment_update_data)) {
  3179. // 获取当前分镜数据
  3180. $current_segment = DB::table('mp_episode_segments')
  3181. ->where('segment_id', $segment_id)
  3182. ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3183. ->first();
  3184. if ($current_segment) {
  3185. $current_segment = (array)$current_segment;
  3186. // 检查参数是否发生变化
  3187. $has_changed = false;
  3188. foreach ($segment_update_data as $field => $new_value) {
  3189. $old_value = getProp($current_segment, $field);
  3190. if ($old_value != $new_value) {
  3191. $has_changed = true;
  3192. break;
  3193. }
  3194. }
  3195. if ($has_changed) {
  3196. // 如果该分镜还未在列表中,添加进去
  3197. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3198. $segment_ids_to_create_task[] = $segment_id;
  3199. $segments_data[$segment_id] = $current_segment;
  3200. }
  3201. // 更新分镜数据并清空音频URL
  3202. $segment_update_data['audio_url'] = '';
  3203. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3204. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3205. }
  3206. }
  3207. }
  3208. // 为所有有变化的分镜创建音频合成任务
  3209. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3210. if (!empty($segment_ids_to_create_task)) {
  3211. foreach ($segment_ids_to_create_task as $sid) {
  3212. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3213. if ($sid === $segment_id && $has_all_special_params) {
  3214. continue;
  3215. }
  3216. // 重新获取更新后的分镜数据
  3217. $updated_segment = DB::table('mp_episode_segments')
  3218. ->where('segment_id', $sid)
  3219. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3220. ->first();
  3221. if (!$updated_segment) continue;
  3222. $updated_segment = (array)$updated_segment;
  3223. // 检查dialogue是否为空
  3224. $dialogue = getProp($updated_segment, 'dialogue');
  3225. if (empty($dialogue)) {
  3226. // dialogue为空时,直接写入默认音频信息
  3227. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3228. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3229. 'audio_duration' => 2.0,
  3230. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3231. 'updated_at' => date('Y-m-d H:i:s')
  3232. ]);
  3233. continue;
  3234. }
  3235. $generate_json = [
  3236. 'text' => $dialogue,
  3237. 'role' => getProp($updated_segment, 'voice_actor'),
  3238. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3239. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3240. 'emotion' => getProp($updated_segment, 'emotion'),
  3241. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3242. 'gender' => getProp($updated_segment, 'gender'),
  3243. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3244. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3245. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3246. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3247. ];
  3248. // 插入视频配音合成任务
  3249. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3250. 'alias_segment_id' => $sid,
  3251. 'generate_status' => '执行中',
  3252. 'audio_url' => '',
  3253. 'generate_json' => json_encode($generate_json, 256),
  3254. 'created_at' => date('Y-m-d H:i:s'),
  3255. 'updated_at' => date('Y-m-d H:i:s'),
  3256. ]);
  3257. if (!$dubTaskId) {
  3258. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3259. continue;
  3260. }
  3261. // 将任务ID添加到Redis列表中
  3262. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3263. // 请求远程服务器执行生成
  3264. try {
  3265. sleep(1);
  3266. $client = new Client(['timeout' => 300, 'verify' => false]);
  3267. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3268. $response = $result->getBody()->getContents();
  3269. $response_arr = json_decode($response, true);
  3270. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3271. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3272. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3273. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3274. }
  3275. } catch (\Exception $e) {
  3276. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3277. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3278. }
  3279. }
  3280. }
  3281. DB::commit();
  3282. } catch (\Exception $e) {
  3283. DB::rollBack();
  3284. Utils::throwError('20003:'.$e->getMessage());
  3285. }
  3286. return true;
  3287. }
  3288. public function episodePicsInfo($data) {
  3289. $anime_id = getProp($data, 'anime_id');
  3290. $episode_id = getProp($data, 'episode_id');
  3291. // 参数验证
  3292. if (!$anime_id && !$episode_id) {
  3293. Utils::throwError('20003:请提供动漫ID或分集ID');
  3294. }
  3295. // 根据参数获取数据源
  3296. if ($episode_id) {
  3297. // 从剧集表获取
  3298. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3299. if (!$source) Utils::throwError('20003:该剧集不存在');
  3300. $table_name = 'mp_anime_episodes';
  3301. $id_field = 'id';
  3302. $id_value = $episode_id;
  3303. // 获取剧集的anime_id用于继承全局数据
  3304. $anime_id = getProp($source, 'anime_id');
  3305. } else {
  3306. // 从动漫表获取
  3307. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3308. if (!$source) Utils::throwError('20003:该动漫不存在');
  3309. $table_name = 'mp_animes';
  3310. $id_field = 'id';
  3311. $id_value = $anime_id;
  3312. }
  3313. $source = (array)$source;
  3314. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3315. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3316. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3317. // 如果是分集数据,需要处理继承和任务创建逻辑
  3318. if ($episode_id) {
  3319. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3320. }
  3321. // 返回生成器函数,用于 SSE 流式输出
  3322. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3323. $startTime = time();
  3324. $maxDuration = 600; // 10分钟超时
  3325. $checkInterval = 3; // 每3秒检查一次
  3326. // Redis 缓存键
  3327. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3328. // 生成当前数据的哈希值用于比较
  3329. $generateHash = function($roles, $scenes, $props) {
  3330. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3331. };
  3332. // 发送初始数据
  3333. $currentHash = $generateHash($roles, $scenes, $props);
  3334. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3335. echo "data: " . json_encode([
  3336. 'type' => 'init',
  3337. 'data' => [
  3338. 'roles' => $roles,
  3339. 'scenes' => $scenes,
  3340. 'props' => $props,
  3341. 'start_time' => $startTime
  3342. ]
  3343. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3344. if (ob_get_level() > 0) {
  3345. ob_flush();
  3346. }
  3347. flush();
  3348. // 持续轮询任务状态
  3349. while (time() - $startTime < $maxDuration) {
  3350. $hasProcessing = false;
  3351. $updated = false;
  3352. // 检查角色任务状态
  3353. foreach ($roles as $index => &$role) {
  3354. $task_id = getProp($role, 'task_id');
  3355. $task_status = getProp($role, 'task_status');
  3356. $existing_url = getProp($role, 'url');
  3357. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3358. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3359. $hasProcessing = ($task_status === 'processing');
  3360. // 查询任务状态
  3361. $task = DB::table('mp_generate_pic_tasks')
  3362. ->where('id', $task_id)
  3363. ->select('id', 'status', 'result_url', 'error_message')
  3364. ->first();
  3365. if ($task) {
  3366. $task = (array)$task;
  3367. $status = getProp($task, 'status');
  3368. // 如果任务完成或失败
  3369. if (in_array($status, ['success', 'failed'])) {
  3370. $role['task_status'] = $status;
  3371. if ($status === 'success') {
  3372. $result_url = getProp($task, 'result_url');
  3373. if ($result_url) {
  3374. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3375. if (is_array($result_urls) && !empty($result_urls[0])) {
  3376. $role['url'] = $result_urls[0];
  3377. }
  3378. }
  3379. }
  3380. $updated = true;
  3381. } else if ($status === 'processing') {
  3382. $hasProcessing = true;
  3383. }
  3384. }
  3385. }
  3386. }
  3387. // 检查场景任务状态
  3388. foreach ($scenes as $index => &$scene) {
  3389. $task_id = getProp($scene, 'task_id');
  3390. $task_status = getProp($scene, 'task_status');
  3391. $existing_url = getProp($scene, 'url');
  3392. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3393. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3394. $hasProcessing = ($task_status === 'processing');
  3395. // 查询任务状态
  3396. $task = DB::table('mp_generate_pic_tasks')
  3397. ->where('id', $task_id)
  3398. ->select('id', 'status', 'result_url', 'error_message')
  3399. ->first();
  3400. if ($task) {
  3401. $task = (array)$task;
  3402. $status = getProp($task, 'status');
  3403. // 如果任务完成或失败
  3404. if (in_array($status, ['success', 'failed'])) {
  3405. $scene['task_status'] = $status;
  3406. if ($status === 'success') {
  3407. $result_url = getProp($task, 'result_url');
  3408. if ($result_url) {
  3409. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3410. if (is_array($result_urls) && !empty($result_urls[0])) {
  3411. $scene['url'] = $result_urls[0];
  3412. }
  3413. }
  3414. }
  3415. $updated = true;
  3416. } else if ($status === 'processing') {
  3417. $hasProcessing = true;
  3418. }
  3419. }
  3420. }
  3421. }
  3422. // 检查道具任务状态
  3423. foreach ($props as $index => &$prop) {
  3424. $task_id = getProp($prop, 'task_id');
  3425. $task_status = getProp($prop, 'task_status');
  3426. $existing_url = getProp($prop, 'url');
  3427. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3428. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3429. $hasProcessing = ($task_status === 'processing');
  3430. // 查询任务状态
  3431. $task = DB::table('mp_generate_pic_tasks')
  3432. ->where('id', $task_id)
  3433. ->select('id', 'status', 'result_url', 'error_message')
  3434. ->first();
  3435. if ($task) {
  3436. $task = (array)$task;
  3437. $status = getProp($task, 'status');
  3438. // 如果任务完成或失败
  3439. if (in_array($status, ['success', 'failed'])) {
  3440. $prop['task_status'] = $status;
  3441. if ($status === 'success') {
  3442. $result_url = getProp($task, 'result_url');
  3443. if ($result_url) {
  3444. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3445. if (is_array($result_urls) && !empty($result_urls[0])) {
  3446. $prop['url'] = $result_urls[0];
  3447. }
  3448. }
  3449. }
  3450. $updated = true;
  3451. } else if ($status === 'processing') {
  3452. $hasProcessing = true;
  3453. }
  3454. }
  3455. }
  3456. }
  3457. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3458. if ($updated) {
  3459. $newHash = $generateHash($roles, $scenes, $props);
  3460. $cachedHash = Redis::get($cacheKey);
  3461. // 只有当数据真正变化时才更新数据库和发送事件
  3462. if ($newHash !== $cachedHash) {
  3463. try {
  3464. // 更新数据库
  3465. DB::table($table_name)->where($id_field, $id_value)->update([
  3466. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3467. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3468. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3469. 'updated_at' => date('Y-m-d H:i:s')
  3470. ]);
  3471. // 更新缓存
  3472. Redis::setex($cacheKey, 600, $newHash);
  3473. // 发送更新事件
  3474. echo "data: " . json_encode([
  3475. 'type' => 'update',
  3476. 'data' => [
  3477. 'roles' => $roles,
  3478. 'scenes' => $scenes,
  3479. 'props' => $props,
  3480. 'elapsed_time' => time() - $startTime
  3481. ]
  3482. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3483. if (ob_get_level() > 0) {
  3484. ob_flush();
  3485. }
  3486. flush();
  3487. } catch (\Exception $e) {
  3488. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3489. }
  3490. } else {
  3491. // 即使哈希相同,如果有URL更新也要发送事件
  3492. $hasUrlUpdate = false;
  3493. foreach ($roles as $role) {
  3494. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3495. $hasUrlUpdate = true;
  3496. break;
  3497. }
  3498. }
  3499. if (!$hasUrlUpdate) {
  3500. foreach ($scenes as $scene) {
  3501. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3502. $hasUrlUpdate = true;
  3503. break;
  3504. }
  3505. }
  3506. }
  3507. if (!$hasUrlUpdate) {
  3508. foreach ($props as $prop) {
  3509. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3510. $hasUrlUpdate = true;
  3511. break;
  3512. }
  3513. }
  3514. }
  3515. if ($hasUrlUpdate) {
  3516. // 强制更新数据库和发送事件
  3517. try {
  3518. DB::table($table_name)->where($id_field, $id_value)->update([
  3519. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3520. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3521. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3522. 'updated_at' => date('Y-m-d H:i:s')
  3523. ]);
  3524. // 更新缓存
  3525. Redis::setex($cacheKey, 600, $newHash);
  3526. // 发送更新事件
  3527. echo "data: " . json_encode([
  3528. 'type' => 'update',
  3529. 'data' => [
  3530. 'roles' => $roles,
  3531. 'scenes' => $scenes,
  3532. 'props' => $props,
  3533. 'elapsed_time' => time() - $startTime
  3534. ]
  3535. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3536. if (ob_get_level() > 0) {
  3537. ob_flush();
  3538. }
  3539. flush();
  3540. } catch (\Exception $e) {
  3541. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3542. }
  3543. }
  3544. }
  3545. }
  3546. // 如果所有任务都已完成,发送完成事件并退出
  3547. if (!$hasProcessing) {
  3548. // 查询数据库中的最终数据,确保返回最新的完整数据
  3549. try {
  3550. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3551. if ($finalSource) {
  3552. $finalSource = (array)$finalSource;
  3553. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3554. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3555. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3556. // 使用数据库中的最终数据
  3557. $roles = $finalRoles;
  3558. $scenes = $finalScenes;
  3559. $props = $finalProps;
  3560. }
  3561. } catch (\Exception $e) {
  3562. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3563. // 如果查询失败,继续使用内存中的数据
  3564. }
  3565. // 清理缓存
  3566. Redis::del($cacheKey);
  3567. echo "data: " . json_encode([
  3568. 'type' => 'completed',
  3569. 'data' => [
  3570. 'roles' => $roles,
  3571. 'scenes' => $scenes,
  3572. 'props' => $props,
  3573. 'total_time' => time() - $startTime
  3574. ]
  3575. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3576. if (ob_get_level() > 0) {
  3577. ob_flush();
  3578. }
  3579. flush();
  3580. break;
  3581. }
  3582. // 等待下次检查
  3583. sleep($checkInterval);
  3584. }
  3585. // 超时处理
  3586. if (time() - $startTime >= $maxDuration) {
  3587. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3588. try {
  3589. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3590. if ($finalSource) {
  3591. $finalSource = (array)$finalSource;
  3592. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3593. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3594. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3595. // 使用数据库中的最终数据
  3596. $roles = $finalRoles;
  3597. $scenes = $finalScenes;
  3598. $props = $finalProps;
  3599. }
  3600. } catch (\Exception $e) {
  3601. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3602. // 如果查询失败,继续使用内存中的数据
  3603. }
  3604. // 清理缓存
  3605. Redis::del($cacheKey);
  3606. echo "data: " . json_encode([
  3607. 'type' => 'timeout',
  3608. 'message' => '轮询超时,请刷新页面查看最新状态',
  3609. 'data' => [
  3610. 'roles' => $roles,
  3611. 'scenes' => $scenes,
  3612. 'props' => $props
  3613. ]
  3614. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3615. if (ob_get_level() > 0) {
  3616. ob_flush();
  3617. }
  3618. flush();
  3619. }
  3620. };
  3621. }
  3622. public function clipSegmentVideo($data) {
  3623. $segment_id = getProp($data, 'segment_id');
  3624. $video_time_point_start = getProp($data, 'video_time_point_start');
  3625. $video_time_point_end = getProp($data, 'video_time_point_end');
  3626. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3627. Utils::throwError('20003:参数异常');
  3628. }
  3629. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3630. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3631. }
  3632. $video_duration = $video_time_point_end - $video_time_point_start;
  3633. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3634. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3635. 'video_duration' => $video_duration,
  3636. 'video_time_point_start' => $video_time_point_start,
  3637. 'video_time_point_end' => $video_time_point_end,
  3638. 'updated_at' => date('Y-m-d H:i:s')
  3639. ]);
  3640. }
  3641. // 轮训获取图片任务结果
  3642. private function loopGetPicTaskResult($task_id) {
  3643. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3644. if (!$task) {
  3645. return '';
  3646. }
  3647. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3648. $model = getProp($task, 'model');
  3649. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3650. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3651. $isSyncModel = $isVolcModel || $isGptModel;
  3652. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3653. $start_count = 0;
  3654. $img_url = '';
  3655. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3656. sleep(3);
  3657. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3658. // 如果任务已经完成,直接返回结果
  3659. if ($task->status === 'success' && $task->result_url) {
  3660. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3661. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3662. }
  3663. // 如果任务已失败,返回空
  3664. if ($task->status === 'failed') {
  3665. return '';
  3666. }
  3667. if ($isSyncModel) continue;
  3668. // 查询任务状态
  3669. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3670. if ($statusInfo['status'] === 'success') {
  3671. $task->updateStatus('success', [
  3672. 'result_url' => $statusInfo['result_url'],
  3673. 'result_json' => $statusInfo['result_json'] ?? []
  3674. ]);
  3675. // 同步调整分镜图片状态和结果
  3676. if (getProp($task, 'alias_segment_id')) {
  3677. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3678. 'img_url' => $statusInfo['result_url'][0],
  3679. 'pic_task_status' => '已完成',
  3680. ]);
  3681. }
  3682. $img_url = $statusInfo['result_url'][0];
  3683. break;
  3684. } elseif ($statusInfo['status'] === 'failed') {
  3685. $task->updateStatus('failed', [
  3686. 'error_message' => $statusInfo['error_message'],
  3687. 'result_json' => $statusInfo['result_json'] ?? []
  3688. ]);
  3689. if (getProp($task, 'alias_segment_id')) {
  3690. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3691. 'pic_task_status' => '失败',
  3692. ]);
  3693. }
  3694. break;
  3695. }
  3696. $start_count++;
  3697. }
  3698. return $img_url;
  3699. }
  3700. /**
  3701. * 从分镜内容中提取涉及的角色
  3702. */
  3703. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3704. $found_characters = [];
  3705. foreach ($available_characters as $character) {
  3706. // 检查角色名称是否在分镜内容中出现
  3707. if (strpos($segment_content, $character) !== false) {
  3708. $found_characters[] = $character;
  3709. }
  3710. }
  3711. if (!$found_characters) {
  3712. foreach ($roles as $character) {
  3713. // 检查角色名称是否在分镜内容中出现
  3714. if (strpos($segment_content, $character) !== false) {
  3715. $found_characters[] = $character;
  3716. }
  3717. }
  3718. }
  3719. return array_unique($found_characters);
  3720. }
  3721. // 从分镜剧本中提取关键字段
  3722. private function handleSegmentContent(&$data) {
  3723. $segmentContent = getProp($data, 'segment_content');
  3724. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3725. $segmentData = [
  3726. 'description' => '',
  3727. 'composition' => '',
  3728. 'camera_movement' => '',
  3729. 'voice_actor' => '',
  3730. 'dialogue' => '',
  3731. 'frame_type' => '',
  3732. 'scene' => '', // 场景
  3733. 'characters' => '', // 出镜角色
  3734. 'tail_frame' => '', // 尾帧描述
  3735. 'emotion' => '中性', // 情感
  3736. 'gender' => '0', // 性别(0未知,1男,2女)
  3737. 'speed_ratio' => 0, // 语速
  3738. 'loudness_ratio' => 0, // 音量
  3739. 'emotion_scale' => 4, // 情感强度
  3740. 'pitch' => 0, // 音调
  3741. ];
  3742. // 用于存储需要从 segment_content 中移除的匹配项
  3743. $replaceEmptyArr = [];
  3744. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3745. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3746. $segmentData['description'] = trim($descMatch[1]);
  3747. $data['description'] = trim($descMatch[1]);
  3748. }
  3749. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3750. $segmentData['composition'] = trim($compMatch[1]);
  3751. $data['composition'] = trim($compMatch[1]);
  3752. }
  3753. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3754. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3755. $data['camera_movement'] = trim($cameraMatch[1]);
  3756. }
  3757. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3758. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3759. $data['voice_actor'] = trim($voiceMatch[1]);
  3760. }
  3761. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3762. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3763. $data['dialogue'] = trim($dialogueMatch[1]);
  3764. }
  3765. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3766. $segmentData['frame_type'] = trim($frameMatch[1]);
  3767. $data['frame_type'] = trim($frameMatch[1]);
  3768. }
  3769. // 场景字段
  3770. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3771. $segmentData['scene'] = trim($sceneMatch[1]);
  3772. $data['scene'] = trim($sceneMatch[1]);
  3773. }
  3774. // 出镜角色字段
  3775. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3776. $segmentData['characters'] = trim($charactersMatch[1]);
  3777. $data['characters'] = trim($charactersMatch[1]);
  3778. }
  3779. // 尾帧描述字段
  3780. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3781. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3782. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3783. }
  3784. // 情感字段
  3785. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3786. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3787. $segmentData['emotion'] = trim($emotionMatch[1]);
  3788. $data['emotion'] = trim($emotionMatch[1]);
  3789. }
  3790. // 性别字段
  3791. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3792. $replaceEmptyArr[] = trim($genderMatch[0]);
  3793. $genderStr = trim($genderMatch[1]);
  3794. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3795. $segmentData['gender'] = '1';
  3796. $data['gender'] = '1';
  3797. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3798. $segmentData['gender'] = '2';
  3799. $data['gender'] = '2';
  3800. } else {
  3801. $segmentData['gender'] = '0';
  3802. $data['gender'] = '0';
  3803. }
  3804. }
  3805. // 语速字段
  3806. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3807. $replaceEmptyArr[] = trim($speedMatch[0]);
  3808. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3809. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3810. }
  3811. // 音量字段
  3812. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3813. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3814. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3815. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3816. }
  3817. // 情感强度字段
  3818. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3819. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3820. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3821. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3822. }
  3823. // 音调字段
  3824. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3825. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3826. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3827. $data['pitch'] = (int)trim($pitchMatch[1]);
  3828. }
  3829. // 从 segment_content 中移除已提取的配音参数字段
  3830. if (!empty($replaceEmptyArr)) {
  3831. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3832. }
  3833. // 如果有配音角色,查询音色信息并验证情感
  3834. $voice_actor = $segmentData['voice_actor'];
  3835. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3836. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3837. $anime_id = getProp($data, 'anime_id');
  3838. $episode_id = getProp($data, 'episode_id');
  3839. // 优先从剧集的角色列表中查找
  3840. $roles = [];
  3841. if ($episode_id) {
  3842. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3843. if ($episode && getProp($episode, 'roles')) {
  3844. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3845. }
  3846. }
  3847. // 如果剧集中没有,从动漫的角色列表中查找
  3848. if (empty($roles) && $anime_id) {
  3849. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3850. if ($anime && getProp($anime, 'roles')) {
  3851. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3852. }
  3853. }
  3854. // 查找匹配的角色音色信息
  3855. $timbre_info = null;
  3856. foreach ($roles as $role) {
  3857. if (getProp($role, 'role') === $voice_actor) {
  3858. $timbre_info = $role;
  3859. break;
  3860. }
  3861. }
  3862. // 如果找到音色信息,添加到数据中
  3863. if ($timbre_info) {
  3864. $voice_type = getProp($timbre_info, 'voice_type');
  3865. $voice_name = getProp($timbre_info, 'voice_name');
  3866. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3867. if ($voice_type) {
  3868. $data['voice_type'] = $voice_type;
  3869. $segmentData['voice_type'] = $voice_type;
  3870. }
  3871. if ($voice_name) {
  3872. $data['voice_name'] = $voice_name;
  3873. $segmentData['voice_name'] = $voice_name;
  3874. }
  3875. if ($voice_audio_url) {
  3876. $data['voice_audio_url'] = $voice_audio_url;
  3877. $segmentData['voice_audio_url'] = $voice_audio_url;
  3878. }
  3879. // 验证情感是否在音色支持的情感列表中
  3880. if ($voice_type) {
  3881. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3882. if ($timbre_emotion) {
  3883. $timbre_emotion = explode(',', $timbre_emotion);
  3884. } else {
  3885. $timbre_emotion = [];
  3886. }
  3887. $emotion = getProp($segmentData, 'emotion', '中性');
  3888. if (!in_array($emotion, $timbre_emotion)) {
  3889. $emotion = '中性';
  3890. }
  3891. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3892. $emotion_list = array_flip($emotion_list);
  3893. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3894. $data['emotion_type'] = $emotion_type;
  3895. $segmentData['emotion_type'] = $emotion_type;
  3896. }
  3897. }
  3898. }
  3899. return $segmentData;
  3900. }
  3901. public function createSegmentVideoTask($data) {
  3902. $segment_id = getProp($data, 'segment_id');
  3903. $tail_frame = getProp($data, 'tail_frame');
  3904. $first_frame_url = getProp($data, 'first_frame_url');
  3905. $tail_frame_url = getProp($data, 'tail_frame_url');
  3906. $generate_audio = getProp($data, 'generate_audio', 0);
  3907. if (!$segment_id) {
  3908. Utils::throwError('1002:分镜ID不能为空');
  3909. }
  3910. // 获取分镜信息
  3911. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3912. if (!$segment) {
  3913. Utils::throwError('20003:分镜不存在');
  3914. }
  3915. $segment = (array)$segment;
  3916. $episode_id = getProp($segment, 'episode_id');
  3917. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3918. if (!$ratio) $ratio = '9:16';
  3919. // 获取分镜内容
  3920. $segmentContent = getProp($segment, 'segment_content', '');
  3921. // 检查 $segmentContent 中是否已有尾帧描述
  3922. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3923. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3924. $finalTailFrame = '';
  3925. if ($tail_frame) {
  3926. // 用户输入了尾帧描述,优先使用
  3927. $finalTailFrame = $tail_frame;
  3928. // 如果 segmentContent 中已有尾帧描述,需要替换
  3929. if ($contentHasTailFrame) {
  3930. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3931. }
  3932. } elseif ($contentHasTailFrame) {
  3933. // segmentContent 中有尾帧描述,使用它
  3934. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3935. } else {
  3936. // 两者都没有,使用分镜表中的尾帧描述
  3937. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3938. }
  3939. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3940. $hasDialogue = false;
  3941. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3942. $dialogue = trim($dialogueMatch[1]);
  3943. // 如果台词不为空且不是"无"
  3944. if (!empty($dialogue) && $dialogue !== '无') {
  3945. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3946. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3947. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3948. $hasDialogue = true;
  3949. }
  3950. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3951. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3952. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3953. if (!preg_match('/^[“]/', $dialogue)) {
  3954. $dialogue = '“' . $dialogue;
  3955. }
  3956. if (!preg_match('/[”]$/', $dialogue)) {
  3957. $dialogue .= '”';
  3958. }
  3959. // 将修改后的台词替换回 $segmentContent
  3960. $originalDialogue = $dialogueMatch[1];
  3961. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3962. }
  3963. }
  3964. // 构建完整的提示词
  3965. $fullPrompt = $segmentContent;
  3966. if ($finalTailFrame && !$contentHasTailFrame) {
  3967. // 只有当 segmentContent 中没有尾帧描述时才追加
  3968. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3969. }
  3970. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3971. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3972. $fullPrompt = trim($fullPrompt);
  3973. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3974. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3975. // 智能选择视频时长
  3976. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3977. $videoDuration = -1;
  3978. // 处理视频模型
  3979. $model = getProp($data, 'model');
  3980. if (!$model) {
  3981. // 用户没有输入,从episode表获取
  3982. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3983. $model = getProp($episode, 'video_model');
  3984. if (!$model) {
  3985. // episode表也没有,使用默认值
  3986. $model = 'doubao-seedance-1-5-pro-251215';
  3987. }
  3988. }
  3989. // 验证模型是否在可用模型表中
  3990. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3991. $model = 'doubao-seedance-1-5-pro-251215';
  3992. }
  3993. // 保存到episode表
  3994. $episode_id = getProp($segment, 'episode_id');
  3995. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3996. 'video_model' => $model,
  3997. 'updated_at' => date('Y-m-d H:i:s')
  3998. ]);
  3999. // 构建视频生成参数
  4000. $videoParams = [
  4001. 'model' => $model,
  4002. 'alias_segment_id' => $segment_id,
  4003. 'prompt' => trim($fullPrompt),
  4004. 'video_duration' => $videoDuration,
  4005. 'video_resolution' => '720P',
  4006. 'seed' => -1,
  4007. 'ratio' => $ratio,
  4008. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4009. 'draft' => false,
  4010. 'watermark' => false,
  4011. 'camera_fixed' => false,
  4012. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4013. ];
  4014. // 如果分镜有图片,作为首帧
  4015. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  4016. $hasVideo = !empty(getProp($segment, 'video_url'));
  4017. if ($hasImage) {
  4018. if ($first_frame_url) {
  4019. $videoParams['first_frame_url'] = $first_frame_url;
  4020. }else {
  4021. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4022. }
  4023. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4024. }
  4025. // 构建content数组
  4026. $videoParams['content'] = [
  4027. [
  4028. 'type' => 'text',
  4029. 'text' => $videoParams['prompt'],
  4030. ]
  4031. ];
  4032. // 如果有首帧图片,添加到content中
  4033. if ($hasImage) {
  4034. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
  4035. $videoParams['content'][] = [
  4036. 'type' => 'image_url',
  4037. 'image_url' => [
  4038. 'url' => $videoParams['first_frame_url'],
  4039. ],
  4040. 'role' => 'reference_image',
  4041. ];
  4042. if (isset($videoParams['tail_frame_url'])) {
  4043. $videoParams['content'][] = [
  4044. 'type' => 'image_url',
  4045. 'image_url' => [
  4046. 'url' => $videoParams['tail_frame_url'],
  4047. ],
  4048. 'role' => 'reference_image',
  4049. ];
  4050. }
  4051. }else {
  4052. $videoParams['content'][] = [
  4053. 'type' => 'image_url',
  4054. 'image_url' => [
  4055. 'url' => $videoParams['first_frame_url'],
  4056. ],
  4057. 'role' => 'first_frame',
  4058. ];
  4059. if (isset($videoParams['tail_frame_url'])) {
  4060. $videoParams['content'][] = [
  4061. 'type' => 'image_url',
  4062. 'image_url' => [
  4063. 'url' => $videoParams['tail_frame_url'],
  4064. ],
  4065. 'role' => 'last_frame',
  4066. ];
  4067. }
  4068. }
  4069. }
  4070. // 获取配音音频URL
  4071. $audioUrl = getProp($segment, 'audio_url');
  4072. $audioDuration = getProp($segment, 'audio_duration');
  4073. // 音频传入的前提:必须有至少一张图片或一个视频
  4074. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4075. // 余额预检:按预估时长计算所需积分,不足直接报错
  4076. $chargeDuration = (int)ceil((float)$audioDuration);
  4077. if ($chargeDuration <= 0) {
  4078. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4079. }
  4080. $this->pointsService->checkUserPointsEnough(
  4081. $this->pointsService->getVideoChargePoints([
  4082. 'model' => $model,
  4083. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4084. 'video_duration' => $chargeDuration,
  4085. 'ratio' => $ratio,
  4086. 'generate_audio' => $current_generate_audio,
  4087. ])
  4088. );
  4089. // dd($videoParams);
  4090. // 根据模型选择不同的视频生成方法
  4091. if (strpos($model, 'jimeng') !== false) {
  4092. // 即梦模型参数调整
  4093. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4094. unset($videoParams['content']); // 即梦不使用content格式
  4095. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4096. } elseif (strpos($model, 'kling') !== false) {
  4097. // Keling模型参数调整
  4098. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4099. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4100. unset($videoParams['ratio']);
  4101. unset($videoParams['content']); // Keling不使用content格式
  4102. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4103. } elseif (strpos($model, 'zhizhen') !== false) {
  4104. // 智帧20等新模型使用统一API
  4105. // 构建统一API参数
  4106. $unifiedParams = [
  4107. 'model_code' => $model,
  4108. 'alias_segment_id' => $segment_id,
  4109. 'prompt' => trim($fullPrompt),
  4110. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4111. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4112. 'video_ratio' => $ratio,
  4113. 'seed' => -1,
  4114. ];
  4115. // 构建parameters参数
  4116. $parameters = [
  4117. 'seconds' => $unifiedParams['video_duration'],
  4118. 'resolution' => $unifiedParams['video_resolution'],
  4119. 'ratio' => $ratio,
  4120. // 'video_mode' => 'multi_image',
  4121. // 'mode' => 'multi_image',
  4122. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4123. ];
  4124. $hasImage = false;
  4125. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4126. if ($hasImage) {
  4127. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4128. if (isset($videoParams['tail_frame_url'])) {
  4129. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4130. }
  4131. // 只有在有图片的情况下才能添加参考音频
  4132. if ($audioUrl) {
  4133. // $parameters['reference_audios'] = [$audioUrl];
  4134. }
  4135. } else {
  4136. // 没有图片时,记录错误日志
  4137. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4138. 'segment_id' => $segment_id,
  4139. 'model' => $model
  4140. ]);
  4141. }
  4142. $unifiedParams['parameters'] = $parameters;
  4143. // 调用统一API创建任务
  4144. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4145. } else {
  4146. // Seedance模型(默认)
  4147. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4148. if ($this->isKuaikuaiSeedanceModel($model)) {
  4149. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4150. if ($canUseAudio && $audioUrl) {
  4151. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4152. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4153. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4154. // 优化提示词,增加音频相关描述
  4155. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4156. $videoParams['prompt'] = $audioPrompt;
  4157. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4158. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4159. }
  4160. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4161. } elseif ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
  4162. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4163. // 添加配音音频到content中
  4164. $videoParams['content'][] = [
  4165. 'type' => 'audio_url',
  4166. 'audio_url' => [
  4167. 'url' => $audioUrl,
  4168. ],
  4169. 'role' => 'reference_audio',
  4170. ];
  4171. // 优化提示词,增加音频相关描述
  4172. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4173. $videoParams['prompt'] = $audioPrompt;
  4174. $videoParams['content'][0]['text'] = $audioPrompt;
  4175. } else {
  4176. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4177. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4178. }
  4179. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4180. }
  4181. }
  4182. // 更新分镜表的视频任务信息
  4183. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4184. 'video_task_id' => $task->id,
  4185. 'video_task_status' => '生成中',
  4186. 'generate_audio' => $generate_audio,
  4187. 'updated_at' => date('Y-m-d H:i:s')
  4188. ]);
  4189. return [
  4190. 'task_id' => $task->id,
  4191. 'status' => $task->status,
  4192. 'segment_id' => $segment_id,
  4193. 'video_duration' => $videoDuration
  4194. ];
  4195. }
  4196. /**
  4197. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4198. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4199. *
  4200. * @param string $model
  4201. * @return bool
  4202. */
  4203. public function isKuaikuaiSeedanceModel(string $model): bool
  4204. {
  4205. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4206. }
  4207. /**
  4208. * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
  4209. *
  4210. * @param string $model
  4211. * @return bool
  4212. */
  4213. public function isBaiduSeedanceModel(string $model): bool
  4214. {
  4215. return in_array($model, [
  4216. 'baidu-doubao-seedance-2-0-260128',
  4217. 'baidu-doubao-seedance-2-0-fast-260128',
  4218. 'baidu-doubao-seedance-2-0-mini-260615',
  4219. 'baidu-doubao-seedance-2-5-260628',
  4220. ], true);
  4221. }
  4222. /**
  4223. * 是否为海外百度Seedance(dreamina真人素材空间)模型
  4224. * 系统内使用 baidu-dreamina- 前缀名,请求网关时映射为 dreamina-* 原名
  4225. *
  4226. * @param string $model
  4227. * @return bool
  4228. */
  4229. public function isOverseasBaiduSeedanceModel(string $model): bool
  4230. {
  4231. return in_array($model, [
  4232. 'baidu-dreamina-seedance-2-0-260128',
  4233. 'baidu-dreamina-seedance-2-0-fast-260128',
  4234. 'baidu-dreamina-seedance-2-0-mini-260615',
  4235. 'baidu-dreamina-seedance-2-5-260628',
  4236. ], true);
  4237. }
  4238. /**
  4239. * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-doubao-* / baidu-dreamina-* / 快快AI seed-2 系列)
  4240. * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
  4241. *
  4242. * @param string $model
  4243. * @return bool
  4244. */
  4245. public function isSeedance20SeriesModel(string $model): bool
  4246. {
  4247. return strpos($model, 'doubao-seedance-2.0') !== false
  4248. || $this->isKuaikuaiSeedanceModel($model)
  4249. || $this->isBaiduSeedanceModel($model)
  4250. || $this->isOverseasBaiduSeedanceModel($model);
  4251. }
  4252. public function createActVideoTask($data) {
  4253. $act_id = getProp($data, 'act_id');
  4254. $first_frame_url = getProp($data, 'first_frame_url');
  4255. $tail_frame_url = getProp($data, 'tail_frame_url');
  4256. $generate_audio = getProp($data, 'generate_audio', 1);
  4257. $video_duration = getProp($data, 'video_duration');
  4258. $video_resolution = getProp($data, 'video_resolution');
  4259. $ratio = getProp($data, 'ratio');
  4260. $products = getProp($data, 'products', []);
  4261. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4262. if (!is_array($reference_images) || !is_array($products)) {
  4263. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4264. }
  4265. if (!$act_id) {
  4266. Utils::throwError('1002:片段ID不能为空');
  4267. }
  4268. // 获取片段信息
  4269. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4270. if (!$act) {
  4271. Utils::throwError('20003:片段不存在');
  4272. }
  4273. $act = (array)$act;
  4274. $anime_id = getProp($act, 'anime_id');
  4275. $episode_id = getProp($act, 'episode_id');
  4276. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4277. $ace_mode = getProp($anime, 'ace_mode');
  4278. $art_style_type = getProp($anime, 'art_style_type');
  4279. $art_style = getProp($anime, 'art_style');
  4280. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4281. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4282. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4283. // 将资产中新出现的资产放到extra_products中
  4284. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4285. if (!empty($products) && $episode) {
  4286. // 获取剧集中的角色、场景和道具列表
  4287. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4288. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4289. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4290. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4291. // 构建角色名称列表
  4292. $role_names = array_column($roles, 'role');
  4293. // 构建场景名称列表
  4294. $scene_names = array_column($scenes, 'scene');
  4295. // 构建道具名称列表
  4296. $prop_names = array_column($props, 'prop');
  4297. // 遍历传入的products
  4298. foreach ($products as $product) {
  4299. $product_name = getProp($product, 'product_name');
  4300. // 如果product_name不在roles、scenes和props中
  4301. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4302. // 查找是否在extra_products中存在同名的
  4303. $found = false;
  4304. foreach ($extra_products as $key => $extra_product) {
  4305. if (getProp($extra_product, 'product_name') === $product_name) {
  4306. // 有同名的则覆盖
  4307. $extra_products[$key] = $product;
  4308. $found = true;
  4309. break;
  4310. }
  4311. }
  4312. // 没有则新增
  4313. if (!$found) {
  4314. $extra_products[] = $product;
  4315. }
  4316. }
  4317. }
  4318. if ($extra_products) {
  4319. // 保存到数据库
  4320. DB::table('mp_anime_episodes')
  4321. ->where('id', $episode_id)
  4322. ->update([
  4323. 'extra_products' => json_encode($extra_products, 256),
  4324. 'updated_at' => date('Y-m-d H:i:s')
  4325. ]);
  4326. }
  4327. }
  4328. // 获取分镜内容
  4329. $actContent = getProp($act, 'act_show_content', '');
  4330. // 音效同出(默认使用)
  4331. $current_generate_audio = $generate_audio ? 1 : 0;
  4332. // 构建完整的提示词
  4333. $processResult = $this->processActContentWithProducts($actContent, $products);
  4334. $fullPrompt = $processResult['content'];
  4335. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4336. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4337. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4338. // 处理视频模型
  4339. $model = getProp($data, 'model');
  4340. if (!$model) {
  4341. $model = getProp($episode, 'video_model');
  4342. if (!$model) {
  4343. // episode表也没有,使用默认值
  4344. $model = 'seed-2';
  4345. }
  4346. }
  4347. // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
  4348. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  4349. if (!in_array($model, $valid_models)) {
  4350. $model = 'seed-2';
  4351. }
  4352. // 保存到episode表(仅在专用方法中更新模型)
  4353. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4354. // 'video_model' => $model,
  4355. // 'updated_at' => date('Y-m-d H:i:s')
  4356. // ]);
  4357. // 余额预检:按预估时长计算所需积分,不足直接报错
  4358. $chargeDuration = (int)$videoDuration;
  4359. if ($chargeDuration <= 0) {
  4360. $chargeDuration = 5; // 无时长时按默认5秒预估
  4361. }
  4362. $this->pointsService->checkUserPointsEnough(
  4363. $this->pointsService->getVideoChargePoints([
  4364. 'model' => $model,
  4365. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4366. 'video_duration' => $chargeDuration,
  4367. 'ratio' => $ratio,
  4368. 'generate_audio' => $current_generate_audio,
  4369. ])
  4370. );
  4371. // 构建视频生成参数
  4372. $videoParams = [
  4373. 'model' => $model,
  4374. 'alias_act_id' => $act_id,
  4375. 'prompt' => trim($fullPrompt),
  4376. 'video_duration' => $videoDuration,
  4377. 'video_resolution' => $video_resolution,
  4378. 'seed' => -1,
  4379. 'ratio' => $ratio,
  4380. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4381. 'draft' => false,
  4382. 'watermark' => false,
  4383. 'camera_fixed' => false,
  4384. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4385. ];
  4386. // 如果分镜有图片,作为首帧
  4387. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4388. $hasVideo = !empty(getProp($act, 'video_url'));
  4389. if ($hasImage) {
  4390. if ($first_frame_url) {
  4391. $videoParams['first_frame_url'] = $first_frame_url;
  4392. }else {
  4393. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4394. }
  4395. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4396. }
  4397. // 构建content数组
  4398. $videoParams['content'] = [
  4399. [
  4400. 'type' => 'text',
  4401. 'text' => $videoParams['prompt'],
  4402. ]
  4403. ];
  4404. // 如果有首帧图片,添加到content中
  4405. if ($hasImage) {
  4406. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
  4407. $videoParams['content'][] = [
  4408. 'type' => 'image_url',
  4409. 'image_url' => [
  4410. 'url' => $videoParams['first_frame_url'],
  4411. ],
  4412. 'role' => 'reference_image',
  4413. ];
  4414. if (isset($videoParams['tail_frame_url'])) {
  4415. $videoParams['content'][] = [
  4416. 'type' => 'image_url',
  4417. 'image_url' => [
  4418. 'url' => $videoParams['tail_frame_url'],
  4419. ],
  4420. 'role' => 'reference_image',
  4421. ];
  4422. }
  4423. }else {
  4424. $videoParams['content'][] = [
  4425. 'type' => 'image_url',
  4426. 'image_url' => [
  4427. 'url' => $videoParams['first_frame_url'],
  4428. ],
  4429. 'role' => 'first_frame',
  4430. ];
  4431. if (isset($videoParams['tail_frame_url'])) {
  4432. $videoParams['content'][] = [
  4433. 'type' => 'image_url',
  4434. 'image_url' => [
  4435. 'url' => $videoParams['tail_frame_url'],
  4436. ],
  4437. 'role' => 'last_frame',
  4438. ];
  4439. }
  4440. }
  4441. }
  4442. // dd($videoParams);
  4443. // 根据模型选择不同的视频生成方法
  4444. try {
  4445. if (strpos($model, 'jimeng') !== false) {
  4446. // 即梦模型参数调整
  4447. unset($videoParams['content']); // 即梦不使用content格式
  4448. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4449. } elseif (strpos($model, 'kling') !== false) {
  4450. // Keling模型参数调整
  4451. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4452. unset($videoParams['ratio']);
  4453. unset($videoParams['content']); // Keling不使用content格式
  4454. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4455. } elseif (strpos($model, 'zhizhen') !== false) {
  4456. // 智帧20等新模型使用统一API
  4457. // 构建统一API参数
  4458. $unifiedParams = [
  4459. 'model_code' => $model,
  4460. 'alias_act_id' => $act_id,
  4461. 'prompt' => trim($fullPrompt),
  4462. 'video_duration' => $videoDuration,
  4463. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4464. 'video_ratio' => $ratio,
  4465. 'seed' => -1,
  4466. ];
  4467. // 构建parameters参数
  4468. $parameters = [
  4469. 'seconds' => $unifiedParams['video_duration'],
  4470. 'resolution' => $unifiedParams['video_resolution'],
  4471. 'ratio' => $ratio,
  4472. // 'video_mode' => 'multi_image',
  4473. // 'mode' => 'multi_image',
  4474. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4475. ];
  4476. $hasImage = false;
  4477. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4478. if ($hasImage) {
  4479. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4480. if (isset($videoParams['tail_frame_url'])) {
  4481. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4482. }
  4483. } else {
  4484. // 没有图片时,记录错误日志
  4485. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4486. 'act_id' => $act_id,
  4487. 'model' => $model
  4488. ]);
  4489. }
  4490. if ($reference_images) {
  4491. // 限制只传入9张参考图
  4492. $reference_images = array_slice($reference_images, 0, 9);
  4493. // 在处理之前先保存原始reference_images到任务参数中
  4494. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4495. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4496. $parameters['reference_images'] = $reference_images;
  4497. $parameters['video_mode'] = 'multi_image';
  4498. $parameters['mode'] = 'multi_image';
  4499. }
  4500. $unifiedParams['parameters'] = $parameters;
  4501. // 调用统一API创建任务
  4502. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4503. } elseif ($this->isSeedance20SeriesModel($model)) {
  4504. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4505. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4506. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4507. // 保存原始参考图用于任务记录
  4508. $videoParams['reference_images'] = $reference_images;
  4509. if ($reference_images) {
  4510. // 限制只传入9张参考图
  4511. $reference_images = array_slice($reference_images, 0, 9);
  4512. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4513. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4514. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4515. $reference_image_assets = $isKuaikuai
  4516. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4517. : ($isDreamina
  4518. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $fullPrompt)
  4519. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt));
  4520. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4521. $videoParams['prompt'] = trim($fullPrompt);
  4522. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4523. $videoParams['reference_image_assets'] = $reference_image_assets;
  4524. }
  4525. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4526. if ($isKuaikuai) {
  4527. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4528. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4529. } else {
  4530. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4531. }
  4532. } else {
  4533. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4534. }
  4535. } catch (ApiException $e) {
  4536. // 上游调用抛出的网关异常统一做友好化处理;本地业务错误(非1001)保持原提示不变
  4537. if ($e->getCode() === 1001) {
  4538. Utils::throwError('1001:' . mapErrorMessage($e->getMessage()));
  4539. }
  4540. throw $e;
  4541. } catch (\Exception $e) {
  4542. // 其他未包装的异常,同样只对报错信息做格式化,便于前端展示友好提示
  4543. Utils::throwError('20003:' . mapErrorMessage($e->getMessage()));
  4544. }
  4545. // 更新分镜表的视频任务信息
  4546. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4547. 'video_task_id' => $task->id,
  4548. 'video_task_status' => '生成中',
  4549. 'generate_audio' => $generate_audio,
  4550. 'updated_at' => date('Y-m-d H:i:s')
  4551. ]);
  4552. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4553. $episode_number = getProp($act, 'episode_number');
  4554. $act_number = getProp($act, 'act_number');
  4555. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4556. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4557. }
  4558. $result = [
  4559. 'task_id' => $task->id,
  4560. 'status' => $task->status,
  4561. 'act_id' => $act_id,
  4562. 'video_duration' => $videoDuration
  4563. ];
  4564. // 仅当任务提交阶段就已失败时,附带格式化后的错误信息;正常返回结构不受影响
  4565. if ($task->status === 'failed' && !empty($task->error_message)) {
  4566. $result['error_message'] = mapErrorMessage($task->error_message);
  4567. }
  4568. return $result;
  4569. }
  4570. /**
  4571. * 文生视频通用方法
  4572. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4573. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4574. *
  4575. * @param array $data 请求参数
  4576. * @return array
  4577. */
  4578. public function generateVideo($data) {
  4579. $prompt = getProp($data, 'prompt');
  4580. if (empty($prompt)) {
  4581. Utils::throwError('20003:提示词不能为空');
  4582. }
  4583. $model = getProp($data, 'model');
  4584. if (!$model) {
  4585. $model = 'seed-2';
  4586. }
  4587. // 验证模型是否在可用模型表中
  4588. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4589. Utils::throwError('20003:该模型已不可用,请更换!');
  4590. }
  4591. $video_duration = getProp($data, 'video_duration', 5);
  4592. // 默认超分720p档(按480p生成后本地超分到720p);480p为原始档需前端显式指定
  4593. $video_resolution = getProp($data, 'video_resolution', 'sr_720p');
  4594. $ratio = getProp($data, 'ratio', '9:16');
  4595. $generate_audio = getProp($data, 'generate_audio', 1);
  4596. $seed = getProp($data, 'seed', -1);
  4597. $first_frame_url = getProp($data, 'first_frame_url');
  4598. $tail_frame_url = getProp($data, 'tail_frame_url');
  4599. // 参考图(支持数组或JSON字符串,最多9张)
  4600. $reference_images = getProp($data, 'reference_images', []);
  4601. if (is_string($reference_images)) {
  4602. $reference_images = json_decode($reference_images, true) ?: [];
  4603. }
  4604. if (!is_array($reference_images)) {
  4605. Utils::throwError('20003:参考图格式不正确');
  4606. }
  4607. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4608. $reference_images = array_slice($reference_images, 0, 9);
  4609. // 参考视频(支持数组或JSON字符串,最多3个)
  4610. $reference_videos = getProp($data, 'reference_videos', []);
  4611. if (is_string($reference_videos)) {
  4612. $reference_videos = json_decode($reference_videos, true) ?: [];
  4613. }
  4614. if (!is_array($reference_videos)) {
  4615. Utils::throwError('20003:参考视频格式不正确');
  4616. }
  4617. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4618. if (count($reference_videos) > 3) {
  4619. Utils::throwError('20003:参考视频最多选择3个');
  4620. }
  4621. $reference_videos = array_slice($reference_videos, 0, 3);
  4622. // 参考音频(支持数组或JSON字符串,最多3个)
  4623. $reference_audios = getProp($data, 'reference_audios', []);
  4624. if (is_string($reference_audios)) {
  4625. $reference_audios = json_decode($reference_audios, true) ?: [];
  4626. }
  4627. if (!is_array($reference_audios)) {
  4628. Utils::throwError('20003:参考音频格式不正确');
  4629. }
  4630. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4631. if (count($reference_audios) > 3) {
  4632. Utils::throwError('20003:参考音频最多选择3个');
  4633. }
  4634. $reference_audios = array_slice($reference_audios, 0, 3);
  4635. // 余额预检:按预估时长计算所需积分,不足直接报错
  4636. $chargeDuration = (int)ceil((float)$video_duration);
  4637. if ($chargeDuration <= 0) {
  4638. $chargeDuration = 5; // 无时长时按默认5秒预估
  4639. }
  4640. $this->pointsService->checkUserPointsEnough(
  4641. $this->pointsService->getVideoChargePoints([
  4642. 'model' => $model,
  4643. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4644. 'video_duration' => $chargeDuration,
  4645. 'ratio' => $ratio,
  4646. 'generate_audio' => (int)$generate_audio,
  4647. ])
  4648. );
  4649. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4650. $videoParams = [
  4651. 'model' => $model,
  4652. 'prompt' => $prompt,
  4653. 'video_duration' => $video_duration,
  4654. 'video_resolution' => $video_resolution,
  4655. 'seed' => $seed,
  4656. 'ratio' => $ratio,
  4657. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4658. 'draft' => getProp($data, 'draft', false),
  4659. 'watermark' => getProp($data, 'watermark', false),
  4660. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4661. ];
  4662. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4663. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4664. // 构建content数组
  4665. $videoParams['content'] = [
  4666. [
  4667. 'type' => 'text',
  4668. 'text' => $prompt,
  4669. ]
  4670. ];
  4671. // 根据模型选择不同的视频生成方法
  4672. if (strpos($model, 'jimeng') !== false) {
  4673. // 即梦模型参数调整
  4674. unset($videoParams['content']); // 即梦不使用content格式
  4675. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4676. } elseif (strpos($model, 'kling') !== false) {
  4677. // 可灵模型参数调整
  4678. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4679. unset($videoParams['ratio']);
  4680. unset($videoParams['content']); // 可灵不使用content格式
  4681. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4682. } elseif (strpos($model, 'zhizhen') !== false) {
  4683. // 智帧等新模型使用统一API
  4684. $unifiedParams = [
  4685. 'model_code' => $model,
  4686. 'prompt' => $prompt,
  4687. 'video_duration' => $video_duration,
  4688. 'video_resolution' => strtolower($video_resolution),
  4689. 'video_ratio' => $ratio,
  4690. 'seed' => $seed,
  4691. ];
  4692. // 构建parameters参数
  4693. $parameters = [
  4694. 'seconds' => $unifiedParams['video_duration'],
  4695. 'resolution' => $unifiedParams['video_resolution'],
  4696. 'ratio' => $ratio,
  4697. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4698. ];
  4699. // 首帧和尾帧
  4700. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4701. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4702. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4703. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4704. if ($refImageUrls) {
  4705. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4706. }
  4707. // 参考图处理
  4708. if ($reference_images) {
  4709. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4710. $parameters['reference_images'] = $reference_images;
  4711. $parameters['video_mode'] = 'multi_image';
  4712. $parameters['mode'] = 'multi_image';
  4713. }
  4714. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4715. if ($reference_videos) {
  4716. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4717. $parameters['reference_videos'] = $reference_videos;
  4718. }
  4719. if ($reference_audios) {
  4720. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4721. $parameters['reference_audios'] = $reference_audios;
  4722. }
  4723. $unifiedParams['parameters'] = $parameters;
  4724. // 调用统一API创建任务
  4725. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4726. } elseif ($this->isSeedance20SeriesModel($model)) {
  4727. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4728. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4729. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4730. $videoParams['reference_images'] = $reference_images;
  4731. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4732. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4733. if ($refImageUrls) {
  4734. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4735. }
  4736. if ($reference_images) {
  4737. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI)
  4738. $reference_image_assets = $isKuaikuai
  4739. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4740. : ($isDreamina
  4741. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $videoParams['prompt'])
  4742. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']));
  4743. $videoParams['reference_image_assets'] = $reference_image_assets;
  4744. }
  4745. // 参考视频上传为素材(国内百度/海外百度dreamina/快快AI)
  4746. if ($reference_videos) {
  4747. $reference_video_assets = $isKuaikuai
  4748. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4749. : ($isDreamina
  4750. ? $this->aiVideoGenerationService->processReferenceVideosToBaiduDreaminaAssets($reference_videos, $videoParams['prompt'])
  4751. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']));
  4752. $videoParams['reference_video_assets'] = $reference_video_assets;
  4753. }
  4754. // 参考音频上传为素材(国内百度/海外百度dreamina/快快AI)
  4755. if ($reference_audios) {
  4756. $reference_audio_assets = $isKuaikuai
  4757. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4758. : ($isDreamina
  4759. ? $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($reference_audios, $videoParams['prompt'])
  4760. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']));
  4761. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4762. }
  4763. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4764. if ($reference_images || $reference_videos || $reference_audios) {
  4765. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4766. }
  4767. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4768. if ($isKuaikuai) {
  4769. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4770. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4771. } else {
  4772. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4773. }
  4774. } else {
  4775. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4776. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4777. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4778. if ($refImageUrls) {
  4779. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4780. }
  4781. if ($reference_videos) {
  4782. foreach ($reference_videos as $videoUrl) {
  4783. $videoParams['content'][] = [
  4784. 'type' => 'video_url',
  4785. 'video_url' => [
  4786. 'url' => $videoUrl,
  4787. ],
  4788. 'role' => 'reference_video',
  4789. ];
  4790. }
  4791. }
  4792. if ($reference_audios) {
  4793. foreach ($reference_audios as $audioUrl) {
  4794. $videoParams['content'][] = [
  4795. 'type' => 'audio_url',
  4796. 'audio_url' => [
  4797. 'url' => $audioUrl,
  4798. ],
  4799. 'role' => 'reference_audio',
  4800. ];
  4801. }
  4802. }
  4803. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4804. }
  4805. return [
  4806. 'task_id' => $task->id,
  4807. 'status' => $task->status,
  4808. 'model' => $model,
  4809. 'video_duration' => $video_duration,
  4810. 'video_resolution' => $video_resolution,
  4811. 'ratio' => $ratio
  4812. ];
  4813. }
  4814. /**
  4815. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4816. *
  4817. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4818. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4819. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4820. *
  4821. * @param array $data
  4822. * @return array
  4823. */
  4824. public function previewCharge(array $data): array
  4825. {
  4826. $mode = (string)getProp($data, 'mode', '');
  4827. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4828. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4829. }
  4830. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4831. $scene = (string)getProp($data, 'scene', 'video_generation');
  4832. // 未显式传scene且带参考视频时,自动按video_to_video定价
  4833. if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
  4834. $scene = 'video_to_video';
  4835. }
  4836. $items = [];
  4837. $model = '';
  4838. $resolution = '';
  4839. if ($mode === 'video') {
  4840. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4841. $model = (string)getProp($data, 'model', '');
  4842. if (!$model) {
  4843. Utils::throwError('1002:model参数不能为空');
  4844. }
  4845. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4846. $duration = (int)getProp($data, 'video_duration', 5);
  4847. if ($duration <= 0) {
  4848. $duration = 5;
  4849. }
  4850. $count = max(1, (int)getProp($data, 'count', 1));
  4851. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4852. 'model' => $model,
  4853. 'video_resolution' => $resolution,
  4854. 'video_duration' => $duration,
  4855. 'mode' => $scene,
  4856. ]);
  4857. $points = $pointsPerVideo * $count;
  4858. $items[] = [
  4859. 'type' => 'video',
  4860. 'model' => $model,
  4861. 'video_resolution' => $resolution,
  4862. 'video_duration' => $duration,
  4863. 'count' => $count,
  4864. 'points' => $points,
  4865. ];
  4866. } elseif ($mode === 'image') {
  4867. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4868. $model = (string)getProp($data, 'model', '');
  4869. if (!$model) {
  4870. Utils::throwError('1002:model参数不能为空');
  4871. }
  4872. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4873. if (!$resolution) {
  4874. $width = (int)getProp($data, 'width', 0);
  4875. $height = (int)getProp($data, 'height', 0);
  4876. if ($width <= 0 || $height <= 0) {
  4877. $width = 1600;
  4878. $height = 2848;
  4879. }
  4880. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4881. }
  4882. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4883. $points = $this->pointsService->getImageChargePoints([
  4884. 'model' => $model,
  4885. 'resolution' => $resolution,
  4886. ]) * $imageNum;
  4887. $items[] = [
  4888. 'type' => 'image',
  4889. 'model' => $model,
  4890. 'resolution' => $resolution,
  4891. 'image_num' => $imageNum,
  4892. 'points' => $points,
  4893. ];
  4894. } else {
  4895. // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
  4896. // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
  4897. $priceType = (string)getProp($data, 'price_type', 'special');
  4898. if (!in_array($priceType, ['special', 'normal'], true)) {
  4899. Utils::throwError('1003:price_type参数仅支持special或normal');
  4900. }
  4901. $count = max(1, (int)getProp($data, 'count', 1));
  4902. $animeId = getProp($data, 'anime_id');
  4903. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4904. if ($animeId && $generateEpisodes > 0) {
  4905. // 批量生成分集按 special 档预估,与实际扣费口径一致
  4906. $priceType = 'special';
  4907. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4908. ->where('anime_id', $animeId)
  4909. ->where('is_default', 1)
  4910. ->max('episode_number');
  4911. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4912. $startEpisodeNumber = $currentMaxEpisode + 1;
  4913. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4914. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4915. ->where('anime_id', $animeId)
  4916. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4917. ->whereIn('status', ['pending', 'processing', 'completed'])
  4918. ->count();
  4919. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4920. if ($count < 0) {
  4921. $count = 0;
  4922. }
  4923. }
  4924. $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
  4925. $items[] = [
  4926. 'type' => 'chat',
  4927. 'count' => $count,
  4928. 'price_type' => $priceType,
  4929. 'points' => $points,
  4930. ];
  4931. }
  4932. $totalPoints = 0;
  4933. foreach ($items as $item) {
  4934. $totalPoints += $item['points'];
  4935. }
  4936. return [
  4937. 'mode' => $mode,
  4938. 'total_points' => $totalPoints,
  4939. 'items' => $items,
  4940. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4941. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4942. ];
  4943. }
  4944. /**
  4945. * 根据提示词内容智能计算最优视频时长
  4946. *
  4947. * @param string $segmentContent 分镜内容
  4948. * @param string $tailFrame 尾帧描述
  4949. * @return int 视频时长(2-12秒)
  4950. */
  4951. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4952. // 合并所有文本内容
  4953. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4954. // 如果没有内容,返回默认时长
  4955. if (empty($fullText)) {
  4956. return 5;
  4957. }
  4958. // 计算文本长度(中文字符按2个字符计算)
  4959. $textLength = mb_strlen($fullText, 'UTF-8');
  4960. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4961. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4962. // 分析内容复杂度
  4963. $complexityScore = $this->analyzeContentComplexity($fullText);
  4964. // 基础时长计算(根据文本长度)
  4965. $baseDuration = 3; // 默认2秒
  4966. // if ($adjustedLength <= 20) {
  4967. // $baseDuration = 3;
  4968. // } elseif ($adjustedLength <= 40) {
  4969. // $baseDuration = 4;
  4970. // } elseif ($adjustedLength <= 60) {
  4971. // $baseDuration = 5;
  4972. // } elseif ($adjustedLength <= 80) {
  4973. // $baseDuration = 6;
  4974. // } elseif ($adjustedLength <= 100) {
  4975. // $baseDuration = 7;
  4976. // } elseif ($adjustedLength <= 120) {
  4977. // $baseDuration = 8;
  4978. // } else {
  4979. // $baseDuration = 9;
  4980. // }
  4981. // 根据内容复杂度调整时长
  4982. $finalDuration = $baseDuration + $complexityScore;
  4983. // 确保时长在2-12秒范围内
  4984. return max(4, min(12, $finalDuration));
  4985. }
  4986. /**
  4987. * 分析内容复杂度,返回时长调整值
  4988. *
  4989. * @param string $text 文本内容
  4990. * @return int 调整值(-2到+3)
  4991. */
  4992. private function analyzeContentComplexity($text) {
  4993. $score = 0;
  4994. // 动作关键词(需要更长时间展现)
  4995. $actionKeywords = [
  4996. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4997. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4998. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4999. ];
  5000. // 静态关键词(可以用较短时间)
  5001. $staticKeywords = [
  5002. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  5003. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  5004. ];
  5005. // 复杂场景关键词(需要更长时间)
  5006. $complexSceneKeywords = [
  5007. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  5008. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  5009. ];
  5010. // 情感关键词(需要适中时间表现)
  5011. $emotionKeywords = [
  5012. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  5013. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  5014. ];
  5015. // 检查动作关键词
  5016. foreach ($actionKeywords as $keyword) {
  5017. if (strpos($text, $keyword) !== false) {
  5018. $score += 1;
  5019. break; // 避免重复加分
  5020. }
  5021. }
  5022. // 检查静态关键词
  5023. foreach ($staticKeywords as $keyword) {
  5024. if (strpos($text, $keyword) !== false) {
  5025. $score -= 1;
  5026. break;
  5027. }
  5028. }
  5029. // 检查复杂场景关键词
  5030. foreach ($complexSceneKeywords as $keyword) {
  5031. if (strpos($text, $keyword) !== false) {
  5032. $score += 1;
  5033. break;
  5034. }
  5035. }
  5036. // 检查情感关键词
  5037. foreach ($emotionKeywords as $keyword) {
  5038. if (strpos($text, $keyword) !== false) {
  5039. $score += 1;
  5040. break;
  5041. }
  5042. }
  5043. // 检查时间相关词汇
  5044. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  5045. $score += 1;
  5046. }
  5047. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  5048. $score -= 1;
  5049. }
  5050. // 检查转场词汇
  5051. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  5052. $score += 1;
  5053. }
  5054. // 检查环境描述(复杂环境需要更多时间)
  5055. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  5056. $score += 1;
  5057. }
  5058. // 检查对话内容(对话需要更多时间)
  5059. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  5060. $score += 1;
  5061. }
  5062. // 限制调整范围
  5063. return max(-1, min(4, $score));
  5064. }
  5065. /**
  5066. * 创建完整视频合成任务
  5067. *
  5068. * @param array $data
  5069. * @return array
  5070. */
  5071. public function createCompleteVideoTask($data)
  5072. {
  5073. $animeId = getProp($data, 'anime_id');
  5074. $episodeId = getProp($data, 'episode_id');
  5075. // 验证参数
  5076. if (!$animeId || !$episodeId) {
  5077. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  5078. }
  5079. // 检查是否已存在处理中的任务
  5080. $existingTask = DB::table('mp_complete_video_tasks')
  5081. ->where('anime_id', $animeId)
  5082. ->where('episode_id', $episodeId)
  5083. ->whereIn('generate_status', ['执行中'])
  5084. ->first();
  5085. if ($existingTask) {
  5086. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  5087. }
  5088. // 获取全能模式状态
  5089. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  5090. if ((int)$ace_mode === 1) {
  5091. // 获取所有片段的配音视频,按 act_number 排序
  5092. $segments = DB::table('mp_episode_segments')
  5093. ->where('anime_id', $animeId)
  5094. ->where('episode_id', $episodeId)
  5095. ->orderBy('segment_number')
  5096. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5097. ->get();
  5098. // 检查是否所有片段都有视频
  5099. $missingVideos = $segments->filter(function($segment) {
  5100. return empty($segment->video_url);
  5101. });
  5102. if ($missingVideos->isNotEmpty()) {
  5103. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  5104. }
  5105. }else {
  5106. // 获取所有分镜的配音视频,按 segment_number 排序
  5107. $segments = DB::table('mp_episode_segments')
  5108. ->where('anime_id', $animeId)
  5109. ->where('episode_id', $episodeId)
  5110. ->orderBy('segment_number')
  5111. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5112. ->get();
  5113. // 检查是否所有分镜都有配音和视频
  5114. $missingVideos = $segments->filter(function($segment) {
  5115. return empty($segment->audio_url) || empty($segment->video_url);
  5116. });
  5117. if ($missingVideos->isNotEmpty()) {
  5118. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5119. }
  5120. }
  5121. if ($segments->isEmpty()) {
  5122. Utils::throwError('20003:未找到该剧集的分镜数据');
  5123. }
  5124. // 获取当前完整视频url
  5125. $completeVideoUrl = DB::table('mp_anime_episodes')
  5126. ->where('anime_id', $animeId)
  5127. ->where('id', $episodeId)
  5128. ->value('complete_video_url');
  5129. // 构建 generate_json
  5130. $generateJson = [];
  5131. $sequence = 1;
  5132. foreach ($segments as $segment) {
  5133. if ((int)$ace_mode === 1) {
  5134. $generateJson[] = [
  5135. 'sequence' => $sequence++,
  5136. 'video_url' => $segment->video_url,
  5137. 'video_time_point_start' => $segment->video_time_point_start,
  5138. 'video_time_point_end' => $segment->video_time_point_end
  5139. ];
  5140. }else {
  5141. $generateJson[] = [
  5142. 'sequence' => $sequence++,
  5143. 'video_url' => $segment->video_url,
  5144. 'audio_url' => $segment->audio_url,
  5145. 'video_time_point_start' => $segment->video_time_point_start,
  5146. 'video_time_point_end' => $segment->video_time_point_end
  5147. ];
  5148. }
  5149. }
  5150. // 创建任务
  5151. $now = date('Y-m-d H:i:s');
  5152. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5153. 'anime_id' => $animeId,
  5154. 'episode_id' => $episodeId,
  5155. 'generate_json' => json_encode($generateJson, 256),
  5156. 'generate_status' => '执行中',
  5157. 'complete_video_url' => '',
  5158. 'created_at' => $now,
  5159. 'updated_at' => $now
  5160. ]);
  5161. if (!$taskId) {
  5162. Utils::throwError('20003:创建任务失败');
  5163. }
  5164. // 更新剧集表的任务ID和状态
  5165. $boolen = DB::table('mp_anime_episodes')
  5166. ->where('anime_id', $animeId)
  5167. ->where('id', $episodeId)
  5168. ->update([
  5169. 'complete_video_task_id' => $taskId,
  5170. 'complete_video_task_status' => '执行中',
  5171. 'updated_at' => $now
  5172. ]);
  5173. if (!$boolen) {
  5174. Utils::throwError('20003:更新剧集表失败');
  5175. }
  5176. dLog('anime')->info('创建完整视频合成任务', [
  5177. 'task_id' => $taskId,
  5178. 'anime_id' => $animeId,
  5179. 'episode_id' => $episodeId,
  5180. 'segment_count' => count($generateJson)
  5181. ]);
  5182. // 请求远程服务器执行生成
  5183. $client = new Client(['timeout' => 600, 'verify' => false]);
  5184. try {
  5185. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5186. $response = $result->getBody()->getContents();
  5187. $response_arr = json_decode($response, true);
  5188. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5189. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5190. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5191. // // 更新任务状态为失败
  5192. // DB::table('mp_complete_video_tasks')
  5193. // ->where('id', $taskId)
  5194. // ->update([
  5195. // 'generate_status' => '执行失败',
  5196. // 'error_message' => $error_msg,
  5197. // 'updated_at' => date('Y-m-d H:i:s')
  5198. // ]);
  5199. // // 同步更新剧集表状态
  5200. // DB::table('mp_anime_episodes')
  5201. // ->where('complete_video_task_id', $taskId)
  5202. // ->update([
  5203. // 'complete_video_task_status' => '执行失败',
  5204. // 'updated_at' => date('Y-m-d H:i:s')
  5205. // ]);
  5206. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5207. }
  5208. } catch (\Exception $e) {
  5209. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5210. // 更新任务状态为失败
  5211. DB::table('mp_complete_video_tasks')
  5212. ->where('id', $taskId)
  5213. ->update([
  5214. 'generate_status' => '执行失败',
  5215. 'error_message' => $e->getMessage(),
  5216. 'updated_at' => date('Y-m-d H:i:s')
  5217. ]);
  5218. // 同步更新剧集表状态
  5219. DB::table('mp_anime_episodes')
  5220. ->where('complete_video_task_id', $taskId)
  5221. ->update([
  5222. 'complete_video_task_status' => '执行失败',
  5223. 'updated_at' => date('Y-m-d H:i:s')
  5224. ]);
  5225. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5226. }
  5227. // 开始轮询任务状态
  5228. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5229. $pollInterval = 5; // 每5秒轮询一次
  5230. $attempt = 0;
  5231. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5232. while ($attempt < $maxAttempts) {
  5233. sleep($pollInterval);
  5234. $attempt++;
  5235. // 查询任务状态
  5236. $task = DB::table('mp_complete_video_tasks')
  5237. ->where('id', $taskId)
  5238. ->first();
  5239. if (!$task) {
  5240. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5241. Utils::throwError('20003:任务不存在');
  5242. }
  5243. dLog('anime')->info('轮询任务状态', [
  5244. 'task_id' => $taskId,
  5245. 'attempt' => $attempt,
  5246. 'status' => $task->generate_status
  5247. ]);
  5248. // 检查任务是否完成
  5249. if ($task->generate_status === '执行成功') {
  5250. // 同步更新剧集表状态
  5251. $boolen3 = DB::table('mp_anime_episodes')
  5252. ->where('anime_id', $animeId)
  5253. ->where('id', $episodeId)
  5254. ->update([
  5255. 'complete_video_url' => $task->complete_video_url,
  5256. 'complete_video_task_status' => '执行成功',
  5257. 'updated_at' => date('Y-m-d H:i:s')
  5258. ]);
  5259. dLog('anime')->info('视频合成任务完成', [
  5260. 'task_id' => $taskId,
  5261. 'video_url' => $task->complete_video_url,
  5262. 'attempts' => $attempt
  5263. ]);
  5264. // 如果更新成功则远程删除之前的文件
  5265. if ($boolen3 && $completeVideoUrl) {
  5266. $encode_url = urlencode($completeVideoUrl);
  5267. $client = new Client(['timeout' => 300, 'verify' => false]);
  5268. // 根据ID通过API通知合成音频
  5269. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5270. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5271. $response = $result->getBody()->getContents();
  5272. $response_arr = json_decode($response, true);
  5273. Log::info('火山删除音频返回: '.$response);
  5274. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5275. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5276. Log::info('火山删除音频失败: '.$error_msg);
  5277. // Utils::throwError('20003:火山删除音频失败');
  5278. }
  5279. }
  5280. return [
  5281. 'task_id' => $taskId,
  5282. 'anime_id' => $animeId,
  5283. 'episode_id' => $episodeId,
  5284. 'segment_count' => count($generateJson),
  5285. 'generate_status' => '执行成功',
  5286. 'complete_video_url' => $task->complete_video_url,
  5287. ];
  5288. }
  5289. // 检查任务是否失败
  5290. if ($task->generate_status === '执行失败') {
  5291. // 同步更新剧集表状态
  5292. DB::table('mp_anime_episodes')
  5293. ->where('anime_id', $animeId)
  5294. ->where('id', $episodeId)
  5295. ->update([
  5296. 'complete_video_task_status' => '执行失败',
  5297. 'updated_at' => date('Y-m-d H:i:s')
  5298. ]);
  5299. $errorMessage = $task->error_message ?? '未知错误';
  5300. dLog('anime')->error('视频合成任务失败', [
  5301. 'task_id' => $taskId,
  5302. 'error' => $errorMessage,
  5303. 'attempts' => $attempt
  5304. ]);
  5305. return [
  5306. 'task_id' => $taskId,
  5307. 'anime_id' => $animeId,
  5308. 'episode_id' => $episodeId,
  5309. 'segment_count' => count($generateJson),
  5310. 'generate_status' => '执行失败',
  5311. 'error_message' => $errorMessage
  5312. ];
  5313. }
  5314. }
  5315. // 超时处理
  5316. dLog('anime')->warning('视频合成任务超时', [
  5317. 'task_id' => $taskId,
  5318. 'max_attempts' => $maxAttempts,
  5319. 'timeout_seconds' => $maxAttempts * $pollInterval
  5320. ]);
  5321. // 更新任务状态为超时
  5322. DB::table('mp_complete_video_tasks')
  5323. ->where('id', $taskId)
  5324. ->update([
  5325. 'generate_status' => '超时',
  5326. 'error_message' => '任务执行超时(5分钟)',
  5327. 'updated_at' => date('Y-m-d H:i:s')
  5328. ]);
  5329. return [
  5330. 'task_id' => $taskId,
  5331. 'anime_id' => $animeId,
  5332. 'episode_id' => $episodeId,
  5333. 'segment_count' => count($generateJson),
  5334. 'generate_status' => '超时',
  5335. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5336. ];
  5337. }
  5338. /**
  5339. * 根据 inner_prompt_type 附加内置提示词
  5340. *
  5341. * @param string $prompt 用户提示词
  5342. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5343. * @return string 合并后的提示词
  5344. */
  5345. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5346. {
  5347. $innerPromptMap = [
  5348. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。',
  5349. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5350. ];
  5351. if (!isset($innerPromptMap[$innerPromptType])) {
  5352. return $prompt;
  5353. }
  5354. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5355. }
  5356. /**
  5357. * 根据 inner_prompt_type 获取生成图片数量
  5358. *
  5359. * @param int $innerPromptType 内置提示词类型
  5360. * @param int $imageNum 传入的图片张数
  5361. * @return int 图片数量
  5362. */
  5363. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5364. {
  5365. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5366. }
  5367. /**
  5368. * 提取图片生成结果URL
  5369. *
  5370. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5371. * @param int $innerPromptType 内置提示词类型
  5372. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5373. */
  5374. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5375. {
  5376. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5377. if (is_array($resultUrls) && !empty($resultUrls)) {
  5378. $resultUrls = array_values($resultUrls);
  5379. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5380. }
  5381. if (!empty($resultUrl)) {
  5382. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5383. }
  5384. return (int)$innerPromptType === 2 ? [] : '';
  5385. }
  5386. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5387. $prompt = getProp($data, 'prompt');
  5388. $episode_id = getProp($data, 'episode_id');
  5389. $ref_img_urls = getProp($data, 'ref_img_urls');
  5390. $ratio = getProp($data, 'ratio', '9:16');
  5391. $resolution = getProp($data, 'resolution', '2k');
  5392. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5393. $imageNum = (int)getProp($data, 'image_num', 1);
  5394. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  5395. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  5396. // 参数验证
  5397. $resolution = strtolower($resolution);
  5398. if (!isset($sizeMap[$resolution])) {
  5399. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5400. }
  5401. if (!isset($sizeMap[$resolution][$ratio])) {
  5402. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5403. }
  5404. // 根据 ratio 和 resolution 确定宽高
  5405. $width = $sizeMap[$resolution][$ratio]['width'];
  5406. $height = $sizeMap[$resolution][$ratio]['height'];
  5407. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5408. if (is_json($ref_img_urls)) {
  5409. $ref_img_urls = json_decode($ref_img_urls, true);
  5410. }else {
  5411. $ref_img_urls = explode(',', $ref_img_urls);
  5412. }
  5413. }
  5414. // 处理图片模型
  5415. $model = getProp($data, 'model');
  5416. if (!$model) {
  5417. // 用户没有输入,从episode表获取
  5418. if ($episode_id) {
  5419. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5420. $model = getProp($episode, 'image_model');
  5421. }
  5422. if (!$model) {
  5423. // episode表也没有,使用默认值
  5424. $model = 'gpt-image-2';
  5425. }
  5426. }
  5427. // 验证模型是否在可用模型表中
  5428. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5429. // $model = 'gpt-image-2';
  5430. Utils::throwError('20003:该模型已不可用,请更换!');
  5431. }
  5432. // 保存到episode表
  5433. if ($episode_id) {
  5434. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5435. 'image_model' => $model,
  5436. 'updated_at' => date('Y-m-d H:i:s')
  5437. ]);
  5438. }
  5439. // 参数验证
  5440. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5441. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5442. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5443. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5444. try {
  5445. // 创建图片生成任务
  5446. $params = [
  5447. 'prompt' => $prompt,
  5448. 'model' => $model,
  5449. 'ref_img_urls' => '',
  5450. 'width' => $width,
  5451. 'height' => $height,
  5452. 'image_num' => $imageNum
  5453. ];
  5454. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5455. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5456. $task_id = $task->id;
  5457. if (!$task_id) {
  5458. Utils::throwError('20003:创建图片生成任务失败');
  5459. }
  5460. // 创建任务中心记录并关联图片任务ID
  5461. $taskCenter = $this->taskCenterService->createTask('image', [
  5462. 'title' => '文生图',
  5463. 'ref_task_id' => $task_id,
  5464. // 'prompt' => $prompt,
  5465. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5466. ]);
  5467. $taskCenterId = $taskCenter->id;
  5468. // 组装本次任务信息(用于init消息,类似generateVideo)
  5469. $taskInfo = [
  5470. 'task_id' => $task_id,
  5471. 'status' => getProp($task, 'status', 'processing'),
  5472. 'model' => $model,
  5473. 'ratio' => $ratio,
  5474. 'resolution' => $resolution,
  5475. 'image_num' => $imageNum,
  5476. ];
  5477. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5478. if (is_callable($onTaskCreated)) {
  5479. $onTaskCreated($taskCenterId, $taskInfo);
  5480. }
  5481. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5482. $model = getProp($task, 'model');
  5483. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5484. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5485. $isSyncModel = $isVolcModel || $isGptModel;
  5486. // 任务需要轮询获取结果(15分钟超时,每3秒查询一次)
  5487. $start_time = time();
  5488. $timeout = 900; // 15分钟
  5489. $img_url = '';
  5490. $img_urls = [];
  5491. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5492. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5493. while (time() - $start_time < $timeout) {
  5494. sleep(3);
  5495. // 每分钟发送一次队列状态消息(仅流式模式)
  5496. if (is_callable($onPoll)) {
  5497. $currentTime = time();
  5498. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5499. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5500. $lastQueueMessageTime = $currentTime;
  5501. }
  5502. }
  5503. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5504. if ($isSyncModel) {
  5505. // 刷新任务状态
  5506. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5507. if ($task->status === 'success' && $task->result_url) {
  5508. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5509. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5510. if (!empty($resultUrls)) {
  5511. $img_urls = $resultUrls;
  5512. $img_url = $resultUrls[0];
  5513. } else {
  5514. $img_url = (string)$task->result_url;
  5515. }
  5516. break;
  5517. } elseif ($task->status === 'failed') {
  5518. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5519. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5520. }
  5521. // // 如果还在处理中,提示用户稍后查看
  5522. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5523. }else {
  5524. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5525. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5526. if ($statusInfo['status'] === 'success') {
  5527. $task->updateStatus('success', [
  5528. 'result_url' => $statusInfo['result_url'],
  5529. 'result_json' => $statusInfo['result_json'] ?? []
  5530. ]);
  5531. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5532. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5533. if (!empty($resultUrls)) {
  5534. $img_urls = $resultUrls;
  5535. $img_url = $resultUrls[0];
  5536. } else {
  5537. $img_url = (string)$statusInfo['result_url'];
  5538. }
  5539. break;
  5540. } elseif ($statusInfo['status'] === 'failed') {
  5541. $task->updateStatus('failed', [
  5542. 'error_message' => $statusInfo['error_message'],
  5543. 'result_json' => $statusInfo['result_json'] ?? []
  5544. ]);
  5545. dLog('anime')->error('图片生成失败,', [
  5546. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5547. ]);
  5548. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5549. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5550. }
  5551. }
  5552. }
  5553. if (empty($img_url)) {
  5554. Utils::throwError('20003:图片生成超时,请稍后重试');
  5555. }
  5556. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5557. if (count($img_urls) > 1) {
  5558. return [
  5559. 'img_url' => $img_url,
  5560. 'image_urls' => $img_urls,
  5561. 'task_id' => $taskCenterId,
  5562. ];
  5563. }
  5564. return [
  5565. 'img_url' => $img_url,
  5566. 'task_id' => $taskCenterId,
  5567. ];
  5568. } catch (\Exception $e) {
  5569. dLog('anime')->error('更新角色或场景失败', [
  5570. 'error' => $e->getMessage()
  5571. ]);
  5572. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5573. Utils::throwError('20003:' . $e->getMessage());
  5574. }
  5575. }
  5576. /**
  5577. * 使用文生文模型解析分镜内容
  5578. */
  5579. private function parseSegmentContentWithAI($segment_content) {
  5580. try {
  5581. // 使用DeepSeek服务的公开方法解析分镜内容
  5582. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5583. } catch (\Exception $e) {
  5584. // 如果AI解析失败,记录日志并返回原内容
  5585. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5586. return $segment_content;
  5587. }
  5588. }
  5589. /**
  5590. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5591. *
  5592. * @param int $episode_id 分集ID
  5593. * @param int $anime_id 动漫ID
  5594. * @param array $roles 分集角色数组(引用传递)
  5595. * @param array $scenes 分集场景数组(引用传递)
  5596. * @param array $episode 分集数据
  5597. */
  5598. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5599. // 获取全局动漫的角色和场景数据
  5600. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5601. if (!$anime) return;
  5602. $art_style_type = getProp($anime, 'art_style_type');
  5603. $character_prefix = '';
  5604. $scene_prefix = '';
  5605. if ($art_style_type) {
  5606. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5607. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5608. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5609. }
  5610. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5611. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5612. $roles_updated = false;
  5613. $scenes_updated = false;
  5614. // 处理角色
  5615. foreach ($roles as &$role) {
  5616. $role_name = getProp($role, 'role');
  5617. $role_description = getProp($role, 'description');
  5618. $role_pic_prompt = getProp($role, 'pic_prompt');
  5619. $role_url = getProp($role, 'url');
  5620. $role_task_id = getProp($role, 'task_id');
  5621. // 如果已有URL或已有任务ID,跳过
  5622. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5623. continue;
  5624. }
  5625. $url_inherited = false;
  5626. // 尝试从全局数据中继承
  5627. foreach ($global_roles as $global_role) {
  5628. $global_role_name = getProp($global_role, 'role');
  5629. $global_role_description = getProp($global_role, 'description');
  5630. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5631. $global_role_url = getProp($global_role, 'url');
  5632. $global_role_task_id = getProp($global_role, 'task_id');
  5633. $global_role_task_status = getProp($global_role, 'task_status');
  5634. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5635. if ($role_name === $global_role_name
  5636. && $role_description === $global_role_description
  5637. && $role_pic_prompt === $global_role_pic_prompt
  5638. && !empty($global_role_url)) {
  5639. // 继承 task_id、task_status 和 url
  5640. $role['task_id'] = $global_role_task_id;
  5641. $role['task_status'] = $global_role_task_status;
  5642. $role['url'] = $global_role_url;
  5643. $roles_updated = true;
  5644. $url_inherited = true;
  5645. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5646. break;
  5647. }
  5648. }
  5649. // 如果无法继承且没有任务ID,创建新任务
  5650. if (!$url_inherited && empty($role_task_id)) {
  5651. try {
  5652. $art_style = getProp($episode, 'art_style');
  5653. // 优先使用 pic_prompt,如果没有则使用 description
  5654. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5655. // if ($art_style) {
  5656. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5657. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5658. // }
  5659. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5660. $params = [
  5661. 'prompt' => $description,
  5662. 'ref_img_urls' => []
  5663. ];
  5664. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5665. $task_id = $task->id;
  5666. if ($task_id) {
  5667. $role['task_id'] = $task_id;
  5668. $role['task_status'] = 'processing';
  5669. $roles_updated = true;
  5670. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5671. }
  5672. } catch (\Exception $e) {
  5673. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5674. }
  5675. }
  5676. }
  5677. // 处理场景
  5678. foreach ($scenes as &$scene) {
  5679. $scene_name = getProp($scene, 'scene');
  5680. $scene_description = getProp($scene, 'description');
  5681. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5682. $scene_url = getProp($scene, 'url');
  5683. $scene_task_id = getProp($scene, 'task_id');
  5684. // 如果已有URL或已有任务ID,跳过
  5685. if (!empty($scene_url) || !empty($scene_task_id)) {
  5686. continue;
  5687. }
  5688. $url_inherited = false;
  5689. // 尝试从全局数据中继承
  5690. foreach ($global_scenes as $global_scene) {
  5691. $global_scene_name = getProp($global_scene, 'scene');
  5692. $global_scene_description = getProp($global_scene, 'description');
  5693. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5694. $global_scene_url = getProp($global_scene, 'url');
  5695. $global_scene_task_id = getProp($global_scene, 'task_id');
  5696. $global_scene_task_status = getProp($global_scene, 'task_status');
  5697. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5698. if ($scene_name === $global_scene_name
  5699. && $scene_description === $global_scene_description
  5700. && $scene_pic_prompt === $global_scene_pic_prompt
  5701. && !empty($global_scene_url)) {
  5702. // 继承 task_id、task_status 和 url
  5703. $scene['task_id'] = $global_scene_task_id;
  5704. $scene['task_status'] = $global_scene_task_status;
  5705. $scene['url'] = $global_scene_url;
  5706. $scenes_updated = true;
  5707. $url_inherited = true;
  5708. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5709. break;
  5710. }
  5711. }
  5712. // 如果无法继承且没有任务ID,创建新任务
  5713. if (!$url_inherited && empty($scene_task_id)) {
  5714. try {
  5715. $art_style = getProp($episode, 'art_style');
  5716. // 优先使用 pic_prompt,如果没有则使用 description
  5717. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5718. // if ($art_style) {
  5719. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5720. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5721. // }
  5722. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5723. $params = [
  5724. 'prompt' => $description,
  5725. 'ref_img_urls' => []
  5726. ];
  5727. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5728. $task_id = $task->id;
  5729. if ($task_id) {
  5730. $scene['task_id'] = $task_id;
  5731. $scene['task_status'] = 'processing';
  5732. $scenes_updated = true;
  5733. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5734. }
  5735. } catch (\Exception $e) {
  5736. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5737. }
  5738. }
  5739. }
  5740. // 如果有更新,保存到数据库
  5741. if ($roles_updated || $scenes_updated) {
  5742. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5743. if ($roles_updated) {
  5744. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5745. }
  5746. if ($scenes_updated) {
  5747. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5748. }
  5749. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5750. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5751. }
  5752. }
  5753. /**
  5754. * 根据图片URL使用AI反推图片提示词
  5755. *
  5756. * @param string $img_url 图片URL
  5757. * @return string 反推的提示词
  5758. */
  5759. private function generateImagePromptFromUrl($img_url) {
  5760. try {
  5761. // 获取默认模型
  5762. $model = 'doubao-seed-2-0-mini-260215';
  5763. // 构建messages参数
  5764. $messages = [
  5765. [
  5766. 'role' => 'user',
  5767. 'content' => [
  5768. [
  5769. 'type' => 'text',
  5770. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5771. ],
  5772. [
  5773. 'type' => 'image_url',
  5774. 'image_url' => [
  5775. 'url' => $img_url
  5776. ]
  5777. ]
  5778. ]
  5779. ]
  5780. ];
  5781. // 构建请求参数
  5782. $params = [
  5783. 'model' => $model,
  5784. 'messages' => $messages,
  5785. 'stream' => false,
  5786. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5787. ];
  5788. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5789. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5790. // 仅记录 token 使用明细(不扣积分)
  5791. $uid = 0;
  5792. try {
  5793. $uid = (int)Site::getUid();
  5794. } catch (\Throwable $e) {
  5795. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5796. }
  5797. $this->pointsService->recordTokenOnlyDetail(
  5798. $uid,
  5799. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5800. [
  5801. 'model' => $model,
  5802. 'img_url' => $img_url,
  5803. 'source' => 'generateImagePromptFromUrl',
  5804. ],
  5805. 'chat',
  5806. $model,
  5807. ''
  5808. );
  5809. // 返回生成的内容
  5810. return getProp($result, 'fullContent', '图片描述生成失败');
  5811. } catch (\Exception $e) {
  5812. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5813. 'img_url' => $img_url
  5814. ]);
  5815. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5816. 'error' => $e->getMessage(),
  5817. 'img_url' => $img_url
  5818. ]);
  5819. return '图片描述生成失败: ' . $e->getMessage();
  5820. }
  5821. }
  5822. /**
  5823. * 音频试听接口
  5824. * 创建音频任务并轮询获取结果
  5825. *
  5826. * @param array $data 参数数组
  5827. * @return array 返回音频URL或错误信息
  5828. */
  5829. public function previewAudio($data) {
  5830. $dialogue = getProp($data, 'dialogue');
  5831. // 必填参数验证
  5832. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5833. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5834. $voice_type = getProp($data, 'voice_type');
  5835. $voice_name = getProp($data, 'voice_name');
  5836. $voice_actor = getProp($data, 'voice_actor');
  5837. $emotion_type = getProp($data, 'emotion_type');
  5838. $gender = getProp($data, 'gender', 0);
  5839. $emotion = getProp($data, 'emotion');
  5840. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5841. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5842. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5843. $pitch = getProp($data, 'pitch', 0);
  5844. try {
  5845. $now = date('Y-m-d H:i:s');
  5846. // 构建生成参数
  5847. $generate_json = json_encode([
  5848. 'text' => $dialogue,
  5849. 'role' => $voice_actor,
  5850. 'voice_type' => $voice_type,
  5851. 'voice_name' => $voice_name,
  5852. 'emotion' => $emotion,
  5853. 'emotion_type' => $emotion_type,
  5854. 'gender' => $gender,
  5855. 'speed_ratio' => $speed_ratio,
  5856. 'loudness_ratio' => $loudness_ratio,
  5857. 'emotion_scale' => $emotion_scale,
  5858. 'pitch' => $pitch,
  5859. ], 256);
  5860. // 请求远程服务器执行生成
  5861. $client = new Client(['timeout' => 600, 'verify' => false]);
  5862. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5863. $response = $result->getBody()->getContents();
  5864. $response_arr = json_decode($response, true);
  5865. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5866. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5867. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5868. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5869. }
  5870. $arr = $response_arr['data'];
  5871. $subtitle_info = $arr['subtitle_info'];
  5872. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5873. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5874. return [
  5875. 'audio_url' => $arr['url'],
  5876. 'subtitle_info' => $subtitle_info,
  5877. 'audio_duration' => round($audio_duration, 2)
  5878. ];
  5879. } catch (\Exception $e) {
  5880. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5881. Utils::throwError('20003:' . $e->getMessage());
  5882. }
  5883. }
  5884. /**
  5885. * 获取角色库列表(支持文件夹递归查询)
  5886. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5887. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5888. */
  5889. public function globalProducts($data) {
  5890. $uid = Site::getUid();
  5891. $cpid = Site::getCpid();
  5892. $role = Site::getRole();
  5893. $id = getProp($data, 'id', 0);
  5894. $parent_id = getProp($data, 'parent_id', 0);
  5895. $product_name = getProp($data, 'product_name');
  5896. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5897. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5898. if (!$product) {
  5899. Utils::throwError('20003:请选择产品类型');
  5900. }
  5901. // 根据角色和is_public参数确定查询范围
  5902. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5903. // user角色:根据is_public参数筛选
  5904. $query_user_ids = [];
  5905. if ($role === 'admin') {
  5906. // admin获取所有个人库和公共库
  5907. $query_user_ids = [$uid, 0];
  5908. } else {
  5909. // user角色根据is_public参数筛选
  5910. if ($is_public == 2) {
  5911. // 个人库+公共库
  5912. $query_user_ids = [$uid, 0];
  5913. } elseif ($is_public == 0) {
  5914. // 仅个人库
  5915. $query_user_ids = [$uid];
  5916. } elseif ($is_public == 1) {
  5917. // 仅公共库
  5918. $query_user_ids = [0];
  5919. }
  5920. }
  5921. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5922. if ($id || $product_name) {
  5923. $query = DB::table('mp_products')
  5924. ->where('cpid', $cpid)
  5925. ->whereIn('user_id', $query_user_ids)
  5926. ->where('is_deleted', 0);
  5927. // 如果指定了 id,按 id 精确查询
  5928. if ($id) {
  5929. $query->where('id', $id);
  5930. }
  5931. // 如果指定了 product_name,按名称模糊查询
  5932. if ($product_name) {
  5933. $query->where('product_name', 'like', "%{$product_name}%");
  5934. }
  5935. // 如果指定了 product,添加筛选条件
  5936. if ($product) {
  5937. $query->where('product', $product);
  5938. }
  5939. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'timbre_url', 'versions', 'product', 'user_id', 'created_at')
  5940. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5941. ->get()
  5942. ->map(function($value) {
  5943. $value = (array)$value;
  5944. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5945. $value['type'] = (int)$value['type'];
  5946. $value['parent_id'] = (int)$value['parent_id'];
  5947. $value['level'] = (int)$value['level'];
  5948. $value['product'] = (int)($value['product'] ?? 1);
  5949. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5950. $value['timbre_url'] = $value['timbre_url'] ?? '';
  5951. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5952. unset($value['user_id']);
  5953. return $value;
  5954. })
  5955. ->toArray();
  5956. return $result;
  5957. }
  5958. // 递归获取所有子目录和角色
  5959. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5960. }
  5961. /**
  5962. * 递归获取指定目录下的所有子目录和角色
  5963. * @param int $cpid 公司ID
  5964. * @param int $parent_id 父目录ID
  5965. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5966. * @param array $query_user_ids 用户ID数组(支持多个)
  5967. * @param int $current_uid 当前用户ID(用于排序)
  5968. * @return array
  5969. */
  5970. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5971. // 查询当前层级的所有项(文件夹和角色)
  5972. $query = DB::table('mp_products')
  5973. ->where('cpid', $cpid)
  5974. ->where('is_deleted', 0)
  5975. ->where('parent_id', $parent_id);
  5976. // 添加用户ID验证(支持多个user_id)
  5977. if (!empty($query_user_ids)) {
  5978. $query->whereIn('user_id', $query_user_ids);
  5979. }
  5980. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5981. if ($product) {
  5982. $query->where('product', $product);
  5983. }
  5984. // 排序规则:
  5985. // 1. 文件夹在前(type DESC)
  5986. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5987. // 3. 其他排序规则
  5988. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'timbre_url', 'versions', 'product', 'user_id', 'created_at')
  5989. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5990. ->get();
  5991. $result = [];
  5992. foreach ($items as $item) {
  5993. $itemArray = [
  5994. 'id' => $item->id,
  5995. 'type' => (int)$item->type,
  5996. 'parent_id' => (int)$item->parent_id,
  5997. 'level' => (int)$item->level,
  5998. 'product_name' => $item->product_name,
  5999. 'url' => $item->url,
  6000. 'pic_prompt' => $item->pic_prompt ?? '',
  6001. 'three_view_image_url' => $item->three_view_image_url,
  6002. 'timbre_url' => $item->timbre_url ?? '',
  6003. 'product' => (int)($item->product ?? 1),
  6004. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  6005. 'created_at' => transDate($item->created_at, 'Y-m-d')
  6006. ];
  6007. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  6008. // 如果是文件夹,递归获取其子项
  6009. if ($item->type == 2) {
  6010. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  6011. if (!empty($children)) {
  6012. $itemArray['children'] = $children;
  6013. }
  6014. }
  6015. $result[] = $itemArray;
  6016. }
  6017. return $result;
  6018. }
  6019. /**
  6020. * 创建文件夹
  6021. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  6022. * @return int 返回新建文件夹ID
  6023. */
  6024. public function createFolder($data) {
  6025. $uid = Site::getUid();
  6026. $cpid = Site::getCpid();
  6027. $role = Site::getRole();
  6028. $parent_id = getProp($data, 'parent_id', 0);
  6029. $folder_name = getProp($data, 'product_name', '新建文件夹');
  6030. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6031. // 如果是公共库操作,需要admin权限
  6032. if ($is_public && $role !== 'admin') {
  6033. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6034. }
  6035. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6036. $store_uid = $is_public ? 0 : $uid;
  6037. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6038. $product = getProp($data, 'product');
  6039. if (!in_array($product, [1, 2, 3])) {
  6040. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  6041. }
  6042. // 验证父文件夹
  6043. $parent_level = 0;
  6044. if ($parent_id > 0) {
  6045. $parent = DB::table('mp_products')
  6046. ->where('id', $parent_id)
  6047. ->where('cpid', $cpid)
  6048. ->where('user_id', $store_uid)
  6049. ->where('type', 2)
  6050. ->where('is_deleted', 0)
  6051. ->first();
  6052. if (!$parent) {
  6053. Utils::throwError('20003:父文件夹不存在');
  6054. }
  6055. // 检查父文件夹的 product 类型是否一致
  6056. if ($parent->product != $product) {
  6057. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  6058. }
  6059. $parent_level = $parent->level;
  6060. // 检查层级限制(最多3层)
  6061. if ($parent_level >= 3) {
  6062. Utils::throwError('20003:文件夹层级不能超过3层');
  6063. }
  6064. }
  6065. // 检查当前目录下是否已存在空白文件夹
  6066. $empty_folder_exists = DB::table('mp_products')
  6067. ->where('parent_id', $parent_id)
  6068. ->where('cpid', $cpid)
  6069. ->where('user_id', $store_uid)
  6070. ->where('type', 2)
  6071. ->where('product', $product)
  6072. ->where('product_name', '新建文件夹')
  6073. ->where('is_deleted', 0)
  6074. ->exists();
  6075. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  6076. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  6077. }
  6078. // 创建文件夹
  6079. $folder_id = DB::table('mp_products')->insertGetId([
  6080. 'user_id' => $store_uid,
  6081. 'cpid' => $cpid,
  6082. 'type' => 2,
  6083. 'parent_id' => $parent_id,
  6084. 'level' => $parent_level + 1,
  6085. 'product_name' => $folder_name,
  6086. 'product' => $product,
  6087. 'sort_order' => time(), // 使用时间戳作为排序权重
  6088. 'is_deleted' => 0,
  6089. 'created_at' => date('Y-m-d H:i:s'),
  6090. 'updated_at' => date('Y-m-d H:i:s')
  6091. ]);
  6092. return [
  6093. 'id' => $folder_id,
  6094. 'type' => 2,
  6095. 'parent_id' => $parent_id,
  6096. 'level' => $parent_level + 1,
  6097. 'product_name' => $folder_name,
  6098. 'product' => $product,
  6099. ];
  6100. }
  6101. /**
  6102. * 重命名文件夹或角色
  6103. * @param array $data 包含 id、product_name(新名称)
  6104. * @return bool
  6105. */
  6106. public function renameFolder($data) {
  6107. $uid = Site::getUid();
  6108. $cpid = Site::getCpid();
  6109. $role = Site::getRole();
  6110. $id = getProp($data, 'id');
  6111. $new_name = getProp($data, 'product_name');
  6112. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6113. if (!$id || !$new_name) {
  6114. Utils::throwError('20003:参数不完整');
  6115. }
  6116. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6117. $query_uid = $is_public ? 0 : $uid;
  6118. // 如果是公共库操作,需要admin权限
  6119. if ($is_public && $role !== 'admin') {
  6120. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6121. }
  6122. // 检查是否存在
  6123. $item = DB::table('mp_products')
  6124. ->where('id', $id)
  6125. ->where('cpid', $cpid)
  6126. ->where('user_id', $query_uid)
  6127. ->where('is_deleted', 0)
  6128. ->first();
  6129. if (!$item) {
  6130. Utils::throwError('20003:项目不存在');
  6131. }
  6132. return DB::table('mp_products')
  6133. ->where('id', $id)
  6134. ->where('cpid', $cpid)
  6135. ->where('user_id', $query_uid)
  6136. ->update([
  6137. 'product_name' => $new_name,
  6138. 'updated_at' => date('Y-m-d H:i:s')
  6139. ]);
  6140. }
  6141. /**
  6142. * 移动角色或文件夹到指定文件夹
  6143. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6144. * @return bool
  6145. */
  6146. public function moveProductOrFolder($data) {
  6147. $uid = Site::getUid();
  6148. $cpid = Site::getCpid();
  6149. $role = Site::getRole();
  6150. $id = getProp($data, 'id');
  6151. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6152. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6153. if (!$id) {
  6154. Utils::throwError('20003:请选择要移动的项目');
  6155. }
  6156. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6157. $query_uid = $is_public ? 0 : $uid;
  6158. // 如果是公共库操作,需要admin权限
  6159. if ($is_public && $role !== 'admin') {
  6160. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6161. }
  6162. // 检查要移动的项目
  6163. $item = DB::table('mp_products')
  6164. ->where('id', $id)
  6165. ->where('cpid', $cpid)
  6166. ->where('user_id', $query_uid)
  6167. ->where('is_deleted', 0)
  6168. ->first();
  6169. if (!$item) {
  6170. Utils::throwError('20003:项目不存在');
  6171. }
  6172. // 验证目标文件夹
  6173. $target_level = 0;
  6174. $target_product = $item->product; // 默认使用当前项目的 product
  6175. if ($target_parent_id > 0) {
  6176. $target_parent = DB::table('mp_products')
  6177. ->where('id', $target_parent_id)
  6178. ->where('cpid', $cpid)
  6179. ->where('user_id', $query_uid)
  6180. ->where('type', 2)
  6181. ->where('is_deleted', 0)
  6182. ->first();
  6183. if (!$target_parent) {
  6184. Utils::throwError('20003:目标文件夹不存在');
  6185. }
  6186. // 检查 product 类型是否一致
  6187. if ($target_parent->product != $item->product) {
  6188. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6189. }
  6190. $target_level = $target_parent->level;
  6191. $target_product = $target_parent->product;
  6192. // 如果移动的是文件夹,需要检查层级
  6193. if ($item->type == 2) {
  6194. // 计算移动后的最大层级
  6195. $max_child_level = $this->getMaxChildLevel($id);
  6196. $depth = $max_child_level - $item->level;
  6197. if ($target_level + 1 + $depth > 3) {
  6198. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6199. }
  6200. // 不能移动到自己或自己的子文件夹下
  6201. if ($this->isDescendant($target_parent_id, $id)) {
  6202. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6203. }
  6204. }
  6205. }
  6206. // 更新父文件夹和层级
  6207. $new_level = $target_level + 1;
  6208. DB::table('mp_products')
  6209. ->where('id', $id)
  6210. ->update([
  6211. 'parent_id' => $target_parent_id,
  6212. 'level' => $new_level,
  6213. 'updated_at' => date('Y-m-d H:i:s')
  6214. ]);
  6215. // 如果是文件夹,需要递归更新所有子项的层级
  6216. if ($item->type == 2) {
  6217. $this->updateChildrenLevel($id, $new_level);
  6218. }
  6219. return true;
  6220. }
  6221. /**
  6222. * 获取文件夹下最大子层级
  6223. * @param int $folder_id
  6224. * @return int
  6225. */
  6226. private function getMaxChildLevel($folder_id) {
  6227. $max_level = DB::table('mp_products')
  6228. ->where('parent_id', $folder_id)
  6229. ->where('is_deleted', 0)
  6230. ->max('level');
  6231. if (!$max_level) {
  6232. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6233. }
  6234. // 递归查找子文件夹
  6235. $children = DB::table('mp_products')
  6236. ->where('parent_id', $folder_id)
  6237. ->where('type', 2)
  6238. ->where('is_deleted', 0)
  6239. ->pluck('id');
  6240. foreach ($children as $child_id) {
  6241. $child_max = $this->getMaxChildLevel($child_id);
  6242. if ($child_max > $max_level) {
  6243. $max_level = $child_max;
  6244. }
  6245. }
  6246. return $max_level;
  6247. }
  6248. /**
  6249. * 检查 target_id 是否是 folder_id 的后代
  6250. * @param int $target_id
  6251. * @param int $folder_id
  6252. * @return bool
  6253. */
  6254. private function isDescendant($target_id, $folder_id) {
  6255. if ($target_id == $folder_id) {
  6256. return true;
  6257. }
  6258. $parent = DB::table('mp_products')
  6259. ->where('id', $target_id)
  6260. ->where('is_deleted', 0)
  6261. ->first();
  6262. if (!$parent || $parent->parent_id == 0) {
  6263. return false;
  6264. }
  6265. return $this->isDescendant($parent->parent_id, $folder_id);
  6266. }
  6267. /**
  6268. * 递归更新子项层级
  6269. * @param int $parent_id
  6270. * @param int $parent_level
  6271. */
  6272. private function updateChildrenLevel($parent_id, $parent_level) {
  6273. $children = DB::table('mp_products')
  6274. ->where('parent_id', $parent_id)
  6275. ->where('is_deleted', 0)
  6276. ->get();
  6277. foreach ($children as $child) {
  6278. $new_level = $parent_level + 1;
  6279. DB::table('mp_products')
  6280. ->where('id', $child->id)
  6281. ->update([
  6282. 'level' => $new_level,
  6283. 'updated_at' => date('Y-m-d H:i:s')
  6284. ]);
  6285. // 如果是文件夹,继续递归
  6286. if ($child->type == 2) {
  6287. $this->updateChildrenLevel($child->id, $new_level);
  6288. }
  6289. }
  6290. }
  6291. /**
  6292. * 获取文件夹路径(面包屑导航)
  6293. * @param array $data 包含 folder_id
  6294. * @return array 返回路径数组
  6295. */
  6296. public function getFolderPath($data) {
  6297. $uid = Site::getUid();
  6298. $cpid = Site::getCpid();
  6299. $folder_id = getProp($data, 'id', 0);
  6300. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6301. if ($folder_id == 0) {
  6302. return [
  6303. ['id' => 0, 'name' => '根目录']
  6304. ];
  6305. }
  6306. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6307. $query_uid = $is_public ? 0 : $uid;
  6308. $path = [];
  6309. $current_id = $folder_id;
  6310. while ($current_id > 0) {
  6311. $folder = DB::table('mp_products')
  6312. ->where('id', $current_id)
  6313. ->where('cpid', $cpid)
  6314. ->where('user_id', $query_uid)
  6315. ->where('type', 2)
  6316. ->where('is_deleted', 0)
  6317. ->first();
  6318. if (!$folder) {
  6319. break;
  6320. }
  6321. array_unshift($path, [
  6322. 'id' => $folder->id,
  6323. 'name' => $folder->product_name
  6324. ]);
  6325. $current_id = $folder->parent_id;
  6326. }
  6327. // 添加根目录
  6328. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6329. return $path;
  6330. }
  6331. public function createProduct($data) {
  6332. $uid = Site::getUid();
  6333. $cpid = Site::getCpid();
  6334. $role = Site::getRole();
  6335. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6336. // 如果是公共库操作,需要admin权限
  6337. if ($is_public && $role !== 'admin') {
  6338. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6339. }
  6340. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6341. $store_uid = $is_public ? 0 : $uid;
  6342. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6343. $script_id = (int)getProp($data, 'script_id', 0);
  6344. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6345. if ($script_id && empty($episode_numbers)) {
  6346. Utils::throwError('20003:剧集序号不能为空');
  6347. }
  6348. if (!$script_id && !empty($episode_numbers)) {
  6349. Utils::throwError('20003:请提供剧本ID');
  6350. }
  6351. $product_name = trim(getProp($data, 'product_name'));
  6352. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6353. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6354. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6355. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6356. $url = trim(getProp($data, 'url'));
  6357. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6358. $versions = getProp($data, 'versions');
  6359. // 检查是否是正确的图片格式
  6360. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6361. $urlPath = parse_url($url, PHP_URL_PATH);
  6362. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6363. if (!in_array($extension, $allowedExtensions)) {
  6364. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6365. }
  6366. // 选填三视图图片地址,格式校验与 url 一致
  6367. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6368. if ($three_view_image_url) {
  6369. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6370. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6371. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6372. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6373. }
  6374. }
  6375. // 选填音色音频地址(兼容 timbre_url/audio_url/timbre 传参)
  6376. $timbre_url = $this->getProductTimbreUrl($data);
  6377. if ($timbre_url) {
  6378. $this->validateProductAudioUrl($timbre_url);
  6379. }
  6380. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6381. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6382. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6383. $product = getProp($data, 'product');
  6384. if (!in_array($product, [1, 2, 3])) {
  6385. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6386. }
  6387. // 获取父文件夹ID和层级
  6388. $parent_id = getProp($data, 'parent_id', 0);
  6389. $parent_level = 0;
  6390. if ($parent_id > 0) {
  6391. $parent = DB::table('mp_products')
  6392. ->where('id', $parent_id)
  6393. ->where('cpid', $cpid)
  6394. ->where('user_id', $store_uid)
  6395. ->where('type', 2)
  6396. ->where('is_deleted', 0)
  6397. ->first();
  6398. if (!$parent) {
  6399. Utils::throwError('20003:父文件夹不存在');
  6400. }
  6401. $parent_level = $parent->level;
  6402. }
  6403. // 创建资产并保存剧本资产关联关系(同一事务)
  6404. DB::beginTransaction();
  6405. try {
  6406. $id = DB::table('mp_products')->insertGetId([
  6407. 'user_id' => $store_uid,
  6408. 'cpid' => $cpid,
  6409. 'type' => 1, // 1=角色图片
  6410. 'parent_id' => $parent_id,
  6411. 'level' => $parent_level + 1,
  6412. 'product_name' => $product_name,
  6413. 'url' => $url,
  6414. 'three_view_image_url' => $three_view_image_url,
  6415. 'timbre_url' => $timbre_url,
  6416. 'pic_prompt' => $pic_prompt,
  6417. 'product' => $product,
  6418. 'versions' => json_encode($versions, 256),
  6419. 'sort_order' => time(), // 使用时间戳作为排序权重
  6420. 'created_at' => date('Y-m-d H:i:s'),
  6421. 'updated_at' => date('Y-m-d H:i:s')
  6422. ]);
  6423. if (!$id) Utils::throwError('20003:创建失败');
  6424. // 保存剧本资产关联关系
  6425. if ($script_id) {
  6426. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6427. }
  6428. DB::commit();
  6429. } catch (\Exception $e) {
  6430. DB::rollback();
  6431. throw $e;
  6432. }
  6433. return [
  6434. 'id' => $id,
  6435. 'type' => 1,
  6436. 'parent_id' => $parent_id,
  6437. 'level' => $parent_level + 1,
  6438. 'product_name' => $product_name,
  6439. 'url' => $url,
  6440. 'three_view_image_url' => $three_view_image_url,
  6441. 'timbre_url' => $timbre_url,
  6442. 'pic_prompt' => $pic_prompt,
  6443. 'product' => $product,
  6444. 'versions' => $versions
  6445. ];
  6446. }
  6447. public function editProduct($data) {
  6448. $uid = Site::getUid();
  6449. $cpid = Site::getCpid();
  6450. $role = Site::getRole();
  6451. $id = getProp($data, 'id');
  6452. if (!$id) Utils::throwError('20003:ID不能为空');
  6453. $versions = getProp($data, 'versions');
  6454. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6455. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6456. $script_id = (int)getProp($data, 'script_id', 0);
  6457. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6458. if ($script_id && empty($episode_numbers)) {
  6459. Utils::throwError('20003:剧集序号不能为空');
  6460. }
  6461. if (!$script_id && !empty($episode_numbers)) {
  6462. Utils::throwError('20003:请提供剧本ID');
  6463. }
  6464. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6465. $query_uid = $is_public ? 0 : $uid;
  6466. // 如果是公共库操作,需要admin权限
  6467. if ($is_public && $role !== 'admin') {
  6468. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6469. }
  6470. // 检查是否存在且属于当前用户或公共库
  6471. $role = DB::table('mp_products')
  6472. ->where('id', $id)
  6473. ->where('cpid', $cpid)
  6474. ->where('user_id', $query_uid)
  6475. ->where('type', 1)->first();
  6476. if (!$role) Utils::throwError('20003:记录不存在');
  6477. $updateData = [];
  6478. // $needVersionRecord = false; // 是否需要记录版本
  6479. // 名称
  6480. $product_name = trim(getProp($data, 'product_name'));
  6481. if ($product_name) {
  6482. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6483. $updateData['product_name'] = $product_name;
  6484. }
  6485. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6486. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6487. // 图片地址
  6488. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6489. $url = trim(getProp($data, 'url'));
  6490. if ($url) {
  6491. // 检查是否是正确的图片格式
  6492. $urlPath = parse_url($url, PHP_URL_PATH);
  6493. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6494. if (!in_array($extension, $allowedExtensions)) {
  6495. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6496. }
  6497. // // 如果 url 有变更,记录版本
  6498. // if ($url !== $role->url) {
  6499. // $needVersionRecord = true;
  6500. // }
  6501. $updateData['url'] = $url;
  6502. }
  6503. // 三视图图片地址(选填),格式校验与 url 一致
  6504. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6505. if ($three_view_image_url) {
  6506. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6507. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6508. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6509. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6510. }
  6511. $updateData['three_view_image_url'] = $three_view_image_url;
  6512. }
  6513. // 音色音频地址(选填,显式传空字符串可清除已有音色)
  6514. if (array_key_exists('timbre_url', $data) || array_key_exists('audio_url', $data) || array_key_exists('timbre', $data)) {
  6515. $timbre_url = $this->getProductTimbreUrl($data);
  6516. if ($timbre_url) {
  6517. $this->validateProductAudioUrl($timbre_url);
  6518. }
  6519. $updateData['timbre_url'] = $timbre_url;
  6520. }
  6521. // 提示词
  6522. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6523. if ($pic_prompt) {
  6524. // // 如果 pic_prompt 有变更,记录版本
  6525. // if ($pic_prompt !== $role->pic_prompt) {
  6526. // $needVersionRecord = true;
  6527. // }
  6528. $updateData['pic_prompt'] = $pic_prompt;
  6529. }
  6530. if (empty($updateData) && !$script_id) {
  6531. Utils::throwError('20003:没有需要更新的数据');
  6532. }
  6533. // // 如果需要记录版本,将数据添加到 versions 数组
  6534. // if ($needVersionRecord) {
  6535. // // 获取现有的 versions 数据
  6536. // $versions = json_decode($role->versions, true) ?: [];
  6537. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6538. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6539. // if ($isFirstVersion) {
  6540. // $oldVersion = [
  6541. // 'url' => $role->url,
  6542. // 'description' => $role->pic_prompt,
  6543. // ];
  6544. // // 旧版本添加到数组末尾
  6545. // $versions[] = $oldVersion;
  6546. // }
  6547. // // 构建新版本(变更后)
  6548. // $newVersion = [
  6549. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6550. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6551. // ];
  6552. // // 检查新版本是否已存在于历史版本中
  6553. // $existingIndex = -1;
  6554. // foreach ($versions as $index => $version) {
  6555. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6556. // $existingIndex = $index;
  6557. // break;
  6558. // }
  6559. // }
  6560. // if ($existingIndex !== -1) {
  6561. // // 如果已存在,移除旧的位置
  6562. // array_splice($versions, $existingIndex, 1);
  6563. // }
  6564. // // 新版本添加到数组开头(最新的在前)
  6565. // array_unshift($versions, $newVersion);
  6566. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6567. // // if (count($versions) > 10) {
  6568. // // $versions = array_slice($versions, 0, 10);
  6569. // // }
  6570. // $updateData['versions'] = json_encode($versions, 256);
  6571. // }
  6572. if ($versions) {
  6573. $updateData['versions'] = json_encode($versions, 256);
  6574. }
  6575. if (!empty($updateData)) {
  6576. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6577. }
  6578. // 更新资产并保存剧本资产关联关系(同一事务)
  6579. DB::beginTransaction();
  6580. try {
  6581. $updated = true;
  6582. if (!empty($updateData)) {
  6583. $updated = DB::table('mp_products')
  6584. ->where('cpid', $cpid)
  6585. ->where('id', $id)
  6586. ->update($updateData);
  6587. }
  6588. // 保存剧本资产关联关系
  6589. if ($script_id) {
  6590. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6591. }
  6592. DB::commit();
  6593. } catch (\Exception $e) {
  6594. DB::rollback();
  6595. throw $e;
  6596. }
  6597. return $updated;
  6598. }
  6599. /**
  6600. * 获取资产音色音频地址
  6601. * 兼容 timbre_url/audio_url/timbre 三种传参,timbre 支持字符串或 {"url":"..."} 结构
  6602. *
  6603. * @param array $data
  6604. * @return string
  6605. */
  6606. private function getProductTimbreUrl($data) {
  6607. foreach (['timbre_url', 'audio_url', 'timbre'] as $key) {
  6608. if (!array_key_exists($key, $data)) {
  6609. continue;
  6610. }
  6611. $value = $data[$key];
  6612. if (is_array($value)) {
  6613. $value = getProp($value, 'url', $value[0] ?? '');
  6614. }
  6615. if (!is_string($value)) {
  6616. continue;
  6617. }
  6618. return trim($value);
  6619. }
  6620. return '';
  6621. }
  6622. /**
  6623. * 校验资产音色音频地址格式
  6624. *
  6625. * @param string $url 音频地址
  6626. * @return void
  6627. */
  6628. private function validateProductAudioUrl($url) {
  6629. $allowedExtensions = ['mp3', 'wav', 'm4a', 'aac', 'ogg', 'oga', 'flac', 'amr', 'wma', 'weba'];
  6630. $urlPath = parse_url($url, PHP_URL_PATH);
  6631. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6632. if (!in_array($extension, $allowedExtensions)) {
  6633. Utils::throwError('20003:音色音频格式不正确,仅支持 mp3、wav、m4a、aac、ogg、flac、amr、wma 格式');
  6634. }
  6635. }
  6636. /**
  6637. * 保存单一资产与剧本剧集的关联关系
  6638. *
  6639. * @param int $product_id 资产ID
  6640. * @param int $script_id 剧本ID
  6641. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6642. * @return int 新增关联数量
  6643. */
  6644. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6645. $uid = Site::getUid();
  6646. // 验证剧本是否存在
  6647. $script = DB::table('mp_scripts')
  6648. ->where('id', $script_id)
  6649. ->where('is_deleted', 0)
  6650. ->first();
  6651. if (!$script) {
  6652. Utils::throwError('20003:剧本不存在');
  6653. }
  6654. // 验证剧本归属:只能关联自己的剧本
  6655. if ((int)$script->user_id !== (int)$uid) {
  6656. Utils::throwError('20003:只能添加到自己的剧本');
  6657. }
  6658. // 使用 splitContent 拆分剧本内容获取总集数
  6659. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6660. // 解析剧集序号(数组)
  6661. $episodes = [];
  6662. foreach ($episode_numbers as $item) {
  6663. if (is_array($item)) {
  6664. continue;
  6665. }
  6666. $item = trim((string)$item);
  6667. if ($item === '' || !is_numeric($item)) {
  6668. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6669. }
  6670. $episodes[] = (int)$item;
  6671. }
  6672. // 去重并校验序号范围(序号从1开始)
  6673. $episodes = array_values(array_unique($episodes));
  6674. if (empty($episodes)) {
  6675. Utils::throwError('20003:剧集序号不能为空');
  6676. }
  6677. foreach ($episodes as $episode) {
  6678. if ($episode < 1 || $episode > $totalEpisodes) {
  6679. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6680. }
  6681. }
  6682. $now = now();
  6683. // 过滤已存在的关联,避免重复
  6684. $existingEpisodes = DB::table('mp_script_product_mappings')
  6685. ->where('script_id', $script_id)
  6686. ->where('product_id', $product_id)
  6687. ->whereIn('episode_number', $episodes)
  6688. ->pluck('episode_number')
  6689. ->all();
  6690. $mappingRecords = [];
  6691. foreach ($episodes as $episode) {
  6692. if (in_array($episode, $existingEpisodes)) {
  6693. continue;
  6694. }
  6695. $mappingRecords[] = [
  6696. 'script_id' => $script_id,
  6697. 'product_id' => $product_id,
  6698. 'episode_number' => $episode,
  6699. 'created_at' => $now,
  6700. 'updated_at' => $now,
  6701. ];
  6702. }
  6703. $insertedCount = 0;
  6704. if (!empty($mappingRecords)) {
  6705. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6706. }
  6707. return $insertedCount;
  6708. }
  6709. /**
  6710. * 规范化剧集序号参数,统一为数组
  6711. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6712. *
  6713. * @param mixed $episode_number 剧集序号参数
  6714. * @return array
  6715. */
  6716. private function normalizeEpisodeNumbers($episode_number) {
  6717. if (!is_array($episode_number)) {
  6718. $episode_number = explode(',', (string)$episode_number);
  6719. }
  6720. $items = [];
  6721. foreach ($episode_number as $item) {
  6722. if (is_array($item)) {
  6723. continue;
  6724. }
  6725. foreach (explode(',', (string)$item) as $part) {
  6726. $part = trim($part);
  6727. if ($part !== '') {
  6728. $items[] = $part;
  6729. }
  6730. }
  6731. }
  6732. return $items;
  6733. }
  6734. /**
  6735. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6736. *
  6737. * @param object $script 剧本记录
  6738. * @return int 总集数
  6739. */
  6740. private function getScriptTotalEpisodeCount($script) {
  6741. if (empty($script->content)) {
  6742. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6743. }
  6744. $totalEpisodes = count(splitContent($script->content));
  6745. if ($totalEpisodes < 1) {
  6746. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6747. }
  6748. return $totalEpisodes;
  6749. }
  6750. /**
  6751. * 获取剧本总集数
  6752. *
  6753. * @param array $data 包含 script_id(剧本ID)
  6754. * @return array
  6755. */
  6756. public function getScriptTotalEpisodes($data) {
  6757. $script_id = (int)getProp($data, 'script_id', 0);
  6758. if (!$script_id) {
  6759. Utils::throwError('20003:请提供剧本ID');
  6760. }
  6761. // 验证剧本是否存在
  6762. $script = DB::table('mp_scripts')
  6763. ->where('id', $script_id)
  6764. ->where('is_deleted', 0)
  6765. ->first();
  6766. if (!$script) {
  6767. Utils::throwError('20003:剧本不存在');
  6768. }
  6769. return [
  6770. 'script_id' => $script_id,
  6771. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6772. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6773. ];
  6774. }
  6775. /**
  6776. * 获取角色版本历史
  6777. * @param array $data 包含 id(角色ID)
  6778. * @return array 返回版本历史列表
  6779. */
  6780. public function getProductVersions($data) {
  6781. $cpid = Site::getCpid();
  6782. $id = getProp($data, 'id');
  6783. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6784. $role = DB::table('mp_products')
  6785. ->where('id', $id)
  6786. ->where('cpid', $cpid)
  6787. ->where('type', 1)
  6788. ->first();
  6789. if (!$role) Utils::throwError('20003:角色不存在');
  6790. // 获取版本历史
  6791. $versions = json_decode($role->versions, true) ?: [];
  6792. // 添加当前版本作为最新版本
  6793. $currentVersion = [
  6794. 'version' => 0, // 0 表示当前版本
  6795. 'url' => $role->url,
  6796. 'pic_prompt' => $role->pic_prompt,
  6797. 'updated_at' => $role->updated_at,
  6798. 'is_current' => true
  6799. ];
  6800. array_unshift($versions, $currentVersion);
  6801. return $versions;
  6802. }
  6803. /**
  6804. * 恢复到指定版本
  6805. * @param array $data 包含 id(角色ID)、version(版本号)
  6806. * @return bool
  6807. */
  6808. public function restoreProductVersion($data) {
  6809. $uid = Site::getUid();
  6810. $cpid = Site::getCpid();
  6811. $id = getProp($data, 'id');
  6812. $version = getProp($data, 'version');
  6813. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6814. if (!$version) Utils::throwError('20003:版本号不能为空');
  6815. $role = DB::table('mp_products')
  6816. ->where('id', $id)
  6817. ->where('cpid', $cpid)
  6818. ->where('type', 1)
  6819. ->first();
  6820. if (!$role) Utils::throwError('20003:角色不存在');
  6821. // 获取版本历史
  6822. $versions = json_decode($role->versions, true) ?: [];
  6823. // 查找指定版本
  6824. $targetVersion = null;
  6825. foreach ($versions as $v) {
  6826. if ($v['version'] == $version) {
  6827. $targetVersion = $v;
  6828. break;
  6829. }
  6830. }
  6831. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6832. // 先将当前版本保存到历史
  6833. $newVersion = [
  6834. 'version' => count($versions) + 1,
  6835. 'url' => $role->url,
  6836. 'pic_prompt' => $role->pic_prompt,
  6837. 'updated_at' => date('Y-m-d H:i:s'),
  6838. 'updated_by' => $uid
  6839. ];
  6840. array_unshift($versions, $newVersion);
  6841. // 限制版本数量
  6842. if (count($versions) > 10) {
  6843. $versions = array_slice($versions, 0, 10);
  6844. }
  6845. // 恢复到指定版本
  6846. return DB::table('mp_products')
  6847. ->where('id', $id)
  6848. ->where('cpid', $cpid)
  6849. ->update([
  6850. 'url' => $targetVersion['url'],
  6851. 'pic_prompt' => $targetVersion['pic_prompt'],
  6852. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6853. 'updated_at' => date('Y-m-d H:i:s')
  6854. ]);
  6855. }
  6856. public function deleteProduct($data) {
  6857. $uid = Site::getUid();
  6858. $cpid = Site::getCpid();
  6859. $role = Site::getRole();
  6860. $id = getProp($data, 'id');
  6861. if (!$id) Utils::throwError('20003:ID不能为空');
  6862. $ids = explode(',', $id);
  6863. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6864. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6865. $query_uid = $is_public ? 0 : $uid;
  6866. // 如果是公共库操作,需要admin权限
  6867. if ($is_public && $role !== 'admin') {
  6868. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6869. }
  6870. // 检查是否存在且属于当前用户或公共库
  6871. $role = DB::table('mp_products')
  6872. ->whereIn('id', $ids)
  6873. ->where('cpid', $cpid)
  6874. ->where('user_id', $query_uid)
  6875. ->get();
  6876. if (!$role) Utils::throwError('20003:记录不存在');
  6877. return DB::table('mp_products')
  6878. ->where('cpid', $cpid)
  6879. ->where('user_id', $query_uid)
  6880. ->whereIn('id', $ids)
  6881. ->update([
  6882. 'is_deleted' => 1,
  6883. 'updated_at' => date('Y-m-d H:i:s')
  6884. ]);
  6885. }
  6886. public function generateThreeView($data) {
  6887. $uid = Site::getUid();
  6888. $cpid = Site::getCpid();
  6889. $role = Site::getRole();
  6890. $id = getProp($data, 'id');
  6891. if (!$id) Utils::throwError('20003:ID不能为空');
  6892. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6893. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6894. $query_uid = $is_public ? 0 : $uid;
  6895. // 如果是公共库操作,需要admin权限
  6896. if ($is_public && $role !== 'admin') {
  6897. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6898. }
  6899. // 检查是否存在且属于当前用户或公共库
  6900. $product = DB::table('mp_products')
  6901. ->where('id', $id)
  6902. ->where('cpid', $cpid)
  6903. ->where('user_id', $query_uid)
  6904. ->where('type', 1)->first();
  6905. if (!$product) Utils::throwError('20003:资产不存在');
  6906. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。'));
  6907. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6908. if (!$ref_img_url) {
  6909. // 如果没有传入参考图,使用角色表中的图片
  6910. $ref_img_url = $product->url ?? '';
  6911. if (!$ref_img_url) {
  6912. Utils::throwError('20003:参考图不能为空');
  6913. }
  6914. }
  6915. $pic_prompt = getProp($product, 'pic_prompt');
  6916. if ($pic_prompt) {
  6917. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6918. }
  6919. // 检查参考图是否是正确的图片格式
  6920. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6921. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6922. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6923. if (!in_array($extension, $allowedExtensions)) {
  6924. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6925. }
  6926. // 处理图片模型
  6927. $model = getProp($data, 'model');
  6928. if (!$model) {
  6929. // 使用默认模型
  6930. $model = 'gpt-image-2';
  6931. }
  6932. // 验证模型是否在可用模型表中
  6933. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6934. Utils::throwError('20003:该模型已不可用,请更换!');
  6935. }
  6936. $ratio = getProp($data, 'ratio', '16:9');
  6937. $resolution = getProp($data, 'resolution', '2k');
  6938. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  6939. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  6940. // 参数验证
  6941. $resolution = strtolower($resolution);
  6942. if (!isset($sizeMap[$resolution])) {
  6943. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6944. }
  6945. if (!isset($sizeMap[$resolution][$ratio])) {
  6946. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6947. }
  6948. // 根据 ratio 和 resolution 确定宽高
  6949. $width = $sizeMap[$resolution][$ratio]['width'];
  6950. $height = $sizeMap[$resolution][$ratio]['height'];
  6951. try {
  6952. // 创建图片生成任务
  6953. $params = [
  6954. 'prompt' => $prompt,
  6955. 'model' => $model,
  6956. 'ref_img_urls' => [$ref_img_url],
  6957. 'width' => $width,
  6958. 'height' => $height
  6959. ];
  6960. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6961. $task_id = $task->id;
  6962. if (!$task_id) {
  6963. Utils::throwError('20003:创建图片生成任务失败');
  6964. }
  6965. // 轮询获取结果
  6966. // 只查询数据库,不调用API,不更新任务表
  6967. $start_time = time();
  6968. $timeout = 1800;
  6969. $img_url = '';
  6970. while (time() - $start_time < $timeout) {
  6971. sleep(5);
  6972. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6973. $task = DB::table('mp_generate_pic_tasks')
  6974. ->where('id', $task_id)
  6975. ->first();
  6976. if (!$task) {
  6977. Utils::throwError('20003:任务不存在');
  6978. }
  6979. if ($task->status === 'success' && $task->result_url) {
  6980. $result_urls = is_string($task->result_url)
  6981. ? json_decode($task->result_url, true)
  6982. : $task->result_url;
  6983. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6984. break;
  6985. } elseif ($task->status === 'failed') {
  6986. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6987. }
  6988. // 其他状态继续轮询
  6989. }
  6990. if (empty($img_url)) {
  6991. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6992. }
  6993. // 更新 mp_products 表(不是任务表)
  6994. DB::table('mp_products')
  6995. ->where('id', $id)
  6996. ->where('cpid', $cpid)
  6997. ->update([
  6998. 'three_view_image_url' => $img_url,
  6999. 'updated_at' => date('Y-m-d H:i:s')
  7000. ]);
  7001. return ['three_view_image_url' => $img_url];
  7002. } catch (\Exception $e) {
  7003. dLog('anime')->error('生成三视图失败', [
  7004. 'error' => $e->getMessage()
  7005. ]);
  7006. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  7007. Utils::throwError('20003:' . $e->getMessage());
  7008. }
  7009. }
  7010. /**
  7011. * 推送(复制)资产或文件夹到目标位置
  7012. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  7013. * @return array 返回推送结果
  7014. */
  7015. public function pushProductOrFolder($data) {
  7016. $uid = Site::getUid();
  7017. $cpid = Site::getCpid();
  7018. $role = Site::getRole();
  7019. $product_id = getProp($data, 'product_id');
  7020. $target_parent_id = getProp($data, 'target_parent_id', 0);
  7021. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  7022. if (!$product_id) {
  7023. Utils::throwError('20003:请选择要推送的项目');
  7024. }
  7025. // 查询源项目(只通过cpid查询,不限制user_id)
  7026. $sourceItem = DB::table('mp_products')
  7027. ->where('id', $product_id)
  7028. ->where('cpid', $cpid)
  7029. ->where('is_deleted', 0)
  7030. ->first();
  7031. if (!$sourceItem) {
  7032. Utils::throwError('20003:要推送的项目不存在');
  7033. }
  7034. // 通过user_id判断源是公共库还是个人库
  7035. $source_uid = $sourceItem->user_id;
  7036. $source_is_public = ($source_uid == 0) ? 1 : 0;
  7037. // 验证目标文件夹并确定目标是公共库还是个人库
  7038. $target_level = 0;
  7039. $target_uid = $uid; // 默认推送到个人库
  7040. $target_is_public = 0;
  7041. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  7042. if ($target_parent_id > 0) {
  7043. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  7044. $targetParent = DB::table('mp_products')
  7045. ->where('id', $target_parent_id)
  7046. ->where('cpid', $cpid)
  7047. ->where('type', 2)
  7048. ->where('is_deleted', 0)
  7049. ->first();
  7050. if (!$targetParent) {
  7051. Utils::throwError('20003:目标文件夹不存在');
  7052. }
  7053. // 通过user_id判断目标是公共库还是个人库
  7054. $target_level = $targetParent->level;
  7055. $target_uid = $targetParent->user_id;
  7056. $target_is_public = ($target_uid == 0) ? 1 : 0;
  7057. // 使用目标文件夹的 product 类型
  7058. $final_product_type = $targetParent->product;
  7059. }
  7060. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  7061. else {
  7062. $push_to_public = getProp($data, 'push_to_public');
  7063. if ($push_to_public === '') {
  7064. Utils::throwError('20003:请选择是否推送到公共库');
  7065. }
  7066. if ($push_to_public) {
  7067. $target_uid = 0;
  7068. $target_is_public = 1;
  7069. }
  7070. // 推送到根目录时,必须指定 product 类型
  7071. if ($target_product === null || $target_product === '') {
  7072. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  7073. }
  7074. $final_product_type = $target_product;
  7075. }
  7076. // 如果目标是公共库,需要admin权限
  7077. if ($target_is_public && $role !== 'admin') {
  7078. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  7079. }
  7080. // 权限验证:验证是否符合允许的推送规则
  7081. $this->validatePushPermission($source_uid, $target_uid, $uid);
  7082. try {
  7083. DB::beginTransaction();
  7084. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  7085. if ($sourceItem->type == 1) {
  7086. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  7087. DB::commit();
  7088. return [
  7089. 'product_id' => $newId,
  7090. ];
  7091. }
  7092. // 如果是文件夹,递归复制(支持跨类型推送)
  7093. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  7094. DB::commit();
  7095. return [
  7096. 'product_id' => $newFolderId,
  7097. ];
  7098. } catch (\Exception $e) {
  7099. DB::rollBack();
  7100. dLog('anime')->error('推送失败', [
  7101. 'error' => $e->getMessage(),
  7102. 'product_id' => $product_id
  7103. ]);
  7104. Utils::throwError('20003:' . $e->getMessage());
  7105. }
  7106. }
  7107. /**
  7108. * 验证推送权限
  7109. * 允许的推送规则:
  7110. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7111. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  7112. * 3. 公共库推送给公共库(公共库 → 公共库)
  7113. *
  7114. * @param int $source_uid 源的user_id
  7115. * @param int $target_uid 目标的user_id
  7116. * @param int $current_uid 当前用户ID
  7117. * @throws \Exception
  7118. */
  7119. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  7120. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7121. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  7122. return; // 允许
  7123. }
  7124. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  7125. if ($source_uid == 0 && $target_uid == $current_uid) {
  7126. return; // 允许
  7127. }
  7128. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7129. if ($source_uid == 0 && $target_uid == 0) {
  7130. return; // 允许
  7131. }
  7132. // 其他情况都不允许
  7133. if ($source_uid != 0 && $source_uid != $current_uid) {
  7134. // 源是别人的个人库
  7135. Utils::throwError('20003:无权限访问该资产');
  7136. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7137. // 个人库推送给公共库(不允许)
  7138. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7139. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7140. // 不同用户的个人库之间推送(不允许)
  7141. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7142. } else {
  7143. // 其他未知情况
  7144. Utils::throwError('20003:不允许的推送操作');
  7145. }
  7146. }
  7147. /**
  7148. * 复制单个资产
  7149. * @param object $sourceProduct 源资产对象
  7150. * @param int $targetParentId 目标父文件夹ID
  7151. * @param int $targetLevel 目标层级
  7152. * @param int $cpid 公司ID
  7153. * @param int $targetUid 目标用户ID
  7154. * @return int 返回新资产ID
  7155. */
  7156. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7157. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7158. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7159. $newProductData = [
  7160. 'user_id' => $targetUid,
  7161. 'cpid' => $cpid,
  7162. 'type' => 1,
  7163. 'parent_id' => $targetParentId,
  7164. 'level' => $targetLevel,
  7165. 'product_name' => $sourceProduct->product_name,
  7166. 'url' => $sourceProduct->url,
  7167. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7168. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7169. 'product' => $finalProductType,
  7170. 'versions' => $sourceProduct->versions ?? '',
  7171. 'sort_order' => time(),
  7172. 'is_deleted' => 0,
  7173. 'created_at' => date('Y-m-d H:i:s'),
  7174. 'updated_at' => date('Y-m-d H:i:s')
  7175. ];
  7176. return DB::table('mp_products')->insertGetId($newProductData);
  7177. }
  7178. /**
  7179. * 递归复制文件夹及其子项
  7180. * @param object $sourceFolder 源文件夹对象
  7181. * @param int $targetParentId 目标父文件夹ID
  7182. * @param int $targetLevel 目标层级
  7183. * @param int $cpid 公司ID
  7184. * @param int $targetUid 目标用户ID
  7185. * @param int $sourceUid 源用户ID
  7186. * @return int 返回新文件夹ID
  7187. */
  7188. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7189. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7190. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7191. // 创建新文件夹
  7192. $newFolderData = [
  7193. 'user_id' => $targetUid,
  7194. 'cpid' => $cpid,
  7195. 'type' => 2,
  7196. 'parent_id' => $targetParentId,
  7197. 'level' => $targetLevel,
  7198. 'product_name' => $sourceFolder->product_name,
  7199. 'product' => $finalProductType,
  7200. 'sort_order' => time(),
  7201. 'is_deleted' => 0,
  7202. 'created_at' => date('Y-m-d H:i:s'),
  7203. 'updated_at' => date('Y-m-d H:i:s')
  7204. ];
  7205. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7206. // 获取源文件夹下的所有子项
  7207. $children = DB::table('mp_products')
  7208. ->where('parent_id', $sourceFolder->id)
  7209. ->where('cpid', $cpid)
  7210. ->where('user_id', $sourceUid)
  7211. ->where('is_deleted', 0)
  7212. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7213. ->get();
  7214. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7215. foreach ($children as $child) {
  7216. if ($child->type == 1) {
  7217. // 资产
  7218. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7219. } else {
  7220. // 文件夹
  7221. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7222. }
  7223. }
  7224. return $newFolderId;
  7225. }
  7226. /**
  7227. * 转让剧本归属(剧本及其关联资产)
  7228. *
  7229. * 仅调整 mp_scripts.user_id 与 mp_products.user_id,其他表保持不变。
  7230. * 权限:仅 admin / superadmin 可操作;目标用户必须是同组(cpid 相同)且角色为 user(组员)的用户,禁止跨组转让。
  7231. * 多个剧本逐个独立事务处理,单个剧本失败不影响其他剧本;
  7232. * 单个剧本内的剧本记录与关联资产必须全部更新成功,否则整体回滚。
  7233. *
  7234. * @param array $data 请求参数:script_ids(数组或英文逗号分隔,兼容单个 script_id)、target_user_id
  7235. * @return array
  7236. */
  7237. public function transferScriptOwner($data) {
  7238. $operatorRole = Site::getRole();
  7239. $operatorCpid = Site::getCpid();
  7240. // 1.权限校验:仅管理员和超管可操作
  7241. if (!in_array($operatorRole, ['admin', 'superadmin'], true)) {
  7242. Utils::throwError(ErrorConst::NOT_ACCESS);
  7243. }
  7244. // 2.目标用户校验:必须存在且角色为 user(组员)
  7245. $targetUserId = (int)getProp($data, 'target_user_id', 0);
  7246. if ($targetUserId < 1) {
  7247. Utils::throwError('1002:请选择转让的目标用户');
  7248. }
  7249. $targetUser = DB::table('mp_manage_users')
  7250. ->where('id', $targetUserId)
  7251. ->where('is_deleted', 0)
  7252. ->first();
  7253. if (!$targetUser) {
  7254. Utils::throwError('20003:目标用户不存在');
  7255. }
  7256. if ((string)getProp($targetUser, 'role') !== 'user') {
  7257. Utils::throwError('20003:只能转让给角色为组员(user)的用户');
  7258. }
  7259. $targetCpid = (int)getProp($targetUser, 'cpid');
  7260. // 3.规范化剧本ID列表(兼容数组、逗号分隔字符串、script_id 单值)
  7261. $rawScriptIds = getProp($data, 'script_ids');
  7262. if (empty($rawScriptIds)) {
  7263. $rawScriptIds = getProp($data, 'script_id');
  7264. }
  7265. $scriptIds = $this->normalizeIdList($rawScriptIds);
  7266. if (empty($scriptIds)) {
  7267. Utils::throwError('20003:请提供剧本ID');
  7268. }
  7269. // 预取剧本名称,便于失败结果中回显
  7270. $scriptNameMap = DB::table('mp_scripts')
  7271. ->whereIn('id', $scriptIds)
  7272. ->pluck('script_name', 'id')
  7273. ->all();
  7274. $successList = [];
  7275. $failedList = [];
  7276. // 4.逐个剧本独立事务处理,单个失败不影响其他剧本
  7277. foreach ($scriptIds as $scriptId) {
  7278. DB::beginTransaction();
  7279. try {
  7280. $successList[] = $this->transferSingleScriptOwner(
  7281. $scriptId,
  7282. $targetUserId,
  7283. $targetCpid,
  7284. $operatorRole,
  7285. $operatorCpid,
  7286. Site::getUid()
  7287. );
  7288. DB::commit();
  7289. } catch (\Throwable $e) {
  7290. DB::rollBack();
  7291. $failedList[] = [
  7292. 'script_id' => (int)$scriptId,
  7293. 'script_name' => (string)($scriptNameMap[$scriptId] ?? ''),
  7294. 'reason' => $e->getMessage() !== '' ? $e->getMessage() : '转让失败',
  7295. ];
  7296. dLog('anime')->error('剧本归属转让失败', [
  7297. 'script_id' => $scriptId,
  7298. 'target_user_id' => $targetUserId,
  7299. 'operator_uid' => Site::getUid(),
  7300. 'error' => $e->getMessage(),
  7301. ]);
  7302. }
  7303. }
  7304. return [
  7305. 'target_user_id' => $targetUserId,
  7306. 'success_count' => count($successList),
  7307. 'failed_count' => count($failedList),
  7308. 'success_list' => $successList,
  7309. 'failed_list' => $failedList,
  7310. ];
  7311. }
  7312. /**
  7313. * 单个剧本的归属转让(需在事务中调用)
  7314. *
  7315. * @param int $scriptId 剧本ID
  7316. * @param int $targetUserId 目标用户ID
  7317. * @param int $targetCpid 目标用户所属公司ID
  7318. * @param string $operatorRole 操作人角色
  7319. * @param int $operatorCpid 操作人所属公司ID
  7320. * @param int $operatorUid 操作人用户ID
  7321. * @return array
  7322. */
  7323. private function transferSingleScriptOwner($scriptId, $targetUserId, $targetCpid, $operatorRole, $operatorCpid, $operatorUid) {
  7324. $script = DB::table('mp_scripts')
  7325. ->where('id', $scriptId)
  7326. ->where('is_deleted', 0)
  7327. ->first();
  7328. if (!$script) {
  7329. Utils::throwError('20003:剧本不存在');
  7330. }
  7331. $scriptCpid = (int)getProp($script, 'cpid');
  7332. $fromUserId = (int)getProp($script, 'user_id');
  7333. // 管理员仅可操作本组剧本
  7334. if ($operatorRole !== 'superadmin' && $scriptCpid !== $operatorCpid) {
  7335. Utils::throwError(ErrorConst::NOT_ACCESS);
  7336. }
  7337. // 管理员仅可转让自己创建的剧本(超管不做此验证)
  7338. if ($operatorRole !== 'superadmin' && $fromUserId !== (int)$operatorUid) {
  7339. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7340. }
  7341. // 禁止跨组转让:目标用户必须与剧本同组
  7342. if ($targetCpid !== $scriptCpid) {
  7343. Utils::throwError('20003:不能跨组转让,目标用户与剧本不在同一组');
  7344. }
  7345. // 关联资产ID(同一资产可能关联多个剧集序号,需去重)
  7346. $productIds = $this->normalizeIdList(
  7347. DB::table('mp_script_product_mappings')
  7348. ->where('script_id', $scriptId)
  7349. ->pluck('product_id')
  7350. ->all()
  7351. );
  7352. $folderIds = [];
  7353. if (!empty($productIds)) {
  7354. $products = DB::table('mp_products')
  7355. ->whereIn('id', $productIds)
  7356. ->select('id', 'cpid', 'parent_id', 'user_id')
  7357. ->get();
  7358. // 关联资产必须全部存在,否则视为数据异常,不提交
  7359. if ($products->count() !== count($productIds)) {
  7360. Utils::throwError('20003:剧本存在已丢失的关联资产,无法完成转让');
  7361. }
  7362. foreach ($products as $product) {
  7363. // 关联资产必须与剧本同组,避免误转让跨组资产
  7364. if ((int)getProp($product, 'cpid') !== $scriptCpid) {
  7365. Utils::throwError('20003:剧本存在跨组关联资产,无法完成转让');
  7366. }
  7367. $parentId = (int)getProp($product, 'parent_id', 0);
  7368. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7369. $folderIds[] = $parentId;
  7370. }
  7371. }
  7372. // 仅转让归属于原剧本所有者的资产
  7373. $folderIds = DB::table('mp_products')
  7374. ->whereIn('id', $folderIds)
  7375. ->where('type', 2)
  7376. ->where('cpid', $scriptCpid)
  7377. ->where('user_id', $fromUserId)
  7378. ->pluck('id')
  7379. ->map('intval')
  7380. ->all();
  7381. // 管理员仅可转让自己创建的资产及其所属文件夹(超管不做此验证)
  7382. if ($operatorRole !== 'superadmin') {
  7383. foreach ($products as $product) {
  7384. if ((int)getProp($product, 'user_id') !== (int)$operatorUid) {
  7385. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7386. }
  7387. }
  7388. foreach ($products as $product) {
  7389. $parentId = (int)getProp($product, 'parent_id', 0);
  7390. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7391. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7392. }
  7393. }
  7394. }
  7395. }
  7396. $now = now();
  7397. // 5.更新剧本归属
  7398. DB::table('mp_scripts')
  7399. ->where('id', $scriptId)
  7400. ->update([
  7401. 'user_id' => $targetUserId,
  7402. 'updated_at' => $now,
  7403. ]);
  7404. // 6.更新关联资产归属
  7405. if (!empty($productIds)) {
  7406. DB::table('mp_products')
  7407. ->whereIn('id', $productIds)
  7408. ->update([
  7409. 'user_id' => $targetUserId,
  7410. 'updated_at' => $now,
  7411. ]);
  7412. }
  7413. // 7.更新资产所属的类型根文件夹归属(文件夹属于 mp_products,随资产一并转让)
  7414. if (!empty($folderIds)) {
  7415. DB::table('mp_products')
  7416. ->whereIn('id', $folderIds)
  7417. ->update([
  7418. 'user_id' => $targetUserId,
  7419. 'updated_at' => $now,
  7420. ]);
  7421. }
  7422. // 8.校验剧本与资产是否全部更新成功,任一未成功则回滚
  7423. $scriptOwner = (int)DB::table('mp_scripts')->where('id', $scriptId)->value('user_id');
  7424. if ($scriptOwner !== $targetUserId) {
  7425. Utils::throwError('20003:剧本归属更新失败');
  7426. }
  7427. if (!empty($productIds)) {
  7428. $updatedProductCount = DB::table('mp_products')
  7429. ->whereIn('id', $productIds)
  7430. ->where('user_id', $targetUserId)
  7431. ->count();
  7432. if ($updatedProductCount !== count($productIds)) {
  7433. Utils::throwError('20003:部分剧本资产转让失败,已回滚');
  7434. }
  7435. }
  7436. if (!empty($folderIds)) {
  7437. $updatedFolderCount = DB::table('mp_products')
  7438. ->whereIn('id', $folderIds)
  7439. ->where('user_id', $targetUserId)
  7440. ->count();
  7441. if ($updatedFolderCount !== count($folderIds)) {
  7442. Utils::throwError('20003:部分资产文件夹转让失败,已回滚');
  7443. }
  7444. }
  7445. return [
  7446. 'script_id' => (int)$scriptId,
  7447. 'script_name' => (string)getProp($script, 'script_name', ''),
  7448. 'from_user_id' => $fromUserId,
  7449. 'to_user_id' => $targetUserId,
  7450. 'product_count' => count($productIds),
  7451. 'folder_count' => count($folderIds),
  7452. ];
  7453. }
  7454. /**
  7455. * 规范化ID列表,兼容数组、逗号分隔字符串以及字符串数组
  7456. *
  7457. * @param mixed $ids 待处理的ID集合
  7458. * @return array 去重后的正整数ID数组
  7459. */
  7460. private function normalizeIdList($ids) {
  7461. if (!is_array($ids)) {
  7462. $ids = explode(',', (string)$ids);
  7463. }
  7464. $result = [];
  7465. foreach ($ids as $item) {
  7466. if (is_array($item)) {
  7467. continue;
  7468. }
  7469. foreach (explode(',', (string)$item) as $part) {
  7470. $part = trim($part);
  7471. if ($part !== '' && is_numeric($part) && (int)$part > 0) {
  7472. $result[] = (int)$part;
  7473. }
  7474. }
  7475. }
  7476. return array_values(array_unique($result));
  7477. }
  7478. /**
  7479. * 通过 Excel 批量导入剧本资产(独立实现,不依赖 saveScriptProducts)
  7480. *
  7481. * 流程:
  7482. * 1. 校验剧本存在且属于当前用户
  7483. * 2. 解析 Excel 并校验强制列与数据完整性(资产类型/资产名称/使用范围/参考提示词)
  7484. * 3. 名称去重(与 Excel 内及该剧本已有关联资产比对)
  7485. * 4. 事务内创建类型文件夹、资产与剧本映射
  7486. * 5. 为没有图片的资产创建图片生成任务,生成中返回 SSE 轮询
  7487. *
  7488. * @param array $data 请求参数
  7489. * @param \Illuminate\Http\UploadedFile $file 上传的 Excel 文件
  7490. * @return array|\Generator
  7491. */
  7492. public function importScriptProductsByExcel($data, $file) {
  7493. $uid = Site::getUid();
  7494. $cpid = Site::getCpid();
  7495. $script_id = (int)getProp($data, 'script_id', 0);
  7496. if (!$script_id) {
  7497. Utils::throwError('20003:请提供剧本ID');
  7498. }
  7499. // 验证剧本是否存在,且只能导入自己创建的剧本
  7500. $script = DB::table('mp_scripts')
  7501. ->where('id', $script_id)
  7502. ->where('is_deleted', 0)
  7503. ->where('user_id', $uid)
  7504. ->first();
  7505. if (!$script) {
  7506. Utils::throwError('20003:剧本不存在或无权限操作');
  7507. }
  7508. $script_name = $script->script_name ?? 'script_' . $script_id;
  7509. // 校验上传文件
  7510. if (!$file) {
  7511. Utils::throwError('20003:请上传Excel文件');
  7512. }
  7513. $extension = strtolower($file->getClientOriginalExtension());
  7514. if (!in_array($extension, ['xlsx', 'xls'])) {
  7515. Utils::throwError('20003:文件格式错误,仅支持 xlsx、xls 格式');
  7516. }
  7517. if ($file->getSize() > 10 * 1024 * 1024) {
  7518. Utils::throwError('20003:文件大小不能超过10M');
  7519. }
  7520. // 解析 Excel(第一行为表头)
  7521. $rows = $this->readImportExcelRows($file);
  7522. if (empty($rows)) {
  7523. Utils::throwError('20003:Excel内容为空');
  7524. }
  7525. $headers = array_shift($rows);
  7526. // 定位强制列
  7527. $typeColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产类型'], ['资产类型', '类型']);
  7528. $nameColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产名称'], ['资产名称', '名称']);
  7529. $rangeColumnIndex = $this->findImportExcelColumnIndex($headers, ['使用范围'], ['使用范围', '范围']);
  7530. $promptColumnIndex = $this->findImportExcelColumnIndex($headers, ['参考提示词', '提示词'], ['提示词']);
  7531. $missingColumns = [];
  7532. if ($typeColumnIndex < 0) {
  7533. $missingColumns[] = '资产类型';
  7534. }
  7535. if ($nameColumnIndex < 0) {
  7536. $missingColumns[] = '资产名称';
  7537. }
  7538. if ($rangeColumnIndex < 0) {
  7539. $missingColumns[] = '使用范围';
  7540. }
  7541. if ($promptColumnIndex < 0) {
  7542. $missingColumns[] = '参考提示词';
  7543. }
  7544. if (!empty($missingColumns)) {
  7545. Utils::throwError('20003:Excel缺少必填列:' . implode('、', $missingColumns));
  7546. }
  7547. // 先整体校验 Excel 数据,所有异常行一次性返回
  7548. $validation = $this->validateImportExcelRows(
  7549. $rows,
  7550. $typeColumnIndex,
  7551. $nameColumnIndex,
  7552. $rangeColumnIndex,
  7553. $promptColumnIndex
  7554. );
  7555. $errors = $validation['errors'];
  7556. $checkedRows = $validation['checked_rows'];
  7557. if (empty($checkedRows)) {
  7558. $errors[] = 'Excel中没有有效的数据行';
  7559. }
  7560. if (!empty($errors)) {
  7561. Utils::throwError('20003:Excel数据校验失败:' . implode(';', $errors));
  7562. }
  7563. // 名称去重:Excel 内部 + 该剧本已关联资产(按 createProduct 的名称判断逻辑)
  7564. $existingNames = $this->getScriptProductNames($script_id, $cpid);
  7565. $dedupResult = $this->deduplicateImportRows($checkedRows, $existingNames);
  7566. $validRows = $dedupResult['valid_rows'];
  7567. $skipped = $dedupResult['skipped'];
  7568. // 图片生成参数(与 saveScriptProducts 保持一致的校验规则)
  7569. $model = getProp($data, 'model');
  7570. if (!$model) {
  7571. $model = 'gpt-image-2';
  7572. }
  7573. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7574. Utils::throwError('20003:该模型已不可用,请更换!');
  7575. }
  7576. $ratio = getProp($data, 'ratio', '9:16');
  7577. $resolution = strtolower(getProp($data, 'resolution', '2k'));
  7578. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7579. if (!isset($sizeMap[$resolution])) {
  7580. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7581. }
  7582. if (!isset($sizeMap[$resolution][$ratio])) {
  7583. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7584. }
  7585. $width = $sizeMap[$resolution][$ratio]['width'];
  7586. $height = $sizeMap[$resolution][$ratio]['height'];
  7587. $autoRaw = getProp($data, 'auto_generate_images', true);
  7588. $auto_generate_images = !in_array($autoRaw, [false, 0, '0', 'false', 'False'], true);
  7589. // 创建/复用任务中心记录(md5 验重,避免重复任务)
  7590. $taskCenterId = $this->createScriptProductTaskCenter(
  7591. $uid,
  7592. $cpid,
  7593. $script_id,
  7594. $validRows,
  7595. $model,
  7596. $ratio,
  7597. $resolution,
  7598. $auto_generate_images
  7599. );
  7600. // 全部为重复项:参照 saveScriptProducts,检查已存在资产的图片状态,缺图的补建任务
  7601. if (empty($validRows)) {
  7602. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7603. $script_id,
  7604. $model,
  7605. $width,
  7606. $height,
  7607. $auto_generate_images
  7608. );
  7609. $productTaskMap = $existingTaskInfo['product_task_map'];
  7610. $typeFolderIds = $existingTaskInfo['type_folder_ids'];
  7611. if (!empty($productTaskMap)) {
  7612. $message = 'Excel中的资产均已存在,正在为缺少图片的资产生成图片';
  7613. } elseif (!$existingTaskInfo['has_all_tasks']) {
  7614. $message = 'Excel中的资产均已存在,部分资产没有参考提示词,无法生成图片';
  7615. } else {
  7616. $message = 'Excel中的资产均已存在,且图片已全部生成完成';
  7617. }
  7618. $resultData = [
  7619. 'success' => true,
  7620. 'message' => $message,
  7621. 'script_id' => $script_id,
  7622. 'script_name' => $script_name,
  7623. 'imported_count' => 0,
  7624. 'existing_products' => $existingTaskInfo['product_count'],
  7625. 'skipped_count' => count($skipped),
  7626. 'skipped' => $skipped,
  7627. 'created_products' => [],
  7628. 'type_folder_ids' => $typeFolderIds,
  7629. 'pending_tasks_count' => count($productTaskMap),
  7630. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7631. 'task_center_id' => $taskCenterId,
  7632. ];
  7633. // 有需要轮询的任务(已有任务或本次补建):走 SSE 轮询
  7634. if (!empty($productTaskMap)) {
  7635. return $this->pollProductImageTasks(
  7636. $script_id,
  7637. $script_name,
  7638. $productTaskMap,
  7639. $typeFolderIds,
  7640. $taskCenterId,
  7641. ['import_result' => $resultData],
  7642. ['import_result' => $resultData]
  7643. );
  7644. }
  7645. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7646. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7647. }
  7648. // 事务内创建资产、类型文件夹与剧本映射
  7649. $typeFolderIds = [];
  7650. $createdProducts = [];
  7651. $mappingRecords = [];
  7652. $now = now();
  7653. DB::beginTransaction();
  7654. try {
  7655. foreach ($validRows as $row) {
  7656. $type = $row['type'];
  7657. if (!isset($typeFolderIds[$type])) {
  7658. // 与 createProduct 一致:先查找该剧本已存在的类型文件夹,没有则创建
  7659. $folder = DB::table('mp_products')
  7660. ->where('cpid', $cpid)
  7661. ->where('type', 2)
  7662. ->where('product', $type)
  7663. ->where('product_name', $script_name)
  7664. ->where('parent_id', 0)
  7665. ->where('is_deleted', 0)
  7666. ->first();
  7667. if ($folder) {
  7668. $typeFolderIds[$type] = $folder->id;
  7669. } else {
  7670. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7671. 'user_id' => $uid,
  7672. 'cpid' => $cpid,
  7673. 'type' => 2, // 文件夹
  7674. 'product' => $type, // 1=角色 2=场景 3=道具
  7675. 'parent_id' => 0,
  7676. 'level' => 1,
  7677. 'product_name' => $script_name,
  7678. 'sort_order' => time() + $type,
  7679. 'is_deleted' => 0,
  7680. 'created_at' => $now,
  7681. 'updated_at' => $now,
  7682. ]);
  7683. }
  7684. }
  7685. $folder_id = $typeFolderIds[$type];
  7686. $product_id = DB::table('mp_products')->insertGetId([
  7687. 'user_id' => $uid,
  7688. 'cpid' => $cpid,
  7689. 'type' => 1, // 资产
  7690. 'product' => $type,
  7691. 'parent_id' => $folder_id,
  7692. 'level' => 2,
  7693. 'product_name' => $row['product_name'],
  7694. 'pic_prompt' => $row['pic_prompt'],
  7695. 'sort_order' => time(),
  7696. 'is_deleted' => 0,
  7697. 'created_at' => $now,
  7698. 'updated_at' => $now,
  7699. ]);
  7700. $createdProducts[] = [
  7701. 'id' => $product_id,
  7702. 'type' => $type,
  7703. 'product_name' => $row['product_name'],
  7704. 'pic_prompt' => $row['pic_prompt'],
  7705. ];
  7706. // 为每个使用范围(集数)创建映射记录
  7707. foreach ($row['episode_numbers'] as $episodeNumber) {
  7708. $mappingRecords[] = [
  7709. 'script_id' => $script_id,
  7710. 'product_id' => $product_id,
  7711. 'episode_number' => $episodeNumber,
  7712. 'created_at' => $now,
  7713. 'updated_at' => $now,
  7714. ];
  7715. }
  7716. }
  7717. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7718. DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7719. // 剧本已有资产,同步更新is_products标记
  7720. DB::table('mp_scripts')->where('id', $script_id)->update([
  7721. 'is_products' => 1,
  7722. 'updated_at' => $now,
  7723. ]);
  7724. DB::commit();
  7725. } catch (\Exception $e) {
  7726. DB::rollback();
  7727. if ($taskCenterId) {
  7728. $this->taskCenterService->updateTask($taskCenterId, [
  7729. 'status' => MpTaskCenter::STATUS_FAILED,
  7730. 'error_message' => $e->getMessage(),
  7731. ]);
  7732. }
  7733. dLog('anime')->error('Excel导入剧本资产失败: ' . $e->getMessage(), [
  7734. 'script_id' => $script_id,
  7735. 'error' => $e->getMessage(),
  7736. 'trace' => $e->getTraceAsString(),
  7737. ]);
  7738. Utils::throwError('20003:Excel导入剧本资产失败:' . $e->getMessage());
  7739. }
  7740. // 参照 saveScriptProducts:为新建资产以及已存在但缺图的资产统一补建图片生成任务
  7741. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7742. $script_id,
  7743. $model,
  7744. $width,
  7745. $height,
  7746. $auto_generate_images
  7747. );
  7748. $productTaskMap = $existingTaskInfo['product_task_map'];
  7749. $resultData = [
  7750. 'success' => true,
  7751. 'message' => '导入完成',
  7752. 'script_id' => $script_id,
  7753. 'script_name' => $script_name,
  7754. 'imported_count' => count($createdProducts),
  7755. 'skipped_count' => count($skipped),
  7756. 'skipped' => $skipped,
  7757. 'created_products' => array_map(function ($item) {
  7758. return [
  7759. 'id' => $item['id'],
  7760. 'type' => $item['type'],
  7761. 'product_name' => $item['product_name'],
  7762. ];
  7763. }, $createdProducts),
  7764. 'type_folder_ids' => $typeFolderIds,
  7765. 'pending_tasks_count' => count($productTaskMap),
  7766. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7767. 'task_center_id' => $taskCenterId,
  7768. ];
  7769. // 有待生成的图片任务:返回 SSE 轮询结果(导入统计在 init 与 complete 事件中)
  7770. if (!empty($productTaskMap)) {
  7771. return $this->pollProductImageTasks(
  7772. $script_id,
  7773. $script_name,
  7774. $productTaskMap,
  7775. $typeFolderIds,
  7776. $taskCenterId,
  7777. ['import_result' => $resultData],
  7778. ['import_result' => $resultData]
  7779. );
  7780. }
  7781. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7782. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7783. }
  7784. /**
  7785. * 校验 Excel 数据行(先校验完毕,再进行后续逻辑)
  7786. *
  7787. * @param array $rows
  7788. * @param int $typeColumnIndex
  7789. * @param int $nameColumnIndex
  7790. * @param int $rangeColumnIndex
  7791. * @param int $promptColumnIndex
  7792. * @return array ['errors' => [], 'checked_rows' => []]
  7793. */
  7794. private function validateImportExcelRows(array $rows, $typeColumnIndex, $nameColumnIndex, $rangeColumnIndex, $promptColumnIndex) {
  7795. $errors = [];
  7796. $checkedRows = [];
  7797. foreach ($rows as $rowIndex => $row) {
  7798. // 数据从第2行开始(表头占第1行)
  7799. $excelRowNo = $rowIndex + 2;
  7800. if (!is_array($row) || $this->isImportExcelRowEmpty($row)) {
  7801. continue;
  7802. }
  7803. $typeRaw = trim((string)($row[$typeColumnIndex] ?? ''));
  7804. $nameRaw = trim((string)($row[$nameColumnIndex] ?? ''));
  7805. $rangeRaw = trim((string)($row[$rangeColumnIndex] ?? ''));
  7806. $promptRaw = trim((string)($row[$promptColumnIndex] ?? ''));
  7807. $missingFields = [];
  7808. if ($typeRaw === '') {
  7809. $missingFields[] = '资产类型';
  7810. }
  7811. if ($nameRaw === '') {
  7812. $missingFields[] = '资产名称';
  7813. }
  7814. if ($rangeRaw === '') {
  7815. $missingFields[] = '使用范围';
  7816. }
  7817. if ($promptRaw === '') {
  7818. $missingFields[] = '参考提示词';
  7819. }
  7820. if (!empty($missingFields)) {
  7821. $errors[] = "第{$excelRowNo}行:" . implode('、', $missingFields) . '不能为空';
  7822. continue;
  7823. }
  7824. // 资产类型校验
  7825. $productType = $this->resolveImportProductType($typeRaw);
  7826. if (!$productType) {
  7827. $errors[] = "第{$excelRowNo}行:资产类型「{$typeRaw}」不正确,仅支持 角色/场景/道具";
  7828. continue;
  7829. }
  7830. // 资产名称去除两边特殊符号
  7831. $productName = $this->normalizeImportProductName($nameRaw);
  7832. if ($productName === '') {
  7833. $errors[] = "第{$excelRowNo}行:资产名称「{$nameRaw}」去除特殊符号后为空";
  7834. continue;
  7835. }
  7836. if (mb_strlen($productName, 'UTF-8') > 64) {
  7837. $errors[] = "第{$excelRowNo}行:资产名称「{$productName}」超过64个字符";
  7838. continue;
  7839. }
  7840. // 解析使用范围(逗号分隔的集数)
  7841. $episodeNumbers = $this->parseImportEpisodeNumbers($rangeRaw);
  7842. if (empty($episodeNumbers)) {
  7843. $errors[] = "第{$excelRowNo}行:使用范围「{$rangeRaw}」格式错误,仅支持数字或逗号分隔的数字";
  7844. continue;
  7845. }
  7846. $checkedRows[] = [
  7847. 'row' => $excelRowNo,
  7848. 'type' => $productType,
  7849. 'product_name' => $productName,
  7850. 'episode_numbers' => $episodeNumbers,
  7851. 'pic_prompt' => $promptRaw,
  7852. ];
  7853. }
  7854. return [
  7855. 'errors' => $errors,
  7856. 'checked_rows' => $checkedRows,
  7857. ];
  7858. }
  7859. /**
  7860. * Excel 资产名称去重:Excel 内部 + 剧本已有关联资产
  7861. *
  7862. * @param array $checkedRows
  7863. * @param array $existingNames 剧本已有关联资产名称集合(name => true)
  7864. * @return array ['valid_rows' => [], 'skipped' => []]
  7865. */
  7866. private function deduplicateImportRows(array $checkedRows, array $existingNames) {
  7867. $seenNames = [];
  7868. $validRows = [];
  7869. $skipped = [];
  7870. foreach ($checkedRows as $row) {
  7871. $nameKey = $row['product_name'];
  7872. $typeText = $this->getImportProductTypeText($row['type']);
  7873. if (isset($seenNames[$nameKey])) {
  7874. $skipped[] = [
  7875. 'row' => $row['row'],
  7876. 'type' => $typeText,
  7877. 'product_name' => $row['product_name'],
  7878. 'reason' => 'Excel中资产名称重复',
  7879. ];
  7880. continue;
  7881. }
  7882. if (isset($existingNames[$nameKey])) {
  7883. $skipped[] = [
  7884. 'row' => $row['row'],
  7885. 'type' => $typeText,
  7886. 'product_name' => $row['product_name'],
  7887. 'reason' => '剧本中已存在同名资产',
  7888. ];
  7889. continue;
  7890. }
  7891. $seenNames[$nameKey] = true;
  7892. $validRows[] = $row;
  7893. }
  7894. return [
  7895. 'valid_rows' => $validRows,
  7896. 'skipped' => $skipped,
  7897. ];
  7898. }
  7899. /**
  7900. * 读取 Excel 文件为二维数组(第一行为表头)
  7901. *
  7902. * @param \Illuminate\Http\UploadedFile $file
  7903. * @return array
  7904. */
  7905. private function readImportExcelRows($file) {
  7906. try {
  7907. $reader = IOFactory::createReaderForFile($file->getRealPath());
  7908. $reader->setReadDataOnly(true);
  7909. $spreadsheet = $reader->load($file->getRealPath());
  7910. $sheet = $spreadsheet->getSheet(0);
  7911. $rows = $sheet->toArray(null, true, true, false);
  7912. $spreadsheet->disconnectWorksheets();
  7913. unset($spreadsheet);
  7914. return $rows;
  7915. } catch (\Exception $e) {
  7916. dLog('anime')->error('Excel文件解析失败', [
  7917. 'error' => $e->getMessage(),
  7918. ]);
  7919. Utils::throwError('20003:Excel文件解析失败,请确认文件格式正确');
  7920. }
  7921. }
  7922. /**
  7923. * 查找 Excel 表头列索引(先精确匹配,再模糊匹配)
  7924. *
  7925. * @param array $headers
  7926. * @param array $exactKeywords
  7927. * @param array $fuzzyKeywords
  7928. * @return int
  7929. */
  7930. private function findImportExcelColumnIndex(array $headers, array $exactKeywords, array $fuzzyKeywords) {
  7931. foreach ($headers as $index => $header) {
  7932. $header = trim((string)$header);
  7933. if ($header === '') {
  7934. continue;
  7935. }
  7936. foreach ($exactKeywords as $keyword) {
  7937. if ($header === $keyword) {
  7938. return $index;
  7939. }
  7940. }
  7941. }
  7942. foreach ($headers as $index => $header) {
  7943. $header = trim((string)$header);
  7944. if ($header === '') {
  7945. continue;
  7946. }
  7947. foreach ($fuzzyKeywords as $keyword) {
  7948. if (mb_strpos($header, $keyword) !== false) {
  7949. return $index;
  7950. }
  7951. }
  7952. }
  7953. return -1;
  7954. }
  7955. /**
  7956. * 判断 Excel 行是否为空行
  7957. *
  7958. * @param array $row
  7959. * @return bool
  7960. */
  7961. private function isImportExcelRowEmpty(array $row) {
  7962. foreach ($row as $cell) {
  7963. if (trim((string)$cell) !== '') {
  7964. return false;
  7965. }
  7966. }
  7967. return true;
  7968. }
  7969. /**
  7970. * 资产名称去除两边特殊符号(与 createProduct 保持一致)
  7971. *
  7972. * @param string $name
  7973. * @return string
  7974. */
  7975. private function normalizeImportProductName($name) {
  7976. $name = trim((string)$name);
  7977. $name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $name);
  7978. if (!$name || preg_match('/^[-—_]+$/u', $name)) {
  7979. return '';
  7980. }
  7981. return $name;
  7982. }
  7983. /**
  7984. * 解析 Excel 中的资产类型
  7985. *
  7986. * @param string $value
  7987. * @return int|null 1=角色 2=场景 3=道具
  7988. */
  7989. private function resolveImportProductType($value) {
  7990. $value = trim((string)$value);
  7991. $map = [
  7992. '角色' => 1,
  7993. '主体' => 1,
  7994. '人物' => 1,
  7995. '1' => 1,
  7996. '场景' => 2,
  7997. '2' => 2,
  7998. '道具' => 3,
  7999. '3' => 3,
  8000. ];
  8001. return isset($map[$value]) ? $map[$value] : null;
  8002. }
  8003. /**
  8004. * 资产类型文案
  8005. *
  8006. * @param int $type
  8007. * @return string
  8008. */
  8009. private function getImportProductTypeText($type) {
  8010. $map = [1 => '角色', 2 => '场景', 3 => '道具'];
  8011. return isset($map[$type]) ? $map[$type] : (string)$type;
  8012. }
  8013. /**
  8014. * 解析使用范围(逗号分隔的集数)
  8015. *
  8016. * @param string $value
  8017. * @return array
  8018. */
  8019. private function parseImportEpisodeNumbers($value) {
  8020. $parts = preg_split('/[,,、\s]+/u', trim((string)$value));
  8021. $episodeNumbers = [];
  8022. foreach ($parts as $part) {
  8023. if ($part === '') {
  8024. continue;
  8025. }
  8026. if (!is_numeric($part)) {
  8027. return [];
  8028. }
  8029. $episodeNumbers[] = (int)$part;
  8030. }
  8031. $episodeNumbers = array_values(array_unique($episodeNumbers));
  8032. sort($episodeNumbers);
  8033. return $episodeNumbers;
  8034. }
  8035. /**
  8036. * 获取剧本已关联资产名称集合(按 createProduct 的名称判断逻辑)
  8037. *
  8038. * @param int $script_id
  8039. * @param int $cpid
  8040. * @return array
  8041. */
  8042. private function getScriptProductNames($script_id, $cpid) {
  8043. $products = DB::table('mp_script_product_mappings as m')
  8044. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8045. ->where('m.script_id', $script_id)
  8046. ->where('p.cpid', $cpid)
  8047. ->where('p.type', 1)
  8048. ->where('p.is_deleted', 0)
  8049. ->get(['p.product_name']);
  8050. $names = [];
  8051. foreach ($products as $product) {
  8052. $name = $this->normalizeImportProductName($product->product_name);
  8053. if ($name !== '') {
  8054. $names[$name] = true;
  8055. }
  8056. }
  8057. return $names;
  8058. }
  8059. /**
  8060. * 获取剧本已关联的资产名称(仅按剧本判重,不区分资产类型)
  8061. *
  8062. * @param int $script_id
  8063. * @return array ['资产名称' => true]
  8064. */
  8065. private function getScriptAssetNames($script_id) {
  8066. $products = DB::table('mp_script_product_mappings as m')
  8067. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8068. ->where('m.script_id', $script_id)
  8069. ->where('p.type', 1)
  8070. ->where('p.is_deleted', 0)
  8071. ->get(['p.product_name']);
  8072. $names = [];
  8073. foreach ($products as $product) {
  8074. $name = $this->normalizeImportProductName($product->product_name);
  8075. if ($name !== '') {
  8076. $names[$name] = true;
  8077. }
  8078. }
  8079. return $names;
  8080. }
  8081. /**
  8082. * 校验并提取本次入参中的新增资产行
  8083. *
  8084. * 规则:
  8085. * - 资产名称为空(或仅剩占位符):跳过
  8086. * - 同一份入参内重名(跨类型):保留最后一条
  8087. * - 与剧本已关联资产同名(跨类型判重,仅限当前剧本):不算新增
  8088. * - 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8089. *
  8090. * @param int $script_id
  8091. * @param mixed $products 入参(数组或 JSON 字符串)
  8092. * @return array [['type' => int, 'product_name' => string, 'pic_prompt' => string, 'episode_numbers' => []]]
  8093. */
  8094. private function extractNewScriptProductRows($script_id, $products) {
  8095. // 兼容 JSON 字符串;无法解析时按"没有新增行"处理,由后续创建逻辑给出原有报错
  8096. if (is_string($products)) {
  8097. $decoded = json_decode($products, true);
  8098. $products = (json_last_error() === JSON_ERROR_NONE) ? $decoded : [];
  8099. }
  8100. if (!is_array($products) || empty($products)) {
  8101. return [];
  8102. }
  8103. $rowMap = [];
  8104. foreach ($products as $productGroup) {
  8105. $type = getProp($productGroup, 'type');
  8106. $content = getProp($productGroup, 'content', []);
  8107. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8108. continue;
  8109. }
  8110. // 获取表头(第一行)并查找关键列的位置
  8111. $headers = $content[0];
  8112. $nameColumnIndex = -1;
  8113. $sequenceColumnIndex = -1;
  8114. $promptColumnIndex = -1;
  8115. $fallbackPromptColumnIndex = -1;
  8116. foreach ($headers as $index => $header) {
  8117. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8118. $nameColumnIndex = $index;
  8119. }
  8120. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8121. $sequenceColumnIndex = $index;
  8122. }
  8123. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8124. $promptColumnIndex = $index;
  8125. } elseif (strpos($header, '提示词') !== false && $fallbackPromptColumnIndex === -1) {
  8126. // 与 Excel 导入保持一致:优先"参考提示词",否则兼容"提示词"列
  8127. $fallbackPromptColumnIndex = $index;
  8128. }
  8129. }
  8130. if ($promptColumnIndex === -1) {
  8131. $promptColumnIndex = $fallbackPromptColumnIndex;
  8132. }
  8133. if ($nameColumnIndex === -1) {
  8134. continue;
  8135. }
  8136. for ($i = 1; $i < count($content); $i++) {
  8137. $row = $content[$i];
  8138. if (empty($row) || !isset($row[$nameColumnIndex])) {
  8139. continue;
  8140. }
  8141. // 处理product_name两边的符号;名称为空或仅剩占位符号则跳过
  8142. $product_name = $this->normalizeImportProductName($row[$nameColumnIndex]);
  8143. if ($product_name === '') {
  8144. continue;
  8145. }
  8146. $pic_prompt = '';
  8147. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8148. $pic_prompt = trim((string)$row[$promptColumnIndex]);
  8149. }
  8150. // 解析使用范围(逗号分隔的序号),为空时由创建逻辑写入默认映射(序号0)
  8151. $sequences = [];
  8152. $sequence_str = ($sequenceColumnIndex >= 0 && isset($row[$sequenceColumnIndex]))
  8153. ? trim((string)$row[$sequenceColumnIndex])
  8154. : '';
  8155. if ($sequence_str !== '') {
  8156. foreach (array_map('trim', explode(',', $sequence_str)) as $part) {
  8157. if (is_numeric($part)) {
  8158. $sequences[] = (int)$part;
  8159. }
  8160. }
  8161. }
  8162. // 跨类型判重,同一份入参内重名保留最后一条
  8163. $rowMap[$product_name] = [
  8164. 'type' => (int)$type,
  8165. 'product_name' => $product_name,
  8166. 'pic_prompt' => $pic_prompt,
  8167. 'episode_numbers' => $sequences,
  8168. ];
  8169. }
  8170. }
  8171. // 与剧本已关联资产判重(仅限当前剧本,跨类型)
  8172. $existingNames = $this->getScriptAssetNames($script_id);
  8173. $newRows = [];
  8174. $emptyPromptNames = [];
  8175. foreach ($rowMap as $name => $row) {
  8176. if (isset($existingNames[$name])) {
  8177. continue;
  8178. }
  8179. if ($row['pic_prompt'] === '') {
  8180. $emptyPromptNames[] = $name;
  8181. continue;
  8182. }
  8183. $newRows[] = $row;
  8184. }
  8185. // 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8186. if (!empty($emptyPromptNames)) {
  8187. Utils::throwError('20003:以下新增资产的参考提示词不能为空:' . implode('、', $emptyPromptNames));
  8188. }
  8189. return $newRows;
  8190. }
  8191. /**
  8192. * 已有关联资产的图片任务处理(参照 saveScriptProducts 的处理方式)
  8193. *
  8194. * - 已有图片任务的资产:收集任务ID,交给轮询
  8195. * - 已有图片且生成成功的资产:跳过
  8196. * - 没有图片的资产:允许自动生成时补建图片任务(需要提示词)
  8197. *
  8198. * @param int $script_id
  8199. * @param string $model
  8200. * @param int $width
  8201. * @param int $height
  8202. * @param bool $auto_generate_images
  8203. * @return array ['product_task_map' => [], 'type_folder_ids' => [], 'has_all_tasks' => bool, 'product_count' => int, 'created_count' => int]
  8204. */
  8205. private function prepareExistingScriptProductTasks($script_id, $model, $width, $height, $auto_generate_images) {
  8206. $productTaskMap = [];
  8207. $typeFolderIds = [];
  8208. $hasAllTasks = true;
  8209. $createdCount = 0;
  8210. $existingMappings = DB::table('mp_script_product_mappings')
  8211. ->where('script_id', $script_id)
  8212. ->get();
  8213. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8214. $productsWithTasks = DB::table('mp_products')
  8215. ->whereIn('id', $productIds)
  8216. ->where('is_deleted', 0)
  8217. ->get();
  8218. foreach ($productsWithTasks as $product) {
  8219. // 收集类型文件夹ID
  8220. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8221. $parentFolder = DB::table('mp_products')
  8222. ->where('id', $product->parent_id)
  8223. ->where('type', 2)
  8224. ->first();
  8225. if ($parentFolder) {
  8226. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8227. }
  8228. }
  8229. // 检查是否有图片生成任务
  8230. if (!empty($product->pic_task_id)) {
  8231. $productTaskMap[$product->id] = $product->pic_task_id;
  8232. } elseif ($product->url && $product->pic_task_status == '生成成功') {
  8233. continue;
  8234. } else {
  8235. // 有资产没有图片
  8236. $hasAllTasks = false;
  8237. }
  8238. }
  8239. // 为没有图片的资产补建图片生成任务
  8240. if (!$hasAllTasks && $auto_generate_images && $productsWithTasks->isNotEmpty()) {
  8241. DB::beginTransaction();
  8242. try {
  8243. foreach ($productsWithTasks as $product) {
  8244. // 跳过已有任务的资产
  8245. if (!empty($product->pic_task_id)) {
  8246. continue;
  8247. }
  8248. // 跳过没有提示词的资产
  8249. if (empty($product->pic_prompt)) {
  8250. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8251. 'product_id' => $product->id,
  8252. 'product_name' => $product->product_name,
  8253. ]);
  8254. continue;
  8255. }
  8256. try {
  8257. $task = $this->aiImageGenerationService->createImageGenerationTask([
  8258. 'prompt' => $product->pic_prompt,
  8259. 'model' => $model,
  8260. 'ref_img_urls' => [],
  8261. 'width' => $width,
  8262. 'height' => $height,
  8263. ]);
  8264. $task_id = $task->id;
  8265. if ($task_id) {
  8266. $productTaskMap[$product->id] = $task_id;
  8267. $createdCount++;
  8268. DB::table('mp_products')
  8269. ->where('id', $product->id)
  8270. ->update([
  8271. 'pic_task_id' => $task_id,
  8272. 'pic_task_status' => '生成中',
  8273. 'updated_at' => now(),
  8274. ]);
  8275. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8276. 'product_id' => $product->id,
  8277. 'task_id' => $task_id,
  8278. ]);
  8279. }
  8280. } catch (\Exception $e) {
  8281. dLog('anime')->error('创建资产图片生成任务失败', [
  8282. 'product_id' => $product->id,
  8283. 'error' => $e->getMessage(),
  8284. ]);
  8285. DB::table('mp_products')
  8286. ->where('id', $product->id)
  8287. ->update([
  8288. 'pic_task_status' => '生成失败',
  8289. 'updated_at' => now(),
  8290. ]);
  8291. }
  8292. }
  8293. DB::commit();
  8294. } catch (\Exception $e) {
  8295. DB::rollback();
  8296. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8297. 'script_id' => $script_id,
  8298. 'error' => $e->getMessage(),
  8299. ]);
  8300. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8301. }
  8302. }
  8303. return [
  8304. 'product_task_map' => $productTaskMap,
  8305. 'type_folder_ids' => $typeFolderIds,
  8306. 'has_all_tasks' => $hasAllTasks,
  8307. 'product_count' => count($productIds),
  8308. 'created_count' => $createdCount,
  8309. ];
  8310. }
  8311. /**
  8312. * 保存剧本资产关联关系
  8313. * @param array $data 请求参数
  8314. * @return bool
  8315. */
  8316. public function saveScriptProducts($data) {
  8317. $uid = Site::getUid();
  8318. $cpid = Site::getCpid();
  8319. $script_id = getProp($data, 'script_id');
  8320. $products = getProp($data, 'products', []);
  8321. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  8322. if (!$script_id) {
  8323. Utils::throwError('20003:请提供剧本ID');
  8324. }
  8325. // 验证剧本是否存在
  8326. $script = DB::table('mp_scripts')
  8327. ->where('id', $script_id)
  8328. ->where('is_deleted', 0)
  8329. ->first();
  8330. if (!$script) {
  8331. Utils::throwError('20003:剧本不存在');
  8332. }
  8333. // 处理图片模型
  8334. $model = getProp($data, 'model');
  8335. if (!$model) {
  8336. // 使用默认模型
  8337. $model = 'gpt-image-2';
  8338. }
  8339. // 验证模型是否在可用模型表中
  8340. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8341. Utils::throwError('20003:该模型已不可用,请更换!');
  8342. }
  8343. $ratio = getProp($data, 'ratio', '9:16');
  8344. $resolution = getProp($data, 'resolution', '2k');
  8345. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  8346. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  8347. // 参数验证
  8348. $resolution = strtolower($resolution);
  8349. if (!isset($sizeMap[$resolution])) {
  8350. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  8351. }
  8352. if (!isset($sizeMap[$resolution][$ratio])) {
  8353. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  8354. }
  8355. // 根据 ratio 和 resolution 确定宽高
  8356. $width = $sizeMap[$resolution][$ratio]['width'];
  8357. $height = $sizeMap[$resolution][$ratio]['height'];
  8358. $script_name = $script->script_name ?? 'script_' . $script_id;
  8359. // 先校验并提取本次入参中的新增资产行:
  8360. // 新增行的参考提示词为空时直接报错,不写任何数据、不创建任务中心记录
  8361. $newRows = $this->extractNewScriptProductRows($script_id, $products);
  8362. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  8363. $taskCenterId = $this->createScriptProductTaskCenter(
  8364. $uid,
  8365. $cpid,
  8366. $script_id,
  8367. $products,
  8368. $model,
  8369. $ratio,
  8370. $resolution,
  8371. $auto_generate_images
  8372. );
  8373. // 检查是否已经有该剧本的资产数据
  8374. $existingMappings = DB::table('mp_script_product_mappings')
  8375. ->where('script_id', $script_id)
  8376. ->get();
  8377. // 已有资产且本次没有新增行时,走原有的"已存在"处理;否则走下方创建逻辑
  8378. if ($existingMappings->isNotEmpty() && empty($newRows)) {
  8379. // 已存在资产映射,检查是否所有资产都有图片生成任务
  8380. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8381. // 查询这些资产的图片生成任务状态
  8382. $productsWithTasks = DB::table('mp_products')
  8383. ->whereIn('id', $productIds)
  8384. ->where('is_deleted', 0)
  8385. ->get();
  8386. $productTaskMap = [];
  8387. $typeFolderIds = [];
  8388. $hasAllTasks = true;
  8389. foreach ($productsWithTasks as $product) {
  8390. // 收集类型文件夹ID
  8391. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8392. $parentFolder = DB::table('mp_products')
  8393. ->where('id', $product->parent_id)
  8394. ->where('type', 2)
  8395. ->first();
  8396. if ($parentFolder) {
  8397. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8398. }
  8399. }
  8400. // 检查是否有图片生成任务
  8401. if (!empty($product->pic_task_id)) {
  8402. $productTaskMap[$product->id] = $product->pic_task_id;
  8403. } else if($product->url && $product->pic_task_status == '生成成功') {
  8404. continue;
  8405. } else {
  8406. // 有资产没有图片任务
  8407. $hasAllTasks = false;
  8408. }
  8409. }
  8410. // 如果所有资产都有任务ID,直接轮询返回结果
  8411. if ($hasAllTasks && !empty($productTaskMap)) {
  8412. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  8413. 'script_id' => $script_id,
  8414. 'script_name' => $script_name,
  8415. 'product_count' => count($productTaskMap)
  8416. ]);
  8417. // 直接返回 SSE 流轮询结果
  8418. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8419. }
  8420. // 如果部分资产没有任务ID,只为这些资产创建任务
  8421. if (!$hasAllTasks && $auto_generate_images) {
  8422. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  8423. 'script_id' => $script_id,
  8424. 'script_name' => $script_name
  8425. ]);
  8426. // 开启事务
  8427. DB::beginTransaction();
  8428. try {
  8429. foreach ($productsWithTasks as $product) {
  8430. // 跳过已有任务的资产
  8431. if (!empty($product->pic_task_id)) {
  8432. continue;
  8433. }
  8434. // 跳过没有提示词的资产
  8435. if (empty($product->pic_prompt)) {
  8436. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8437. 'product_id' => $product->id,
  8438. 'product_name' => $product->product_name
  8439. ]);
  8440. continue;
  8441. }
  8442. try {
  8443. // 创建图片生成任务
  8444. $params = [
  8445. 'prompt' => $product->pic_prompt,
  8446. 'model' => $model,
  8447. 'ref_img_urls' => [],
  8448. 'width' => $width,
  8449. 'height' => $height
  8450. ];
  8451. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8452. $task_id = $task->id;
  8453. if ($task_id) {
  8454. $productTaskMap[$product->id] = $task_id;
  8455. // 在事务中更新资产表的任务ID和状态
  8456. DB::table('mp_products')
  8457. ->where('id', $product->id)
  8458. ->update([
  8459. 'pic_task_id' => $task_id,
  8460. 'pic_task_status' => '生成中',
  8461. 'updated_at' => now()
  8462. ]);
  8463. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8464. 'product_id' => $product->id,
  8465. 'task_id' => $task_id
  8466. ]);
  8467. }
  8468. } catch (\Exception $e) {
  8469. dLog('anime')->error('创建资产图片生成任务失败', [
  8470. 'product_id' => $product->id,
  8471. 'error' => $e->getMessage()
  8472. ]);
  8473. // 标记为失败(仍在事务中)
  8474. DB::table('mp_products')
  8475. ->where('id', $product->id)
  8476. ->update([
  8477. 'pic_task_status' => '生成失败',
  8478. 'updated_at' => now()
  8479. ]);
  8480. }
  8481. }
  8482. // 提交事务
  8483. DB::commit();
  8484. // 如果有新创建的任务,返回 SSE 流
  8485. if (!empty($productTaskMap)) {
  8486. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8487. }
  8488. } catch (\Exception $e) {
  8489. // 回滚事务
  8490. DB::rollback();
  8491. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8492. 'script_id' => $script_id,
  8493. 'error' => $e->getMessage()
  8494. ]);
  8495. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8496. }
  8497. }
  8498. // 如果不需要生成图片,返回已存在的信息
  8499. $resultData = [
  8500. 'success' => true,
  8501. 'message' => '剧本资产已存在',
  8502. 'script_id' => $script_id,
  8503. 'script_name' => $script_name,
  8504. 'type_folder_ids' => $typeFolderIds,
  8505. 'existing_products' => count($productIds),
  8506. 'tasks_count' => count($productTaskMap),
  8507. 'task_center_id' => $taskCenterId
  8508. ];
  8509. // 接口已正常完成,更新任务中心状态和结果
  8510. if ($taskCenterId) {
  8511. $this->taskCenterService->updateTask($taskCenterId, [
  8512. 'status' => MpTaskCenter::STATUS_SUCCESS,
  8513. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  8514. 'error_message' => null
  8515. ]);
  8516. }
  8517. return $resultData;
  8518. }
  8519. // 走到这里说明有新行需要创建(或剧本还没有任何资产),保留原有的入参校验报错
  8520. if (empty($newRows)) {
  8521. $decodedProducts = $products;
  8522. if (is_string($decodedProducts)) {
  8523. $decodedProducts = json_decode($decodedProducts, true);
  8524. if (json_last_error() !== JSON_ERROR_NONE) {
  8525. Utils::throwError('20003:产品数据格式错误');
  8526. }
  8527. }
  8528. if (!is_array($decodedProducts) || empty($decodedProducts)) {
  8529. Utils::throwError('20003:产品数据不能为空');
  8530. }
  8531. Utils::throwError('20003:没有有效的产品数据');
  8532. }
  8533. // 仅保留本次新增的资产行,复用下方原有的创建逻辑
  8534. $products = [];
  8535. foreach ($newRows as $newRow) {
  8536. if (!isset($products[$newRow['type']])) {
  8537. $products[$newRow['type']] = [
  8538. 'type' => $newRow['type'],
  8539. 'content' => [['资产名称', '使用范围', '参考提示词']],
  8540. ];
  8541. }
  8542. $products[$newRow['type']]['content'][] = [
  8543. $newRow['product_name'],
  8544. implode(',', $newRow['episode_numbers']),
  8545. $newRow['pic_prompt'],
  8546. ];
  8547. }
  8548. $products = array_values($products);
  8549. // 以下是原有的创建逻辑...
  8550. // 开启事务
  8551. DB::beginTransaction();
  8552. try {
  8553. $now = now();
  8554. $mappingRecords = [];
  8555. $createdProductIds = []; // 记录所有创建的资产ID
  8556. // 获取剧本名称
  8557. $script_name = $script->script_name ?? 'script_' . $script_id;
  8558. // 存储每个类型的根文件夹ID
  8559. $typeFolderIds = [];
  8560. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  8561. foreach ($products as $productGroup) {
  8562. $type = getProp($productGroup, 'type');
  8563. $title = getProp($productGroup, 'title', '');
  8564. $content = getProp($productGroup, 'content', []);
  8565. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8566. continue;
  8567. }
  8568. // 为当前类型获取根文件夹:该剧本已存在则复用,避免重复创建根文件夹
  8569. if (!isset($typeFolderIds[$type])) {
  8570. $folder = DB::table('mp_products')
  8571. ->where('cpid', $cpid)
  8572. ->where('type', 2)
  8573. ->where('product', $type)
  8574. ->where('product_name', $script_name)
  8575. ->where('parent_id', 0)
  8576. ->where('is_deleted', 0)
  8577. ->first();
  8578. if ($folder) {
  8579. $typeFolderIds[$type] = $folder->id;
  8580. } else {
  8581. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  8582. 'user_id' => $uid,
  8583. 'cpid' => $cpid,
  8584. 'type' => 2, // 1.资产 2文件夹
  8585. 'product' => $type, // 1.主体 2.场景 3.道具
  8586. 'parent_id' => 0, // 根文件夹,parent_id=0
  8587. 'level' => 1, // 第一层级
  8588. 'product_name' => $script_name,
  8589. 'sort_order' => time() + $type,
  8590. 'is_deleted' => 0,
  8591. 'created_at' => $now,
  8592. 'updated_at' => $now
  8593. ]);
  8594. }
  8595. }
  8596. $folder_id = $typeFolderIds[$type];
  8597. // 获取表头(第一行)并查找关键列的位置
  8598. $headers = $content[0];
  8599. $nameColumnIndex = -1; // 资产名称列索引
  8600. $sequenceColumnIndex = -1; // 使用范围列索引
  8601. $promptColumnIndex = -1; // 参考提示词列索引
  8602. foreach ($headers as $index => $header) {
  8603. // 查找"资产名称"列
  8604. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8605. $nameColumnIndex = $index;
  8606. }
  8607. // 查找"使用范围"列
  8608. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8609. $sequenceColumnIndex = $index;
  8610. }
  8611. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  8612. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8613. $promptColumnIndex = $index;
  8614. }
  8615. }
  8616. // 验证必要的列是否都找到了
  8617. if ($nameColumnIndex === -1) {
  8618. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  8619. continue;
  8620. }
  8621. if ($sequenceColumnIndex === -1) {
  8622. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  8623. continue;
  8624. }
  8625. // 跳过表头,解析每一行数据
  8626. for ($i = 1; $i < count($content); $i++) {
  8627. $row = $content[$i];
  8628. // 确保行数据有效
  8629. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  8630. continue;
  8631. }
  8632. // 根据动态查找的列索引提取数据
  8633. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  8634. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  8635. $pic_prompt = '';
  8636. // 提取参考提示词(如果找到了该列)
  8637. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8638. $pic_prompt = trim($row[$promptColumnIndex]);
  8639. }
  8640. // 解析使用范围(逗号分隔的序号)
  8641. $sequences = [];
  8642. if (!empty($sequence_str)) {
  8643. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  8644. foreach ($sequenceParts as $part) {
  8645. if (is_numeric($part)) {
  8646. $sequences[] = (int)$part;
  8647. }
  8648. }
  8649. }
  8650. if (empty($product_name)) {
  8651. continue;
  8652. }
  8653. // 处理product_name两边的符号
  8654. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8655. // 如果名称不存在或仅剩占位符号,则跳过
  8656. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  8657. dLog('anime')->warning('资产名称无效,跳过保存', [
  8658. 'script_id' => $script_id,
  8659. 'type' => $type,
  8660. 'product_name' => $product_name
  8661. ]);
  8662. continue;
  8663. }
  8664. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  8665. $product_id = DB::table('mp_products')->insertGetId([
  8666. 'product_name' => $product_name,
  8667. 'type' => 1, // 1=资产 2.文件夹
  8668. 'product' => $type, // 1=角色, 2=场景, 3=道具
  8669. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  8670. 'level' => 2, // 第二层级
  8671. 'pic_prompt' => $pic_prompt,
  8672. 'user_id' => $uid,
  8673. 'cpid' => $cpid,
  8674. 'sort_order' => time(),
  8675. 'is_deleted' => 0,
  8676. 'created_at' => $now,
  8677. 'updated_at' => $now,
  8678. ]);
  8679. // 记录创建的资产ID
  8680. $createdProductIds[] = $product_id;
  8681. // 为每个序号创建映射记录
  8682. if (!empty($sequences)) {
  8683. foreach ($sequences as $sequence) {
  8684. $mappingRecords[] = [
  8685. 'script_id' => $script_id,
  8686. 'product_id' => $product_id,
  8687. 'episode_number' => $sequence,
  8688. 'created_at' => $now,
  8689. 'updated_at' => $now,
  8690. ];
  8691. }
  8692. } else {
  8693. // 如果没有指定序号,创建一个默认映射(序号为0)
  8694. $mappingRecords[] = [
  8695. 'script_id' => $script_id,
  8696. 'product_id' => $product_id,
  8697. 'episode_number' => 0,
  8698. 'created_at' => $now,
  8699. 'updated_at' => $now,
  8700. ];
  8701. }
  8702. }
  8703. }
  8704. if (empty($mappingRecords)) {
  8705. Utils::throwError('20003:没有有效的产品数据');
  8706. }
  8707. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  8708. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  8709. // 剧本已有资产,同步更新is_products标记
  8710. DB::table('mp_scripts')->where('id', $script_id)->update([
  8711. 'is_products' => 1,
  8712. 'updated_at' => $now
  8713. ]);
  8714. // 如果需要自动生成图片,在事务中创建图片生成任务
  8715. $productTaskMap = [];
  8716. if ($auto_generate_images && !empty($createdProductIds)) {
  8717. // 查询所有创建的资产
  8718. $productsToGenerate = DB::table('mp_products')
  8719. ->whereIn('id', $createdProductIds)
  8720. ->where('is_deleted', 0)
  8721. ->get();
  8722. foreach ($productsToGenerate as $product) {
  8723. if (empty($product->pic_prompt)) {
  8724. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8725. 'product_id' => $product->id,
  8726. 'product_name' => $product->product_name
  8727. ]);
  8728. continue;
  8729. }
  8730. try {
  8731. // 创建图片生成任务
  8732. $params = [
  8733. 'prompt' => $product->pic_prompt,
  8734. 'model' => $model,
  8735. 'ref_img_urls' => [],
  8736. 'width' => $width,
  8737. 'height' => $height
  8738. ];
  8739. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8740. $task_id = $task->id;
  8741. if ($task_id) {
  8742. $productTaskMap[$product->id] = $task_id;
  8743. // 在事务中更新资产表的任务ID和状态
  8744. DB::table('mp_products')
  8745. ->where('id', $product->id)
  8746. ->update([
  8747. 'pic_task_id' => $task_id,
  8748. 'pic_task_status' => '生成中',
  8749. 'updated_at' => now()
  8750. ]);
  8751. dLog('anime')->info('创建资产图片生成任务', [
  8752. 'product_id' => $product->id,
  8753. 'task_id' => $task_id
  8754. ]);
  8755. }
  8756. } catch (\Exception $e) {
  8757. dLog('anime')->error('创建资产图片生成任务失败', [
  8758. 'product_id' => $product->id,
  8759. 'error' => $e->getMessage()
  8760. ]);
  8761. // 标记为失败(仍在事务中)
  8762. DB::table('mp_products')
  8763. ->where('id', $product->id)
  8764. ->update([
  8765. 'pic_task_status' => '生成失败',
  8766. 'updated_at' => now()
  8767. ]);
  8768. }
  8769. }
  8770. }
  8771. // 提交事务
  8772. DB::commit();
  8773. // 本次新增资产创建的图片任务
  8774. $createdTaskMap = $productTaskMap;
  8775. } catch (\Exception $e) {
  8776. // 回滚事务
  8777. DB::rollback();
  8778. // 更新任务中心状态为失败
  8779. if (!empty($taskCenterId)) {
  8780. $this->taskCenterService->updateTask($taskCenterId, [
  8781. 'status' => MpTaskCenter::STATUS_FAILED,
  8782. 'error_message' => $e->getMessage()
  8783. ]);
  8784. }
  8785. // 记录错误日志
  8786. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  8787. 'script_id' => $script_id,
  8788. 'error' => $e->getMessage(),
  8789. 'trace' => $e->getTraceAsString()
  8790. ]);
  8791. // 统一使用 Utils::throwError 抛出错误
  8792. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  8793. }
  8794. // 落库成功后统一处理图片任务:
  8795. // 1) 本次新增资产的图片任务已在上方事务中创建
  8796. // 2) 剧本内已存在但缺图的资产在此补建,并与新增资产的任务一并收集为待轮询任务
  8797. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  8798. $script_id,
  8799. $model,
  8800. $width,
  8801. $height,
  8802. $auto_generate_images
  8803. );
  8804. $productTaskMap = $existingTaskInfo['product_task_map'];
  8805. // 创建阶段解析到的类型根文件夹优先
  8806. $typeFolderIds = $typeFolderIds + $existingTaskInfo['type_folder_ids'];
  8807. // 保存结果(SSE 的 init / complete 事件会携带该结构)
  8808. $resultData = [
  8809. 'success' => true,
  8810. 'message' => '保存完成',
  8811. 'script_id' => $script_id,
  8812. 'script_name' => $script_name,
  8813. 'type_folder_ids' => $typeFolderIds,
  8814. 'inserted_count' => $insertedCount,
  8815. 'total_records' => count($mappingRecords),
  8816. 'created_products' => count($createdProductIds),
  8817. 'pending_tasks_count' => count($productTaskMap),
  8818. 'image_tasks_created' => count($createdTaskMap) + $existingTaskInfo['created_count'],
  8819. 'task_center_id' => $taskCenterId,
  8820. ];
  8821. // 有待完成的图片任务:返回 SSE 轮询流(事务外轮询)
  8822. if ($auto_generate_images && !empty($productTaskMap)) {
  8823. return $this->pollProductImageTasks(
  8824. $script_id,
  8825. $script_name,
  8826. $productTaskMap,
  8827. $typeFolderIds,
  8828. $taskCenterId,
  8829. ['import_result' => $resultData],
  8830. ['import_result' => $resultData]
  8831. );
  8832. }
  8833. // 没有需要轮询的任务:通过 SSE complete 事件返回保存结果
  8834. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  8835. }
  8836. /**
  8837. * 根据入参创建或复用任务中心记录
  8838. *
  8839. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  8840. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  8841. * 避免生成重复任务。
  8842. *
  8843. * @param int|string $uid
  8844. * @param int|string $cpid
  8845. * @param int|string $script_id
  8846. * @param mixed $products
  8847. * @param string $model
  8848. * @param string $ratio
  8849. * @param string $resolution
  8850. * @param mixed $auto_generate_images
  8851. * @return int 任务中心ID
  8852. */
  8853. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  8854. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  8855. if (is_string($products)) {
  8856. $decoded = json_decode($products, true);
  8857. if (json_last_error() === JSON_ERROR_NONE) {
  8858. $products = $decoded;
  8859. }
  8860. }
  8861. $params = [
  8862. 'script_id' => (int)$script_id,
  8863. 'products' => $products,
  8864. 'model' => $model,
  8865. 'ratio' => $ratio,
  8866. 'resolution' => $resolution,
  8867. 'auto_generate_images' => (bool)$auto_generate_images,
  8868. ];
  8869. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  8870. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  8871. $existing = DB::table('mp_task_center')
  8872. ->where('uid', (int)$uid)
  8873. ->where('cpid', (int)$cpid)
  8874. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8875. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  8876. ->where('params_md5', $paramsMd5)
  8877. ->orderBy('id', 'desc')
  8878. ->first();
  8879. if ($existing) {
  8880. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  8881. 'script_id' => $script_id,
  8882. 'task_center_id' => $existing->id,
  8883. 'params_md5' => $paramsMd5,
  8884. ]);
  8885. return (int)$existing->id;
  8886. }
  8887. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  8888. $now = date('Y-m-d H:i:s');
  8889. DB::table('mp_task_center')->insertOrIgnore([
  8890. 'uid' => (int)$uid,
  8891. 'cpid' => (int)$cpid,
  8892. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  8893. 'title' => '剧本资产图片生成',
  8894. 'ref_task_id' => 0,
  8895. 'status' => MpTaskCenter::STATUS_PROCESSING,
  8896. 'result' => null,
  8897. 'error_message' => null,
  8898. 'prompt' => null,
  8899. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  8900. 'params_md5' => $paramsMd5,
  8901. 'created_at' => $now,
  8902. 'updated_at' => $now,
  8903. ]);
  8904. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  8905. $taskId = (int)DB::table('mp_task_center')
  8906. ->where('uid', (int)$uid)
  8907. ->where('cpid', (int)$cpid)
  8908. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8909. ->where('params_md5', $paramsMd5)
  8910. ->orderBy('id', 'desc')
  8911. ->value('id');
  8912. dLog('anime')->info('创建任务中心记录', [
  8913. 'script_id' => $script_id,
  8914. 'task_center_id' => $taskId,
  8915. 'params_md5' => $paramsMd5,
  8916. ]);
  8917. return $taskId;
  8918. }
  8919. /**
  8920. * 任务结束时更新任务中心记录的状态和结果
  8921. *
  8922. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  8923. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  8924. *
  8925. * @param int|null $taskCenterId
  8926. * @param array $resultData 接口返回结果数组
  8927. * @param bool $timeout 是否超时未完成
  8928. */
  8929. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  8930. if (!$taskCenterId) {
  8931. return;
  8932. }
  8933. $stats = $resultData['stats'] ?? [];
  8934. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  8935. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  8936. $failedCount = $completedCount - $successCount;
  8937. // 与接口返回给客户端的结果保持一致
  8938. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  8939. if ($timeout) {
  8940. $this->taskCenterService->updateTask((int)$taskCenterId, [
  8941. 'status' => MpTaskCenter::STATUS_FAILED,
  8942. 'result' => $result,
  8943. 'error_message' => '部分任务超时,请稍后查看结果',
  8944. ]);
  8945. return;
  8946. }
  8947. $this->taskCenterService->updateTask((int)$taskCenterId, [
  8948. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  8949. 'result' => $result,
  8950. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  8951. ]);
  8952. }
  8953. /**
  8954. * 批量为剧本资产生成图片
  8955. *
  8956. * @param array $data 请求参数
  8957. * @return \Generator 返回 SSE 流
  8958. */
  8959. public function batchGenerateProductImages($data) {
  8960. $script_id = getProp($data, 'script_id');
  8961. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  8962. if (!$script_id) {
  8963. Utils::throwError('20003:请提供剧本ID');
  8964. }
  8965. // 验证剧本是否存在
  8966. $script = DB::table('mp_scripts')
  8967. ->where('id', $script_id)
  8968. ->where('is_deleted', 0)
  8969. ->first();
  8970. if (!$script) {
  8971. Utils::throwError('20003:剧本不存在');
  8972. }
  8973. $script_name = $script->script_name ?? 'script_' . $script_id;
  8974. // 获取需要生成图片的所有资产
  8975. $products = DB::table('mp_products')
  8976. ->whereIn('parent_id', array_values($type_folder_ids))
  8977. ->where('is_deleted', 0)
  8978. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  8979. ->get();
  8980. if ($products->isEmpty()) {
  8981. Utils::throwError('20003:没有找到需要生成图片的资产');
  8982. }
  8983. // 默认参数
  8984. $model = 'gpt-image-2';
  8985. $width = 1600;
  8986. $height = 2848;
  8987. // 开始为每个资产创建图片生成任务
  8988. $taskIds = [];
  8989. $productTaskMap = []; // 资产ID到任务ID的映射
  8990. foreach ($products as $product) {
  8991. if (empty($product->pic_prompt)) {
  8992. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  8993. continue;
  8994. }
  8995. try {
  8996. // 创建图片生成任务
  8997. $params = [
  8998. 'prompt' => $product->pic_prompt,
  8999. 'model' => $model,
  9000. 'ref_img_urls' => [],
  9001. 'width' => $width,
  9002. 'height' => $height
  9003. ];
  9004. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9005. $task_id = $task->id;
  9006. if ($task_id) {
  9007. $taskIds[] = $task_id;
  9008. $productTaskMap[$product->id] = $task_id;
  9009. // 更新资产表的任务ID和状态
  9010. DB::table('mp_products')
  9011. ->where('id', $product->id)
  9012. ->update([
  9013. 'pic_task_id' => $task_id,
  9014. 'pic_task_status' => '生成中',
  9015. 'updated_at' => now()
  9016. ]);
  9017. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  9018. }
  9019. } catch (\Exception $e) {
  9020. dLog('anime')->error('创建资产图片生成任务失败', [
  9021. 'product_id' => $product->id,
  9022. 'error' => $e->getMessage()
  9023. ]);
  9024. // 标记为失败
  9025. DB::table('mp_products')
  9026. ->where('id', $product->id)
  9027. ->update([
  9028. 'pic_task_status' => '生成失败',
  9029. 'updated_at' => now()
  9030. ]);
  9031. }
  9032. }
  9033. if (empty($taskIds)) {
  9034. Utils::throwError('20003:没有成功创建任何图片生成任务');
  9035. }
  9036. // 返回 SSE 流
  9037. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  9038. }
  9039. /**
  9040. * 无需轮询时的 SSE 返回:直接通过 complete 事件返回导入结果
  9041. *
  9042. * @param int $script_id
  9043. * @param string $script_name
  9044. * @param array $resultData 导入结果(原普通 JSON 的 data 内容)
  9045. * @param array $type_folder_ids
  9046. * @param int|null $taskCenterId
  9047. * @return \Generator
  9048. */
  9049. private function streamImportComplete($script_id, $script_name, array $resultData, $type_folder_ids, $taskCenterId = null) {
  9050. if ($taskCenterId) {
  9051. $initResponse = [
  9052. 'type' => 'init',
  9053. 'script_id' => $script_id,
  9054. 'script_name' => $script_name,
  9055. 'timestamp' => date('Y-m-d H:i:s'),
  9056. 'task_center_id' => (int)$taskCenterId,
  9057. 'import_result' => $resultData,
  9058. ];
  9059. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9060. }
  9061. $stats = $this->collectScriptProductStats($script_id);
  9062. $response = [
  9063. 'type' => 'complete',
  9064. 'script_id' => $script_id,
  9065. 'script_name' => $script_name,
  9066. 'stats' => $stats,
  9067. 'timestamp' => date('Y-m-d H:i:s'),
  9068. 'import_result' => $resultData,
  9069. ];
  9070. if ($taskCenterId) {
  9071. $response['task_center_id'] = (int)$taskCenterId;
  9072. }
  9073. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9074. // 更新任务中心状态和结果
  9075. $this->finishScriptProductTask($taskCenterId, $response);
  9076. }
  9077. /**
  9078. * 统计剧本资产的图片生成状态(仅按 mp_products 当前状态统计,不驱动任务)
  9079. *
  9080. * @param int $script_id
  9081. * @return array
  9082. */
  9083. private function collectScriptProductStats($script_id) {
  9084. $stats = [
  9085. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9086. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9087. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9088. ];
  9089. $typeNames = [1 => 'roles', 2 => 'scenes', 3 => 'props'];
  9090. $productIds = DB::table('mp_script_product_mappings')
  9091. ->where('script_id', $script_id)
  9092. ->pluck('product_id')
  9093. ->unique()
  9094. ->toArray();
  9095. if (empty($productIds)) {
  9096. return [];
  9097. }
  9098. $products = DB::table('mp_products')
  9099. ->whereIn('id', $productIds)
  9100. ->where('is_deleted', 0)
  9101. ->get();
  9102. foreach ($products as $product) {
  9103. $typeName = $typeNames[$product->product] ?? 'unknown';
  9104. if (!isset($stats[$typeName])) {
  9105. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9106. }
  9107. $stats[$typeName]['total']++;
  9108. if ($product->pic_task_status === '生成成功') {
  9109. $stats[$typeName]['success']++;
  9110. $stats[$typeName]['completed']++;
  9111. } elseif ($product->pic_task_status === '生成失败') {
  9112. $stats[$typeName]['completed']++;
  9113. }
  9114. }
  9115. foreach ($stats as $typeName => $stat) {
  9116. if ($stat['total'] === 0) {
  9117. unset($stats[$typeName]);
  9118. }
  9119. }
  9120. return $stats;
  9121. }
  9122. /**
  9123. * 轮询资产图片生成任务状态(SSE流式返回)
  9124. * 只通过查询数据库获取任务状态,不主动调用API
  9125. *
  9126. * @param int $script_id 剧本ID
  9127. * @param string $script_name 剧本名称
  9128. * @param array $productTaskMap 资产ID到任务ID的映射
  9129. * @param array $type_folder_ids 类型文件夹ID映射
  9130. * @param int|null $taskCenterId 任务中心ID
  9131. * @param array $initExtra 追加到 init 事件中的额外数据
  9132. * @param array $completeExtra 追加到 complete、timeout 事件中的额外数据
  9133. * @return \Generator
  9134. */
  9135. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null, array $initExtra = [], array $completeExtra = []) {
  9136. $startTime = time();
  9137. $timeout = 1800; // 30分钟超时
  9138. $pollInterval = 10; // 10秒轮询一次
  9139. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  9140. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  9141. if ($taskCenterId) {
  9142. $initResponse = array_merge([
  9143. 'type' => 'init',
  9144. 'script_id' => $script_id,
  9145. 'script_name' => $script_name,
  9146. 'timestamp' => date('Y-m-d H:i:s'),
  9147. 'task_center_id' => (int)$taskCenterId,
  9148. ], $initExtra);
  9149. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9150. }
  9151. // 定义类型名称映射
  9152. $typeNames = [
  9153. 1 => 'roles', // 角色
  9154. 2 => 'scenes', // 场景
  9155. 3 => 'props' // 道具
  9156. ];
  9157. while (time() - $startTime < $timeout) {
  9158. sleep($pollInterval);
  9159. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  9160. $mappings = DB::table('mp_script_product_mappings')
  9161. ->where('script_id', $script_id)
  9162. ->pluck('product_id')
  9163. ->unique()
  9164. ->toArray();
  9165. if (empty($mappings)) {
  9166. dLog('anime')->warning('该剧本没有关联的资产', [
  9167. 'script_id' => $script_id,
  9168. 'script_name' => $script_name
  9169. ]);
  9170. break;
  9171. }
  9172. // 查询所有资产的当前状态
  9173. $products = DB::table('mp_products')
  9174. ->whereIn('id', $mappings)
  9175. ->where('is_deleted', 0)
  9176. ->get();
  9177. // 统计各类型的状态(使用类型名称作为键名)
  9178. $stats = [
  9179. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  9180. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  9181. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  9182. ];
  9183. $allCompleted = true;
  9184. $hasStatusChange = false;
  9185. foreach ($products as $product) {
  9186. $type = $product->product;
  9187. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  9188. // 如果类型名称不在 stats 中,初始化
  9189. if (!isset($stats[$typeName])) {
  9190. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9191. }
  9192. $stats[$typeName]['total']++;
  9193. $task_id = $product->pic_task_id;
  9194. $currentStatus = $product->pic_task_status;
  9195. // 检查状态是否有变化
  9196. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  9197. $hasStatusChange = true;
  9198. $lastStatus[$product->id] = $currentStatus;
  9199. }
  9200. // 如果是生成中,查询任务表状态
  9201. if ($currentStatus === '生成中' && $task_id) {
  9202. // 只查询数据库,不调用API
  9203. $task = DB::table('mp_generate_pic_tasks')
  9204. ->where('id', $task_id)
  9205. ->first();
  9206. if ($task) {
  9207. // 检查任务状态
  9208. if ($task->status === 'success' && $task->result_url) {
  9209. // 解析图片URL
  9210. $result_urls = $task->result_url;
  9211. if (is_string($result_urls)) {
  9212. $result_urls = json_decode($result_urls, true);
  9213. }
  9214. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  9215. // 更新资产表状态
  9216. DB::table('mp_products')
  9217. ->where('id', $product->id)
  9218. ->update([
  9219. 'pic_task_status' => '生成成功',
  9220. 'url' => $img_url,
  9221. 'updated_at' => now()
  9222. ]);
  9223. $stats[$typeName]['success']++;
  9224. $stats[$typeName]['completed']++;
  9225. $hasStatusChange = true;
  9226. dLog('anime')->info('资产图片生成成功', [
  9227. 'product_id' => $product->id,
  9228. 'task_id' => $task_id,
  9229. 'img_url' => $img_url
  9230. ]);
  9231. } elseif ($task->status === 'failed') {
  9232. // 更新资产表状态
  9233. DB::table('mp_products')
  9234. ->where('id', $product->id)
  9235. ->update([
  9236. 'pic_task_status' => '生成失败',
  9237. 'updated_at' => now()
  9238. ]);
  9239. $stats[$typeName]['completed']++;
  9240. $hasStatusChange = true;
  9241. dLog('anime')->warning('资产图片生成失败', [
  9242. 'product_id' => $product->id,
  9243. 'task_id' => $task_id,
  9244. 'error' => $task->error_message ?? '未知错误'
  9245. ]);
  9246. } else {
  9247. // 任务还在处理中
  9248. $allCompleted = false;
  9249. }
  9250. } else {
  9251. // 任务不存在,标记为失败
  9252. DB::table('mp_products')
  9253. ->where('id', $product->id)
  9254. ->update([
  9255. 'pic_task_status' => '生成失败',
  9256. 'updated_at' => now()
  9257. ]);
  9258. $stats[$typeName]['completed']++;
  9259. $hasStatusChange = true;
  9260. dLog('anime')->error('图片生成任务不存在', [
  9261. 'product_id' => $product->id,
  9262. 'task_id' => $task_id
  9263. ]);
  9264. }
  9265. } elseif ($currentStatus === '生成成功') {
  9266. $stats[$typeName]['success']++;
  9267. $stats[$typeName]['completed']++;
  9268. } elseif ($currentStatus === '生成失败') {
  9269. $stats[$typeName]['completed']++;
  9270. } else {
  9271. // 其他状态也认为未完成
  9272. $allCompleted = false;
  9273. }
  9274. }
  9275. // 移除没有数据的类型(total=0)
  9276. foreach ($stats as $typeName => $stat) {
  9277. if ($stat['total'] === 0) {
  9278. unset($stats[$typeName]);
  9279. }
  9280. }
  9281. // 如果有状态变化,发送 SSE 更新
  9282. if ($hasStatusChange) {
  9283. $eventType = $allCompleted ? 'complete' : 'update';
  9284. $response = [
  9285. 'type' => $eventType,
  9286. 'script_id' => $script_id,
  9287. 'script_name' => $script_name,
  9288. 'stats' => $stats,
  9289. 'timestamp' => date('Y-m-d H:i:s')
  9290. ];
  9291. if ($taskCenterId) {
  9292. $response['task_center_id'] = $taskCenterId;
  9293. }
  9294. if ($eventType === 'complete') {
  9295. $response = array_merge($response, $completeExtra);
  9296. }
  9297. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9298. dLog('anime')->info('SSE更新', [
  9299. 'event_type' => $eventType,
  9300. 'script_id' => $script_id,
  9301. 'script_name' => $script_name,
  9302. 'stats' => $stats
  9303. ]);
  9304. if ($allCompleted) {
  9305. dLog('anime')->info('所有资产图片生成任务已完成', [
  9306. 'script_id' => $script_id,
  9307. 'script_name' => $script_name,
  9308. 'stats' => $stats
  9309. ]);
  9310. // 全部任务完成,更新任务中心状态和结果
  9311. $this->finishScriptProductTask($taskCenterId, $response);
  9312. break;
  9313. }
  9314. }
  9315. }
  9316. // 超时处理
  9317. if (time() - $startTime >= $timeout && !$allCompleted) {
  9318. $response = [
  9319. 'type' => 'timeout',
  9320. 'message' => '部分任务超时,请稍后查看结果',
  9321. 'script_id' => $script_id,
  9322. 'script_name' => $script_name,
  9323. 'timestamp' => date('Y-m-d H:i:s')
  9324. ];
  9325. if ($taskCenterId) {
  9326. $response['task_center_id'] = $taskCenterId;
  9327. }
  9328. $response = array_merge($response, $completeExtra);
  9329. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9330. dLog('anime')->warning('资产图片生成任务超时', [
  9331. 'script_id' => $script_id,
  9332. 'script_name' => $script_name,
  9333. 'timeout' => $timeout
  9334. ]);
  9335. // 超时未完成,更新任务中心状态和结果
  9336. $this->finishScriptProductTask($taskCenterId, $response, true);
  9337. }
  9338. }
  9339. /**
  9340. * 定时任务:检查产品图片生成任务状态并更新产品记录
  9341. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  9342. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  9343. *
  9344. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  9345. */
  9346. public function checkProductPicTasks() {
  9347. // 查询所有生成中的产品图片任务
  9348. $products = DB::table('mp_products')
  9349. ->whereNotNull('pic_task_id')
  9350. ->where('pic_task_status', '生成中')
  9351. ->where('is_deleted', 0)
  9352. ->get();
  9353. $stats = [
  9354. 'total' => $products->count(),
  9355. 'success' => 0,
  9356. 'failed' => 0,
  9357. 'pending' => 0,
  9358. ];
  9359. foreach ($products as $product) {
  9360. try {
  9361. $task_id = $product->pic_task_id;
  9362. // 通过 pic_task_id 查询图片生成任务结果
  9363. $task = DB::table('mp_generate_pic_tasks')
  9364. ->where('id', $task_id)
  9365. ->first();
  9366. if ($task) {
  9367. if ($task->status === 'success' && $task->result_url) {
  9368. // 解析图片URL
  9369. $result_urls = $task->result_url;
  9370. if (is_string($result_urls)) {
  9371. $result_urls = json_decode($result_urls, true);
  9372. }
  9373. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  9374. // 更新资产表状态
  9375. DB::table('mp_products')
  9376. ->where('id', $product->id)
  9377. ->update([
  9378. 'pic_task_status' => '生成成功',
  9379. 'url' => $img_url,
  9380. 'updated_at' => now()
  9381. ]);
  9382. $stats['success']++;
  9383. dLog('anime')->info('资产图片生成成功', [
  9384. 'product_id' => $product->id,
  9385. 'task_id' => $task_id,
  9386. 'img_url' => $img_url
  9387. ]);
  9388. } elseif ($task->status === 'failed') {
  9389. // 更新资产表状态
  9390. DB::table('mp_products')
  9391. ->where('id', $product->id)
  9392. ->update([
  9393. 'pic_task_status' => '生成失败',
  9394. 'updated_at' => now()
  9395. ]);
  9396. $stats['failed']++;
  9397. dLog('anime')->warning('资产图片生成失败', [
  9398. 'product_id' => $product->id,
  9399. 'task_id' => $task_id,
  9400. 'error' => $task->error_message ?? '未知错误'
  9401. ]);
  9402. } else {
  9403. // 任务还在处理中
  9404. $stats['pending']++;
  9405. }
  9406. } else {
  9407. // 任务不存在,标记为失败
  9408. DB::table('mp_products')
  9409. ->where('id', $product->id)
  9410. ->update([
  9411. 'pic_task_status' => '生成失败',
  9412. 'updated_at' => now()
  9413. ]);
  9414. $stats['failed']++;
  9415. dLog('anime')->error('图片生成任务不存在', [
  9416. 'product_id' => $product->id,
  9417. 'task_id' => $task_id
  9418. ]);
  9419. }
  9420. } catch (\Exception $e) {
  9421. dLog('anime')->error('检查产品图片生成任务异常', [
  9422. 'product_id' => $product->id,
  9423. 'task_id' => $product->pic_task_id ?? null,
  9424. 'error' => $e->getMessage()
  9425. ]);
  9426. }
  9427. }
  9428. return $stats;
  9429. }
  9430. /**
  9431. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  9432. *
  9433. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  9434. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  9435. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  9436. *
  9437. * @return int 更新的任务中心记录数
  9438. */
  9439. public function checkSaveScriptProductTaskCenters() {
  9440. $updated = 0;
  9441. // 只扫描尚未结束的 saveScriptProducts 任务
  9442. $tasks = DB::table('mp_task_center')
  9443. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9444. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  9445. ->orderBy('id', 'desc')
  9446. ->limit(500)
  9447. ->get();
  9448. // 与 pollProductImageTasks 保持一致的类型名称映射
  9449. $typeNames = [
  9450. 1 => 'roles', // 角色
  9451. 2 => 'scenes', // 场景
  9452. 3 => 'props', // 道具
  9453. ];
  9454. foreach ($tasks as $task) {
  9455. try {
  9456. $taskParams = json_decode((string)$task->params, true);
  9457. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  9458. if (!$script_id) {
  9459. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  9460. 'task_center_id' => $task->id,
  9461. ]);
  9462. continue;
  9463. }
  9464. // 获取该剧本关联的全部资产ID
  9465. $productIds = DB::table('mp_script_product_mappings')
  9466. ->where('script_id', $script_id)
  9467. ->pluck('product_id')
  9468. ->unique()
  9469. ->toArray();
  9470. if (empty($productIds)) {
  9471. // 剧本没有关联资产,不视为完成,等待下一次检查
  9472. continue;
  9473. }
  9474. $products = DB::table('mp_products')
  9475. ->whereIn('id', $productIds)
  9476. ->where('is_deleted', 0)
  9477. ->get();
  9478. $stats = [];
  9479. $allCompleted = true;
  9480. foreach ($products as $product) {
  9481. $typeName = $typeNames[$product->product] ?? 'unknown';
  9482. if (!isset($stats[$typeName])) {
  9483. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9484. }
  9485. $stats[$typeName]['total']++;
  9486. if ($product->pic_task_status === '生成成功') {
  9487. $stats[$typeName]['success']++;
  9488. $stats[$typeName]['completed']++;
  9489. } elseif ($product->pic_task_status === '生成失败') {
  9490. $stats[$typeName]['completed']++;
  9491. } else {
  9492. // 仍有资产在生成中或未生成,任务未完成
  9493. $allCompleted = false;
  9494. }
  9495. }
  9496. if (!$allCompleted) {
  9497. continue;
  9498. }
  9499. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  9500. $script = DB::table('mp_scripts')
  9501. ->where('id', $script_id)
  9502. ->where('is_deleted', 0)
  9503. ->first();
  9504. $script_name = $script->script_name ?? 'script_' . $script_id;
  9505. $this->finishScriptProductTask($task->id, [
  9506. 'type' => 'complete',
  9507. 'script_id' => $script_id,
  9508. 'script_name' => $script_name,
  9509. 'stats' => $stats,
  9510. 'timestamp' => date('Y-m-d H:i:s'),
  9511. 'task_center_id' => (int)$task->id,
  9512. ]);
  9513. $updated++;
  9514. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  9515. 'task_center_id' => $task->id,
  9516. 'script_id' => $script_id,
  9517. 'stats' => $stats,
  9518. ]);
  9519. } catch (\Exception $e) {
  9520. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  9521. 'task_center_id' => $task->id,
  9522. 'error' => $e->getMessage(),
  9523. ]);
  9524. }
  9525. }
  9526. return $updated;
  9527. }
  9528. /**
  9529. * 获取剧本关联的资产列表
  9530. * @param array $data 请求参数
  9531. * @return array
  9532. */
  9533. public function getScriptProducts($data) {
  9534. $uid = Site::getUid();
  9535. $cpid = Site::getCpid();
  9536. $script_id = getProp($data, 'script_id');
  9537. $episode_number = getProp($data, 'episode_number');
  9538. if (!$script_id) {
  9539. Utils::throwError('20003:请提供剧本ID');
  9540. }
  9541. // 验证剧本是否存在
  9542. $script = DB::table('mp_scripts')
  9543. ->where('id', $script_id)
  9544. ->where('is_deleted', 0)
  9545. ->first();
  9546. if (!$script) {
  9547. Utils::throwError('20003:剧本不存在');
  9548. }
  9549. // 联表查询资产信息
  9550. $query = DB::table('mp_script_product_mappings as mapping')
  9551. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9552. ->where('mapping.script_id', $script_id)
  9553. ->where('product.cpid', $cpid)
  9554. ->where('product.is_deleted', 0);
  9555. // 如果提供了 episode_number,则过滤指定集数
  9556. if ($episode_number !== null && $episode_number !== '') {
  9557. $query->where('mapping.episode_number', $episode_number);
  9558. }
  9559. $mappings = $query->select(
  9560. 'mapping.script_id',
  9561. 'mapping.product_id',
  9562. 'mapping.episode_number',
  9563. 'product.product_name',
  9564. 'product.type',
  9565. 'product.product',
  9566. 'product.pic_prompt',
  9567. 'product.url',
  9568. 'product.pic_task_id',
  9569. 'product.pic_task_status',
  9570. 'product.three_view_image_url',
  9571. 'product.timbre_url',
  9572. 'mapping.created_at'
  9573. )
  9574. ->orderBy('mapping.product_id', 'asc')
  9575. ->orderBy('mapping.episode_number', 'asc')
  9576. ->get();
  9577. // 按 product_id 分组,合并 episode_number
  9578. $productMap = [];
  9579. foreach ($mappings as $item) {
  9580. $product_id = $item->product_id;
  9581. if (!isset($productMap[$product_id])) {
  9582. $productMap[$product_id] = [
  9583. 'product_id' => $product_id,
  9584. 'product_name' => $item->product_name,
  9585. 'type' => (int)$item->type,
  9586. 'product' => (int)$item->product,
  9587. 'pic_prompt' => $item->pic_prompt,
  9588. 'url' => $item->url,
  9589. 'timbre_url' => $item->timbre_url,
  9590. 'pic_task_id' => $item->pic_task_id,
  9591. 'pic_task_status' => $item->pic_task_status,
  9592. 'episode_numbers' => [],
  9593. 'created_at' => $item->created_at,
  9594. ];
  9595. }
  9596. // 添加 episode_number(去重)
  9597. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  9598. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  9599. }
  9600. }
  9601. // 按类型分组
  9602. $roles = []; // type=1 角色/主体
  9603. $scenes = []; // type=2 场景
  9604. $props = []; // type=3 道具
  9605. foreach ($productMap as $product) {
  9606. // 将 episode_numbers 数组转换为逗号分隔的字符串
  9607. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  9608. // 构造返回数据
  9609. $productData = [
  9610. 'product_id' => $product['product_id'],
  9611. 'product_name' => $product['product_name'],
  9612. 'product' => $product['product'],
  9613. 'pic_prompt' => $product['pic_prompt'],
  9614. 'url' => $product['url'],
  9615. 'timbre_url' => $product['timbre_url'] ?? '',
  9616. 'pic_task_id' => $product['pic_task_id'],
  9617. 'pic_task_status' => $product['pic_task_status'],
  9618. 'episode_numbers' => $episodeNumbersStr,
  9619. 'created_at' => $product['created_at'],
  9620. ];
  9621. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  9622. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  9623. switch ($product['product']) {
  9624. case 1:
  9625. $roles[] = $productData;
  9626. break;
  9627. case 2:
  9628. $scenes[] = $productData;
  9629. break;
  9630. case 3:
  9631. $props[] = $productData;
  9632. break;
  9633. }
  9634. }
  9635. return [
  9636. 'script_id' => $script_id,
  9637. 'script_name' => $script->script_name ?? '',
  9638. 'roles' => $roles, // 主体
  9639. 'scenes' => $scenes, // 场景
  9640. 'props' => $props, // 道具
  9641. ];
  9642. }
  9643. /**
  9644. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  9645. * @param string $actContent 原始内容
  9646. * @param array $products 产品数组(包含product_name和url)
  9647. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  9648. */
  9649. public function processActContentWithProducts($actContent, $products) {
  9650. if (empty($actContent) || empty($products)) {
  9651. return [
  9652. 'content' => $actContent,
  9653. 'reference_images' => []
  9654. ];
  9655. }
  9656. // 构建产品名称到产品信息的映射
  9657. $product_dict = [];
  9658. foreach ($products as $product) {
  9659. $product_name = getProp($product, 'product_name');
  9660. if ($product_name) {
  9661. $product_dict[$product_name] = [
  9662. // 优先使用三视图图片作为素材/参考图,否则使用原图 url
  9663. 'url' => getProp($product, 'three_view_image_url') ?: getProp($product, 'url'),
  9664. 'voice_prompt' => getProp($product, 'voice_prompt')
  9665. ];
  9666. }
  9667. }
  9668. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  9669. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  9670. $reference_images = [];
  9671. $product_index_map = []; // 产品名称 => 图片序号的映射
  9672. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  9673. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  9674. $current_index = 1;
  9675. if (!empty($matches[1])) {
  9676. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  9677. $seen_products = []; // 用于去重
  9678. foreach ($matches[1] as $product_name) {
  9679. // 跳过已处理的产品
  9680. if (isset($seen_products[$product_name])) {
  9681. continue;
  9682. }
  9683. $seen_products[$product_name] = true;
  9684. // 检查产品是否在字典中
  9685. if (isset($product_dict[$product_name])) {
  9686. $url = $product_dict[$product_name]['url'];
  9687. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  9688. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  9689. if (!empty($voice_prompt) && $product_name !== '旁白') {
  9690. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  9691. }
  9692. // 只有URL非空才分配序号和添加到参考图片
  9693. if (!empty($url)) {
  9694. // 检查URL是否已经在reference_images中(去重)
  9695. if (!in_array($url, $reference_images)) {
  9696. $reference_images[] = $url;
  9697. $product_index_map[$product_name] = $current_index;
  9698. $current_index++;
  9699. } else {
  9700. // URL重复,找到已有的序号
  9701. $existing_index = array_search($url, $reference_images) + 1;
  9702. $product_index_map[$product_name] = $existing_index;
  9703. }
  9704. } else {
  9705. // URL为空,不分配序号(后续直接去掉{})
  9706. $product_index_map[$product_name] = 0;
  9707. }
  9708. } else {
  9709. // 产品不在字典中,不分配序号
  9710. $product_index_map[$product_name] = 0;
  9711. }
  9712. }
  9713. }
  9714. // 第二步:替换内容中的 {产品名称}
  9715. $processedContent = $actContent;
  9716. foreach ($product_index_map as $product_name => $index) {
  9717. $escaped_name = preg_quote($product_name, '/');
  9718. if ($index > 0) {
  9719. // 有图片,替换为:产品名称(图X)
  9720. $replacement = $product_name . '<图片' . $index . '>';
  9721. } else {
  9722. // 无图片,只保留产品名称
  9723. $replacement = $product_name;
  9724. }
  9725. // 替换所有 {产品名称} 为处理后的格式
  9726. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  9727. }
  9728. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  9729. foreach ($products as $product) {
  9730. $product_name = getProp($product, 'product_name');
  9731. $voice_prompt = getProp($product, 'voice_prompt');
  9732. if ($product_name === '旁白' && !empty($voice_prompt)) {
  9733. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  9734. break; // 找到旁白后退出循环
  9735. }
  9736. }
  9737. // 第四步:将voice_prompt信息添加到内容最前面
  9738. $voice_prompt_prefix = '';
  9739. if (!empty($voice_prompts)) {
  9740. $voice_prompt_prefix .= implode('', $voice_prompts);
  9741. }
  9742. // 旁白的voice_prompt放在最后
  9743. if (!empty($narrator_voice_prompt)) {
  9744. $voice_prompt_prefix .= $narrator_voice_prompt;
  9745. }
  9746. // 如果有voice_prompt信息,添加到内容开头
  9747. if (!empty($voice_prompt_prefix)) {
  9748. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  9749. }
  9750. return [
  9751. 'content' => $processedContent,
  9752. 'reference_images' => $reference_images
  9753. ];
  9754. }
  9755. public function saveActVideoGenerateParams($data) {
  9756. $episode_id = getProp($data, 'episode_id');
  9757. $model = getProp($data, 'video_model');
  9758. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  9759. if (!in_array($model, $valid_models)) {
  9760. Utils::throwError('20003:该模型不可用');
  9761. }
  9762. // 验证模型是否在可用模型表中
  9763. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9764. Utils::throwError('20003:该模型已不可用,请更换!');
  9765. }
  9766. $video_resolution = getProp($data, 'video_resolution', '720p');
  9767. $ratio = getProp($data, 'ratio');
  9768. if (!$ratio) $ratio = '9:16';
  9769. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  9770. if (!$episode) {
  9771. Utils::throwError('20003:分集不存在');
  9772. }
  9773. dLog('anime')->info('保存分集视频参数', $data);
  9774. try {
  9775. DB::beginTransaction();
  9776. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  9777. 'video_model' => $model,
  9778. 'video_resolution' => $video_resolution,
  9779. 'ratio' => $ratio,
  9780. 'updated_at' => date('Y-m-d H:i:s')
  9781. ]);
  9782. if ($result === false) {
  9783. Utils::throwError('20003:分集视频参数保存失败');
  9784. }
  9785. // 同步更新mp_animes表
  9786. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  9787. 'video_model' => $model,
  9788. 'video_resolution' => $video_resolution,
  9789. 'video_ratio' => $ratio,
  9790. 'updated_at' => date('Y-m-d H:i:s')
  9791. ]);
  9792. if ($anime_result === false) {
  9793. Utils::throwError('20003:动漫视频参数保存失败');
  9794. }
  9795. } catch (\Exception $e) {
  9796. DB::rollBack();
  9797. Utils::throwError('20003:'.$e->getMessage());
  9798. }
  9799. DB::commit();
  9800. return $result;
  9801. }
  9802. public function confirmActs($data) {
  9803. $episode_id = getProp($data, 'episode_id');
  9804. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  9805. if (!$episode) {
  9806. Utils::throwError('20003:分集不存在');
  9807. }
  9808. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9809. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9810. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  9811. // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
  9812. $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
  9813. // 获取所有片段数据
  9814. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  9815. // 先构建完整的 products(角色、场景、道具、extra_products,并用资产库映射覆盖),
  9816. // 再处理每个片段的 act_content,避免 extra_products 等资产名未被格式化为 {资产名}
  9817. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  9818. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  9819. $products = [];
  9820. // 先处理角色数组
  9821. foreach ($roles as $role) {
  9822. $product = $role;
  9823. // 将role字段重命名为product_name
  9824. if (isset($product['role'])) {
  9825. $product['product_name'] = $product['role'];
  9826. unset($product['role']);
  9827. $product['product'] = 1; // 标记类型为角色
  9828. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9829. }
  9830. }
  9831. // 处理场景数组
  9832. foreach ($scenes as $scene) {
  9833. $product = $scene;
  9834. // 将scene字段重命名为product_name
  9835. if (isset($product['scene'])) {
  9836. $product['product_name'] = $product['scene'];
  9837. unset($product['scene']);
  9838. $product['product'] = 2; // 标记类型为场景
  9839. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9840. }
  9841. }
  9842. // 处理道具数组(逻辑与场景一致)
  9843. foreach ($props as $prop) {
  9844. $product = $prop;
  9845. // 将prop字段重命名为product_name
  9846. if (isset($product['prop'])) {
  9847. $product['product_name'] = $product['prop'];
  9848. unset($product['prop']);
  9849. $product['product'] = 3; // 标记类型为道具
  9850. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9851. }
  9852. }
  9853. // extra_products优先级更高,直接覆盖同名的roles和scenes
  9854. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  9855. foreach ($extra_products as $extra_product) {
  9856. $product_name = getProp($extra_product, 'product_name');
  9857. if ($product_name) {
  9858. $products[$product_name] = $extra_product; // 覆盖同名数据
  9859. }
  9860. }
  9861. // mp_script_product_mappings 信息优先级更高:
  9862. // 获取当前剧集所属动漫剧本下、与本集资产同名的资产库最新数据(url/三视图/提示词等),
  9863. // 覆盖分集 JSON 中保存的同名旧快照;分集内独有的 description、voice_prompt 等字段保留
  9864. $anime = DB::table('mp_animes')->where('id', getProp($episode, 'anime_id'))->first();
  9865. $script_id = $anime ? (int)getProp($anime, 'script_id', 0) : 0;
  9866. if ($script_id && !empty($products)) {
  9867. $currentProductNames = array_keys($products);
  9868. $normalizeName = function($name) {
  9869. return trim(preg_replace(
  9870. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  9871. '',
  9872. trim((string)$name)
  9873. ));
  9874. };
  9875. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  9876. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9877. ->where('mapping.script_id', $script_id)
  9878. ->where('product.is_deleted', 0)
  9879. ->whereIn('product.product_name', $currentProductNames)
  9880. ->select(
  9881. 'mapping.product_id',
  9882. 'product.product_name',
  9883. 'product.product',
  9884. 'product.pic_prompt',
  9885. 'product.url',
  9886. 'product.three_view_image_url',
  9887. )
  9888. ->get();
  9889. $mappingByName = [];
  9890. foreach ($mappingItems as $mappingItem) {
  9891. $normalizedName = $normalizeName($mappingItem->product_name);
  9892. if (!$normalizedName) continue;
  9893. $mappingByName[$normalizedName] = [
  9894. 'product_id' => (int)$mappingItem->product_id,
  9895. 'product_name' => $mappingItem->product_name,
  9896. 'product' => (int)$mappingItem->product,
  9897. 'pic_prompt' => $mappingItem->pic_prompt ?? '',
  9898. 'url' => $mappingItem->url ?? '',
  9899. 'three_view_image_url' => $mappingItem->three_view_image_url ?? '',
  9900. ];
  9901. }
  9902. foreach ($products as $key => &$product) {
  9903. $normalizedKey = $normalizeName($key);
  9904. if ($normalizedKey && isset($mappingByName[$normalizedKey])) {
  9905. $product = array_merge($product, $mappingByName[$normalizedKey]);
  9906. }
  9907. }
  9908. unset($product);
  9909. }
  9910. // 兼容返回 three_view_image_url 字段(旧数据可能没有该键,统一补空值)
  9911. foreach ($products as &$product) {
  9912. if (!isset($product['three_view_image_url'])) {
  9913. $product['three_view_image_url'] = '';
  9914. }
  9915. }
  9916. unset($product);
  9917. // 重新索引数组(去除key)
  9918. $products = array_values($products);
  9919. // 基于构建完成的 products 收集所有资产名称(含 extra_products 中的资产)
  9920. $product_names = [];
  9921. foreach ($products as $product) {
  9922. $product_name = getProp($product, 'product_name');
  9923. if ($product_name && $product_name !== '旁白') {
  9924. $product_names[] = $product_name;
  9925. }
  9926. }
  9927. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  9928. $product_names = array_unique($product_names);
  9929. usort($product_names, function($a, $b) {
  9930. return mb_strlen($b) - mb_strlen($a);
  9931. });
  9932. try {
  9933. DB::beginTransaction();
  9934. // 处理每个片段
  9935. foreach ($acts as $act) {
  9936. $act_content = getProp($act, 'act_content');
  9937. if (!$act_content) continue;
  9938. $processed_content = $act_content;
  9939. // 统一替换所有资产名称为 {资产名} 格式
  9940. // 使用占位符避免嵌套替换问题
  9941. $placeholder_map = [];
  9942. $placeholder_index = 0;
  9943. foreach ($product_names as $product_name) {
  9944. // 转义特殊字符
  9945. $escaped_product = preg_quote($product_name, '/');
  9946. // 检查是否匹配且未被 {} 包裹
  9947. $processed_content = preg_replace_callback(
  9948. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  9949. function($matches) use (&$placeholder_map, &$placeholder_index) {
  9950. // 使用唯一占位符
  9951. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  9952. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  9953. $placeholder_index++;
  9954. return $placeholder;
  9955. },
  9956. $processed_content
  9957. );
  9958. }
  9959. // 将所有占位符替换回实际内容
  9960. foreach ($placeholder_map as $placeholder => $replacement) {
  9961. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  9962. }
  9963. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  9964. $shot_counter = 0;
  9965. $processed_content = preg_replace_callback(
  9966. '/【(?:镜头|分镜)(\d+)】/u',
  9967. function($matches) use (&$shot_counter) {
  9968. $shot_counter++;
  9969. return '【镜头' . $shot_counter . '】';
  9970. },
  9971. $processed_content
  9972. );
  9973. // 更新数据库
  9974. $boolen = DB::table('mp_episode_segments')
  9975. ->where('id', $act->id)
  9976. ->update([
  9977. 'act_show_content' => $processed_content,
  9978. 'updated_at' => date('Y-m-d H:i:s')
  9979. ]);
  9980. if (!$boolen) {
  9981. Utils::throwError('20003:片段处理失败');
  9982. }
  9983. }
  9984. }catch (\Exception $e) {
  9985. DB::rollBack();
  9986. Utils::throwError('20003:'.$e->getMessage());
  9987. }
  9988. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  9989. 'is_generated' => 1,
  9990. 'updated_at' => date('Y-m-d H:i:s')
  9991. ]);
  9992. if (!$boolen1) {
  9993. DB::rollBack();
  9994. Utils::throwError('20003:分集处理失败!');
  9995. }
  9996. DB::commit();
  9997. // 重新查询更新后的片段数据
  9998. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  9999. // 构建返回的acts数组
  10000. $return_acts = [];
  10001. foreach ($acts as $act) {
  10002. $return_acts[] = [
  10003. 'act_id' => getProp($act, 'id'),
  10004. 'act_number' => getProp($act, 'act_number'),
  10005. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  10006. 'act_show_content' => getProp($act, 'act_show_content'),
  10007. 'video_url' => getProp($act, 'video_url'),
  10008. 'video_duration' => getProp($act, 'video_duration'),
  10009. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  10010. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  10011. ];
  10012. }
  10013. return [
  10014. 'anime_id' => getProp($episode, 'anime_id'),
  10015. 'episode_id' => $episode_id,
  10016. 'title' => getProp($episode, 'title'),
  10017. 'episode_number' => getProp($episode, 'episode_number'),
  10018. 'is_generated' => getProp($episode, 'is_generated'),
  10019. 'video_params' => [
  10020. 'video_model' => getProp($episode, 'video_model'),
  10021. 'video_resolution' => getProp($episode, 'video_resolution'),
  10022. 'ratio' => getProp($episode, 'ratio'),
  10023. ],
  10024. 'products' => $products,
  10025. 'acts' => $return_acts
  10026. ];
  10027. }
  10028. /**
  10029. * 参照 episodePicsInfo 的更新与监控逻辑:
  10030. * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
  10031. * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
  10032. */
  10033. private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
  10034. $pollInterval = 5; // 每5秒查询一次
  10035. $maxWaitSeconds = 60; // 最多持续1分钟
  10036. $startTime = time();
  10037. while (true) {
  10038. // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
  10039. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  10040. if (!$episode) {
  10041. Utils::throwError('20003:分集不存在');
  10042. }
  10043. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10044. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10045. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  10046. $updated = false;
  10047. $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
  10048. $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
  10049. $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
  10050. $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
  10051. $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
  10052. // 有图片任务结果更新时写回分集表
  10053. if ($updated) {
  10054. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10055. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  10056. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  10057. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  10058. 'updated_at' => date('Y-m-d H:i:s')
  10059. ]);
  10060. }
  10061. // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
  10062. if (empty($waitingAssets) && empty($missingAssets)) {
  10063. return;
  10064. }
  10065. // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
  10066. if (empty($waitingAssets)) {
  10067. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10068. }
  10069. // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
  10070. if (time() - $startTime >= $maxWaitSeconds) {
  10071. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10072. }
  10073. sleep($pollInterval);
  10074. }
  10075. }
  10076. /**
  10077. * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
  10078. * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
  10079. * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
  10080. */
  10081. private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
  10082. foreach ($assets as &$asset) {
  10083. $assetName = getProp($asset, $nameKey);
  10084. if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
  10085. continue;
  10086. }
  10087. // 已有图片URL的资产视为已生成
  10088. if (getProp($asset, 'url')) {
  10089. continue;
  10090. }
  10091. $task_id = getProp($asset, 'task_id');
  10092. // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
  10093. if (!$task_id) {
  10094. $missingAssets[] = $assetName;
  10095. continue;
  10096. }
  10097. $task = DB::table('mp_generate_pic_tasks')
  10098. ->where('id', $task_id)
  10099. ->select('status', 'result_url')
  10100. ->first();
  10101. // 任务不存在:同样记录为缺失项,不在此处直接报错
  10102. if (!$task) {
  10103. $missingAssets[] = $assetName;
  10104. continue;
  10105. }
  10106. if ($task->status === 'success') {
  10107. $result_url = getProp($task, 'result_url');
  10108. if ($result_url) {
  10109. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  10110. if (is_array($result_urls) && !empty($result_urls[0])) {
  10111. $asset['url'] = $result_urls[0];
  10112. $asset['task_status'] = 'success';
  10113. $updated = true;
  10114. continue;
  10115. }
  10116. }
  10117. // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
  10118. $waitingAssets[] = $assetName;
  10119. } elseif ($task->status === 'failed') {
  10120. // 生成失败:记录为缺失项,待其他任务处理完后统一报错
  10121. $missingAssets[] = $assetName;
  10122. } else {
  10123. // 任务仍在生成中,等待下一次轮询
  10124. $waitingAssets[] = $assetName;
  10125. }
  10126. }
  10127. unset($asset);
  10128. }
  10129. /**
  10130. * 导出动漫剧本为PDF(参照示例PDF版式)
  10131. * @param int $animeId 动漫ID
  10132. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  10133. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  10134. * @return string|null
  10135. */
  10136. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  10137. // 图片下载与转换可能占用较多内存
  10138. ini_set('memory_limit', '512M');
  10139. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  10140. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  10141. $anime = (array)$anime;
  10142. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  10143. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  10144. // 获取分集(默认展示版本,按集数升序)
  10145. $episodeQuery = DB::table('mp_anime_episodes')
  10146. ->where('anime_id', $animeId)
  10147. ->where('is_default', 1)
  10148. ->orderBy('episode_number')
  10149. ->orderBy('id');
  10150. if ($episodeCount > 0) {
  10151. $episodeQuery->limit($episodeCount);
  10152. }
  10153. $episodes = $episodeQuery->get()->map(function ($value) {
  10154. return (array)$value;
  10155. })->toArray();
  10156. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  10157. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  10158. $roles = $this->mergeEpisodeItems($episodes, 'role');
  10159. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  10160. $props = $this->mergeEpisodeItems($episodes, 'prop');
  10161. // 组装分集剧本数据
  10162. $episodeScripts = [];
  10163. foreach ($episodes as $episode) {
  10164. $segments = DB::table('mp_episode_segments')
  10165. ->where('anime_id', $animeId)
  10166. ->where('episode_id', $episode['id'])
  10167. ->get();
  10168. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  10169. $acts = [];
  10170. foreach ($segments as $segment) {
  10171. $segment = (array)$segment;
  10172. $actNumber = (int)getProp($segment, 'act_number', 0);
  10173. if ($actNumber <= 0) continue;
  10174. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  10175. $acts[$actNumber] = [
  10176. 'id' => (int)$segment['id'],
  10177. 'act_number' => $actNumber,
  10178. 'duration' => getProp($segment, 'act_duration', ''),
  10179. 'content' => getProp($segment, 'act_content', ''),
  10180. ];
  10181. }
  10182. }
  10183. ksort($acts);
  10184. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  10185. $segmentCounter = 0;
  10186. foreach ($acts as &$act) {
  10187. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  10188. }
  10189. unset($act);
  10190. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  10191. $narratorVoice = '';
  10192. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  10193. foreach ($episodeRoles as $role) {
  10194. if (getProp($role, 'role') === '旁白') {
  10195. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  10196. break;
  10197. }
  10198. }
  10199. if ($narratorVoice === '') {
  10200. foreach ($acts as $act) {
  10201. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  10202. $narratorVoice = trim($match[1]);
  10203. break;
  10204. }
  10205. }
  10206. }
  10207. $episodeScripts[] = [
  10208. 'episode_number' => getProp($episode, 'episode_number'),
  10209. 'title' => getProp($episode, 'title', ''),
  10210. 'act_count' => count($acts),
  10211. 'narrator_voice' => $narratorVoice,
  10212. 'acts' => array_values($acts),
  10213. ];
  10214. }
  10215. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  10216. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  10217. // 构建PDF
  10218. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  10219. // 图片已嵌入PDF,清理临时文件
  10220. foreach ($imageCache as $imgFile) {
  10221. @unlink($imgFile);
  10222. }
  10223. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  10224. if ($savePath) {
  10225. $pdf->Output($savePath, 'F');
  10226. return $savePath;
  10227. }
  10228. // 直接下载输出
  10229. header('Content-Type: application/pdf');
  10230. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  10231. $pdf->Output($filename . '.pdf', 'D');
  10232. exit();
  10233. }
  10234. /**
  10235. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  10236. * @param array $episodes 分集数据
  10237. * @param string $nameKey role|scene|prop
  10238. * @return array
  10239. */
  10240. private function mergeEpisodeItems(array $episodes, $nameKey) {
  10241. $fieldMap = [
  10242. 'role' => 'roles',
  10243. 'scene' => 'scenes',
  10244. 'prop' => 'props',
  10245. ];
  10246. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  10247. $items = [];
  10248. foreach ($episodes as $episode) {
  10249. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  10250. foreach ($list as $item) {
  10251. if (!is_array($item)) continue;
  10252. $name = trim((string)getProp($item, $nameKey, ''));
  10253. if ($name === '') continue;
  10254. // 旁白不进入主体列表(仅作为旁白音色来源)
  10255. if ($nameKey === 'role' && $name === '旁白') continue;
  10256. if (!isset($items[$name])) {
  10257. $items[$name] = $item;
  10258. }
  10259. }
  10260. }
  10261. return array_values($items);
  10262. }
  10263. /**
  10264. * 构建动漫剧本PDF
  10265. * @param array $anime 动漫信息
  10266. * @param array $roles 主体列表
  10267. * @param array $scenes 场景列表
  10268. * @param array $props 道具列表
  10269. * @param array $episodeScripts 分集剧本数据
  10270. * @param array $imageCache 图片缓存(url => 临时文件路径)
  10271. * @return \TCPDF
  10272. */
  10273. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  10274. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  10275. $pdf->SetCreator('动漫剧本导出系统');
  10276. $pdf->SetAuthor('系统');
  10277. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  10278. $pdf->SetSubject('动漫剧本导出');
  10279. $pdf->SetMargins(15, 15, 15);
  10280. $pdf->SetAutoPageBreak(true, 15);
  10281. // 剧本名
  10282. $pdf->AddPage();
  10283. $pdf->SetFont('simsun', 'B', 20);
  10284. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  10285. $pdf->Ln(5);
  10286. // 故事梗概
  10287. $intro = trim((string)getProp($anime, 'intro', ''));
  10288. if ($intro !== '') {
  10289. $this->pdfSectionTitle($pdf, '故事梗概');
  10290. $this->pdfBody($pdf, $intro);
  10291. }
  10292. // 美术风格
  10293. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  10294. if ($artStyle !== '') {
  10295. $this->pdfSectionTitle($pdf, '美术风格');
  10296. $this->pdfBody($pdf, $artStyle);
  10297. }
  10298. // 主体列表(文字+图片)
  10299. $this->pdfSectionTitle($pdf, '主体列表');
  10300. foreach ($roles as $index => $role) {
  10301. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  10302. }
  10303. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  10304. // 场景列表(文字+图片)
  10305. $this->pdfSectionTitle($pdf, '场景列表');
  10306. foreach ($scenes as $index => $scene) {
  10307. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  10308. }
  10309. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  10310. // 道具列表(文字+图片)
  10311. $this->pdfSectionTitle($pdf, '道具列表');
  10312. foreach ($props as $index => $prop) {
  10313. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  10314. }
  10315. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  10316. // 分镜剧本
  10317. $this->pdfSectionTitle($pdf, '分镜剧本');
  10318. foreach ($episodeScripts as $episodeScript) {
  10319. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  10320. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  10321. if ($episodeTitleRaw !== '') {
  10322. // title 字段可能已带"第N集"前缀,避免重复
  10323. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  10324. $episodeTitle = $episodeTitleRaw;
  10325. } else {
  10326. $episodeTitle .= ':' . $episodeTitleRaw;
  10327. }
  10328. }
  10329. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  10330. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  10331. if (getProp($episodeScript, 'narrator_voice') !== '') {
  10332. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  10333. }
  10334. foreach (getProp($episodeScript, 'acts', []) as $act) {
  10335. $actTitle = '片段' . getProp($act, 'act_number');
  10336. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  10337. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  10338. }
  10339. $this->pdfSubTitle($pdf, $actTitle, 12);
  10340. if (getProp($act, 'content') !== '') {
  10341. $this->pdfBody($pdf, getProp($act, 'content'));
  10342. }
  10343. }
  10344. }
  10345. return $pdf;
  10346. }
  10347. /**
  10348. * PDF章节标题(带分隔线)
  10349. */
  10350. private function pdfSectionTitle($pdf, $title) {
  10351. if ($pdf->GetY() > 230) {
  10352. $pdf->AddPage();
  10353. }
  10354. $pdf->SetFont('simsun', 'B', 15);
  10355. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  10356. $y = $pdf->GetY();
  10357. $pdf->SetLineWidth(0.4);
  10358. $pdf->Line(15, $y, 195, $y);
  10359. $pdf->Ln(4);
  10360. }
  10361. /**
  10362. * PDF子标题(集数/片段标题)
  10363. */
  10364. private function pdfSubTitle($pdf, $title, $size = 13) {
  10365. if ($pdf->GetY() > 240) {
  10366. $pdf->AddPage();
  10367. }
  10368. $pdf->SetFont('simsun', 'B', $size);
  10369. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  10370. $pdf->Ln(1);
  10371. }
  10372. /**
  10373. * PDF正文段落
  10374. */
  10375. private function pdfBody($pdf, $text) {
  10376. $pdf->SetFont('simsun', '', 11);
  10377. $pdf->MultiCell(0, 6, $text, 0, 'L');
  10378. $pdf->Ln(2);
  10379. }
  10380. /**
  10381. * 输出列表项图片(每张图单独一页,图下标注名称)
  10382. * @param \TCPDF $pdf
  10383. * @param array $items 列表项
  10384. * @param string $nameKey role|scene|prop
  10385. * @param array $imageCache 图片缓存(url => 临时文件路径)
  10386. */
  10387. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  10388. foreach ($items as $item) {
  10389. $url = trim((string)getProp($item, 'url', ''));
  10390. $name = trim((string)getProp($item, $nameKey, ''));
  10391. if ($url === '' || !isset($imageCache[$url])) continue;
  10392. $imgPath = $imageCache[$url];
  10393. $size = @getimagesize($imgPath);
  10394. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  10395. continue;
  10396. }
  10397. $pdf->AddPage();
  10398. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  10399. $maxW = 160;
  10400. $maxH = 170;
  10401. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  10402. $drawW = $size[0] * $ratio;
  10403. $drawH = $size[1] * $ratio;
  10404. $x = (210 - $drawW) / 2;
  10405. $y = max(15, (297 - $drawH) / 2 - 10);
  10406. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  10407. // 图下标注名称
  10408. $pdf->SetFont('simsun', 'B', 13);
  10409. $pdf->SetY(297 - 28);
  10410. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  10411. }
  10412. }
  10413. /**
  10414. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  10415. * @param array $items 包含url字段的列表项
  10416. * @return array url => 临时文件路径
  10417. */
  10418. private function downloadImagesConcurrently(array $items) {
  10419. // 收集唯一的图片URL
  10420. $urls = [];
  10421. foreach ($items as $item) {
  10422. $url = trim((string)getProp($item, 'url', ''));
  10423. if ($url !== '') $urls[$url] = true;
  10424. }
  10425. if (!$urls) return [];
  10426. $urls = array_keys($urls);
  10427. $tmpDir = sys_get_temp_dir();
  10428. $rawFiles = [];
  10429. foreach ($urls as $url) {
  10430. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  10431. $rawFiles[$url] = $rawFile;
  10432. }
  10433. $client = new Client(['timeout' => 180, 'verify' => false]);
  10434. // 低并发下载,sink写入文件避免大图占用内存
  10435. $generator = (function () use ($urls, $client, $rawFiles) {
  10436. foreach ($urls as $url) {
  10437. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  10438. }
  10439. })();
  10440. $errors = [];
  10441. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  10442. 'concurrency' => 4,
  10443. 'rejected' => function ($reason, $url) use (&$errors) {
  10444. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  10445. },
  10446. ]);
  10447. $each->promise()->wait();
  10448. // 失败的图片串行重试一次(独占带宽,提高成功率)
  10449. foreach ($urls as $url) {
  10450. if (!isset($errors[$url])) continue;
  10451. try {
  10452. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  10453. unset($errors[$url]);
  10454. } catch (\Throwable $e) {
  10455. // 重试仍失败
  10456. }
  10457. }
  10458. $cache = [];
  10459. foreach ($urls as $url) {
  10460. $rawFile = $rawFiles[$url];
  10461. if (isset($errors[$url])) {
  10462. dLog('anime')->error('导出PDF图片下载失败', [
  10463. 'url' => $url,
  10464. 'error' => $errors[$url],
  10465. ]);
  10466. @unlink($rawFile);
  10467. continue;
  10468. }
  10469. $converted = $this->convertImageFile($rawFile, $url);
  10470. if ($converted !== null) {
  10471. $cache[$url] = $converted;
  10472. } else {
  10473. @unlink($rawFile);
  10474. }
  10475. }
  10476. return $cache;
  10477. }
  10478. /**
  10479. * 将已下载的图片文件缩放并转为JPEG
  10480. * @param string $rawFile 原始图片临时文件
  10481. * @param string $url 图片地址(用于命名)
  10482. * @return string|null 转换后的文件路径,转换失败返回null
  10483. */
  10484. private function convertImageFile($rawFile, $url) {
  10485. $content = @file_get_contents($rawFile);
  10486. if ($content === false || $content === '') return null;
  10487. if (!function_exists('imagecreatefromstring')) return null;
  10488. $image = @imagecreatefromstring($content);
  10489. if ($image === false) return null;
  10490. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  10491. imagedestroy($image);
  10492. if ($jpeg !== null) {
  10493. @unlink($rawFile);
  10494. }
  10495. return $jpeg;
  10496. }
  10497. /**
  10498. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  10499. * @param resource $srcImage GD图片资源
  10500. * @param string $rawFile 原始图片临时文件
  10501. * @param string $url 图片地址(用于命名)
  10502. * @return string|null 压缩后的JPEG文件路径
  10503. */
  10504. private function compressImageForPdf($srcImage, $rawFile, $url) {
  10505. $maxBytes = 2 * 1024 * 1024; // 2MB
  10506. $sizes = [2048, 1600, 1280, 1024, 800];
  10507. $qualities = [85, 70, 55, 40];
  10508. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  10509. foreach ($sizes as $size) {
  10510. $resized = $this->copyAndResize($srcImage, $size);
  10511. $flat = $this->flattenToWhite($resized);
  10512. imagedestroy($resized);
  10513. foreach ($qualities as $quality) {
  10514. ob_start();
  10515. $saved = imagejpeg($flat, null, $quality);
  10516. $data = ob_get_clean();
  10517. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  10518. file_put_contents($jpeg, $data);
  10519. imagedestroy($flat);
  10520. dLog('anime')->info('导出PDF图片压缩完成', [
  10521. 'url' => $url,
  10522. 'size' => filesize($jpeg),
  10523. 'edge' => $size,
  10524. 'quality' => $quality,
  10525. ]);
  10526. return $jpeg;
  10527. }
  10528. }
  10529. imagedestroy($flat);
  10530. }
  10531. // 兜底:最小尺寸、最低质量强制输出
  10532. $resized = $this->copyAndResize($srcImage, 800);
  10533. $flat = $this->flattenToWhite($resized);
  10534. imagedestroy($resized);
  10535. $saved = imagejpeg($flat, $jpeg, 30);
  10536. imagedestroy($flat);
  10537. if (!$saved) return null;
  10538. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  10539. 'url' => $url,
  10540. 'size' => filesize($jpeg),
  10541. ]);
  10542. return $jpeg;
  10543. }
  10544. /**
  10545. * 等比缩放图片副本(不销毁原图)
  10546. * @param resource $srcImage GD图片资源
  10547. * @param int $maxEdge 最大边长
  10548. * @return resource
  10549. */
  10550. private function copyAndResize($srcImage, $maxEdge) {
  10551. $width = imagesx($srcImage);
  10552. $height = imagesy($srcImage);
  10553. $max = max($width, $height);
  10554. if ($max <= $maxEdge) {
  10555. $copy = imagecreatetruecolor($width, $height);
  10556. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  10557. return $copy;
  10558. }
  10559. $ratio = $maxEdge / $max;
  10560. $newWidth = max(1, (int)round($width * $ratio));
  10561. $newHeight = max(1, (int)round($height * $ratio));
  10562. $resized = imagecreatetruecolor($newWidth, $newHeight);
  10563. imagealphablending($resized, false);
  10564. imagesavealpha($resized, true);
  10565. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  10566. return $resized;
  10567. }
  10568. /**
  10569. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  10570. * @param resource $image GD图片资源
  10571. * @return resource
  10572. */
  10573. private function flattenToWhite($image) {
  10574. $width = imagesx($image);
  10575. $height = imagesy($image);
  10576. $flat = imagecreatetruecolor($width, $height);
  10577. $white = imagecolorallocate($flat, 255, 255, 255);
  10578. imagefill($flat, 0, 0, $white);
  10579. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  10580. return $flat;
  10581. }
  10582. /**
  10583. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  10584. * @param string $content 片段内容
  10585. * @param int $counter 当前已编号数量(引用传递,整集累计)
  10586. * @return string
  10587. */
  10588. private function renumberSegmentBlocks($content, &$counter) {
  10589. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  10590. $counter++;
  10591. return '【' . $match[1] . $counter . '】';
  10592. }, $content);
  10593. }
  10594. }