AnimeService.php 522 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291
  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. 'anime_id' => $anime_id,
  310. 'episode_id' => $episode_id,
  311. 'episode_number' => getProp($episode, 'episode_number'),
  312. ];
  313. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  314. $task_id = $task->id;
  315. if (!$task_id) {
  316. Utils::throwError("20003:角色({$role_name})生成图片失败");
  317. }
  318. $role['task_id'] = $task_id;
  319. $role['task_status'] = 'processing';
  320. } catch (\Exception $e) {
  321. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  322. Utils::throwError("20003:" . $e->getMessage());
  323. }
  324. }
  325. // 保存角色信息
  326. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  327. 'roles' => json_encode($roles, 256),
  328. 'generate_status' => '执行中',
  329. 'generate_at' => date('Y-m-d H:i:s'),
  330. 'updated_at' => date('Y-m-d H:i:s')
  331. ]);
  332. if (!$boolen) {
  333. Utils::throwError('20003:保存角色信息失败');
  334. }
  335. return $boolen;
  336. }
  337. public function batchSetSceneImg($data) {
  338. $episode_id = getProp($data, 'episode_id');
  339. if (!$episode_id) Utils::throwError('1002:请选择分集');
  340. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  341. $scenes = json_decode(getProp($episode, 'scenes'), true);
  342. $art_style = getProp($episode, 'art_style');
  343. $target_scene = getProp($data, 'target_scene');
  344. $anime_id = getProp($episode, 'anime_id');
  345. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  346. $art_style_type = getProp($anime, 'art_style_type');
  347. $character_prefix = '';
  348. $scene_prefix = '';
  349. if ($art_style_type) {
  350. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  351. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  352. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  353. }
  354. foreach ($scenes as &$scene) {
  355. $scene_name = getProp($scene, 'scene');
  356. if ($scene_name != $target_scene) continue;
  357. // 优先使用 pic_prompt,如果没有则使用 description
  358. $pic_prompt = getProp($scene, 'pic_prompt');
  359. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  360. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  361. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  362. // 参考图地址
  363. $ref_img_url = getProp($scene, 'url');
  364. if ($ref_img_url) continue; // 已有图片则跳过
  365. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  366. try {
  367. $params = [
  368. 'prompt' => $description,
  369. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  370. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  371. 'anime_id' => $anime_id,
  372. 'episode_id' => $episode_id,
  373. 'episode_number' => getProp($episode, 'episode_number'),
  374. ];
  375. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  376. $task_id = $task->id;
  377. if (!$task_id) {
  378. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  379. }
  380. $scene['task_id'] = $task_id;
  381. $scene['task_status'] = 'processing';
  382. } catch (\Exception $e) {
  383. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  384. Utils::throwError("20003:" . $e->getMessage());
  385. }
  386. }
  387. // 保存场景信息
  388. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  389. 'scenes' => json_encode($scenes, 256),
  390. 'generate_status' => '执行中',
  391. 'generate_at' => date('Y-m-d H:i:s'),
  392. 'updated_at' => date('Y-m-d H:i:s')
  393. ]);
  394. if (!$boolen) {
  395. Utils::throwError('20003:保存角色信息失败');
  396. }
  397. return $boolen;
  398. }
  399. public function editAnime($data) {
  400. $anime_id = getProp($data, 'anime_id');
  401. $anime_name = trim(getProp($data, 'anime_name'));
  402. // 确认对话名称唯一性
  403. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  404. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  405. }
  406. if (!$anime_id || !$anime_name) {
  407. Utils::throwError('20003:参数异常');
  408. }
  409. return DB::table('mp_animes')->where('id', $anime_id)->update([
  410. 'anime_name' => $anime_name,
  411. 'updated_at' => date('Y-m-d H:i:s')
  412. ]);
  413. // $script_arr =getProp($data, 'script', []);
  414. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  415. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  416. // $anime_id = getProp($data, 'anime_id');
  417. // try {
  418. // DB::beginTransaction();
  419. // $table_data = [
  420. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  421. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  422. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  423. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  424. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  425. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  426. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  427. // 'status' => 3,
  428. // 'start_episode_sequence' => $start_episode_sequence,
  429. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  430. // 'episode_num' => count($script_arr['episodes']),
  431. // 'updated_at' => date('Y-m-d H:i:s')
  432. // ];
  433. // // 保存剧本内容
  434. // if (!empty($anime_id)) {
  435. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  436. // if (!$boolen) {
  437. // dLog('anime')->info('对话保存失败', $table_data);
  438. // Utils::throwError('20003:对话保存失败');
  439. // }
  440. // }else {
  441. // $table['created_at'] = $table_data['updated_at'];
  442. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  443. // if (!$anime_id) {
  444. // dLog('anime')->info('对话保存失败', $table_data);
  445. // Utils::throwError('20003:对话保存失败');
  446. // }
  447. // }
  448. // // 保存分集内容
  449. // // 删除历史分集内容
  450. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  451. // $episodes = [];
  452. // $sequence = 1;
  453. // foreach ($script_arr['episodes'] as $episode) {
  454. // $segment_number = 1;
  455. // foreach($episode['segments'] as $segment) {
  456. // $episodes[] = [
  457. // 'anime_id' => $anime_id,
  458. // 'episode_number' => $episode['episode_number'],
  459. // 'title' => $episode['title'],
  460. // // 'content' => $episode['content'],
  461. // 'content' => '',
  462. // 'segment_number' => $segment_number,
  463. // 'segment_content' => $segment['segment_content'],
  464. // 'sequence' => $sequence,
  465. // 'created_at' => date('Y-m-d H:i:s'),
  466. // 'updated_at' => date('Y-m-d H:i:s')
  467. // ];
  468. // $sequence++;
  469. // $segment_number++;
  470. // }
  471. // }
  472. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  473. // if (!$boolen2) {
  474. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  475. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  476. // Utils::throwError('20003:分集内容保存失败');
  477. // }
  478. // } catch (\Exception $e) {
  479. // DB::rollBack();
  480. // Utils::throwError('20003:'.$e->getMessage());
  481. // }
  482. // DB::commit();
  483. // return true;
  484. }
  485. public function delAnime($data) {
  486. $anime_id = getProp($data, 'anime_id');
  487. if (!$anime_id) {
  488. Utils::throwError('20003:请选择剧本');
  489. }
  490. return DB::table('mp_animes')->where('id', $anime_id)->update([
  491. 'is_deleted' => 1,
  492. 'updated_at' => date('Y-m-d H:i:s')
  493. ]);
  494. }
  495. public function animeDetail($data) {
  496. $uid = Site::getUid();
  497. $anime_id = getProp($data, 'anime_id');
  498. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  499. ->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();
  500. if (!$anime) Utils::throwError('20003:权限不足');
  501. $anime = (array)$anime;
  502. $anime['roles'] = json_decode($anime['roles']);
  503. $anime['scenes'] = json_decode($anime['scenes']);
  504. // 获取分集信息
  505. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  506. ->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"))
  507. ->orderBy('episode_number')->get()->map(function ($value) {
  508. return (array)$value;
  509. })->toArray();
  510. $anime['episodes'] = $episodes;
  511. // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
  512. $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
  513. $episodeTasks = DB::table('mp_batch_episode_generation_details')
  514. ->where('anime_id', $anime_id)
  515. ->whereIn('status', ['pending', 'processing', 'failed']) // 只获取待生成/生成中任务,已完成或失败的不显示
  516. ->orderBy('episode_number')
  517. ->get()
  518. ->map(function ($task) use ($episodeNumbers) {
  519. if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
  520. return null;
  521. }
  522. return [
  523. 'episode_number' => (int)$task->episode_number,
  524. 'status' => $task->status,
  525. 'error_message' => $task->status == 'failed' ? $task->error_message : '',
  526. ];
  527. })
  528. ->filter()
  529. ->values()
  530. ->toArray();
  531. $anime['episode_tasks'] = $episodeTasks;
  532. return $anime;
  533. }
  534. public function episodeInfo($data) {
  535. $uid = Site::getUid();
  536. $anime_id = getProp($data, 'anime_id');
  537. $episode_id = getProp($data, 'episode_id');
  538. if (!$anime_id || !$episode_id) {
  539. Utils::throwError('1002:请选择剧集');
  540. }
  541. // 验证用户权限
  542. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  543. if (!$anime) Utils::throwError('20003:权限不足');
  544. $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();
  545. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  546. $episode = (array)$episode;
  547. $episode['roles'] = json_decode($episode['roles'], true);
  548. // foreach($episode['roles'] as &$item) {
  549. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  550. // }
  551. $episode['scenes'] = json_decode($episode['scenes'], true);
  552. // foreach($episode['scenes'] as &$item) {
  553. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  554. // }
  555. // 获取分镜信息
  556. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  557. ->select('*')->get()->map(function ($value) {
  558. return (array)$value;
  559. })->toArray();
  560. // 使用公共方法构建分镜结构
  561. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  562. $episode['acts'] = $segmentsStructure['acts'];
  563. $episode['total_duration'] = $segmentsStructure['total_duration'];
  564. return $episode;
  565. }
  566. public function episodeInfoForAce($data) {
  567. $anime_id = getProp($data, 'anime_id');
  568. $episode_id = getProp($data, 'episode_id');
  569. if (!$anime_id || !$episode_id) {
  570. Utils::throwError('1002:请选择剧集');
  571. }
  572. $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();
  573. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  574. $episode = (array)$episode;
  575. $episode['roles'] = json_decode($episode['roles'], true);
  576. // foreach($episode['roles'] as &$item) {
  577. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  578. // }
  579. $episode['scenes'] = json_decode($episode['scenes'], true);
  580. // foreach($episode['scenes'] as &$item) {
  581. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  582. // }
  583. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  584. // 获取分镜信息
  585. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  586. ->select('*')->get()->map(function ($value) {
  587. return (array)$value;
  588. })->toArray();
  589. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  590. $episode['acts'] = $segmentsStructure['acts'];
  591. $episode['total_duration'] = $segmentsStructure['total_duration'];
  592. // 获取mp_animes表中的视频参数
  593. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  594. $episode['video_params'] = [
  595. 'video_model' => getProp($anime, 'video_model'),
  596. 'video_resolution' => getProp($anime, 'video_resolution'),
  597. 'ratio' => getProp($anime, 'video_ratio'),
  598. ];
  599. return $episode;
  600. }
  601. public function segmentInfo($data) {
  602. $uid = Site::getUid();
  603. $segment_id = getProp($data, 'segment_id');
  604. if (!$segment_id) {
  605. Utils::throwError('1002:请选择分镜');
  606. }
  607. // 获取分镜信息
  608. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  609. // 验证用户权限
  610. if ($segment) {
  611. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  612. if (!$anime) Utils::throwError('20003:权限不足');
  613. }
  614. $result = [
  615. 'segment_id' => getProp($segment, 'segment_id'),
  616. 'segment_number' => getProp($segment, 'segment_number'),
  617. 'segment_content' => getProp($segment, 'segment_content'),
  618. 'description' => getProp($segment, 'description'),
  619. 'composition' => getProp($segment, 'composition'),
  620. 'camera_movement' => getProp($segment, 'camera_movement'),
  621. 'voice_actor' => getProp($segment, 'voice_actor'),
  622. 'dialogue' => getProp($segment, 'dialogue'),
  623. 'frame_type' => getProp($segment, 'frame_type'),
  624. 'scene' => getProp($segment, 'scene'),
  625. 'characters' => getProp($segment, 'characters'),
  626. 'tail_frame' => getProp($segment, 'tail_frame'),
  627. 'emotion' => getProp($segment, 'emotion'),
  628. 'emotion_type' => getProp($segment, 'emotion_type'),
  629. 'gender' => getProp($segment, 'gender'),
  630. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  631. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  632. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  633. 'pitch' => getProp($segment, 'pitch'),
  634. 'voice_name' => getProp($segment, 'voice_name'),
  635. 'voice_type' => getProp($segment, 'voice_type'),
  636. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  637. 'img_url' => getProp($segment, 'img_url'),
  638. 'video_url' => getProp($segment, 'video_url'),
  639. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  640. ];
  641. return $result;
  642. }
  643. public function copyEpisodeVersion($data) {
  644. $episode_id = getProp($data, 'episode_id');
  645. $uid = Site::getUid();
  646. $cpid = Site::getCpid();
  647. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  648. if (!$episode) Utils::throwError('20003:该剧集不存在');
  649. $episode = (array)$episode;
  650. $anime_id = $episode['anime_id'];
  651. $episode_number = $episode['episode_number'];
  652. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  653. $sequence = $count + 1;
  654. unset($episode['id']);
  655. $now = date('Y-m-d H:i:s');
  656. $episode['created_at'] = $now;
  657. $episode['updated_at'] = $now;
  658. $episode['is_default'] = 1;
  659. // 获取版本中含有"(副本"字样的个数
  660. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  661. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  662. $episode['sequence'] = $sequence;
  663. $episode['is_generated'] = 0;
  664. $episode['cpid'] = $cpid;
  665. // 获取ace_mode
  666. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  667. try {
  668. DB::beginTransaction();
  669. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  670. // 新增副本
  671. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  672. if (!$new_episode_id) {
  673. Utils::throwError('20003:创建副本失败!');
  674. }
  675. // 获取分镜数据并准备插入
  676. $segments_for_insert = DB::table('mp_episode_segments')
  677. ->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')
  678. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  679. $item = (array)$item;
  680. $item['episode_id'] = $new_episode_id;
  681. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  682. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  683. return $item;
  684. })->toArray();
  685. // 写入分镜数据
  686. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  687. if (!$boolen2) {
  688. Utils::throwError('20003:写入分镜数据失败!');
  689. }
  690. // 写入对话历史
  691. $records = [
  692. [
  693. 'uid' => $uid,
  694. 'anime_id' => $anime_id,
  695. 'role' => 'user',
  696. 'content' => '创建副本',
  697. 'sequence' => $episode_number,
  698. 'episode_id' => $new_episode_id,
  699. 'created_at' => $now,
  700. 'updated_at' => $now
  701. ],
  702. [
  703. 'uid' => $uid,
  704. 'anime_id' => $anime_id,
  705. 'role' => 'assistant',
  706. 'content' => '好的,已为您创建副本',
  707. 'sequence' => $episode_number,
  708. 'episode_id' => $new_episode_id,
  709. 'created_at' => $now,
  710. 'updated_at' => $now
  711. ]
  712. ];
  713. $boolen3 = DB::table('mp_anime_records')->insert($records);
  714. if (!$boolen3) {
  715. Utils::throwError('20003:对话记录保存失败');
  716. }
  717. }catch (\Exception $e) {
  718. DB::rollBack();
  719. Utils::throwError('20003:'.$e->getMessage());
  720. }
  721. DB::commit();
  722. // 构建与 episodeInfo 方法一致的返回数据结构
  723. $result = [
  724. 'episode_id' => $new_episode_id,
  725. 'anime_id' => $anime_id,
  726. 'episode_number' => $episode_number,
  727. 'title' => $episode['title'],
  728. 'intro' => $episode['intro'],
  729. 'art_style' => $episode['art_style'],
  730. 'roles' => json_decode($episode['roles'], true),
  731. 'scenes' => json_decode($episode['scenes'], true),
  732. 'is_generated' => (int)$episode['is_generated']
  733. ];
  734. if ((int)$ace_mode === 1) {
  735. // 获取分镜信息
  736. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  737. ->select('*')->get()->map(function ($value) {
  738. return (array)$value;
  739. })->toArray();
  740. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  741. }else {
  742. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  743. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  744. }
  745. $result['acts'] = $segmentsStructure['acts'];
  746. $result['total_duration'] = $segmentsStructure['total_duration'];
  747. return $result;
  748. }
  749. public function episodeVersions($data) {
  750. $anime_id = getProp($data, 'anime_id');
  751. $episode_id = getProp($data, 'episode_id');
  752. if (!$anime_id || !$episode_id) {
  753. Utils::throwError('1002:请选择剧集');
  754. }
  755. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  756. $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) {
  757. return (array)$value;
  758. })->toArray();
  759. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  760. foreach($episodes as &$episode) {
  761. $episode['version'] = 'V'.$episode['sequence'];
  762. $episode['roles'] = json_decode($episode['roles'], true);
  763. $episode['scenes'] = json_decode($episode['scenes'], true);
  764. // 获取分镜信息
  765. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  766. ->select('*')->get()->map(function ($value) {
  767. return (array)$value;
  768. })->toArray();
  769. // 使用公共方法构建分镜结构
  770. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  771. $episode['acts'] = $segmentsStructure['acts'];
  772. $episode['total_duration'] = $segmentsStructure['total_duration'];
  773. }
  774. return $episodes;
  775. }
  776. public function bindEpisodeVersion($data) {
  777. $episode_id = getProp($data, 'episode_id');
  778. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  779. if (!$episode) Utils::throwError('20003:该剧集不存在');
  780. $episode = (array)$episode;
  781. if ((int)$episode['is_default'] === 1) return true;
  782. try {
  783. DB::beginTransaction();
  784. // 移除is_default标志
  785. $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')]);
  786. if (!$boolen) {
  787. Utils::throwError('20003:更新失败!');
  788. }
  789. // 绑定副本
  790. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  791. if (!$boolen2) {
  792. Utils::throwError('20003:绑定失败!');
  793. }
  794. }catch (\Exception $e) {
  795. DB::rollBack();
  796. Utils::throwError('20003:'.$e->getMessage());
  797. }
  798. DB::commit();
  799. return true;
  800. }
  801. public function chatChangeImg($data) {
  802. $segment_id = getProp($data, 'segment_id');
  803. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  804. $prompt = getProp($data, 'prompt');
  805. if (!$prompt || !$segment_id) {
  806. Utils::throwError('1002:请输入提示词,并且选择分镜');
  807. }
  808. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  809. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  810. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  811. else $ref_img_url = '';
  812. // $ref_img_url = '';
  813. if (empty($prompt)) {
  814. if (empty($ref_img_url)) {
  815. $prompt = getProp($segment, 'segment_content');
  816. }else {
  817. $prompt = '请根据图片生成';
  818. }
  819. }
  820. $anime_id = getProp($segment, 'anime_id');
  821. $episode_id = getProp($segment, 'episode_id');
  822. $episode_number = getProp($segment, 'episode_number');
  823. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  824. $ratio = getProp($data, 'ratio');
  825. if (!$ratio) {
  826. $ratio = getProp($episode, 'ratio');
  827. if (!$ratio) $ratio = '9:16';
  828. }
  829. $art_style = getProp($episode, 'art_style');
  830. if ($art_style) {
  831. $prompt = "美术风格:{$art_style}\n{$prompt}";
  832. }
  833. $dimensions = $this->getRatioDimensions($ratio);
  834. $width = $dimensions['width'];
  835. $height = $dimensions['height'];
  836. try {
  837. $params = [
  838. 'alias_segment_id' => $segment_id,
  839. 'prompt' => $prompt,
  840. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  841. 'width' => $width,
  842. 'height' => $height
  843. ];
  844. // 优化提示词(不要生成字幕)
  845. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  846. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  847. $task_id = $task->id;
  848. if (!$task_id) {
  849. Utils::throwError("20003:生成图片失败");
  850. }
  851. // 更新任务ID
  852. $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')]);
  853. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  854. } catch (\Exception $e) {
  855. Utils::throwError("20003:" . $e->getMessage());
  856. }
  857. // 创建任务之后先暂停10s等待异步任务完成
  858. sleep(10);
  859. $img_url = $this->loopGetPicTaskResult($task_id);
  860. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  861. // 图片生成后新增对话记录
  862. try {
  863. $uid = Site::getUid();
  864. $now = date('Y-m-d H:i:s');
  865. // 使用AI反推图片提示词
  866. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  867. // 保存对话记录
  868. $records = [
  869. [
  870. 'uid' => $uid,
  871. 'anime_id' => $anime_id,
  872. 'sequence' => $episode_number,
  873. 'role' => 'user',
  874. 'content' => $prompt,
  875. 'segment_id' => $segment_id,
  876. 'pic_task_id' => $task_id,
  877. 'image_url' => '',
  878. 'created_at' => $now,
  879. 'updated_at' => $now
  880. ],
  881. [
  882. 'uid' => $uid,
  883. 'anime_id' => $anime_id,
  884. 'sequence' => $episode_number,
  885. 'role' => 'assistant',
  886. 'content' => $pic_prompt,
  887. 'segment_id' => $segment_id,
  888. 'pic_task_id' => $task_id,
  889. 'image_url' => $img_url,
  890. 'created_at' => $now,
  891. 'updated_at' => $now
  892. ]
  893. ];
  894. DB::table('mp_anime_records')->insert($records);
  895. } catch (\Exception $e) {
  896. // 记录日志但不影响主流程
  897. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  898. 'segment_id' => $segment_id,
  899. 'img_url' => $img_url
  900. ]);
  901. logDB('anime', 'error', '保存对话记录失败', [
  902. 'segment_id' => $segment_id,
  903. 'img_url' => $img_url,
  904. 'error' => $e->getMessage()
  905. ]);
  906. }
  907. return $img_url;
  908. }
  909. public function segmentChatHistory($data) {
  910. $segment_id = getProp($data, 'segment_id');
  911. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  912. $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');
  913. $chat = $query->orderBy('id')->get()->map(function ($value) {
  914. $value = (array)$value;
  915. $value['created_at'] = transDate($value['created_at']);
  916. return $value;
  917. })->toArray();
  918. // 获取历史图片
  919. $url = [];
  920. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  921. foreach($pic_history as $task) {
  922. $result_url = getProp($task, 'result_url');
  923. if (is_json($result_url)) {
  924. $url = array_merge($url, json_decode($result_url, true));
  925. }else {
  926. $url[] = $result_url;
  927. }
  928. }
  929. // 获取历史视频
  930. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  931. foreach($video_history as $task) {
  932. $result_url = getProp($task, 'compressed_url');
  933. if (is_json($result_url)) {
  934. $url = array_merge($url, json_decode($result_url, true));
  935. }else {
  936. $url[] = $result_url;
  937. }
  938. }
  939. return compact('chat', 'url');
  940. }
  941. public function changeEpisodeRoles($data) {
  942. $anime_id = getProp($data, 'anime_id');
  943. $episode_id = getProp($data, 'episode_id');
  944. $target_roles = getProp($data, 'roles');
  945. // 删除标志优先取最外层入参 is_deleted,兼容角色对象内部(roles.is_deleted)的传参
  946. $is_deleted = getProp($data, 'is_deleted', getProp($target_roles, 'is_deleted', 0));
  947. // 控制字段不随角色内容写入分集roles存储
  948. if (is_array($target_roles)) {
  949. unset($target_roles['is_deleted']);
  950. }
  951. // 参数验证
  952. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  953. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  954. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  955. // 验证剧集是否存在
  956. $episode = DB::table('mp_anime_episodes')
  957. ->where('anime_id', $anime_id)
  958. ->where('id', $episode_id)
  959. ->first();
  960. if (!$episode) Utils::throwError('20003:该剧集不存在');
  961. $roles = json_decode(getProp($episode, 'roles'), true);
  962. // 获取anime信息,检查是否有关联的script_id
  963. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  964. if (!$anime) Utils::throwError('20003:动漫不存在');
  965. $script_id = getProp($anime, 'script_id');
  966. $episode_number = getProp($episode, 'episode_number', 1);
  967. $uid = Site::getUid();
  968. $cpid = Site::getCpid();
  969. try {
  970. $target_role_name = getProp($target_roles, 'role');
  971. if (empty($target_role_name)) {
  972. Utils::throwError('20003:角色名称不能为空');
  973. }
  974. // 如果是删除操作
  975. if ($is_deleted == 1) {
  976. // 从角色列表中移除该角色
  977. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  978. return getProp($role, 'role') !== $target_role_name;
  979. }));
  980. // 更新角色列表
  981. $result = DB::table('mp_anime_episodes')
  982. ->where('anime_id', $anime_id)
  983. ->where('id', $episode_id)
  984. ->update([
  985. 'roles' => json_encode($roles, 256),
  986. 'updated_at' => date('Y-m-d H:i:s')
  987. ]);
  988. if ($result === false) {
  989. Utils::throwError('20003:删除角色失败');
  990. }
  991. } else {
  992. // 新增或更新操作
  993. $role_found = false;
  994. $is_new_role = false;
  995. // 查找并更新已存在的角色
  996. foreach($roles as &$role) {
  997. if (getProp($role, 'role') === $target_role_name) {
  998. $role = $target_roles;
  999. $role_found = true;
  1000. break;
  1001. }
  1002. }
  1003. // 如果角色不存在,则新增
  1004. if (!$role_found) {
  1005. $roles[] = $target_roles;
  1006. $is_new_role = true;
  1007. }
  1008. // 更新角色列表
  1009. $result = DB::table('mp_anime_episodes')
  1010. ->where('anime_id', $anime_id)
  1011. ->where('id', $episode_id)
  1012. ->update([
  1013. 'roles' => json_encode($roles, 256),
  1014. 'updated_at' => date('Y-m-d H:i:s')
  1015. ]);
  1016. if ($result === false) {
  1017. Utils::throwError('20003:更新角色列表失败');
  1018. }
  1019. // 同步更新分镜表中对应主体的音色信息
  1020. $voice_name = getProp($target_roles, 'voice_name');
  1021. $voice_type = getProp($target_roles, 'voice_type');
  1022. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  1023. DB::table('mp_episode_segments')
  1024. ->where('anime_id', $anime_id)
  1025. ->where('episode_id', $episode_id)
  1026. ->where('voice_actor', $target_role_name)
  1027. ->update([
  1028. 'voice_name' => $voice_name,
  1029. 'voice_type' => $voice_type,
  1030. 'voice_audio_url' => $voice_audio_url,
  1031. 'updated_at' => date('Y-m-d H:i:s')
  1032. ]);
  1033. // 如果有关联的script_id,则同步到mp_products表
  1034. if ($script_id) {
  1035. // 查询剧本信息
  1036. $script = DB::table('mp_scripts')
  1037. ->where('id', $script_id)
  1038. ->where('is_deleted', 0)
  1039. ->first();
  1040. if ($script) {
  1041. $script_name = $script->script_name ?? 'script_' . $script_id;
  1042. $product_name = getProp($target_roles, 'role');
  1043. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1044. $url = getProp($target_roles, 'url', '');
  1045. $product_type = 1; // 1=角色
  1046. // 查找或创建以script_name命名的文件夹
  1047. $folder = DB::table('mp_products')
  1048. ->where('cpid', $cpid)
  1049. ->where('type', 2) // 文件夹类型
  1050. ->where('product', $product_type) // 角色类型
  1051. ->where('product_name', $script_name)
  1052. ->where('parent_id', 0)
  1053. ->where('is_deleted', 0)
  1054. ->first();
  1055. if (!$folder) {
  1056. // 创建文件夹
  1057. $folder_id = DB::table('mp_products')->insertGetId([
  1058. 'user_id' => $uid,
  1059. 'cpid' => $cpid,
  1060. 'type' => 2, // 文件夹
  1061. 'product' => $product_type, // 角色类型
  1062. 'parent_id' => 0,
  1063. 'level' => 1,
  1064. 'product_name' => $script_name,
  1065. 'sort_order' => time(),
  1066. 'is_deleted' => 0,
  1067. 'created_at' => date('Y-m-d H:i:s'),
  1068. 'updated_at' => date('Y-m-d H:i:s')
  1069. ]);
  1070. } else {
  1071. $folder_id = $folder->id;
  1072. }
  1073. // 查找该文件夹下是否已存在同名资产
  1074. $existing_product = DB::table('mp_products')
  1075. ->where('cpid', $cpid)
  1076. ->where('type', 1) // 资产类型
  1077. ->where('product', $product_type)
  1078. ->where('parent_id', $folder_id)
  1079. ->where('product_name', $product_name)
  1080. ->where('is_deleted', 0)
  1081. ->first();
  1082. if ($existing_product) {
  1083. // 更新已存在的资产
  1084. $updateData = [
  1085. 'pic_task_status' => '生成成功',
  1086. ];
  1087. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1088. if ($url) $updateData['url'] = $url;
  1089. // 处理versions字段
  1090. $versions = getProp($target_roles, 'versions', []);
  1091. if ($versions && is_array($versions)) {
  1092. $updateData['versions'] = json_encode($versions, 256);
  1093. }
  1094. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1095. DB::table('mp_products')
  1096. ->where('id', $existing_product->id)
  1097. ->update($updateData);
  1098. $product_id = $existing_product->id;
  1099. } else {
  1100. // 创建新资产
  1101. $versions = getProp($target_roles, 'versions', []);
  1102. $product_id = DB::table('mp_products')->insertGetId([
  1103. 'user_id' => $uid,
  1104. 'cpid' => $cpid,
  1105. 'type' => 1, // 资产
  1106. 'product' => $product_type, // 角色
  1107. 'parent_id' => $folder_id,
  1108. 'level' => 2,
  1109. 'product_name' => $product_name,
  1110. 'url' => $url,
  1111. 'pic_prompt' => $pic_prompt,
  1112. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1113. 'sort_order' => time(),
  1114. 'is_deleted' => 0,
  1115. 'pic_task_status' => '生成成功',
  1116. 'created_at' => date('Y-m-d H:i:s'),
  1117. 'updated_at' => date('Y-m-d H:i:s')
  1118. ]);
  1119. }
  1120. // 建立或更新绑定关系
  1121. $existing_mapping = DB::table('mp_script_product_mappings')
  1122. ->where('script_id', $script_id)
  1123. ->where('product_id', $product_id)
  1124. ->where('episode_number', $episode_number)
  1125. ->first();
  1126. if (!$existing_mapping) {
  1127. // 创建绑定关系
  1128. DB::table('mp_script_product_mappings')->insert([
  1129. 'script_id' => $script_id,
  1130. 'product_id' => $product_id,
  1131. 'episode_number' => $episode_number,
  1132. 'created_at' => date('Y-m-d H:i:s'),
  1133. 'updated_at' => date('Y-m-d H:i:s')
  1134. ]);
  1135. }
  1136. }
  1137. }
  1138. }
  1139. } catch (\Exception $e) {
  1140. dLog('anime')->error('更新剧集角色失败', [
  1141. 'anime_id' => $anime_id,
  1142. 'episode_id' => $episode_id,
  1143. 'error' => $e->getMessage()
  1144. ]);
  1145. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1146. }
  1147. return true;
  1148. }
  1149. public function changeEpisodeScenes($data) {
  1150. $anime_id = getProp($data, 'anime_id');
  1151. $episode_id = getProp($data, 'episode_id');
  1152. $target_scenes = getProp($data, 'scenes');
  1153. // 删除标志优先取最外层入参 is_deleted,兼容场景对象内部(scenes.is_deleted)的传参
  1154. $is_deleted = getProp($data, 'is_deleted', getProp($target_scenes, 'is_deleted', 0));
  1155. // 控制字段不随场景内容写入分集scenes存储
  1156. if (is_array($target_scenes)) {
  1157. unset($target_scenes['is_deleted']);
  1158. }
  1159. // 参数验证
  1160. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1161. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1162. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1163. // 验证剧集是否存在
  1164. $episode = DB::table('mp_anime_episodes')
  1165. ->where('anime_id', $anime_id)
  1166. ->where('id', $episode_id)
  1167. ->first();
  1168. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1169. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1170. // 获取anime信息,检查是否有关联的script_id
  1171. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1172. if (!$anime) Utils::throwError('20003:动漫不存在');
  1173. $script_id = getProp($anime, 'script_id');
  1174. $episode_number = getProp($episode, 'episode_number', 1);
  1175. $uid = Site::getUid();
  1176. $cpid = Site::getCpid();
  1177. try {
  1178. $target_scene_name = getProp($target_scenes, 'scene');
  1179. if (empty($target_scene_name)) {
  1180. Utils::throwError('20003:场景名称不能为空');
  1181. }
  1182. // 如果是删除操作
  1183. if ($is_deleted == 1) {
  1184. // 从场景列表中移除该场景
  1185. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1186. return getProp($scene, 'scene') !== $target_scene_name;
  1187. }));
  1188. // 更新场景列表
  1189. $result = DB::table('mp_anime_episodes')
  1190. ->where('anime_id', $anime_id)
  1191. ->where('id', $episode_id)
  1192. ->update([
  1193. 'scenes' => json_encode($scenes, 256),
  1194. 'updated_at' => date('Y-m-d H:i:s')
  1195. ]);
  1196. if ($result === false) {
  1197. Utils::throwError('20003:删除场景失败');
  1198. }
  1199. } else {
  1200. // 新增或更新操作
  1201. $scene_found = false;
  1202. $is_new_scene = false;
  1203. // 查找并更新已存在的场景
  1204. foreach($scenes as &$scene) {
  1205. if (getProp($scene, 'scene') === $target_scene_name) {
  1206. $scene = $target_scenes;
  1207. $scene_found = true;
  1208. break;
  1209. }
  1210. }
  1211. // 如果场景不存在,则新增
  1212. if (!$scene_found) {
  1213. $scenes[] = $target_scenes;
  1214. $is_new_scene = true;
  1215. }
  1216. // 更新场景列表
  1217. $result = DB::table('mp_anime_episodes')
  1218. ->where('anime_id', $anime_id)
  1219. ->where('id', $episode_id)
  1220. ->update([
  1221. 'scenes' => json_encode($scenes, 256),
  1222. 'updated_at' => date('Y-m-d H:i:s')
  1223. ]);
  1224. if ($result === false) {
  1225. Utils::throwError('20003:更新场景列表失败');
  1226. }
  1227. // 如果有关联的script_id,则同步到mp_products表
  1228. if ($script_id) {
  1229. // 查询剧本信息
  1230. $script = DB::table('mp_scripts')
  1231. ->where('id', $script_id)
  1232. ->where('is_deleted', 0)
  1233. ->first();
  1234. if ($script) {
  1235. $script_name = $script->script_name ?? 'script_' . $script_id;
  1236. $product_name = getProp($target_scenes, 'scene');
  1237. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1238. $url = getProp($target_scenes, 'url', '');
  1239. $product_type = 2; // 2=场景
  1240. // 查找或创建以script_name命名的文件夹
  1241. $folder = DB::table('mp_products')
  1242. ->where('cpid', $cpid)
  1243. ->where('type', 2) // 文件夹类型
  1244. ->where('product', $product_type) // 场景类型
  1245. ->where('product_name', $script_name)
  1246. ->where('parent_id', 0)
  1247. ->where('is_deleted', 0)
  1248. ->first();
  1249. if (!$folder) {
  1250. // 创建文件夹
  1251. $folder_id = DB::table('mp_products')->insertGetId([
  1252. 'user_id' => $uid,
  1253. 'cpid' => $cpid,
  1254. 'type' => 2, // 文件夹
  1255. 'product' => $product_type, // 场景类型
  1256. 'parent_id' => 0,
  1257. 'level' => 1,
  1258. 'product_name' => $script_name,
  1259. 'sort_order' => time(),
  1260. 'is_deleted' => 0,
  1261. 'created_at' => date('Y-m-d H:i:s'),
  1262. 'updated_at' => date('Y-m-d H:i:s')
  1263. ]);
  1264. } else {
  1265. $folder_id = $folder->id;
  1266. }
  1267. // 查找该文件夹下是否已存在同名资产
  1268. $existing_product = DB::table('mp_products')
  1269. ->where('cpid', $cpid)
  1270. ->where('type', 1) // 资产类型
  1271. ->where('product', $product_type)
  1272. ->where('parent_id', $folder_id)
  1273. ->where('product_name', $product_name)
  1274. ->where('is_deleted', 0)
  1275. ->first();
  1276. if ($existing_product) {
  1277. // 更新已存在的资产
  1278. $updateData = [
  1279. 'pic_task_status' => '生成成功'
  1280. ];
  1281. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1282. if ($url) $updateData['url'] = $url;
  1283. // 处理versions字段
  1284. $versions = getProp($target_scenes, 'versions', []);
  1285. if ($versions && is_array($versions)) {
  1286. $updateData['versions'] = json_encode($versions, 256);
  1287. }
  1288. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1289. DB::table('mp_products')
  1290. ->where('id', $existing_product->id)
  1291. ->update($updateData);
  1292. $product_id = $existing_product->id;
  1293. } else {
  1294. // 创建新资产
  1295. $versions = getProp($target_scenes, 'versions', []);
  1296. $product_id = DB::table('mp_products')->insertGetId([
  1297. 'user_id' => $uid,
  1298. 'cpid' => $cpid,
  1299. 'type' => 1, // 资产
  1300. 'product' => $product_type, // 场景
  1301. 'parent_id' => $folder_id,
  1302. 'level' => 2,
  1303. 'product_name' => $product_name,
  1304. 'url' => $url,
  1305. 'pic_prompt' => $pic_prompt,
  1306. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1307. 'sort_order' => time(),
  1308. 'is_deleted' => 0,
  1309. 'pic_task_status' => '生成成功',
  1310. 'created_at' => date('Y-m-d H:i:s'),
  1311. 'updated_at' => date('Y-m-d H:i:s')
  1312. ]);
  1313. }
  1314. // 建立或更新绑定关系
  1315. $existing_mapping = DB::table('mp_script_product_mappings')
  1316. ->where('script_id', $script_id)
  1317. ->where('product_id', $product_id)
  1318. ->where('episode_number', $episode_number)
  1319. ->first();
  1320. if (!$existing_mapping) {
  1321. // 创建绑定关系
  1322. DB::table('mp_script_product_mappings')->insert([
  1323. 'script_id' => $script_id,
  1324. 'product_id' => $product_id,
  1325. 'episode_number' => $episode_number,
  1326. 'created_at' => date('Y-m-d H:i:s'),
  1327. 'updated_at' => date('Y-m-d H:i:s')
  1328. ]);
  1329. }
  1330. }
  1331. }
  1332. }
  1333. } catch (\Exception $e) {
  1334. dLog('anime')->error('更新剧集场景失败', [
  1335. 'anime_id' => $anime_id,
  1336. 'episode_id' => $episode_id,
  1337. 'error' => $e->getMessage()
  1338. ]);
  1339. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1340. }
  1341. return true;
  1342. }
  1343. public function changeEpisodeProps($data) {
  1344. $anime_id = getProp($data, 'anime_id');
  1345. $episode_id = getProp($data, 'episode_id');
  1346. $target_props = getProp($data, 'props');
  1347. // 删除标志优先取最外层入参 is_deleted,兼容道具对象内部(props.is_deleted)的传参
  1348. $is_deleted = getProp($data, 'is_deleted', getProp($target_props, 'is_deleted', 0));
  1349. // 控制字段不随道具内容写入分集props存储
  1350. if (is_array($target_props)) {
  1351. unset($target_props['is_deleted']);
  1352. }
  1353. // 参数验证
  1354. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1355. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1356. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1357. // 验证剧集是否存在
  1358. $episode = DB::table('mp_anime_episodes')
  1359. ->where('anime_id', $anime_id)
  1360. ->where('id', $episode_id)
  1361. ->first();
  1362. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1363. $props = json_decode(getProp($episode, 'props'), true);
  1364. // 获取anime信息,检查是否有关联的script_id
  1365. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1366. if (!$anime) Utils::throwError('20003:动漫不存在');
  1367. $script_id = getProp($anime, 'script_id');
  1368. $episode_number = getProp($episode, 'episode_number', 1);
  1369. $uid = Site::getUid();
  1370. $cpid = Site::getCpid();
  1371. try {
  1372. $target_prop_name = getProp($target_props, 'prop');
  1373. if (empty($target_prop_name)) {
  1374. Utils::throwError('20003:道具名称不能为空');
  1375. }
  1376. // 如果是删除操作
  1377. if ($is_deleted == 1) {
  1378. // 从道具列表中移除该道具
  1379. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1380. return getProp($prop, 'prop') !== $target_prop_name;
  1381. }));
  1382. // 更新道具列表
  1383. $result = DB::table('mp_anime_episodes')
  1384. ->where('anime_id', $anime_id)
  1385. ->where('id', $episode_id)
  1386. ->update([
  1387. 'props' => json_encode($props, 256),
  1388. 'updated_at' => date('Y-m-d H:i:s')
  1389. ]);
  1390. if ($result === false) {
  1391. Utils::throwError('20003:删除道具失败');
  1392. }
  1393. } else {
  1394. // 新增或更新操作
  1395. $prop_found = false;
  1396. $is_new_prop = false;
  1397. // 查找并更新已存在的道具
  1398. foreach($props as &$prop) {
  1399. if (getProp($prop, 'prop') === $target_prop_name) {
  1400. $prop = $target_props;
  1401. $prop_found = true;
  1402. break;
  1403. }
  1404. }
  1405. // 如果道具不存在,则新增
  1406. if (!$prop_found) {
  1407. $props[] = $target_props;
  1408. $is_new_prop = true;
  1409. }
  1410. // 更新道具列表
  1411. $result = DB::table('mp_anime_episodes')
  1412. ->where('anime_id', $anime_id)
  1413. ->where('id', $episode_id)
  1414. ->update([
  1415. 'props' => json_encode($props, 256),
  1416. 'updated_at' => date('Y-m-d H:i:s')
  1417. ]);
  1418. if ($result === false) {
  1419. Utils::throwError('20003:更新道具列表失败');
  1420. }
  1421. // 如果有关联的script_id,则同步到mp_products表
  1422. if ($script_id) {
  1423. // 查询剧本信息
  1424. $script = DB::table('mp_scripts')
  1425. ->where('id', $script_id)
  1426. ->where('is_deleted', 0)
  1427. ->first();
  1428. if ($script) {
  1429. $script_name = $script->script_name ?? 'script_' . $script_id;
  1430. $product_name = getProp($target_props, 'prop');
  1431. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1432. $url = getProp($target_props, 'url', '');
  1433. $product_type = 3; // 3=道具
  1434. // 查找或创建以script_name命名的文件夹
  1435. $folder = DB::table('mp_products')
  1436. ->where('cpid', $cpid)
  1437. ->where('type', 2) // 文件夹类型
  1438. ->where('product', $product_type) // 道具类型
  1439. ->where('product_name', $script_name)
  1440. ->where('parent_id', 0)
  1441. ->where('is_deleted', 0)
  1442. ->first();
  1443. if (!$folder) {
  1444. // 创建文件夹
  1445. $folder_id = DB::table('mp_products')->insertGetId([
  1446. 'user_id' => $uid,
  1447. 'cpid' => $cpid,
  1448. 'type' => 2, // 文件夹
  1449. 'product' => $product_type, // 道具类型
  1450. 'parent_id' => 0,
  1451. 'level' => 1,
  1452. 'product_name' => $script_name,
  1453. 'sort_order' => time(),
  1454. 'is_deleted' => 0,
  1455. 'created_at' => date('Y-m-d H:i:s'),
  1456. 'updated_at' => date('Y-m-d H:i:s')
  1457. ]);
  1458. } else {
  1459. $folder_id = $folder->id;
  1460. }
  1461. // 查找该文件夹下是否已存在同名资产
  1462. $existing_product = DB::table('mp_products')
  1463. ->where('cpid', $cpid)
  1464. ->where('type', 1) // 资产类型
  1465. ->where('product', $product_type)
  1466. ->where('parent_id', $folder_id)
  1467. ->where('product_name', $product_name)
  1468. ->where('is_deleted', 0)
  1469. ->first();
  1470. if ($existing_product) {
  1471. // 更新已存在的资产
  1472. $updateData = [
  1473. 'pic_task_status' => '生成成功'
  1474. ];
  1475. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1476. if ($url) $updateData['url'] = $url;
  1477. // 处理versions字段
  1478. $versions = getProp($target_props, 'versions', []);
  1479. if ($versions && is_array($versions)) {
  1480. $updateData['versions'] = json_encode($versions, 256);
  1481. }
  1482. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1483. DB::table('mp_products')
  1484. ->where('id', $existing_product->id)
  1485. ->update($updateData);
  1486. $product_id = $existing_product->id;
  1487. } else {
  1488. // 创建新资产
  1489. $versions = getProp($target_props, 'versions', []);
  1490. $product_id = DB::table('mp_products')->insertGetId([
  1491. 'user_id' => $uid,
  1492. 'cpid' => $cpid,
  1493. 'type' => 1, // 资产
  1494. 'product' => $product_type, // 道具
  1495. 'parent_id' => $folder_id,
  1496. 'level' => 2,
  1497. 'product_name' => $product_name,
  1498. 'url' => $url,
  1499. 'pic_prompt' => $pic_prompt,
  1500. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1501. 'sort_order' => time(),
  1502. 'is_deleted' => 0,
  1503. 'pic_task_status' => '生成成功',
  1504. 'created_at' => date('Y-m-d H:i:s'),
  1505. 'updated_at' => date('Y-m-d H:i:s')
  1506. ]);
  1507. }
  1508. // 建立或更新绑定关系
  1509. $existing_mapping = DB::table('mp_script_product_mappings')
  1510. ->where('script_id', $script_id)
  1511. ->where('product_id', $product_id)
  1512. ->where('episode_number', $episode_number)
  1513. ->first();
  1514. if (!$existing_mapping) {
  1515. // 创建绑定关系
  1516. DB::table('mp_script_product_mappings')->insert([
  1517. 'script_id' => $script_id,
  1518. 'product_id' => $product_id,
  1519. 'episode_number' => $episode_number,
  1520. 'created_at' => date('Y-m-d H:i:s'),
  1521. 'updated_at' => date('Y-m-d H:i:s')
  1522. ]);
  1523. }
  1524. }
  1525. }
  1526. }
  1527. } catch (\Exception $e) {
  1528. dLog('anime')->error('更新剧集道具失败', [
  1529. 'anime_id' => $anime_id,
  1530. 'episode_id' => $episode_id,
  1531. 'error' => $e->getMessage()
  1532. ]);
  1533. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1534. }
  1535. return true;
  1536. }
  1537. public function editSegment($data) {
  1538. $segment_id = getProp($data, 'segment_id');
  1539. $segment_content = getProp($data, 'segment_content');
  1540. $image_url = getProp($data, 'image_url');
  1541. $video_url = getProp($data, 'video_url');
  1542. // 参数验证
  1543. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1544. // 验证分镜是否存在
  1545. $segment = DB::table('mp_episode_segments')
  1546. ->where('segment_id', $segment_id)
  1547. ->first();
  1548. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1549. $dubTaskId = 0;
  1550. try {
  1551. DB::beginTransaction();
  1552. // 准备更新数据
  1553. $update_data = [
  1554. 'updated_at' => date('Y-m-d H:i:s')
  1555. ];
  1556. if ($segment_content) {
  1557. // 先将segment_content赋值到update_data
  1558. $update_data['segment_content'] = $segment_content;
  1559. // 使用现有方法分析segment_content,提取各个字段
  1560. $this->handleSegmentContent($update_data);
  1561. // 如果有对话内容,创建视频配音合成任务
  1562. $dialogue = getProp($update_data, 'dialogue');
  1563. if (!empty($dialogue)) {
  1564. $now = date('Y-m-d H:i:s');
  1565. $generate_json = [
  1566. 'text' => $dialogue,
  1567. 'role' => getProp($update_data, 'voice_actor'),
  1568. 'voice_type' => getProp($update_data, 'voice_type'),
  1569. 'voice_name' => getProp($update_data, 'voice_name'),
  1570. 'emotion' => getProp($update_data, 'emotion'),
  1571. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1572. 'gender' => getProp($update_data, 'gender'),
  1573. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1574. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1575. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1576. 'pitch' => getProp($update_data, 'pitch', 0),
  1577. ];
  1578. // 插入视频配音合成任务
  1579. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1580. 'alias_segment_id' => $segment_id,
  1581. 'generate_status' => '执行中',
  1582. 'audio_url' => '',
  1583. 'generate_json' => json_encode($generate_json, 256),
  1584. 'created_at' => $now,
  1585. 'updated_at' => $now,
  1586. ]);
  1587. if (!$dubTaskId) {
  1588. Utils::throwError('20003:创建配音任务失败!');
  1589. }
  1590. $update_data['audio_url'] = '';
  1591. } else {
  1592. // dialogue为空时,直接写入默认音频信息
  1593. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1594. $update_data['audio_duration'] = 2.0;
  1595. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1596. }
  1597. }
  1598. if ($image_url) {
  1599. $update_data['img_url'] = $image_url;
  1600. // 同时写入一个简单的图片生成任务
  1601. $pic_task = [
  1602. 'alias_segment_id' => $segment_id,
  1603. 'ref_img_url' => json_encode([]),
  1604. 'status' => 'success',
  1605. 'result_url' => json_encode([$image_url], 256),
  1606. 'model' => '',
  1607. 'created_at' => date('Y-m-d H:i:s'),
  1608. 'updated_at' => date('Y-m-d H:i:s'),
  1609. ];
  1610. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1611. }
  1612. if ($video_url) {
  1613. $update_data['origin_video_url'] = $video_url;
  1614. $compressed_video_url = compressVideo($video_url);
  1615. $update_data['current_type'] = 2;
  1616. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1617. // 同时写入一个简单的视频生成任务
  1618. $video_task = [
  1619. 'alias_segment_id' => $segment_id,
  1620. 'status' => 'success',
  1621. 'result_url' => $update_data['origin_video_url'],
  1622. 'compressed_url' => $update_data['video_url'],
  1623. 'created_at' => date('Y-m-d H:i:s'),
  1624. 'updated_at' => date('Y-m-d H:i:s'),
  1625. ];
  1626. DB::table('mp_generate_video_tasks')->insert($video_task);
  1627. }
  1628. // 更新分镜信息
  1629. $result = DB::table('mp_episode_segments')
  1630. ->where('segment_id', $segment_id)
  1631. ->update($update_data);
  1632. if ($result === false) {
  1633. Utils::throwError('20003:更新分镜剧本失败');
  1634. }
  1635. DB::commit();
  1636. // 如果有创建音频生成任务则调用API
  1637. if ($dubTaskId) {
  1638. // 请求远程服务器执行生成
  1639. $client = new Client(['timeout' => 300, 'verify' => false]);
  1640. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1641. $response = $result->getBody()->getContents();
  1642. $response_arr = json_decode($response, true);
  1643. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1644. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1645. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1646. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1647. Utils::throwError('20003:火山生成音频失败');
  1648. }
  1649. }
  1650. return true;
  1651. } catch (\Exception $e) {
  1652. DB::rollBack();
  1653. dLog('anime')->error('更新分镜剧本失败', [
  1654. 'segment_id' => $segment_id,
  1655. 'error' => $e->getMessage()
  1656. ]);
  1657. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1658. }
  1659. }
  1660. public function batchSetSegmentPics($data) {
  1661. $anime_id = getProp($data, 'anime_id');
  1662. $episode_id = getProp($data, 'episode_id');
  1663. $ratio = getProp($data, 'ratio');
  1664. $dimensions = $this->getRatioDimensions($ratio);
  1665. $width = $dimensions['width'];
  1666. $height = $dimensions['height'];
  1667. if (!$anime_id || !$episode_id) {
  1668. Utils::throwError('1002:请选择剧集');
  1669. }
  1670. // 获取剧集信息
  1671. $episode = DB::table('mp_anime_episodes')
  1672. ->where('anime_id', $anime_id)
  1673. ->where('id', $episode_id)
  1674. ->where('is_default', 1)
  1675. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1676. ->first();
  1677. if (!$episode) {
  1678. Utils::throwError('20003:该剧集不存在');
  1679. }
  1680. $model = getProp($data, 'model');
  1681. if (!$model) {
  1682. $model = getProp($episode, 'image_model');
  1683. if (!$model) {
  1684. // episode表也没有,使用默认值
  1685. $model = 'gpt-image-2';
  1686. }
  1687. }
  1688. // 验证模型是否在可用模型表中
  1689. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1690. $model = 'gpt-image-2';
  1691. }
  1692. $roles = json_decode(getProp($episode, 'roles'), true);
  1693. if (!$roles) {
  1694. Utils::throwError('20003:角色信息格式错误');
  1695. }
  1696. // 构建角色名称到参考图的映射
  1697. $role_map = [];
  1698. foreach ($roles as $role) {
  1699. $role_name = getProp($role, 'role');
  1700. $role_url = getProp($role, 'url');
  1701. if (!empty($role_name) && !empty($role_url)) {
  1702. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1703. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1704. // $role_map[$base_name] = $role_url;
  1705. // 同时保存完整名称的映射
  1706. $role_map[$role_name] = $role_url;
  1707. }
  1708. }
  1709. $scenes = json_decode(getProp($episode, 'roles'), true);
  1710. if (!$scenes) {
  1711. Utils::throwError('20003:场景信息格式错误');
  1712. }
  1713. // 构建角色名称到参考图的映射
  1714. $scene_map = [];
  1715. foreach ($scenes as $scene) {
  1716. $scene_name = getProp($scene, 'scene');
  1717. $scene_url = getProp($scene, 'url');
  1718. if (!empty($scene_name) && !empty($scene_url)) {
  1719. $scene_map[$scene_name] = $scene_url;
  1720. }
  1721. }
  1722. // 获取所有分镜信息
  1723. $segments = DB::table('mp_episode_segments')
  1724. ->where('anime_id', $anime_id)
  1725. ->where('episode_id', $episode_id)
  1726. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1727. ->orderBy('segment_number')
  1728. ->get()
  1729. ->toArray();
  1730. if (empty($segments)) {
  1731. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1732. }
  1733. // 保存图片比例
  1734. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1735. $updated_segments = [];
  1736. $failed_segments = [];
  1737. // 批量为每个分镜生成图片任务
  1738. foreach ($segments as $segment) {
  1739. $segment_id = $segment->segment_id;
  1740. $segment_content = $segment->segment_content;
  1741. if (empty($segment_content)) {
  1742. $failed_segments[] = [
  1743. 'segment_id' => $segment_id,
  1744. 'error' => '分镜内容为空'
  1745. ];
  1746. continue;
  1747. }
  1748. try {
  1749. $dubTaskId = 0;
  1750. // 解析分镜内容,提取画面描述作为主要提示词
  1751. $prompt = $segment_content;
  1752. $ref_img_urls = [];
  1753. // 分镜场景
  1754. $scene = getProp($segment, 'scene');
  1755. $matched_scene = '';
  1756. if (isset($scene_map[$scene])) {
  1757. $img_index = count($ref_img_urls) + 1;
  1758. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1759. $ref_img_urls[] = $scene_map[$scene];
  1760. $matched_scene = $scene;
  1761. }
  1762. // 分镜角色
  1763. $characters = getProp($segment, 'characters');
  1764. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1765. $roles = explode(',', $characters);
  1766. // 从分镜内容中提取涉及的角色
  1767. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1768. // 获取匹配角色的参考图
  1769. foreach ($segment_characters as $character) {
  1770. if (isset($role_map[$character])) {
  1771. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1772. $img_index = count($ref_img_urls) + 1;
  1773. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1774. $ref_img_urls[] = $role_map[$character];
  1775. }
  1776. }
  1777. // 如果没有找到匹配的角色参考图,不使用参考图
  1778. if (empty($ref_img_urls)) {
  1779. $ref_img_urls = [];
  1780. }
  1781. // 准备生成任务参数
  1782. $params = [
  1783. 'model' => $model,
  1784. 'alias_segment_id' => $segment_id,
  1785. 'prompt' => $prompt,
  1786. 'ref_img_urls' => $ref_img_urls,
  1787. 'width' => $width,
  1788. 'height' => $height,
  1789. ];
  1790. // 优化提示词(不要生成字幕)
  1791. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1792. // $task_id = mt_rand(100000, 999999);
  1793. // 调用AI图片生成服务
  1794. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1795. $task_id = $task->id;
  1796. if (!$task_id) {
  1797. $failed_segments[] = [
  1798. 'segment_id' => $segment_id,
  1799. 'error' => '创建生成任务失败'
  1800. ];
  1801. continue;
  1802. }
  1803. $update_data = [
  1804. 'pic_task_id' => $task_id,
  1805. 'pic_task_status' => '生成中',
  1806. 'audio_url' => '',
  1807. 'updated_at' => date('Y-m-d H:i:s')
  1808. ];
  1809. // 如果有对话内容,创建视频配音合成任务
  1810. $dialogue = getProp($segment, 'dialogue');
  1811. if (!empty($dialogue)) {
  1812. $now = date('Y-m-d H:i:s');
  1813. $generate_json = [
  1814. 'text' => $dialogue,
  1815. 'role' => getProp($segment, 'voice_actor'),
  1816. 'voice_type' => getProp($segment, 'voice_type'),
  1817. 'voice_name' => getProp($segment, 'voice_name'),
  1818. 'emotion' => getProp($segment, 'emotion'),
  1819. 'emotion_type' => getProp($segment, 'emotion_type'),
  1820. 'gender' => getProp($segment, 'gender'),
  1821. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1822. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1823. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1824. 'pitch' => getProp($segment, 'pitch', 0),
  1825. ];
  1826. // 插入视频配音合成任务
  1827. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1828. 'alias_segment_id' => $segment_id,
  1829. 'generate_status' => '执行中',
  1830. 'audio_url' => '',
  1831. 'generate_json' => json_encode($generate_json, 256),
  1832. 'created_at' => $now,
  1833. 'updated_at' => $now,
  1834. ]);
  1835. if (!$dubTaskId) {
  1836. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1837. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1838. // Utils::throwError('20003:创建配音任务失败!');
  1839. }
  1840. } else {
  1841. // dialogue为空时,直接写入默认音频信息到分镜表
  1842. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1843. $update_data['audio_duration'] = 2.0;
  1844. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1845. }
  1846. // 更新分镜的任务信息
  1847. $update_result = DB::table('mp_episode_segments')
  1848. ->where('segment_id', $segment_id)
  1849. ->update($update_data);
  1850. // 如果是第一集的首帧图片,则存入待更新数组
  1851. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1852. Redis::sadd('anime_first_frame_urls', $segment_id);
  1853. }
  1854. if ($update_result) {
  1855. $updated_segments[] = [
  1856. 'segment_id' => $segment_id,
  1857. 'task_id' => $task_id,
  1858. 'status' => '生成中',
  1859. 'matched_scenes' => $matched_scene,
  1860. 'matched_roles' => $segment_characters,
  1861. 'ref_urls_count' => count($ref_img_urls)
  1862. ];
  1863. } else {
  1864. $failed_segments[] = [
  1865. 'segment_id' => $segment_id,
  1866. 'error' => '更新分镜任务状态失败'
  1867. ];
  1868. }
  1869. if ($dubTaskId) {
  1870. sleep(1);
  1871. // 请求远程服务器执行生成
  1872. $client = new Client(['timeout' => 300, 'verify' => false]);
  1873. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1874. $response = $result->getBody()->getContents();
  1875. $response_arr = json_decode($response, true);
  1876. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1877. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1878. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1879. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1880. }
  1881. }
  1882. } catch (\Exception $e) {
  1883. $failed_segments[] = [
  1884. 'segment_id' => $segment_id,
  1885. 'error' => $e->getMessage()
  1886. ];
  1887. }
  1888. }
  1889. // 更新剧集生成状态
  1890. if (!empty($updated_segments)) {
  1891. DB::table('mp_anime_episodes')
  1892. ->where('id', $episode_id)
  1893. ->update([
  1894. 'is_generated' => 1,
  1895. 'updated_at' => date('Y-m-d H:i:s')
  1896. ]);
  1897. }
  1898. return [
  1899. 'success_count' => count($updated_segments),
  1900. 'failed_count' => count($failed_segments),
  1901. 'success_segments' => $updated_segments,
  1902. 'failed_segments' => $failed_segments,
  1903. 'total_segments' => count($segments)
  1904. ];
  1905. }
  1906. public function reGenerateSegment($data) {
  1907. $segment_id = getProp($data, 'segment_id');
  1908. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1909. $anime_id = getProp($segment, 'anime_id');
  1910. $episode_id = getProp($segment, 'episode_id');
  1911. $episode_number = getProp($segment, 'episode_number');
  1912. $segment_content = getProp($data, 'segment_content');
  1913. $ratio = getProp($data, 'ratio');
  1914. if (!$ratio) {
  1915. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1916. if (!$ratio) $ratio = '9:16';
  1917. }
  1918. $dimensions = $this->getRatioDimensions($ratio);
  1919. $width = $dimensions['width'];
  1920. $height = $dimensions['height'];
  1921. if (!$anime_id || !$episode_id) {
  1922. Utils::throwError('1002:请选择分镜');
  1923. }
  1924. // 使用文生文模型重新解析segment_content
  1925. if (!empty($segment_content)) {
  1926. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1927. }
  1928. // 获取动漫的角色信息(包含参考图)
  1929. $anime = DB::table('mp_animes')
  1930. ->where('id', $anime_id)
  1931. ->select('roles', 'scenes')
  1932. ->first();
  1933. if (!$anime || !$anime->roles) {
  1934. Utils::throwError('20003:未找到角色信息');
  1935. }
  1936. $roles = json_decode($anime->roles, true);
  1937. if (!$roles) {
  1938. Utils::throwError('20003:角色信息格式错误');
  1939. }
  1940. // 构建角色名称到参考图的映射
  1941. $role_map = [];
  1942. foreach ($roles as $role) {
  1943. $role_name = getProp($role, 'role');
  1944. $role_url = getProp($role, 'url');
  1945. if (!empty($role_name) && !empty($role_url)) {
  1946. $role_map[$role_name] = $role_url;
  1947. }
  1948. }
  1949. $scenes = json_decode($anime->scenes, true);
  1950. if (!$scenes) {
  1951. Utils::throwError('20003:角色信息格式错误');
  1952. }
  1953. // 构建角色名称到参考图的映射
  1954. $scene_map = [];
  1955. foreach ($scenes as $scene) {
  1956. $scene_name = getProp($scene, 'scene');
  1957. $scene_url = getProp($scene, 'url');
  1958. if (!empty($scene_name) && !empty($scene_url)) {
  1959. $scene_map[$scene_name] = $scene_url;
  1960. }
  1961. }
  1962. $segment_id = $segment->segment_id;
  1963. $original_segment_content = $segment->segment_content;
  1964. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1965. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1966. if (empty($final_segment_content)) {
  1967. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1968. }
  1969. try {
  1970. $dubTaskId = 0;
  1971. // 分镜剧本数组
  1972. $update_data = [
  1973. 'segment_content' => $final_segment_content,
  1974. 'pic_task_status' => '生成中',
  1975. 'updated_at' => date('Y-m-d H:i:s')
  1976. ];
  1977. // 解析分镜内容,提取画面描述作为主要提示词
  1978. $prompt = $final_segment_content;
  1979. $ref_img_urls = [];
  1980. // 分镜场景
  1981. $scene = getProp($data, 'scene');
  1982. if ($scene) {
  1983. $matched_scene = '';
  1984. if (isset($scene_map[$scene])) {
  1985. $img_index = count($ref_img_urls) + 1;
  1986. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1987. $ref_img_urls[] = $scene_map[$scene];
  1988. $matched_scene = $scene;
  1989. }
  1990. $update_data['scene'] = $scene;
  1991. }
  1992. // 分镜角色
  1993. $characters = getProp($data, 'characters');
  1994. if ($characters) {
  1995. $update_data['characters'] = $characters;
  1996. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1997. $characters = explode(',', $characters);
  1998. // 从分镜内容中提取涉及的角色
  1999. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2000. // 获取匹配角色的参考图
  2001. foreach ($segment_characters as $character) {
  2002. if (isset($role_map[$character])) {
  2003. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2004. $img_index = count($ref_img_urls) + 1;
  2005. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2006. $ref_img_urls[] = $role_map[$character];
  2007. }
  2008. }
  2009. }
  2010. // 如果没有找到匹配的角色参考图,不使用参考图
  2011. if (empty($ref_img_urls)) {
  2012. $ref_img_urls = [];
  2013. }
  2014. // 准备生成任务参数
  2015. $params = [
  2016. 'alias_segment_id' => $segment_id,
  2017. 'prompt' => $prompt,
  2018. 'ref_img_urls' => $ref_img_urls,
  2019. 'width' => $width,
  2020. 'height' => $height,
  2021. ];
  2022. // 优化提示词(不要生成字幕)
  2023. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  2024. // 调用AI图片生成服务
  2025. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2026. $task_id = $task->id;
  2027. if (!$task_id) {
  2028. Utils::throwError('20003:创建生成任务失败!');
  2029. }
  2030. $update_data['pic_task_id'] = $task_id;
  2031. // 更新分镜剧本信息
  2032. $this->handleSegmentContent($update_data);
  2033. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2034. if ($segment_content) {
  2035. $dialogue = getProp($update_data, 'dialogue');
  2036. if (!empty($dialogue)) {
  2037. $now = date('Y-m-d H:i:s');
  2038. $generate_json = [
  2039. 'text' => $dialogue,
  2040. 'role' => getProp($update_data, 'voice_actor'),
  2041. 'voice_type' => getProp($update_data, 'voice_type'),
  2042. 'voice_name' => getProp($update_data, 'voice_name'),
  2043. 'emotion' => getProp($update_data, 'emotion'),
  2044. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2045. 'gender' => getProp($update_data, 'gender'),
  2046. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2047. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2048. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2049. 'pitch' => getProp($update_data, 'pitch', 0),
  2050. ];
  2051. // 插入视频配音合成任务
  2052. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2053. 'alias_segment_id' => $segment_id,
  2054. 'generate_status' => '执行中',
  2055. 'audio_url' => '',
  2056. 'generate_json' => json_encode($generate_json, 256),
  2057. 'created_at' => date('Y-m-d H:i:s'),
  2058. 'updated_at' => date('Y-m-d H:i:s'),
  2059. ]);
  2060. if (!$dubTaskId) {
  2061. Utils::throwError('20003:创建配音任务失败!');
  2062. }
  2063. $update_data['audio_url'] = '';
  2064. } else {
  2065. // dialogue为空时,直接写入默认音频信息
  2066. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2067. $update_data['audio_duration'] = 2.0;
  2068. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2069. }
  2070. }
  2071. $boolen = DB::table('mp_episode_segments')
  2072. ->where('segment_id', $segment_id)
  2073. ->update($update_data);
  2074. // 如果是第一集的首帧图片,则存入待更新数组
  2075. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2076. Redis::sadd('anime_first_frame_urls', $segment_id);
  2077. }
  2078. if ($dubTaskId) {
  2079. // 请求远程服务器执行生成
  2080. $client = new Client(['timeout' => 300, 'verify' => false]);
  2081. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2082. $response = $result->getBody()->getContents();
  2083. $response_arr = json_decode($response, true);
  2084. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2085. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2086. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2087. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2088. Utils::throwError('20003:火山生成音频失败');
  2089. }
  2090. }
  2091. } catch (\Exception $e) {
  2092. $failed_segments[] = [
  2093. 'segment_id' => $segment_id,
  2094. 'error' => $e->getMessage()
  2095. ];
  2096. }
  2097. // 创建任务之后先暂停10s等待异步任务完成
  2098. sleep(10);
  2099. $img_url = $this->loopGetPicTaskResult($task_id);
  2100. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2101. // 图片生成后新增对话记录
  2102. try {
  2103. $uid = Site::getUid();
  2104. $now = date('Y-m-d H:i:s');
  2105. // 使用AI反推图片提示词
  2106. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2107. // 保存对话记录
  2108. $records = [
  2109. [
  2110. 'uid' => $uid,
  2111. 'anime_id' => $anime_id,
  2112. 'sequence' => $episode_number,
  2113. 'role' => 'user',
  2114. 'content' => '重新生成',
  2115. 'segment_id' => $segment_id,
  2116. 'pic_task_id' => $task_id,
  2117. 'image_url' => '',
  2118. 'created_at' => $now,
  2119. 'updated_at' => $now
  2120. ],
  2121. [
  2122. 'uid' => $uid,
  2123. 'anime_id' => $anime_id,
  2124. 'sequence' => $episode_number,
  2125. 'role' => 'assistant',
  2126. 'content' => $pic_prompt,
  2127. 'segment_id' => $segment_id,
  2128. 'pic_task_id' => $task_id,
  2129. 'image_url' => $img_url,
  2130. 'created_at' => $now,
  2131. 'updated_at' => $now
  2132. ]
  2133. ];
  2134. DB::table('mp_anime_records')->insert($records);
  2135. } catch (\Exception $e) {
  2136. // 记录日志但不影响主流程
  2137. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2138. 'segment_id' => $segment_id,
  2139. 'img_url' => $img_url
  2140. ]);
  2141. }
  2142. return $img_url;
  2143. }
  2144. public function addSegment($data) {
  2145. $prev_segment_id = getProp($data, 'prev_segment_id');
  2146. $img_url = getProp($data, 'img_url');
  2147. $video_url = getProp($data, 'video_url');
  2148. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2149. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2150. $anime_id = getProp($segment, 'anime_id');
  2151. $episode_id = getProp($segment, 'episode_id');
  2152. $episode_number = getProp($segment, 'episode_number');
  2153. $segment_number = getProp($segment, 'segment_number');
  2154. $new_segment_number = $segment_number + 1;
  2155. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2156. // 分镜剧本数组
  2157. $insert_data = [
  2158. 'anime_id' => $anime_id,
  2159. 'episode_id' => $episode_id,
  2160. 'episode_number' => $episode_number,
  2161. 'act_number' => getProp($segment, 'act_number'),
  2162. 'act_title' => getProp($segment, 'act_title'),
  2163. 'segment_id' => $segment_id,
  2164. 'segment_number' => $new_segment_number,
  2165. 'segment_content' => '',
  2166. 'img_url' => '',
  2167. 'video_url' => '',
  2168. 'created_at' => date('Y-m-d H:i:s'),
  2169. 'updated_at' => date('Y-m-d H:i:s')
  2170. ];
  2171. if ($img_url) $insert_data['img_url'] = $img_url;
  2172. if ($video_url) {
  2173. $insert_data['origin_video_url'] = $video_url;
  2174. $insert_data['current_type'] = 2;
  2175. $compressed_video_url = compressVideo($video_url);
  2176. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2177. }
  2178. try {
  2179. DB::beginTransaction();
  2180. // 先更新序号
  2181. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2182. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2183. if (!$id) {
  2184. Utils::throwError('20003:新增分镜失败!');
  2185. }
  2186. }catch (\Exception $e) {
  2187. DB::rollBack();
  2188. Utils::throwError('20003:'.$e->getMessage());
  2189. }
  2190. DB::commit();
  2191. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2192. $segment = $segment ? (array)$segment : [];
  2193. return $segment;
  2194. // 以下代码暂弃用
  2195. $anime_id = getProp($segment, 'anime_id');
  2196. $episode_id = getProp($segment, 'episode_id');
  2197. $episode_number = getProp($segment, 'episode_number');
  2198. $segment_number = getProp($segment, 'segment_number');
  2199. $segment_content = getProp($data, 'segment_content');
  2200. $img_url = getProp($data, 'img_url');
  2201. $video_url = getProp($data, 'video_url');
  2202. $ratio = getProp($data, 'ratio');
  2203. $dimensions = $this->getRatioDimensions($ratio);
  2204. $width = $dimensions['width'];
  2205. $height = $dimensions['height'];
  2206. if (!$anime_id || !$episode_id) {
  2207. Utils::throwError('1002:请选择分镜');
  2208. }
  2209. // 使用文生文模型重新解析segment_content
  2210. if (!empty($segment_content)) {
  2211. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2212. }
  2213. // 获取动漫的角色信息(包含参考图)
  2214. $anime = DB::table('mp_animes')
  2215. ->where('id', $anime_id)
  2216. ->select('roles', 'scenes')
  2217. ->first();
  2218. if (!$anime || !$anime->roles) {
  2219. Utils::throwError('20003:未找到角色信息');
  2220. }
  2221. $roles = json_decode($anime->roles, true);
  2222. if (!$roles) {
  2223. Utils::throwError('20003:角色信息格式错误');
  2224. }
  2225. // 构建角色名称到参考图的映射
  2226. $role_map = [];
  2227. foreach ($roles as $role) {
  2228. $role_name = getProp($role, 'role');
  2229. $role_url = getProp($role, 'url');
  2230. if (!empty($role_name) && !empty($role_url)) {
  2231. $role_map[$role_name] = $role_url;
  2232. }
  2233. }
  2234. $scenes = json_decode($anime->scenes, true);
  2235. if (!$scenes) {
  2236. Utils::throwError('20003:角色信息格式错误');
  2237. }
  2238. // 构建角色名称到参考图的映射
  2239. $scene_map = [];
  2240. foreach ($scenes as $scene) {
  2241. $scene_name = getProp($scene, 'scene');
  2242. $scene_url = getProp($scene, 'url');
  2243. if (!empty($scene_name) && !empty($scene_url)) {
  2244. $scene_map[$scene_name] = $scene_url;
  2245. }
  2246. }
  2247. $segment_id = $segment->segment_id;
  2248. $original_segment_content = $segment->segment_content;
  2249. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2250. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2251. if (empty($final_segment_content)) {
  2252. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2253. }
  2254. try {
  2255. $dubTaskId = 0;
  2256. DB::beginTransaction();
  2257. $new_segment_number = $segment_number + 1;
  2258. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2259. // 分镜剧本数组
  2260. $insert_data = [
  2261. 'anime_id' => $anime_id,
  2262. 'episode_id' => $episode_id,
  2263. 'episode_number' => $episode_number,
  2264. 'act_number' => getProp($segment, 'act_number'),
  2265. 'act_title' => getProp($segment, 'act_title'),
  2266. 'segment_id' => $segment_id,
  2267. 'segment_number' => $new_segment_number,
  2268. 'segment_content' => $final_segment_content,
  2269. 'img_url' => $img_url,
  2270. 'video_url' => $video_url,
  2271. 'created_at' => date('Y-m-d H:i:s'),
  2272. 'updated_at' => date('Y-m-d H:i:s')
  2273. ];
  2274. // 更新分镜剧本信息
  2275. $this->handleSegmentContent($insert_data);
  2276. // 如果有对话内容,创建视频配音合成任务
  2277. $dialogue = getProp($insert_data, 'dialogue');
  2278. if (!empty($dialogue)) {
  2279. $now = date('Y-m-d H:i:s');
  2280. $generate_json = [
  2281. 'text' => $dialogue,
  2282. 'role' => getProp($insert_data, 'voice_actor'),
  2283. 'voice_type' => getProp($insert_data, 'voice_type'),
  2284. 'voice_name' => getProp($insert_data, 'voice_name'),
  2285. 'emotion' => getProp($insert_data, 'emotion'),
  2286. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2287. 'gender' => getProp($insert_data, 'gender'),
  2288. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2289. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2290. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2291. 'pitch' => getProp($insert_data, 'pitch', 0),
  2292. ];
  2293. // 插入视频配音合成任务
  2294. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2295. 'alias_segment_id' => $segment_id,
  2296. 'generate_status' => '执行中',
  2297. 'audio_url' => '',
  2298. 'generate_json' => json_encode($generate_json, 256),
  2299. 'created_at' => $now,
  2300. 'updated_at' => $now,
  2301. ]);
  2302. if (!$dubTaskId) {
  2303. Utils::throwError('20003:创建配音任务失败!');
  2304. }
  2305. $insert_data['audio_url'] = '';
  2306. } else {
  2307. // dialogue为空时,直接写入默认音频信息
  2308. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2309. $insert_data['audio_duration'] = 2.0;
  2310. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2311. }
  2312. // 如果没有上传图片则使用当前描述进行生成
  2313. if (!$img_url) {
  2314. // 解析分镜内容,提取画面描述作为主要提示词
  2315. $prompt = $final_segment_content;
  2316. $ref_img_urls = [];
  2317. // 分镜场景
  2318. $scene = getProp($insert_data, 'scene');
  2319. if ($scene) {
  2320. $matched_scene = '';
  2321. if (isset($scene_map[$scene])) {
  2322. $img_index = count($ref_img_urls) + 1;
  2323. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2324. $ref_img_urls[] = $scene_map[$scene];
  2325. $matched_scene = $scene;
  2326. }
  2327. $update_data['scene'] = $scene;
  2328. }
  2329. // 分镜角色
  2330. $characters = getProp($insert_data, 'characters');
  2331. if ($characters) {
  2332. $update_data['characters'] = $characters;
  2333. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2334. $characters = explode(',', $characters);
  2335. // 从分镜内容中提取涉及的角色
  2336. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2337. // 获取匹配角色的参考图
  2338. foreach ($segment_characters as $character) {
  2339. if (isset($role_map[$character])) {
  2340. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2341. $img_index = count($ref_img_urls) + 1;
  2342. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2343. $ref_img_urls[] = $role_map[$character];
  2344. }
  2345. }
  2346. }
  2347. // 如果没有找到匹配的角色参考图,不使用参考图
  2348. if (empty($ref_img_urls)) {
  2349. $ref_img_urls = [];
  2350. }
  2351. // 准备生成任务参数
  2352. $params = [
  2353. 'alias_segment_id' => $segment_id,
  2354. 'prompt' => $prompt,
  2355. 'ref_img_urls' => $ref_img_urls,
  2356. 'width' => $width,
  2357. 'height' => $height,
  2358. ];
  2359. // 调用AI图片生成服务
  2360. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2361. $task_id = $task->id;
  2362. // $task_id = 'whatever';
  2363. if (!$task_id) {
  2364. Utils::throwError('20003:创建生成任务失败!');
  2365. }
  2366. $insert_data['pic_task_status'] = '生成中';
  2367. $insert_data['pic_task_id'] = $task_id;
  2368. }
  2369. // 先更新序号
  2370. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2371. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2372. if (!$boolen) {
  2373. Utils::throwError('20003:新增分镜失败!');
  2374. }
  2375. // 如果是第一集的首帧图片,则存入待更新数组
  2376. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2377. Redis::sadd('anime_first_frame_urls', $segment_id);
  2378. }
  2379. if ($dubTaskId) {
  2380. // 请求远程服务器执行生成
  2381. $client = new Client(['timeout' => 300, 'verify' => false]);
  2382. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2383. $response = $result->getBody()->getContents();
  2384. $response_arr = json_decode($response, true);
  2385. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2386. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2387. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2388. Utils::throwError('20003:火山生成音频失败');
  2389. }
  2390. }
  2391. } catch (\Exception $e) {
  2392. DB::rollBack();
  2393. Utils::throwError('20003:'.$e->getMessage());
  2394. }
  2395. DB::commit();
  2396. // 创建任务之后先暂停10s等待异步任务完成
  2397. sleep(10);
  2398. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2399. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2400. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2401. $segment = $segment ? (array)$segment : [];
  2402. return $segment;
  2403. }
  2404. public function copySegment($data) {
  2405. $segment_id = getProp($data, 'segment_id');
  2406. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2407. if (!$segment) Utils::throwError('20003:请选择分镜');
  2408. $anime_id = getProp($segment, 'anime_id');
  2409. $episode_id = getProp($segment, 'episode_id');
  2410. $episode_number = getProp($segment, 'episode_number');
  2411. $segment_number = getProp($segment, 'segment_number');
  2412. $new_segment_id = 0;
  2413. try {
  2414. DB::beginTransaction();
  2415. $segment = (array)$segment;
  2416. unset($segment['id']);
  2417. $segment['segment_number'] += 1;
  2418. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2419. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2420. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2421. // 更新其他分镜序号
  2422. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2423. // 复制分镜
  2424. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2425. if (!$id) {
  2426. Utils::throwError('20003:复制分镜失败');
  2427. }
  2428. }catch (\Exception $e) {
  2429. DB::rollBack();
  2430. Utils::throwError('20003:'.$e->getMessage());
  2431. }
  2432. DB::commit();
  2433. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2434. $segment = $segment ? (array)$segment : [];
  2435. return $segment;
  2436. }
  2437. public function moveSegment($data) {
  2438. $segment_id = getProp($data, 'segment_id');
  2439. $target_segment_id = getProp($data, 'target_segment_id');
  2440. // 获取源分镜信息
  2441. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2442. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2443. // 获取目标分镜信息
  2444. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2445. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2446. $anime_id = getProp($source_segment, 'anime_id');
  2447. $episode_id = getProp($source_segment, 'episode_id');
  2448. $episode_number = getProp($source_segment, 'episode_number');
  2449. $source_segment_number = getProp($source_segment, 'segment_number');
  2450. $target_segment_number = getProp($target_segment, 'segment_number');
  2451. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2452. $target_anime_id = getProp($target_segment, 'anime_id');
  2453. $target_episode_number = getProp($target_segment, 'episode_number');
  2454. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2455. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2456. }
  2457. // 如果源分镜和目标分镜相同,无需移动
  2458. if ($source_segment_number == $target_segment_number) {
  2459. return true;
  2460. }
  2461. try {
  2462. DB::beginTransaction();
  2463. if ($source_segment_number < $target_segment_number) {
  2464. // 向后移动:源分镜移动到目标分镜之后
  2465. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2466. DB::table('mp_episode_segments')
  2467. ->where('anime_id', $anime_id)
  2468. ->where('episode_id', $episode_id)
  2469. ->where('segment_number', '>', $source_segment_number)
  2470. ->where('segment_number', '<=', $target_segment_number)
  2471. ->decrement('segment_number');
  2472. // 2. 将源分镜移动到目标分镜之后
  2473. $new_segment_number = $target_segment_number;
  2474. } else {
  2475. // 向前移动:源分镜移动到目标分镜之后
  2476. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2477. DB::table('mp_episode_segments')
  2478. ->where('anime_id', $anime_id)
  2479. ->where('episode_id', $episode_id)
  2480. ->where('segment_number', '>', $target_segment_number)
  2481. ->where('segment_number', '<', $source_segment_number)
  2482. ->increment('segment_number');
  2483. // 2. 将源分镜移动到目标分镜之后
  2484. $new_segment_number = $target_segment_number + 1;
  2485. }
  2486. // 3. 更新源分镜的序号
  2487. $update_result = DB::table('mp_episode_segments')
  2488. ->where('segment_id', $segment_id)
  2489. ->update([
  2490. 'segment_number' => $new_segment_number,
  2491. 'updated_at' => date('Y-m-d H:i:s')
  2492. ]);
  2493. if (!$update_result) {
  2494. Utils::throwError('20003:更新分镜序号失败');
  2495. }
  2496. DB::commit();
  2497. return true;
  2498. } catch (\Exception $e) {
  2499. DB::rollBack();
  2500. Utils::throwError('20003:' . $e->getMessage());
  2501. }
  2502. }
  2503. public function delSegment($data) {
  2504. $segment_id = getProp($data, 'segment_id');
  2505. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2506. if (!$segment) Utils::throwError('20003:请选择分镜');
  2507. $anime_id = getProp($segment, 'anime_id');
  2508. $episode_id = getProp($segment, 'episode_id');
  2509. $episode_number = getProp($segment, 'episode_number');
  2510. $segment_number = getProp($segment, 'segment_number');
  2511. try {
  2512. DB::beginTransaction();
  2513. // 删除分镜
  2514. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2515. if (!$boolen) {
  2516. Utils::throwError('20003:删除分镜失败');
  2517. }
  2518. // 更新其他分镜序号
  2519. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2520. }catch (\Exception $e) {
  2521. DB::rollBack();
  2522. Utils::throwError('20003:'.$e->getMessage());
  2523. }
  2524. DB::commit();
  2525. return true;
  2526. }
  2527. public function applySegment($data) {
  2528. $segment_id = getProp($data, 'segment_id');
  2529. $url = getProp($data, 'url');
  2530. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2531. if (!$url) Utils::throwError('20003:URL不能为空');
  2532. // 获取URL的文件扩展名
  2533. $urlPath = parse_url($url, PHP_URL_PATH);
  2534. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2535. // 定义图片和视频的扩展名
  2536. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2537. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2538. // 判断是图片还是视频
  2539. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2540. if (in_array($extension, $imageExtensions)) {
  2541. // 图片类型
  2542. $updateData['img_url'] = $url;
  2543. $updateData['current_type'] = 1;
  2544. } elseif (in_array($extension, $videoExtensions)) {
  2545. // 视频类型
  2546. $updateData['video_url'] = $url;
  2547. $updateData['current_type'] = 2;
  2548. } else {
  2549. Utils::throwError('20003:不支持的文件类型');
  2550. }
  2551. // 更新分镜表
  2552. $result = DB::table('mp_episode_segments')
  2553. ->where('segment_id', $segment_id)
  2554. ->update($updateData);
  2555. if (!$result) {
  2556. Utils::throwError('20003:更新分镜失败');
  2557. }
  2558. return true;
  2559. }
  2560. public function segmentHistory($data) {
  2561. $segment_id = getProp($data, 'segment_id');
  2562. // 获取历史图片
  2563. $pics = [];
  2564. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2565. foreach($pic_history as $task) {
  2566. $result_url = getProp($task, 'result_url');
  2567. if (is_json($result_url)) {
  2568. $pics = array_merge($pics, json_decode($result_url, true));
  2569. }else {
  2570. $pics[] = $result_url;
  2571. }
  2572. }
  2573. // 获取历史视频
  2574. $videos = [];
  2575. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2576. foreach($video_history as $task) {
  2577. $result_url = getProp($task, 'result_url');
  2578. if (is_json($result_url)) {
  2579. $videos = array_merge($videos, json_decode($result_url, true));
  2580. }else {
  2581. $videos[] = $result_url;
  2582. }
  2583. }
  2584. return compact('pics', 'videos');
  2585. }
  2586. public function addAct($data) {
  2587. $prev_act_id = getProp($data, 'prev_act_id');
  2588. $act_title = getProp($data, 'act_title', '');
  2589. $act_content = getProp($data, 'act_content', '');
  2590. $act_duration = getProp($data, 'act_duration', 5);
  2591. $video_url = getProp($data, 'video_url');
  2592. // 根据prev_act_id获取记录
  2593. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2594. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2595. $anime_id = getProp($prev_segment, 'anime_id');
  2596. $episode_id = getProp($prev_segment, 'episode_id');
  2597. $episode_number = getProp($prev_segment, 'episode_number');
  2598. $prev_act_number = getProp($prev_segment, 'act_number');
  2599. // 获取新的act_number
  2600. $new_act_number = $prev_act_number + 1;
  2601. try {
  2602. DB::beginTransaction();
  2603. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2604. DB::table('mp_episode_segments')
  2605. ->where('anime_id', $anime_id)
  2606. ->where('episode_id', $episode_id)
  2607. ->where('act_number', '>', $prev_act_number)
  2608. ->increment('act_number');
  2609. // 插入新片段记录
  2610. $insert_data = [
  2611. 'anime_id' => $anime_id,
  2612. 'episode_id' => $episode_id,
  2613. 'episode_number' => $episode_number,
  2614. 'act_number' => $new_act_number,
  2615. 'created_at' => date('Y-m-d H:i:s'),
  2616. 'updated_at' => date('Y-m-d H:i:s')
  2617. ];
  2618. if ($act_title) {
  2619. $insert_data['act_title'] = $act_title;
  2620. }
  2621. if ($act_content) {
  2622. $insert_data['act_content'] = $act_content;
  2623. }
  2624. if ($act_duration) {
  2625. $insert_data['act_duration'] = $act_duration;
  2626. }
  2627. if ($video_url) {
  2628. $insert_data['origin_video_url'] = $video_url;
  2629. $insert_data['current_type'] = 2;
  2630. $compressed_video_url = compressVideo($video_url);
  2631. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2632. }
  2633. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2634. if (!$id) {
  2635. Utils::throwError('20003:新增片段失败!');
  2636. }
  2637. DB::commit();
  2638. }catch (\Exception $e) {
  2639. DB::rollBack();
  2640. Utils::throwError('20003:'.$e->getMessage());
  2641. }
  2642. $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();
  2643. $segment = $segment ? (array)$segment : [];
  2644. return $segment;
  2645. }
  2646. public function editAct($data) {
  2647. $act_id = getProp($data, 'act_id');
  2648. $act_content = getProp($data, 'act_content');
  2649. $act_duration = getProp($data, 'act_duration');
  2650. $act_title = getProp($data, 'act_title');
  2651. $image_url = getProp($data, 'image_url');
  2652. $video_url = getProp($data, 'video_url');
  2653. // 参数验证
  2654. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2655. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2656. $segment = DB::table('mp_episode_segments')
  2657. ->where('id', $act_id)
  2658. ->first();
  2659. if (!$segment) Utils::throwError('20003:该片段不存在');
  2660. try {
  2661. DB::beginTransaction();
  2662. // 准备更新数据
  2663. $update_data = [
  2664. 'updated_at' => date('Y-m-d H:i:s')
  2665. ];
  2666. // 更新act相关字段
  2667. if (!empty($act_content)) {
  2668. $update_data['act_show_content'] = $act_content;
  2669. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2670. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2671. $shot_counter = 0;
  2672. $update_data['act_show_content'] = preg_replace_callback(
  2673. '/【(?:镜头|分镜)(\d+)】/u',
  2674. function($matches) use (&$shot_counter) {
  2675. $shot_counter++;
  2676. return '【镜头' . $shot_counter . '】';
  2677. },
  2678. $update_data['act_show_content']
  2679. );
  2680. }
  2681. if (!empty($act_duration)) {
  2682. $update_data['act_duration'] = $act_duration;
  2683. }
  2684. if (!empty($act_title)) {
  2685. $update_data['act_title'] = $act_title;
  2686. }
  2687. // 处理图片上传
  2688. if ($image_url) {
  2689. $update_data['img_url'] = $image_url;
  2690. $update_data['current_type'] = 1;
  2691. // 同时写入一个图片生成任务记录
  2692. if ($act_id) {
  2693. $pic_task = [
  2694. 'alias_act_id' => $act_id,
  2695. 'ref_img_url' => json_encode([]),
  2696. 'status' => 'success',
  2697. 'result_url' => json_encode([$image_url], 256),
  2698. 'model' => '',
  2699. 'created_at' => date('Y-m-d H:i:s'),
  2700. 'updated_at' => date('Y-m-d H:i:s'),
  2701. ];
  2702. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2703. }
  2704. }
  2705. // 处理视频上传
  2706. if ($video_url) {
  2707. $update_data['origin_video_url'] = $video_url;
  2708. $compressed_video_url = compressVideo($video_url);
  2709. $update_data['current_type'] = 2;
  2710. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2711. // 同时写入一个视频生成任务记录
  2712. if ($act_id) {
  2713. $video_task = [
  2714. 'alias_act_id' => $act_id,
  2715. 'status' => 'success',
  2716. 'result_url' => $update_data['origin_video_url'],
  2717. 'compressed_url' => $update_data['video_url'],
  2718. 'created_at' => date('Y-m-d H:i:s'),
  2719. 'updated_at' => date('Y-m-d H:i:s'),
  2720. ];
  2721. DB::table('mp_generate_video_tasks')->insert($video_task);
  2722. }
  2723. }
  2724. // 更新片段信息
  2725. $result = DB::table('mp_episode_segments')
  2726. ->where('id', $act_id)
  2727. ->update($update_data);
  2728. if ($result === false) {
  2729. Utils::throwError('20003:更新片段失败');
  2730. }
  2731. DB::commit();
  2732. // 返回新复制的记录
  2733. $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();
  2734. $new_segment = (array)$new_segment;
  2735. return $new_segment;
  2736. } catch (\Exception $e) {
  2737. DB::rollBack();
  2738. dLog('anime')->error('更新片段失败', [
  2739. 'act_id' => $act_id,
  2740. 'error' => $e->getMessage()
  2741. ]);
  2742. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2743. }
  2744. }
  2745. public function copyAct($data) {
  2746. $act_id = getProp($data, 'act_id');
  2747. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2748. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2749. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2750. $anime_id = getProp($source_segment, 'anime_id');
  2751. $episode_id = getProp($source_segment, 'episode_id');
  2752. $episode_number = getProp($source_segment, 'episode_number');
  2753. $act_number = getProp($source_segment, 'act_number');
  2754. try {
  2755. DB::beginTransaction();
  2756. // 新act的编号
  2757. $new_act_number = $act_number + 1;
  2758. // 更新后续所有act的act_number
  2759. DB::table('mp_episode_segments')
  2760. ->where('anime_id', $anime_id)
  2761. ->where('episode_id', $episode_id)
  2762. ->where('act_number', '>', $act_number)
  2763. ->increment('act_number');
  2764. // 复制该片段记录
  2765. $segment_data = (array)$source_segment;
  2766. unset($segment_data['id']);
  2767. $segment_data['video_url'] = '';
  2768. $segment_data['video_task_id'] = '';
  2769. $segment_data['video_task_status'] = '';
  2770. $segment_data['act_number'] = $new_act_number;
  2771. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2772. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2773. if (!$id) {
  2774. Utils::throwError('20003:复制片段失败');
  2775. }
  2776. DB::commit();
  2777. }catch (\Exception $e) {
  2778. DB::rollBack();
  2779. Utils::throwError('20003:'.$e->getMessage());
  2780. }
  2781. // 返回新复制的记录
  2782. $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();
  2783. $new_segment = $new_segment ? (array)$new_segment : [];
  2784. $new_segment['act_id'] = $id;
  2785. return $new_segment;
  2786. }
  2787. public function moveAct($data) {
  2788. $act_id = getProp($data, 'act_id');
  2789. $target_act_id = getProp($data, 'target_act_id');
  2790. // 获取源片段信息
  2791. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2792. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2793. // 获取目标片段信息
  2794. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2795. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2796. $anime_id = getProp($source_segment, 'anime_id');
  2797. $episode_id = getProp($source_segment, 'episode_id');
  2798. $source_act_number = getProp($source_segment, 'act_number');
  2799. $target_act_number = getProp($target_segment, 'act_number');
  2800. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2801. $target_anime_id = getProp($target_segment, 'anime_id');
  2802. $target_episode_id = getProp($target_segment, 'episode_id');
  2803. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2804. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2805. }
  2806. // 如果源片段和目标片段相同,无需移动
  2807. if ($source_act_number == $target_act_number) {
  2808. return true;
  2809. }
  2810. try {
  2811. DB::beginTransaction();
  2812. if ($source_act_number < $target_act_number) {
  2813. // 向后移动:源片段移动到目标片段之后
  2814. // 1. 将源片段和目标片段之间的所有片段编号减1
  2815. DB::table('mp_episode_segments')
  2816. ->where('anime_id', $anime_id)
  2817. ->where('episode_id', $episode_id)
  2818. ->where('act_number', '>', $source_act_number)
  2819. ->where('act_number', '<=', $target_act_number)
  2820. ->decrement('act_number');
  2821. // 2. 将源片段移动到目标片段之后
  2822. $new_act_number = $target_act_number;
  2823. } else {
  2824. // 向前移动:源片段移动到目标片段之后
  2825. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2826. DB::table('mp_episode_segments')
  2827. ->where('anime_id', $anime_id)
  2828. ->where('episode_id', $episode_id)
  2829. ->where('act_number', '>', $target_act_number)
  2830. ->where('act_number', '<', $source_act_number)
  2831. ->increment('act_number');
  2832. // 2. 将源片段移动到目标片段之后
  2833. $new_act_number = $target_act_number + 1;
  2834. }
  2835. // 3. 更新源片段的编号
  2836. $update_result = DB::table('mp_episode_segments')
  2837. ->where('id', $act_id)
  2838. ->update([
  2839. 'act_number' => $new_act_number,
  2840. 'updated_at' => date('Y-m-d H:i:s')
  2841. ]);
  2842. if (!$update_result) {
  2843. Utils::throwError('20003:更新片段编号失败');
  2844. }
  2845. DB::commit();
  2846. return true;
  2847. } catch (\Exception $e) {
  2848. DB::rollBack();
  2849. Utils::throwError('20003:' . $e->getMessage());
  2850. }
  2851. }
  2852. public function delAct($data) {
  2853. $act_id = getProp($data, 'act_id');
  2854. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2855. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2856. if (!$segment) Utils::throwError('20003:请选择片段');
  2857. $anime_id = getProp($segment, 'anime_id');
  2858. $episode_id = getProp($segment, 'episode_id');
  2859. $act_number = getProp($segment, 'act_number');
  2860. try {
  2861. DB::beginTransaction();
  2862. // 删除该片段记录
  2863. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2864. if (!$deleted) {
  2865. Utils::throwError('20003:删除片段失败');
  2866. }
  2867. // 更新后续act的编号
  2868. DB::table('mp_episode_segments')
  2869. ->where('anime_id', $anime_id)
  2870. ->where('episode_id', $episode_id)
  2871. ->where('act_number', '>', $act_number)
  2872. ->decrement('act_number');
  2873. DB::commit();
  2874. }catch (\Exception $e) {
  2875. DB::rollBack();
  2876. Utils::throwError('20003:'.$e->getMessage());
  2877. }
  2878. return true;
  2879. }
  2880. public function applyAct($data) {
  2881. $act_id = getProp($data, 'act_id');
  2882. $url = getProp($data, 'url');
  2883. if (!$act_id) Utils::throwError('20003:请选择片段');
  2884. if (!$url) Utils::throwError('20003:URL不能为空');
  2885. // 获取URL的文件扩展名
  2886. $urlPath = parse_url($url, PHP_URL_PATH);
  2887. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2888. // 定义图片和视频的扩展名
  2889. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2890. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2891. // 判断是图片还是视频
  2892. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2893. if (in_array($extension, $imageExtensions)) {
  2894. // 图片类型
  2895. $updateData['img_url'] = $url;
  2896. $updateData['current_type'] = 1;
  2897. } elseif (in_array($extension, $videoExtensions)) {
  2898. // 视频类型
  2899. $updateData['video_url'] = $url;
  2900. $updateData['current_type'] = 2;
  2901. } else {
  2902. Utils::throwError('20003:不支持的文件类型');
  2903. }
  2904. // 更新片段记录(全能模式下每个act只有一条记录)
  2905. $result = DB::table('mp_episode_segments')
  2906. ->where('id', $act_id)
  2907. ->update($updateData);
  2908. if (!$result) {
  2909. Utils::throwError('20003:更新片段失败');
  2910. }
  2911. return true;
  2912. }
  2913. public function actChatHistory($data) {
  2914. $act_id = getProp($data, 'act_id');
  2915. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2916. $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');
  2917. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2918. $value = (array)$value;
  2919. $value['created_at'] = transDate($value['created_at']);
  2920. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2921. else $value['reference_images'] = [];
  2922. return $value;
  2923. })->toArray();
  2924. // 获取历史图片
  2925. $url = [];
  2926. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2927. foreach($pic_history as $task) {
  2928. $result_url = getProp($task, 'result_url');
  2929. if (is_json($result_url)) {
  2930. $url = array_merge($url, json_decode($result_url, true));
  2931. }else {
  2932. $url[] = $result_url;
  2933. }
  2934. }
  2935. // 获取历史视频
  2936. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2937. foreach($video_history as $task) {
  2938. $result_url = getProp($task, 'result_url');
  2939. if (is_json($result_url)) {
  2940. $url = array_merge($url, json_decode($result_url, true));
  2941. }else {
  2942. $url[] = $result_url;
  2943. }
  2944. }
  2945. // 获取资产库
  2946. $products = [];
  2947. // 通过act_id查询片段信息获取episode_id
  2948. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2949. if ($segment) {
  2950. $episode_id = getProp($segment, 'episode_id');
  2951. // 查询剧集信息获取roles、scenes和extra_products
  2952. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2953. if ($episode) {
  2954. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2955. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2956. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2957. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2958. // 先合并roles、scenes和props
  2959. // 处理角色数组
  2960. foreach ($roles as $role) {
  2961. $product = $role;
  2962. // 将role字段重命名为product_name
  2963. if (is_array($product) && !empty($product['role'] ?? null)) {
  2964. $product['product_name'] = $product['role'];
  2965. unset($product['role']);
  2966. $product['product'] = 1; // 标记类型为角色
  2967. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2968. }
  2969. }
  2970. // 处理场景数组
  2971. foreach ($scenes as $scene) {
  2972. $product = $scene;
  2973. // 将scene字段重命名为product_name
  2974. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2975. $product['product_name'] = $product['scene'];
  2976. unset($product['scene']);
  2977. $product['product'] = 2; // 标记类型为场景
  2978. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2979. }
  2980. }
  2981. // 处理道具数组
  2982. foreach ($props as $prop) {
  2983. $product = $prop;
  2984. // 将prop字段重命名为product_name
  2985. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2986. $product['product_name'] = $product['prop'];
  2987. unset($product['prop']);
  2988. $product['product'] = 3; // 标记类型为道具
  2989. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2990. }
  2991. }
  2992. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2993. foreach ($extra_products as $extra_product) {
  2994. $product_name = getProp($extra_product, 'product_name');
  2995. if ($product_name) {
  2996. $products[$product_name] = $extra_product; // 覆盖同名数据
  2997. }
  2998. }
  2999. // 重新索引数组(去除key)
  3000. $products = array_values($products);
  3001. }
  3002. }
  3003. // 获取执行中的任务
  3004. $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) {
  3005. $value = (array)$value;
  3006. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  3007. else $value['ref_image_url'] = [];
  3008. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  3009. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  3010. if (!empty($value['prompt'])) {
  3011. $prompt = $value['prompt'];
  3012. // 查找第一个【镜头】的位置
  3013. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  3014. // 从【镜头】开始截取
  3015. $prompt = substr($prompt, $matches[0][1]);
  3016. }
  3017. // 去除所有<图片X>格式的标记(X可以是任意数字)
  3018. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  3019. $value['prompt'] = $prompt;
  3020. }
  3021. return $value;
  3022. })->toArray();
  3023. return compact('chat', 'url', 'products', 'tasks');
  3024. }
  3025. public function applyAudioData($data) {
  3026. $segment_id = getProp($data, 'segment_id');
  3027. $global_data = getProp($data, 'global_data');
  3028. $segment_data = getProp($data, 'segment_data');
  3029. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3030. $global_data = is_array($global_data) ? $global_data : [];
  3031. $segment_data = is_array($segment_data) ? $segment_data : [];
  3032. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3033. $dialogue_item = null;
  3034. foreach ($global_data as $key => $item) {
  3035. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3036. $dialogue_item = $item;
  3037. unset($global_data[$key]);
  3038. break;
  3039. }
  3040. }
  3041. if ($dialogue_item) {
  3042. $segment_data[] = $dialogue_item;
  3043. }
  3044. // 特殊参数: audio_url,audio_duration,subtitle_info
  3045. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3046. // 如果不是全部存在,则仍需创建音频任务
  3047. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3048. $special_update_data = [];
  3049. $has_all_special_params = false;
  3050. // 从segment_data中提取特殊参数
  3051. $filtered_segment_data = [];
  3052. foreach ($segment_data as $item) {
  3053. $field_name = trim((string)getProp($item, 'name'));
  3054. if (in_array($field_name, $special_fields)) {
  3055. $special_update_data[$field_name] = getProp($item, 'value');
  3056. } else {
  3057. // 非特殊参数保留,继续后续处理
  3058. $filtered_segment_data[] = $item;
  3059. }
  3060. }
  3061. // 检查是否三个特殊参数都存在
  3062. if (count($special_update_data) === 3 &&
  3063. isset($special_update_data['audio_url']) &&
  3064. isset($special_update_data['audio_duration']) &&
  3065. isset($special_update_data['subtitle_info'])) {
  3066. $has_all_special_params = true;
  3067. // 立即更新到当前分镜
  3068. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3069. DB::table('mp_episode_segments')
  3070. ->where('segment_id', $segment_id)
  3071. ->update($special_update_data);
  3072. }
  3073. // 使用过滤后的segment_data继续处理其他参数
  3074. $segment_data = $filtered_segment_data;
  3075. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3076. $global_update_data = [];
  3077. $segment_update_data = [];
  3078. $global_voice_type = '';
  3079. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3080. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3081. $episode_id = getProp($target_segment, 'episode_id');
  3082. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3083. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3084. if (!$episode) Utils::throwError('20003:分集不存在');
  3085. foreach ($global_data as $item) {
  3086. $field_name = trim((string)getProp($item, 'name'));
  3087. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3088. continue;
  3089. }
  3090. $global_update_data[$field_name] = getProp($item, 'value');
  3091. if ($field_name === 'voice_type') {
  3092. $global_voice_type = trim((string)getProp($item, 'value'));
  3093. }
  3094. }
  3095. foreach ($segment_data as $item) {
  3096. $field_name = trim((string)getProp($item, 'name'));
  3097. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3098. continue;
  3099. }
  3100. $segment_update_data[$field_name] = getProp($item, 'value');
  3101. }
  3102. if ($global_voice_type) {
  3103. $timbre_info = DB::table('mp_timbres')
  3104. ->where('timbre_type', $global_voice_type)
  3105. ->select('audio_url', 'timbre_name')
  3106. ->first();
  3107. if ($timbre_info) {
  3108. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3109. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3110. }
  3111. }
  3112. try {
  3113. DB::beginTransaction();
  3114. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3115. $segment_ids_to_create_task = [];
  3116. $segments_data = [];
  3117. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3118. if (!empty($global_update_data)) {
  3119. // 如果角色不存在,则只更新当前分镜
  3120. if (!$target_voice_actor) {
  3121. // 只处理当前分镜
  3122. $affected_segments = DB::table('mp_episode_segments')
  3123. ->where('segment_id', $segment_id)
  3124. ->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')
  3125. ->get();
  3126. } else {
  3127. // 获取该角色的所有分镜
  3128. $affected_segments = DB::table('mp_episode_segments')
  3129. ->where('episode_id', $episode_id)
  3130. ->where('voice_actor', $target_voice_actor)
  3131. ->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')
  3132. ->get();
  3133. }
  3134. foreach ($affected_segments as $seg) {
  3135. $seg = (array)$seg;
  3136. $sid = getProp($seg, 'segment_id');
  3137. // 检查参数是否发生变化
  3138. $has_changed = false;
  3139. foreach ($global_update_data as $field => $new_value) {
  3140. $old_value = getProp($seg, $field);
  3141. if ($old_value != $new_value) {
  3142. $has_changed = true;
  3143. break;
  3144. }
  3145. }
  3146. if ($has_changed) {
  3147. $segment_ids_to_create_task[] = $sid;
  3148. $segments_data[$sid] = $seg;
  3149. }
  3150. }
  3151. // 只有在有变化的分镜时才更新
  3152. if (!empty($segment_ids_to_create_task)) {
  3153. $global_segment_update_data = $global_update_data;
  3154. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3155. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3156. DB::table('mp_episode_segments')
  3157. ->where('episode_id', $episode_id)
  3158. ->where('voice_actor', $target_voice_actor)
  3159. ->whereIn('segment_id', $segment_ids_to_create_task)
  3160. ->update($global_segment_update_data);
  3161. }
  3162. if ($global_voice_type) {
  3163. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3164. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3165. $roles_updated = false;
  3166. foreach ($episode_roles as &$role) {
  3167. // 通过 role 字段匹配角色名,而不是 voice_name
  3168. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3169. continue;
  3170. }
  3171. $role['voice_type'] = $global_voice_type;
  3172. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3173. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3174. $roles_updated = true;
  3175. }
  3176. unset($role);
  3177. if ($roles_updated) {
  3178. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3179. 'roles' => json_encode($episode_roles, 256),
  3180. 'updated_at' => date('Y-m-d H:i:s'),
  3181. ]);
  3182. }
  3183. }
  3184. }
  3185. // 如果有单个分镜更新,检查是否有变化
  3186. if (!empty($segment_update_data)) {
  3187. // 获取当前分镜数据
  3188. $current_segment = DB::table('mp_episode_segments')
  3189. ->where('segment_id', $segment_id)
  3190. ->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')
  3191. ->first();
  3192. if ($current_segment) {
  3193. $current_segment = (array)$current_segment;
  3194. // 检查参数是否发生变化
  3195. $has_changed = false;
  3196. foreach ($segment_update_data as $field => $new_value) {
  3197. $old_value = getProp($current_segment, $field);
  3198. if ($old_value != $new_value) {
  3199. $has_changed = true;
  3200. break;
  3201. }
  3202. }
  3203. if ($has_changed) {
  3204. // 如果该分镜还未在列表中,添加进去
  3205. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3206. $segment_ids_to_create_task[] = $segment_id;
  3207. $segments_data[$segment_id] = $current_segment;
  3208. }
  3209. // 更新分镜数据并清空音频URL
  3210. $segment_update_data['audio_url'] = '';
  3211. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3212. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3213. }
  3214. }
  3215. }
  3216. // 为所有有变化的分镜创建音频合成任务
  3217. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3218. if (!empty($segment_ids_to_create_task)) {
  3219. foreach ($segment_ids_to_create_task as $sid) {
  3220. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3221. if ($sid === $segment_id && $has_all_special_params) {
  3222. continue;
  3223. }
  3224. // 重新获取更新后的分镜数据
  3225. $updated_segment = DB::table('mp_episode_segments')
  3226. ->where('segment_id', $sid)
  3227. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3228. ->first();
  3229. if (!$updated_segment) continue;
  3230. $updated_segment = (array)$updated_segment;
  3231. // 检查dialogue是否为空
  3232. $dialogue = getProp($updated_segment, 'dialogue');
  3233. if (empty($dialogue)) {
  3234. // dialogue为空时,直接写入默认音频信息
  3235. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3236. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3237. 'audio_duration' => 2.0,
  3238. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3239. 'updated_at' => date('Y-m-d H:i:s')
  3240. ]);
  3241. continue;
  3242. }
  3243. $generate_json = [
  3244. 'text' => $dialogue,
  3245. 'role' => getProp($updated_segment, 'voice_actor'),
  3246. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3247. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3248. 'emotion' => getProp($updated_segment, 'emotion'),
  3249. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3250. 'gender' => getProp($updated_segment, 'gender'),
  3251. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3252. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3253. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3254. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3255. ];
  3256. // 插入视频配音合成任务
  3257. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3258. 'alias_segment_id' => $sid,
  3259. 'generate_status' => '执行中',
  3260. 'audio_url' => '',
  3261. 'generate_json' => json_encode($generate_json, 256),
  3262. 'created_at' => date('Y-m-d H:i:s'),
  3263. 'updated_at' => date('Y-m-d H:i:s'),
  3264. ]);
  3265. if (!$dubTaskId) {
  3266. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3267. continue;
  3268. }
  3269. // 将任务ID添加到Redis列表中
  3270. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3271. // 请求远程服务器执行生成
  3272. try {
  3273. sleep(1);
  3274. $client = new Client(['timeout' => 300, 'verify' => false]);
  3275. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3276. $response = $result->getBody()->getContents();
  3277. $response_arr = json_decode($response, true);
  3278. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3279. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3280. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3281. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3282. }
  3283. } catch (\Exception $e) {
  3284. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3285. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3286. }
  3287. }
  3288. }
  3289. DB::commit();
  3290. } catch (\Exception $e) {
  3291. DB::rollBack();
  3292. Utils::throwError('20003:'.$e->getMessage());
  3293. }
  3294. return true;
  3295. }
  3296. public function episodePicsInfo($data) {
  3297. $anime_id = getProp($data, 'anime_id');
  3298. $episode_id = getProp($data, 'episode_id');
  3299. // 参数验证
  3300. if (!$anime_id && !$episode_id) {
  3301. Utils::throwError('20003:请提供动漫ID或分集ID');
  3302. }
  3303. // 根据参数获取数据源
  3304. if ($episode_id) {
  3305. // 从剧集表获取
  3306. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3307. if (!$source) Utils::throwError('20003:该剧集不存在');
  3308. $table_name = 'mp_anime_episodes';
  3309. $id_field = 'id';
  3310. $id_value = $episode_id;
  3311. // 获取剧集的anime_id用于继承全局数据
  3312. $anime_id = getProp($source, 'anime_id');
  3313. } else {
  3314. // 从动漫表获取
  3315. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3316. if (!$source) Utils::throwError('20003:该动漫不存在');
  3317. $table_name = 'mp_animes';
  3318. $id_field = 'id';
  3319. $id_value = $anime_id;
  3320. }
  3321. $source = (array)$source;
  3322. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3323. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3324. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3325. // 如果是分集数据,需要处理继承和任务创建逻辑
  3326. if ($episode_id) {
  3327. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3328. }
  3329. // 返回生成器函数,用于 SSE 流式输出
  3330. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3331. $startTime = time();
  3332. $maxDuration = 600; // 10分钟超时
  3333. $checkInterval = 3; // 每3秒检查一次
  3334. // Redis 缓存键
  3335. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3336. // 生成当前数据的哈希值用于比较
  3337. $generateHash = function($roles, $scenes, $props) {
  3338. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3339. };
  3340. // 发送初始数据
  3341. $currentHash = $generateHash($roles, $scenes, $props);
  3342. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3343. echo "data: " . json_encode([
  3344. 'type' => 'init',
  3345. 'data' => [
  3346. 'roles' => $roles,
  3347. 'scenes' => $scenes,
  3348. 'props' => $props,
  3349. 'start_time' => $startTime
  3350. ]
  3351. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3352. if (ob_get_level() > 0) {
  3353. ob_flush();
  3354. }
  3355. flush();
  3356. // 持续轮询任务状态
  3357. while (time() - $startTime < $maxDuration) {
  3358. $hasProcessing = false;
  3359. $updated = false;
  3360. // 检查角色任务状态
  3361. foreach ($roles as $index => &$role) {
  3362. $task_id = getProp($role, 'task_id');
  3363. $task_status = getProp($role, 'task_status');
  3364. $existing_url = getProp($role, 'url');
  3365. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3366. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3367. $hasProcessing = ($task_status === 'processing');
  3368. // 查询任务状态
  3369. $task = DB::table('mp_generate_pic_tasks')
  3370. ->where('id', $task_id)
  3371. ->select('id', 'status', 'result_url', 'error_message')
  3372. ->first();
  3373. if ($task) {
  3374. $task = (array)$task;
  3375. $status = getProp($task, 'status');
  3376. // 如果任务完成或失败
  3377. if (in_array($status, ['success', 'failed'])) {
  3378. $role['task_status'] = $status;
  3379. if ($status === 'success') {
  3380. $result_url = getProp($task, 'result_url');
  3381. if ($result_url) {
  3382. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3383. if (is_array($result_urls) && !empty($result_urls[0])) {
  3384. $role['url'] = $result_urls[0];
  3385. }
  3386. }
  3387. }
  3388. $updated = true;
  3389. } else if ($status === 'processing') {
  3390. $hasProcessing = true;
  3391. }
  3392. }
  3393. }
  3394. }
  3395. // 检查场景任务状态
  3396. foreach ($scenes as $index => &$scene) {
  3397. $task_id = getProp($scene, 'task_id');
  3398. $task_status = getProp($scene, 'task_status');
  3399. $existing_url = getProp($scene, 'url');
  3400. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3401. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3402. $hasProcessing = ($task_status === 'processing');
  3403. // 查询任务状态
  3404. $task = DB::table('mp_generate_pic_tasks')
  3405. ->where('id', $task_id)
  3406. ->select('id', 'status', 'result_url', 'error_message')
  3407. ->first();
  3408. if ($task) {
  3409. $task = (array)$task;
  3410. $status = getProp($task, 'status');
  3411. // 如果任务完成或失败
  3412. if (in_array($status, ['success', 'failed'])) {
  3413. $scene['task_status'] = $status;
  3414. if ($status === 'success') {
  3415. $result_url = getProp($task, 'result_url');
  3416. if ($result_url) {
  3417. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3418. if (is_array($result_urls) && !empty($result_urls[0])) {
  3419. $scene['url'] = $result_urls[0];
  3420. }
  3421. }
  3422. }
  3423. $updated = true;
  3424. } else if ($status === 'processing') {
  3425. $hasProcessing = true;
  3426. }
  3427. }
  3428. }
  3429. }
  3430. // 检查道具任务状态
  3431. foreach ($props as $index => &$prop) {
  3432. $task_id = getProp($prop, 'task_id');
  3433. $task_status = getProp($prop, 'task_status');
  3434. $existing_url = getProp($prop, 'url');
  3435. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3436. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3437. $hasProcessing = ($task_status === 'processing');
  3438. // 查询任务状态
  3439. $task = DB::table('mp_generate_pic_tasks')
  3440. ->where('id', $task_id)
  3441. ->select('id', 'status', 'result_url', 'error_message')
  3442. ->first();
  3443. if ($task) {
  3444. $task = (array)$task;
  3445. $status = getProp($task, 'status');
  3446. // 如果任务完成或失败
  3447. if (in_array($status, ['success', 'failed'])) {
  3448. $prop['task_status'] = $status;
  3449. if ($status === 'success') {
  3450. $result_url = getProp($task, 'result_url');
  3451. if ($result_url) {
  3452. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3453. if (is_array($result_urls) && !empty($result_urls[0])) {
  3454. $prop['url'] = $result_urls[0];
  3455. }
  3456. }
  3457. }
  3458. $updated = true;
  3459. } else if ($status === 'processing') {
  3460. $hasProcessing = true;
  3461. }
  3462. }
  3463. }
  3464. }
  3465. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3466. if ($updated) {
  3467. $newHash = $generateHash($roles, $scenes, $props);
  3468. $cachedHash = Redis::get($cacheKey);
  3469. // 只有当数据真正变化时才更新数据库和发送事件
  3470. if ($newHash !== $cachedHash) {
  3471. try {
  3472. // 更新数据库
  3473. DB::table($table_name)->where($id_field, $id_value)->update([
  3474. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3475. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3476. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3477. 'updated_at' => date('Y-m-d H:i:s')
  3478. ]);
  3479. // 更新缓存
  3480. Redis::setex($cacheKey, 600, $newHash);
  3481. // 发送更新事件
  3482. echo "data: " . json_encode([
  3483. 'type' => 'update',
  3484. 'data' => [
  3485. 'roles' => $roles,
  3486. 'scenes' => $scenes,
  3487. 'props' => $props,
  3488. 'elapsed_time' => time() - $startTime
  3489. ]
  3490. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3491. if (ob_get_level() > 0) {
  3492. ob_flush();
  3493. }
  3494. flush();
  3495. } catch (\Exception $e) {
  3496. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3497. }
  3498. } else {
  3499. // 即使哈希相同,如果有URL更新也要发送事件
  3500. $hasUrlUpdate = false;
  3501. foreach ($roles as $role) {
  3502. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3503. $hasUrlUpdate = true;
  3504. break;
  3505. }
  3506. }
  3507. if (!$hasUrlUpdate) {
  3508. foreach ($scenes as $scene) {
  3509. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3510. $hasUrlUpdate = true;
  3511. break;
  3512. }
  3513. }
  3514. }
  3515. if (!$hasUrlUpdate) {
  3516. foreach ($props as $prop) {
  3517. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3518. $hasUrlUpdate = true;
  3519. break;
  3520. }
  3521. }
  3522. }
  3523. if ($hasUrlUpdate) {
  3524. // 强制更新数据库和发送事件
  3525. try {
  3526. DB::table($table_name)->where($id_field, $id_value)->update([
  3527. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3528. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3529. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3530. 'updated_at' => date('Y-m-d H:i:s')
  3531. ]);
  3532. // 更新缓存
  3533. Redis::setex($cacheKey, 600, $newHash);
  3534. // 发送更新事件
  3535. echo "data: " . json_encode([
  3536. 'type' => 'update',
  3537. 'data' => [
  3538. 'roles' => $roles,
  3539. 'scenes' => $scenes,
  3540. 'props' => $props,
  3541. 'elapsed_time' => time() - $startTime
  3542. ]
  3543. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3544. if (ob_get_level() > 0) {
  3545. ob_flush();
  3546. }
  3547. flush();
  3548. } catch (\Exception $e) {
  3549. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3550. }
  3551. }
  3552. }
  3553. }
  3554. // 如果所有任务都已完成,发送完成事件并退出
  3555. if (!$hasProcessing) {
  3556. // 查询数据库中的最终数据,确保返回最新的完整数据
  3557. try {
  3558. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3559. if ($finalSource) {
  3560. $finalSource = (array)$finalSource;
  3561. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3562. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3563. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3564. // 使用数据库中的最终数据
  3565. $roles = $finalRoles;
  3566. $scenes = $finalScenes;
  3567. $props = $finalProps;
  3568. }
  3569. } catch (\Exception $e) {
  3570. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3571. // 如果查询失败,继续使用内存中的数据
  3572. }
  3573. // 清理缓存
  3574. Redis::del($cacheKey);
  3575. echo "data: " . json_encode([
  3576. 'type' => 'completed',
  3577. 'data' => [
  3578. 'roles' => $roles,
  3579. 'scenes' => $scenes,
  3580. 'props' => $props,
  3581. 'total_time' => time() - $startTime
  3582. ]
  3583. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3584. if (ob_get_level() > 0) {
  3585. ob_flush();
  3586. }
  3587. flush();
  3588. break;
  3589. }
  3590. // 等待下次检查
  3591. sleep($checkInterval);
  3592. }
  3593. // 超时处理
  3594. if (time() - $startTime >= $maxDuration) {
  3595. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3596. try {
  3597. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3598. if ($finalSource) {
  3599. $finalSource = (array)$finalSource;
  3600. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3601. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3602. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3603. // 使用数据库中的最终数据
  3604. $roles = $finalRoles;
  3605. $scenes = $finalScenes;
  3606. $props = $finalProps;
  3607. }
  3608. } catch (\Exception $e) {
  3609. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3610. // 如果查询失败,继续使用内存中的数据
  3611. }
  3612. // 清理缓存
  3613. Redis::del($cacheKey);
  3614. echo "data: " . json_encode([
  3615. 'type' => 'timeout',
  3616. 'message' => '轮询超时,请刷新页面查看最新状态',
  3617. 'data' => [
  3618. 'roles' => $roles,
  3619. 'scenes' => $scenes,
  3620. 'props' => $props
  3621. ]
  3622. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3623. if (ob_get_level() > 0) {
  3624. ob_flush();
  3625. }
  3626. flush();
  3627. }
  3628. };
  3629. }
  3630. public function clipSegmentVideo($data) {
  3631. $segment_id = getProp($data, 'segment_id');
  3632. $video_time_point_start = getProp($data, 'video_time_point_start');
  3633. $video_time_point_end = getProp($data, 'video_time_point_end');
  3634. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3635. Utils::throwError('20003:参数异常');
  3636. }
  3637. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3638. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3639. }
  3640. $video_duration = $video_time_point_end - $video_time_point_start;
  3641. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3642. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3643. 'video_duration' => $video_duration,
  3644. 'video_time_point_start' => $video_time_point_start,
  3645. 'video_time_point_end' => $video_time_point_end,
  3646. 'updated_at' => date('Y-m-d H:i:s')
  3647. ]);
  3648. }
  3649. // 轮训获取图片任务结果
  3650. private function loopGetPicTaskResult($task_id) {
  3651. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3652. if (!$task) {
  3653. return '';
  3654. }
  3655. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3656. $model = getProp($task, 'model');
  3657. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3658. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3659. $isSyncModel = $isVolcModel || $isGptModel;
  3660. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3661. $start_count = 0;
  3662. $img_url = '';
  3663. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3664. sleep(3);
  3665. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3666. // 如果任务已经完成,直接返回结果
  3667. if ($task->status === 'success' && $task->result_url) {
  3668. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3669. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3670. }
  3671. // 如果任务已失败,返回空
  3672. if ($task->status === 'failed') {
  3673. return '';
  3674. }
  3675. if ($isSyncModel) continue;
  3676. // 查询任务状态
  3677. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3678. if ($statusInfo['status'] === 'success') {
  3679. $task->updateStatus('success', [
  3680. 'result_url' => $statusInfo['result_url'],
  3681. 'result_json' => $statusInfo['result_json'] ?? []
  3682. ]);
  3683. // 同步调整分镜图片状态和结果
  3684. if (getProp($task, 'alias_segment_id')) {
  3685. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3686. 'img_url' => $statusInfo['result_url'][0],
  3687. 'pic_task_status' => '已完成',
  3688. ]);
  3689. }
  3690. $img_url = $statusInfo['result_url'][0];
  3691. break;
  3692. } elseif ($statusInfo['status'] === 'failed') {
  3693. $task->updateStatus('failed', [
  3694. 'error_message' => $statusInfo['error_message'],
  3695. 'result_json' => $statusInfo['result_json'] ?? []
  3696. ]);
  3697. if (getProp($task, 'alias_segment_id')) {
  3698. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3699. 'pic_task_status' => '失败',
  3700. ]);
  3701. }
  3702. break;
  3703. }
  3704. $start_count++;
  3705. }
  3706. return $img_url;
  3707. }
  3708. /**
  3709. * 从分镜内容中提取涉及的角色
  3710. */
  3711. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3712. $found_characters = [];
  3713. foreach ($available_characters as $character) {
  3714. // 检查角色名称是否在分镜内容中出现
  3715. if (strpos($segment_content, $character) !== false) {
  3716. $found_characters[] = $character;
  3717. }
  3718. }
  3719. if (!$found_characters) {
  3720. foreach ($roles as $character) {
  3721. // 检查角色名称是否在分镜内容中出现
  3722. if (strpos($segment_content, $character) !== false) {
  3723. $found_characters[] = $character;
  3724. }
  3725. }
  3726. }
  3727. return array_unique($found_characters);
  3728. }
  3729. // 从分镜剧本中提取关键字段
  3730. private function handleSegmentContent(&$data) {
  3731. $segmentContent = getProp($data, 'segment_content');
  3732. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3733. $segmentData = [
  3734. 'description' => '',
  3735. 'composition' => '',
  3736. 'camera_movement' => '',
  3737. 'voice_actor' => '',
  3738. 'dialogue' => '',
  3739. 'frame_type' => '',
  3740. 'scene' => '', // 场景
  3741. 'characters' => '', // 出镜角色
  3742. 'tail_frame' => '', // 尾帧描述
  3743. 'emotion' => '中性', // 情感
  3744. 'gender' => '0', // 性别(0未知,1男,2女)
  3745. 'speed_ratio' => 0, // 语速
  3746. 'loudness_ratio' => 0, // 音量
  3747. 'emotion_scale' => 4, // 情感强度
  3748. 'pitch' => 0, // 音调
  3749. ];
  3750. // 用于存储需要从 segment_content 中移除的匹配项
  3751. $replaceEmptyArr = [];
  3752. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3753. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3754. $segmentData['description'] = trim($descMatch[1]);
  3755. $data['description'] = trim($descMatch[1]);
  3756. }
  3757. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3758. $segmentData['composition'] = trim($compMatch[1]);
  3759. $data['composition'] = trim($compMatch[1]);
  3760. }
  3761. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3762. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3763. $data['camera_movement'] = trim($cameraMatch[1]);
  3764. }
  3765. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3766. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3767. $data['voice_actor'] = trim($voiceMatch[1]);
  3768. }
  3769. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3770. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3771. $data['dialogue'] = trim($dialogueMatch[1]);
  3772. }
  3773. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3774. $segmentData['frame_type'] = trim($frameMatch[1]);
  3775. $data['frame_type'] = trim($frameMatch[1]);
  3776. }
  3777. // 场景字段
  3778. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3779. $segmentData['scene'] = trim($sceneMatch[1]);
  3780. $data['scene'] = trim($sceneMatch[1]);
  3781. }
  3782. // 出镜角色字段
  3783. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3784. $segmentData['characters'] = trim($charactersMatch[1]);
  3785. $data['characters'] = trim($charactersMatch[1]);
  3786. }
  3787. // 尾帧描述字段
  3788. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3789. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3790. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3791. }
  3792. // 情感字段
  3793. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3794. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3795. $segmentData['emotion'] = trim($emotionMatch[1]);
  3796. $data['emotion'] = trim($emotionMatch[1]);
  3797. }
  3798. // 性别字段
  3799. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3800. $replaceEmptyArr[] = trim($genderMatch[0]);
  3801. $genderStr = trim($genderMatch[1]);
  3802. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3803. $segmentData['gender'] = '1';
  3804. $data['gender'] = '1';
  3805. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3806. $segmentData['gender'] = '2';
  3807. $data['gender'] = '2';
  3808. } else {
  3809. $segmentData['gender'] = '0';
  3810. $data['gender'] = '0';
  3811. }
  3812. }
  3813. // 语速字段
  3814. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3815. $replaceEmptyArr[] = trim($speedMatch[0]);
  3816. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3817. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3818. }
  3819. // 音量字段
  3820. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3821. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3822. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3823. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3824. }
  3825. // 情感强度字段
  3826. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3827. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3828. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3829. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3830. }
  3831. // 音调字段
  3832. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3833. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3834. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3835. $data['pitch'] = (int)trim($pitchMatch[1]);
  3836. }
  3837. // 从 segment_content 中移除已提取的配音参数字段
  3838. if (!empty($replaceEmptyArr)) {
  3839. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3840. }
  3841. // 如果有配音角色,查询音色信息并验证情感
  3842. $voice_actor = $segmentData['voice_actor'];
  3843. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3844. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3845. $anime_id = getProp($data, 'anime_id');
  3846. $episode_id = getProp($data, 'episode_id');
  3847. // 优先从剧集的角色列表中查找
  3848. $roles = [];
  3849. if ($episode_id) {
  3850. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3851. if ($episode && getProp($episode, 'roles')) {
  3852. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3853. }
  3854. }
  3855. // 如果剧集中没有,从动漫的角色列表中查找
  3856. if (empty($roles) && $anime_id) {
  3857. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3858. if ($anime && getProp($anime, 'roles')) {
  3859. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3860. }
  3861. }
  3862. // 查找匹配的角色音色信息
  3863. $timbre_info = null;
  3864. foreach ($roles as $role) {
  3865. if (getProp($role, 'role') === $voice_actor) {
  3866. $timbre_info = $role;
  3867. break;
  3868. }
  3869. }
  3870. // 如果找到音色信息,添加到数据中
  3871. if ($timbre_info) {
  3872. $voice_type = getProp($timbre_info, 'voice_type');
  3873. $voice_name = getProp($timbre_info, 'voice_name');
  3874. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3875. if ($voice_type) {
  3876. $data['voice_type'] = $voice_type;
  3877. $segmentData['voice_type'] = $voice_type;
  3878. }
  3879. if ($voice_name) {
  3880. $data['voice_name'] = $voice_name;
  3881. $segmentData['voice_name'] = $voice_name;
  3882. }
  3883. if ($voice_audio_url) {
  3884. $data['voice_audio_url'] = $voice_audio_url;
  3885. $segmentData['voice_audio_url'] = $voice_audio_url;
  3886. }
  3887. // 验证情感是否在音色支持的情感列表中
  3888. if ($voice_type) {
  3889. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3890. if ($timbre_emotion) {
  3891. $timbre_emotion = explode(',', $timbre_emotion);
  3892. } else {
  3893. $timbre_emotion = [];
  3894. }
  3895. $emotion = getProp($segmentData, 'emotion', '中性');
  3896. if (!in_array($emotion, $timbre_emotion)) {
  3897. $emotion = '中性';
  3898. }
  3899. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3900. $emotion_list = array_flip($emotion_list);
  3901. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3902. $data['emotion_type'] = $emotion_type;
  3903. $segmentData['emotion_type'] = $emotion_type;
  3904. }
  3905. }
  3906. }
  3907. return $segmentData;
  3908. }
  3909. public function createSegmentVideoTask($data) {
  3910. $segment_id = getProp($data, 'segment_id');
  3911. $tail_frame = getProp($data, 'tail_frame');
  3912. $first_frame_url = getProp($data, 'first_frame_url');
  3913. $tail_frame_url = getProp($data, 'tail_frame_url');
  3914. $generate_audio = getProp($data, 'generate_audio', 0);
  3915. if (!$segment_id) {
  3916. Utils::throwError('1002:分镜ID不能为空');
  3917. }
  3918. // 获取分镜信息
  3919. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3920. if (!$segment) {
  3921. Utils::throwError('20003:分镜不存在');
  3922. }
  3923. $segment = (array)$segment;
  3924. $episode_id = getProp($segment, 'episode_id');
  3925. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3926. if (!$ratio) $ratio = '9:16';
  3927. // 获取分镜内容
  3928. $segmentContent = getProp($segment, 'segment_content', '');
  3929. // 检查 $segmentContent 中是否已有尾帧描述
  3930. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3931. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3932. $finalTailFrame = '';
  3933. if ($tail_frame) {
  3934. // 用户输入了尾帧描述,优先使用
  3935. $finalTailFrame = $tail_frame;
  3936. // 如果 segmentContent 中已有尾帧描述,需要替换
  3937. if ($contentHasTailFrame) {
  3938. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3939. }
  3940. } elseif ($contentHasTailFrame) {
  3941. // segmentContent 中有尾帧描述,使用它
  3942. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3943. } else {
  3944. // 两者都没有,使用分镜表中的尾帧描述
  3945. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3946. }
  3947. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3948. $hasDialogue = false;
  3949. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3950. $dialogue = trim($dialogueMatch[1]);
  3951. // 如果台词不为空且不是"无"
  3952. if (!empty($dialogue) && $dialogue !== '无') {
  3953. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3954. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3955. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3956. $hasDialogue = true;
  3957. }
  3958. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3959. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3960. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3961. if (!preg_match('/^[“]/', $dialogue)) {
  3962. $dialogue = '“' . $dialogue;
  3963. }
  3964. if (!preg_match('/[”]$/', $dialogue)) {
  3965. $dialogue .= '”';
  3966. }
  3967. // 将修改后的台词替换回 $segmentContent
  3968. $originalDialogue = $dialogueMatch[1];
  3969. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3970. }
  3971. }
  3972. // 构建完整的提示词
  3973. $fullPrompt = $segmentContent;
  3974. if ($finalTailFrame && !$contentHasTailFrame) {
  3975. // 只有当 segmentContent 中没有尾帧描述时才追加
  3976. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3977. }
  3978. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3979. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3980. $fullPrompt = trim($fullPrompt);
  3981. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3982. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3983. // 智能选择视频时长
  3984. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3985. $videoDuration = -1;
  3986. // 处理视频模型
  3987. $model = getProp($data, 'model');
  3988. if (!$model) {
  3989. // 用户没有输入,从episode表获取
  3990. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3991. $model = getProp($episode, 'video_model');
  3992. if (!$model) {
  3993. // episode表也没有,使用默认值
  3994. $model = 'doubao-seedance-1-5-pro-251215';
  3995. }
  3996. }
  3997. // 验证模型是否在可用模型表中
  3998. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3999. $model = 'doubao-seedance-1-5-pro-251215';
  4000. }
  4001. // 保存到episode表
  4002. $episode_id = getProp($segment, 'episode_id');
  4003. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4004. 'video_model' => $model,
  4005. 'updated_at' => date('Y-m-d H:i:s')
  4006. ]);
  4007. // 构建视频生成参数
  4008. $videoParams = [
  4009. 'model' => $model,
  4010. 'alias_segment_id' => $segment_id,
  4011. 'prompt' => trim($fullPrompt),
  4012. 'video_duration' => $videoDuration,
  4013. 'video_resolution' => '720P',
  4014. 'seed' => -1,
  4015. 'ratio' => $ratio,
  4016. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4017. 'draft' => false,
  4018. 'watermark' => false,
  4019. 'camera_fixed' => false,
  4020. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4021. ];
  4022. // 如果分镜有图片,作为首帧
  4023. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  4024. $hasVideo = !empty(getProp($segment, 'video_url'));
  4025. if ($hasImage) {
  4026. if ($first_frame_url) {
  4027. $videoParams['first_frame_url'] = $first_frame_url;
  4028. }else {
  4029. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4030. }
  4031. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4032. }
  4033. // 构建content数组
  4034. $videoParams['content'] = [
  4035. [
  4036. 'type' => 'text',
  4037. 'text' => $videoParams['prompt'],
  4038. ]
  4039. ];
  4040. // 如果有首帧图片,添加到content中
  4041. if ($hasImage) {
  4042. 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'])) {
  4043. $videoParams['content'][] = [
  4044. 'type' => 'image_url',
  4045. 'image_url' => [
  4046. 'url' => $videoParams['first_frame_url'],
  4047. ],
  4048. 'role' => 'reference_image',
  4049. ];
  4050. if (isset($videoParams['tail_frame_url'])) {
  4051. $videoParams['content'][] = [
  4052. 'type' => 'image_url',
  4053. 'image_url' => [
  4054. 'url' => $videoParams['tail_frame_url'],
  4055. ],
  4056. 'role' => 'reference_image',
  4057. ];
  4058. }
  4059. }else {
  4060. $videoParams['content'][] = [
  4061. 'type' => 'image_url',
  4062. 'image_url' => [
  4063. 'url' => $videoParams['first_frame_url'],
  4064. ],
  4065. 'role' => 'first_frame',
  4066. ];
  4067. if (isset($videoParams['tail_frame_url'])) {
  4068. $videoParams['content'][] = [
  4069. 'type' => 'image_url',
  4070. 'image_url' => [
  4071. 'url' => $videoParams['tail_frame_url'],
  4072. ],
  4073. 'role' => 'last_frame',
  4074. ];
  4075. }
  4076. }
  4077. }
  4078. // 获取配音音频URL
  4079. $audioUrl = getProp($segment, 'audio_url');
  4080. $audioDuration = getProp($segment, 'audio_duration');
  4081. // 音频传入的前提:必须有至少一张图片或一个视频
  4082. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4083. // 余额预检:按预估时长计算所需积分,不足直接报错
  4084. $chargeDuration = (int)ceil((float)$audioDuration);
  4085. if ($chargeDuration <= 0) {
  4086. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4087. }
  4088. $this->pointsService->checkUserPointsEnough(
  4089. $this->pointsService->getVideoChargePoints([
  4090. 'model' => $model,
  4091. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4092. 'video_duration' => $chargeDuration,
  4093. 'ratio' => $ratio,
  4094. 'generate_audio' => $current_generate_audio,
  4095. ])
  4096. );
  4097. // dd($videoParams);
  4098. // 根据模型选择不同的视频生成方法
  4099. if (strpos($model, 'jimeng') !== false) {
  4100. // 即梦模型参数调整
  4101. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4102. unset($videoParams['content']); // 即梦不使用content格式
  4103. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4104. } elseif (strpos($model, 'kling') !== false) {
  4105. // Keling模型参数调整
  4106. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4107. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4108. unset($videoParams['ratio']);
  4109. unset($videoParams['content']); // Keling不使用content格式
  4110. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4111. } elseif (strpos($model, 'zhizhen') !== false) {
  4112. // 智帧20等新模型使用统一API
  4113. // 构建统一API参数
  4114. $unifiedParams = [
  4115. 'model_code' => $model,
  4116. 'alias_segment_id' => $segment_id,
  4117. 'prompt' => trim($fullPrompt),
  4118. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4119. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4120. 'video_ratio' => $ratio,
  4121. 'seed' => -1,
  4122. ];
  4123. // 构建parameters参数
  4124. $parameters = [
  4125. 'seconds' => $unifiedParams['video_duration'],
  4126. 'resolution' => $unifiedParams['video_resolution'],
  4127. 'ratio' => $ratio,
  4128. // 'video_mode' => 'multi_image',
  4129. // 'mode' => 'multi_image',
  4130. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4131. ];
  4132. $hasImage = false;
  4133. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4134. if ($hasImage) {
  4135. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4136. if (isset($videoParams['tail_frame_url'])) {
  4137. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4138. }
  4139. // 只有在有图片的情况下才能添加参考音频
  4140. if ($audioUrl) {
  4141. // $parameters['reference_audios'] = [$audioUrl];
  4142. }
  4143. } else {
  4144. // 没有图片时,记录错误日志
  4145. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4146. 'segment_id' => $segment_id,
  4147. 'model' => $model
  4148. ]);
  4149. }
  4150. $unifiedParams['parameters'] = $parameters;
  4151. // 调用统一API创建任务
  4152. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4153. } else {
  4154. // Seedance模型(默认)
  4155. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4156. if ($this->isKuaikuaiSeedanceModel($model)) {
  4157. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4158. if ($canUseAudio && $audioUrl) {
  4159. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4160. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4161. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4162. // 优化提示词,增加音频相关描述
  4163. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4164. $videoParams['prompt'] = $audioPrompt;
  4165. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4166. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4167. }
  4168. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4169. } 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'])) {
  4170. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4171. // 添加配音音频到content中
  4172. $videoParams['content'][] = [
  4173. 'type' => 'audio_url',
  4174. 'audio_url' => [
  4175. 'url' => $audioUrl,
  4176. ],
  4177. 'role' => 'reference_audio',
  4178. ];
  4179. // 优化提示词,增加音频相关描述
  4180. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4181. $videoParams['prompt'] = $audioPrompt;
  4182. $videoParams['content'][0]['text'] = $audioPrompt;
  4183. } else {
  4184. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4185. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4186. }
  4187. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4188. }
  4189. }
  4190. // 更新分镜表的视频任务信息
  4191. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4192. 'video_task_id' => $task->id,
  4193. 'video_task_status' => '生成中',
  4194. 'generate_audio' => $generate_audio,
  4195. 'updated_at' => date('Y-m-d H:i:s')
  4196. ]);
  4197. return [
  4198. 'task_id' => $task->id,
  4199. 'status' => $task->status,
  4200. 'segment_id' => $segment_id,
  4201. 'video_duration' => $videoDuration
  4202. ];
  4203. }
  4204. /**
  4205. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4206. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4207. *
  4208. * @param string $model
  4209. * @return bool
  4210. */
  4211. public function isKuaikuaiSeedanceModel(string $model): bool
  4212. {
  4213. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4214. }
  4215. /**
  4216. * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
  4217. *
  4218. * @param string $model
  4219. * @return bool
  4220. */
  4221. public function isBaiduSeedanceModel(string $model): bool
  4222. {
  4223. return in_array($model, [
  4224. 'baidu-doubao-seedance-2-0-260128',
  4225. 'baidu-doubao-seedance-2-0-fast-260128',
  4226. 'baidu-doubao-seedance-2-0-mini-260615',
  4227. 'baidu-doubao-seedance-2-5-260628',
  4228. ], true);
  4229. }
  4230. /**
  4231. * 是否为海外百度Seedance(dreamina真人素材空间)模型
  4232. * 系统内使用 baidu-dreamina- 前缀名,请求网关时映射为 dreamina-* 原名
  4233. *
  4234. * @param string $model
  4235. * @return bool
  4236. */
  4237. public function isOverseasBaiduSeedanceModel(string $model): bool
  4238. {
  4239. return in_array($model, [
  4240. 'baidu-dreamina-seedance-2-0-260128',
  4241. 'baidu-dreamina-seedance-2-0-fast-260128',
  4242. 'baidu-dreamina-seedance-2-0-mini-260615',
  4243. 'baidu-dreamina-seedance-2-5-260628',
  4244. ], true);
  4245. }
  4246. /**
  4247. * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-doubao-* / baidu-dreamina-* / 快快AI seed-2 系列)
  4248. * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
  4249. *
  4250. * @param string $model
  4251. * @return bool
  4252. */
  4253. public function isSeedance20SeriesModel(string $model): bool
  4254. {
  4255. return strpos($model, 'doubao-seedance-2.0') !== false
  4256. || $this->isKuaikuaiSeedanceModel($model)
  4257. || $this->isBaiduSeedanceModel($model)
  4258. || $this->isOverseasBaiduSeedanceModel($model);
  4259. }
  4260. public function createActVideoTask($data) {
  4261. $act_id = getProp($data, 'act_id');
  4262. $first_frame_url = getProp($data, 'first_frame_url');
  4263. $tail_frame_url = getProp($data, 'tail_frame_url');
  4264. $generate_audio = getProp($data, 'generate_audio', 1);
  4265. $video_duration = getProp($data, 'video_duration');
  4266. $video_resolution = getProp($data, 'video_resolution');
  4267. $ratio = getProp($data, 'ratio');
  4268. $products = getProp($data, 'products', []);
  4269. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4270. if (!is_array($reference_images) || !is_array($products)) {
  4271. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4272. }
  4273. if (!$act_id) {
  4274. Utils::throwError('1002:片段ID不能为空');
  4275. }
  4276. // 获取片段信息
  4277. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4278. if (!$act) {
  4279. Utils::throwError('20003:片段不存在');
  4280. }
  4281. $act = (array)$act;
  4282. $anime_id = getProp($act, 'anime_id');
  4283. $episode_id = getProp($act, 'episode_id');
  4284. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4285. $ace_mode = getProp($anime, 'ace_mode');
  4286. $art_style_type = getProp($anime, 'art_style_type');
  4287. $art_style = getProp($anime, 'art_style');
  4288. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4289. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4290. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4291. // 将资产中新出现的资产放到extra_products中
  4292. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4293. if (!empty($products) && $episode) {
  4294. // 获取剧集中的角色、场景和道具列表
  4295. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4296. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4297. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4298. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4299. // 构建角色名称列表
  4300. $role_names = array_column($roles, 'role');
  4301. // 构建场景名称列表
  4302. $scene_names = array_column($scenes, 'scene');
  4303. // 构建道具名称列表
  4304. $prop_names = array_column($props, 'prop');
  4305. // 遍历传入的products
  4306. foreach ($products as $product) {
  4307. $product_name = getProp($product, 'product_name');
  4308. // 如果product_name不在roles、scenes和props中
  4309. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4310. // 查找是否在extra_products中存在同名的
  4311. $found = false;
  4312. foreach ($extra_products as $key => $extra_product) {
  4313. if (getProp($extra_product, 'product_name') === $product_name) {
  4314. // 有同名的则覆盖
  4315. $extra_products[$key] = $product;
  4316. $found = true;
  4317. break;
  4318. }
  4319. }
  4320. // 没有则新增
  4321. if (!$found) {
  4322. $extra_products[] = $product;
  4323. }
  4324. }
  4325. }
  4326. if ($extra_products) {
  4327. // 保存到数据库
  4328. DB::table('mp_anime_episodes')
  4329. ->where('id', $episode_id)
  4330. ->update([
  4331. 'extra_products' => json_encode($extra_products, 256),
  4332. 'updated_at' => date('Y-m-d H:i:s')
  4333. ]);
  4334. }
  4335. }
  4336. // 获取分镜内容
  4337. $actContent = getProp($act, 'act_show_content', '');
  4338. // 音效同出(默认使用)
  4339. $current_generate_audio = $generate_audio ? 1 : 0;
  4340. // 构建完整的提示词
  4341. $processResult = $this->processActContentWithProducts($actContent, $products);
  4342. $fullPrompt = $processResult['content'];
  4343. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4344. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4345. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4346. // 处理视频模型
  4347. $model = getProp($data, 'model');
  4348. if (!$model) {
  4349. $model = getProp($episode, 'video_model');
  4350. if (!$model) {
  4351. // episode表也没有,使用默认值
  4352. $model = 'seed-2';
  4353. }
  4354. }
  4355. // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
  4356. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  4357. if (!in_array($model, $valid_models)) {
  4358. $model = 'seed-2';
  4359. }
  4360. // 保存到episode表(仅在专用方法中更新模型)
  4361. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4362. // 'video_model' => $model,
  4363. // 'updated_at' => date('Y-m-d H:i:s')
  4364. // ]);
  4365. // 余额预检:按预估时长计算所需积分,不足直接报错
  4366. $chargeDuration = (int)$videoDuration;
  4367. if ($chargeDuration <= 0) {
  4368. $chargeDuration = 5; // 无时长时按默认5秒预估
  4369. }
  4370. $this->pointsService->checkUserPointsEnough(
  4371. $this->pointsService->getVideoChargePoints([
  4372. 'model' => $model,
  4373. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4374. 'video_duration' => $chargeDuration,
  4375. 'ratio' => $ratio,
  4376. 'generate_audio' => $current_generate_audio,
  4377. ])
  4378. );
  4379. // 构建视频生成参数
  4380. $videoParams = [
  4381. 'model' => $model,
  4382. 'alias_act_id' => $act_id,
  4383. 'prompt' => trim($fullPrompt),
  4384. 'video_duration' => $videoDuration,
  4385. 'video_resolution' => $video_resolution,
  4386. 'seed' => -1,
  4387. 'ratio' => $ratio,
  4388. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4389. 'draft' => false,
  4390. 'watermark' => false,
  4391. 'camera_fixed' => false,
  4392. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4393. ];
  4394. // 如果分镜有图片,作为首帧
  4395. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4396. $hasVideo = !empty(getProp($act, 'video_url'));
  4397. if ($hasImage) {
  4398. if ($first_frame_url) {
  4399. $videoParams['first_frame_url'] = $first_frame_url;
  4400. }else {
  4401. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4402. }
  4403. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4404. }
  4405. // 构建content数组
  4406. $videoParams['content'] = [
  4407. [
  4408. 'type' => 'text',
  4409. 'text' => $videoParams['prompt'],
  4410. ]
  4411. ];
  4412. // 如果有首帧图片,添加到content中
  4413. if ($hasImage) {
  4414. 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'])) {
  4415. $videoParams['content'][] = [
  4416. 'type' => 'image_url',
  4417. 'image_url' => [
  4418. 'url' => $videoParams['first_frame_url'],
  4419. ],
  4420. 'role' => 'reference_image',
  4421. ];
  4422. if (isset($videoParams['tail_frame_url'])) {
  4423. $videoParams['content'][] = [
  4424. 'type' => 'image_url',
  4425. 'image_url' => [
  4426. 'url' => $videoParams['tail_frame_url'],
  4427. ],
  4428. 'role' => 'reference_image',
  4429. ];
  4430. }
  4431. }else {
  4432. $videoParams['content'][] = [
  4433. 'type' => 'image_url',
  4434. 'image_url' => [
  4435. 'url' => $videoParams['first_frame_url'],
  4436. ],
  4437. 'role' => 'first_frame',
  4438. ];
  4439. if (isset($videoParams['tail_frame_url'])) {
  4440. $videoParams['content'][] = [
  4441. 'type' => 'image_url',
  4442. 'image_url' => [
  4443. 'url' => $videoParams['tail_frame_url'],
  4444. ],
  4445. 'role' => 'last_frame',
  4446. ];
  4447. }
  4448. }
  4449. }
  4450. // dd($videoParams);
  4451. // 根据模型选择不同的视频生成方法
  4452. try {
  4453. if (strpos($model, 'jimeng') !== false) {
  4454. // 即梦模型参数调整
  4455. unset($videoParams['content']); // 即梦不使用content格式
  4456. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4457. } elseif (strpos($model, 'kling') !== false) {
  4458. // Keling模型参数调整
  4459. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4460. unset($videoParams['ratio']);
  4461. unset($videoParams['content']); // Keling不使用content格式
  4462. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4463. } elseif (strpos($model, 'zhizhen') !== false) {
  4464. // 智帧20等新模型使用统一API
  4465. // 构建统一API参数
  4466. $unifiedParams = [
  4467. 'model_code' => $model,
  4468. 'alias_act_id' => $act_id,
  4469. 'prompt' => trim($fullPrompt),
  4470. 'video_duration' => $videoDuration,
  4471. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4472. 'video_ratio' => $ratio,
  4473. 'seed' => -1,
  4474. ];
  4475. // 构建parameters参数
  4476. $parameters = [
  4477. 'seconds' => $unifiedParams['video_duration'],
  4478. 'resolution' => $unifiedParams['video_resolution'],
  4479. 'ratio' => $ratio,
  4480. // 'video_mode' => 'multi_image',
  4481. // 'mode' => 'multi_image',
  4482. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4483. ];
  4484. $hasImage = false;
  4485. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4486. if ($hasImage) {
  4487. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4488. if (isset($videoParams['tail_frame_url'])) {
  4489. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4490. }
  4491. } else {
  4492. // 没有图片时,记录错误日志
  4493. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4494. 'act_id' => $act_id,
  4495. 'model' => $model
  4496. ]);
  4497. }
  4498. if ($reference_images) {
  4499. // 限制只传入9张参考图
  4500. $reference_images = array_slice($reference_images, 0, 9);
  4501. // 在处理之前先保存原始reference_images到任务参数中
  4502. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4503. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4504. $parameters['reference_images'] = $reference_images;
  4505. $parameters['video_mode'] = 'multi_image';
  4506. $parameters['mode'] = 'multi_image';
  4507. }
  4508. $unifiedParams['parameters'] = $parameters;
  4509. // 调用统一API创建任务
  4510. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4511. } elseif ($this->isSeedance20SeriesModel($model)) {
  4512. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4513. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4514. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4515. // 保存原始参考图用于任务记录
  4516. $videoParams['reference_images'] = $reference_images;
  4517. if ($reference_images) {
  4518. // 限制只传入9张参考图
  4519. $reference_images = array_slice($reference_images, 0, 9);
  4520. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4521. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4522. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4523. $reference_image_assets = $isKuaikuai
  4524. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4525. : ($isDreamina
  4526. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $fullPrompt)
  4527. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt));
  4528. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4529. $videoParams['prompt'] = trim($fullPrompt);
  4530. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4531. $videoParams['reference_image_assets'] = $reference_image_assets;
  4532. }
  4533. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4534. if ($isKuaikuai) {
  4535. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4536. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4537. } else {
  4538. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4539. }
  4540. } else {
  4541. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4542. }
  4543. } catch (ApiException $e) {
  4544. // 上游调用抛出的网关异常统一做友好化处理;本地业务错误(非1001)保持原提示不变
  4545. if ($e->getCode() === 1001) {
  4546. Utils::throwError('1001:' . mapErrorMessage($e->getMessage()));
  4547. }
  4548. throw $e;
  4549. } catch (\Exception $e) {
  4550. // 其他未包装的异常,同样只对报错信息做格式化,便于前端展示友好提示
  4551. Utils::throwError('20003:' . mapErrorMessage($e->getMessage()));
  4552. }
  4553. // 更新分镜表的视频任务信息
  4554. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4555. 'video_task_id' => $task->id,
  4556. 'video_task_status' => '生成中',
  4557. 'generate_audio' => $generate_audio,
  4558. 'updated_at' => date('Y-m-d H:i:s')
  4559. ]);
  4560. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4561. $episode_number = getProp($act, 'episode_number');
  4562. $act_number = getProp($act, 'act_number');
  4563. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4564. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4565. }
  4566. $result = [
  4567. 'task_id' => $task->id,
  4568. 'status' => $task->status,
  4569. 'act_id' => $act_id,
  4570. 'video_duration' => $videoDuration
  4571. ];
  4572. // 仅当任务提交阶段就已失败时,附带格式化后的错误信息;正常返回结构不受影响
  4573. if ($task->status === 'failed' && !empty($task->error_message)) {
  4574. $result['error_message'] = mapErrorMessage($task->error_message);
  4575. }
  4576. return $result;
  4577. }
  4578. /**
  4579. * 文生视频通用方法
  4580. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4581. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4582. *
  4583. * @param array $data 请求参数
  4584. * @return array
  4585. */
  4586. public function generateVideo($data) {
  4587. $prompt = getProp($data, 'prompt');
  4588. if (empty($prompt)) {
  4589. Utils::throwError('20003:提示词不能为空');
  4590. }
  4591. $model = getProp($data, 'model');
  4592. if (!$model) {
  4593. $model = 'seed-2';
  4594. }
  4595. // 验证模型是否在可用模型表中
  4596. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4597. Utils::throwError('20003:该模型已不可用,请更换!');
  4598. }
  4599. $video_duration = getProp($data, 'video_duration', 5);
  4600. // 默认超分720p档(按480p生成后本地超分到720p);480p为原始档需前端显式指定
  4601. $video_resolution = getProp($data, 'video_resolution', 'sr_720p');
  4602. $ratio = getProp($data, 'ratio', '9:16');
  4603. $generate_audio = getProp($data, 'generate_audio', 1);
  4604. $seed = getProp($data, 'seed', -1);
  4605. $first_frame_url = getProp($data, 'first_frame_url');
  4606. $tail_frame_url = getProp($data, 'tail_frame_url');
  4607. // 参考图(支持数组或JSON字符串,最多9张)
  4608. $reference_images = getProp($data, 'reference_images', []);
  4609. if (is_string($reference_images)) {
  4610. $reference_images = json_decode($reference_images, true) ?: [];
  4611. }
  4612. if (!is_array($reference_images)) {
  4613. Utils::throwError('20003:参考图格式不正确');
  4614. }
  4615. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4616. $reference_images = array_slice($reference_images, 0, 9);
  4617. // 参考视频(支持数组或JSON字符串,最多3个)
  4618. $reference_videos = getProp($data, 'reference_videos', []);
  4619. if (is_string($reference_videos)) {
  4620. $reference_videos = json_decode($reference_videos, true) ?: [];
  4621. }
  4622. if (!is_array($reference_videos)) {
  4623. Utils::throwError('20003:参考视频格式不正确');
  4624. }
  4625. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4626. if (count($reference_videos) > 3) {
  4627. Utils::throwError('20003:参考视频最多选择3个');
  4628. }
  4629. $reference_videos = array_slice($reference_videos, 0, 3);
  4630. // 参考音频(支持数组或JSON字符串,最多3个)
  4631. $reference_audios = getProp($data, 'reference_audios', []);
  4632. if (is_string($reference_audios)) {
  4633. $reference_audios = json_decode($reference_audios, true) ?: [];
  4634. }
  4635. if (!is_array($reference_audios)) {
  4636. Utils::throwError('20003:参考音频格式不正确');
  4637. }
  4638. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4639. if (count($reference_audios) > 3) {
  4640. Utils::throwError('20003:参考音频最多选择3个');
  4641. }
  4642. $reference_audios = array_slice($reference_audios, 0, 3);
  4643. // 余额预检:按预估时长计算所需积分,不足直接报错
  4644. $chargeDuration = (int)ceil((float)$video_duration);
  4645. if ($chargeDuration <= 0) {
  4646. $chargeDuration = 5; // 无时长时按默认5秒预估
  4647. }
  4648. $this->pointsService->checkUserPointsEnough(
  4649. $this->pointsService->getVideoChargePoints([
  4650. 'model' => $model,
  4651. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4652. 'video_duration' => $chargeDuration,
  4653. 'ratio' => $ratio,
  4654. 'generate_audio' => (int)$generate_audio,
  4655. ])
  4656. );
  4657. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4658. $videoParams = [
  4659. 'model' => $model,
  4660. 'prompt' => $prompt,
  4661. 'video_duration' => $video_duration,
  4662. 'video_resolution' => $video_resolution,
  4663. 'seed' => $seed,
  4664. 'ratio' => $ratio,
  4665. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4666. 'draft' => getProp($data, 'draft', false),
  4667. 'watermark' => getProp($data, 'watermark', false),
  4668. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4669. ];
  4670. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4671. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4672. // 构建content数组
  4673. $videoParams['content'] = [
  4674. [
  4675. 'type' => 'text',
  4676. 'text' => $prompt,
  4677. ]
  4678. ];
  4679. // 根据模型选择不同的视频生成方法
  4680. if (strpos($model, 'jimeng') !== false) {
  4681. // 即梦模型参数调整
  4682. unset($videoParams['content']); // 即梦不使用content格式
  4683. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4684. } elseif (strpos($model, 'kling') !== false) {
  4685. // 可灵模型参数调整
  4686. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4687. unset($videoParams['ratio']);
  4688. unset($videoParams['content']); // 可灵不使用content格式
  4689. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4690. } elseif (strpos($model, 'zhizhen') !== false) {
  4691. // 智帧等新模型使用统一API
  4692. $unifiedParams = [
  4693. 'model_code' => $model,
  4694. 'prompt' => $prompt,
  4695. 'video_duration' => $video_duration,
  4696. 'video_resolution' => strtolower($video_resolution),
  4697. 'video_ratio' => $ratio,
  4698. 'seed' => $seed,
  4699. ];
  4700. // 构建parameters参数
  4701. $parameters = [
  4702. 'seconds' => $unifiedParams['video_duration'],
  4703. 'resolution' => $unifiedParams['video_resolution'],
  4704. 'ratio' => $ratio,
  4705. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4706. ];
  4707. // 首帧和尾帧
  4708. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4709. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4710. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4711. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4712. if ($refImageUrls) {
  4713. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4714. }
  4715. // 参考图处理
  4716. if ($reference_images) {
  4717. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4718. $parameters['reference_images'] = $reference_images;
  4719. $parameters['video_mode'] = 'multi_image';
  4720. $parameters['mode'] = 'multi_image';
  4721. }
  4722. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4723. if ($reference_videos) {
  4724. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4725. $parameters['reference_videos'] = $reference_videos;
  4726. }
  4727. if ($reference_audios) {
  4728. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4729. $parameters['reference_audios'] = $reference_audios;
  4730. }
  4731. $unifiedParams['parameters'] = $parameters;
  4732. // 调用统一API创建任务
  4733. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4734. } elseif ($this->isSeedance20SeriesModel($model)) {
  4735. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4736. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4737. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4738. $videoParams['reference_images'] = $reference_images;
  4739. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4740. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4741. if ($refImageUrls) {
  4742. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4743. }
  4744. if ($reference_images) {
  4745. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI)
  4746. $reference_image_assets = $isKuaikuai
  4747. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4748. : ($isDreamina
  4749. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $videoParams['prompt'])
  4750. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']));
  4751. $videoParams['reference_image_assets'] = $reference_image_assets;
  4752. }
  4753. // 参考视频上传为素材(国内百度/海外百度dreamina/快快AI)
  4754. if ($reference_videos) {
  4755. $reference_video_assets = $isKuaikuai
  4756. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4757. : ($isDreamina
  4758. ? $this->aiVideoGenerationService->processReferenceVideosToBaiduDreaminaAssets($reference_videos, $videoParams['prompt'])
  4759. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']));
  4760. $videoParams['reference_video_assets'] = $reference_video_assets;
  4761. }
  4762. // 参考音频上传为素材(国内百度/海外百度dreamina/快快AI)
  4763. if ($reference_audios) {
  4764. $reference_audio_assets = $isKuaikuai
  4765. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4766. : ($isDreamina
  4767. ? $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($reference_audios, $videoParams['prompt'])
  4768. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']));
  4769. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4770. }
  4771. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4772. if ($reference_images || $reference_videos || $reference_audios) {
  4773. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4774. }
  4775. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4776. if ($isKuaikuai) {
  4777. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4778. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4779. } else {
  4780. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4781. }
  4782. } else {
  4783. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4784. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4785. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4786. if ($refImageUrls) {
  4787. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4788. }
  4789. if ($reference_videos) {
  4790. foreach ($reference_videos as $videoUrl) {
  4791. $videoParams['content'][] = [
  4792. 'type' => 'video_url',
  4793. 'video_url' => [
  4794. 'url' => $videoUrl,
  4795. ],
  4796. 'role' => 'reference_video',
  4797. ];
  4798. }
  4799. }
  4800. if ($reference_audios) {
  4801. foreach ($reference_audios as $audioUrl) {
  4802. $videoParams['content'][] = [
  4803. 'type' => 'audio_url',
  4804. 'audio_url' => [
  4805. 'url' => $audioUrl,
  4806. ],
  4807. 'role' => 'reference_audio',
  4808. ];
  4809. }
  4810. }
  4811. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4812. }
  4813. return [
  4814. 'task_id' => $task->id,
  4815. 'status' => $task->status,
  4816. 'model' => $model,
  4817. 'video_duration' => $video_duration,
  4818. 'video_resolution' => $video_resolution,
  4819. 'ratio' => $ratio
  4820. ];
  4821. }
  4822. /**
  4823. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4824. *
  4825. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4826. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4827. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4828. *
  4829. * @param array $data
  4830. * @return array
  4831. */
  4832. public function previewCharge(array $data): array
  4833. {
  4834. $mode = (string)getProp($data, 'mode', '');
  4835. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4836. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4837. }
  4838. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4839. $scene = (string)getProp($data, 'scene', 'video_generation');
  4840. // 未显式传scene且带参考视频时,自动按video_to_video定价
  4841. if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
  4842. $scene = 'video_to_video';
  4843. }
  4844. $items = [];
  4845. $model = '';
  4846. $resolution = '';
  4847. if ($mode === 'video') {
  4848. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4849. $model = (string)getProp($data, 'model', '');
  4850. if (!$model) {
  4851. Utils::throwError('1002:model参数不能为空');
  4852. }
  4853. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4854. $duration = (int)getProp($data, 'video_duration', 5);
  4855. if ($duration <= 0) {
  4856. $duration = 5;
  4857. }
  4858. $count = max(1, (int)getProp($data, 'count', 1));
  4859. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4860. 'model' => $model,
  4861. 'video_resolution' => $resolution,
  4862. 'video_duration' => $duration,
  4863. 'mode' => $scene,
  4864. ]);
  4865. $points = $pointsPerVideo * $count;
  4866. $items[] = [
  4867. 'type' => 'video',
  4868. 'model' => $model,
  4869. 'video_resolution' => $resolution,
  4870. 'video_duration' => $duration,
  4871. 'count' => $count,
  4872. 'points' => $points,
  4873. ];
  4874. } elseif ($mode === 'image') {
  4875. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4876. $model = (string)getProp($data, 'model', '');
  4877. if (!$model) {
  4878. Utils::throwError('1002:model参数不能为空');
  4879. }
  4880. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4881. if (!$resolution) {
  4882. $width = (int)getProp($data, 'width', 0);
  4883. $height = (int)getProp($data, 'height', 0);
  4884. if ($width <= 0 || $height <= 0) {
  4885. $width = 1600;
  4886. $height = 2848;
  4887. }
  4888. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4889. }
  4890. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4891. $points = $this->pointsService->getImageChargePoints([
  4892. 'model' => $model,
  4893. 'resolution' => $resolution,
  4894. ]) * $imageNum;
  4895. $items[] = [
  4896. 'type' => 'image',
  4897. 'model' => $model,
  4898. 'resolution' => $resolution,
  4899. 'image_num' => $imageNum,
  4900. 'points' => $points,
  4901. ];
  4902. } else {
  4903. // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
  4904. // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
  4905. $priceType = (string)getProp($data, 'price_type', 'special');
  4906. if (!in_array($priceType, ['special', 'normal'], true)) {
  4907. Utils::throwError('1003:price_type参数仅支持special或normal');
  4908. }
  4909. $count = max(1, (int)getProp($data, 'count', 1));
  4910. $animeId = getProp($data, 'anime_id');
  4911. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4912. if ($animeId && $generateEpisodes > 0) {
  4913. // 批量生成分集按 special 档预估,与实际扣费口径一致
  4914. $priceType = 'special';
  4915. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4916. ->where('anime_id', $animeId)
  4917. ->where('is_default', 1)
  4918. ->max('episode_number');
  4919. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4920. $startEpisodeNumber = $currentMaxEpisode + 1;
  4921. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4922. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4923. ->where('anime_id', $animeId)
  4924. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4925. ->whereIn('status', ['pending', 'processing', 'completed'])
  4926. ->count();
  4927. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4928. if ($count < 0) {
  4929. $count = 0;
  4930. }
  4931. }
  4932. $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
  4933. $items[] = [
  4934. 'type' => 'chat',
  4935. 'count' => $count,
  4936. 'price_type' => $priceType,
  4937. 'points' => $points,
  4938. ];
  4939. }
  4940. $totalPoints = 0;
  4941. foreach ($items as $item) {
  4942. $totalPoints += $item['points'];
  4943. }
  4944. return [
  4945. 'mode' => $mode,
  4946. 'total_points' => $totalPoints,
  4947. 'items' => $items,
  4948. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4949. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4950. ];
  4951. }
  4952. /**
  4953. * 根据提示词内容智能计算最优视频时长
  4954. *
  4955. * @param string $segmentContent 分镜内容
  4956. * @param string $tailFrame 尾帧描述
  4957. * @return int 视频时长(2-12秒)
  4958. */
  4959. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4960. // 合并所有文本内容
  4961. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4962. // 如果没有内容,返回默认时长
  4963. if (empty($fullText)) {
  4964. return 5;
  4965. }
  4966. // 计算文本长度(中文字符按2个字符计算)
  4967. $textLength = mb_strlen($fullText, 'UTF-8');
  4968. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4969. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4970. // 分析内容复杂度
  4971. $complexityScore = $this->analyzeContentComplexity($fullText);
  4972. // 基础时长计算(根据文本长度)
  4973. $baseDuration = 3; // 默认2秒
  4974. // if ($adjustedLength <= 20) {
  4975. // $baseDuration = 3;
  4976. // } elseif ($adjustedLength <= 40) {
  4977. // $baseDuration = 4;
  4978. // } elseif ($adjustedLength <= 60) {
  4979. // $baseDuration = 5;
  4980. // } elseif ($adjustedLength <= 80) {
  4981. // $baseDuration = 6;
  4982. // } elseif ($adjustedLength <= 100) {
  4983. // $baseDuration = 7;
  4984. // } elseif ($adjustedLength <= 120) {
  4985. // $baseDuration = 8;
  4986. // } else {
  4987. // $baseDuration = 9;
  4988. // }
  4989. // 根据内容复杂度调整时长
  4990. $finalDuration = $baseDuration + $complexityScore;
  4991. // 确保时长在2-12秒范围内
  4992. return max(4, min(12, $finalDuration));
  4993. }
  4994. /**
  4995. * 分析内容复杂度,返回时长调整值
  4996. *
  4997. * @param string $text 文本内容
  4998. * @return int 调整值(-2到+3)
  4999. */
  5000. private function analyzeContentComplexity($text) {
  5001. $score = 0;
  5002. // 动作关键词(需要更长时间展现)
  5003. $actionKeywords = [
  5004. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  5005. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  5006. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  5007. ];
  5008. // 静态关键词(可以用较短时间)
  5009. $staticKeywords = [
  5010. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  5011. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  5012. ];
  5013. // 复杂场景关键词(需要更长时间)
  5014. $complexSceneKeywords = [
  5015. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  5016. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  5017. ];
  5018. // 情感关键词(需要适中时间表现)
  5019. $emotionKeywords = [
  5020. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  5021. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  5022. ];
  5023. // 检查动作关键词
  5024. foreach ($actionKeywords as $keyword) {
  5025. if (strpos($text, $keyword) !== false) {
  5026. $score += 1;
  5027. break; // 避免重复加分
  5028. }
  5029. }
  5030. // 检查静态关键词
  5031. foreach ($staticKeywords as $keyword) {
  5032. if (strpos($text, $keyword) !== false) {
  5033. $score -= 1;
  5034. break;
  5035. }
  5036. }
  5037. // 检查复杂场景关键词
  5038. foreach ($complexSceneKeywords as $keyword) {
  5039. if (strpos($text, $keyword) !== false) {
  5040. $score += 1;
  5041. break;
  5042. }
  5043. }
  5044. // 检查情感关键词
  5045. foreach ($emotionKeywords as $keyword) {
  5046. if (strpos($text, $keyword) !== false) {
  5047. $score += 1;
  5048. break;
  5049. }
  5050. }
  5051. // 检查时间相关词汇
  5052. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  5053. $score += 1;
  5054. }
  5055. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  5056. $score -= 1;
  5057. }
  5058. // 检查转场词汇
  5059. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  5060. $score += 1;
  5061. }
  5062. // 检查环境描述(复杂环境需要更多时间)
  5063. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  5064. $score += 1;
  5065. }
  5066. // 检查对话内容(对话需要更多时间)
  5067. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  5068. $score += 1;
  5069. }
  5070. // 限制调整范围
  5071. return max(-1, min(4, $score));
  5072. }
  5073. /**
  5074. * 创建完整视频合成任务
  5075. *
  5076. * @param array $data
  5077. * @return array
  5078. */
  5079. public function createCompleteVideoTask($data)
  5080. {
  5081. $animeId = getProp($data, 'anime_id');
  5082. $episodeId = getProp($data, 'episode_id');
  5083. // 验证参数
  5084. if (!$animeId || !$episodeId) {
  5085. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  5086. }
  5087. // 检查是否已存在处理中的任务
  5088. $existingTask = DB::table('mp_complete_video_tasks')
  5089. ->where('anime_id', $animeId)
  5090. ->where('episode_id', $episodeId)
  5091. ->whereIn('generate_status', ['执行中'])
  5092. ->first();
  5093. if ($existingTask) {
  5094. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  5095. }
  5096. // 获取全能模式状态
  5097. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  5098. if ((int)$ace_mode === 1) {
  5099. // 获取所有片段的配音视频,按 act_number 排序
  5100. $segments = DB::table('mp_episode_segments')
  5101. ->where('anime_id', $animeId)
  5102. ->where('episode_id', $episodeId)
  5103. ->orderBy('segment_number')
  5104. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5105. ->get();
  5106. // 检查是否所有片段都有视频
  5107. $missingVideos = $segments->filter(function($segment) {
  5108. return empty($segment->video_url);
  5109. });
  5110. if ($missingVideos->isNotEmpty()) {
  5111. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  5112. }
  5113. }else {
  5114. // 获取所有分镜的配音视频,按 segment_number 排序
  5115. $segments = DB::table('mp_episode_segments')
  5116. ->where('anime_id', $animeId)
  5117. ->where('episode_id', $episodeId)
  5118. ->orderBy('segment_number')
  5119. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5120. ->get();
  5121. // 检查是否所有分镜都有配音和视频
  5122. $missingVideos = $segments->filter(function($segment) {
  5123. return empty($segment->audio_url) || empty($segment->video_url);
  5124. });
  5125. if ($missingVideos->isNotEmpty()) {
  5126. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5127. }
  5128. }
  5129. if ($segments->isEmpty()) {
  5130. Utils::throwError('20003:未找到该剧集的分镜数据');
  5131. }
  5132. // 获取当前完整视频url
  5133. $completeVideoUrl = DB::table('mp_anime_episodes')
  5134. ->where('anime_id', $animeId)
  5135. ->where('id', $episodeId)
  5136. ->value('complete_video_url');
  5137. // 构建 generate_json
  5138. $generateJson = [];
  5139. $sequence = 1;
  5140. foreach ($segments as $segment) {
  5141. if ((int)$ace_mode === 1) {
  5142. $generateJson[] = [
  5143. 'sequence' => $sequence++,
  5144. 'video_url' => $segment->video_url,
  5145. 'video_time_point_start' => $segment->video_time_point_start,
  5146. 'video_time_point_end' => $segment->video_time_point_end
  5147. ];
  5148. }else {
  5149. $generateJson[] = [
  5150. 'sequence' => $sequence++,
  5151. 'video_url' => $segment->video_url,
  5152. 'audio_url' => $segment->audio_url,
  5153. 'video_time_point_start' => $segment->video_time_point_start,
  5154. 'video_time_point_end' => $segment->video_time_point_end
  5155. ];
  5156. }
  5157. }
  5158. // 创建任务
  5159. $now = date('Y-m-d H:i:s');
  5160. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5161. 'anime_id' => $animeId,
  5162. 'episode_id' => $episodeId,
  5163. 'generate_json' => json_encode($generateJson, 256),
  5164. 'generate_status' => '执行中',
  5165. 'complete_video_url' => '',
  5166. 'created_at' => $now,
  5167. 'updated_at' => $now
  5168. ]);
  5169. if (!$taskId) {
  5170. Utils::throwError('20003:创建任务失败');
  5171. }
  5172. // 更新剧集表的任务ID和状态
  5173. $boolen = DB::table('mp_anime_episodes')
  5174. ->where('anime_id', $animeId)
  5175. ->where('id', $episodeId)
  5176. ->update([
  5177. 'complete_video_task_id' => $taskId,
  5178. 'complete_video_task_status' => '执行中',
  5179. 'updated_at' => $now
  5180. ]);
  5181. if (!$boolen) {
  5182. Utils::throwError('20003:更新剧集表失败');
  5183. }
  5184. dLog('anime')->info('创建完整视频合成任务', [
  5185. 'task_id' => $taskId,
  5186. 'anime_id' => $animeId,
  5187. 'episode_id' => $episodeId,
  5188. 'segment_count' => count($generateJson)
  5189. ]);
  5190. // 请求远程服务器执行生成
  5191. $client = new Client(['timeout' => 600, 'verify' => false]);
  5192. try {
  5193. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5194. $response = $result->getBody()->getContents();
  5195. $response_arr = json_decode($response, true);
  5196. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5197. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5198. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5199. // // 更新任务状态为失败
  5200. // DB::table('mp_complete_video_tasks')
  5201. // ->where('id', $taskId)
  5202. // ->update([
  5203. // 'generate_status' => '执行失败',
  5204. // 'error_message' => $error_msg,
  5205. // 'updated_at' => date('Y-m-d H:i:s')
  5206. // ]);
  5207. // // 同步更新剧集表状态
  5208. // DB::table('mp_anime_episodes')
  5209. // ->where('complete_video_task_id', $taskId)
  5210. // ->update([
  5211. // 'complete_video_task_status' => '执行失败',
  5212. // 'updated_at' => date('Y-m-d H:i:s')
  5213. // ]);
  5214. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5215. }
  5216. } catch (\Exception $e) {
  5217. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5218. // 更新任务状态为失败
  5219. DB::table('mp_complete_video_tasks')
  5220. ->where('id', $taskId)
  5221. ->update([
  5222. 'generate_status' => '执行失败',
  5223. 'error_message' => $e->getMessage(),
  5224. 'updated_at' => date('Y-m-d H:i:s')
  5225. ]);
  5226. // 同步更新剧集表状态
  5227. DB::table('mp_anime_episodes')
  5228. ->where('complete_video_task_id', $taskId)
  5229. ->update([
  5230. 'complete_video_task_status' => '执行失败',
  5231. 'updated_at' => date('Y-m-d H:i:s')
  5232. ]);
  5233. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5234. }
  5235. // 开始轮询任务状态
  5236. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5237. $pollInterval = 5; // 每5秒轮询一次
  5238. $attempt = 0;
  5239. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5240. while ($attempt < $maxAttempts) {
  5241. sleep($pollInterval);
  5242. $attempt++;
  5243. // 查询任务状态
  5244. $task = DB::table('mp_complete_video_tasks')
  5245. ->where('id', $taskId)
  5246. ->first();
  5247. if (!$task) {
  5248. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5249. Utils::throwError('20003:任务不存在');
  5250. }
  5251. dLog('anime')->info('轮询任务状态', [
  5252. 'task_id' => $taskId,
  5253. 'attempt' => $attempt,
  5254. 'status' => $task->generate_status
  5255. ]);
  5256. // 检查任务是否完成
  5257. if ($task->generate_status === '执行成功') {
  5258. // 同步更新剧集表状态
  5259. $boolen3 = DB::table('mp_anime_episodes')
  5260. ->where('anime_id', $animeId)
  5261. ->where('id', $episodeId)
  5262. ->update([
  5263. 'complete_video_url' => $task->complete_video_url,
  5264. 'complete_video_task_status' => '执行成功',
  5265. 'updated_at' => date('Y-m-d H:i:s')
  5266. ]);
  5267. dLog('anime')->info('视频合成任务完成', [
  5268. 'task_id' => $taskId,
  5269. 'video_url' => $task->complete_video_url,
  5270. 'attempts' => $attempt
  5271. ]);
  5272. // 如果更新成功则远程删除之前的文件
  5273. if ($boolen3 && $completeVideoUrl) {
  5274. $encode_url = urlencode($completeVideoUrl);
  5275. $client = new Client(['timeout' => 300, 'verify' => false]);
  5276. // 根据ID通过API通知合成音频
  5277. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5278. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5279. $response = $result->getBody()->getContents();
  5280. $response_arr = json_decode($response, true);
  5281. Log::info('火山删除音频返回: '.$response);
  5282. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5283. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5284. Log::info('火山删除音频失败: '.$error_msg);
  5285. // Utils::throwError('20003:火山删除音频失败');
  5286. }
  5287. }
  5288. return [
  5289. 'task_id' => $taskId,
  5290. 'anime_id' => $animeId,
  5291. 'episode_id' => $episodeId,
  5292. 'segment_count' => count($generateJson),
  5293. 'generate_status' => '执行成功',
  5294. 'complete_video_url' => $task->complete_video_url,
  5295. ];
  5296. }
  5297. // 检查任务是否失败
  5298. if ($task->generate_status === '执行失败') {
  5299. // 同步更新剧集表状态
  5300. DB::table('mp_anime_episodes')
  5301. ->where('anime_id', $animeId)
  5302. ->where('id', $episodeId)
  5303. ->update([
  5304. 'complete_video_task_status' => '执行失败',
  5305. 'updated_at' => date('Y-m-d H:i:s')
  5306. ]);
  5307. $errorMessage = $task->error_message ?? '未知错误';
  5308. dLog('anime')->error('视频合成任务失败', [
  5309. 'task_id' => $taskId,
  5310. 'error' => $errorMessage,
  5311. 'attempts' => $attempt
  5312. ]);
  5313. return [
  5314. 'task_id' => $taskId,
  5315. 'anime_id' => $animeId,
  5316. 'episode_id' => $episodeId,
  5317. 'segment_count' => count($generateJson),
  5318. 'generate_status' => '执行失败',
  5319. 'error_message' => $errorMessage
  5320. ];
  5321. }
  5322. }
  5323. // 超时处理
  5324. dLog('anime')->warning('视频合成任务超时', [
  5325. 'task_id' => $taskId,
  5326. 'max_attempts' => $maxAttempts,
  5327. 'timeout_seconds' => $maxAttempts * $pollInterval
  5328. ]);
  5329. // 更新任务状态为超时
  5330. DB::table('mp_complete_video_tasks')
  5331. ->where('id', $taskId)
  5332. ->update([
  5333. 'generate_status' => '超时',
  5334. 'error_message' => '任务执行超时(5分钟)',
  5335. 'updated_at' => date('Y-m-d H:i:s')
  5336. ]);
  5337. return [
  5338. 'task_id' => $taskId,
  5339. 'anime_id' => $animeId,
  5340. 'episode_id' => $episodeId,
  5341. 'segment_count' => count($generateJson),
  5342. 'generate_status' => '超时',
  5343. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5344. ];
  5345. }
  5346. /**
  5347. * 根据 inner_prompt_type 附加内置提示词
  5348. *
  5349. * @param string $prompt 用户提示词
  5350. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5351. * @return string 合并后的提示词
  5352. */
  5353. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5354. {
  5355. $innerPromptMap = [
  5356. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。',
  5357. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5358. ];
  5359. if (!isset($innerPromptMap[$innerPromptType])) {
  5360. return $prompt;
  5361. }
  5362. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5363. }
  5364. /**
  5365. * 根据 inner_prompt_type 获取生成图片数量
  5366. *
  5367. * @param int $innerPromptType 内置提示词类型
  5368. * @param int $imageNum 传入的图片张数
  5369. * @return int 图片数量
  5370. */
  5371. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5372. {
  5373. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5374. }
  5375. /**
  5376. * 提取图片生成结果URL
  5377. *
  5378. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5379. * @param int $innerPromptType 内置提示词类型
  5380. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5381. */
  5382. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5383. {
  5384. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5385. if (is_array($resultUrls) && !empty($resultUrls)) {
  5386. $resultUrls = array_values($resultUrls);
  5387. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5388. }
  5389. if (!empty($resultUrl)) {
  5390. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5391. }
  5392. return (int)$innerPromptType === 2 ? [] : '';
  5393. }
  5394. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5395. $prompt = getProp($data, 'prompt');
  5396. $episode_id = getProp($data, 'episode_id');
  5397. $ref_img_urls = getProp($data, 'ref_img_urls');
  5398. $ratio = getProp($data, 'ratio', '9:16');
  5399. $resolution = getProp($data, 'resolution', '2k');
  5400. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5401. $imageNum = (int)getProp($data, 'image_num', 1);
  5402. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  5403. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  5404. // 参数验证
  5405. $resolution = strtolower($resolution);
  5406. if (!isset($sizeMap[$resolution])) {
  5407. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5408. }
  5409. if (!isset($sizeMap[$resolution][$ratio])) {
  5410. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5411. }
  5412. // 根据 ratio 和 resolution 确定宽高
  5413. $width = $sizeMap[$resolution][$ratio]['width'];
  5414. $height = $sizeMap[$resolution][$ratio]['height'];
  5415. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5416. if (is_json($ref_img_urls)) {
  5417. $ref_img_urls = json_decode($ref_img_urls, true);
  5418. }else {
  5419. $ref_img_urls = explode(',', $ref_img_urls);
  5420. }
  5421. }
  5422. // 处理图片模型
  5423. $model = getProp($data, 'model');
  5424. if (!$model) {
  5425. // 用户没有输入,从episode表获取
  5426. if ($episode_id) {
  5427. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5428. $model = getProp($episode, 'image_model');
  5429. }
  5430. if (!$model) {
  5431. // episode表也没有,使用默认值
  5432. $model = 'gpt-image-2';
  5433. }
  5434. }
  5435. // 验证模型是否在可用模型表中
  5436. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5437. // $model = 'gpt-image-2';
  5438. Utils::throwError('20003:该模型已不可用,请更换!');
  5439. }
  5440. // 保存到episode表
  5441. if ($episode_id) {
  5442. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5443. 'image_model' => $model,
  5444. 'updated_at' => date('Y-m-d H:i:s')
  5445. ]);
  5446. }
  5447. // 参数验证
  5448. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5449. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5450. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5451. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5452. try {
  5453. // 创建图片生成任务
  5454. $params = [
  5455. 'prompt' => $prompt,
  5456. 'model' => $model,
  5457. 'ref_img_urls' => '',
  5458. 'width' => $width,
  5459. 'height' => $height,
  5460. 'image_num' => $imageNum,
  5461. // 计费锚点(动漫/剧集/剧本),上下文没有时不记录
  5462. 'anime_id' => getProp($data, 'anime_id'),
  5463. 'episode_id' => $episode_id,
  5464. ];
  5465. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5466. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5467. $task_id = $task->id;
  5468. if (!$task_id) {
  5469. Utils::throwError('20003:创建图片生成任务失败');
  5470. }
  5471. // 创建任务中心记录并关联图片任务ID
  5472. $taskCenter = $this->taskCenterService->createTask('image', [
  5473. 'title' => '文生图',
  5474. 'ref_task_id' => $task_id,
  5475. // 'prompt' => $prompt,
  5476. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5477. ]);
  5478. $taskCenterId = $taskCenter->id;
  5479. // 组装本次任务信息(用于init消息,类似generateVideo)
  5480. $taskInfo = [
  5481. 'task_id' => $task_id,
  5482. 'status' => getProp($task, 'status', 'processing'),
  5483. 'model' => $model,
  5484. 'ratio' => $ratio,
  5485. 'resolution' => $resolution,
  5486. 'image_num' => $imageNum,
  5487. ];
  5488. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5489. if (is_callable($onTaskCreated)) {
  5490. $onTaskCreated($taskCenterId, $taskInfo);
  5491. }
  5492. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5493. $model = getProp($task, 'model');
  5494. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5495. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5496. $isSyncModel = $isVolcModel || $isGptModel;
  5497. // 任务需要轮询获取结果(15分钟超时,每3秒查询一次)
  5498. $start_time = time();
  5499. $timeout = 900; // 15分钟
  5500. $img_url = '';
  5501. $img_urls = [];
  5502. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5503. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5504. while (time() - $start_time < $timeout) {
  5505. sleep(3);
  5506. // 每分钟发送一次队列状态消息(仅流式模式)
  5507. if (is_callable($onPoll)) {
  5508. $currentTime = time();
  5509. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5510. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5511. $lastQueueMessageTime = $currentTime;
  5512. }
  5513. }
  5514. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5515. if ($isSyncModel) {
  5516. // 刷新任务状态
  5517. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5518. if ($task->status === 'success' && $task->result_url) {
  5519. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5520. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5521. if (!empty($resultUrls)) {
  5522. $img_urls = $resultUrls;
  5523. $img_url = $resultUrls[0];
  5524. } else {
  5525. $img_url = (string)$task->result_url;
  5526. }
  5527. break;
  5528. } elseif ($task->status === 'failed') {
  5529. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5530. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5531. }
  5532. // // 如果还在处理中,提示用户稍后查看
  5533. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5534. }else {
  5535. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5536. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5537. if ($statusInfo['status'] === 'success') {
  5538. $task->updateStatus('success', [
  5539. 'result_url' => $statusInfo['result_url'],
  5540. 'result_json' => $statusInfo['result_json'] ?? []
  5541. ]);
  5542. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5543. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5544. if (!empty($resultUrls)) {
  5545. $img_urls = $resultUrls;
  5546. $img_url = $resultUrls[0];
  5547. } else {
  5548. $img_url = (string)$statusInfo['result_url'];
  5549. }
  5550. break;
  5551. } elseif ($statusInfo['status'] === 'failed') {
  5552. $task->updateStatus('failed', [
  5553. 'error_message' => $statusInfo['error_message'],
  5554. 'result_json' => $statusInfo['result_json'] ?? []
  5555. ]);
  5556. dLog('anime')->error('图片生成失败,', [
  5557. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5558. ]);
  5559. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5560. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5561. }
  5562. }
  5563. }
  5564. if (empty($img_url)) {
  5565. Utils::throwError('20003:图片生成超时,请稍后重试');
  5566. }
  5567. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5568. if (count($img_urls) > 1) {
  5569. return [
  5570. 'img_url' => $img_url,
  5571. 'image_urls' => $img_urls,
  5572. 'task_id' => $taskCenterId,
  5573. ];
  5574. }
  5575. return [
  5576. 'img_url' => $img_url,
  5577. 'task_id' => $taskCenterId,
  5578. ];
  5579. } catch (\Exception $e) {
  5580. dLog('anime')->error('更新角色或场景失败', [
  5581. 'error' => $e->getMessage()
  5582. ]);
  5583. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5584. Utils::throwError('20003:' . $e->getMessage());
  5585. }
  5586. }
  5587. /**
  5588. * 使用文生文模型解析分镜内容
  5589. */
  5590. private function parseSegmentContentWithAI($segment_content) {
  5591. try {
  5592. // 使用DeepSeek服务的公开方法解析分镜内容
  5593. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5594. } catch (\Exception $e) {
  5595. // 如果AI解析失败,记录日志并返回原内容
  5596. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5597. return $segment_content;
  5598. }
  5599. }
  5600. /**
  5601. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5602. *
  5603. * @param int $episode_id 分集ID
  5604. * @param int $anime_id 动漫ID
  5605. * @param array $roles 分集角色数组(引用传递)
  5606. * @param array $scenes 分集场景数组(引用传递)
  5607. * @param array $episode 分集数据
  5608. */
  5609. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5610. // 获取全局动漫的角色和场景数据
  5611. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5612. if (!$anime) return;
  5613. $art_style_type = getProp($anime, 'art_style_type');
  5614. $character_prefix = '';
  5615. $scene_prefix = '';
  5616. if ($art_style_type) {
  5617. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5618. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5619. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5620. }
  5621. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5622. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5623. $roles_updated = false;
  5624. $scenes_updated = false;
  5625. // 处理角色
  5626. foreach ($roles as &$role) {
  5627. $role_name = getProp($role, 'role');
  5628. $role_description = getProp($role, 'description');
  5629. $role_pic_prompt = getProp($role, 'pic_prompt');
  5630. $role_url = getProp($role, 'url');
  5631. $role_task_id = getProp($role, 'task_id');
  5632. // 如果已有URL或已有任务ID,跳过
  5633. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5634. continue;
  5635. }
  5636. $url_inherited = false;
  5637. // 尝试从全局数据中继承
  5638. foreach ($global_roles as $global_role) {
  5639. $global_role_name = getProp($global_role, 'role');
  5640. $global_role_description = getProp($global_role, 'description');
  5641. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5642. $global_role_url = getProp($global_role, 'url');
  5643. $global_role_task_id = getProp($global_role, 'task_id');
  5644. $global_role_task_status = getProp($global_role, 'task_status');
  5645. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5646. if ($role_name === $global_role_name
  5647. && $role_description === $global_role_description
  5648. && $role_pic_prompt === $global_role_pic_prompt
  5649. && !empty($global_role_url)) {
  5650. // 继承 task_id、task_status 和 url
  5651. $role['task_id'] = $global_role_task_id;
  5652. $role['task_status'] = $global_role_task_status;
  5653. $role['url'] = $global_role_url;
  5654. $roles_updated = true;
  5655. $url_inherited = true;
  5656. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5657. break;
  5658. }
  5659. }
  5660. // 如果无法继承且没有任务ID,创建新任务
  5661. if (!$url_inherited && empty($role_task_id)) {
  5662. try {
  5663. $art_style = getProp($episode, 'art_style');
  5664. // 优先使用 pic_prompt,如果没有则使用 description
  5665. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5666. // if ($art_style) {
  5667. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5668. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5669. // }
  5670. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5671. $params = [
  5672. 'prompt' => $description,
  5673. 'ref_img_urls' => [],
  5674. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  5675. 'anime_id' => $anime_id,
  5676. 'episode_id' => $episode_id,
  5677. 'episode_number' => getProp($episode, 'episode_number'),
  5678. ];
  5679. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5680. $task_id = $task->id;
  5681. if ($task_id) {
  5682. $role['task_id'] = $task_id;
  5683. $role['task_status'] = 'processing';
  5684. $roles_updated = true;
  5685. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5686. }
  5687. } catch (\Exception $e) {
  5688. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5689. }
  5690. }
  5691. }
  5692. // 处理场景
  5693. foreach ($scenes as &$scene) {
  5694. $scene_name = getProp($scene, 'scene');
  5695. $scene_description = getProp($scene, 'description');
  5696. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5697. $scene_url = getProp($scene, 'url');
  5698. $scene_task_id = getProp($scene, 'task_id');
  5699. // 如果已有URL或已有任务ID,跳过
  5700. if (!empty($scene_url) || !empty($scene_task_id)) {
  5701. continue;
  5702. }
  5703. $url_inherited = false;
  5704. // 尝试从全局数据中继承
  5705. foreach ($global_scenes as $global_scene) {
  5706. $global_scene_name = getProp($global_scene, 'scene');
  5707. $global_scene_description = getProp($global_scene, 'description');
  5708. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5709. $global_scene_url = getProp($global_scene, 'url');
  5710. $global_scene_task_id = getProp($global_scene, 'task_id');
  5711. $global_scene_task_status = getProp($global_scene, 'task_status');
  5712. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5713. if ($scene_name === $global_scene_name
  5714. && $scene_description === $global_scene_description
  5715. && $scene_pic_prompt === $global_scene_pic_prompt
  5716. && !empty($global_scene_url)) {
  5717. // 继承 task_id、task_status 和 url
  5718. $scene['task_id'] = $global_scene_task_id;
  5719. $scene['task_status'] = $global_scene_task_status;
  5720. $scene['url'] = $global_scene_url;
  5721. $scenes_updated = true;
  5722. $url_inherited = true;
  5723. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5724. break;
  5725. }
  5726. }
  5727. // 如果无法继承且没有任务ID,创建新任务
  5728. if (!$url_inherited && empty($scene_task_id)) {
  5729. try {
  5730. $art_style = getProp($episode, 'art_style');
  5731. // 优先使用 pic_prompt,如果没有则使用 description
  5732. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5733. // if ($art_style) {
  5734. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5735. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5736. // }
  5737. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5738. $params = [
  5739. 'prompt' => $description,
  5740. 'ref_img_urls' => [],
  5741. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  5742. 'anime_id' => $anime_id,
  5743. 'episode_id' => $episode_id,
  5744. 'episode_number' => getProp($episode, 'episode_number'),
  5745. ];
  5746. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5747. $task_id = $task->id;
  5748. if ($task_id) {
  5749. $scene['task_id'] = $task_id;
  5750. $scene['task_status'] = 'processing';
  5751. $scenes_updated = true;
  5752. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5753. }
  5754. } catch (\Exception $e) {
  5755. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5756. }
  5757. }
  5758. }
  5759. // 如果有更新,保存到数据库
  5760. if ($roles_updated || $scenes_updated) {
  5761. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5762. if ($roles_updated) {
  5763. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5764. }
  5765. if ($scenes_updated) {
  5766. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5767. }
  5768. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5769. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5770. }
  5771. }
  5772. /**
  5773. * 根据图片URL使用AI反推图片提示词
  5774. *
  5775. * @param string $img_url 图片URL
  5776. * @return string 反推的提示词
  5777. */
  5778. private function generateImagePromptFromUrl($img_url) {
  5779. try {
  5780. // 获取默认模型
  5781. $model = 'doubao-seed-2-0-mini-260215';
  5782. // 构建messages参数
  5783. $messages = [
  5784. [
  5785. 'role' => 'user',
  5786. 'content' => [
  5787. [
  5788. 'type' => 'text',
  5789. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5790. ],
  5791. [
  5792. 'type' => 'image_url',
  5793. 'image_url' => [
  5794. 'url' => $img_url
  5795. ]
  5796. ]
  5797. ]
  5798. ]
  5799. ];
  5800. // 构建请求参数
  5801. $params = [
  5802. 'model' => $model,
  5803. 'messages' => $messages,
  5804. 'stream' => false,
  5805. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5806. ];
  5807. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5808. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5809. // 仅记录 token 使用明细(不扣积分)
  5810. $uid = 0;
  5811. try {
  5812. $uid = (int)Site::getUid();
  5813. } catch (\Throwable $e) {
  5814. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5815. }
  5816. $this->pointsService->recordTokenOnlyDetail(
  5817. $uid,
  5818. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5819. [
  5820. 'model' => $model,
  5821. 'img_url' => $img_url,
  5822. 'source' => 'generateImagePromptFromUrl',
  5823. ],
  5824. 'chat',
  5825. $model,
  5826. ''
  5827. );
  5828. // 返回生成的内容
  5829. return getProp($result, 'fullContent', '图片描述生成失败');
  5830. } catch (\Exception $e) {
  5831. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5832. 'img_url' => $img_url
  5833. ]);
  5834. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5835. 'error' => $e->getMessage(),
  5836. 'img_url' => $img_url
  5837. ]);
  5838. return '图片描述生成失败: ' . $e->getMessage();
  5839. }
  5840. }
  5841. /**
  5842. * 音频试听接口
  5843. * 创建音频任务并轮询获取结果
  5844. *
  5845. * @param array $data 参数数组
  5846. * @return array 返回音频URL或错误信息
  5847. */
  5848. public function previewAudio($data) {
  5849. $dialogue = getProp($data, 'dialogue');
  5850. // 必填参数验证
  5851. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5852. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5853. $voice_type = getProp($data, 'voice_type');
  5854. $voice_name = getProp($data, 'voice_name');
  5855. $voice_actor = getProp($data, 'voice_actor');
  5856. $emotion_type = getProp($data, 'emotion_type');
  5857. $gender = getProp($data, 'gender', 0);
  5858. $emotion = getProp($data, 'emotion');
  5859. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5860. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5861. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5862. $pitch = getProp($data, 'pitch', 0);
  5863. try {
  5864. $now = date('Y-m-d H:i:s');
  5865. // 构建生成参数
  5866. $generate_json = json_encode([
  5867. 'text' => $dialogue,
  5868. 'role' => $voice_actor,
  5869. 'voice_type' => $voice_type,
  5870. 'voice_name' => $voice_name,
  5871. 'emotion' => $emotion,
  5872. 'emotion_type' => $emotion_type,
  5873. 'gender' => $gender,
  5874. 'speed_ratio' => $speed_ratio,
  5875. 'loudness_ratio' => $loudness_ratio,
  5876. 'emotion_scale' => $emotion_scale,
  5877. 'pitch' => $pitch,
  5878. ], 256);
  5879. // 请求远程服务器执行生成
  5880. $client = new Client(['timeout' => 600, 'verify' => false]);
  5881. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5882. $response = $result->getBody()->getContents();
  5883. $response_arr = json_decode($response, true);
  5884. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5885. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5886. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5887. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5888. }
  5889. $arr = $response_arr['data'];
  5890. $subtitle_info = $arr['subtitle_info'];
  5891. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5892. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5893. return [
  5894. 'audio_url' => $arr['url'],
  5895. 'subtitle_info' => $subtitle_info,
  5896. 'audio_duration' => round($audio_duration, 2)
  5897. ];
  5898. } catch (\Exception $e) {
  5899. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5900. Utils::throwError('20003:' . $e->getMessage());
  5901. }
  5902. }
  5903. /**
  5904. * 获取角色库列表(支持文件夹递归查询)
  5905. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5906. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5907. */
  5908. public function globalProducts($data) {
  5909. $uid = Site::getUid();
  5910. $cpid = Site::getCpid();
  5911. $role = Site::getRole();
  5912. $id = getProp($data, 'id', 0);
  5913. $parent_id = getProp($data, 'parent_id', 0);
  5914. $product_name = getProp($data, 'product_name');
  5915. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5916. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5917. if (!$product) {
  5918. Utils::throwError('20003:请选择产品类型');
  5919. }
  5920. // 根据角色和is_public参数确定查询范围
  5921. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5922. // user角色:根据is_public参数筛选
  5923. $query_user_ids = [];
  5924. if ($role === 'admin') {
  5925. // admin获取所有个人库和公共库
  5926. $query_user_ids = [$uid, 0];
  5927. } else {
  5928. // user角色根据is_public参数筛选
  5929. if ($is_public == 2) {
  5930. // 个人库+公共库
  5931. $query_user_ids = [$uid, 0];
  5932. } elseif ($is_public == 0) {
  5933. // 仅个人库
  5934. $query_user_ids = [$uid];
  5935. } elseif ($is_public == 1) {
  5936. // 仅公共库
  5937. $query_user_ids = [0];
  5938. }
  5939. }
  5940. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5941. if ($id || $product_name) {
  5942. $query = DB::table('mp_products')
  5943. ->where('cpid', $cpid)
  5944. ->whereIn('user_id', $query_user_ids)
  5945. ->where('is_deleted', 0);
  5946. // 如果指定了 id,按 id 精确查询
  5947. if ($id) {
  5948. $query->where('id', $id);
  5949. }
  5950. // 如果指定了 product_name,按名称模糊查询
  5951. if ($product_name) {
  5952. $query->where('product_name', 'like', "%{$product_name}%");
  5953. }
  5954. // 如果指定了 product,添加筛选条件
  5955. if ($product) {
  5956. $query->where('product', $product);
  5957. }
  5958. $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')
  5959. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5960. ->get()
  5961. ->map(function($value) {
  5962. $value = (array)$value;
  5963. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5964. $value['type'] = (int)$value['type'];
  5965. $value['parent_id'] = (int)$value['parent_id'];
  5966. $value['level'] = (int)$value['level'];
  5967. $value['product'] = (int)($value['product'] ?? 1);
  5968. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5969. $value['timbre_url'] = $value['timbre_url'] ?? '';
  5970. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5971. unset($value['user_id']);
  5972. return $value;
  5973. })
  5974. ->toArray();
  5975. return $result;
  5976. }
  5977. // 递归获取所有子目录和角色
  5978. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5979. }
  5980. /**
  5981. * 递归获取指定目录下的所有子目录和角色
  5982. * @param int $cpid 公司ID
  5983. * @param int $parent_id 父目录ID
  5984. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5985. * @param array $query_user_ids 用户ID数组(支持多个)
  5986. * @param int $current_uid 当前用户ID(用于排序)
  5987. * @return array
  5988. */
  5989. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5990. // 查询当前层级的所有项(文件夹和角色)
  5991. $query = DB::table('mp_products')
  5992. ->where('cpid', $cpid)
  5993. ->where('is_deleted', 0)
  5994. ->where('parent_id', $parent_id);
  5995. // 添加用户ID验证(支持多个user_id)
  5996. if (!empty($query_user_ids)) {
  5997. $query->whereIn('user_id', $query_user_ids);
  5998. }
  5999. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  6000. if ($product) {
  6001. $query->where('product', $product);
  6002. }
  6003. // 排序规则:
  6004. // 1. 文件夹在前(type DESC)
  6005. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  6006. // 3. 其他排序规则
  6007. $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')
  6008. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  6009. ->get();
  6010. $result = [];
  6011. foreach ($items as $item) {
  6012. $itemArray = [
  6013. 'id' => $item->id,
  6014. 'type' => (int)$item->type,
  6015. 'parent_id' => (int)$item->parent_id,
  6016. 'level' => (int)$item->level,
  6017. 'product_name' => $item->product_name,
  6018. 'url' => $item->url,
  6019. 'pic_prompt' => $item->pic_prompt ?? '',
  6020. 'three_view_image_url' => $item->three_view_image_url,
  6021. 'timbre_url' => $item->timbre_url ?? '',
  6022. 'product' => (int)($item->product ?? 1),
  6023. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  6024. 'created_at' => transDate($item->created_at, 'Y-m-d')
  6025. ];
  6026. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  6027. // 如果是文件夹,递归获取其子项
  6028. if ($item->type == 2) {
  6029. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  6030. if (!empty($children)) {
  6031. $itemArray['children'] = $children;
  6032. }
  6033. }
  6034. $result[] = $itemArray;
  6035. }
  6036. return $result;
  6037. }
  6038. /**
  6039. * 创建文件夹
  6040. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  6041. * @return int 返回新建文件夹ID
  6042. */
  6043. public function createFolder($data) {
  6044. $uid = Site::getUid();
  6045. $cpid = Site::getCpid();
  6046. $role = Site::getRole();
  6047. $parent_id = getProp($data, 'parent_id', 0);
  6048. $folder_name = getProp($data, 'product_name', '新建文件夹');
  6049. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6050. // 如果是公共库操作,需要admin权限
  6051. if ($is_public && $role !== 'admin') {
  6052. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6053. }
  6054. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6055. $store_uid = $is_public ? 0 : $uid;
  6056. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6057. $product = getProp($data, 'product');
  6058. if (!in_array($product, [1, 2, 3])) {
  6059. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  6060. }
  6061. // 验证父文件夹
  6062. $parent_level = 0;
  6063. if ($parent_id > 0) {
  6064. $parent = DB::table('mp_products')
  6065. ->where('id', $parent_id)
  6066. ->where('cpid', $cpid)
  6067. ->where('user_id', $store_uid)
  6068. ->where('type', 2)
  6069. ->where('is_deleted', 0)
  6070. ->first();
  6071. if (!$parent) {
  6072. Utils::throwError('20003:父文件夹不存在');
  6073. }
  6074. // 检查父文件夹的 product 类型是否一致
  6075. if ($parent->product != $product) {
  6076. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  6077. }
  6078. $parent_level = $parent->level;
  6079. // 检查层级限制(最多3层)
  6080. if ($parent_level >= 3) {
  6081. Utils::throwError('20003:文件夹层级不能超过3层');
  6082. }
  6083. }
  6084. // 检查当前目录下是否已存在空白文件夹
  6085. $empty_folder_exists = DB::table('mp_products')
  6086. ->where('parent_id', $parent_id)
  6087. ->where('cpid', $cpid)
  6088. ->where('user_id', $store_uid)
  6089. ->where('type', 2)
  6090. ->where('product', $product)
  6091. ->where('product_name', '新建文件夹')
  6092. ->where('is_deleted', 0)
  6093. ->exists();
  6094. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  6095. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  6096. }
  6097. // 创建文件夹
  6098. $folder_id = DB::table('mp_products')->insertGetId([
  6099. 'user_id' => $store_uid,
  6100. 'cpid' => $cpid,
  6101. 'type' => 2,
  6102. 'parent_id' => $parent_id,
  6103. 'level' => $parent_level + 1,
  6104. 'product_name' => $folder_name,
  6105. 'product' => $product,
  6106. 'sort_order' => time(), // 使用时间戳作为排序权重
  6107. 'is_deleted' => 0,
  6108. 'created_at' => date('Y-m-d H:i:s'),
  6109. 'updated_at' => date('Y-m-d H:i:s')
  6110. ]);
  6111. return [
  6112. 'id' => $folder_id,
  6113. 'type' => 2,
  6114. 'parent_id' => $parent_id,
  6115. 'level' => $parent_level + 1,
  6116. 'product_name' => $folder_name,
  6117. 'product' => $product,
  6118. ];
  6119. }
  6120. /**
  6121. * 重命名文件夹或角色
  6122. * @param array $data 包含 id、product_name(新名称)
  6123. * @return bool
  6124. */
  6125. public function renameFolder($data) {
  6126. $uid = Site::getUid();
  6127. $cpid = Site::getCpid();
  6128. $role = Site::getRole();
  6129. $id = getProp($data, 'id');
  6130. $new_name = getProp($data, 'product_name');
  6131. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6132. if (!$id || !$new_name) {
  6133. Utils::throwError('20003:参数不完整');
  6134. }
  6135. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6136. $query_uid = $is_public ? 0 : $uid;
  6137. // 如果是公共库操作,需要admin权限
  6138. if ($is_public && $role !== 'admin') {
  6139. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6140. }
  6141. // 检查是否存在
  6142. $item = DB::table('mp_products')
  6143. ->where('id', $id)
  6144. ->where('cpid', $cpid)
  6145. ->where('user_id', $query_uid)
  6146. ->where('is_deleted', 0)
  6147. ->first();
  6148. if (!$item) {
  6149. Utils::throwError('20003:项目不存在');
  6150. }
  6151. return DB::table('mp_products')
  6152. ->where('id', $id)
  6153. ->where('cpid', $cpid)
  6154. ->where('user_id', $query_uid)
  6155. ->update([
  6156. 'product_name' => $new_name,
  6157. 'updated_at' => date('Y-m-d H:i:s')
  6158. ]);
  6159. }
  6160. /**
  6161. * 移动角色或文件夹到指定文件夹
  6162. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6163. * @return bool
  6164. */
  6165. public function moveProductOrFolder($data) {
  6166. $uid = Site::getUid();
  6167. $cpid = Site::getCpid();
  6168. $role = Site::getRole();
  6169. $id = getProp($data, 'id');
  6170. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6171. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6172. if (!$id) {
  6173. Utils::throwError('20003:请选择要移动的项目');
  6174. }
  6175. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6176. $query_uid = $is_public ? 0 : $uid;
  6177. // 如果是公共库操作,需要admin权限
  6178. if ($is_public && $role !== 'admin') {
  6179. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6180. }
  6181. // 检查要移动的项目
  6182. $item = DB::table('mp_products')
  6183. ->where('id', $id)
  6184. ->where('cpid', $cpid)
  6185. ->where('user_id', $query_uid)
  6186. ->where('is_deleted', 0)
  6187. ->first();
  6188. if (!$item) {
  6189. Utils::throwError('20003:项目不存在');
  6190. }
  6191. // 验证目标文件夹
  6192. $target_level = 0;
  6193. $target_product = $item->product; // 默认使用当前项目的 product
  6194. if ($target_parent_id > 0) {
  6195. $target_parent = DB::table('mp_products')
  6196. ->where('id', $target_parent_id)
  6197. ->where('cpid', $cpid)
  6198. ->where('user_id', $query_uid)
  6199. ->where('type', 2)
  6200. ->where('is_deleted', 0)
  6201. ->first();
  6202. if (!$target_parent) {
  6203. Utils::throwError('20003:目标文件夹不存在');
  6204. }
  6205. // 检查 product 类型是否一致
  6206. if ($target_parent->product != $item->product) {
  6207. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6208. }
  6209. $target_level = $target_parent->level;
  6210. $target_product = $target_parent->product;
  6211. // 如果移动的是文件夹,需要检查层级
  6212. if ($item->type == 2) {
  6213. // 计算移动后的最大层级
  6214. $max_child_level = $this->getMaxChildLevel($id);
  6215. $depth = $max_child_level - $item->level;
  6216. if ($target_level + 1 + $depth > 3) {
  6217. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6218. }
  6219. // 不能移动到自己或自己的子文件夹下
  6220. if ($this->isDescendant($target_parent_id, $id)) {
  6221. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6222. }
  6223. }
  6224. }
  6225. // 更新父文件夹和层级
  6226. $new_level = $target_level + 1;
  6227. DB::table('mp_products')
  6228. ->where('id', $id)
  6229. ->update([
  6230. 'parent_id' => $target_parent_id,
  6231. 'level' => $new_level,
  6232. 'updated_at' => date('Y-m-d H:i:s')
  6233. ]);
  6234. // 如果是文件夹,需要递归更新所有子项的层级
  6235. if ($item->type == 2) {
  6236. $this->updateChildrenLevel($id, $new_level);
  6237. }
  6238. return true;
  6239. }
  6240. /**
  6241. * 获取文件夹下最大子层级
  6242. * @param int $folder_id
  6243. * @return int
  6244. */
  6245. private function getMaxChildLevel($folder_id) {
  6246. $max_level = DB::table('mp_products')
  6247. ->where('parent_id', $folder_id)
  6248. ->where('is_deleted', 0)
  6249. ->max('level');
  6250. if (!$max_level) {
  6251. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6252. }
  6253. // 递归查找子文件夹
  6254. $children = DB::table('mp_products')
  6255. ->where('parent_id', $folder_id)
  6256. ->where('type', 2)
  6257. ->where('is_deleted', 0)
  6258. ->pluck('id');
  6259. foreach ($children as $child_id) {
  6260. $child_max = $this->getMaxChildLevel($child_id);
  6261. if ($child_max > $max_level) {
  6262. $max_level = $child_max;
  6263. }
  6264. }
  6265. return $max_level;
  6266. }
  6267. /**
  6268. * 检查 target_id 是否是 folder_id 的后代
  6269. * @param int $target_id
  6270. * @param int $folder_id
  6271. * @return bool
  6272. */
  6273. private function isDescendant($target_id, $folder_id) {
  6274. if ($target_id == $folder_id) {
  6275. return true;
  6276. }
  6277. $parent = DB::table('mp_products')
  6278. ->where('id', $target_id)
  6279. ->where('is_deleted', 0)
  6280. ->first();
  6281. if (!$parent || $parent->parent_id == 0) {
  6282. return false;
  6283. }
  6284. return $this->isDescendant($parent->parent_id, $folder_id);
  6285. }
  6286. /**
  6287. * 递归更新子项层级
  6288. * @param int $parent_id
  6289. * @param int $parent_level
  6290. */
  6291. private function updateChildrenLevel($parent_id, $parent_level) {
  6292. $children = DB::table('mp_products')
  6293. ->where('parent_id', $parent_id)
  6294. ->where('is_deleted', 0)
  6295. ->get();
  6296. foreach ($children as $child) {
  6297. $new_level = $parent_level + 1;
  6298. DB::table('mp_products')
  6299. ->where('id', $child->id)
  6300. ->update([
  6301. 'level' => $new_level,
  6302. 'updated_at' => date('Y-m-d H:i:s')
  6303. ]);
  6304. // 如果是文件夹,继续递归
  6305. if ($child->type == 2) {
  6306. $this->updateChildrenLevel($child->id, $new_level);
  6307. }
  6308. }
  6309. }
  6310. /**
  6311. * 获取文件夹路径(面包屑导航)
  6312. * @param array $data 包含 folder_id
  6313. * @return array 返回路径数组
  6314. */
  6315. public function getFolderPath($data) {
  6316. $uid = Site::getUid();
  6317. $cpid = Site::getCpid();
  6318. $folder_id = getProp($data, 'id', 0);
  6319. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6320. if ($folder_id == 0) {
  6321. return [
  6322. ['id' => 0, 'name' => '根目录']
  6323. ];
  6324. }
  6325. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6326. $query_uid = $is_public ? 0 : $uid;
  6327. $path = [];
  6328. $current_id = $folder_id;
  6329. while ($current_id > 0) {
  6330. $folder = DB::table('mp_products')
  6331. ->where('id', $current_id)
  6332. ->where('cpid', $cpid)
  6333. ->where('user_id', $query_uid)
  6334. ->where('type', 2)
  6335. ->where('is_deleted', 0)
  6336. ->first();
  6337. if (!$folder) {
  6338. break;
  6339. }
  6340. array_unshift($path, [
  6341. 'id' => $folder->id,
  6342. 'name' => $folder->product_name
  6343. ]);
  6344. $current_id = $folder->parent_id;
  6345. }
  6346. // 添加根目录
  6347. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6348. return $path;
  6349. }
  6350. public function createProduct($data) {
  6351. $uid = Site::getUid();
  6352. $cpid = Site::getCpid();
  6353. $role = Site::getRole();
  6354. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6355. // 如果是公共库操作,需要admin权限
  6356. if ($is_public && $role !== 'admin') {
  6357. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6358. }
  6359. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6360. $store_uid = $is_public ? 0 : $uid;
  6361. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6362. $script_id = (int)getProp($data, 'script_id', 0);
  6363. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6364. if ($script_id && empty($episode_numbers)) {
  6365. Utils::throwError('20003:剧集序号不能为空');
  6366. }
  6367. if (!$script_id && !empty($episode_numbers)) {
  6368. Utils::throwError('20003:请提供剧本ID');
  6369. }
  6370. $product_name = trim(getProp($data, 'product_name'));
  6371. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6372. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6373. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6374. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6375. $url = trim(getProp($data, 'url'));
  6376. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6377. $versions = getProp($data, 'versions');
  6378. // 检查是否是正确的图片格式
  6379. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6380. $urlPath = parse_url($url, PHP_URL_PATH);
  6381. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6382. if (!in_array($extension, $allowedExtensions)) {
  6383. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6384. }
  6385. // 选填三视图图片地址,格式校验与 url 一致
  6386. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6387. if ($three_view_image_url) {
  6388. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6389. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6390. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6391. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6392. }
  6393. }
  6394. // 选填音色音频地址(兼容 timbre_url/audio_url/timbre 传参)
  6395. $timbre_url = $this->getProductTimbreUrl($data);
  6396. if ($timbre_url) {
  6397. $this->validateProductAudioUrl($timbre_url);
  6398. }
  6399. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6400. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6401. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6402. $product = getProp($data, 'product');
  6403. if (!in_array($product, [1, 2, 3])) {
  6404. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6405. }
  6406. // 获取父文件夹ID和层级
  6407. $parent_id = getProp($data, 'parent_id', 0);
  6408. $parent_level = 0;
  6409. if ($parent_id > 0) {
  6410. $parent = DB::table('mp_products')
  6411. ->where('id', $parent_id)
  6412. ->where('cpid', $cpid)
  6413. ->where('user_id', $store_uid)
  6414. ->where('type', 2)
  6415. ->where('is_deleted', 0)
  6416. ->first();
  6417. if (!$parent) {
  6418. Utils::throwError('20003:父文件夹不存在');
  6419. }
  6420. $parent_level = $parent->level;
  6421. }
  6422. // 创建资产并保存剧本资产关联关系(同一事务)
  6423. DB::beginTransaction();
  6424. try {
  6425. $id = DB::table('mp_products')->insertGetId([
  6426. 'user_id' => $store_uid,
  6427. 'cpid' => $cpid,
  6428. 'type' => 1, // 1=角色图片
  6429. 'parent_id' => $parent_id,
  6430. 'level' => $parent_level + 1,
  6431. 'product_name' => $product_name,
  6432. 'url' => $url,
  6433. 'three_view_image_url' => $three_view_image_url,
  6434. 'timbre_url' => $timbre_url,
  6435. 'pic_prompt' => $pic_prompt,
  6436. 'product' => $product,
  6437. 'versions' => json_encode($versions, 256),
  6438. 'sort_order' => time(), // 使用时间戳作为排序权重
  6439. 'created_at' => date('Y-m-d H:i:s'),
  6440. 'updated_at' => date('Y-m-d H:i:s')
  6441. ]);
  6442. if (!$id) Utils::throwError('20003:创建失败');
  6443. // 保存剧本资产关联关系
  6444. if ($script_id) {
  6445. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6446. }
  6447. DB::commit();
  6448. } catch (\Exception $e) {
  6449. DB::rollback();
  6450. throw $e;
  6451. }
  6452. return [
  6453. 'id' => $id,
  6454. 'type' => 1,
  6455. 'parent_id' => $parent_id,
  6456. 'level' => $parent_level + 1,
  6457. 'product_name' => $product_name,
  6458. 'url' => $url,
  6459. 'three_view_image_url' => $three_view_image_url,
  6460. 'timbre_url' => $timbre_url,
  6461. 'pic_prompt' => $pic_prompt,
  6462. 'product' => $product,
  6463. 'versions' => $versions
  6464. ];
  6465. }
  6466. public function editProduct($data) {
  6467. $uid = Site::getUid();
  6468. $cpid = Site::getCpid();
  6469. $role = Site::getRole();
  6470. $id = getProp($data, 'id');
  6471. if (!$id) Utils::throwError('20003:ID不能为空');
  6472. $versions = getProp($data, 'versions');
  6473. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6474. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6475. $script_id = (int)getProp($data, 'script_id', 0);
  6476. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6477. if ($script_id && empty($episode_numbers)) {
  6478. Utils::throwError('20003:剧集序号不能为空');
  6479. }
  6480. if (!$script_id && !empty($episode_numbers)) {
  6481. Utils::throwError('20003:请提供剧本ID');
  6482. }
  6483. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6484. $query_uid = $is_public ? 0 : $uid;
  6485. // 如果是公共库操作,需要admin权限
  6486. if ($is_public && $role !== 'admin') {
  6487. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6488. }
  6489. // 检查是否存在且属于当前用户或公共库
  6490. $role = DB::table('mp_products')
  6491. ->where('id', $id)
  6492. ->where('cpid', $cpid)
  6493. ->where('user_id', $query_uid)
  6494. ->where('type', 1)->first();
  6495. if (!$role) Utils::throwError('20003:记录不存在');
  6496. $updateData = [];
  6497. // $needVersionRecord = false; // 是否需要记录版本
  6498. // 名称
  6499. $product_name = trim(getProp($data, 'product_name'));
  6500. if ($product_name) {
  6501. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6502. $updateData['product_name'] = $product_name;
  6503. }
  6504. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6505. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6506. // 图片地址
  6507. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6508. $url = trim(getProp($data, 'url'));
  6509. if ($url) {
  6510. // 检查是否是正确的图片格式
  6511. $urlPath = parse_url($url, PHP_URL_PATH);
  6512. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6513. if (!in_array($extension, $allowedExtensions)) {
  6514. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6515. }
  6516. // // 如果 url 有变更,记录版本
  6517. // if ($url !== $role->url) {
  6518. // $needVersionRecord = true;
  6519. // }
  6520. $updateData['url'] = $url;
  6521. }
  6522. // 三视图图片地址(选填),格式校验与 url 一致
  6523. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6524. if ($three_view_image_url) {
  6525. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6526. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6527. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6528. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6529. }
  6530. $updateData['three_view_image_url'] = $three_view_image_url;
  6531. }
  6532. // 音色音频地址(选填,显式传空字符串可清除已有音色)
  6533. if (array_key_exists('timbre_url', $data) || array_key_exists('audio_url', $data) || array_key_exists('timbre', $data)) {
  6534. $timbre_url = $this->getProductTimbreUrl($data);
  6535. if ($timbre_url) {
  6536. $this->validateProductAudioUrl($timbre_url);
  6537. }
  6538. $updateData['timbre_url'] = $timbre_url;
  6539. }
  6540. // 提示词
  6541. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6542. if ($pic_prompt) {
  6543. // // 如果 pic_prompt 有变更,记录版本
  6544. // if ($pic_prompt !== $role->pic_prompt) {
  6545. // $needVersionRecord = true;
  6546. // }
  6547. $updateData['pic_prompt'] = $pic_prompt;
  6548. }
  6549. if (empty($updateData) && !$script_id) {
  6550. Utils::throwError('20003:没有需要更新的数据');
  6551. }
  6552. // // 如果需要记录版本,将数据添加到 versions 数组
  6553. // if ($needVersionRecord) {
  6554. // // 获取现有的 versions 数据
  6555. // $versions = json_decode($role->versions, true) ?: [];
  6556. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6557. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6558. // if ($isFirstVersion) {
  6559. // $oldVersion = [
  6560. // 'url' => $role->url,
  6561. // 'description' => $role->pic_prompt,
  6562. // ];
  6563. // // 旧版本添加到数组末尾
  6564. // $versions[] = $oldVersion;
  6565. // }
  6566. // // 构建新版本(变更后)
  6567. // $newVersion = [
  6568. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6569. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6570. // ];
  6571. // // 检查新版本是否已存在于历史版本中
  6572. // $existingIndex = -1;
  6573. // foreach ($versions as $index => $version) {
  6574. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6575. // $existingIndex = $index;
  6576. // break;
  6577. // }
  6578. // }
  6579. // if ($existingIndex !== -1) {
  6580. // // 如果已存在,移除旧的位置
  6581. // array_splice($versions, $existingIndex, 1);
  6582. // }
  6583. // // 新版本添加到数组开头(最新的在前)
  6584. // array_unshift($versions, $newVersion);
  6585. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6586. // // if (count($versions) > 10) {
  6587. // // $versions = array_slice($versions, 0, 10);
  6588. // // }
  6589. // $updateData['versions'] = json_encode($versions, 256);
  6590. // }
  6591. if ($versions) {
  6592. $updateData['versions'] = json_encode($versions, 256);
  6593. }
  6594. if (!empty($updateData)) {
  6595. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6596. }
  6597. // 更新资产并保存剧本资产关联关系(同一事务)
  6598. DB::beginTransaction();
  6599. try {
  6600. $updated = true;
  6601. if (!empty($updateData)) {
  6602. $updated = DB::table('mp_products')
  6603. ->where('cpid', $cpid)
  6604. ->where('id', $id)
  6605. ->update($updateData);
  6606. }
  6607. // 保存剧本资产关联关系
  6608. if ($script_id) {
  6609. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6610. }
  6611. DB::commit();
  6612. } catch (\Exception $e) {
  6613. DB::rollback();
  6614. throw $e;
  6615. }
  6616. return $updated;
  6617. }
  6618. /**
  6619. * 获取资产音色音频地址
  6620. * 兼容 timbre_url/audio_url/timbre 三种传参,timbre 支持字符串或 {"url":"..."} 结构
  6621. *
  6622. * @param array $data
  6623. * @return string
  6624. */
  6625. private function getProductTimbreUrl($data) {
  6626. foreach (['timbre_url', 'audio_url', 'timbre'] as $key) {
  6627. if (!array_key_exists($key, $data)) {
  6628. continue;
  6629. }
  6630. $value = $data[$key];
  6631. if (is_array($value)) {
  6632. $value = getProp($value, 'url', $value[0] ?? '');
  6633. }
  6634. if (!is_string($value)) {
  6635. continue;
  6636. }
  6637. return trim($value);
  6638. }
  6639. return '';
  6640. }
  6641. /**
  6642. * 校验资产音色音频地址格式
  6643. *
  6644. * @param string $url 音频地址
  6645. * @return void
  6646. */
  6647. private function validateProductAudioUrl($url) {
  6648. $allowedExtensions = ['mp3', 'wav', 'm4a', 'aac', 'ogg', 'oga', 'flac', 'amr', 'wma', 'weba'];
  6649. $urlPath = parse_url($url, PHP_URL_PATH);
  6650. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6651. if (!in_array($extension, $allowedExtensions)) {
  6652. Utils::throwError('20003:音色音频格式不正确,仅支持 mp3、wav、m4a、aac、ogg、flac、amr、wma 格式');
  6653. }
  6654. }
  6655. /**
  6656. * 保存单一资产与剧本剧集的关联关系
  6657. *
  6658. * @param int $product_id 资产ID
  6659. * @param int $script_id 剧本ID
  6660. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6661. * @return int 新增关联数量
  6662. */
  6663. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6664. $uid = Site::getUid();
  6665. // 验证剧本是否存在
  6666. $script = DB::table('mp_scripts')
  6667. ->where('id', $script_id)
  6668. ->where('is_deleted', 0)
  6669. ->first();
  6670. if (!$script) {
  6671. Utils::throwError('20003:剧本不存在');
  6672. }
  6673. // 验证剧本归属:只能关联自己的剧本
  6674. if ((int)$script->user_id !== (int)$uid) {
  6675. Utils::throwError('20003:只能添加到自己的剧本');
  6676. }
  6677. // 使用 splitContent 拆分剧本内容获取总集数
  6678. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6679. // 解析剧集序号(数组)
  6680. $episodes = [];
  6681. foreach ($episode_numbers as $item) {
  6682. if (is_array($item)) {
  6683. continue;
  6684. }
  6685. $item = trim((string)$item);
  6686. if ($item === '' || !is_numeric($item)) {
  6687. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6688. }
  6689. $episodes[] = (int)$item;
  6690. }
  6691. // 去重并校验序号范围(序号从1开始)
  6692. $episodes = array_values(array_unique($episodes));
  6693. if (empty($episodes)) {
  6694. Utils::throwError('20003:剧集序号不能为空');
  6695. }
  6696. foreach ($episodes as $episode) {
  6697. if ($episode < 1 || $episode > $totalEpisodes) {
  6698. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6699. }
  6700. }
  6701. $now = now();
  6702. // 过滤已存在的关联,避免重复
  6703. $existingEpisodes = DB::table('mp_script_product_mappings')
  6704. ->where('script_id', $script_id)
  6705. ->where('product_id', $product_id)
  6706. ->whereIn('episode_number', $episodes)
  6707. ->pluck('episode_number')
  6708. ->all();
  6709. $mappingRecords = [];
  6710. foreach ($episodes as $episode) {
  6711. if (in_array($episode, $existingEpisodes)) {
  6712. continue;
  6713. }
  6714. $mappingRecords[] = [
  6715. 'script_id' => $script_id,
  6716. 'product_id' => $product_id,
  6717. 'episode_number' => $episode,
  6718. 'created_at' => $now,
  6719. 'updated_at' => $now,
  6720. ];
  6721. }
  6722. $insertedCount = 0;
  6723. if (!empty($mappingRecords)) {
  6724. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6725. }
  6726. return $insertedCount;
  6727. }
  6728. /**
  6729. * 规范化剧集序号参数,统一为数组
  6730. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6731. *
  6732. * @param mixed $episode_number 剧集序号参数
  6733. * @return array
  6734. */
  6735. private function normalizeEpisodeNumbers($episode_number) {
  6736. if (!is_array($episode_number)) {
  6737. $episode_number = explode(',', (string)$episode_number);
  6738. }
  6739. $items = [];
  6740. foreach ($episode_number as $item) {
  6741. if (is_array($item)) {
  6742. continue;
  6743. }
  6744. foreach (explode(',', (string)$item) as $part) {
  6745. $part = trim($part);
  6746. if ($part !== '') {
  6747. $items[] = $part;
  6748. }
  6749. }
  6750. }
  6751. return $items;
  6752. }
  6753. /**
  6754. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6755. *
  6756. * @param object $script 剧本记录
  6757. * @return int 总集数
  6758. */
  6759. private function getScriptTotalEpisodeCount($script) {
  6760. if (empty($script->content)) {
  6761. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6762. }
  6763. $totalEpisodes = count(splitContent($script->content));
  6764. if ($totalEpisodes < 1) {
  6765. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6766. }
  6767. return $totalEpisodes;
  6768. }
  6769. /**
  6770. * 获取剧本总集数
  6771. *
  6772. * @param array $data 包含 script_id(剧本ID)
  6773. * @return array
  6774. */
  6775. public function getScriptTotalEpisodes($data) {
  6776. $script_id = (int)getProp($data, 'script_id', 0);
  6777. if (!$script_id) {
  6778. Utils::throwError('20003:请提供剧本ID');
  6779. }
  6780. // 验证剧本是否存在
  6781. $script = DB::table('mp_scripts')
  6782. ->where('id', $script_id)
  6783. ->where('is_deleted', 0)
  6784. ->first();
  6785. if (!$script) {
  6786. Utils::throwError('20003:剧本不存在');
  6787. }
  6788. return [
  6789. 'script_id' => $script_id,
  6790. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6791. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6792. ];
  6793. }
  6794. /**
  6795. * 获取角色版本历史
  6796. * @param array $data 包含 id(角色ID)
  6797. * @return array 返回版本历史列表
  6798. */
  6799. public function getProductVersions($data) {
  6800. $cpid = Site::getCpid();
  6801. $id = getProp($data, 'id');
  6802. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6803. $role = DB::table('mp_products')
  6804. ->where('id', $id)
  6805. ->where('cpid', $cpid)
  6806. ->where('type', 1)
  6807. ->first();
  6808. if (!$role) Utils::throwError('20003:角色不存在');
  6809. // 获取版本历史
  6810. $versions = json_decode($role->versions, true) ?: [];
  6811. // 添加当前版本作为最新版本
  6812. $currentVersion = [
  6813. 'version' => 0, // 0 表示当前版本
  6814. 'url' => $role->url,
  6815. 'pic_prompt' => $role->pic_prompt,
  6816. 'updated_at' => $role->updated_at,
  6817. 'is_current' => true
  6818. ];
  6819. array_unshift($versions, $currentVersion);
  6820. return $versions;
  6821. }
  6822. /**
  6823. * 恢复到指定版本
  6824. * @param array $data 包含 id(角色ID)、version(版本号)
  6825. * @return bool
  6826. */
  6827. public function restoreProductVersion($data) {
  6828. $uid = Site::getUid();
  6829. $cpid = Site::getCpid();
  6830. $id = getProp($data, 'id');
  6831. $version = getProp($data, 'version');
  6832. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6833. if (!$version) Utils::throwError('20003:版本号不能为空');
  6834. $role = DB::table('mp_products')
  6835. ->where('id', $id)
  6836. ->where('cpid', $cpid)
  6837. ->where('type', 1)
  6838. ->first();
  6839. if (!$role) Utils::throwError('20003:角色不存在');
  6840. // 获取版本历史
  6841. $versions = json_decode($role->versions, true) ?: [];
  6842. // 查找指定版本
  6843. $targetVersion = null;
  6844. foreach ($versions as $v) {
  6845. if ($v['version'] == $version) {
  6846. $targetVersion = $v;
  6847. break;
  6848. }
  6849. }
  6850. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6851. // 先将当前版本保存到历史
  6852. $newVersion = [
  6853. 'version' => count($versions) + 1,
  6854. 'url' => $role->url,
  6855. 'pic_prompt' => $role->pic_prompt,
  6856. 'updated_at' => date('Y-m-d H:i:s'),
  6857. 'updated_by' => $uid
  6858. ];
  6859. array_unshift($versions, $newVersion);
  6860. // 限制版本数量
  6861. if (count($versions) > 10) {
  6862. $versions = array_slice($versions, 0, 10);
  6863. }
  6864. // 恢复到指定版本
  6865. return DB::table('mp_products')
  6866. ->where('id', $id)
  6867. ->where('cpid', $cpid)
  6868. ->update([
  6869. 'url' => $targetVersion['url'],
  6870. 'pic_prompt' => $targetVersion['pic_prompt'],
  6871. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6872. 'updated_at' => date('Y-m-d H:i:s')
  6873. ]);
  6874. }
  6875. public function deleteProduct($data) {
  6876. $uid = Site::getUid();
  6877. $cpid = Site::getCpid();
  6878. $role = Site::getRole();
  6879. $id = getProp($data, 'id');
  6880. if (!$id) Utils::throwError('20003:ID不能为空');
  6881. $ids = explode(',', $id);
  6882. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6883. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6884. $query_uid = $is_public ? 0 : $uid;
  6885. // 如果是公共库操作,需要admin权限
  6886. if ($is_public && $role !== 'admin') {
  6887. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6888. }
  6889. // 检查是否存在且属于当前用户或公共库
  6890. $role = DB::table('mp_products')
  6891. ->whereIn('id', $ids)
  6892. ->where('cpid', $cpid)
  6893. ->where('user_id', $query_uid)
  6894. ->get();
  6895. if (!$role) Utils::throwError('20003:记录不存在');
  6896. return DB::table('mp_products')
  6897. ->where('cpid', $cpid)
  6898. ->where('user_id', $query_uid)
  6899. ->whereIn('id', $ids)
  6900. ->update([
  6901. 'is_deleted' => 1,
  6902. 'updated_at' => date('Y-m-d H:i:s')
  6903. ]);
  6904. }
  6905. public function generateThreeView($data) {
  6906. $uid = Site::getUid();
  6907. $cpid = Site::getCpid();
  6908. $role = Site::getRole();
  6909. $id = getProp($data, 'id');
  6910. if (!$id) Utils::throwError('20003:ID不能为空');
  6911. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6912. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6913. $query_uid = $is_public ? 0 : $uid;
  6914. // 如果是公共库操作,需要admin权限
  6915. if ($is_public && $role !== 'admin') {
  6916. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6917. }
  6918. // 检查是否存在且属于当前用户或公共库
  6919. $product = DB::table('mp_products')
  6920. ->where('id', $id)
  6921. ->where('cpid', $cpid)
  6922. ->where('user_id', $query_uid)
  6923. ->where('type', 1)->first();
  6924. if (!$product) Utils::throwError('20003:资产不存在');
  6925. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。'));
  6926. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6927. if (!$ref_img_url) {
  6928. // 如果没有传入参考图,使用角色表中的图片
  6929. $ref_img_url = $product->url ?? '';
  6930. if (!$ref_img_url) {
  6931. Utils::throwError('20003:参考图不能为空');
  6932. }
  6933. }
  6934. $pic_prompt = getProp($product, 'pic_prompt');
  6935. if ($pic_prompt) {
  6936. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6937. }
  6938. // 检查参考图是否是正确的图片格式
  6939. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6940. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6941. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6942. if (!in_array($extension, $allowedExtensions)) {
  6943. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6944. }
  6945. // 处理图片模型
  6946. $model = getProp($data, 'model');
  6947. if (!$model) {
  6948. // 使用默认模型
  6949. $model = 'gpt-image-2';
  6950. }
  6951. // 验证模型是否在可用模型表中
  6952. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6953. Utils::throwError('20003:该模型已不可用,请更换!');
  6954. }
  6955. $ratio = getProp($data, 'ratio', '16:9');
  6956. $resolution = getProp($data, 'resolution', '2k');
  6957. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  6958. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  6959. // 参数验证
  6960. $resolution = strtolower($resolution);
  6961. if (!isset($sizeMap[$resolution])) {
  6962. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6963. }
  6964. if (!isset($sizeMap[$resolution][$ratio])) {
  6965. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6966. }
  6967. // 根据 ratio 和 resolution 确定宽高
  6968. $width = $sizeMap[$resolution][$ratio]['width'];
  6969. $height = $sizeMap[$resolution][$ratio]['height'];
  6970. try {
  6971. // 创建图片生成任务
  6972. $params = [
  6973. 'prompt' => $prompt,
  6974. 'model' => $model,
  6975. 'ref_img_urls' => [$ref_img_url],
  6976. 'width' => $width,
  6977. 'height' => $height
  6978. ];
  6979. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6980. $task_id = $task->id;
  6981. if (!$task_id) {
  6982. Utils::throwError('20003:创建图片生成任务失败');
  6983. }
  6984. // 轮询获取结果
  6985. // 只查询数据库,不调用API,不更新任务表
  6986. $start_time = time();
  6987. $timeout = 1800;
  6988. $img_url = '';
  6989. while (time() - $start_time < $timeout) {
  6990. sleep(5);
  6991. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6992. $task = DB::table('mp_generate_pic_tasks')
  6993. ->where('id', $task_id)
  6994. ->first();
  6995. if (!$task) {
  6996. Utils::throwError('20003:任务不存在');
  6997. }
  6998. if ($task->status === 'success' && $task->result_url) {
  6999. $result_urls = is_string($task->result_url)
  7000. ? json_decode($task->result_url, true)
  7001. : $task->result_url;
  7002. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7003. break;
  7004. } elseif ($task->status === 'failed') {
  7005. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  7006. }
  7007. // 其他状态继续轮询
  7008. }
  7009. if (empty($img_url)) {
  7010. Utils::throwError('20003:三视图生成超时,请稍后重试');
  7011. }
  7012. // 更新 mp_products 表(不是任务表)
  7013. DB::table('mp_products')
  7014. ->where('id', $id)
  7015. ->where('cpid', $cpid)
  7016. ->update([
  7017. 'three_view_image_url' => $img_url,
  7018. 'updated_at' => date('Y-m-d H:i:s')
  7019. ]);
  7020. return ['three_view_image_url' => $img_url];
  7021. } catch (\Exception $e) {
  7022. dLog('anime')->error('生成三视图失败', [
  7023. 'error' => $e->getMessage()
  7024. ]);
  7025. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  7026. Utils::throwError('20003:' . $e->getMessage());
  7027. }
  7028. }
  7029. /**
  7030. * 推送(复制)资产或文件夹到目标位置
  7031. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  7032. * @return array 返回推送结果
  7033. */
  7034. public function pushProductOrFolder($data) {
  7035. $uid = Site::getUid();
  7036. $cpid = Site::getCpid();
  7037. $role = Site::getRole();
  7038. $product_id = getProp($data, 'product_id');
  7039. $target_parent_id = getProp($data, 'target_parent_id', 0);
  7040. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  7041. if (!$product_id) {
  7042. Utils::throwError('20003:请选择要推送的项目');
  7043. }
  7044. // 查询源项目(只通过cpid查询,不限制user_id)
  7045. $sourceItem = DB::table('mp_products')
  7046. ->where('id', $product_id)
  7047. ->where('cpid', $cpid)
  7048. ->where('is_deleted', 0)
  7049. ->first();
  7050. if (!$sourceItem) {
  7051. Utils::throwError('20003:要推送的项目不存在');
  7052. }
  7053. // 通过user_id判断源是公共库还是个人库
  7054. $source_uid = $sourceItem->user_id;
  7055. $source_is_public = ($source_uid == 0) ? 1 : 0;
  7056. // 验证目标文件夹并确定目标是公共库还是个人库
  7057. $target_level = 0;
  7058. $target_uid = $uid; // 默认推送到个人库
  7059. $target_is_public = 0;
  7060. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  7061. if ($target_parent_id > 0) {
  7062. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  7063. $targetParent = DB::table('mp_products')
  7064. ->where('id', $target_parent_id)
  7065. ->where('cpid', $cpid)
  7066. ->where('type', 2)
  7067. ->where('is_deleted', 0)
  7068. ->first();
  7069. if (!$targetParent) {
  7070. Utils::throwError('20003:目标文件夹不存在');
  7071. }
  7072. // 通过user_id判断目标是公共库还是个人库
  7073. $target_level = $targetParent->level;
  7074. $target_uid = $targetParent->user_id;
  7075. $target_is_public = ($target_uid == 0) ? 1 : 0;
  7076. // 使用目标文件夹的 product 类型
  7077. $final_product_type = $targetParent->product;
  7078. }
  7079. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  7080. else {
  7081. $push_to_public = getProp($data, 'push_to_public');
  7082. if ($push_to_public === '') {
  7083. Utils::throwError('20003:请选择是否推送到公共库');
  7084. }
  7085. if ($push_to_public) {
  7086. $target_uid = 0;
  7087. $target_is_public = 1;
  7088. }
  7089. // 推送到根目录时,必须指定 product 类型
  7090. if ($target_product === null || $target_product === '') {
  7091. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  7092. }
  7093. $final_product_type = $target_product;
  7094. }
  7095. // 如果目标是公共库,需要admin权限
  7096. if ($target_is_public && $role !== 'admin') {
  7097. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  7098. }
  7099. // 权限验证:验证是否符合允许的推送规则
  7100. $this->validatePushPermission($source_uid, $target_uid, $uid);
  7101. try {
  7102. DB::beginTransaction();
  7103. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  7104. if ($sourceItem->type == 1) {
  7105. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  7106. DB::commit();
  7107. return [
  7108. 'product_id' => $newId,
  7109. ];
  7110. }
  7111. // 如果是文件夹,递归复制(支持跨类型推送)
  7112. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  7113. DB::commit();
  7114. return [
  7115. 'product_id' => $newFolderId,
  7116. ];
  7117. } catch (\Exception $e) {
  7118. DB::rollBack();
  7119. dLog('anime')->error('推送失败', [
  7120. 'error' => $e->getMessage(),
  7121. 'product_id' => $product_id
  7122. ]);
  7123. Utils::throwError('20003:' . $e->getMessage());
  7124. }
  7125. }
  7126. /**
  7127. * 验证推送权限
  7128. * 允许的推送规则:
  7129. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7130. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  7131. * 3. 公共库推送给公共库(公共库 → 公共库)
  7132. *
  7133. * @param int $source_uid 源的user_id
  7134. * @param int $target_uid 目标的user_id
  7135. * @param int $current_uid 当前用户ID
  7136. * @throws \Exception
  7137. */
  7138. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  7139. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7140. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  7141. return; // 允许
  7142. }
  7143. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  7144. if ($source_uid == 0 && $target_uid == $current_uid) {
  7145. return; // 允许
  7146. }
  7147. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7148. if ($source_uid == 0 && $target_uid == 0) {
  7149. return; // 允许
  7150. }
  7151. // 其他情况都不允许
  7152. if ($source_uid != 0 && $source_uid != $current_uid) {
  7153. // 源是别人的个人库
  7154. Utils::throwError('20003:无权限访问该资产');
  7155. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7156. // 个人库推送给公共库(不允许)
  7157. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7158. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7159. // 不同用户的个人库之间推送(不允许)
  7160. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7161. } else {
  7162. // 其他未知情况
  7163. Utils::throwError('20003:不允许的推送操作');
  7164. }
  7165. }
  7166. /**
  7167. * 复制单个资产
  7168. * @param object $sourceProduct 源资产对象
  7169. * @param int $targetParentId 目标父文件夹ID
  7170. * @param int $targetLevel 目标层级
  7171. * @param int $cpid 公司ID
  7172. * @param int $targetUid 目标用户ID
  7173. * @return int 返回新资产ID
  7174. */
  7175. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7176. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7177. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7178. $newProductData = [
  7179. 'user_id' => $targetUid,
  7180. 'cpid' => $cpid,
  7181. 'type' => 1,
  7182. 'parent_id' => $targetParentId,
  7183. 'level' => $targetLevel,
  7184. 'product_name' => $sourceProduct->product_name,
  7185. 'url' => $sourceProduct->url,
  7186. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7187. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7188. 'product' => $finalProductType,
  7189. 'versions' => $sourceProduct->versions ?? '',
  7190. 'sort_order' => time(),
  7191. 'is_deleted' => 0,
  7192. 'created_at' => date('Y-m-d H:i:s'),
  7193. 'updated_at' => date('Y-m-d H:i:s')
  7194. ];
  7195. return DB::table('mp_products')->insertGetId($newProductData);
  7196. }
  7197. /**
  7198. * 递归复制文件夹及其子项
  7199. * @param object $sourceFolder 源文件夹对象
  7200. * @param int $targetParentId 目标父文件夹ID
  7201. * @param int $targetLevel 目标层级
  7202. * @param int $cpid 公司ID
  7203. * @param int $targetUid 目标用户ID
  7204. * @param int $sourceUid 源用户ID
  7205. * @return int 返回新文件夹ID
  7206. */
  7207. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7208. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7209. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7210. // 创建新文件夹
  7211. $newFolderData = [
  7212. 'user_id' => $targetUid,
  7213. 'cpid' => $cpid,
  7214. 'type' => 2,
  7215. 'parent_id' => $targetParentId,
  7216. 'level' => $targetLevel,
  7217. 'product_name' => $sourceFolder->product_name,
  7218. 'product' => $finalProductType,
  7219. 'sort_order' => time(),
  7220. 'is_deleted' => 0,
  7221. 'created_at' => date('Y-m-d H:i:s'),
  7222. 'updated_at' => date('Y-m-d H:i:s')
  7223. ];
  7224. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7225. // 获取源文件夹下的所有子项
  7226. $children = DB::table('mp_products')
  7227. ->where('parent_id', $sourceFolder->id)
  7228. ->where('cpid', $cpid)
  7229. ->where('user_id', $sourceUid)
  7230. ->where('is_deleted', 0)
  7231. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7232. ->get();
  7233. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7234. foreach ($children as $child) {
  7235. if ($child->type == 1) {
  7236. // 资产
  7237. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7238. } else {
  7239. // 文件夹
  7240. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7241. }
  7242. }
  7243. return $newFolderId;
  7244. }
  7245. /**
  7246. * 转让剧本归属(剧本及其关联资产)
  7247. *
  7248. * 仅调整 mp_scripts.user_id 与 mp_products.user_id,其他表保持不变。
  7249. * 权限:仅 admin / superadmin 可操作;目标用户必须是同组(cpid 相同)且角色为 user(组员)的用户,禁止跨组转让。
  7250. * 多个剧本逐个独立事务处理,单个剧本失败不影响其他剧本;
  7251. * 单个剧本内的剧本记录与关联资产必须全部更新成功,否则整体回滚。
  7252. *
  7253. * @param array $data 请求参数:script_ids(数组或英文逗号分隔,兼容单个 script_id)、target_user_id
  7254. * @return array
  7255. */
  7256. public function transferScriptOwner($data) {
  7257. $operatorRole = Site::getRole();
  7258. $operatorCpid = Site::getCpid();
  7259. // 1.权限校验:仅管理员和超管可操作
  7260. if (!in_array($operatorRole, ['admin', 'superadmin'], true)) {
  7261. Utils::throwError(ErrorConst::NOT_ACCESS);
  7262. }
  7263. // 2.目标用户校验:必须存在且角色为 user(组员)
  7264. $targetUserId = (int)getProp($data, 'target_user_id', 0);
  7265. if ($targetUserId < 1) {
  7266. Utils::throwError('1002:请选择转让的目标用户');
  7267. }
  7268. $targetUser = DB::table('mp_manage_users')
  7269. ->where('id', $targetUserId)
  7270. ->where('is_deleted', 0)
  7271. ->first();
  7272. if (!$targetUser) {
  7273. Utils::throwError('20003:目标用户不存在');
  7274. }
  7275. if ((string)getProp($targetUser, 'role') !== 'user') {
  7276. Utils::throwError('20003:只能转让给角色为组员(user)的用户');
  7277. }
  7278. $targetCpid = (int)getProp($targetUser, 'cpid');
  7279. // 3.规范化剧本ID列表(兼容数组、逗号分隔字符串、script_id 单值)
  7280. $rawScriptIds = getProp($data, 'script_ids');
  7281. if (empty($rawScriptIds)) {
  7282. $rawScriptIds = getProp($data, 'script_id');
  7283. }
  7284. $scriptIds = $this->normalizeIdList($rawScriptIds);
  7285. if (empty($scriptIds)) {
  7286. Utils::throwError('20003:请提供剧本ID');
  7287. }
  7288. // 预取剧本名称,便于失败结果中回显
  7289. $scriptNameMap = DB::table('mp_scripts')
  7290. ->whereIn('id', $scriptIds)
  7291. ->pluck('script_name', 'id')
  7292. ->all();
  7293. $successList = [];
  7294. $failedList = [];
  7295. // 4.逐个剧本独立事务处理,单个失败不影响其他剧本
  7296. foreach ($scriptIds as $scriptId) {
  7297. DB::beginTransaction();
  7298. try {
  7299. $successList[] = $this->transferSingleScriptOwner(
  7300. $scriptId,
  7301. $targetUserId,
  7302. $targetCpid,
  7303. $operatorRole,
  7304. $operatorCpid,
  7305. Site::getUid()
  7306. );
  7307. DB::commit();
  7308. } catch (\Throwable $e) {
  7309. DB::rollBack();
  7310. $failedList[] = [
  7311. 'script_id' => (int)$scriptId,
  7312. 'script_name' => (string)($scriptNameMap[$scriptId] ?? ''),
  7313. 'reason' => $e->getMessage() !== '' ? $e->getMessage() : '转让失败',
  7314. ];
  7315. dLog('anime')->error('剧本归属转让失败', [
  7316. 'script_id' => $scriptId,
  7317. 'target_user_id' => $targetUserId,
  7318. 'operator_uid' => Site::getUid(),
  7319. 'error' => $e->getMessage(),
  7320. ]);
  7321. }
  7322. }
  7323. return [
  7324. 'target_user_id' => $targetUserId,
  7325. 'success_count' => count($successList),
  7326. 'failed_count' => count($failedList),
  7327. 'success_list' => $successList,
  7328. 'failed_list' => $failedList,
  7329. ];
  7330. }
  7331. /**
  7332. * 单个剧本的归属转让(需在事务中调用)
  7333. *
  7334. * @param int $scriptId 剧本ID
  7335. * @param int $targetUserId 目标用户ID
  7336. * @param int $targetCpid 目标用户所属公司ID
  7337. * @param string $operatorRole 操作人角色
  7338. * @param int $operatorCpid 操作人所属公司ID
  7339. * @param int $operatorUid 操作人用户ID
  7340. * @return array
  7341. */
  7342. private function transferSingleScriptOwner($scriptId, $targetUserId, $targetCpid, $operatorRole, $operatorCpid, $operatorUid) {
  7343. $script = DB::table('mp_scripts')
  7344. ->where('id', $scriptId)
  7345. ->where('is_deleted', 0)
  7346. ->first();
  7347. if (!$script) {
  7348. Utils::throwError('20003:剧本不存在');
  7349. }
  7350. $scriptCpid = (int)getProp($script, 'cpid');
  7351. $fromUserId = (int)getProp($script, 'user_id');
  7352. // 管理员仅可操作本组剧本
  7353. if ($operatorRole !== 'superadmin' && $scriptCpid !== $operatorCpid) {
  7354. Utils::throwError(ErrorConst::NOT_ACCESS);
  7355. }
  7356. // 管理员仅可转让自己创建的剧本(超管不做此验证)
  7357. if ($operatorRole !== 'superadmin' && $fromUserId !== (int)$operatorUid) {
  7358. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7359. }
  7360. // 禁止跨组转让:目标用户必须与剧本同组
  7361. if ($targetCpid !== $scriptCpid) {
  7362. Utils::throwError('20003:不能跨组转让,目标用户与剧本不在同一组');
  7363. }
  7364. // 关联资产ID(同一资产可能关联多个剧集序号,需去重)
  7365. $productIds = $this->normalizeIdList(
  7366. DB::table('mp_script_product_mappings')
  7367. ->where('script_id', $scriptId)
  7368. ->pluck('product_id')
  7369. ->all()
  7370. );
  7371. $folderIds = [];
  7372. if (!empty($productIds)) {
  7373. $products = DB::table('mp_products')
  7374. ->whereIn('id', $productIds)
  7375. ->select('id', 'cpid', 'parent_id', 'user_id')
  7376. ->get();
  7377. // 关联资产必须全部存在,否则视为数据异常,不提交
  7378. if ($products->count() !== count($productIds)) {
  7379. Utils::throwError('20003:剧本存在已丢失的关联资产,无法完成转让');
  7380. }
  7381. foreach ($products as $product) {
  7382. // 关联资产必须与剧本同组,避免误转让跨组资产
  7383. if ((int)getProp($product, 'cpid') !== $scriptCpid) {
  7384. Utils::throwError('20003:剧本存在跨组关联资产,无法完成转让');
  7385. }
  7386. $parentId = (int)getProp($product, 'parent_id', 0);
  7387. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7388. $folderIds[] = $parentId;
  7389. }
  7390. }
  7391. // 仅转让归属于原剧本所有者的资产
  7392. $folderIds = DB::table('mp_products')
  7393. ->whereIn('id', $folderIds)
  7394. ->where('type', 2)
  7395. ->where('cpid', $scriptCpid)
  7396. ->where('user_id', $fromUserId)
  7397. ->pluck('id')
  7398. ->map('intval')
  7399. ->all();
  7400. // 管理员仅可转让自己创建的资产及其所属文件夹(超管不做此验证)
  7401. if ($operatorRole !== 'superadmin') {
  7402. foreach ($products as $product) {
  7403. if ((int)getProp($product, 'user_id') !== (int)$operatorUid) {
  7404. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7405. }
  7406. }
  7407. foreach ($products as $product) {
  7408. $parentId = (int)getProp($product, 'parent_id', 0);
  7409. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7410. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7411. }
  7412. }
  7413. }
  7414. }
  7415. $now = now();
  7416. // 5.更新剧本归属
  7417. DB::table('mp_scripts')
  7418. ->where('id', $scriptId)
  7419. ->update([
  7420. 'user_id' => $targetUserId,
  7421. 'updated_at' => $now,
  7422. ]);
  7423. // 6.更新关联资产归属
  7424. if (!empty($productIds)) {
  7425. DB::table('mp_products')
  7426. ->whereIn('id', $productIds)
  7427. ->update([
  7428. 'user_id' => $targetUserId,
  7429. 'updated_at' => $now,
  7430. ]);
  7431. }
  7432. // 7.更新资产所属的类型根文件夹归属(文件夹属于 mp_products,随资产一并转让)
  7433. if (!empty($folderIds)) {
  7434. DB::table('mp_products')
  7435. ->whereIn('id', $folderIds)
  7436. ->update([
  7437. 'user_id' => $targetUserId,
  7438. 'updated_at' => $now,
  7439. ]);
  7440. }
  7441. // 8.校验剧本与资产是否全部更新成功,任一未成功则回滚
  7442. $scriptOwner = (int)DB::table('mp_scripts')->where('id', $scriptId)->value('user_id');
  7443. if ($scriptOwner !== $targetUserId) {
  7444. Utils::throwError('20003:剧本归属更新失败');
  7445. }
  7446. if (!empty($productIds)) {
  7447. $updatedProductCount = DB::table('mp_products')
  7448. ->whereIn('id', $productIds)
  7449. ->where('user_id', $targetUserId)
  7450. ->count();
  7451. if ($updatedProductCount !== count($productIds)) {
  7452. Utils::throwError('20003:部分剧本资产转让失败,已回滚');
  7453. }
  7454. }
  7455. if (!empty($folderIds)) {
  7456. $updatedFolderCount = DB::table('mp_products')
  7457. ->whereIn('id', $folderIds)
  7458. ->where('user_id', $targetUserId)
  7459. ->count();
  7460. if ($updatedFolderCount !== count($folderIds)) {
  7461. Utils::throwError('20003:部分资产文件夹转让失败,已回滚');
  7462. }
  7463. }
  7464. return [
  7465. 'script_id' => (int)$scriptId,
  7466. 'script_name' => (string)getProp($script, 'script_name', ''),
  7467. 'from_user_id' => $fromUserId,
  7468. 'to_user_id' => $targetUserId,
  7469. 'product_count' => count($productIds),
  7470. 'folder_count' => count($folderIds),
  7471. ];
  7472. }
  7473. /**
  7474. * 规范化ID列表,兼容数组、逗号分隔字符串以及字符串数组
  7475. *
  7476. * @param mixed $ids 待处理的ID集合
  7477. * @return array 去重后的正整数ID数组
  7478. */
  7479. private function normalizeIdList($ids) {
  7480. if (!is_array($ids)) {
  7481. $ids = explode(',', (string)$ids);
  7482. }
  7483. $result = [];
  7484. foreach ($ids as $item) {
  7485. if (is_array($item)) {
  7486. continue;
  7487. }
  7488. foreach (explode(',', (string)$item) as $part) {
  7489. $part = trim($part);
  7490. if ($part !== '' && is_numeric($part) && (int)$part > 0) {
  7491. $result[] = (int)$part;
  7492. }
  7493. }
  7494. }
  7495. return array_values(array_unique($result));
  7496. }
  7497. /**
  7498. * 通过 Excel 批量导入剧本资产(独立实现,不依赖 saveScriptProducts)
  7499. *
  7500. * 流程:
  7501. * 1. 校验剧本存在且属于当前用户
  7502. * 2. 解析 Excel 并校验强制列与数据完整性(资产类型/资产名称/使用范围/参考提示词)
  7503. * 3. 名称去重(与 Excel 内及该剧本已有关联资产比对)
  7504. * 4. 事务内创建类型文件夹、资产与剧本映射
  7505. * 5. 为没有图片的资产创建图片生成任务,生成中返回 SSE 轮询
  7506. *
  7507. * @param array $data 请求参数
  7508. * @param \Illuminate\Http\UploadedFile $file 上传的 Excel 文件
  7509. * @return array|\Generator
  7510. */
  7511. public function importScriptProductsByExcel($data, $file) {
  7512. $uid = Site::getUid();
  7513. $cpid = Site::getCpid();
  7514. $script_id = (int)getProp($data, 'script_id', 0);
  7515. if (!$script_id) {
  7516. Utils::throwError('20003:请提供剧本ID');
  7517. }
  7518. // 验证剧本是否存在,且只能导入自己创建的剧本
  7519. $script = DB::table('mp_scripts')
  7520. ->where('id', $script_id)
  7521. ->where('is_deleted', 0)
  7522. ->where('user_id', $uid)
  7523. ->first();
  7524. if (!$script) {
  7525. Utils::throwError('20003:剧本不存在或无权限操作');
  7526. }
  7527. $script_name = $script->script_name ?? 'script_' . $script_id;
  7528. // 校验上传文件
  7529. if (!$file) {
  7530. Utils::throwError('20003:请上传Excel文件');
  7531. }
  7532. $extension = strtolower($file->getClientOriginalExtension());
  7533. if (!in_array($extension, ['xlsx', 'xls'])) {
  7534. Utils::throwError('20003:文件格式错误,仅支持 xlsx、xls 格式');
  7535. }
  7536. if ($file->getSize() > 10 * 1024 * 1024) {
  7537. Utils::throwError('20003:文件大小不能超过10M');
  7538. }
  7539. // 解析 Excel(第一行为表头)
  7540. $rows = $this->readImportExcelRows($file);
  7541. if (empty($rows)) {
  7542. Utils::throwError('20003:Excel内容为空');
  7543. }
  7544. $headers = array_shift($rows);
  7545. // 定位强制列
  7546. $typeColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产类型'], ['资产类型', '类型']);
  7547. $nameColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产名称'], ['资产名称', '名称']);
  7548. $rangeColumnIndex = $this->findImportExcelColumnIndex($headers, ['使用范围'], ['使用范围', '范围']);
  7549. $promptColumnIndex = $this->findImportExcelColumnIndex($headers, ['参考提示词', '提示词'], ['提示词']);
  7550. $missingColumns = [];
  7551. if ($typeColumnIndex < 0) {
  7552. $missingColumns[] = '资产类型';
  7553. }
  7554. if ($nameColumnIndex < 0) {
  7555. $missingColumns[] = '资产名称';
  7556. }
  7557. if ($rangeColumnIndex < 0) {
  7558. $missingColumns[] = '使用范围';
  7559. }
  7560. if ($promptColumnIndex < 0) {
  7561. $missingColumns[] = '参考提示词';
  7562. }
  7563. if (!empty($missingColumns)) {
  7564. Utils::throwError('20003:Excel缺少必填列:' . implode('、', $missingColumns));
  7565. }
  7566. // 先整体校验 Excel 数据,所有异常行一次性返回
  7567. $validation = $this->validateImportExcelRows(
  7568. $rows,
  7569. $typeColumnIndex,
  7570. $nameColumnIndex,
  7571. $rangeColumnIndex,
  7572. $promptColumnIndex
  7573. );
  7574. $errors = $validation['errors'];
  7575. $checkedRows = $validation['checked_rows'];
  7576. if (empty($checkedRows)) {
  7577. $errors[] = 'Excel中没有有效的数据行';
  7578. }
  7579. if (!empty($errors)) {
  7580. Utils::throwError('20003:Excel数据校验失败:' . implode(';', $errors));
  7581. }
  7582. // 名称去重:Excel 内部 + 该剧本已关联资产(按 createProduct 的名称判断逻辑)
  7583. $existingNames = $this->getScriptProductNames($script_id, $cpid);
  7584. $dedupResult = $this->deduplicateImportRows($checkedRows, $existingNames);
  7585. $validRows = $dedupResult['valid_rows'];
  7586. $skipped = $dedupResult['skipped'];
  7587. // 图片生成参数(与 saveScriptProducts 保持一致的校验规则)
  7588. $model = getProp($data, 'model');
  7589. if (!$model) {
  7590. $model = 'gpt-image-2';
  7591. }
  7592. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7593. Utils::throwError('20003:该模型已不可用,请更换!');
  7594. }
  7595. $ratio = getProp($data, 'ratio', '9:16');
  7596. $resolution = strtolower(getProp($data, 'resolution', '2k'));
  7597. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7598. if (!isset($sizeMap[$resolution])) {
  7599. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7600. }
  7601. if (!isset($sizeMap[$resolution][$ratio])) {
  7602. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7603. }
  7604. $width = $sizeMap[$resolution][$ratio]['width'];
  7605. $height = $sizeMap[$resolution][$ratio]['height'];
  7606. $autoRaw = getProp($data, 'auto_generate_images', true);
  7607. $auto_generate_images = !in_array($autoRaw, [false, 0, '0', 'false', 'False'], true);
  7608. // 创建/复用任务中心记录(md5 验重,避免重复任务)
  7609. $taskCenterId = $this->createScriptProductTaskCenter(
  7610. $uid,
  7611. $cpid,
  7612. $script_id,
  7613. $validRows,
  7614. $model,
  7615. $ratio,
  7616. $resolution,
  7617. $auto_generate_images
  7618. );
  7619. // 全部为重复项:参照 saveScriptProducts,检查已存在资产的图片状态,缺图的补建任务
  7620. if (empty($validRows)) {
  7621. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7622. $script_id,
  7623. $model,
  7624. $width,
  7625. $height,
  7626. $auto_generate_images
  7627. );
  7628. $productTaskMap = $existingTaskInfo['product_task_map'];
  7629. $typeFolderIds = $existingTaskInfo['type_folder_ids'];
  7630. if (!empty($productTaskMap)) {
  7631. $message = 'Excel中的资产均已存在,正在为缺少图片的资产生成图片';
  7632. } elseif (!$existingTaskInfo['has_all_tasks']) {
  7633. $message = 'Excel中的资产均已存在,部分资产没有参考提示词,无法生成图片';
  7634. } else {
  7635. $message = 'Excel中的资产均已存在,且图片已全部生成完成';
  7636. }
  7637. $resultData = [
  7638. 'success' => true,
  7639. 'message' => $message,
  7640. 'script_id' => $script_id,
  7641. 'script_name' => $script_name,
  7642. 'imported_count' => 0,
  7643. 'existing_products' => $existingTaskInfo['product_count'],
  7644. 'skipped_count' => count($skipped),
  7645. 'skipped' => $skipped,
  7646. 'created_products' => [],
  7647. 'type_folder_ids' => $typeFolderIds,
  7648. 'pending_tasks_count' => count($productTaskMap),
  7649. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7650. 'task_center_id' => $taskCenterId,
  7651. ];
  7652. // 有需要轮询的任务(已有任务或本次补建):走 SSE 轮询
  7653. if (!empty($productTaskMap)) {
  7654. return $this->pollProductImageTasks(
  7655. $script_id,
  7656. $script_name,
  7657. $productTaskMap,
  7658. $typeFolderIds,
  7659. $taskCenterId,
  7660. ['import_result' => $resultData],
  7661. ['import_result' => $resultData]
  7662. );
  7663. }
  7664. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7665. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7666. }
  7667. // 事务内创建资产、类型文件夹与剧本映射
  7668. $typeFolderIds = [];
  7669. $createdProducts = [];
  7670. $mappingRecords = [];
  7671. $now = now();
  7672. DB::beginTransaction();
  7673. try {
  7674. foreach ($validRows as $row) {
  7675. $type = $row['type'];
  7676. if (!isset($typeFolderIds[$type])) {
  7677. // 与 createProduct 一致:先查找该剧本已存在的类型文件夹,没有则创建
  7678. $folder = DB::table('mp_products')
  7679. ->where('cpid', $cpid)
  7680. ->where('type', 2)
  7681. ->where('product', $type)
  7682. ->where('product_name', $script_name)
  7683. ->where('parent_id', 0)
  7684. ->where('is_deleted', 0)
  7685. ->first();
  7686. if ($folder) {
  7687. $typeFolderIds[$type] = $folder->id;
  7688. } else {
  7689. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7690. 'user_id' => $uid,
  7691. 'cpid' => $cpid,
  7692. 'type' => 2, // 文件夹
  7693. 'product' => $type, // 1=角色 2=场景 3=道具
  7694. 'parent_id' => 0,
  7695. 'level' => 1,
  7696. 'product_name' => $script_name,
  7697. 'sort_order' => time() + $type,
  7698. 'is_deleted' => 0,
  7699. 'created_at' => $now,
  7700. 'updated_at' => $now,
  7701. ]);
  7702. }
  7703. }
  7704. $folder_id = $typeFolderIds[$type];
  7705. $product_id = DB::table('mp_products')->insertGetId([
  7706. 'user_id' => $uid,
  7707. 'cpid' => $cpid,
  7708. 'type' => 1, // 资产
  7709. 'product' => $type,
  7710. 'parent_id' => $folder_id,
  7711. 'level' => 2,
  7712. 'product_name' => $row['product_name'],
  7713. 'pic_prompt' => $row['pic_prompt'],
  7714. 'sort_order' => time(),
  7715. 'is_deleted' => 0,
  7716. 'created_at' => $now,
  7717. 'updated_at' => $now,
  7718. ]);
  7719. $createdProducts[] = [
  7720. 'id' => $product_id,
  7721. 'type' => $type,
  7722. 'product_name' => $row['product_name'],
  7723. 'pic_prompt' => $row['pic_prompt'],
  7724. ];
  7725. // 为每个使用范围(集数)创建映射记录
  7726. foreach ($row['episode_numbers'] as $episodeNumber) {
  7727. $mappingRecords[] = [
  7728. 'script_id' => $script_id,
  7729. 'product_id' => $product_id,
  7730. 'episode_number' => $episodeNumber,
  7731. 'created_at' => $now,
  7732. 'updated_at' => $now,
  7733. ];
  7734. }
  7735. }
  7736. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7737. DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7738. // 剧本已有资产,同步更新is_products标记
  7739. DB::table('mp_scripts')->where('id', $script_id)->update([
  7740. 'is_products' => 1,
  7741. 'updated_at' => $now,
  7742. ]);
  7743. DB::commit();
  7744. } catch (\Exception $e) {
  7745. DB::rollback();
  7746. if ($taskCenterId) {
  7747. $this->taskCenterService->updateTask($taskCenterId, [
  7748. 'status' => MpTaskCenter::STATUS_FAILED,
  7749. 'error_message' => $e->getMessage(),
  7750. ]);
  7751. }
  7752. dLog('anime')->error('Excel导入剧本资产失败: ' . $e->getMessage(), [
  7753. 'script_id' => $script_id,
  7754. 'error' => $e->getMessage(),
  7755. 'trace' => $e->getTraceAsString(),
  7756. ]);
  7757. Utils::throwError('20003:Excel导入剧本资产失败:' . $e->getMessage());
  7758. }
  7759. // 参照 saveScriptProducts:为新建资产以及已存在但缺图的资产统一补建图片生成任务
  7760. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7761. $script_id,
  7762. $model,
  7763. $width,
  7764. $height,
  7765. $auto_generate_images
  7766. );
  7767. $productTaskMap = $existingTaskInfo['product_task_map'];
  7768. $resultData = [
  7769. 'success' => true,
  7770. 'message' => '导入完成',
  7771. 'script_id' => $script_id,
  7772. 'script_name' => $script_name,
  7773. 'imported_count' => count($createdProducts),
  7774. 'skipped_count' => count($skipped),
  7775. 'skipped' => $skipped,
  7776. 'created_products' => array_map(function ($item) {
  7777. return [
  7778. 'id' => $item['id'],
  7779. 'type' => $item['type'],
  7780. 'product_name' => $item['product_name'],
  7781. ];
  7782. }, $createdProducts),
  7783. 'type_folder_ids' => $typeFolderIds,
  7784. 'pending_tasks_count' => count($productTaskMap),
  7785. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7786. 'task_center_id' => $taskCenterId,
  7787. ];
  7788. // 有待生成的图片任务:返回 SSE 轮询结果(导入统计在 init 与 complete 事件中)
  7789. if (!empty($productTaskMap)) {
  7790. return $this->pollProductImageTasks(
  7791. $script_id,
  7792. $script_name,
  7793. $productTaskMap,
  7794. $typeFolderIds,
  7795. $taskCenterId,
  7796. ['import_result' => $resultData],
  7797. ['import_result' => $resultData]
  7798. );
  7799. }
  7800. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7801. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7802. }
  7803. /**
  7804. * 校验 Excel 数据行(先校验完毕,再进行后续逻辑)
  7805. *
  7806. * @param array $rows
  7807. * @param int $typeColumnIndex
  7808. * @param int $nameColumnIndex
  7809. * @param int $rangeColumnIndex
  7810. * @param int $promptColumnIndex
  7811. * @return array ['errors' => [], 'checked_rows' => []]
  7812. */
  7813. private function validateImportExcelRows(array $rows, $typeColumnIndex, $nameColumnIndex, $rangeColumnIndex, $promptColumnIndex) {
  7814. $errors = [];
  7815. $checkedRows = [];
  7816. foreach ($rows as $rowIndex => $row) {
  7817. // 数据从第2行开始(表头占第1行)
  7818. $excelRowNo = $rowIndex + 2;
  7819. if (!is_array($row) || $this->isImportExcelRowEmpty($row)) {
  7820. continue;
  7821. }
  7822. $typeRaw = trim((string)($row[$typeColumnIndex] ?? ''));
  7823. $nameRaw = trim((string)($row[$nameColumnIndex] ?? ''));
  7824. $rangeRaw = trim((string)($row[$rangeColumnIndex] ?? ''));
  7825. $promptRaw = trim((string)($row[$promptColumnIndex] ?? ''));
  7826. $missingFields = [];
  7827. if ($typeRaw === '') {
  7828. $missingFields[] = '资产类型';
  7829. }
  7830. if ($nameRaw === '') {
  7831. $missingFields[] = '资产名称';
  7832. }
  7833. if ($rangeRaw === '') {
  7834. $missingFields[] = '使用范围';
  7835. }
  7836. if ($promptRaw === '') {
  7837. $missingFields[] = '参考提示词';
  7838. }
  7839. if (!empty($missingFields)) {
  7840. $errors[] = "第{$excelRowNo}行:" . implode('、', $missingFields) . '不能为空';
  7841. continue;
  7842. }
  7843. // 资产类型校验
  7844. $productType = $this->resolveImportProductType($typeRaw);
  7845. if (!$productType) {
  7846. $errors[] = "第{$excelRowNo}行:资产类型「{$typeRaw}」不正确,仅支持 角色/场景/道具";
  7847. continue;
  7848. }
  7849. // 资产名称去除两边特殊符号
  7850. $productName = $this->normalizeImportProductName($nameRaw);
  7851. if ($productName === '') {
  7852. $errors[] = "第{$excelRowNo}行:资产名称「{$nameRaw}」去除特殊符号后为空";
  7853. continue;
  7854. }
  7855. if (mb_strlen($productName, 'UTF-8') > 64) {
  7856. $errors[] = "第{$excelRowNo}行:资产名称「{$productName}」超过64个字符";
  7857. continue;
  7858. }
  7859. // 解析使用范围(逗号分隔的集数)
  7860. $episodeNumbers = $this->parseImportEpisodeNumbers($rangeRaw);
  7861. if (empty($episodeNumbers)) {
  7862. $errors[] = "第{$excelRowNo}行:使用范围「{$rangeRaw}」格式错误,仅支持数字或逗号分隔的数字";
  7863. continue;
  7864. }
  7865. $checkedRows[] = [
  7866. 'row' => $excelRowNo,
  7867. 'type' => $productType,
  7868. 'product_name' => $productName,
  7869. 'episode_numbers' => $episodeNumbers,
  7870. 'pic_prompt' => $promptRaw,
  7871. ];
  7872. }
  7873. return [
  7874. 'errors' => $errors,
  7875. 'checked_rows' => $checkedRows,
  7876. ];
  7877. }
  7878. /**
  7879. * Excel 资产名称去重:Excel 内部 + 剧本已有关联资产
  7880. *
  7881. * @param array $checkedRows
  7882. * @param array $existingNames 剧本已有关联资产名称集合(name => true)
  7883. * @return array ['valid_rows' => [], 'skipped' => []]
  7884. */
  7885. private function deduplicateImportRows(array $checkedRows, array $existingNames) {
  7886. $seenNames = [];
  7887. $validRows = [];
  7888. $skipped = [];
  7889. foreach ($checkedRows as $row) {
  7890. $nameKey = $row['product_name'];
  7891. $typeText = $this->getImportProductTypeText($row['type']);
  7892. if (isset($seenNames[$nameKey])) {
  7893. $skipped[] = [
  7894. 'row' => $row['row'],
  7895. 'type' => $typeText,
  7896. 'product_name' => $row['product_name'],
  7897. 'reason' => 'Excel中资产名称重复',
  7898. ];
  7899. continue;
  7900. }
  7901. if (isset($existingNames[$nameKey])) {
  7902. $skipped[] = [
  7903. 'row' => $row['row'],
  7904. 'type' => $typeText,
  7905. 'product_name' => $row['product_name'],
  7906. 'reason' => '剧本中已存在同名资产',
  7907. ];
  7908. continue;
  7909. }
  7910. $seenNames[$nameKey] = true;
  7911. $validRows[] = $row;
  7912. }
  7913. return [
  7914. 'valid_rows' => $validRows,
  7915. 'skipped' => $skipped,
  7916. ];
  7917. }
  7918. /**
  7919. * 读取 Excel 文件为二维数组(第一行为表头)
  7920. *
  7921. * @param \Illuminate\Http\UploadedFile $file
  7922. * @return array
  7923. */
  7924. private function readImportExcelRows($file) {
  7925. try {
  7926. $reader = IOFactory::createReaderForFile($file->getRealPath());
  7927. $reader->setReadDataOnly(true);
  7928. $spreadsheet = $reader->load($file->getRealPath());
  7929. $sheet = $spreadsheet->getSheet(0);
  7930. $rows = $sheet->toArray(null, true, true, false);
  7931. $spreadsheet->disconnectWorksheets();
  7932. unset($spreadsheet);
  7933. return $rows;
  7934. } catch (\Exception $e) {
  7935. dLog('anime')->error('Excel文件解析失败', [
  7936. 'error' => $e->getMessage(),
  7937. ]);
  7938. Utils::throwError('20003:Excel文件解析失败,请确认文件格式正确');
  7939. }
  7940. }
  7941. /**
  7942. * 查找 Excel 表头列索引(先精确匹配,再模糊匹配)
  7943. *
  7944. * @param array $headers
  7945. * @param array $exactKeywords
  7946. * @param array $fuzzyKeywords
  7947. * @return int
  7948. */
  7949. private function findImportExcelColumnIndex(array $headers, array $exactKeywords, array $fuzzyKeywords) {
  7950. foreach ($headers as $index => $header) {
  7951. $header = trim((string)$header);
  7952. if ($header === '') {
  7953. continue;
  7954. }
  7955. foreach ($exactKeywords as $keyword) {
  7956. if ($header === $keyword) {
  7957. return $index;
  7958. }
  7959. }
  7960. }
  7961. foreach ($headers as $index => $header) {
  7962. $header = trim((string)$header);
  7963. if ($header === '') {
  7964. continue;
  7965. }
  7966. foreach ($fuzzyKeywords as $keyword) {
  7967. if (mb_strpos($header, $keyword) !== false) {
  7968. return $index;
  7969. }
  7970. }
  7971. }
  7972. return -1;
  7973. }
  7974. /**
  7975. * 判断 Excel 行是否为空行
  7976. *
  7977. * @param array $row
  7978. * @return bool
  7979. */
  7980. private function isImportExcelRowEmpty(array $row) {
  7981. foreach ($row as $cell) {
  7982. if (trim((string)$cell) !== '') {
  7983. return false;
  7984. }
  7985. }
  7986. return true;
  7987. }
  7988. /**
  7989. * 资产名称去除两边特殊符号(与 createProduct 保持一致)
  7990. *
  7991. * @param string $name
  7992. * @return string
  7993. */
  7994. private function normalizeImportProductName($name) {
  7995. $name = trim((string)$name);
  7996. $name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $name);
  7997. if (!$name || preg_match('/^[-—_]+$/u', $name)) {
  7998. return '';
  7999. }
  8000. return $name;
  8001. }
  8002. /**
  8003. * 解析 Excel 中的资产类型
  8004. *
  8005. * @param string $value
  8006. * @return int|null 1=角色 2=场景 3=道具
  8007. */
  8008. private function resolveImportProductType($value) {
  8009. $value = trim((string)$value);
  8010. $map = [
  8011. '角色' => 1,
  8012. '主体' => 1,
  8013. '人物' => 1,
  8014. '1' => 1,
  8015. '场景' => 2,
  8016. '2' => 2,
  8017. '道具' => 3,
  8018. '3' => 3,
  8019. ];
  8020. return isset($map[$value]) ? $map[$value] : null;
  8021. }
  8022. /**
  8023. * 资产类型文案
  8024. *
  8025. * @param int $type
  8026. * @return string
  8027. */
  8028. private function getImportProductTypeText($type) {
  8029. $map = [1 => '角色', 2 => '场景', 3 => '道具'];
  8030. return isset($map[$type]) ? $map[$type] : (string)$type;
  8031. }
  8032. /**
  8033. * 解析使用范围(逗号分隔的集数)
  8034. *
  8035. * @param string $value
  8036. * @return array
  8037. */
  8038. private function parseImportEpisodeNumbers($value) {
  8039. $parts = preg_split('/[,,、\s]+/u', trim((string)$value));
  8040. $episodeNumbers = [];
  8041. foreach ($parts as $part) {
  8042. if ($part === '') {
  8043. continue;
  8044. }
  8045. if (!is_numeric($part)) {
  8046. return [];
  8047. }
  8048. $episodeNumbers[] = (int)$part;
  8049. }
  8050. $episodeNumbers = array_values(array_unique($episodeNumbers));
  8051. sort($episodeNumbers);
  8052. return $episodeNumbers;
  8053. }
  8054. /**
  8055. * 获取剧本已关联资产名称集合(按 createProduct 的名称判断逻辑)
  8056. *
  8057. * @param int $script_id
  8058. * @param int $cpid
  8059. * @return array
  8060. */
  8061. private function getScriptProductNames($script_id, $cpid) {
  8062. $products = DB::table('mp_script_product_mappings as m')
  8063. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8064. ->where('m.script_id', $script_id)
  8065. ->where('p.cpid', $cpid)
  8066. ->where('p.type', 1)
  8067. ->where('p.is_deleted', 0)
  8068. ->get(['p.product_name']);
  8069. $names = [];
  8070. foreach ($products as $product) {
  8071. $name = $this->normalizeImportProductName($product->product_name);
  8072. if ($name !== '') {
  8073. $names[$name] = true;
  8074. }
  8075. }
  8076. return $names;
  8077. }
  8078. /**
  8079. * 获取剧本已关联的资产名称(仅按剧本判重,不区分资产类型)
  8080. *
  8081. * @param int $script_id
  8082. * @return array ['资产名称' => true]
  8083. */
  8084. private function getScriptAssetNames($script_id) {
  8085. $products = DB::table('mp_script_product_mappings as m')
  8086. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8087. ->where('m.script_id', $script_id)
  8088. ->where('p.type', 1)
  8089. ->where('p.is_deleted', 0)
  8090. ->get(['p.product_name']);
  8091. $names = [];
  8092. foreach ($products as $product) {
  8093. $name = $this->normalizeImportProductName($product->product_name);
  8094. if ($name !== '') {
  8095. $names[$name] = true;
  8096. }
  8097. }
  8098. return $names;
  8099. }
  8100. /**
  8101. * 校验并提取本次入参中的新增资产行
  8102. *
  8103. * 规则:
  8104. * - 资产名称为空(或仅剩占位符):跳过
  8105. * - 同一份入参内重名(跨类型):保留最后一条
  8106. * - 与剧本已关联资产同名(跨类型判重,仅限当前剧本):不算新增
  8107. * - 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8108. *
  8109. * @param int $script_id
  8110. * @param mixed $products 入参(数组或 JSON 字符串)
  8111. * @return array [['type' => int, 'product_name' => string, 'pic_prompt' => string, 'episode_numbers' => []]]
  8112. */
  8113. private function extractNewScriptProductRows($script_id, $products) {
  8114. // 兼容 JSON 字符串;无法解析时按"没有新增行"处理,由后续创建逻辑给出原有报错
  8115. if (is_string($products)) {
  8116. $decoded = json_decode($products, true);
  8117. $products = (json_last_error() === JSON_ERROR_NONE) ? $decoded : [];
  8118. }
  8119. if (!is_array($products) || empty($products)) {
  8120. return [];
  8121. }
  8122. $rowMap = [];
  8123. foreach ($products as $productGroup) {
  8124. $type = getProp($productGroup, 'type');
  8125. $content = getProp($productGroup, 'content', []);
  8126. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8127. continue;
  8128. }
  8129. // 获取表头(第一行)并查找关键列的位置
  8130. $headers = $content[0];
  8131. $nameColumnIndex = -1;
  8132. $sequenceColumnIndex = -1;
  8133. $promptColumnIndex = -1;
  8134. $fallbackPromptColumnIndex = -1;
  8135. foreach ($headers as $index => $header) {
  8136. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8137. $nameColumnIndex = $index;
  8138. }
  8139. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8140. $sequenceColumnIndex = $index;
  8141. }
  8142. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8143. $promptColumnIndex = $index;
  8144. } elseif (strpos($header, '提示词') !== false && $fallbackPromptColumnIndex === -1) {
  8145. // 与 Excel 导入保持一致:优先"参考提示词",否则兼容"提示词"列
  8146. $fallbackPromptColumnIndex = $index;
  8147. }
  8148. }
  8149. if ($promptColumnIndex === -1) {
  8150. $promptColumnIndex = $fallbackPromptColumnIndex;
  8151. }
  8152. if ($nameColumnIndex === -1) {
  8153. continue;
  8154. }
  8155. for ($i = 1; $i < count($content); $i++) {
  8156. $row = $content[$i];
  8157. if (empty($row) || !isset($row[$nameColumnIndex])) {
  8158. continue;
  8159. }
  8160. // 处理product_name两边的符号;名称为空或仅剩占位符号则跳过
  8161. $product_name = $this->normalizeImportProductName($row[$nameColumnIndex]);
  8162. if ($product_name === '') {
  8163. continue;
  8164. }
  8165. $pic_prompt = '';
  8166. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8167. $pic_prompt = trim((string)$row[$promptColumnIndex]);
  8168. }
  8169. // 解析使用范围(逗号分隔的序号),为空时由创建逻辑写入默认映射(序号0)
  8170. $sequences = [];
  8171. $sequence_str = ($sequenceColumnIndex >= 0 && isset($row[$sequenceColumnIndex]))
  8172. ? trim((string)$row[$sequenceColumnIndex])
  8173. : '';
  8174. if ($sequence_str !== '') {
  8175. foreach (array_map('trim', explode(',', $sequence_str)) as $part) {
  8176. if (is_numeric($part)) {
  8177. $sequences[] = (int)$part;
  8178. }
  8179. }
  8180. }
  8181. // 跨类型判重,同一份入参内重名保留最后一条
  8182. $rowMap[$product_name] = [
  8183. 'type' => (int)$type,
  8184. 'product_name' => $product_name,
  8185. 'pic_prompt' => $pic_prompt,
  8186. 'episode_numbers' => $sequences,
  8187. ];
  8188. }
  8189. }
  8190. // 与剧本已关联资产判重(仅限当前剧本,跨类型)
  8191. $existingNames = $this->getScriptAssetNames($script_id);
  8192. $newRows = [];
  8193. $emptyPromptNames = [];
  8194. foreach ($rowMap as $name => $row) {
  8195. if (isset($existingNames[$name])) {
  8196. continue;
  8197. }
  8198. if ($row['pic_prompt'] === '') {
  8199. $emptyPromptNames[] = $name;
  8200. continue;
  8201. }
  8202. $newRows[] = $row;
  8203. }
  8204. // 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8205. if (!empty($emptyPromptNames)) {
  8206. Utils::throwError('20003:以下新增资产的参考提示词不能为空:' . implode('、', $emptyPromptNames));
  8207. }
  8208. return $newRows;
  8209. }
  8210. /**
  8211. * 已有关联资产的图片任务处理(参照 saveScriptProducts 的处理方式)
  8212. *
  8213. * - 已有图片任务的资产:收集任务ID,交给轮询
  8214. * - 已有图片且生成成功的资产:跳过
  8215. * - 没有图片的资产:允许自动生成时补建图片任务(需要提示词)
  8216. *
  8217. * @param int $script_id
  8218. * @param string $model
  8219. * @param int $width
  8220. * @param int $height
  8221. * @param bool $auto_generate_images
  8222. * @return array ['product_task_map' => [], 'type_folder_ids' => [], 'has_all_tasks' => bool, 'product_count' => int, 'created_count' => int]
  8223. */
  8224. private function prepareExistingScriptProductTasks($script_id, $model, $width, $height, $auto_generate_images) {
  8225. $productTaskMap = [];
  8226. $typeFolderIds = [];
  8227. $hasAllTasks = true;
  8228. $createdCount = 0;
  8229. $existingMappings = DB::table('mp_script_product_mappings')
  8230. ->where('script_id', $script_id)
  8231. ->get();
  8232. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8233. $productsWithTasks = DB::table('mp_products')
  8234. ->whereIn('id', $productIds)
  8235. ->where('is_deleted', 0)
  8236. ->get();
  8237. foreach ($productsWithTasks as $product) {
  8238. // 收集类型文件夹ID
  8239. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8240. $parentFolder = DB::table('mp_products')
  8241. ->where('id', $product->parent_id)
  8242. ->where('type', 2)
  8243. ->first();
  8244. if ($parentFolder) {
  8245. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8246. }
  8247. }
  8248. // 检查是否有图片生成任务
  8249. if (!empty($product->pic_task_id)) {
  8250. $productTaskMap[$product->id] = $product->pic_task_id;
  8251. } elseif ($product->url && $product->pic_task_status == '生成成功') {
  8252. continue;
  8253. } else {
  8254. // 有资产没有图片
  8255. $hasAllTasks = false;
  8256. }
  8257. }
  8258. // 为没有图片的资产补建图片生成任务
  8259. if (!$hasAllTasks && $auto_generate_images && $productsWithTasks->isNotEmpty()) {
  8260. DB::beginTransaction();
  8261. try {
  8262. foreach ($productsWithTasks as $product) {
  8263. // 跳过已有任务的资产
  8264. if (!empty($product->pic_task_id)) {
  8265. continue;
  8266. }
  8267. // 跳过没有提示词的资产
  8268. if (empty($product->pic_prompt)) {
  8269. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8270. 'product_id' => $product->id,
  8271. 'product_name' => $product->product_name,
  8272. ]);
  8273. continue;
  8274. }
  8275. try {
  8276. $task = $this->aiImageGenerationService->createImageGenerationTask([
  8277. 'prompt' => $product->pic_prompt,
  8278. 'model' => $model,
  8279. 'ref_img_urls' => [],
  8280. 'width' => $width,
  8281. 'height' => $height,
  8282. // 计费锚点(剧本),用于积分明细归属统计
  8283. 'script_id' => $script_id,
  8284. ]);
  8285. $task_id = $task->id;
  8286. if ($task_id) {
  8287. $productTaskMap[$product->id] = $task_id;
  8288. $createdCount++;
  8289. DB::table('mp_products')
  8290. ->where('id', $product->id)
  8291. ->update([
  8292. 'pic_task_id' => $task_id,
  8293. 'pic_task_status' => '生成中',
  8294. 'updated_at' => now(),
  8295. ]);
  8296. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8297. 'product_id' => $product->id,
  8298. 'task_id' => $task_id,
  8299. ]);
  8300. }
  8301. } catch (\Exception $e) {
  8302. dLog('anime')->error('创建资产图片生成任务失败', [
  8303. 'product_id' => $product->id,
  8304. 'error' => $e->getMessage(),
  8305. ]);
  8306. DB::table('mp_products')
  8307. ->where('id', $product->id)
  8308. ->update([
  8309. 'pic_task_status' => '生成失败',
  8310. 'updated_at' => now(),
  8311. ]);
  8312. }
  8313. }
  8314. DB::commit();
  8315. } catch (\Exception $e) {
  8316. DB::rollback();
  8317. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8318. 'script_id' => $script_id,
  8319. 'error' => $e->getMessage(),
  8320. ]);
  8321. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8322. }
  8323. }
  8324. return [
  8325. 'product_task_map' => $productTaskMap,
  8326. 'type_folder_ids' => $typeFolderIds,
  8327. 'has_all_tasks' => $hasAllTasks,
  8328. 'product_count' => count($productIds),
  8329. 'created_count' => $createdCount,
  8330. ];
  8331. }
  8332. /**
  8333. * 保存剧本资产关联关系
  8334. * @param array $data 请求参数
  8335. * @return bool
  8336. */
  8337. public function saveScriptProducts($data) {
  8338. $uid = Site::getUid();
  8339. $cpid = Site::getCpid();
  8340. $script_id = getProp($data, 'script_id');
  8341. $products = getProp($data, 'products', []);
  8342. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  8343. if (!$script_id) {
  8344. Utils::throwError('20003:请提供剧本ID');
  8345. }
  8346. // 验证剧本是否存在
  8347. $script = DB::table('mp_scripts')
  8348. ->where('id', $script_id)
  8349. ->where('is_deleted', 0)
  8350. ->first();
  8351. if (!$script) {
  8352. Utils::throwError('20003:剧本不存在');
  8353. }
  8354. // 处理图片模型
  8355. $model = getProp($data, 'model');
  8356. if (!$model) {
  8357. // 使用默认模型
  8358. $model = 'gpt-image-2';
  8359. }
  8360. // 验证模型是否在可用模型表中
  8361. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8362. Utils::throwError('20003:该模型已不可用,请更换!');
  8363. }
  8364. $ratio = getProp($data, 'ratio', '9:16');
  8365. $resolution = getProp($data, 'resolution', '2k');
  8366. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  8367. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  8368. // 参数验证
  8369. $resolution = strtolower($resolution);
  8370. if (!isset($sizeMap[$resolution])) {
  8371. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  8372. }
  8373. if (!isset($sizeMap[$resolution][$ratio])) {
  8374. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  8375. }
  8376. // 根据 ratio 和 resolution 确定宽高
  8377. $width = $sizeMap[$resolution][$ratio]['width'];
  8378. $height = $sizeMap[$resolution][$ratio]['height'];
  8379. $script_name = $script->script_name ?? 'script_' . $script_id;
  8380. // 先校验并提取本次入参中的新增资产行:
  8381. // 新增行的参考提示词为空时直接报错,不写任何数据、不创建任务中心记录
  8382. $newRows = $this->extractNewScriptProductRows($script_id, $products);
  8383. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  8384. $taskCenterId = $this->createScriptProductTaskCenter(
  8385. $uid,
  8386. $cpid,
  8387. $script_id,
  8388. $products,
  8389. $model,
  8390. $ratio,
  8391. $resolution,
  8392. $auto_generate_images
  8393. );
  8394. // 检查是否已经有该剧本的资产数据
  8395. $existingMappings = DB::table('mp_script_product_mappings')
  8396. ->where('script_id', $script_id)
  8397. ->get();
  8398. // 已有资产且本次没有新增行时,走原有的"已存在"处理;否则走下方创建逻辑
  8399. if ($existingMappings->isNotEmpty() && empty($newRows)) {
  8400. // 已存在资产映射,检查是否所有资产都有图片生成任务
  8401. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8402. // 查询这些资产的图片生成任务状态
  8403. $productsWithTasks = DB::table('mp_products')
  8404. ->whereIn('id', $productIds)
  8405. ->where('is_deleted', 0)
  8406. ->get();
  8407. $productTaskMap = [];
  8408. $typeFolderIds = [];
  8409. $hasAllTasks = true;
  8410. foreach ($productsWithTasks as $product) {
  8411. // 收集类型文件夹ID
  8412. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8413. $parentFolder = DB::table('mp_products')
  8414. ->where('id', $product->parent_id)
  8415. ->where('type', 2)
  8416. ->first();
  8417. if ($parentFolder) {
  8418. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8419. }
  8420. }
  8421. // 检查是否有图片生成任务
  8422. if (!empty($product->pic_task_id)) {
  8423. $productTaskMap[$product->id] = $product->pic_task_id;
  8424. } else if($product->url && $product->pic_task_status == '生成成功') {
  8425. continue;
  8426. } else {
  8427. // 有资产没有图片任务
  8428. $hasAllTasks = false;
  8429. }
  8430. }
  8431. // 如果所有资产都有任务ID,直接轮询返回结果
  8432. if ($hasAllTasks && !empty($productTaskMap)) {
  8433. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  8434. 'script_id' => $script_id,
  8435. 'script_name' => $script_name,
  8436. 'product_count' => count($productTaskMap)
  8437. ]);
  8438. // 直接返回 SSE 流轮询结果
  8439. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8440. }
  8441. // 如果部分资产没有任务ID,只为这些资产创建任务
  8442. if (!$hasAllTasks && $auto_generate_images) {
  8443. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  8444. 'script_id' => $script_id,
  8445. 'script_name' => $script_name
  8446. ]);
  8447. // 开启事务
  8448. DB::beginTransaction();
  8449. try {
  8450. foreach ($productsWithTasks as $product) {
  8451. // 跳过已有任务的资产
  8452. if (!empty($product->pic_task_id)) {
  8453. continue;
  8454. }
  8455. // 跳过没有提示词的资产
  8456. if (empty($product->pic_prompt)) {
  8457. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8458. 'product_id' => $product->id,
  8459. 'product_name' => $product->product_name
  8460. ]);
  8461. continue;
  8462. }
  8463. try {
  8464. // 创建图片生成任务
  8465. $params = [
  8466. 'prompt' => $product->pic_prompt,
  8467. 'model' => $model,
  8468. 'ref_img_urls' => [],
  8469. 'width' => $width,
  8470. 'height' => $height,
  8471. // 计费锚点(剧本),用于积分明细归属统计
  8472. 'script_id' => $script_id,
  8473. ];
  8474. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8475. $task_id = $task->id;
  8476. if ($task_id) {
  8477. $productTaskMap[$product->id] = $task_id;
  8478. // 在事务中更新资产表的任务ID和状态
  8479. DB::table('mp_products')
  8480. ->where('id', $product->id)
  8481. ->update([
  8482. 'pic_task_id' => $task_id,
  8483. 'pic_task_status' => '生成中',
  8484. 'updated_at' => now()
  8485. ]);
  8486. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8487. 'product_id' => $product->id,
  8488. 'task_id' => $task_id
  8489. ]);
  8490. }
  8491. } catch (\Exception $e) {
  8492. dLog('anime')->error('创建资产图片生成任务失败', [
  8493. 'product_id' => $product->id,
  8494. 'error' => $e->getMessage()
  8495. ]);
  8496. // 标记为失败(仍在事务中)
  8497. DB::table('mp_products')
  8498. ->where('id', $product->id)
  8499. ->update([
  8500. 'pic_task_status' => '生成失败',
  8501. 'updated_at' => now()
  8502. ]);
  8503. }
  8504. }
  8505. // 提交事务
  8506. DB::commit();
  8507. // 如果有新创建的任务,返回 SSE 流
  8508. if (!empty($productTaskMap)) {
  8509. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8510. }
  8511. } catch (\Exception $e) {
  8512. // 回滚事务
  8513. DB::rollback();
  8514. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8515. 'script_id' => $script_id,
  8516. 'error' => $e->getMessage()
  8517. ]);
  8518. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8519. }
  8520. }
  8521. // 如果不需要生成图片,返回已存在的信息
  8522. $resultData = [
  8523. 'success' => true,
  8524. 'message' => '剧本资产已存在',
  8525. 'script_id' => $script_id,
  8526. 'script_name' => $script_name,
  8527. 'type_folder_ids' => $typeFolderIds,
  8528. 'existing_products' => count($productIds),
  8529. 'tasks_count' => count($productTaskMap),
  8530. 'task_center_id' => $taskCenterId
  8531. ];
  8532. // 接口已正常完成,更新任务中心状态和结果
  8533. if ($taskCenterId) {
  8534. $this->taskCenterService->updateTask($taskCenterId, [
  8535. 'status' => MpTaskCenter::STATUS_SUCCESS,
  8536. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  8537. 'error_message' => null
  8538. ]);
  8539. }
  8540. return $resultData;
  8541. }
  8542. // 走到这里说明有新行需要创建(或剧本还没有任何资产),保留原有的入参校验报错
  8543. if (empty($newRows)) {
  8544. $decodedProducts = $products;
  8545. if (is_string($decodedProducts)) {
  8546. $decodedProducts = json_decode($decodedProducts, true);
  8547. if (json_last_error() !== JSON_ERROR_NONE) {
  8548. Utils::throwError('20003:产品数据格式错误');
  8549. }
  8550. }
  8551. if (!is_array($decodedProducts) || empty($decodedProducts)) {
  8552. Utils::throwError('20003:产品数据不能为空');
  8553. }
  8554. Utils::throwError('20003:没有有效的产品数据');
  8555. }
  8556. // 仅保留本次新增的资产行,复用下方原有的创建逻辑
  8557. $products = [];
  8558. foreach ($newRows as $newRow) {
  8559. if (!isset($products[$newRow['type']])) {
  8560. $products[$newRow['type']] = [
  8561. 'type' => $newRow['type'],
  8562. 'content' => [['资产名称', '使用范围', '参考提示词']],
  8563. ];
  8564. }
  8565. $products[$newRow['type']]['content'][] = [
  8566. $newRow['product_name'],
  8567. implode(',', $newRow['episode_numbers']),
  8568. $newRow['pic_prompt'],
  8569. ];
  8570. }
  8571. $products = array_values($products);
  8572. // 以下是原有的创建逻辑...
  8573. // 开启事务
  8574. DB::beginTransaction();
  8575. try {
  8576. $now = now();
  8577. $mappingRecords = [];
  8578. $createdProductIds = []; // 记录所有创建的资产ID
  8579. // 获取剧本名称
  8580. $script_name = $script->script_name ?? 'script_' . $script_id;
  8581. // 存储每个类型的根文件夹ID
  8582. $typeFolderIds = [];
  8583. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  8584. foreach ($products as $productGroup) {
  8585. $type = getProp($productGroup, 'type');
  8586. $title = getProp($productGroup, 'title', '');
  8587. $content = getProp($productGroup, 'content', []);
  8588. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8589. continue;
  8590. }
  8591. // 为当前类型获取根文件夹:该剧本已存在则复用,避免重复创建根文件夹
  8592. if (!isset($typeFolderIds[$type])) {
  8593. $folder = DB::table('mp_products')
  8594. ->where('cpid', $cpid)
  8595. ->where('type', 2)
  8596. ->where('product', $type)
  8597. ->where('product_name', $script_name)
  8598. ->where('parent_id', 0)
  8599. ->where('is_deleted', 0)
  8600. ->first();
  8601. if ($folder) {
  8602. $typeFolderIds[$type] = $folder->id;
  8603. } else {
  8604. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  8605. 'user_id' => $uid,
  8606. 'cpid' => $cpid,
  8607. 'type' => 2, // 1.资产 2文件夹
  8608. 'product' => $type, // 1.主体 2.场景 3.道具
  8609. 'parent_id' => 0, // 根文件夹,parent_id=0
  8610. 'level' => 1, // 第一层级
  8611. 'product_name' => $script_name,
  8612. 'sort_order' => time() + $type,
  8613. 'is_deleted' => 0,
  8614. 'created_at' => $now,
  8615. 'updated_at' => $now
  8616. ]);
  8617. }
  8618. }
  8619. $folder_id = $typeFolderIds[$type];
  8620. // 获取表头(第一行)并查找关键列的位置
  8621. $headers = $content[0];
  8622. $nameColumnIndex = -1; // 资产名称列索引
  8623. $sequenceColumnIndex = -1; // 使用范围列索引
  8624. $promptColumnIndex = -1; // 参考提示词列索引
  8625. foreach ($headers as $index => $header) {
  8626. // 查找"资产名称"列
  8627. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8628. $nameColumnIndex = $index;
  8629. }
  8630. // 查找"使用范围"列
  8631. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8632. $sequenceColumnIndex = $index;
  8633. }
  8634. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  8635. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8636. $promptColumnIndex = $index;
  8637. }
  8638. }
  8639. // 验证必要的列是否都找到了
  8640. if ($nameColumnIndex === -1) {
  8641. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  8642. continue;
  8643. }
  8644. if ($sequenceColumnIndex === -1) {
  8645. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  8646. continue;
  8647. }
  8648. // 跳过表头,解析每一行数据
  8649. for ($i = 1; $i < count($content); $i++) {
  8650. $row = $content[$i];
  8651. // 确保行数据有效
  8652. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  8653. continue;
  8654. }
  8655. // 根据动态查找的列索引提取数据
  8656. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  8657. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  8658. $pic_prompt = '';
  8659. // 提取参考提示词(如果找到了该列)
  8660. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8661. $pic_prompt = trim($row[$promptColumnIndex]);
  8662. }
  8663. // 解析使用范围(逗号分隔的序号)
  8664. $sequences = [];
  8665. if (!empty($sequence_str)) {
  8666. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  8667. foreach ($sequenceParts as $part) {
  8668. if (is_numeric($part)) {
  8669. $sequences[] = (int)$part;
  8670. }
  8671. }
  8672. }
  8673. if (empty($product_name)) {
  8674. continue;
  8675. }
  8676. // 处理product_name两边的符号
  8677. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8678. // 如果名称不存在或仅剩占位符号,则跳过
  8679. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  8680. dLog('anime')->warning('资产名称无效,跳过保存', [
  8681. 'script_id' => $script_id,
  8682. 'type' => $type,
  8683. 'product_name' => $product_name
  8684. ]);
  8685. continue;
  8686. }
  8687. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  8688. $product_id = DB::table('mp_products')->insertGetId([
  8689. 'product_name' => $product_name,
  8690. 'type' => 1, // 1=资产 2.文件夹
  8691. 'product' => $type, // 1=角色, 2=场景, 3=道具
  8692. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  8693. 'level' => 2, // 第二层级
  8694. 'pic_prompt' => $pic_prompt,
  8695. 'user_id' => $uid,
  8696. 'cpid' => $cpid,
  8697. 'sort_order' => time(),
  8698. 'is_deleted' => 0,
  8699. 'created_at' => $now,
  8700. 'updated_at' => $now,
  8701. ]);
  8702. // 记录创建的资产ID
  8703. $createdProductIds[] = $product_id;
  8704. // 为每个序号创建映射记录
  8705. if (!empty($sequences)) {
  8706. foreach ($sequences as $sequence) {
  8707. $mappingRecords[] = [
  8708. 'script_id' => $script_id,
  8709. 'product_id' => $product_id,
  8710. 'episode_number' => $sequence,
  8711. 'created_at' => $now,
  8712. 'updated_at' => $now,
  8713. ];
  8714. }
  8715. } else {
  8716. // 如果没有指定序号,创建一个默认映射(序号为0)
  8717. $mappingRecords[] = [
  8718. 'script_id' => $script_id,
  8719. 'product_id' => $product_id,
  8720. 'episode_number' => 0,
  8721. 'created_at' => $now,
  8722. 'updated_at' => $now,
  8723. ];
  8724. }
  8725. }
  8726. }
  8727. if (empty($mappingRecords)) {
  8728. Utils::throwError('20003:没有有效的产品数据');
  8729. }
  8730. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  8731. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  8732. // 剧本已有资产,同步更新is_products标记
  8733. DB::table('mp_scripts')->where('id', $script_id)->update([
  8734. 'is_products' => 1,
  8735. 'updated_at' => $now
  8736. ]);
  8737. // 如果需要自动生成图片,在事务中创建图片生成任务
  8738. $productTaskMap = [];
  8739. if ($auto_generate_images && !empty($createdProductIds)) {
  8740. // 查询所有创建的资产
  8741. $productsToGenerate = DB::table('mp_products')
  8742. ->whereIn('id', $createdProductIds)
  8743. ->where('is_deleted', 0)
  8744. ->get();
  8745. foreach ($productsToGenerate as $product) {
  8746. if (empty($product->pic_prompt)) {
  8747. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8748. 'product_id' => $product->id,
  8749. 'product_name' => $product->product_name
  8750. ]);
  8751. continue;
  8752. }
  8753. try {
  8754. // 创建图片生成任务
  8755. $params = [
  8756. 'prompt' => $product->pic_prompt,
  8757. 'model' => $model,
  8758. 'ref_img_urls' => [],
  8759. 'width' => $width,
  8760. 'height' => $height,
  8761. // 计费锚点(剧本),用于积分明细归属统计
  8762. 'script_id' => $script_id,
  8763. ];
  8764. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8765. $task_id = $task->id;
  8766. if ($task_id) {
  8767. $productTaskMap[$product->id] = $task_id;
  8768. // 在事务中更新资产表的任务ID和状态
  8769. DB::table('mp_products')
  8770. ->where('id', $product->id)
  8771. ->update([
  8772. 'pic_task_id' => $task_id,
  8773. 'pic_task_status' => '生成中',
  8774. 'updated_at' => now()
  8775. ]);
  8776. dLog('anime')->info('创建资产图片生成任务', [
  8777. 'product_id' => $product->id,
  8778. 'task_id' => $task_id
  8779. ]);
  8780. }
  8781. } catch (\Exception $e) {
  8782. dLog('anime')->error('创建资产图片生成任务失败', [
  8783. 'product_id' => $product->id,
  8784. 'error' => $e->getMessage()
  8785. ]);
  8786. // 标记为失败(仍在事务中)
  8787. DB::table('mp_products')
  8788. ->where('id', $product->id)
  8789. ->update([
  8790. 'pic_task_status' => '生成失败',
  8791. 'updated_at' => now()
  8792. ]);
  8793. }
  8794. }
  8795. }
  8796. // 提交事务
  8797. DB::commit();
  8798. // 本次新增资产创建的图片任务
  8799. $createdTaskMap = $productTaskMap;
  8800. } catch (\Exception $e) {
  8801. // 回滚事务
  8802. DB::rollback();
  8803. // 更新任务中心状态为失败
  8804. if (!empty($taskCenterId)) {
  8805. $this->taskCenterService->updateTask($taskCenterId, [
  8806. 'status' => MpTaskCenter::STATUS_FAILED,
  8807. 'error_message' => $e->getMessage()
  8808. ]);
  8809. }
  8810. // 记录错误日志
  8811. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  8812. 'script_id' => $script_id,
  8813. 'error' => $e->getMessage(),
  8814. 'trace' => $e->getTraceAsString()
  8815. ]);
  8816. // 统一使用 Utils::throwError 抛出错误
  8817. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  8818. }
  8819. // 落库成功后统一处理图片任务:
  8820. // 1) 本次新增资产的图片任务已在上方事务中创建
  8821. // 2) 剧本内已存在但缺图的资产在此补建,并与新增资产的任务一并收集为待轮询任务
  8822. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  8823. $script_id,
  8824. $model,
  8825. $width,
  8826. $height,
  8827. $auto_generate_images
  8828. );
  8829. $productTaskMap = $existingTaskInfo['product_task_map'];
  8830. // 创建阶段解析到的类型根文件夹优先
  8831. $typeFolderIds = $typeFolderIds + $existingTaskInfo['type_folder_ids'];
  8832. // 保存结果(SSE 的 init / complete 事件会携带该结构)
  8833. $resultData = [
  8834. 'success' => true,
  8835. 'message' => '保存完成',
  8836. 'script_id' => $script_id,
  8837. 'script_name' => $script_name,
  8838. 'type_folder_ids' => $typeFolderIds,
  8839. 'inserted_count' => $insertedCount,
  8840. 'total_records' => count($mappingRecords),
  8841. 'created_products' => count($createdProductIds),
  8842. 'pending_tasks_count' => count($productTaskMap),
  8843. 'image_tasks_created' => count($createdTaskMap) + $existingTaskInfo['created_count'],
  8844. 'task_center_id' => $taskCenterId,
  8845. ];
  8846. // 有待完成的图片任务:返回 SSE 轮询流(事务外轮询)
  8847. if ($auto_generate_images && !empty($productTaskMap)) {
  8848. return $this->pollProductImageTasks(
  8849. $script_id,
  8850. $script_name,
  8851. $productTaskMap,
  8852. $typeFolderIds,
  8853. $taskCenterId,
  8854. ['import_result' => $resultData],
  8855. ['import_result' => $resultData]
  8856. );
  8857. }
  8858. // 没有需要轮询的任务:通过 SSE complete 事件返回保存结果
  8859. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  8860. }
  8861. /**
  8862. * 根据入参创建或复用任务中心记录
  8863. *
  8864. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  8865. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  8866. * 避免生成重复任务。
  8867. *
  8868. * @param int|string $uid
  8869. * @param int|string $cpid
  8870. * @param int|string $script_id
  8871. * @param mixed $products
  8872. * @param string $model
  8873. * @param string $ratio
  8874. * @param string $resolution
  8875. * @param mixed $auto_generate_images
  8876. * @return int 任务中心ID
  8877. */
  8878. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  8879. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  8880. if (is_string($products)) {
  8881. $decoded = json_decode($products, true);
  8882. if (json_last_error() === JSON_ERROR_NONE) {
  8883. $products = $decoded;
  8884. }
  8885. }
  8886. $params = [
  8887. 'script_id' => (int)$script_id,
  8888. 'products' => $products,
  8889. 'model' => $model,
  8890. 'ratio' => $ratio,
  8891. 'resolution' => $resolution,
  8892. 'auto_generate_images' => (bool)$auto_generate_images,
  8893. ];
  8894. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  8895. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  8896. $existing = DB::table('mp_task_center')
  8897. ->where('uid', (int)$uid)
  8898. ->where('cpid', (int)$cpid)
  8899. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8900. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  8901. ->where('params_md5', $paramsMd5)
  8902. ->orderBy('id', 'desc')
  8903. ->first();
  8904. if ($existing) {
  8905. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  8906. 'script_id' => $script_id,
  8907. 'task_center_id' => $existing->id,
  8908. 'params_md5' => $paramsMd5,
  8909. ]);
  8910. return (int)$existing->id;
  8911. }
  8912. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  8913. $now = date('Y-m-d H:i:s');
  8914. DB::table('mp_task_center')->insertOrIgnore([
  8915. 'uid' => (int)$uid,
  8916. 'cpid' => (int)$cpid,
  8917. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  8918. 'title' => '剧本资产图片生成',
  8919. 'ref_task_id' => 0,
  8920. 'status' => MpTaskCenter::STATUS_PROCESSING,
  8921. 'result' => null,
  8922. 'error_message' => null,
  8923. 'prompt' => null,
  8924. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  8925. 'params_md5' => $paramsMd5,
  8926. 'created_at' => $now,
  8927. 'updated_at' => $now,
  8928. ]);
  8929. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  8930. $taskId = (int)DB::table('mp_task_center')
  8931. ->where('uid', (int)$uid)
  8932. ->where('cpid', (int)$cpid)
  8933. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8934. ->where('params_md5', $paramsMd5)
  8935. ->orderBy('id', 'desc')
  8936. ->value('id');
  8937. dLog('anime')->info('创建任务中心记录', [
  8938. 'script_id' => $script_id,
  8939. 'task_center_id' => $taskId,
  8940. 'params_md5' => $paramsMd5,
  8941. ]);
  8942. return $taskId;
  8943. }
  8944. /**
  8945. * 任务结束时更新任务中心记录的状态和结果
  8946. *
  8947. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  8948. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  8949. *
  8950. * @param int|null $taskCenterId
  8951. * @param array $resultData 接口返回结果数组
  8952. * @param bool $timeout 是否超时未完成
  8953. */
  8954. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  8955. if (!$taskCenterId) {
  8956. return;
  8957. }
  8958. $stats = $resultData['stats'] ?? [];
  8959. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  8960. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  8961. $failedCount = $completedCount - $successCount;
  8962. // 与接口返回给客户端的结果保持一致
  8963. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  8964. if ($timeout) {
  8965. $this->taskCenterService->updateTask((int)$taskCenterId, [
  8966. 'status' => MpTaskCenter::STATUS_FAILED,
  8967. 'result' => $result,
  8968. 'error_message' => '部分任务超时,请稍后查看结果',
  8969. ]);
  8970. return;
  8971. }
  8972. $this->taskCenterService->updateTask((int)$taskCenterId, [
  8973. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  8974. 'result' => $result,
  8975. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  8976. ]);
  8977. }
  8978. /**
  8979. * 批量为剧本资产生成图片
  8980. *
  8981. * @param array $data 请求参数
  8982. * @return \Generator 返回 SSE 流
  8983. */
  8984. public function batchGenerateProductImages($data) {
  8985. $script_id = getProp($data, 'script_id');
  8986. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  8987. if (!$script_id) {
  8988. Utils::throwError('20003:请提供剧本ID');
  8989. }
  8990. // 验证剧本是否存在
  8991. $script = DB::table('mp_scripts')
  8992. ->where('id', $script_id)
  8993. ->where('is_deleted', 0)
  8994. ->first();
  8995. if (!$script) {
  8996. Utils::throwError('20003:剧本不存在');
  8997. }
  8998. $script_name = $script->script_name ?? 'script_' . $script_id;
  8999. // 获取需要生成图片的所有资产
  9000. $products = DB::table('mp_products')
  9001. ->whereIn('parent_id', array_values($type_folder_ids))
  9002. ->where('is_deleted', 0)
  9003. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  9004. ->get();
  9005. if ($products->isEmpty()) {
  9006. Utils::throwError('20003:没有找到需要生成图片的资产');
  9007. }
  9008. // 默认参数
  9009. $model = 'gpt-image-2';
  9010. $width = 1600;
  9011. $height = 2848;
  9012. // 开始为每个资产创建图片生成任务
  9013. $taskIds = [];
  9014. $productTaskMap = []; // 资产ID到任务ID的映射
  9015. foreach ($products as $product) {
  9016. if (empty($product->pic_prompt)) {
  9017. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  9018. continue;
  9019. }
  9020. try {
  9021. // 创建图片生成任务
  9022. $params = [
  9023. 'prompt' => $product->pic_prompt,
  9024. 'model' => $model,
  9025. 'ref_img_urls' => [],
  9026. 'width' => $width,
  9027. 'height' => $height,
  9028. // 计费锚点(剧本),用于积分明细归属统计
  9029. 'script_id' => $script_id,
  9030. ];
  9031. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9032. $task_id = $task->id;
  9033. if ($task_id) {
  9034. $taskIds[] = $task_id;
  9035. $productTaskMap[$product->id] = $task_id;
  9036. // 更新资产表的任务ID和状态
  9037. DB::table('mp_products')
  9038. ->where('id', $product->id)
  9039. ->update([
  9040. 'pic_task_id' => $task_id,
  9041. 'pic_task_status' => '生成中',
  9042. 'updated_at' => now()
  9043. ]);
  9044. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  9045. }
  9046. } catch (\Exception $e) {
  9047. dLog('anime')->error('创建资产图片生成任务失败', [
  9048. 'product_id' => $product->id,
  9049. 'error' => $e->getMessage()
  9050. ]);
  9051. // 标记为失败
  9052. DB::table('mp_products')
  9053. ->where('id', $product->id)
  9054. ->update([
  9055. 'pic_task_status' => '生成失败',
  9056. 'updated_at' => now()
  9057. ]);
  9058. }
  9059. }
  9060. if (empty($taskIds)) {
  9061. Utils::throwError('20003:没有成功创建任何图片生成任务');
  9062. }
  9063. // 返回 SSE 流
  9064. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  9065. }
  9066. /**
  9067. * 无需轮询时的 SSE 返回:直接通过 complete 事件返回导入结果
  9068. *
  9069. * @param int $script_id
  9070. * @param string $script_name
  9071. * @param array $resultData 导入结果(原普通 JSON 的 data 内容)
  9072. * @param array $type_folder_ids
  9073. * @param int|null $taskCenterId
  9074. * @return \Generator
  9075. */
  9076. private function streamImportComplete($script_id, $script_name, array $resultData, $type_folder_ids, $taskCenterId = null) {
  9077. if ($taskCenterId) {
  9078. $initResponse = [
  9079. 'type' => 'init',
  9080. 'script_id' => $script_id,
  9081. 'script_name' => $script_name,
  9082. 'timestamp' => date('Y-m-d H:i:s'),
  9083. 'task_center_id' => (int)$taskCenterId,
  9084. 'import_result' => $resultData,
  9085. ];
  9086. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9087. }
  9088. $stats = $this->collectScriptProductStats($script_id);
  9089. $response = [
  9090. 'type' => 'complete',
  9091. 'script_id' => $script_id,
  9092. 'script_name' => $script_name,
  9093. 'stats' => $stats,
  9094. 'timestamp' => date('Y-m-d H:i:s'),
  9095. 'import_result' => $resultData,
  9096. ];
  9097. if ($taskCenterId) {
  9098. $response['task_center_id'] = (int)$taskCenterId;
  9099. }
  9100. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9101. // 更新任务中心状态和结果
  9102. $this->finishScriptProductTask($taskCenterId, $response);
  9103. }
  9104. /**
  9105. * 统计剧本资产的图片生成状态(仅按 mp_products 当前状态统计,不驱动任务)
  9106. *
  9107. * @param int $script_id
  9108. * @return array
  9109. */
  9110. private function collectScriptProductStats($script_id) {
  9111. $stats = [
  9112. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9113. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9114. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9115. ];
  9116. $typeNames = [1 => 'roles', 2 => 'scenes', 3 => 'props'];
  9117. $productIds = DB::table('mp_script_product_mappings')
  9118. ->where('script_id', $script_id)
  9119. ->pluck('product_id')
  9120. ->unique()
  9121. ->toArray();
  9122. if (empty($productIds)) {
  9123. return [];
  9124. }
  9125. $products = DB::table('mp_products')
  9126. ->whereIn('id', $productIds)
  9127. ->where('is_deleted', 0)
  9128. ->get();
  9129. foreach ($products as $product) {
  9130. $typeName = $typeNames[$product->product] ?? 'unknown';
  9131. if (!isset($stats[$typeName])) {
  9132. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9133. }
  9134. $stats[$typeName]['total']++;
  9135. if ($product->pic_task_status === '生成成功') {
  9136. $stats[$typeName]['success']++;
  9137. $stats[$typeName]['completed']++;
  9138. } elseif ($product->pic_task_status === '生成失败') {
  9139. $stats[$typeName]['completed']++;
  9140. }
  9141. }
  9142. foreach ($stats as $typeName => $stat) {
  9143. if ($stat['total'] === 0) {
  9144. unset($stats[$typeName]);
  9145. }
  9146. }
  9147. return $stats;
  9148. }
  9149. /**
  9150. * 轮询资产图片生成任务状态(SSE流式返回)
  9151. * 只通过查询数据库获取任务状态,不主动调用API
  9152. *
  9153. * @param int $script_id 剧本ID
  9154. * @param string $script_name 剧本名称
  9155. * @param array $productTaskMap 资产ID到任务ID的映射
  9156. * @param array $type_folder_ids 类型文件夹ID映射
  9157. * @param int|null $taskCenterId 任务中心ID
  9158. * @param array $initExtra 追加到 init 事件中的额外数据
  9159. * @param array $completeExtra 追加到 complete、timeout 事件中的额外数据
  9160. * @return \Generator
  9161. */
  9162. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null, array $initExtra = [], array $completeExtra = []) {
  9163. $startTime = time();
  9164. $timeout = 1800; // 30分钟超时
  9165. $pollInterval = 10; // 10秒轮询一次
  9166. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  9167. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  9168. if ($taskCenterId) {
  9169. $initResponse = array_merge([
  9170. 'type' => 'init',
  9171. 'script_id' => $script_id,
  9172. 'script_name' => $script_name,
  9173. 'timestamp' => date('Y-m-d H:i:s'),
  9174. 'task_center_id' => (int)$taskCenterId,
  9175. ], $initExtra);
  9176. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9177. }
  9178. // 定义类型名称映射
  9179. $typeNames = [
  9180. 1 => 'roles', // 角色
  9181. 2 => 'scenes', // 场景
  9182. 3 => 'props' // 道具
  9183. ];
  9184. while (time() - $startTime < $timeout) {
  9185. sleep($pollInterval);
  9186. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  9187. $mappings = DB::table('mp_script_product_mappings')
  9188. ->where('script_id', $script_id)
  9189. ->pluck('product_id')
  9190. ->unique()
  9191. ->toArray();
  9192. if (empty($mappings)) {
  9193. dLog('anime')->warning('该剧本没有关联的资产', [
  9194. 'script_id' => $script_id,
  9195. 'script_name' => $script_name
  9196. ]);
  9197. break;
  9198. }
  9199. // 查询所有资产的当前状态
  9200. $products = DB::table('mp_products')
  9201. ->whereIn('id', $mappings)
  9202. ->where('is_deleted', 0)
  9203. ->get();
  9204. // 统计各类型的状态(使用类型名称作为键名)
  9205. $stats = [
  9206. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  9207. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  9208. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  9209. ];
  9210. $allCompleted = true;
  9211. $hasStatusChange = false;
  9212. foreach ($products as $product) {
  9213. $type = $product->product;
  9214. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  9215. // 如果类型名称不在 stats 中,初始化
  9216. if (!isset($stats[$typeName])) {
  9217. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9218. }
  9219. $stats[$typeName]['total']++;
  9220. $task_id = $product->pic_task_id;
  9221. $currentStatus = $product->pic_task_status;
  9222. // 检查状态是否有变化
  9223. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  9224. $hasStatusChange = true;
  9225. $lastStatus[$product->id] = $currentStatus;
  9226. }
  9227. // 如果是生成中,查询任务表状态
  9228. if ($currentStatus === '生成中' && $task_id) {
  9229. // 只查询数据库,不调用API
  9230. $task = DB::table('mp_generate_pic_tasks')
  9231. ->where('id', $task_id)
  9232. ->first();
  9233. if ($task) {
  9234. // 检查任务状态
  9235. if ($task->status === 'success' && $task->result_url) {
  9236. // 解析图片URL
  9237. $result_urls = $task->result_url;
  9238. if (is_string($result_urls)) {
  9239. $result_urls = json_decode($result_urls, true);
  9240. }
  9241. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  9242. // 更新资产表状态
  9243. DB::table('mp_products')
  9244. ->where('id', $product->id)
  9245. ->update([
  9246. 'pic_task_status' => '生成成功',
  9247. 'url' => $img_url,
  9248. 'updated_at' => now()
  9249. ]);
  9250. $stats[$typeName]['success']++;
  9251. $stats[$typeName]['completed']++;
  9252. $hasStatusChange = true;
  9253. dLog('anime')->info('资产图片生成成功', [
  9254. 'product_id' => $product->id,
  9255. 'task_id' => $task_id,
  9256. 'img_url' => $img_url
  9257. ]);
  9258. } elseif ($task->status === 'failed') {
  9259. // 更新资产表状态
  9260. DB::table('mp_products')
  9261. ->where('id', $product->id)
  9262. ->update([
  9263. 'pic_task_status' => '生成失败',
  9264. 'updated_at' => now()
  9265. ]);
  9266. $stats[$typeName]['completed']++;
  9267. $hasStatusChange = true;
  9268. dLog('anime')->warning('资产图片生成失败', [
  9269. 'product_id' => $product->id,
  9270. 'task_id' => $task_id,
  9271. 'error' => $task->error_message ?? '未知错误'
  9272. ]);
  9273. } else {
  9274. // 任务还在处理中
  9275. $allCompleted = false;
  9276. }
  9277. } else {
  9278. // 任务不存在,标记为失败
  9279. DB::table('mp_products')
  9280. ->where('id', $product->id)
  9281. ->update([
  9282. 'pic_task_status' => '生成失败',
  9283. 'updated_at' => now()
  9284. ]);
  9285. $stats[$typeName]['completed']++;
  9286. $hasStatusChange = true;
  9287. dLog('anime')->error('图片生成任务不存在', [
  9288. 'product_id' => $product->id,
  9289. 'task_id' => $task_id
  9290. ]);
  9291. }
  9292. } elseif ($currentStatus === '生成成功') {
  9293. $stats[$typeName]['success']++;
  9294. $stats[$typeName]['completed']++;
  9295. } elseif ($currentStatus === '生成失败') {
  9296. $stats[$typeName]['completed']++;
  9297. } else {
  9298. // 其他状态也认为未完成
  9299. $allCompleted = false;
  9300. }
  9301. }
  9302. // 移除没有数据的类型(total=0)
  9303. foreach ($stats as $typeName => $stat) {
  9304. if ($stat['total'] === 0) {
  9305. unset($stats[$typeName]);
  9306. }
  9307. }
  9308. // 如果有状态变化,发送 SSE 更新
  9309. if ($hasStatusChange) {
  9310. $eventType = $allCompleted ? 'complete' : 'update';
  9311. $response = [
  9312. 'type' => $eventType,
  9313. 'script_id' => $script_id,
  9314. 'script_name' => $script_name,
  9315. 'stats' => $stats,
  9316. 'timestamp' => date('Y-m-d H:i:s')
  9317. ];
  9318. if ($taskCenterId) {
  9319. $response['task_center_id'] = $taskCenterId;
  9320. }
  9321. if ($eventType === 'complete') {
  9322. $response = array_merge($response, $completeExtra);
  9323. }
  9324. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9325. dLog('anime')->info('SSE更新', [
  9326. 'event_type' => $eventType,
  9327. 'script_id' => $script_id,
  9328. 'script_name' => $script_name,
  9329. 'stats' => $stats
  9330. ]);
  9331. if ($allCompleted) {
  9332. dLog('anime')->info('所有资产图片生成任务已完成', [
  9333. 'script_id' => $script_id,
  9334. 'script_name' => $script_name,
  9335. 'stats' => $stats
  9336. ]);
  9337. // 全部任务完成,更新任务中心状态和结果
  9338. $this->finishScriptProductTask($taskCenterId, $response);
  9339. break;
  9340. }
  9341. }
  9342. }
  9343. // 超时处理
  9344. if (time() - $startTime >= $timeout && !$allCompleted) {
  9345. $response = [
  9346. 'type' => 'timeout',
  9347. 'message' => '部分任务超时,请稍后查看结果',
  9348. 'script_id' => $script_id,
  9349. 'script_name' => $script_name,
  9350. 'timestamp' => date('Y-m-d H:i:s')
  9351. ];
  9352. if ($taskCenterId) {
  9353. $response['task_center_id'] = $taskCenterId;
  9354. }
  9355. $response = array_merge($response, $completeExtra);
  9356. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9357. dLog('anime')->warning('资产图片生成任务超时', [
  9358. 'script_id' => $script_id,
  9359. 'script_name' => $script_name,
  9360. 'timeout' => $timeout
  9361. ]);
  9362. // 超时未完成,更新任务中心状态和结果
  9363. $this->finishScriptProductTask($taskCenterId, $response, true);
  9364. }
  9365. }
  9366. /**
  9367. * 定时任务:检查产品图片生成任务状态并更新产品记录
  9368. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  9369. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  9370. *
  9371. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  9372. */
  9373. public function checkProductPicTasks() {
  9374. // 查询所有生成中的产品图片任务
  9375. $products = DB::table('mp_products')
  9376. ->whereNotNull('pic_task_id')
  9377. ->where('pic_task_status', '生成中')
  9378. ->where('is_deleted', 0)
  9379. ->get();
  9380. $stats = [
  9381. 'total' => $products->count(),
  9382. 'success' => 0,
  9383. 'failed' => 0,
  9384. 'pending' => 0,
  9385. ];
  9386. foreach ($products as $product) {
  9387. try {
  9388. $task_id = $product->pic_task_id;
  9389. // 通过 pic_task_id 查询图片生成任务结果
  9390. $task = DB::table('mp_generate_pic_tasks')
  9391. ->where('id', $task_id)
  9392. ->first();
  9393. if ($task) {
  9394. if ($task->status === 'success' && $task->result_url) {
  9395. // 解析图片URL
  9396. $result_urls = $task->result_url;
  9397. if (is_string($result_urls)) {
  9398. $result_urls = json_decode($result_urls, true);
  9399. }
  9400. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  9401. // 更新资产表状态
  9402. DB::table('mp_products')
  9403. ->where('id', $product->id)
  9404. ->update([
  9405. 'pic_task_status' => '生成成功',
  9406. 'url' => $img_url,
  9407. 'updated_at' => now()
  9408. ]);
  9409. $stats['success']++;
  9410. dLog('anime')->info('资产图片生成成功', [
  9411. 'product_id' => $product->id,
  9412. 'task_id' => $task_id,
  9413. 'img_url' => $img_url
  9414. ]);
  9415. } elseif ($task->status === 'failed') {
  9416. // 更新资产表状态
  9417. DB::table('mp_products')
  9418. ->where('id', $product->id)
  9419. ->update([
  9420. 'pic_task_status' => '生成失败',
  9421. 'updated_at' => now()
  9422. ]);
  9423. $stats['failed']++;
  9424. dLog('anime')->warning('资产图片生成失败', [
  9425. 'product_id' => $product->id,
  9426. 'task_id' => $task_id,
  9427. 'error' => $task->error_message ?? '未知错误'
  9428. ]);
  9429. } else {
  9430. // 任务还在处理中
  9431. $stats['pending']++;
  9432. }
  9433. } else {
  9434. // 任务不存在,标记为失败
  9435. DB::table('mp_products')
  9436. ->where('id', $product->id)
  9437. ->update([
  9438. 'pic_task_status' => '生成失败',
  9439. 'updated_at' => now()
  9440. ]);
  9441. $stats['failed']++;
  9442. dLog('anime')->error('图片生成任务不存在', [
  9443. 'product_id' => $product->id,
  9444. 'task_id' => $task_id
  9445. ]);
  9446. }
  9447. } catch (\Exception $e) {
  9448. dLog('anime')->error('检查产品图片生成任务异常', [
  9449. 'product_id' => $product->id,
  9450. 'task_id' => $product->pic_task_id ?? null,
  9451. 'error' => $e->getMessage()
  9452. ]);
  9453. }
  9454. }
  9455. return $stats;
  9456. }
  9457. /**
  9458. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  9459. *
  9460. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  9461. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  9462. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  9463. *
  9464. * @return int 更新的任务中心记录数
  9465. */
  9466. public function checkSaveScriptProductTaskCenters() {
  9467. $updated = 0;
  9468. // 只扫描尚未结束的 saveScriptProducts 任务
  9469. $tasks = DB::table('mp_task_center')
  9470. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9471. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  9472. ->orderBy('id', 'desc')
  9473. ->limit(500)
  9474. ->get();
  9475. // 与 pollProductImageTasks 保持一致的类型名称映射
  9476. $typeNames = [
  9477. 1 => 'roles', // 角色
  9478. 2 => 'scenes', // 场景
  9479. 3 => 'props', // 道具
  9480. ];
  9481. foreach ($tasks as $task) {
  9482. try {
  9483. $taskParams = json_decode((string)$task->params, true);
  9484. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  9485. if (!$script_id) {
  9486. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  9487. 'task_center_id' => $task->id,
  9488. ]);
  9489. continue;
  9490. }
  9491. // 获取该剧本关联的全部资产ID
  9492. $productIds = DB::table('mp_script_product_mappings')
  9493. ->where('script_id', $script_id)
  9494. ->pluck('product_id')
  9495. ->unique()
  9496. ->toArray();
  9497. if (empty($productIds)) {
  9498. // 剧本没有关联资产,不视为完成,等待下一次检查
  9499. continue;
  9500. }
  9501. $products = DB::table('mp_products')
  9502. ->whereIn('id', $productIds)
  9503. ->where('is_deleted', 0)
  9504. ->get();
  9505. $stats = [];
  9506. $allCompleted = true;
  9507. foreach ($products as $product) {
  9508. $typeName = $typeNames[$product->product] ?? 'unknown';
  9509. if (!isset($stats[$typeName])) {
  9510. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9511. }
  9512. $stats[$typeName]['total']++;
  9513. if ($product->pic_task_status === '生成成功') {
  9514. $stats[$typeName]['success']++;
  9515. $stats[$typeName]['completed']++;
  9516. } elseif ($product->pic_task_status === '生成失败') {
  9517. $stats[$typeName]['completed']++;
  9518. } else {
  9519. // 仍有资产在生成中或未生成,任务未完成
  9520. $allCompleted = false;
  9521. }
  9522. }
  9523. if (!$allCompleted) {
  9524. continue;
  9525. }
  9526. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  9527. $script = DB::table('mp_scripts')
  9528. ->where('id', $script_id)
  9529. ->where('is_deleted', 0)
  9530. ->first();
  9531. $script_name = $script->script_name ?? 'script_' . $script_id;
  9532. $this->finishScriptProductTask($task->id, [
  9533. 'type' => 'complete',
  9534. 'script_id' => $script_id,
  9535. 'script_name' => $script_name,
  9536. 'stats' => $stats,
  9537. 'timestamp' => date('Y-m-d H:i:s'),
  9538. 'task_center_id' => (int)$task->id,
  9539. ]);
  9540. $updated++;
  9541. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  9542. 'task_center_id' => $task->id,
  9543. 'script_id' => $script_id,
  9544. 'stats' => $stats,
  9545. ]);
  9546. } catch (\Exception $e) {
  9547. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  9548. 'task_center_id' => $task->id,
  9549. 'error' => $e->getMessage(),
  9550. ]);
  9551. }
  9552. }
  9553. return $updated;
  9554. }
  9555. /**
  9556. * 获取剧本关联的资产列表
  9557. * @param array $data 请求参数
  9558. * @return array
  9559. */
  9560. public function getScriptProducts($data) {
  9561. $uid = Site::getUid();
  9562. $cpid = Site::getCpid();
  9563. $script_id = getProp($data, 'script_id');
  9564. $episode_number = getProp($data, 'episode_number');
  9565. if (!$script_id) {
  9566. Utils::throwError('20003:请提供剧本ID');
  9567. }
  9568. // 验证剧本是否存在
  9569. $script = DB::table('mp_scripts')
  9570. ->where('id', $script_id)
  9571. ->where('is_deleted', 0)
  9572. ->first();
  9573. if (!$script) {
  9574. Utils::throwError('20003:剧本不存在');
  9575. }
  9576. // 联表查询资产信息
  9577. $query = DB::table('mp_script_product_mappings as mapping')
  9578. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9579. ->where('mapping.script_id', $script_id)
  9580. ->where('product.cpid', $cpid)
  9581. ->where('product.is_deleted', 0);
  9582. // 如果提供了 episode_number,则过滤指定集数
  9583. if ($episode_number !== null && $episode_number !== '') {
  9584. $query->where('mapping.episode_number', $episode_number);
  9585. }
  9586. $mappings = $query->select(
  9587. 'mapping.script_id',
  9588. 'mapping.product_id',
  9589. 'mapping.episode_number',
  9590. 'product.product_name',
  9591. 'product.type',
  9592. 'product.product',
  9593. 'product.pic_prompt',
  9594. 'product.url',
  9595. 'product.pic_task_id',
  9596. 'product.pic_task_status',
  9597. 'product.three_view_image_url',
  9598. 'product.timbre_url',
  9599. 'mapping.created_at'
  9600. )
  9601. ->orderBy('mapping.product_id', 'asc')
  9602. ->orderBy('mapping.episode_number', 'asc')
  9603. ->get();
  9604. // 按 product_id 分组,合并 episode_number
  9605. $productMap = [];
  9606. foreach ($mappings as $item) {
  9607. $product_id = $item->product_id;
  9608. if (!isset($productMap[$product_id])) {
  9609. $productMap[$product_id] = [
  9610. 'product_id' => $product_id,
  9611. 'product_name' => $item->product_name,
  9612. 'type' => (int)$item->type,
  9613. 'product' => (int)$item->product,
  9614. 'pic_prompt' => $item->pic_prompt,
  9615. 'url' => $item->url,
  9616. 'timbre_url' => $item->timbre_url,
  9617. 'pic_task_id' => $item->pic_task_id,
  9618. 'pic_task_status' => $item->pic_task_status,
  9619. 'episode_numbers' => [],
  9620. 'created_at' => $item->created_at,
  9621. ];
  9622. }
  9623. // 添加 episode_number(去重)
  9624. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  9625. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  9626. }
  9627. }
  9628. // 按类型分组
  9629. $roles = []; // type=1 角色/主体
  9630. $scenes = []; // type=2 场景
  9631. $props = []; // type=3 道具
  9632. foreach ($productMap as $product) {
  9633. // 将 episode_numbers 数组转换为逗号分隔的字符串
  9634. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  9635. // 构造返回数据
  9636. $productData = [
  9637. 'product_id' => $product['product_id'],
  9638. 'product_name' => $product['product_name'],
  9639. 'product' => $product['product'],
  9640. 'pic_prompt' => $product['pic_prompt'],
  9641. 'url' => $product['url'],
  9642. 'timbre_url' => $product['timbre_url'] ?? '',
  9643. 'pic_task_id' => $product['pic_task_id'],
  9644. 'pic_task_status' => $product['pic_task_status'],
  9645. 'episode_numbers' => $episodeNumbersStr,
  9646. 'created_at' => $product['created_at'],
  9647. ];
  9648. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  9649. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  9650. switch ($product['product']) {
  9651. case 1:
  9652. $roles[] = $productData;
  9653. break;
  9654. case 2:
  9655. $scenes[] = $productData;
  9656. break;
  9657. case 3:
  9658. $props[] = $productData;
  9659. break;
  9660. }
  9661. }
  9662. return [
  9663. 'script_id' => $script_id,
  9664. 'script_name' => $script->script_name ?? '',
  9665. 'roles' => $roles, // 主体
  9666. 'scenes' => $scenes, // 场景
  9667. 'props' => $props, // 道具
  9668. ];
  9669. }
  9670. /**
  9671. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  9672. * @param string $actContent 原始内容
  9673. * @param array $products 产品数组(包含product_name和url)
  9674. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  9675. */
  9676. public function processActContentWithProducts($actContent, $products) {
  9677. if (empty($actContent) || empty($products)) {
  9678. return [
  9679. 'content' => $actContent,
  9680. 'reference_images' => []
  9681. ];
  9682. }
  9683. // 构建产品名称到产品信息的映射
  9684. $product_dict = [];
  9685. foreach ($products as $product) {
  9686. $product_name = getProp($product, 'product_name');
  9687. if ($product_name) {
  9688. $product_dict[$product_name] = [
  9689. // 优先使用三视图图片作为素材/参考图,否则使用原图 url
  9690. 'url' => getProp($product, 'three_view_image_url') ?: getProp($product, 'url'),
  9691. 'voice_prompt' => getProp($product, 'voice_prompt')
  9692. ];
  9693. }
  9694. }
  9695. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  9696. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  9697. $reference_images = [];
  9698. $product_index_map = []; // 产品名称 => 图片序号的映射
  9699. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  9700. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  9701. $current_index = 1;
  9702. if (!empty($matches[1])) {
  9703. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  9704. $seen_products = []; // 用于去重
  9705. foreach ($matches[1] as $product_name) {
  9706. // 跳过已处理的产品
  9707. if (isset($seen_products[$product_name])) {
  9708. continue;
  9709. }
  9710. $seen_products[$product_name] = true;
  9711. // 检查产品是否在字典中
  9712. if (isset($product_dict[$product_name])) {
  9713. $url = $product_dict[$product_name]['url'];
  9714. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  9715. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  9716. if (!empty($voice_prompt) && $product_name !== '旁白') {
  9717. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  9718. }
  9719. // 只有URL非空才分配序号和添加到参考图片
  9720. if (!empty($url)) {
  9721. // 检查URL是否已经在reference_images中(去重)
  9722. if (!in_array($url, $reference_images)) {
  9723. $reference_images[] = $url;
  9724. $product_index_map[$product_name] = $current_index;
  9725. $current_index++;
  9726. } else {
  9727. // URL重复,找到已有的序号
  9728. $existing_index = array_search($url, $reference_images) + 1;
  9729. $product_index_map[$product_name] = $existing_index;
  9730. }
  9731. } else {
  9732. // URL为空,不分配序号(后续直接去掉{})
  9733. $product_index_map[$product_name] = 0;
  9734. }
  9735. } else {
  9736. // 产品不在字典中,不分配序号
  9737. $product_index_map[$product_name] = 0;
  9738. }
  9739. }
  9740. }
  9741. // 第二步:替换内容中的 {产品名称}
  9742. $processedContent = $actContent;
  9743. foreach ($product_index_map as $product_name => $index) {
  9744. $escaped_name = preg_quote($product_name, '/');
  9745. if ($index > 0) {
  9746. // 有图片,替换为:产品名称(图X)
  9747. $replacement = $product_name . '<图片' . $index . '>';
  9748. } else {
  9749. // 无图片,只保留产品名称
  9750. $replacement = $product_name;
  9751. }
  9752. // 替换所有 {产品名称} 为处理后的格式
  9753. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  9754. }
  9755. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  9756. foreach ($products as $product) {
  9757. $product_name = getProp($product, 'product_name');
  9758. $voice_prompt = getProp($product, 'voice_prompt');
  9759. if ($product_name === '旁白' && !empty($voice_prompt)) {
  9760. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  9761. break; // 找到旁白后退出循环
  9762. }
  9763. }
  9764. // 第四步:将voice_prompt信息添加到内容最前面
  9765. $voice_prompt_prefix = '';
  9766. if (!empty($voice_prompts)) {
  9767. $voice_prompt_prefix .= implode('', $voice_prompts);
  9768. }
  9769. // 旁白的voice_prompt放在最后
  9770. if (!empty($narrator_voice_prompt)) {
  9771. $voice_prompt_prefix .= $narrator_voice_prompt;
  9772. }
  9773. // 如果有voice_prompt信息,添加到内容开头
  9774. if (!empty($voice_prompt_prefix)) {
  9775. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  9776. }
  9777. return [
  9778. 'content' => $processedContent,
  9779. 'reference_images' => $reference_images
  9780. ];
  9781. }
  9782. public function saveActVideoGenerateParams($data) {
  9783. $episode_id = getProp($data, 'episode_id');
  9784. $model = getProp($data, 'video_model');
  9785. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  9786. if (!in_array($model, $valid_models)) {
  9787. Utils::throwError('20003:该模型不可用');
  9788. }
  9789. // 验证模型是否在可用模型表中
  9790. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9791. Utils::throwError('20003:该模型已不可用,请更换!');
  9792. }
  9793. $video_resolution = getProp($data, 'video_resolution', '720p');
  9794. $ratio = getProp($data, 'ratio');
  9795. if (!$ratio) $ratio = '9:16';
  9796. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  9797. if (!$episode) {
  9798. Utils::throwError('20003:分集不存在');
  9799. }
  9800. dLog('anime')->info('保存分集视频参数', $data);
  9801. try {
  9802. DB::beginTransaction();
  9803. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  9804. 'video_model' => $model,
  9805. 'video_resolution' => $video_resolution,
  9806. 'ratio' => $ratio,
  9807. 'updated_at' => date('Y-m-d H:i:s')
  9808. ]);
  9809. if ($result === false) {
  9810. Utils::throwError('20003:分集视频参数保存失败');
  9811. }
  9812. // 同步更新mp_animes表
  9813. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  9814. 'video_model' => $model,
  9815. 'video_resolution' => $video_resolution,
  9816. 'video_ratio' => $ratio,
  9817. 'updated_at' => date('Y-m-d H:i:s')
  9818. ]);
  9819. if ($anime_result === false) {
  9820. Utils::throwError('20003:动漫视频参数保存失败');
  9821. }
  9822. } catch (\Exception $e) {
  9823. DB::rollBack();
  9824. Utils::throwError('20003:'.$e->getMessage());
  9825. }
  9826. DB::commit();
  9827. return $result;
  9828. }
  9829. public function confirmActs($data) {
  9830. $episode_id = getProp($data, 'episode_id');
  9831. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  9832. if (!$episode) {
  9833. Utils::throwError('20003:分集不存在');
  9834. }
  9835. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9836. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9837. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  9838. // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
  9839. $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
  9840. // 获取所有片段数据
  9841. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  9842. // 先构建完整的 products(角色、场景、道具、extra_products,并用资产库映射覆盖),
  9843. // 再处理每个片段的 act_content,避免 extra_products 等资产名未被格式化为 {资产名}
  9844. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  9845. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  9846. $products = [];
  9847. // 先处理角色数组
  9848. foreach ($roles as $role) {
  9849. $product = $role;
  9850. // 将role字段重命名为product_name
  9851. if (isset($product['role'])) {
  9852. $product['product_name'] = $product['role'];
  9853. unset($product['role']);
  9854. $product['product'] = 1; // 标记类型为角色
  9855. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9856. }
  9857. }
  9858. // 处理场景数组
  9859. foreach ($scenes as $scene) {
  9860. $product = $scene;
  9861. // 将scene字段重命名为product_name
  9862. if (isset($product['scene'])) {
  9863. $product['product_name'] = $product['scene'];
  9864. unset($product['scene']);
  9865. $product['product'] = 2; // 标记类型为场景
  9866. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9867. }
  9868. }
  9869. // 处理道具数组(逻辑与场景一致)
  9870. foreach ($props as $prop) {
  9871. $product = $prop;
  9872. // 将prop字段重命名为product_name
  9873. if (isset($product['prop'])) {
  9874. $product['product_name'] = $product['prop'];
  9875. unset($product['prop']);
  9876. $product['product'] = 3; // 标记类型为道具
  9877. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  9878. }
  9879. }
  9880. // extra_products优先级更高,直接覆盖同名的roles和scenes
  9881. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  9882. foreach ($extra_products as $extra_product) {
  9883. $product_name = getProp($extra_product, 'product_name');
  9884. if ($product_name) {
  9885. $products[$product_name] = $extra_product; // 覆盖同名数据
  9886. }
  9887. }
  9888. // mp_script_product_mappings 信息优先级更高:
  9889. // 获取当前剧集所属动漫剧本下、与本集资产同名的资产库最新数据(url/三视图/提示词等),
  9890. // 覆盖分集 JSON 中保存的同名旧快照;分集内独有的 description、voice_prompt 等字段保留
  9891. $anime = DB::table('mp_animes')->where('id', getProp($episode, 'anime_id'))->first();
  9892. $script_id = $anime ? (int)getProp($anime, 'script_id', 0) : 0;
  9893. if ($script_id && !empty($products)) {
  9894. $currentProductNames = array_keys($products);
  9895. $normalizeName = function($name) {
  9896. return trim(preg_replace(
  9897. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  9898. '',
  9899. trim((string)$name)
  9900. ));
  9901. };
  9902. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  9903. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9904. ->where('mapping.script_id', $script_id)
  9905. ->where('product.is_deleted', 0)
  9906. ->whereIn('product.product_name', $currentProductNames)
  9907. ->select(
  9908. 'mapping.product_id',
  9909. 'product.product_name',
  9910. 'product.product',
  9911. 'product.pic_prompt',
  9912. 'product.url',
  9913. 'product.three_view_image_url',
  9914. )
  9915. ->get();
  9916. $mappingByName = [];
  9917. foreach ($mappingItems as $mappingItem) {
  9918. $normalizedName = $normalizeName($mappingItem->product_name);
  9919. if (!$normalizedName) continue;
  9920. $mappingByName[$normalizedName] = [
  9921. 'product_id' => (int)$mappingItem->product_id,
  9922. 'product_name' => $mappingItem->product_name,
  9923. 'product' => (int)$mappingItem->product,
  9924. 'pic_prompt' => $mappingItem->pic_prompt ?? '',
  9925. 'url' => $mappingItem->url ?? '',
  9926. 'three_view_image_url' => $mappingItem->three_view_image_url ?? '',
  9927. ];
  9928. }
  9929. foreach ($products as $key => &$product) {
  9930. $normalizedKey = $normalizeName($key);
  9931. if ($normalizedKey && isset($mappingByName[$normalizedKey])) {
  9932. $product = array_merge($product, $mappingByName[$normalizedKey]);
  9933. }
  9934. }
  9935. unset($product);
  9936. }
  9937. // 兼容返回 three_view_image_url 字段(旧数据可能没有该键,统一补空值)
  9938. foreach ($products as &$product) {
  9939. if (!isset($product['three_view_image_url'])) {
  9940. $product['three_view_image_url'] = '';
  9941. }
  9942. }
  9943. unset($product);
  9944. // 重新索引数组(去除key)
  9945. $products = array_values($products);
  9946. // 基于构建完成的 products 收集所有资产名称(含 extra_products 中的资产)
  9947. $product_names = [];
  9948. foreach ($products as $product) {
  9949. $product_name = getProp($product, 'product_name');
  9950. if ($product_name && $product_name !== '旁白') {
  9951. $product_names[] = $product_name;
  9952. }
  9953. }
  9954. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  9955. $product_names = array_unique($product_names);
  9956. usort($product_names, function($a, $b) {
  9957. return mb_strlen($b) - mb_strlen($a);
  9958. });
  9959. try {
  9960. DB::beginTransaction();
  9961. // 处理每个片段
  9962. foreach ($acts as $act) {
  9963. $act_content = getProp($act, 'act_content');
  9964. if (!$act_content) continue;
  9965. $processed_content = $act_content;
  9966. // 统一替换所有资产名称为 {资产名} 格式
  9967. // 使用占位符避免嵌套替换问题
  9968. $placeholder_map = [];
  9969. $placeholder_index = 0;
  9970. foreach ($product_names as $product_name) {
  9971. // 转义特殊字符
  9972. $escaped_product = preg_quote($product_name, '/');
  9973. // 检查是否匹配且未被 {} 包裹
  9974. $processed_content = preg_replace_callback(
  9975. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  9976. function($matches) use (&$placeholder_map, &$placeholder_index) {
  9977. // 使用唯一占位符
  9978. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  9979. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  9980. $placeholder_index++;
  9981. return $placeholder;
  9982. },
  9983. $processed_content
  9984. );
  9985. }
  9986. // 将所有占位符替换回实际内容
  9987. foreach ($placeholder_map as $placeholder => $replacement) {
  9988. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  9989. }
  9990. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  9991. $shot_counter = 0;
  9992. $processed_content = preg_replace_callback(
  9993. '/【(?:镜头|分镜)(\d+)】/u',
  9994. function($matches) use (&$shot_counter) {
  9995. $shot_counter++;
  9996. return '【镜头' . $shot_counter . '】';
  9997. },
  9998. $processed_content
  9999. );
  10000. // 更新数据库
  10001. $boolen = DB::table('mp_episode_segments')
  10002. ->where('id', $act->id)
  10003. ->update([
  10004. 'act_show_content' => $processed_content,
  10005. 'updated_at' => date('Y-m-d H:i:s')
  10006. ]);
  10007. if (!$boolen) {
  10008. Utils::throwError('20003:片段处理失败');
  10009. }
  10010. }
  10011. }catch (\Exception $e) {
  10012. DB::rollBack();
  10013. Utils::throwError('20003:'.$e->getMessage());
  10014. }
  10015. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10016. 'is_generated' => 1,
  10017. 'updated_at' => date('Y-m-d H:i:s')
  10018. ]);
  10019. if (!$boolen1) {
  10020. DB::rollBack();
  10021. Utils::throwError('20003:分集处理失败!');
  10022. }
  10023. DB::commit();
  10024. // 重新查询更新后的片段数据
  10025. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  10026. // 构建返回的acts数组
  10027. $return_acts = [];
  10028. foreach ($acts as $act) {
  10029. $return_acts[] = [
  10030. 'act_id' => getProp($act, 'id'),
  10031. 'act_number' => getProp($act, 'act_number'),
  10032. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  10033. 'act_show_content' => getProp($act, 'act_show_content'),
  10034. 'video_url' => getProp($act, 'video_url'),
  10035. 'video_duration' => getProp($act, 'video_duration'),
  10036. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  10037. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  10038. ];
  10039. }
  10040. return [
  10041. 'anime_id' => getProp($episode, 'anime_id'),
  10042. 'episode_id' => $episode_id,
  10043. 'title' => getProp($episode, 'title'),
  10044. 'episode_number' => getProp($episode, 'episode_number'),
  10045. 'is_generated' => getProp($episode, 'is_generated'),
  10046. 'video_params' => [
  10047. 'video_model' => getProp($episode, 'video_model'),
  10048. 'video_resolution' => getProp($episode, 'video_resolution'),
  10049. 'ratio' => getProp($episode, 'ratio'),
  10050. ],
  10051. 'products' => $products,
  10052. 'acts' => $return_acts
  10053. ];
  10054. }
  10055. /**
  10056. * 参照 episodePicsInfo 的更新与监控逻辑:
  10057. * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
  10058. * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
  10059. */
  10060. private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
  10061. $pollInterval = 5; // 每5秒查询一次
  10062. $maxWaitSeconds = 60; // 最多持续1分钟
  10063. $startTime = time();
  10064. while (true) {
  10065. // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
  10066. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  10067. if (!$episode) {
  10068. Utils::throwError('20003:分集不存在');
  10069. }
  10070. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10071. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10072. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  10073. $updated = false;
  10074. $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
  10075. $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
  10076. $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
  10077. $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
  10078. $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
  10079. // 有图片任务结果更新时写回分集表
  10080. if ($updated) {
  10081. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10082. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  10083. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  10084. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  10085. 'updated_at' => date('Y-m-d H:i:s')
  10086. ]);
  10087. }
  10088. // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
  10089. if (empty($waitingAssets) && empty($missingAssets)) {
  10090. return;
  10091. }
  10092. // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
  10093. if (empty($waitingAssets)) {
  10094. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10095. }
  10096. // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
  10097. if (time() - $startTime >= $maxWaitSeconds) {
  10098. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10099. }
  10100. sleep($pollInterval);
  10101. }
  10102. }
  10103. /**
  10104. * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
  10105. * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
  10106. * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
  10107. */
  10108. private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
  10109. foreach ($assets as &$asset) {
  10110. $assetName = getProp($asset, $nameKey);
  10111. if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
  10112. continue;
  10113. }
  10114. // 已有图片URL的资产视为已生成
  10115. if (getProp($asset, 'url')) {
  10116. continue;
  10117. }
  10118. $task_id = getProp($asset, 'task_id');
  10119. // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
  10120. if (!$task_id) {
  10121. $missingAssets[] = $assetName;
  10122. continue;
  10123. }
  10124. $task = DB::table('mp_generate_pic_tasks')
  10125. ->where('id', $task_id)
  10126. ->select('status', 'result_url')
  10127. ->first();
  10128. // 任务不存在:同样记录为缺失项,不在此处直接报错
  10129. if (!$task) {
  10130. $missingAssets[] = $assetName;
  10131. continue;
  10132. }
  10133. if ($task->status === 'success') {
  10134. $result_url = getProp($task, 'result_url');
  10135. if ($result_url) {
  10136. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  10137. if (is_array($result_urls) && !empty($result_urls[0])) {
  10138. $asset['url'] = $result_urls[0];
  10139. $asset['task_status'] = 'success';
  10140. $updated = true;
  10141. continue;
  10142. }
  10143. }
  10144. // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
  10145. $waitingAssets[] = $assetName;
  10146. } elseif ($task->status === 'failed') {
  10147. // 生成失败:记录为缺失项,待其他任务处理完后统一报错
  10148. $missingAssets[] = $assetName;
  10149. } else {
  10150. // 任务仍在生成中,等待下一次轮询
  10151. $waitingAssets[] = $assetName;
  10152. }
  10153. }
  10154. unset($asset);
  10155. }
  10156. /**
  10157. * 导出动漫剧本为PDF(参照示例PDF版式)
  10158. * @param int $animeId 动漫ID
  10159. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  10160. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  10161. * @return string|null
  10162. */
  10163. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  10164. // 图片下载与转换可能占用较多内存
  10165. ini_set('memory_limit', '512M');
  10166. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  10167. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  10168. $anime = (array)$anime;
  10169. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  10170. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  10171. // 获取分集(默认展示版本,按集数升序)
  10172. $episodeQuery = DB::table('mp_anime_episodes')
  10173. ->where('anime_id', $animeId)
  10174. ->where('is_default', 1)
  10175. ->orderBy('episode_number')
  10176. ->orderBy('id');
  10177. if ($episodeCount > 0) {
  10178. $episodeQuery->limit($episodeCount);
  10179. }
  10180. $episodes = $episodeQuery->get()->map(function ($value) {
  10181. return (array)$value;
  10182. })->toArray();
  10183. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  10184. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  10185. $roles = $this->mergeEpisodeItems($episodes, 'role');
  10186. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  10187. $props = $this->mergeEpisodeItems($episodes, 'prop');
  10188. // 组装分集剧本数据
  10189. $episodeScripts = [];
  10190. foreach ($episodes as $episode) {
  10191. $segments = DB::table('mp_episode_segments')
  10192. ->where('anime_id', $animeId)
  10193. ->where('episode_id', $episode['id'])
  10194. ->get();
  10195. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  10196. $acts = [];
  10197. foreach ($segments as $segment) {
  10198. $segment = (array)$segment;
  10199. $actNumber = (int)getProp($segment, 'act_number', 0);
  10200. if ($actNumber <= 0) continue;
  10201. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  10202. $acts[$actNumber] = [
  10203. 'id' => (int)$segment['id'],
  10204. 'act_number' => $actNumber,
  10205. 'duration' => getProp($segment, 'act_duration', ''),
  10206. 'content' => getProp($segment, 'act_content', ''),
  10207. ];
  10208. }
  10209. }
  10210. ksort($acts);
  10211. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  10212. $segmentCounter = 0;
  10213. foreach ($acts as &$act) {
  10214. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  10215. }
  10216. unset($act);
  10217. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  10218. $narratorVoice = '';
  10219. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  10220. foreach ($episodeRoles as $role) {
  10221. if (getProp($role, 'role') === '旁白') {
  10222. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  10223. break;
  10224. }
  10225. }
  10226. if ($narratorVoice === '') {
  10227. foreach ($acts as $act) {
  10228. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  10229. $narratorVoice = trim($match[1]);
  10230. break;
  10231. }
  10232. }
  10233. }
  10234. $episodeScripts[] = [
  10235. 'episode_number' => getProp($episode, 'episode_number'),
  10236. 'title' => getProp($episode, 'title', ''),
  10237. 'act_count' => count($acts),
  10238. 'narrator_voice' => $narratorVoice,
  10239. 'acts' => array_values($acts),
  10240. ];
  10241. }
  10242. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  10243. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  10244. // 构建PDF
  10245. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  10246. // 图片已嵌入PDF,清理临时文件
  10247. foreach ($imageCache as $imgFile) {
  10248. @unlink($imgFile);
  10249. }
  10250. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  10251. if ($savePath) {
  10252. $pdf->Output($savePath, 'F');
  10253. return $savePath;
  10254. }
  10255. // 直接下载输出
  10256. header('Content-Type: application/pdf');
  10257. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  10258. $pdf->Output($filename . '.pdf', 'D');
  10259. exit();
  10260. }
  10261. /**
  10262. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  10263. * @param array $episodes 分集数据
  10264. * @param string $nameKey role|scene|prop
  10265. * @return array
  10266. */
  10267. private function mergeEpisodeItems(array $episodes, $nameKey) {
  10268. $fieldMap = [
  10269. 'role' => 'roles',
  10270. 'scene' => 'scenes',
  10271. 'prop' => 'props',
  10272. ];
  10273. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  10274. $items = [];
  10275. foreach ($episodes as $episode) {
  10276. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  10277. foreach ($list as $item) {
  10278. if (!is_array($item)) continue;
  10279. $name = trim((string)getProp($item, $nameKey, ''));
  10280. if ($name === '') continue;
  10281. // 旁白不进入主体列表(仅作为旁白音色来源)
  10282. if ($nameKey === 'role' && $name === '旁白') continue;
  10283. if (!isset($items[$name])) {
  10284. $items[$name] = $item;
  10285. }
  10286. }
  10287. }
  10288. return array_values($items);
  10289. }
  10290. /**
  10291. * 构建动漫剧本PDF
  10292. * @param array $anime 动漫信息
  10293. * @param array $roles 主体列表
  10294. * @param array $scenes 场景列表
  10295. * @param array $props 道具列表
  10296. * @param array $episodeScripts 分集剧本数据
  10297. * @param array $imageCache 图片缓存(url => 临时文件路径)
  10298. * @return \TCPDF
  10299. */
  10300. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  10301. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  10302. $pdf->SetCreator('动漫剧本导出系统');
  10303. $pdf->SetAuthor('系统');
  10304. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  10305. $pdf->SetSubject('动漫剧本导出');
  10306. $pdf->SetMargins(15, 15, 15);
  10307. $pdf->SetAutoPageBreak(true, 15);
  10308. // 剧本名
  10309. $pdf->AddPage();
  10310. $pdf->SetFont('simsun', 'B', 20);
  10311. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  10312. $pdf->Ln(5);
  10313. // 故事梗概
  10314. $intro = trim((string)getProp($anime, 'intro', ''));
  10315. if ($intro !== '') {
  10316. $this->pdfSectionTitle($pdf, '故事梗概');
  10317. $this->pdfBody($pdf, $intro);
  10318. }
  10319. // 美术风格
  10320. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  10321. if ($artStyle !== '') {
  10322. $this->pdfSectionTitle($pdf, '美术风格');
  10323. $this->pdfBody($pdf, $artStyle);
  10324. }
  10325. // 主体列表(文字+图片)
  10326. $this->pdfSectionTitle($pdf, '主体列表');
  10327. foreach ($roles as $index => $role) {
  10328. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  10329. }
  10330. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  10331. // 场景列表(文字+图片)
  10332. $this->pdfSectionTitle($pdf, '场景列表');
  10333. foreach ($scenes as $index => $scene) {
  10334. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  10335. }
  10336. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  10337. // 道具列表(文字+图片)
  10338. $this->pdfSectionTitle($pdf, '道具列表');
  10339. foreach ($props as $index => $prop) {
  10340. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  10341. }
  10342. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  10343. // 分镜剧本
  10344. $this->pdfSectionTitle($pdf, '分镜剧本');
  10345. foreach ($episodeScripts as $episodeScript) {
  10346. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  10347. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  10348. if ($episodeTitleRaw !== '') {
  10349. // title 字段可能已带"第N集"前缀,避免重复
  10350. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  10351. $episodeTitle = $episodeTitleRaw;
  10352. } else {
  10353. $episodeTitle .= ':' . $episodeTitleRaw;
  10354. }
  10355. }
  10356. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  10357. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  10358. if (getProp($episodeScript, 'narrator_voice') !== '') {
  10359. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  10360. }
  10361. foreach (getProp($episodeScript, 'acts', []) as $act) {
  10362. $actTitle = '片段' . getProp($act, 'act_number');
  10363. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  10364. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  10365. }
  10366. $this->pdfSubTitle($pdf, $actTitle, 12);
  10367. if (getProp($act, 'content') !== '') {
  10368. $this->pdfBody($pdf, getProp($act, 'content'));
  10369. }
  10370. }
  10371. }
  10372. return $pdf;
  10373. }
  10374. /**
  10375. * PDF章节标题(带分隔线)
  10376. */
  10377. private function pdfSectionTitle($pdf, $title) {
  10378. if ($pdf->GetY() > 230) {
  10379. $pdf->AddPage();
  10380. }
  10381. $pdf->SetFont('simsun', 'B', 15);
  10382. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  10383. $y = $pdf->GetY();
  10384. $pdf->SetLineWidth(0.4);
  10385. $pdf->Line(15, $y, 195, $y);
  10386. $pdf->Ln(4);
  10387. }
  10388. /**
  10389. * PDF子标题(集数/片段标题)
  10390. */
  10391. private function pdfSubTitle($pdf, $title, $size = 13) {
  10392. if ($pdf->GetY() > 240) {
  10393. $pdf->AddPage();
  10394. }
  10395. $pdf->SetFont('simsun', 'B', $size);
  10396. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  10397. $pdf->Ln(1);
  10398. }
  10399. /**
  10400. * PDF正文段落
  10401. */
  10402. private function pdfBody($pdf, $text) {
  10403. $pdf->SetFont('simsun', '', 11);
  10404. $pdf->MultiCell(0, 6, $text, 0, 'L');
  10405. $pdf->Ln(2);
  10406. }
  10407. /**
  10408. * 输出列表项图片(每张图单独一页,图下标注名称)
  10409. * @param \TCPDF $pdf
  10410. * @param array $items 列表项
  10411. * @param string $nameKey role|scene|prop
  10412. * @param array $imageCache 图片缓存(url => 临时文件路径)
  10413. */
  10414. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  10415. foreach ($items as $item) {
  10416. $url = trim((string)getProp($item, 'url', ''));
  10417. $name = trim((string)getProp($item, $nameKey, ''));
  10418. if ($url === '' || !isset($imageCache[$url])) continue;
  10419. $imgPath = $imageCache[$url];
  10420. $size = @getimagesize($imgPath);
  10421. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  10422. continue;
  10423. }
  10424. $pdf->AddPage();
  10425. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  10426. $maxW = 160;
  10427. $maxH = 170;
  10428. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  10429. $drawW = $size[0] * $ratio;
  10430. $drawH = $size[1] * $ratio;
  10431. $x = (210 - $drawW) / 2;
  10432. $y = max(15, (297 - $drawH) / 2 - 10);
  10433. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  10434. // 图下标注名称
  10435. $pdf->SetFont('simsun', 'B', 13);
  10436. $pdf->SetY(297 - 28);
  10437. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  10438. }
  10439. }
  10440. /**
  10441. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  10442. * @param array $items 包含url字段的列表项
  10443. * @return array url => 临时文件路径
  10444. */
  10445. private function downloadImagesConcurrently(array $items) {
  10446. // 收集唯一的图片URL
  10447. $urls = [];
  10448. foreach ($items as $item) {
  10449. $url = trim((string)getProp($item, 'url', ''));
  10450. if ($url !== '') $urls[$url] = true;
  10451. }
  10452. if (!$urls) return [];
  10453. $urls = array_keys($urls);
  10454. $tmpDir = sys_get_temp_dir();
  10455. $rawFiles = [];
  10456. foreach ($urls as $url) {
  10457. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  10458. $rawFiles[$url] = $rawFile;
  10459. }
  10460. $client = new Client(['timeout' => 180, 'verify' => false]);
  10461. // 低并发下载,sink写入文件避免大图占用内存
  10462. $generator = (function () use ($urls, $client, $rawFiles) {
  10463. foreach ($urls as $url) {
  10464. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  10465. }
  10466. })();
  10467. $errors = [];
  10468. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  10469. 'concurrency' => 4,
  10470. 'rejected' => function ($reason, $url) use (&$errors) {
  10471. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  10472. },
  10473. ]);
  10474. $each->promise()->wait();
  10475. // 失败的图片串行重试一次(独占带宽,提高成功率)
  10476. foreach ($urls as $url) {
  10477. if (!isset($errors[$url])) continue;
  10478. try {
  10479. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  10480. unset($errors[$url]);
  10481. } catch (\Throwable $e) {
  10482. // 重试仍失败
  10483. }
  10484. }
  10485. $cache = [];
  10486. foreach ($urls as $url) {
  10487. $rawFile = $rawFiles[$url];
  10488. if (isset($errors[$url])) {
  10489. dLog('anime')->error('导出PDF图片下载失败', [
  10490. 'url' => $url,
  10491. 'error' => $errors[$url],
  10492. ]);
  10493. @unlink($rawFile);
  10494. continue;
  10495. }
  10496. $converted = $this->convertImageFile($rawFile, $url);
  10497. if ($converted !== null) {
  10498. $cache[$url] = $converted;
  10499. } else {
  10500. @unlink($rawFile);
  10501. }
  10502. }
  10503. return $cache;
  10504. }
  10505. /**
  10506. * 将已下载的图片文件缩放并转为JPEG
  10507. * @param string $rawFile 原始图片临时文件
  10508. * @param string $url 图片地址(用于命名)
  10509. * @return string|null 转换后的文件路径,转换失败返回null
  10510. */
  10511. private function convertImageFile($rawFile, $url) {
  10512. $content = @file_get_contents($rawFile);
  10513. if ($content === false || $content === '') return null;
  10514. if (!function_exists('imagecreatefromstring')) return null;
  10515. $image = @imagecreatefromstring($content);
  10516. if ($image === false) return null;
  10517. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  10518. imagedestroy($image);
  10519. if ($jpeg !== null) {
  10520. @unlink($rawFile);
  10521. }
  10522. return $jpeg;
  10523. }
  10524. /**
  10525. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  10526. * @param resource $srcImage GD图片资源
  10527. * @param string $rawFile 原始图片临时文件
  10528. * @param string $url 图片地址(用于命名)
  10529. * @return string|null 压缩后的JPEG文件路径
  10530. */
  10531. private function compressImageForPdf($srcImage, $rawFile, $url) {
  10532. $maxBytes = 2 * 1024 * 1024; // 2MB
  10533. $sizes = [2048, 1600, 1280, 1024, 800];
  10534. $qualities = [85, 70, 55, 40];
  10535. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  10536. foreach ($sizes as $size) {
  10537. $resized = $this->copyAndResize($srcImage, $size);
  10538. $flat = $this->flattenToWhite($resized);
  10539. imagedestroy($resized);
  10540. foreach ($qualities as $quality) {
  10541. ob_start();
  10542. $saved = imagejpeg($flat, null, $quality);
  10543. $data = ob_get_clean();
  10544. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  10545. file_put_contents($jpeg, $data);
  10546. imagedestroy($flat);
  10547. dLog('anime')->info('导出PDF图片压缩完成', [
  10548. 'url' => $url,
  10549. 'size' => filesize($jpeg),
  10550. 'edge' => $size,
  10551. 'quality' => $quality,
  10552. ]);
  10553. return $jpeg;
  10554. }
  10555. }
  10556. imagedestroy($flat);
  10557. }
  10558. // 兜底:最小尺寸、最低质量强制输出
  10559. $resized = $this->copyAndResize($srcImage, 800);
  10560. $flat = $this->flattenToWhite($resized);
  10561. imagedestroy($resized);
  10562. $saved = imagejpeg($flat, $jpeg, 30);
  10563. imagedestroy($flat);
  10564. if (!$saved) return null;
  10565. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  10566. 'url' => $url,
  10567. 'size' => filesize($jpeg),
  10568. ]);
  10569. return $jpeg;
  10570. }
  10571. /**
  10572. * 等比缩放图片副本(不销毁原图)
  10573. * @param resource $srcImage GD图片资源
  10574. * @param int $maxEdge 最大边长
  10575. * @return resource
  10576. */
  10577. private function copyAndResize($srcImage, $maxEdge) {
  10578. $width = imagesx($srcImage);
  10579. $height = imagesy($srcImage);
  10580. $max = max($width, $height);
  10581. if ($max <= $maxEdge) {
  10582. $copy = imagecreatetruecolor($width, $height);
  10583. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  10584. return $copy;
  10585. }
  10586. $ratio = $maxEdge / $max;
  10587. $newWidth = max(1, (int)round($width * $ratio));
  10588. $newHeight = max(1, (int)round($height * $ratio));
  10589. $resized = imagecreatetruecolor($newWidth, $newHeight);
  10590. imagealphablending($resized, false);
  10591. imagesavealpha($resized, true);
  10592. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  10593. return $resized;
  10594. }
  10595. /**
  10596. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  10597. * @param resource $image GD图片资源
  10598. * @return resource
  10599. */
  10600. private function flattenToWhite($image) {
  10601. $width = imagesx($image);
  10602. $height = imagesy($image);
  10603. $flat = imagecreatetruecolor($width, $height);
  10604. $white = imagecolorallocate($flat, 255, 255, 255);
  10605. imagefill($flat, 0, 0, $white);
  10606. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  10607. return $flat;
  10608. }
  10609. /**
  10610. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  10611. * @param string $content 片段内容
  10612. * @param int $counter 当前已编号数量(引用传递,整集累计)
  10613. * @return string
  10614. */
  10615. private function renumberSegmentBlocks($content, &$counter) {
  10616. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  10617. $counter++;
  10618. return '【' . $match[1] . $counter . '】';
  10619. }, $content);
  10620. }
  10621. }