AnimeService.php 543 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696
  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('user_id', $uid)
  1039. ->where('is_deleted', 0)
  1040. ->first();
  1041. if ($script) {
  1042. $script_name = $script->script_name ?? 'script_' . $script_id;
  1043. $product_name = getProp($target_roles, 'role');
  1044. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1045. $url = getProp($target_roles, 'url', '');
  1046. $three_view_image_url = trim(getProp($target_roles, 'three_view_image_url', ''));
  1047. // 兼容 versions 传入数组或 JSON 字符串
  1048. $versions = getProp($target_roles, 'versions', null);
  1049. if (is_string($versions) && $versions !== '') {
  1050. $decoded_versions = json_decode($versions, true);
  1051. if (is_array($decoded_versions)) {
  1052. $versions = $decoded_versions;
  1053. }
  1054. }
  1055. $product_type = 1; // 1=角色
  1056. // 查找或创建以script_name命名的文件夹
  1057. $folder = DB::table('mp_products')
  1058. ->where('cpid', $cpid)
  1059. ->where('type', 2) // 文件夹类型
  1060. ->where('product', $product_type) // 角色类型
  1061. ->where('product_name', $script_name)
  1062. ->where('parent_id', 0)
  1063. ->where('is_deleted', 0)
  1064. ->first();
  1065. if (!$folder) {
  1066. // 创建文件夹
  1067. $folder_id = DB::table('mp_products')->insertGetId([
  1068. 'user_id' => $uid,
  1069. 'cpid' => $cpid,
  1070. 'type' => 2, // 文件夹
  1071. 'product' => $product_type, // 角色类型
  1072. 'parent_id' => 0,
  1073. 'level' => 1,
  1074. 'product_name' => $script_name,
  1075. 'sort_order' => time(),
  1076. 'is_deleted' => 0,
  1077. 'created_at' => date('Y-m-d H:i:s'),
  1078. 'updated_at' => date('Y-m-d H:i:s')
  1079. ]);
  1080. } else {
  1081. $folder_id = $folder->id;
  1082. }
  1083. // 查找该文件夹下是否已存在同名资产
  1084. $existing_product = DB::table('mp_products')
  1085. ->where('cpid', $cpid)
  1086. ->where('type', 1) // 资产类型
  1087. ->where('product', $product_type)
  1088. ->where('parent_id', $folder_id)
  1089. ->where('product_name', $product_name)
  1090. ->where('is_deleted', 0)
  1091. ->first();
  1092. if ($existing_product) {
  1093. // 更新已存在的资产
  1094. $updateData = [
  1095. 'pic_task_status' => '生成成功',
  1096. ];
  1097. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1098. if ($url) $updateData['url'] = $url;
  1099. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1100. if (is_array($target_roles) && array_key_exists('three_view_image_url', $target_roles)) {
  1101. $updateData['three_view_image_url'] = trim(getProp($target_roles, 'three_view_image_url', ''));
  1102. }
  1103. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1104. if (is_array($versions)) {
  1105. $updateData['versions'] = json_encode($versions, 256);
  1106. }
  1107. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1108. DB::table('mp_products')
  1109. ->where('id', $existing_product->id)
  1110. ->update($updateData);
  1111. $product_id = $existing_product->id;
  1112. } else {
  1113. // 创建新资产
  1114. $product_id = DB::table('mp_products')->insertGetId([
  1115. 'user_id' => $uid,
  1116. 'cpid' => $cpid,
  1117. 'type' => 1, // 资产
  1118. 'product' => $product_type, // 角色
  1119. 'parent_id' => $folder_id,
  1120. 'level' => 2,
  1121. 'product_name' => $product_name,
  1122. 'url' => $url,
  1123. 'three_view_image_url' => $three_view_image_url,
  1124. 'pic_prompt' => $pic_prompt,
  1125. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1126. 'sort_order' => time(),
  1127. 'is_deleted' => 0,
  1128. 'pic_task_status' => '生成成功',
  1129. 'created_at' => date('Y-m-d H:i:s'),
  1130. 'updated_at' => date('Y-m-d H:i:s')
  1131. ]);
  1132. }
  1133. // 建立或更新绑定关系
  1134. $existing_mapping = DB::table('mp_script_product_mappings')
  1135. ->where('script_id', $script_id)
  1136. ->where('product_id', $product_id)
  1137. ->where('episode_number', $episode_number)
  1138. ->first();
  1139. if (!$existing_mapping) {
  1140. // 创建绑定关系
  1141. DB::table('mp_script_product_mappings')->insert([
  1142. 'script_id' => $script_id,
  1143. 'product_id' => $product_id,
  1144. 'episode_number' => $episode_number,
  1145. 'created_at' => date('Y-m-d H:i:s'),
  1146. 'updated_at' => date('Y-m-d H:i:s')
  1147. ]);
  1148. }
  1149. }
  1150. }
  1151. }
  1152. } catch (\Exception $e) {
  1153. dLog('anime')->error('更新剧集角色失败', [
  1154. 'anime_id' => $anime_id,
  1155. 'episode_id' => $episode_id,
  1156. 'error' => $e->getMessage()
  1157. ]);
  1158. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1159. }
  1160. return true;
  1161. }
  1162. public function changeEpisodeScenes($data) {
  1163. $anime_id = getProp($data, 'anime_id');
  1164. $episode_id = getProp($data, 'episode_id');
  1165. $target_scenes = getProp($data, 'scenes');
  1166. // 删除标志优先取最外层入参 is_deleted,兼容场景对象内部(scenes.is_deleted)的传参
  1167. $is_deleted = getProp($data, 'is_deleted', getProp($target_scenes, 'is_deleted', 0));
  1168. // 控制字段不随场景内容写入分集scenes存储
  1169. if (is_array($target_scenes)) {
  1170. unset($target_scenes['is_deleted']);
  1171. }
  1172. // 参数验证
  1173. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1174. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1175. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1176. // 验证剧集是否存在
  1177. $episode = DB::table('mp_anime_episodes')
  1178. ->where('anime_id', $anime_id)
  1179. ->where('id', $episode_id)
  1180. ->first();
  1181. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1182. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1183. // 获取anime信息,检查是否有关联的script_id
  1184. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1185. if (!$anime) Utils::throwError('20003:动漫不存在');
  1186. $script_id = getProp($anime, 'script_id');
  1187. $episode_number = getProp($episode, 'episode_number', 1);
  1188. $uid = Site::getUid();
  1189. $cpid = Site::getCpid();
  1190. try {
  1191. $target_scene_name = getProp($target_scenes, 'scene');
  1192. if (empty($target_scene_name)) {
  1193. Utils::throwError('20003:场景名称不能为空');
  1194. }
  1195. // 如果是删除操作
  1196. if ($is_deleted == 1) {
  1197. // 从场景列表中移除该场景
  1198. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1199. return getProp($scene, 'scene') !== $target_scene_name;
  1200. }));
  1201. // 更新场景列表
  1202. $result = DB::table('mp_anime_episodes')
  1203. ->where('anime_id', $anime_id)
  1204. ->where('id', $episode_id)
  1205. ->update([
  1206. 'scenes' => json_encode($scenes, 256),
  1207. 'updated_at' => date('Y-m-d H:i:s')
  1208. ]);
  1209. if ($result === false) {
  1210. Utils::throwError('20003:删除场景失败');
  1211. }
  1212. } else {
  1213. // 新增或更新操作
  1214. $scene_found = false;
  1215. $is_new_scene = false;
  1216. // 查找并更新已存在的场景
  1217. foreach($scenes as &$scene) {
  1218. if (getProp($scene, 'scene') === $target_scene_name) {
  1219. $scene = $target_scenes;
  1220. $scene_found = true;
  1221. break;
  1222. }
  1223. }
  1224. // 如果场景不存在,则新增
  1225. if (!$scene_found) {
  1226. $scenes[] = $target_scenes;
  1227. $is_new_scene = true;
  1228. }
  1229. // 更新场景列表
  1230. $result = DB::table('mp_anime_episodes')
  1231. ->where('anime_id', $anime_id)
  1232. ->where('id', $episode_id)
  1233. ->update([
  1234. 'scenes' => json_encode($scenes, 256),
  1235. 'updated_at' => date('Y-m-d H:i:s')
  1236. ]);
  1237. if ($result === false) {
  1238. Utils::throwError('20003:更新场景列表失败');
  1239. }
  1240. // 如果有关联的script_id,则同步到mp_products表
  1241. if ($script_id) {
  1242. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1243. $script = DB::table('mp_scripts')
  1244. ->where('id', $script_id)
  1245. ->where('user_id', $uid)
  1246. ->where('is_deleted', 0)
  1247. ->first();
  1248. if ($script) {
  1249. $script_name = $script->script_name ?? 'script_' . $script_id;
  1250. $product_name = getProp($target_scenes, 'scene');
  1251. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1252. $url = getProp($target_scenes, 'url', '');
  1253. $three_view_image_url = trim(getProp($target_scenes, 'three_view_image_url', ''));
  1254. // 兼容 versions 传入数组或 JSON 字符串
  1255. $versions = getProp($target_scenes, 'versions', null);
  1256. if (is_string($versions) && $versions !== '') {
  1257. $decoded_versions = json_decode($versions, true);
  1258. if (is_array($decoded_versions)) {
  1259. $versions = $decoded_versions;
  1260. }
  1261. }
  1262. $product_type = 2; // 2=场景
  1263. // 查找或创建以script_name命名的文件夹
  1264. $folder = DB::table('mp_products')
  1265. ->where('cpid', $cpid)
  1266. ->where('type', 2) // 文件夹类型
  1267. ->where('product', $product_type) // 场景类型
  1268. ->where('product_name', $script_name)
  1269. ->where('parent_id', 0)
  1270. ->where('is_deleted', 0)
  1271. ->first();
  1272. if (!$folder) {
  1273. // 创建文件夹
  1274. $folder_id = DB::table('mp_products')->insertGetId([
  1275. 'user_id' => $uid,
  1276. 'cpid' => $cpid,
  1277. 'type' => 2, // 文件夹
  1278. 'product' => $product_type, // 场景类型
  1279. 'parent_id' => 0,
  1280. 'level' => 1,
  1281. 'product_name' => $script_name,
  1282. 'sort_order' => time(),
  1283. 'is_deleted' => 0,
  1284. 'created_at' => date('Y-m-d H:i:s'),
  1285. 'updated_at' => date('Y-m-d H:i:s')
  1286. ]);
  1287. } else {
  1288. $folder_id = $folder->id;
  1289. }
  1290. // 查找该文件夹下是否已存在同名资产
  1291. $existing_product = DB::table('mp_products')
  1292. ->where('cpid', $cpid)
  1293. ->where('type', 1) // 资产类型
  1294. ->where('product', $product_type)
  1295. ->where('parent_id', $folder_id)
  1296. ->where('product_name', $product_name)
  1297. ->where('is_deleted', 0)
  1298. ->first();
  1299. if ($existing_product) {
  1300. // 更新已存在的资产
  1301. $updateData = [
  1302. 'pic_task_status' => '生成成功'
  1303. ];
  1304. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1305. if ($url) $updateData['url'] = $url;
  1306. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1307. if (is_array($target_scenes) && array_key_exists('three_view_image_url', $target_scenes)) {
  1308. $updateData['three_view_image_url'] = trim(getProp($target_scenes, 'three_view_image_url', ''));
  1309. }
  1310. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1311. if (is_array($versions)) {
  1312. $updateData['versions'] = json_encode($versions, 256);
  1313. }
  1314. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1315. DB::table('mp_products')
  1316. ->where('id', $existing_product->id)
  1317. ->update($updateData);
  1318. $product_id = $existing_product->id;
  1319. } else {
  1320. // 创建新资产
  1321. $product_id = DB::table('mp_products')->insertGetId([
  1322. 'user_id' => $uid,
  1323. 'cpid' => $cpid,
  1324. 'type' => 1, // 资产
  1325. 'product' => $product_type, // 场景
  1326. 'parent_id' => $folder_id,
  1327. 'level' => 2,
  1328. 'product_name' => $product_name,
  1329. 'url' => $url,
  1330. 'three_view_image_url' => $three_view_image_url,
  1331. 'pic_prompt' => $pic_prompt,
  1332. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1333. 'sort_order' => time(),
  1334. 'is_deleted' => 0,
  1335. 'pic_task_status' => '生成成功',
  1336. 'created_at' => date('Y-m-d H:i:s'),
  1337. 'updated_at' => date('Y-m-d H:i:s')
  1338. ]);
  1339. }
  1340. // 建立或更新绑定关系
  1341. $existing_mapping = DB::table('mp_script_product_mappings')
  1342. ->where('script_id', $script_id)
  1343. ->where('product_id', $product_id)
  1344. ->where('episode_number', $episode_number)
  1345. ->first();
  1346. if (!$existing_mapping) {
  1347. // 创建绑定关系
  1348. DB::table('mp_script_product_mappings')->insert([
  1349. 'script_id' => $script_id,
  1350. 'product_id' => $product_id,
  1351. 'episode_number' => $episode_number,
  1352. 'created_at' => date('Y-m-d H:i:s'),
  1353. 'updated_at' => date('Y-m-d H:i:s')
  1354. ]);
  1355. }
  1356. }
  1357. }
  1358. }
  1359. } catch (\Exception $e) {
  1360. dLog('anime')->error('更新剧集场景失败', [
  1361. 'anime_id' => $anime_id,
  1362. 'episode_id' => $episode_id,
  1363. 'error' => $e->getMessage()
  1364. ]);
  1365. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1366. }
  1367. return true;
  1368. }
  1369. public function changeEpisodeProps($data) {
  1370. $anime_id = getProp($data, 'anime_id');
  1371. $episode_id = getProp($data, 'episode_id');
  1372. $target_props = getProp($data, 'props');
  1373. // 删除标志优先取最外层入参 is_deleted,兼容道具对象内部(props.is_deleted)的传参
  1374. $is_deleted = getProp($data, 'is_deleted', getProp($target_props, 'is_deleted', 0));
  1375. // 控制字段不随道具内容写入分集props存储
  1376. if (is_array($target_props)) {
  1377. unset($target_props['is_deleted']);
  1378. }
  1379. // 参数验证
  1380. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1381. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1382. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1383. // 验证剧集是否存在
  1384. $episode = DB::table('mp_anime_episodes')
  1385. ->where('anime_id', $anime_id)
  1386. ->where('id', $episode_id)
  1387. ->first();
  1388. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1389. $props = json_decode(getProp($episode, 'props'), true);
  1390. // 获取anime信息,检查是否有关联的script_id
  1391. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1392. if (!$anime) Utils::throwError('20003:动漫不存在');
  1393. $script_id = getProp($anime, 'script_id');
  1394. $episode_number = getProp($episode, 'episode_number', 1);
  1395. $uid = Site::getUid();
  1396. $cpid = Site::getCpid();
  1397. try {
  1398. $target_prop_name = getProp($target_props, 'prop');
  1399. if (empty($target_prop_name)) {
  1400. Utils::throwError('20003:道具名称不能为空');
  1401. }
  1402. // 如果是删除操作
  1403. if ($is_deleted == 1) {
  1404. // 从道具列表中移除该道具
  1405. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1406. return getProp($prop, 'prop') !== $target_prop_name;
  1407. }));
  1408. // 更新道具列表
  1409. $result = DB::table('mp_anime_episodes')
  1410. ->where('anime_id', $anime_id)
  1411. ->where('id', $episode_id)
  1412. ->update([
  1413. 'props' => json_encode($props, 256),
  1414. 'updated_at' => date('Y-m-d H:i:s')
  1415. ]);
  1416. if ($result === false) {
  1417. Utils::throwError('20003:删除道具失败');
  1418. }
  1419. } else {
  1420. // 新增或更新操作
  1421. $prop_found = false;
  1422. $is_new_prop = false;
  1423. // 查找并更新已存在的道具
  1424. foreach($props as &$prop) {
  1425. if (getProp($prop, 'prop') === $target_prop_name) {
  1426. $prop = $target_props;
  1427. $prop_found = true;
  1428. break;
  1429. }
  1430. }
  1431. // 如果道具不存在,则新增
  1432. if (!$prop_found) {
  1433. $props[] = $target_props;
  1434. $is_new_prop = true;
  1435. }
  1436. // 更新道具列表
  1437. $result = DB::table('mp_anime_episodes')
  1438. ->where('anime_id', $anime_id)
  1439. ->where('id', $episode_id)
  1440. ->update([
  1441. 'props' => json_encode($props, 256),
  1442. 'updated_at' => date('Y-m-d H:i:s')
  1443. ]);
  1444. if ($result === false) {
  1445. Utils::throwError('20003:更新道具列表失败');
  1446. }
  1447. // 如果有关联的script_id,则同步到mp_products表
  1448. if ($script_id) {
  1449. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1450. $script = DB::table('mp_scripts')
  1451. ->where('id', $script_id)
  1452. ->where('user_id', $uid)
  1453. ->where('is_deleted', 0)
  1454. ->first();
  1455. if ($script) {
  1456. $script_name = $script->script_name ?? 'script_' . $script_id;
  1457. $product_name = getProp($target_props, 'prop');
  1458. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1459. $url = getProp($target_props, 'url', '');
  1460. $three_view_image_url = trim(getProp($target_props, 'three_view_image_url', ''));
  1461. // 兼容 versions 传入数组或 JSON 字符串
  1462. $versions = getProp($target_props, 'versions', null);
  1463. if (is_string($versions) && $versions !== '') {
  1464. $decoded_versions = json_decode($versions, true);
  1465. if (is_array($decoded_versions)) {
  1466. $versions = $decoded_versions;
  1467. }
  1468. }
  1469. $product_type = 3; // 3=道具
  1470. // 查找或创建以script_name命名的文件夹
  1471. $folder = DB::table('mp_products')
  1472. ->where('cpid', $cpid)
  1473. ->where('type', 2) // 文件夹类型
  1474. ->where('product', $product_type) // 道具类型
  1475. ->where('product_name', $script_name)
  1476. ->where('parent_id', 0)
  1477. ->where('is_deleted', 0)
  1478. ->first();
  1479. if (!$folder) {
  1480. // 创建文件夹
  1481. $folder_id = DB::table('mp_products')->insertGetId([
  1482. 'user_id' => $uid,
  1483. 'cpid' => $cpid,
  1484. 'type' => 2, // 文件夹
  1485. 'product' => $product_type, // 道具类型
  1486. 'parent_id' => 0,
  1487. 'level' => 1,
  1488. 'product_name' => $script_name,
  1489. 'sort_order' => time(),
  1490. 'is_deleted' => 0,
  1491. 'created_at' => date('Y-m-d H:i:s'),
  1492. 'updated_at' => date('Y-m-d H:i:s')
  1493. ]);
  1494. } else {
  1495. $folder_id = $folder->id;
  1496. }
  1497. // 查找该文件夹下是否已存在同名资产
  1498. $existing_product = DB::table('mp_products')
  1499. ->where('cpid', $cpid)
  1500. ->where('type', 1) // 资产类型
  1501. ->where('product', $product_type)
  1502. ->where('parent_id', $folder_id)
  1503. ->where('product_name', $product_name)
  1504. ->where('is_deleted', 0)
  1505. ->first();
  1506. if ($existing_product) {
  1507. // 更新已存在的资产
  1508. $updateData = [
  1509. 'pic_task_status' => '生成成功'
  1510. ];
  1511. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1512. if ($url) $updateData['url'] = $url;
  1513. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1514. if (is_array($target_props) && array_key_exists('three_view_image_url', $target_props)) {
  1515. $updateData['three_view_image_url'] = trim(getProp($target_props, 'three_view_image_url', ''));
  1516. }
  1517. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1518. if (is_array($versions)) {
  1519. $updateData['versions'] = json_encode($versions, 256);
  1520. }
  1521. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1522. DB::table('mp_products')
  1523. ->where('id', $existing_product->id)
  1524. ->update($updateData);
  1525. $product_id = $existing_product->id;
  1526. } else {
  1527. // 创建新资产
  1528. $product_id = DB::table('mp_products')->insertGetId([
  1529. 'user_id' => $uid,
  1530. 'cpid' => $cpid,
  1531. 'type' => 1, // 资产
  1532. 'product' => $product_type, // 道具
  1533. 'parent_id' => $folder_id,
  1534. 'level' => 2,
  1535. 'product_name' => $product_name,
  1536. 'url' => $url,
  1537. 'three_view_image_url' => $three_view_image_url,
  1538. 'pic_prompt' => $pic_prompt,
  1539. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1540. 'sort_order' => time(),
  1541. 'is_deleted' => 0,
  1542. 'pic_task_status' => '生成成功',
  1543. 'created_at' => date('Y-m-d H:i:s'),
  1544. 'updated_at' => date('Y-m-d H:i:s')
  1545. ]);
  1546. }
  1547. // 建立或更新绑定关系
  1548. $existing_mapping = DB::table('mp_script_product_mappings')
  1549. ->where('script_id', $script_id)
  1550. ->where('product_id', $product_id)
  1551. ->where('episode_number', $episode_number)
  1552. ->first();
  1553. if (!$existing_mapping) {
  1554. // 创建绑定关系
  1555. DB::table('mp_script_product_mappings')->insert([
  1556. 'script_id' => $script_id,
  1557. 'product_id' => $product_id,
  1558. 'episode_number' => $episode_number,
  1559. 'created_at' => date('Y-m-d H:i:s'),
  1560. 'updated_at' => date('Y-m-d H:i:s')
  1561. ]);
  1562. }
  1563. }
  1564. }
  1565. }
  1566. } catch (\Exception $e) {
  1567. dLog('anime')->error('更新剧集道具失败', [
  1568. 'anime_id' => $anime_id,
  1569. 'episode_id' => $episode_id,
  1570. 'error' => $e->getMessage()
  1571. ]);
  1572. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1573. }
  1574. return true;
  1575. }
  1576. public function editSegment($data) {
  1577. $segment_id = getProp($data, 'segment_id');
  1578. $segment_content = getProp($data, 'segment_content');
  1579. $image_url = getProp($data, 'image_url');
  1580. $video_url = getProp($data, 'video_url');
  1581. // 参数验证
  1582. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1583. // 验证分镜是否存在
  1584. $segment = DB::table('mp_episode_segments')
  1585. ->where('segment_id', $segment_id)
  1586. ->first();
  1587. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1588. $dubTaskId = 0;
  1589. try {
  1590. DB::beginTransaction();
  1591. // 准备更新数据
  1592. $update_data = [
  1593. 'updated_at' => date('Y-m-d H:i:s')
  1594. ];
  1595. if ($segment_content) {
  1596. // 先将segment_content赋值到update_data
  1597. $update_data['segment_content'] = $segment_content;
  1598. // 使用现有方法分析segment_content,提取各个字段
  1599. $this->handleSegmentContent($update_data);
  1600. // 如果有对话内容,创建视频配音合成任务
  1601. $dialogue = getProp($update_data, 'dialogue');
  1602. if (!empty($dialogue)) {
  1603. $now = date('Y-m-d H:i:s');
  1604. $generate_json = [
  1605. 'text' => $dialogue,
  1606. 'role' => getProp($update_data, 'voice_actor'),
  1607. 'voice_type' => getProp($update_data, 'voice_type'),
  1608. 'voice_name' => getProp($update_data, 'voice_name'),
  1609. 'emotion' => getProp($update_data, 'emotion'),
  1610. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1611. 'gender' => getProp($update_data, 'gender'),
  1612. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1613. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1614. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1615. 'pitch' => getProp($update_data, 'pitch', 0),
  1616. ];
  1617. // 插入视频配音合成任务
  1618. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1619. 'alias_segment_id' => $segment_id,
  1620. 'generate_status' => '执行中',
  1621. 'audio_url' => '',
  1622. 'generate_json' => json_encode($generate_json, 256),
  1623. 'created_at' => $now,
  1624. 'updated_at' => $now,
  1625. ]);
  1626. if (!$dubTaskId) {
  1627. Utils::throwError('20003:创建配音任务失败!');
  1628. }
  1629. $update_data['audio_url'] = '';
  1630. } else {
  1631. // dialogue为空时,直接写入默认音频信息
  1632. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1633. $update_data['audio_duration'] = 2.0;
  1634. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1635. }
  1636. }
  1637. if ($image_url) {
  1638. $update_data['img_url'] = $image_url;
  1639. // 同时写入一个简单的图片生成任务
  1640. $pic_task = [
  1641. 'alias_segment_id' => $segment_id,
  1642. 'ref_img_url' => json_encode([]),
  1643. 'status' => 'success',
  1644. 'result_url' => json_encode([$image_url], 256),
  1645. 'model' => '',
  1646. 'created_at' => date('Y-m-d H:i:s'),
  1647. 'updated_at' => date('Y-m-d H:i:s'),
  1648. ];
  1649. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1650. }
  1651. if ($video_url) {
  1652. $update_data['origin_video_url'] = $video_url;
  1653. $compressed_video_url = compressVideo($video_url);
  1654. $update_data['current_type'] = 2;
  1655. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1656. // 同时写入一个简单的视频生成任务
  1657. $video_task = [
  1658. 'alias_segment_id' => $segment_id,
  1659. 'status' => 'success',
  1660. 'result_url' => $update_data['origin_video_url'],
  1661. 'compressed_url' => $update_data['video_url'],
  1662. 'created_at' => date('Y-m-d H:i:s'),
  1663. 'updated_at' => date('Y-m-d H:i:s'),
  1664. ];
  1665. DB::table('mp_generate_video_tasks')->insert($video_task);
  1666. }
  1667. // 更新分镜信息
  1668. $result = DB::table('mp_episode_segments')
  1669. ->where('segment_id', $segment_id)
  1670. ->update($update_data);
  1671. if ($result === false) {
  1672. Utils::throwError('20003:更新分镜剧本失败');
  1673. }
  1674. DB::commit();
  1675. // 如果有创建音频生成任务则调用API
  1676. if ($dubTaskId) {
  1677. // 请求远程服务器执行生成
  1678. $client = new Client(['timeout' => 300, 'verify' => false]);
  1679. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1680. $response = $result->getBody()->getContents();
  1681. $response_arr = json_decode($response, true);
  1682. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1683. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1684. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1685. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1686. Utils::throwError('20003:火山生成音频失败');
  1687. }
  1688. }
  1689. return true;
  1690. } catch (\Exception $e) {
  1691. DB::rollBack();
  1692. dLog('anime')->error('更新分镜剧本失败', [
  1693. 'segment_id' => $segment_id,
  1694. 'error' => $e->getMessage()
  1695. ]);
  1696. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1697. }
  1698. }
  1699. public function batchSetSegmentPics($data) {
  1700. $anime_id = getProp($data, 'anime_id');
  1701. $episode_id = getProp($data, 'episode_id');
  1702. $ratio = getProp($data, 'ratio');
  1703. $dimensions = $this->getRatioDimensions($ratio);
  1704. $width = $dimensions['width'];
  1705. $height = $dimensions['height'];
  1706. if (!$anime_id || !$episode_id) {
  1707. Utils::throwError('1002:请选择剧集');
  1708. }
  1709. // 获取剧集信息
  1710. $episode = DB::table('mp_anime_episodes')
  1711. ->where('anime_id', $anime_id)
  1712. ->where('id', $episode_id)
  1713. ->where('is_default', 1)
  1714. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1715. ->first();
  1716. if (!$episode) {
  1717. Utils::throwError('20003:该剧集不存在');
  1718. }
  1719. $model = getProp($data, 'model');
  1720. if (!$model) {
  1721. $model = getProp($episode, 'image_model');
  1722. if (!$model) {
  1723. // episode表也没有,使用默认值
  1724. $model = 'gpt-image-2';
  1725. }
  1726. }
  1727. // 验证模型是否在可用模型表中
  1728. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1729. $model = 'gpt-image-2';
  1730. }
  1731. $roles = json_decode(getProp($episode, 'roles'), true);
  1732. if (!$roles) {
  1733. Utils::throwError('20003:角色信息格式错误');
  1734. }
  1735. // 构建角色名称到参考图的映射
  1736. $role_map = [];
  1737. foreach ($roles as $role) {
  1738. $role_name = getProp($role, 'role');
  1739. $role_url = getProp($role, 'url');
  1740. if (!empty($role_name) && !empty($role_url)) {
  1741. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1742. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1743. // $role_map[$base_name] = $role_url;
  1744. // 同时保存完整名称的映射
  1745. $role_map[$role_name] = $role_url;
  1746. }
  1747. }
  1748. $scenes = json_decode(getProp($episode, 'roles'), true);
  1749. if (!$scenes) {
  1750. Utils::throwError('20003:场景信息格式错误');
  1751. }
  1752. // 构建角色名称到参考图的映射
  1753. $scene_map = [];
  1754. foreach ($scenes as $scene) {
  1755. $scene_name = getProp($scene, 'scene');
  1756. $scene_url = getProp($scene, 'url');
  1757. if (!empty($scene_name) && !empty($scene_url)) {
  1758. $scene_map[$scene_name] = $scene_url;
  1759. }
  1760. }
  1761. // 获取所有分镜信息
  1762. $segments = DB::table('mp_episode_segments')
  1763. ->where('anime_id', $anime_id)
  1764. ->where('episode_id', $episode_id)
  1765. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1766. ->orderBy('segment_number')
  1767. ->get()
  1768. ->toArray();
  1769. if (empty($segments)) {
  1770. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1771. }
  1772. // 保存图片比例
  1773. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1774. $updated_segments = [];
  1775. $failed_segments = [];
  1776. // 批量为每个分镜生成图片任务
  1777. foreach ($segments as $segment) {
  1778. $segment_id = $segment->segment_id;
  1779. $segment_content = $segment->segment_content;
  1780. if (empty($segment_content)) {
  1781. $failed_segments[] = [
  1782. 'segment_id' => $segment_id,
  1783. 'error' => '分镜内容为空'
  1784. ];
  1785. continue;
  1786. }
  1787. try {
  1788. $dubTaskId = 0;
  1789. // 解析分镜内容,提取画面描述作为主要提示词
  1790. $prompt = $segment_content;
  1791. $ref_img_urls = [];
  1792. // 分镜场景
  1793. $scene = getProp($segment, 'scene');
  1794. $matched_scene = '';
  1795. if (isset($scene_map[$scene])) {
  1796. $img_index = count($ref_img_urls) + 1;
  1797. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1798. $ref_img_urls[] = $scene_map[$scene];
  1799. $matched_scene = $scene;
  1800. }
  1801. // 分镜角色
  1802. $characters = getProp($segment, 'characters');
  1803. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1804. $roles = explode(',', $characters);
  1805. // 从分镜内容中提取涉及的角色
  1806. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1807. // 获取匹配角色的参考图
  1808. foreach ($segment_characters as $character) {
  1809. if (isset($role_map[$character])) {
  1810. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1811. $img_index = count($ref_img_urls) + 1;
  1812. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1813. $ref_img_urls[] = $role_map[$character];
  1814. }
  1815. }
  1816. // 如果没有找到匹配的角色参考图,不使用参考图
  1817. if (empty($ref_img_urls)) {
  1818. $ref_img_urls = [];
  1819. }
  1820. // 准备生成任务参数
  1821. $params = [
  1822. 'model' => $model,
  1823. 'alias_segment_id' => $segment_id,
  1824. 'prompt' => $prompt,
  1825. 'ref_img_urls' => $ref_img_urls,
  1826. 'width' => $width,
  1827. 'height' => $height,
  1828. ];
  1829. // 优化提示词(不要生成字幕)
  1830. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1831. // $task_id = mt_rand(100000, 999999);
  1832. // 调用AI图片生成服务
  1833. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1834. $task_id = $task->id;
  1835. if (!$task_id) {
  1836. $failed_segments[] = [
  1837. 'segment_id' => $segment_id,
  1838. 'error' => '创建生成任务失败'
  1839. ];
  1840. continue;
  1841. }
  1842. $update_data = [
  1843. 'pic_task_id' => $task_id,
  1844. 'pic_task_status' => '生成中',
  1845. 'audio_url' => '',
  1846. 'updated_at' => date('Y-m-d H:i:s')
  1847. ];
  1848. // 如果有对话内容,创建视频配音合成任务
  1849. $dialogue = getProp($segment, 'dialogue');
  1850. if (!empty($dialogue)) {
  1851. $now = date('Y-m-d H:i:s');
  1852. $generate_json = [
  1853. 'text' => $dialogue,
  1854. 'role' => getProp($segment, 'voice_actor'),
  1855. 'voice_type' => getProp($segment, 'voice_type'),
  1856. 'voice_name' => getProp($segment, 'voice_name'),
  1857. 'emotion' => getProp($segment, 'emotion'),
  1858. 'emotion_type' => getProp($segment, 'emotion_type'),
  1859. 'gender' => getProp($segment, 'gender'),
  1860. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1861. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1862. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1863. 'pitch' => getProp($segment, 'pitch', 0),
  1864. ];
  1865. // 插入视频配音合成任务
  1866. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1867. 'alias_segment_id' => $segment_id,
  1868. 'generate_status' => '执行中',
  1869. 'audio_url' => '',
  1870. 'generate_json' => json_encode($generate_json, 256),
  1871. 'created_at' => $now,
  1872. 'updated_at' => $now,
  1873. ]);
  1874. if (!$dubTaskId) {
  1875. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1876. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1877. // Utils::throwError('20003:创建配音任务失败!');
  1878. }
  1879. } else {
  1880. // dialogue为空时,直接写入默认音频信息到分镜表
  1881. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1882. $update_data['audio_duration'] = 2.0;
  1883. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1884. }
  1885. // 更新分镜的任务信息
  1886. $update_result = DB::table('mp_episode_segments')
  1887. ->where('segment_id', $segment_id)
  1888. ->update($update_data);
  1889. // 如果是第一集的首帧图片,则存入待更新数组
  1890. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1891. Redis::sadd('anime_first_frame_urls', $segment_id);
  1892. }
  1893. if ($update_result) {
  1894. $updated_segments[] = [
  1895. 'segment_id' => $segment_id,
  1896. 'task_id' => $task_id,
  1897. 'status' => '生成中',
  1898. 'matched_scenes' => $matched_scene,
  1899. 'matched_roles' => $segment_characters,
  1900. 'ref_urls_count' => count($ref_img_urls)
  1901. ];
  1902. } else {
  1903. $failed_segments[] = [
  1904. 'segment_id' => $segment_id,
  1905. 'error' => '更新分镜任务状态失败'
  1906. ];
  1907. }
  1908. if ($dubTaskId) {
  1909. sleep(1);
  1910. // 请求远程服务器执行生成
  1911. $client = new Client(['timeout' => 300, 'verify' => false]);
  1912. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1913. $response = $result->getBody()->getContents();
  1914. $response_arr = json_decode($response, true);
  1915. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1916. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1917. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1918. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1919. }
  1920. }
  1921. } catch (\Exception $e) {
  1922. $failed_segments[] = [
  1923. 'segment_id' => $segment_id,
  1924. 'error' => $e->getMessage()
  1925. ];
  1926. }
  1927. }
  1928. // 更新剧集生成状态
  1929. if (!empty($updated_segments)) {
  1930. DB::table('mp_anime_episodes')
  1931. ->where('id', $episode_id)
  1932. ->update([
  1933. 'is_generated' => 1,
  1934. 'updated_at' => date('Y-m-d H:i:s')
  1935. ]);
  1936. }
  1937. return [
  1938. 'success_count' => count($updated_segments),
  1939. 'failed_count' => count($failed_segments),
  1940. 'success_segments' => $updated_segments,
  1941. 'failed_segments' => $failed_segments,
  1942. 'total_segments' => count($segments)
  1943. ];
  1944. }
  1945. public function reGenerateSegment($data) {
  1946. $segment_id = getProp($data, 'segment_id');
  1947. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1948. $anime_id = getProp($segment, 'anime_id');
  1949. $episode_id = getProp($segment, 'episode_id');
  1950. $episode_number = getProp($segment, 'episode_number');
  1951. $segment_content = getProp($data, 'segment_content');
  1952. $ratio = getProp($data, 'ratio');
  1953. if (!$ratio) {
  1954. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1955. if (!$ratio) $ratio = '9:16';
  1956. }
  1957. $dimensions = $this->getRatioDimensions($ratio);
  1958. $width = $dimensions['width'];
  1959. $height = $dimensions['height'];
  1960. if (!$anime_id || !$episode_id) {
  1961. Utils::throwError('1002:请选择分镜');
  1962. }
  1963. // 使用文生文模型重新解析segment_content
  1964. if (!empty($segment_content)) {
  1965. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1966. }
  1967. // 获取动漫的角色信息(包含参考图)
  1968. $anime = DB::table('mp_animes')
  1969. ->where('id', $anime_id)
  1970. ->select('roles', 'scenes')
  1971. ->first();
  1972. if (!$anime || !$anime->roles) {
  1973. Utils::throwError('20003:未找到角色信息');
  1974. }
  1975. $roles = json_decode($anime->roles, true);
  1976. if (!$roles) {
  1977. Utils::throwError('20003:角色信息格式错误');
  1978. }
  1979. // 构建角色名称到参考图的映射
  1980. $role_map = [];
  1981. foreach ($roles as $role) {
  1982. $role_name = getProp($role, 'role');
  1983. $role_url = getProp($role, 'url');
  1984. if (!empty($role_name) && !empty($role_url)) {
  1985. $role_map[$role_name] = $role_url;
  1986. }
  1987. }
  1988. $scenes = json_decode($anime->scenes, true);
  1989. if (!$scenes) {
  1990. Utils::throwError('20003:角色信息格式错误');
  1991. }
  1992. // 构建角色名称到参考图的映射
  1993. $scene_map = [];
  1994. foreach ($scenes as $scene) {
  1995. $scene_name = getProp($scene, 'scene');
  1996. $scene_url = getProp($scene, 'url');
  1997. if (!empty($scene_name) && !empty($scene_url)) {
  1998. $scene_map[$scene_name] = $scene_url;
  1999. }
  2000. }
  2001. $segment_id = $segment->segment_id;
  2002. $original_segment_content = $segment->segment_content;
  2003. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2004. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2005. if (empty($final_segment_content)) {
  2006. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2007. }
  2008. try {
  2009. $dubTaskId = 0;
  2010. // 分镜剧本数组
  2011. $update_data = [
  2012. 'segment_content' => $final_segment_content,
  2013. 'pic_task_status' => '生成中',
  2014. 'updated_at' => date('Y-m-d H:i:s')
  2015. ];
  2016. // 解析分镜内容,提取画面描述作为主要提示词
  2017. $prompt = $final_segment_content;
  2018. $ref_img_urls = [];
  2019. // 分镜场景
  2020. $scene = getProp($data, 'scene');
  2021. if ($scene) {
  2022. $matched_scene = '';
  2023. if (isset($scene_map[$scene])) {
  2024. $img_index = count($ref_img_urls) + 1;
  2025. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2026. $ref_img_urls[] = $scene_map[$scene];
  2027. $matched_scene = $scene;
  2028. }
  2029. $update_data['scene'] = $scene;
  2030. }
  2031. // 分镜角色
  2032. $characters = getProp($data, 'characters');
  2033. if ($characters) {
  2034. $update_data['characters'] = $characters;
  2035. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2036. $characters = explode(',', $characters);
  2037. // 从分镜内容中提取涉及的角色
  2038. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2039. // 获取匹配角色的参考图
  2040. foreach ($segment_characters as $character) {
  2041. if (isset($role_map[$character])) {
  2042. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2043. $img_index = count($ref_img_urls) + 1;
  2044. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2045. $ref_img_urls[] = $role_map[$character];
  2046. }
  2047. }
  2048. }
  2049. // 如果没有找到匹配的角色参考图,不使用参考图
  2050. if (empty($ref_img_urls)) {
  2051. $ref_img_urls = [];
  2052. }
  2053. // 准备生成任务参数
  2054. $params = [
  2055. 'alias_segment_id' => $segment_id,
  2056. 'prompt' => $prompt,
  2057. 'ref_img_urls' => $ref_img_urls,
  2058. 'width' => $width,
  2059. 'height' => $height,
  2060. ];
  2061. // 优化提示词(不要生成字幕)
  2062. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  2063. // 调用AI图片生成服务
  2064. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2065. $task_id = $task->id;
  2066. if (!$task_id) {
  2067. Utils::throwError('20003:创建生成任务失败!');
  2068. }
  2069. $update_data['pic_task_id'] = $task_id;
  2070. // 更新分镜剧本信息
  2071. $this->handleSegmentContent($update_data);
  2072. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2073. if ($segment_content) {
  2074. $dialogue = getProp($update_data, 'dialogue');
  2075. if (!empty($dialogue)) {
  2076. $now = date('Y-m-d H:i:s');
  2077. $generate_json = [
  2078. 'text' => $dialogue,
  2079. 'role' => getProp($update_data, 'voice_actor'),
  2080. 'voice_type' => getProp($update_data, 'voice_type'),
  2081. 'voice_name' => getProp($update_data, 'voice_name'),
  2082. 'emotion' => getProp($update_data, 'emotion'),
  2083. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2084. 'gender' => getProp($update_data, 'gender'),
  2085. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2086. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2087. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2088. 'pitch' => getProp($update_data, 'pitch', 0),
  2089. ];
  2090. // 插入视频配音合成任务
  2091. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2092. 'alias_segment_id' => $segment_id,
  2093. 'generate_status' => '执行中',
  2094. 'audio_url' => '',
  2095. 'generate_json' => json_encode($generate_json, 256),
  2096. 'created_at' => date('Y-m-d H:i:s'),
  2097. 'updated_at' => date('Y-m-d H:i:s'),
  2098. ]);
  2099. if (!$dubTaskId) {
  2100. Utils::throwError('20003:创建配音任务失败!');
  2101. }
  2102. $update_data['audio_url'] = '';
  2103. } else {
  2104. // dialogue为空时,直接写入默认音频信息
  2105. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2106. $update_data['audio_duration'] = 2.0;
  2107. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2108. }
  2109. }
  2110. $boolen = DB::table('mp_episode_segments')
  2111. ->where('segment_id', $segment_id)
  2112. ->update($update_data);
  2113. // 如果是第一集的首帧图片,则存入待更新数组
  2114. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2115. Redis::sadd('anime_first_frame_urls', $segment_id);
  2116. }
  2117. if ($dubTaskId) {
  2118. // 请求远程服务器执行生成
  2119. $client = new Client(['timeout' => 300, 'verify' => false]);
  2120. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2121. $response = $result->getBody()->getContents();
  2122. $response_arr = json_decode($response, true);
  2123. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2124. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2125. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2126. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2127. Utils::throwError('20003:火山生成音频失败');
  2128. }
  2129. }
  2130. } catch (\Exception $e) {
  2131. $failed_segments[] = [
  2132. 'segment_id' => $segment_id,
  2133. 'error' => $e->getMessage()
  2134. ];
  2135. }
  2136. // 创建任务之后先暂停10s等待异步任务完成
  2137. sleep(10);
  2138. $img_url = $this->loopGetPicTaskResult($task_id);
  2139. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2140. // 图片生成后新增对话记录
  2141. try {
  2142. $uid = Site::getUid();
  2143. $now = date('Y-m-d H:i:s');
  2144. // 使用AI反推图片提示词
  2145. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2146. // 保存对话记录
  2147. $records = [
  2148. [
  2149. 'uid' => $uid,
  2150. 'anime_id' => $anime_id,
  2151. 'sequence' => $episode_number,
  2152. 'role' => 'user',
  2153. 'content' => '重新生成',
  2154. 'segment_id' => $segment_id,
  2155. 'pic_task_id' => $task_id,
  2156. 'image_url' => '',
  2157. 'created_at' => $now,
  2158. 'updated_at' => $now
  2159. ],
  2160. [
  2161. 'uid' => $uid,
  2162. 'anime_id' => $anime_id,
  2163. 'sequence' => $episode_number,
  2164. 'role' => 'assistant',
  2165. 'content' => $pic_prompt,
  2166. 'segment_id' => $segment_id,
  2167. 'pic_task_id' => $task_id,
  2168. 'image_url' => $img_url,
  2169. 'created_at' => $now,
  2170. 'updated_at' => $now
  2171. ]
  2172. ];
  2173. DB::table('mp_anime_records')->insert($records);
  2174. } catch (\Exception $e) {
  2175. // 记录日志但不影响主流程
  2176. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2177. 'segment_id' => $segment_id,
  2178. 'img_url' => $img_url
  2179. ]);
  2180. }
  2181. return $img_url;
  2182. }
  2183. public function addSegment($data) {
  2184. $prev_segment_id = getProp($data, 'prev_segment_id');
  2185. $img_url = getProp($data, 'img_url');
  2186. $video_url = getProp($data, 'video_url');
  2187. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2188. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2189. $anime_id = getProp($segment, 'anime_id');
  2190. $episode_id = getProp($segment, 'episode_id');
  2191. $episode_number = getProp($segment, 'episode_number');
  2192. $segment_number = getProp($segment, 'segment_number');
  2193. $new_segment_number = $segment_number + 1;
  2194. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2195. // 分镜剧本数组
  2196. $insert_data = [
  2197. 'anime_id' => $anime_id,
  2198. 'episode_id' => $episode_id,
  2199. 'episode_number' => $episode_number,
  2200. 'act_number' => getProp($segment, 'act_number'),
  2201. 'act_title' => getProp($segment, 'act_title'),
  2202. 'segment_id' => $segment_id,
  2203. 'segment_number' => $new_segment_number,
  2204. 'segment_content' => '',
  2205. 'img_url' => '',
  2206. 'video_url' => '',
  2207. 'created_at' => date('Y-m-d H:i:s'),
  2208. 'updated_at' => date('Y-m-d H:i:s')
  2209. ];
  2210. if ($img_url) $insert_data['img_url'] = $img_url;
  2211. if ($video_url) {
  2212. $insert_data['origin_video_url'] = $video_url;
  2213. $insert_data['current_type'] = 2;
  2214. $compressed_video_url = compressVideo($video_url);
  2215. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2216. }
  2217. try {
  2218. DB::beginTransaction();
  2219. // 先更新序号
  2220. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2221. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2222. if (!$id) {
  2223. Utils::throwError('20003:新增分镜失败!');
  2224. }
  2225. }catch (\Exception $e) {
  2226. DB::rollBack();
  2227. Utils::throwError('20003:'.$e->getMessage());
  2228. }
  2229. DB::commit();
  2230. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2231. $segment = $segment ? (array)$segment : [];
  2232. return $segment;
  2233. // 以下代码暂弃用
  2234. $anime_id = getProp($segment, 'anime_id');
  2235. $episode_id = getProp($segment, 'episode_id');
  2236. $episode_number = getProp($segment, 'episode_number');
  2237. $segment_number = getProp($segment, 'segment_number');
  2238. $segment_content = getProp($data, 'segment_content');
  2239. $img_url = getProp($data, 'img_url');
  2240. $video_url = getProp($data, 'video_url');
  2241. $ratio = getProp($data, 'ratio');
  2242. $dimensions = $this->getRatioDimensions($ratio);
  2243. $width = $dimensions['width'];
  2244. $height = $dimensions['height'];
  2245. if (!$anime_id || !$episode_id) {
  2246. Utils::throwError('1002:请选择分镜');
  2247. }
  2248. // 使用文生文模型重新解析segment_content
  2249. if (!empty($segment_content)) {
  2250. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2251. }
  2252. // 获取动漫的角色信息(包含参考图)
  2253. $anime = DB::table('mp_animes')
  2254. ->where('id', $anime_id)
  2255. ->select('roles', 'scenes')
  2256. ->first();
  2257. if (!$anime || !$anime->roles) {
  2258. Utils::throwError('20003:未找到角色信息');
  2259. }
  2260. $roles = json_decode($anime->roles, true);
  2261. if (!$roles) {
  2262. Utils::throwError('20003:角色信息格式错误');
  2263. }
  2264. // 构建角色名称到参考图的映射
  2265. $role_map = [];
  2266. foreach ($roles as $role) {
  2267. $role_name = getProp($role, 'role');
  2268. $role_url = getProp($role, 'url');
  2269. if (!empty($role_name) && !empty($role_url)) {
  2270. $role_map[$role_name] = $role_url;
  2271. }
  2272. }
  2273. $scenes = json_decode($anime->scenes, true);
  2274. if (!$scenes) {
  2275. Utils::throwError('20003:角色信息格式错误');
  2276. }
  2277. // 构建角色名称到参考图的映射
  2278. $scene_map = [];
  2279. foreach ($scenes as $scene) {
  2280. $scene_name = getProp($scene, 'scene');
  2281. $scene_url = getProp($scene, 'url');
  2282. if (!empty($scene_name) && !empty($scene_url)) {
  2283. $scene_map[$scene_name] = $scene_url;
  2284. }
  2285. }
  2286. $segment_id = $segment->segment_id;
  2287. $original_segment_content = $segment->segment_content;
  2288. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2289. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2290. if (empty($final_segment_content)) {
  2291. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2292. }
  2293. try {
  2294. $dubTaskId = 0;
  2295. DB::beginTransaction();
  2296. $new_segment_number = $segment_number + 1;
  2297. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2298. // 分镜剧本数组
  2299. $insert_data = [
  2300. 'anime_id' => $anime_id,
  2301. 'episode_id' => $episode_id,
  2302. 'episode_number' => $episode_number,
  2303. 'act_number' => getProp($segment, 'act_number'),
  2304. 'act_title' => getProp($segment, 'act_title'),
  2305. 'segment_id' => $segment_id,
  2306. 'segment_number' => $new_segment_number,
  2307. 'segment_content' => $final_segment_content,
  2308. 'img_url' => $img_url,
  2309. 'video_url' => $video_url,
  2310. 'created_at' => date('Y-m-d H:i:s'),
  2311. 'updated_at' => date('Y-m-d H:i:s')
  2312. ];
  2313. // 更新分镜剧本信息
  2314. $this->handleSegmentContent($insert_data);
  2315. // 如果有对话内容,创建视频配音合成任务
  2316. $dialogue = getProp($insert_data, 'dialogue');
  2317. if (!empty($dialogue)) {
  2318. $now = date('Y-m-d H:i:s');
  2319. $generate_json = [
  2320. 'text' => $dialogue,
  2321. 'role' => getProp($insert_data, 'voice_actor'),
  2322. 'voice_type' => getProp($insert_data, 'voice_type'),
  2323. 'voice_name' => getProp($insert_data, 'voice_name'),
  2324. 'emotion' => getProp($insert_data, 'emotion'),
  2325. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2326. 'gender' => getProp($insert_data, 'gender'),
  2327. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2328. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2329. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2330. 'pitch' => getProp($insert_data, 'pitch', 0),
  2331. ];
  2332. // 插入视频配音合成任务
  2333. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2334. 'alias_segment_id' => $segment_id,
  2335. 'generate_status' => '执行中',
  2336. 'audio_url' => '',
  2337. 'generate_json' => json_encode($generate_json, 256),
  2338. 'created_at' => $now,
  2339. 'updated_at' => $now,
  2340. ]);
  2341. if (!$dubTaskId) {
  2342. Utils::throwError('20003:创建配音任务失败!');
  2343. }
  2344. $insert_data['audio_url'] = '';
  2345. } else {
  2346. // dialogue为空时,直接写入默认音频信息
  2347. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2348. $insert_data['audio_duration'] = 2.0;
  2349. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2350. }
  2351. // 如果没有上传图片则使用当前描述进行生成
  2352. if (!$img_url) {
  2353. // 解析分镜内容,提取画面描述作为主要提示词
  2354. $prompt = $final_segment_content;
  2355. $ref_img_urls = [];
  2356. // 分镜场景
  2357. $scene = getProp($insert_data, 'scene');
  2358. if ($scene) {
  2359. $matched_scene = '';
  2360. if (isset($scene_map[$scene])) {
  2361. $img_index = count($ref_img_urls) + 1;
  2362. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2363. $ref_img_urls[] = $scene_map[$scene];
  2364. $matched_scene = $scene;
  2365. }
  2366. $update_data['scene'] = $scene;
  2367. }
  2368. // 分镜角色
  2369. $characters = getProp($insert_data, 'characters');
  2370. if ($characters) {
  2371. $update_data['characters'] = $characters;
  2372. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2373. $characters = explode(',', $characters);
  2374. // 从分镜内容中提取涉及的角色
  2375. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2376. // 获取匹配角色的参考图
  2377. foreach ($segment_characters as $character) {
  2378. if (isset($role_map[$character])) {
  2379. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2380. $img_index = count($ref_img_urls) + 1;
  2381. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2382. $ref_img_urls[] = $role_map[$character];
  2383. }
  2384. }
  2385. }
  2386. // 如果没有找到匹配的角色参考图,不使用参考图
  2387. if (empty($ref_img_urls)) {
  2388. $ref_img_urls = [];
  2389. }
  2390. // 准备生成任务参数
  2391. $params = [
  2392. 'alias_segment_id' => $segment_id,
  2393. 'prompt' => $prompt,
  2394. 'ref_img_urls' => $ref_img_urls,
  2395. 'width' => $width,
  2396. 'height' => $height,
  2397. ];
  2398. // 调用AI图片生成服务
  2399. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2400. $task_id = $task->id;
  2401. // $task_id = 'whatever';
  2402. if (!$task_id) {
  2403. Utils::throwError('20003:创建生成任务失败!');
  2404. }
  2405. $insert_data['pic_task_status'] = '生成中';
  2406. $insert_data['pic_task_id'] = $task_id;
  2407. }
  2408. // 先更新序号
  2409. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2410. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2411. if (!$boolen) {
  2412. Utils::throwError('20003:新增分镜失败!');
  2413. }
  2414. // 如果是第一集的首帧图片,则存入待更新数组
  2415. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2416. Redis::sadd('anime_first_frame_urls', $segment_id);
  2417. }
  2418. if ($dubTaskId) {
  2419. // 请求远程服务器执行生成
  2420. $client = new Client(['timeout' => 300, 'verify' => false]);
  2421. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2422. $response = $result->getBody()->getContents();
  2423. $response_arr = json_decode($response, true);
  2424. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2425. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2426. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2427. Utils::throwError('20003:火山生成音频失败');
  2428. }
  2429. }
  2430. } catch (\Exception $e) {
  2431. DB::rollBack();
  2432. Utils::throwError('20003:'.$e->getMessage());
  2433. }
  2434. DB::commit();
  2435. // 创建任务之后先暂停10s等待异步任务完成
  2436. sleep(10);
  2437. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2438. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2439. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2440. $segment = $segment ? (array)$segment : [];
  2441. return $segment;
  2442. }
  2443. public function copySegment($data) {
  2444. $segment_id = getProp($data, 'segment_id');
  2445. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2446. if (!$segment) Utils::throwError('20003:请选择分镜');
  2447. $anime_id = getProp($segment, 'anime_id');
  2448. $episode_id = getProp($segment, 'episode_id');
  2449. $episode_number = getProp($segment, 'episode_number');
  2450. $segment_number = getProp($segment, 'segment_number');
  2451. $new_segment_id = 0;
  2452. try {
  2453. DB::beginTransaction();
  2454. $segment = (array)$segment;
  2455. unset($segment['id']);
  2456. $segment['segment_number'] += 1;
  2457. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2458. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2459. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2460. // 更新其他分镜序号
  2461. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2462. // 复制分镜
  2463. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2464. if (!$id) {
  2465. Utils::throwError('20003:复制分镜失败');
  2466. }
  2467. }catch (\Exception $e) {
  2468. DB::rollBack();
  2469. Utils::throwError('20003:'.$e->getMessage());
  2470. }
  2471. DB::commit();
  2472. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2473. $segment = $segment ? (array)$segment : [];
  2474. return $segment;
  2475. }
  2476. public function moveSegment($data) {
  2477. $segment_id = getProp($data, 'segment_id');
  2478. $target_segment_id = getProp($data, 'target_segment_id');
  2479. // 获取源分镜信息
  2480. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2481. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2482. // 获取目标分镜信息
  2483. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2484. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2485. $anime_id = getProp($source_segment, 'anime_id');
  2486. $episode_id = getProp($source_segment, 'episode_id');
  2487. $episode_number = getProp($source_segment, 'episode_number');
  2488. $source_segment_number = getProp($source_segment, 'segment_number');
  2489. $target_segment_number = getProp($target_segment, 'segment_number');
  2490. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2491. $target_anime_id = getProp($target_segment, 'anime_id');
  2492. $target_episode_number = getProp($target_segment, 'episode_number');
  2493. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2494. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2495. }
  2496. // 如果源分镜和目标分镜相同,无需移动
  2497. if ($source_segment_number == $target_segment_number) {
  2498. return true;
  2499. }
  2500. try {
  2501. DB::beginTransaction();
  2502. if ($source_segment_number < $target_segment_number) {
  2503. // 向后移动:源分镜移动到目标分镜之后
  2504. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2505. DB::table('mp_episode_segments')
  2506. ->where('anime_id', $anime_id)
  2507. ->where('episode_id', $episode_id)
  2508. ->where('segment_number', '>', $source_segment_number)
  2509. ->where('segment_number', '<=', $target_segment_number)
  2510. ->decrement('segment_number');
  2511. // 2. 将源分镜移动到目标分镜之后
  2512. $new_segment_number = $target_segment_number;
  2513. } else {
  2514. // 向前移动:源分镜移动到目标分镜之后
  2515. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2516. DB::table('mp_episode_segments')
  2517. ->where('anime_id', $anime_id)
  2518. ->where('episode_id', $episode_id)
  2519. ->where('segment_number', '>', $target_segment_number)
  2520. ->where('segment_number', '<', $source_segment_number)
  2521. ->increment('segment_number');
  2522. // 2. 将源分镜移动到目标分镜之后
  2523. $new_segment_number = $target_segment_number + 1;
  2524. }
  2525. // 3. 更新源分镜的序号
  2526. $update_result = DB::table('mp_episode_segments')
  2527. ->where('segment_id', $segment_id)
  2528. ->update([
  2529. 'segment_number' => $new_segment_number,
  2530. 'updated_at' => date('Y-m-d H:i:s')
  2531. ]);
  2532. if (!$update_result) {
  2533. Utils::throwError('20003:更新分镜序号失败');
  2534. }
  2535. DB::commit();
  2536. return true;
  2537. } catch (\Exception $e) {
  2538. DB::rollBack();
  2539. Utils::throwError('20003:' . $e->getMessage());
  2540. }
  2541. }
  2542. public function delSegment($data) {
  2543. $segment_id = getProp($data, 'segment_id');
  2544. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2545. if (!$segment) Utils::throwError('20003:请选择分镜');
  2546. $anime_id = getProp($segment, 'anime_id');
  2547. $episode_id = getProp($segment, 'episode_id');
  2548. $episode_number = getProp($segment, 'episode_number');
  2549. $segment_number = getProp($segment, 'segment_number');
  2550. try {
  2551. DB::beginTransaction();
  2552. // 删除分镜
  2553. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2554. if (!$boolen) {
  2555. Utils::throwError('20003:删除分镜失败');
  2556. }
  2557. // 更新其他分镜序号
  2558. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2559. }catch (\Exception $e) {
  2560. DB::rollBack();
  2561. Utils::throwError('20003:'.$e->getMessage());
  2562. }
  2563. DB::commit();
  2564. return true;
  2565. }
  2566. public function applySegment($data) {
  2567. $segment_id = getProp($data, 'segment_id');
  2568. $url = getProp($data, 'url');
  2569. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2570. if (!$url) Utils::throwError('20003:URL不能为空');
  2571. // 获取URL的文件扩展名
  2572. $urlPath = parse_url($url, PHP_URL_PATH);
  2573. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2574. // 定义图片和视频的扩展名
  2575. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2576. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2577. // 判断是图片还是视频
  2578. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2579. if (in_array($extension, $imageExtensions)) {
  2580. // 图片类型
  2581. $updateData['img_url'] = $url;
  2582. $updateData['current_type'] = 1;
  2583. } elseif (in_array($extension, $videoExtensions)) {
  2584. // 视频类型
  2585. $updateData['video_url'] = $url;
  2586. $updateData['current_type'] = 2;
  2587. } else {
  2588. Utils::throwError('20003:不支持的文件类型');
  2589. }
  2590. // 更新分镜表
  2591. $result = DB::table('mp_episode_segments')
  2592. ->where('segment_id', $segment_id)
  2593. ->update($updateData);
  2594. if (!$result) {
  2595. Utils::throwError('20003:更新分镜失败');
  2596. }
  2597. return true;
  2598. }
  2599. public function segmentHistory($data) {
  2600. $segment_id = getProp($data, 'segment_id');
  2601. // 获取历史图片
  2602. $pics = [];
  2603. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2604. foreach($pic_history as $task) {
  2605. $result_url = getProp($task, 'result_url');
  2606. if (is_json($result_url)) {
  2607. $pics = array_merge($pics, json_decode($result_url, true));
  2608. }else {
  2609. $pics[] = $result_url;
  2610. }
  2611. }
  2612. // 获取历史视频
  2613. $videos = [];
  2614. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2615. foreach($video_history as $task) {
  2616. $result_url = getProp($task, 'result_url');
  2617. if (is_json($result_url)) {
  2618. $videos = array_merge($videos, json_decode($result_url, true));
  2619. }else {
  2620. $videos[] = $result_url;
  2621. }
  2622. }
  2623. return compact('pics', 'videos');
  2624. }
  2625. public function addAct($data) {
  2626. $prev_act_id = getProp($data, 'prev_act_id');
  2627. $act_title = getProp($data, 'act_title', '');
  2628. $act_content = getProp($data, 'act_content', '');
  2629. $act_duration = getProp($data, 'act_duration', 5);
  2630. $video_url = getProp($data, 'video_url');
  2631. // 根据prev_act_id获取记录
  2632. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2633. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2634. $anime_id = getProp($prev_segment, 'anime_id');
  2635. $episode_id = getProp($prev_segment, 'episode_id');
  2636. $episode_number = getProp($prev_segment, 'episode_number');
  2637. $prev_act_number = getProp($prev_segment, 'act_number');
  2638. // 获取新的act_number
  2639. $new_act_number = $prev_act_number + 1;
  2640. try {
  2641. DB::beginTransaction();
  2642. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2643. DB::table('mp_episode_segments')
  2644. ->where('anime_id', $anime_id)
  2645. ->where('episode_id', $episode_id)
  2646. ->where('act_number', '>', $prev_act_number)
  2647. ->increment('act_number');
  2648. // 插入新片段记录
  2649. $insert_data = [
  2650. 'anime_id' => $anime_id,
  2651. 'episode_id' => $episode_id,
  2652. 'episode_number' => $episode_number,
  2653. 'act_number' => $new_act_number,
  2654. 'created_at' => date('Y-m-d H:i:s'),
  2655. 'updated_at' => date('Y-m-d H:i:s')
  2656. ];
  2657. if ($act_title) {
  2658. $insert_data['act_title'] = $act_title;
  2659. }
  2660. if ($act_content) {
  2661. $insert_data['act_content'] = $act_content;
  2662. }
  2663. if ($act_duration) {
  2664. $insert_data['act_duration'] = $act_duration;
  2665. }
  2666. if ($video_url) {
  2667. $insert_data['origin_video_url'] = $video_url;
  2668. $insert_data['current_type'] = 2;
  2669. $compressed_video_url = compressVideo($video_url);
  2670. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2671. }
  2672. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2673. if (!$id) {
  2674. Utils::throwError('20003:新增片段失败!');
  2675. }
  2676. DB::commit();
  2677. }catch (\Exception $e) {
  2678. DB::rollBack();
  2679. Utils::throwError('20003:'.$e->getMessage());
  2680. }
  2681. $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();
  2682. $segment = $segment ? (array)$segment : [];
  2683. return $segment;
  2684. }
  2685. public function editAct($data) {
  2686. $act_id = getProp($data, 'act_id');
  2687. $act_content = getProp($data, 'act_content');
  2688. $act_duration = getProp($data, 'act_duration');
  2689. $act_title = getProp($data, 'act_title');
  2690. $image_url = getProp($data, 'image_url');
  2691. $video_url = getProp($data, 'video_url');
  2692. // 参数验证
  2693. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2694. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2695. $segment = DB::table('mp_episode_segments')
  2696. ->where('id', $act_id)
  2697. ->first();
  2698. if (!$segment) Utils::throwError('20003:该片段不存在');
  2699. try {
  2700. DB::beginTransaction();
  2701. // 准备更新数据
  2702. $update_data = [
  2703. 'updated_at' => date('Y-m-d H:i:s')
  2704. ];
  2705. // 更新act相关字段
  2706. if (!empty($act_content)) {
  2707. $update_data['act_show_content'] = $act_content;
  2708. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2709. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2710. $shot_counter = 0;
  2711. $update_data['act_show_content'] = preg_replace_callback(
  2712. '/【(?:镜头|分镜)(\d+)】/u',
  2713. function($matches) use (&$shot_counter) {
  2714. $shot_counter++;
  2715. return '【镜头' . $shot_counter . '】';
  2716. },
  2717. $update_data['act_show_content']
  2718. );
  2719. }
  2720. if (!empty($act_duration)) {
  2721. $update_data['act_duration'] = $act_duration;
  2722. }
  2723. if (!empty($act_title)) {
  2724. $update_data['act_title'] = $act_title;
  2725. }
  2726. // 处理图片上传
  2727. if ($image_url) {
  2728. $update_data['img_url'] = $image_url;
  2729. $update_data['current_type'] = 1;
  2730. // 同时写入一个图片生成任务记录
  2731. if ($act_id) {
  2732. $pic_task = [
  2733. 'alias_act_id' => $act_id,
  2734. 'ref_img_url' => json_encode([]),
  2735. 'status' => 'success',
  2736. 'result_url' => json_encode([$image_url], 256),
  2737. 'model' => '',
  2738. 'created_at' => date('Y-m-d H:i:s'),
  2739. 'updated_at' => date('Y-m-d H:i:s'),
  2740. ];
  2741. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2742. }
  2743. }
  2744. // 处理视频上传
  2745. if ($video_url) {
  2746. $update_data['origin_video_url'] = $video_url;
  2747. $compressed_video_url = compressVideo($video_url);
  2748. $update_data['current_type'] = 2;
  2749. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2750. // 同时写入一个视频生成任务记录
  2751. if ($act_id) {
  2752. $video_task = [
  2753. 'alias_act_id' => $act_id,
  2754. 'status' => 'success',
  2755. 'result_url' => $update_data['origin_video_url'],
  2756. 'compressed_url' => $update_data['video_url'],
  2757. 'created_at' => date('Y-m-d H:i:s'),
  2758. 'updated_at' => date('Y-m-d H:i:s'),
  2759. ];
  2760. DB::table('mp_generate_video_tasks')->insert($video_task);
  2761. }
  2762. }
  2763. // 更新片段信息
  2764. $result = DB::table('mp_episode_segments')
  2765. ->where('id', $act_id)
  2766. ->update($update_data);
  2767. if ($result === false) {
  2768. Utils::throwError('20003:更新片段失败');
  2769. }
  2770. DB::commit();
  2771. // 返回新复制的记录
  2772. $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();
  2773. $new_segment = (array)$new_segment;
  2774. return $new_segment;
  2775. } catch (\Exception $e) {
  2776. DB::rollBack();
  2777. dLog('anime')->error('更新片段失败', [
  2778. 'act_id' => $act_id,
  2779. 'error' => $e->getMessage()
  2780. ]);
  2781. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2782. }
  2783. }
  2784. public function copyAct($data) {
  2785. $act_id = getProp($data, 'act_id');
  2786. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2787. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2788. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2789. $anime_id = getProp($source_segment, 'anime_id');
  2790. $episode_id = getProp($source_segment, 'episode_id');
  2791. $episode_number = getProp($source_segment, 'episode_number');
  2792. $act_number = getProp($source_segment, 'act_number');
  2793. try {
  2794. DB::beginTransaction();
  2795. // 新act的编号
  2796. $new_act_number = $act_number + 1;
  2797. // 更新后续所有act的act_number
  2798. DB::table('mp_episode_segments')
  2799. ->where('anime_id', $anime_id)
  2800. ->where('episode_id', $episode_id)
  2801. ->where('act_number', '>', $act_number)
  2802. ->increment('act_number');
  2803. // 复制该片段记录
  2804. $segment_data = (array)$source_segment;
  2805. unset($segment_data['id']);
  2806. $segment_data['video_url'] = '';
  2807. $segment_data['video_task_id'] = '';
  2808. $segment_data['video_task_status'] = '';
  2809. $segment_data['act_number'] = $new_act_number;
  2810. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2811. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2812. if (!$id) {
  2813. Utils::throwError('20003:复制片段失败');
  2814. }
  2815. DB::commit();
  2816. }catch (\Exception $e) {
  2817. DB::rollBack();
  2818. Utils::throwError('20003:'.$e->getMessage());
  2819. }
  2820. // 返回新复制的记录
  2821. $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();
  2822. $new_segment = $new_segment ? (array)$new_segment : [];
  2823. $new_segment['act_id'] = $id;
  2824. return $new_segment;
  2825. }
  2826. public function moveAct($data) {
  2827. $act_id = getProp($data, 'act_id');
  2828. $target_act_id = getProp($data, 'target_act_id');
  2829. // 获取源片段信息
  2830. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2831. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2832. // 获取目标片段信息
  2833. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2834. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2835. $anime_id = getProp($source_segment, 'anime_id');
  2836. $episode_id = getProp($source_segment, 'episode_id');
  2837. $source_act_number = getProp($source_segment, 'act_number');
  2838. $target_act_number = getProp($target_segment, 'act_number');
  2839. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2840. $target_anime_id = getProp($target_segment, 'anime_id');
  2841. $target_episode_id = getProp($target_segment, 'episode_id');
  2842. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2843. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2844. }
  2845. // 如果源片段和目标片段相同,无需移动
  2846. if ($source_act_number == $target_act_number) {
  2847. return true;
  2848. }
  2849. try {
  2850. DB::beginTransaction();
  2851. if ($source_act_number < $target_act_number) {
  2852. // 向后移动:源片段移动到目标片段之后
  2853. // 1. 将源片段和目标片段之间的所有片段编号减1
  2854. DB::table('mp_episode_segments')
  2855. ->where('anime_id', $anime_id)
  2856. ->where('episode_id', $episode_id)
  2857. ->where('act_number', '>', $source_act_number)
  2858. ->where('act_number', '<=', $target_act_number)
  2859. ->decrement('act_number');
  2860. // 2. 将源片段移动到目标片段之后
  2861. $new_act_number = $target_act_number;
  2862. } else {
  2863. // 向前移动:源片段移动到目标片段之后
  2864. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2865. DB::table('mp_episode_segments')
  2866. ->where('anime_id', $anime_id)
  2867. ->where('episode_id', $episode_id)
  2868. ->where('act_number', '>', $target_act_number)
  2869. ->where('act_number', '<', $source_act_number)
  2870. ->increment('act_number');
  2871. // 2. 将源片段移动到目标片段之后
  2872. $new_act_number = $target_act_number + 1;
  2873. }
  2874. // 3. 更新源片段的编号
  2875. $update_result = DB::table('mp_episode_segments')
  2876. ->where('id', $act_id)
  2877. ->update([
  2878. 'act_number' => $new_act_number,
  2879. 'updated_at' => date('Y-m-d H:i:s')
  2880. ]);
  2881. if (!$update_result) {
  2882. Utils::throwError('20003:更新片段编号失败');
  2883. }
  2884. DB::commit();
  2885. return true;
  2886. } catch (\Exception $e) {
  2887. DB::rollBack();
  2888. Utils::throwError('20003:' . $e->getMessage());
  2889. }
  2890. }
  2891. public function delAct($data) {
  2892. $act_id = getProp($data, 'act_id');
  2893. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2894. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2895. if (!$segment) Utils::throwError('20003:请选择片段');
  2896. $anime_id = getProp($segment, 'anime_id');
  2897. $episode_id = getProp($segment, 'episode_id');
  2898. $act_number = getProp($segment, 'act_number');
  2899. try {
  2900. DB::beginTransaction();
  2901. // 删除该片段记录
  2902. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2903. if (!$deleted) {
  2904. Utils::throwError('20003:删除片段失败');
  2905. }
  2906. // 更新后续act的编号
  2907. DB::table('mp_episode_segments')
  2908. ->where('anime_id', $anime_id)
  2909. ->where('episode_id', $episode_id)
  2910. ->where('act_number', '>', $act_number)
  2911. ->decrement('act_number');
  2912. DB::commit();
  2913. }catch (\Exception $e) {
  2914. DB::rollBack();
  2915. Utils::throwError('20003:'.$e->getMessage());
  2916. }
  2917. return true;
  2918. }
  2919. public function applyAct($data) {
  2920. $act_id = getProp($data, 'act_id');
  2921. $url = getProp($data, 'url');
  2922. if (!$act_id) Utils::throwError('20003:请选择片段');
  2923. if (!$url) Utils::throwError('20003:URL不能为空');
  2924. // 获取URL的文件扩展名
  2925. $urlPath = parse_url($url, PHP_URL_PATH);
  2926. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2927. // 定义图片和视频的扩展名
  2928. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2929. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2930. // 判断是图片还是视频
  2931. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2932. if (in_array($extension, $imageExtensions)) {
  2933. // 图片类型
  2934. $updateData['img_url'] = $url;
  2935. $updateData['current_type'] = 1;
  2936. } elseif (in_array($extension, $videoExtensions)) {
  2937. // 视频类型
  2938. $updateData['video_url'] = $url;
  2939. $updateData['current_type'] = 2;
  2940. } else {
  2941. Utils::throwError('20003:不支持的文件类型');
  2942. }
  2943. // 更新片段记录(全能模式下每个act只有一条记录)
  2944. $result = DB::table('mp_episode_segments')
  2945. ->where('id', $act_id)
  2946. ->update($updateData);
  2947. if (!$result) {
  2948. Utils::throwError('20003:更新片段失败');
  2949. }
  2950. return true;
  2951. }
  2952. public function actChatHistory($data) {
  2953. $act_id = getProp($data, 'act_id');
  2954. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2955. $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');
  2956. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2957. $value = (array)$value;
  2958. $value['created_at'] = transDate($value['created_at']);
  2959. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2960. else $value['reference_images'] = [];
  2961. return $value;
  2962. })->toArray();
  2963. // 获取历史图片
  2964. $url = [];
  2965. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2966. foreach($pic_history as $task) {
  2967. $result_url = getProp($task, 'result_url');
  2968. if (is_json($result_url)) {
  2969. $url = array_merge($url, json_decode($result_url, true));
  2970. }else {
  2971. $url[] = $result_url;
  2972. }
  2973. }
  2974. // 获取历史视频
  2975. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2976. foreach($video_history as $task) {
  2977. $result_url = getProp($task, 'result_url');
  2978. if (is_json($result_url)) {
  2979. $url = array_merge($url, json_decode($result_url, true));
  2980. }else {
  2981. $url[] = $result_url;
  2982. }
  2983. }
  2984. // 获取资产库
  2985. $products = [];
  2986. // 通过act_id查询片段信息获取episode_id
  2987. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2988. if ($segment) {
  2989. $episode_id = getProp($segment, 'episode_id');
  2990. // 查询剧集信息获取roles、scenes和extra_products
  2991. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2992. if ($episode) {
  2993. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2994. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2995. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2996. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2997. // 先合并roles、scenes和props
  2998. // 处理角色数组
  2999. foreach ($roles as $role) {
  3000. $product = $role;
  3001. // 将role字段重命名为product_name
  3002. if (is_array($product) && !empty($product['role'] ?? null)) {
  3003. $product['product_name'] = $product['role'];
  3004. unset($product['role']);
  3005. $product['product'] = 1; // 标记类型为角色
  3006. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3007. }
  3008. }
  3009. // 处理场景数组
  3010. foreach ($scenes as $scene) {
  3011. $product = $scene;
  3012. // 将scene字段重命名为product_name
  3013. if (is_array($product) && !empty($product['scene'] ?? null)) {
  3014. $product['product_name'] = $product['scene'];
  3015. unset($product['scene']);
  3016. $product['product'] = 2; // 标记类型为场景
  3017. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3018. }
  3019. }
  3020. // 处理道具数组
  3021. foreach ($props as $prop) {
  3022. $product = $prop;
  3023. // 将prop字段重命名为product_name
  3024. if (is_array($product) && !empty($product['prop'] ?? null)) {
  3025. $product['product_name'] = $product['prop'];
  3026. unset($product['prop']);
  3027. $product['product'] = 3; // 标记类型为道具
  3028. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3029. }
  3030. }
  3031. // extra_products优先级更高,直接覆盖同名的roles和scenes
  3032. foreach ($extra_products as $extra_product) {
  3033. $product_name = getProp($extra_product, 'product_name');
  3034. if ($product_name) {
  3035. $products[$product_name] = $extra_product; // 覆盖同名数据
  3036. }
  3037. }
  3038. // 重新索引数组(去除key)
  3039. $products = array_values($products);
  3040. }
  3041. }
  3042. // 获取执行中的任务
  3043. $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) {
  3044. $value = (array)$value;
  3045. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  3046. else $value['ref_image_url'] = [];
  3047. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  3048. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  3049. if (!empty($value['prompt'])) {
  3050. $prompt = $value['prompt'];
  3051. // 查找第一个【镜头】的位置
  3052. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  3053. // 从【镜头】开始截取
  3054. $prompt = substr($prompt, $matches[0][1]);
  3055. }
  3056. // 去除所有<图片X>格式的标记(X可以是任意数字)
  3057. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  3058. $value['prompt'] = $prompt;
  3059. }
  3060. return $value;
  3061. })->toArray();
  3062. return compact('chat', 'url', 'products', 'tasks');
  3063. }
  3064. public function applyAudioData($data) {
  3065. $segment_id = getProp($data, 'segment_id');
  3066. $global_data = getProp($data, 'global_data');
  3067. $segment_data = getProp($data, 'segment_data');
  3068. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3069. $global_data = is_array($global_data) ? $global_data : [];
  3070. $segment_data = is_array($segment_data) ? $segment_data : [];
  3071. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3072. $dialogue_item = null;
  3073. foreach ($global_data as $key => $item) {
  3074. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3075. $dialogue_item = $item;
  3076. unset($global_data[$key]);
  3077. break;
  3078. }
  3079. }
  3080. if ($dialogue_item) {
  3081. $segment_data[] = $dialogue_item;
  3082. }
  3083. // 特殊参数: audio_url,audio_duration,subtitle_info
  3084. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3085. // 如果不是全部存在,则仍需创建音频任务
  3086. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3087. $special_update_data = [];
  3088. $has_all_special_params = false;
  3089. // 从segment_data中提取特殊参数
  3090. $filtered_segment_data = [];
  3091. foreach ($segment_data as $item) {
  3092. $field_name = trim((string)getProp($item, 'name'));
  3093. if (in_array($field_name, $special_fields)) {
  3094. $special_update_data[$field_name] = getProp($item, 'value');
  3095. } else {
  3096. // 非特殊参数保留,继续后续处理
  3097. $filtered_segment_data[] = $item;
  3098. }
  3099. }
  3100. // 检查是否三个特殊参数都存在
  3101. if (count($special_update_data) === 3 &&
  3102. isset($special_update_data['audio_url']) &&
  3103. isset($special_update_data['audio_duration']) &&
  3104. isset($special_update_data['subtitle_info'])) {
  3105. $has_all_special_params = true;
  3106. // 立即更新到当前分镜
  3107. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3108. DB::table('mp_episode_segments')
  3109. ->where('segment_id', $segment_id)
  3110. ->update($special_update_data);
  3111. }
  3112. // 使用过滤后的segment_data继续处理其他参数
  3113. $segment_data = $filtered_segment_data;
  3114. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3115. $global_update_data = [];
  3116. $segment_update_data = [];
  3117. $global_voice_type = '';
  3118. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3119. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3120. $episode_id = getProp($target_segment, 'episode_id');
  3121. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3122. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3123. if (!$episode) Utils::throwError('20003:分集不存在');
  3124. foreach ($global_data as $item) {
  3125. $field_name = trim((string)getProp($item, 'name'));
  3126. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3127. continue;
  3128. }
  3129. $global_update_data[$field_name] = getProp($item, 'value');
  3130. if ($field_name === 'voice_type') {
  3131. $global_voice_type = trim((string)getProp($item, 'value'));
  3132. }
  3133. }
  3134. foreach ($segment_data as $item) {
  3135. $field_name = trim((string)getProp($item, 'name'));
  3136. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3137. continue;
  3138. }
  3139. $segment_update_data[$field_name] = getProp($item, 'value');
  3140. }
  3141. if ($global_voice_type) {
  3142. $timbre_info = DB::table('mp_timbres')
  3143. ->where('timbre_type', $global_voice_type)
  3144. ->select('audio_url', 'timbre_name')
  3145. ->first();
  3146. if ($timbre_info) {
  3147. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3148. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3149. }
  3150. }
  3151. try {
  3152. DB::beginTransaction();
  3153. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3154. $segment_ids_to_create_task = [];
  3155. $segments_data = [];
  3156. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3157. if (!empty($global_update_data)) {
  3158. // 如果角色不存在,则只更新当前分镜
  3159. if (!$target_voice_actor) {
  3160. // 只处理当前分镜
  3161. $affected_segments = DB::table('mp_episode_segments')
  3162. ->where('segment_id', $segment_id)
  3163. ->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')
  3164. ->get();
  3165. } else {
  3166. // 获取该角色的所有分镜
  3167. $affected_segments = DB::table('mp_episode_segments')
  3168. ->where('episode_id', $episode_id)
  3169. ->where('voice_actor', $target_voice_actor)
  3170. ->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')
  3171. ->get();
  3172. }
  3173. foreach ($affected_segments as $seg) {
  3174. $seg = (array)$seg;
  3175. $sid = getProp($seg, 'segment_id');
  3176. // 检查参数是否发生变化
  3177. $has_changed = false;
  3178. foreach ($global_update_data as $field => $new_value) {
  3179. $old_value = getProp($seg, $field);
  3180. if ($old_value != $new_value) {
  3181. $has_changed = true;
  3182. break;
  3183. }
  3184. }
  3185. if ($has_changed) {
  3186. $segment_ids_to_create_task[] = $sid;
  3187. $segments_data[$sid] = $seg;
  3188. }
  3189. }
  3190. // 只有在有变化的分镜时才更新
  3191. if (!empty($segment_ids_to_create_task)) {
  3192. $global_segment_update_data = $global_update_data;
  3193. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3194. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3195. DB::table('mp_episode_segments')
  3196. ->where('episode_id', $episode_id)
  3197. ->where('voice_actor', $target_voice_actor)
  3198. ->whereIn('segment_id', $segment_ids_to_create_task)
  3199. ->update($global_segment_update_data);
  3200. }
  3201. if ($global_voice_type) {
  3202. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3203. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3204. $roles_updated = false;
  3205. foreach ($episode_roles as &$role) {
  3206. // 通过 role 字段匹配角色名,而不是 voice_name
  3207. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3208. continue;
  3209. }
  3210. $role['voice_type'] = $global_voice_type;
  3211. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3212. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3213. $roles_updated = true;
  3214. }
  3215. unset($role);
  3216. if ($roles_updated) {
  3217. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3218. 'roles' => json_encode($episode_roles, 256),
  3219. 'updated_at' => date('Y-m-d H:i:s'),
  3220. ]);
  3221. }
  3222. }
  3223. }
  3224. // 如果有单个分镜更新,检查是否有变化
  3225. if (!empty($segment_update_data)) {
  3226. // 获取当前分镜数据
  3227. $current_segment = DB::table('mp_episode_segments')
  3228. ->where('segment_id', $segment_id)
  3229. ->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')
  3230. ->first();
  3231. if ($current_segment) {
  3232. $current_segment = (array)$current_segment;
  3233. // 检查参数是否发生变化
  3234. $has_changed = false;
  3235. foreach ($segment_update_data as $field => $new_value) {
  3236. $old_value = getProp($current_segment, $field);
  3237. if ($old_value != $new_value) {
  3238. $has_changed = true;
  3239. break;
  3240. }
  3241. }
  3242. if ($has_changed) {
  3243. // 如果该分镜还未在列表中,添加进去
  3244. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3245. $segment_ids_to_create_task[] = $segment_id;
  3246. $segments_data[$segment_id] = $current_segment;
  3247. }
  3248. // 更新分镜数据并清空音频URL
  3249. $segment_update_data['audio_url'] = '';
  3250. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3251. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3252. }
  3253. }
  3254. }
  3255. // 为所有有变化的分镜创建音频合成任务
  3256. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3257. if (!empty($segment_ids_to_create_task)) {
  3258. foreach ($segment_ids_to_create_task as $sid) {
  3259. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3260. if ($sid === $segment_id && $has_all_special_params) {
  3261. continue;
  3262. }
  3263. // 重新获取更新后的分镜数据
  3264. $updated_segment = DB::table('mp_episode_segments')
  3265. ->where('segment_id', $sid)
  3266. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3267. ->first();
  3268. if (!$updated_segment) continue;
  3269. $updated_segment = (array)$updated_segment;
  3270. // 检查dialogue是否为空
  3271. $dialogue = getProp($updated_segment, 'dialogue');
  3272. if (empty($dialogue)) {
  3273. // dialogue为空时,直接写入默认音频信息
  3274. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3275. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3276. 'audio_duration' => 2.0,
  3277. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3278. 'updated_at' => date('Y-m-d H:i:s')
  3279. ]);
  3280. continue;
  3281. }
  3282. $generate_json = [
  3283. 'text' => $dialogue,
  3284. 'role' => getProp($updated_segment, 'voice_actor'),
  3285. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3286. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3287. 'emotion' => getProp($updated_segment, 'emotion'),
  3288. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3289. 'gender' => getProp($updated_segment, 'gender'),
  3290. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3291. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3292. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3293. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3294. ];
  3295. // 插入视频配音合成任务
  3296. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3297. 'alias_segment_id' => $sid,
  3298. 'generate_status' => '执行中',
  3299. 'audio_url' => '',
  3300. 'generate_json' => json_encode($generate_json, 256),
  3301. 'created_at' => date('Y-m-d H:i:s'),
  3302. 'updated_at' => date('Y-m-d H:i:s'),
  3303. ]);
  3304. if (!$dubTaskId) {
  3305. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3306. continue;
  3307. }
  3308. // 将任务ID添加到Redis列表中
  3309. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3310. // 请求远程服务器执行生成
  3311. try {
  3312. sleep(1);
  3313. $client = new Client(['timeout' => 300, 'verify' => false]);
  3314. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3315. $response = $result->getBody()->getContents();
  3316. $response_arr = json_decode($response, true);
  3317. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3318. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3319. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3320. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3321. }
  3322. } catch (\Exception $e) {
  3323. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3324. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3325. }
  3326. }
  3327. }
  3328. DB::commit();
  3329. } catch (\Exception $e) {
  3330. DB::rollBack();
  3331. Utils::throwError('20003:'.$e->getMessage());
  3332. }
  3333. return true;
  3334. }
  3335. public function episodePicsInfo($data) {
  3336. $anime_id = getProp($data, 'anime_id');
  3337. $episode_id = getProp($data, 'episode_id');
  3338. // 参数验证
  3339. if (!$anime_id && !$episode_id) {
  3340. Utils::throwError('20003:请提供动漫ID或分集ID');
  3341. }
  3342. // 根据参数获取数据源
  3343. if ($episode_id) {
  3344. // 从剧集表获取
  3345. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3346. if (!$source) Utils::throwError('20003:该剧集不存在');
  3347. $table_name = 'mp_anime_episodes';
  3348. $id_field = 'id';
  3349. $id_value = $episode_id;
  3350. // 获取剧集的anime_id用于继承全局数据
  3351. $anime_id = getProp($source, 'anime_id');
  3352. } else {
  3353. // 从动漫表获取
  3354. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3355. if (!$source) Utils::throwError('20003:该动漫不存在');
  3356. $table_name = 'mp_animes';
  3357. $id_field = 'id';
  3358. $id_value = $anime_id;
  3359. }
  3360. $source = (array)$source;
  3361. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3362. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3363. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3364. // 如果是分集数据,需要处理继承和任务创建逻辑
  3365. if ($episode_id) {
  3366. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3367. }
  3368. // 返回生成器函数,用于 SSE 流式输出
  3369. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3370. $startTime = time();
  3371. $maxDuration = 600; // 10分钟超时
  3372. $checkInterval = 3; // 每3秒检查一次
  3373. // Redis 缓存键
  3374. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3375. // 生成当前数据的哈希值用于比较
  3376. $generateHash = function($roles, $scenes, $props) {
  3377. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3378. };
  3379. // 发送初始数据
  3380. $currentHash = $generateHash($roles, $scenes, $props);
  3381. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3382. echo "data: " . json_encode([
  3383. 'type' => 'init',
  3384. 'data' => [
  3385. 'roles' => $roles,
  3386. 'scenes' => $scenes,
  3387. 'props' => $props,
  3388. 'start_time' => $startTime
  3389. ]
  3390. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3391. if (ob_get_level() > 0) {
  3392. ob_flush();
  3393. }
  3394. flush();
  3395. // 持续轮询任务状态
  3396. while (time() - $startTime < $maxDuration) {
  3397. $hasProcessing = false;
  3398. $updated = false;
  3399. // 检查角色任务状态
  3400. foreach ($roles as $index => &$role) {
  3401. $task_id = getProp($role, 'task_id');
  3402. $task_status = getProp($role, 'task_status');
  3403. $existing_url = getProp($role, 'url');
  3404. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3405. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3406. $hasProcessing = ($task_status === 'processing');
  3407. // 查询任务状态
  3408. $task = DB::table('mp_generate_pic_tasks')
  3409. ->where('id', $task_id)
  3410. ->select('id', 'status', 'result_url', 'error_message')
  3411. ->first();
  3412. if ($task) {
  3413. $task = (array)$task;
  3414. $status = getProp($task, 'status');
  3415. // 如果任务完成或失败
  3416. if (in_array($status, ['success', 'failed'])) {
  3417. $role['task_status'] = $status;
  3418. if ($status === 'success') {
  3419. $result_url = getProp($task, 'result_url');
  3420. if ($result_url) {
  3421. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3422. if (is_array($result_urls) && !empty($result_urls[0])) {
  3423. $role['url'] = $result_urls[0];
  3424. }
  3425. }
  3426. }
  3427. $updated = true;
  3428. } else if ($status === 'processing') {
  3429. $hasProcessing = true;
  3430. }
  3431. }
  3432. }
  3433. }
  3434. // 检查场景任务状态
  3435. foreach ($scenes as $index => &$scene) {
  3436. $task_id = getProp($scene, 'task_id');
  3437. $task_status = getProp($scene, 'task_status');
  3438. $existing_url = getProp($scene, 'url');
  3439. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3440. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3441. $hasProcessing = ($task_status === 'processing');
  3442. // 查询任务状态
  3443. $task = DB::table('mp_generate_pic_tasks')
  3444. ->where('id', $task_id)
  3445. ->select('id', 'status', 'result_url', 'error_message')
  3446. ->first();
  3447. if ($task) {
  3448. $task = (array)$task;
  3449. $status = getProp($task, 'status');
  3450. // 如果任务完成或失败
  3451. if (in_array($status, ['success', 'failed'])) {
  3452. $scene['task_status'] = $status;
  3453. if ($status === 'success') {
  3454. $result_url = getProp($task, 'result_url');
  3455. if ($result_url) {
  3456. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3457. if (is_array($result_urls) && !empty($result_urls[0])) {
  3458. $scene['url'] = $result_urls[0];
  3459. }
  3460. }
  3461. }
  3462. $updated = true;
  3463. } else if ($status === 'processing') {
  3464. $hasProcessing = true;
  3465. }
  3466. }
  3467. }
  3468. }
  3469. // 检查道具任务状态
  3470. foreach ($props as $index => &$prop) {
  3471. $task_id = getProp($prop, 'task_id');
  3472. $task_status = getProp($prop, 'task_status');
  3473. $existing_url = getProp($prop, 'url');
  3474. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3475. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3476. $hasProcessing = ($task_status === 'processing');
  3477. // 查询任务状态
  3478. $task = DB::table('mp_generate_pic_tasks')
  3479. ->where('id', $task_id)
  3480. ->select('id', 'status', 'result_url', 'error_message')
  3481. ->first();
  3482. if ($task) {
  3483. $task = (array)$task;
  3484. $status = getProp($task, 'status');
  3485. // 如果任务完成或失败
  3486. if (in_array($status, ['success', 'failed'])) {
  3487. $prop['task_status'] = $status;
  3488. if ($status === 'success') {
  3489. $result_url = getProp($task, 'result_url');
  3490. if ($result_url) {
  3491. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3492. if (is_array($result_urls) && !empty($result_urls[0])) {
  3493. $prop['url'] = $result_urls[0];
  3494. }
  3495. }
  3496. }
  3497. $updated = true;
  3498. } else if ($status === 'processing') {
  3499. $hasProcessing = true;
  3500. }
  3501. }
  3502. }
  3503. }
  3504. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3505. if ($updated) {
  3506. $newHash = $generateHash($roles, $scenes, $props);
  3507. $cachedHash = Redis::get($cacheKey);
  3508. // 只有当数据真正变化时才更新数据库和发送事件
  3509. if ($newHash !== $cachedHash) {
  3510. try {
  3511. // 更新数据库
  3512. DB::table($table_name)->where($id_field, $id_value)->update([
  3513. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3514. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3515. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3516. 'updated_at' => date('Y-m-d H:i:s')
  3517. ]);
  3518. // 更新缓存
  3519. Redis::setex($cacheKey, 600, $newHash);
  3520. // 发送更新事件
  3521. echo "data: " . json_encode([
  3522. 'type' => 'update',
  3523. 'data' => [
  3524. 'roles' => $roles,
  3525. 'scenes' => $scenes,
  3526. 'props' => $props,
  3527. 'elapsed_time' => time() - $startTime
  3528. ]
  3529. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3530. if (ob_get_level() > 0) {
  3531. ob_flush();
  3532. }
  3533. flush();
  3534. } catch (\Exception $e) {
  3535. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3536. }
  3537. } else {
  3538. // 即使哈希相同,如果有URL更新也要发送事件
  3539. $hasUrlUpdate = false;
  3540. foreach ($roles as $role) {
  3541. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3542. $hasUrlUpdate = true;
  3543. break;
  3544. }
  3545. }
  3546. if (!$hasUrlUpdate) {
  3547. foreach ($scenes as $scene) {
  3548. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3549. $hasUrlUpdate = true;
  3550. break;
  3551. }
  3552. }
  3553. }
  3554. if (!$hasUrlUpdate) {
  3555. foreach ($props as $prop) {
  3556. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3557. $hasUrlUpdate = true;
  3558. break;
  3559. }
  3560. }
  3561. }
  3562. if ($hasUrlUpdate) {
  3563. // 强制更新数据库和发送事件
  3564. try {
  3565. DB::table($table_name)->where($id_field, $id_value)->update([
  3566. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3567. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3568. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3569. 'updated_at' => date('Y-m-d H:i:s')
  3570. ]);
  3571. // 更新缓存
  3572. Redis::setex($cacheKey, 600, $newHash);
  3573. // 发送更新事件
  3574. echo "data: " . json_encode([
  3575. 'type' => 'update',
  3576. 'data' => [
  3577. 'roles' => $roles,
  3578. 'scenes' => $scenes,
  3579. 'props' => $props,
  3580. 'elapsed_time' => time() - $startTime
  3581. ]
  3582. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3583. if (ob_get_level() > 0) {
  3584. ob_flush();
  3585. }
  3586. flush();
  3587. } catch (\Exception $e) {
  3588. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3589. }
  3590. }
  3591. }
  3592. }
  3593. // 如果所有任务都已完成,发送完成事件并退出
  3594. if (!$hasProcessing) {
  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' => 'completed',
  3616. 'data' => [
  3617. 'roles' => $roles,
  3618. 'scenes' => $scenes,
  3619. 'props' => $props,
  3620. 'total_time' => time() - $startTime
  3621. ]
  3622. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3623. if (ob_get_level() > 0) {
  3624. ob_flush();
  3625. }
  3626. flush();
  3627. break;
  3628. }
  3629. // 等待下次检查
  3630. sleep($checkInterval);
  3631. }
  3632. // 超时处理
  3633. if (time() - $startTime >= $maxDuration) {
  3634. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3635. try {
  3636. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3637. if ($finalSource) {
  3638. $finalSource = (array)$finalSource;
  3639. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3640. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3641. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3642. // 使用数据库中的最终数据
  3643. $roles = $finalRoles;
  3644. $scenes = $finalScenes;
  3645. $props = $finalProps;
  3646. }
  3647. } catch (\Exception $e) {
  3648. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3649. // 如果查询失败,继续使用内存中的数据
  3650. }
  3651. // 清理缓存
  3652. Redis::del($cacheKey);
  3653. echo "data: " . json_encode([
  3654. 'type' => 'timeout',
  3655. 'message' => '轮询超时,请刷新页面查看最新状态',
  3656. 'data' => [
  3657. 'roles' => $roles,
  3658. 'scenes' => $scenes,
  3659. 'props' => $props
  3660. ]
  3661. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3662. if (ob_get_level() > 0) {
  3663. ob_flush();
  3664. }
  3665. flush();
  3666. }
  3667. };
  3668. }
  3669. public function clipSegmentVideo($data) {
  3670. $segment_id = getProp($data, 'segment_id');
  3671. $video_time_point_start = getProp($data, 'video_time_point_start');
  3672. $video_time_point_end = getProp($data, 'video_time_point_end');
  3673. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3674. Utils::throwError('20003:参数异常');
  3675. }
  3676. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3677. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3678. }
  3679. $video_duration = $video_time_point_end - $video_time_point_start;
  3680. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3681. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3682. 'video_duration' => $video_duration,
  3683. 'video_time_point_start' => $video_time_point_start,
  3684. 'video_time_point_end' => $video_time_point_end,
  3685. 'updated_at' => date('Y-m-d H:i:s')
  3686. ]);
  3687. }
  3688. // 轮训获取图片任务结果
  3689. private function loopGetPicTaskResult($task_id) {
  3690. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3691. if (!$task) {
  3692. return '';
  3693. }
  3694. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3695. $model = getProp($task, 'model');
  3696. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3697. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3698. $isSyncModel = $isVolcModel || $isGptModel;
  3699. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3700. $start_count = 0;
  3701. $img_url = '';
  3702. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3703. sleep(3);
  3704. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3705. // 如果任务已经完成,直接返回结果
  3706. if ($task->status === 'success' && $task->result_url) {
  3707. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3708. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3709. }
  3710. // 如果任务已失败,返回空
  3711. if ($task->status === 'failed') {
  3712. return '';
  3713. }
  3714. if ($isSyncModel) continue;
  3715. // 查询任务状态
  3716. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3717. if ($statusInfo['status'] === 'success') {
  3718. $task->updateStatus('success', [
  3719. 'result_url' => $statusInfo['result_url'],
  3720. 'result_json' => $statusInfo['result_json'] ?? []
  3721. ]);
  3722. // 同步调整分镜图片状态和结果
  3723. if (getProp($task, 'alias_segment_id')) {
  3724. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3725. 'img_url' => $statusInfo['result_url'][0],
  3726. 'pic_task_status' => '已完成',
  3727. ]);
  3728. }
  3729. $img_url = $statusInfo['result_url'][0];
  3730. break;
  3731. } elseif ($statusInfo['status'] === 'failed') {
  3732. $task->updateStatus('failed', [
  3733. 'error_message' => $statusInfo['error_message'],
  3734. 'result_json' => $statusInfo['result_json'] ?? []
  3735. ]);
  3736. if (getProp($task, 'alias_segment_id')) {
  3737. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3738. 'pic_task_status' => '失败',
  3739. ]);
  3740. }
  3741. break;
  3742. }
  3743. $start_count++;
  3744. }
  3745. return $img_url;
  3746. }
  3747. /**
  3748. * 从分镜内容中提取涉及的角色
  3749. */
  3750. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3751. $found_characters = [];
  3752. foreach ($available_characters as $character) {
  3753. // 检查角色名称是否在分镜内容中出现
  3754. if (strpos($segment_content, $character) !== false) {
  3755. $found_characters[] = $character;
  3756. }
  3757. }
  3758. if (!$found_characters) {
  3759. foreach ($roles as $character) {
  3760. // 检查角色名称是否在分镜内容中出现
  3761. if (strpos($segment_content, $character) !== false) {
  3762. $found_characters[] = $character;
  3763. }
  3764. }
  3765. }
  3766. return array_unique($found_characters);
  3767. }
  3768. // 从分镜剧本中提取关键字段
  3769. private function handleSegmentContent(&$data) {
  3770. $segmentContent = getProp($data, 'segment_content');
  3771. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3772. $segmentData = [
  3773. 'description' => '',
  3774. 'composition' => '',
  3775. 'camera_movement' => '',
  3776. 'voice_actor' => '',
  3777. 'dialogue' => '',
  3778. 'frame_type' => '',
  3779. 'scene' => '', // 场景
  3780. 'characters' => '', // 出镜角色
  3781. 'tail_frame' => '', // 尾帧描述
  3782. 'emotion' => '中性', // 情感
  3783. 'gender' => '0', // 性别(0未知,1男,2女)
  3784. 'speed_ratio' => 0, // 语速
  3785. 'loudness_ratio' => 0, // 音量
  3786. 'emotion_scale' => 4, // 情感强度
  3787. 'pitch' => 0, // 音调
  3788. ];
  3789. // 用于存储需要从 segment_content 中移除的匹配项
  3790. $replaceEmptyArr = [];
  3791. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3792. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3793. $segmentData['description'] = trim($descMatch[1]);
  3794. $data['description'] = trim($descMatch[1]);
  3795. }
  3796. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3797. $segmentData['composition'] = trim($compMatch[1]);
  3798. $data['composition'] = trim($compMatch[1]);
  3799. }
  3800. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3801. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3802. $data['camera_movement'] = trim($cameraMatch[1]);
  3803. }
  3804. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3805. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3806. $data['voice_actor'] = trim($voiceMatch[1]);
  3807. }
  3808. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3809. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3810. $data['dialogue'] = trim($dialogueMatch[1]);
  3811. }
  3812. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3813. $segmentData['frame_type'] = trim($frameMatch[1]);
  3814. $data['frame_type'] = trim($frameMatch[1]);
  3815. }
  3816. // 场景字段
  3817. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3818. $segmentData['scene'] = trim($sceneMatch[1]);
  3819. $data['scene'] = trim($sceneMatch[1]);
  3820. }
  3821. // 出镜角色字段
  3822. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3823. $segmentData['characters'] = trim($charactersMatch[1]);
  3824. $data['characters'] = trim($charactersMatch[1]);
  3825. }
  3826. // 尾帧描述字段
  3827. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3828. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3829. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3830. }
  3831. // 情感字段
  3832. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3833. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3834. $segmentData['emotion'] = trim($emotionMatch[1]);
  3835. $data['emotion'] = trim($emotionMatch[1]);
  3836. }
  3837. // 性别字段
  3838. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3839. $replaceEmptyArr[] = trim($genderMatch[0]);
  3840. $genderStr = trim($genderMatch[1]);
  3841. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3842. $segmentData['gender'] = '1';
  3843. $data['gender'] = '1';
  3844. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3845. $segmentData['gender'] = '2';
  3846. $data['gender'] = '2';
  3847. } else {
  3848. $segmentData['gender'] = '0';
  3849. $data['gender'] = '0';
  3850. }
  3851. }
  3852. // 语速字段
  3853. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3854. $replaceEmptyArr[] = trim($speedMatch[0]);
  3855. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3856. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3857. }
  3858. // 音量字段
  3859. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3860. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3861. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3862. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3863. }
  3864. // 情感强度字段
  3865. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3866. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3867. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3868. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3869. }
  3870. // 音调字段
  3871. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3872. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3873. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3874. $data['pitch'] = (int)trim($pitchMatch[1]);
  3875. }
  3876. // 从 segment_content 中移除已提取的配音参数字段
  3877. if (!empty($replaceEmptyArr)) {
  3878. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3879. }
  3880. // 如果有配音角色,查询音色信息并验证情感
  3881. $voice_actor = $segmentData['voice_actor'];
  3882. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3883. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3884. $anime_id = getProp($data, 'anime_id');
  3885. $episode_id = getProp($data, 'episode_id');
  3886. // 优先从剧集的角色列表中查找
  3887. $roles = [];
  3888. if ($episode_id) {
  3889. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3890. if ($episode && getProp($episode, 'roles')) {
  3891. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3892. }
  3893. }
  3894. // 如果剧集中没有,从动漫的角色列表中查找
  3895. if (empty($roles) && $anime_id) {
  3896. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3897. if ($anime && getProp($anime, 'roles')) {
  3898. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3899. }
  3900. }
  3901. // 查找匹配的角色音色信息
  3902. $timbre_info = null;
  3903. foreach ($roles as $role) {
  3904. if (getProp($role, 'role') === $voice_actor) {
  3905. $timbre_info = $role;
  3906. break;
  3907. }
  3908. }
  3909. // 如果找到音色信息,添加到数据中
  3910. if ($timbre_info) {
  3911. $voice_type = getProp($timbre_info, 'voice_type');
  3912. $voice_name = getProp($timbre_info, 'voice_name');
  3913. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3914. if ($voice_type) {
  3915. $data['voice_type'] = $voice_type;
  3916. $segmentData['voice_type'] = $voice_type;
  3917. }
  3918. if ($voice_name) {
  3919. $data['voice_name'] = $voice_name;
  3920. $segmentData['voice_name'] = $voice_name;
  3921. }
  3922. if ($voice_audio_url) {
  3923. $data['voice_audio_url'] = $voice_audio_url;
  3924. $segmentData['voice_audio_url'] = $voice_audio_url;
  3925. }
  3926. // 验证情感是否在音色支持的情感列表中
  3927. if ($voice_type) {
  3928. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3929. if ($timbre_emotion) {
  3930. $timbre_emotion = explode(',', $timbre_emotion);
  3931. } else {
  3932. $timbre_emotion = [];
  3933. }
  3934. $emotion = getProp($segmentData, 'emotion', '中性');
  3935. if (!in_array($emotion, $timbre_emotion)) {
  3936. $emotion = '中性';
  3937. }
  3938. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3939. $emotion_list = array_flip($emotion_list);
  3940. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3941. $data['emotion_type'] = $emotion_type;
  3942. $segmentData['emotion_type'] = $emotion_type;
  3943. }
  3944. }
  3945. }
  3946. return $segmentData;
  3947. }
  3948. public function createSegmentVideoTask($data) {
  3949. $segment_id = getProp($data, 'segment_id');
  3950. $tail_frame = getProp($data, 'tail_frame');
  3951. $first_frame_url = getProp($data, 'first_frame_url');
  3952. $tail_frame_url = getProp($data, 'tail_frame_url');
  3953. $generate_audio = getProp($data, 'generate_audio', 0);
  3954. if (!$segment_id) {
  3955. Utils::throwError('1002:分镜ID不能为空');
  3956. }
  3957. // 获取分镜信息
  3958. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3959. if (!$segment) {
  3960. Utils::throwError('20003:分镜不存在');
  3961. }
  3962. $segment = (array)$segment;
  3963. $episode_id = getProp($segment, 'episode_id');
  3964. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3965. if (!$ratio) $ratio = '9:16';
  3966. // 获取分镜内容
  3967. $segmentContent = getProp($segment, 'segment_content', '');
  3968. // 检查 $segmentContent 中是否已有尾帧描述
  3969. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3970. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3971. $finalTailFrame = '';
  3972. if ($tail_frame) {
  3973. // 用户输入了尾帧描述,优先使用
  3974. $finalTailFrame = $tail_frame;
  3975. // 如果 segmentContent 中已有尾帧描述,需要替换
  3976. if ($contentHasTailFrame) {
  3977. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3978. }
  3979. } elseif ($contentHasTailFrame) {
  3980. // segmentContent 中有尾帧描述,使用它
  3981. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3982. } else {
  3983. // 两者都没有,使用分镜表中的尾帧描述
  3984. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3985. }
  3986. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3987. $hasDialogue = false;
  3988. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3989. $dialogue = trim($dialogueMatch[1]);
  3990. // 如果台词不为空且不是"无"
  3991. if (!empty($dialogue) && $dialogue !== '无') {
  3992. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3993. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3994. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3995. $hasDialogue = true;
  3996. }
  3997. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3998. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3999. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  4000. if (!preg_match('/^[“]/', $dialogue)) {
  4001. $dialogue = '“' . $dialogue;
  4002. }
  4003. if (!preg_match('/[”]$/', $dialogue)) {
  4004. $dialogue .= '”';
  4005. }
  4006. // 将修改后的台词替换回 $segmentContent
  4007. $originalDialogue = $dialogueMatch[1];
  4008. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  4009. }
  4010. }
  4011. // 构建完整的提示词
  4012. $fullPrompt = $segmentContent;
  4013. if ($finalTailFrame && !$contentHasTailFrame) {
  4014. // 只有当 segmentContent 中没有尾帧描述时才追加
  4015. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  4016. }
  4017. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  4018. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  4019. $fullPrompt = trim($fullPrompt);
  4020. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  4021. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  4022. // 智能选择视频时长
  4023. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  4024. $videoDuration = -1;
  4025. // 处理视频模型
  4026. $model = getProp($data, 'model');
  4027. if (!$model) {
  4028. // 用户没有输入,从episode表获取
  4029. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  4030. $model = getProp($episode, 'video_model');
  4031. if (!$model) {
  4032. // episode表也没有,使用默认值
  4033. $model = 'doubao-seedance-1-5-pro-251215';
  4034. }
  4035. }
  4036. // 验证模型是否在可用模型表中
  4037. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4038. $model = 'doubao-seedance-1-5-pro-251215';
  4039. }
  4040. // 保存到episode表
  4041. $episode_id = getProp($segment, 'episode_id');
  4042. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4043. 'video_model' => $model,
  4044. 'updated_at' => date('Y-m-d H:i:s')
  4045. ]);
  4046. // 构建视频生成参数
  4047. $videoParams = [
  4048. 'model' => $model,
  4049. 'alias_segment_id' => $segment_id,
  4050. 'prompt' => trim($fullPrompt),
  4051. 'video_duration' => $videoDuration,
  4052. 'video_resolution' => '720P',
  4053. 'seed' => -1,
  4054. 'ratio' => $ratio,
  4055. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4056. 'draft' => false,
  4057. 'watermark' => false,
  4058. 'camera_fixed' => false,
  4059. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4060. ];
  4061. // 如果分镜有图片,作为首帧
  4062. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  4063. $hasVideo = !empty(getProp($segment, 'video_url'));
  4064. if ($hasImage) {
  4065. if ($first_frame_url) {
  4066. $videoParams['first_frame_url'] = $first_frame_url;
  4067. }else {
  4068. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4069. }
  4070. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4071. }
  4072. // 构建content数组
  4073. $videoParams['content'] = [
  4074. [
  4075. 'type' => 'text',
  4076. 'text' => $videoParams['prompt'],
  4077. ]
  4078. ];
  4079. // 如果有首帧图片,添加到content中
  4080. if ($hasImage) {
  4081. 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'])) {
  4082. $videoParams['content'][] = [
  4083. 'type' => 'image_url',
  4084. 'image_url' => [
  4085. 'url' => $videoParams['first_frame_url'],
  4086. ],
  4087. 'role' => 'reference_image',
  4088. ];
  4089. if (isset($videoParams['tail_frame_url'])) {
  4090. $videoParams['content'][] = [
  4091. 'type' => 'image_url',
  4092. 'image_url' => [
  4093. 'url' => $videoParams['tail_frame_url'],
  4094. ],
  4095. 'role' => 'reference_image',
  4096. ];
  4097. }
  4098. }else {
  4099. $videoParams['content'][] = [
  4100. 'type' => 'image_url',
  4101. 'image_url' => [
  4102. 'url' => $videoParams['first_frame_url'],
  4103. ],
  4104. 'role' => 'first_frame',
  4105. ];
  4106. if (isset($videoParams['tail_frame_url'])) {
  4107. $videoParams['content'][] = [
  4108. 'type' => 'image_url',
  4109. 'image_url' => [
  4110. 'url' => $videoParams['tail_frame_url'],
  4111. ],
  4112. 'role' => 'last_frame',
  4113. ];
  4114. }
  4115. }
  4116. }
  4117. // 获取配音音频URL
  4118. $audioUrl = getProp($segment, 'audio_url');
  4119. $audioDuration = getProp($segment, 'audio_duration');
  4120. // 音频传入的前提:必须有至少一张图片或一个视频
  4121. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4122. // 余额预检:按预估时长计算所需积分,不足直接报错
  4123. $chargeDuration = (int)ceil((float)$audioDuration);
  4124. if ($chargeDuration <= 0) {
  4125. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4126. }
  4127. $this->pointsService->checkUserPointsEnough(
  4128. $this->pointsService->getVideoChargePoints([
  4129. 'model' => $model,
  4130. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4131. 'video_duration' => $chargeDuration,
  4132. 'ratio' => $ratio,
  4133. 'generate_audio' => $current_generate_audio,
  4134. ])
  4135. );
  4136. // dd($videoParams);
  4137. // 根据模型选择不同的视频生成方法
  4138. if (strpos($model, 'jimeng') !== false) {
  4139. // 即梦模型参数调整
  4140. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4141. unset($videoParams['content']); // 即梦不使用content格式
  4142. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4143. } elseif (strpos($model, 'kling') !== false) {
  4144. // Keling模型参数调整
  4145. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4146. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4147. unset($videoParams['ratio']);
  4148. unset($videoParams['content']); // Keling不使用content格式
  4149. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4150. } elseif (strpos($model, 'zhizhen') !== false) {
  4151. // 智帧20等新模型使用统一API
  4152. // 构建统一API参数
  4153. $unifiedParams = [
  4154. 'model_code' => $model,
  4155. 'alias_segment_id' => $segment_id,
  4156. 'prompt' => trim($fullPrompt),
  4157. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4158. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4159. 'video_ratio' => $ratio,
  4160. 'seed' => -1,
  4161. ];
  4162. // 构建parameters参数
  4163. $parameters = [
  4164. 'seconds' => $unifiedParams['video_duration'],
  4165. 'resolution' => $unifiedParams['video_resolution'],
  4166. 'ratio' => $ratio,
  4167. // 'video_mode' => 'multi_image',
  4168. // 'mode' => 'multi_image',
  4169. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4170. ];
  4171. $hasImage = false;
  4172. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4173. if ($hasImage) {
  4174. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4175. if (isset($videoParams['tail_frame_url'])) {
  4176. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4177. }
  4178. // 只有在有图片的情况下才能添加参考音频
  4179. if ($audioUrl) {
  4180. // $parameters['reference_audios'] = [$audioUrl];
  4181. }
  4182. } else {
  4183. // 没有图片时,记录错误日志
  4184. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4185. 'segment_id' => $segment_id,
  4186. 'model' => $model
  4187. ]);
  4188. }
  4189. $unifiedParams['parameters'] = $parameters;
  4190. // 调用统一API创建任务
  4191. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4192. } else {
  4193. // Seedance模型(默认)
  4194. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4195. if ($this->isKuaikuaiSeedanceModel($model)) {
  4196. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4197. if ($canUseAudio && $audioUrl) {
  4198. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4199. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4200. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4201. // 优化提示词,增加音频相关描述
  4202. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4203. $videoParams['prompt'] = $audioPrompt;
  4204. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4205. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4206. }
  4207. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4208. } 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'])) {
  4209. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4210. // 添加配音音频到content中
  4211. $videoParams['content'][] = [
  4212. 'type' => 'audio_url',
  4213. 'audio_url' => [
  4214. 'url' => $audioUrl,
  4215. ],
  4216. 'role' => 'reference_audio',
  4217. ];
  4218. // 优化提示词,增加音频相关描述
  4219. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4220. $videoParams['prompt'] = $audioPrompt;
  4221. $videoParams['content'][0]['text'] = $audioPrompt;
  4222. } else {
  4223. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4224. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4225. }
  4226. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4227. }
  4228. }
  4229. // 更新分镜表的视频任务信息
  4230. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4231. 'video_task_id' => $task->id,
  4232. 'video_task_status' => '生成中',
  4233. 'generate_audio' => $generate_audio,
  4234. 'updated_at' => date('Y-m-d H:i:s')
  4235. ]);
  4236. return [
  4237. 'task_id' => $task->id,
  4238. 'status' => $task->status,
  4239. 'segment_id' => $segment_id,
  4240. 'video_duration' => $videoDuration
  4241. ];
  4242. }
  4243. /**
  4244. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4245. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4246. *
  4247. * @param string $model
  4248. * @return bool
  4249. */
  4250. public function isKuaikuaiSeedanceModel(string $model): bool
  4251. {
  4252. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4253. }
  4254. /**
  4255. * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
  4256. *
  4257. * @param string $model
  4258. * @return bool
  4259. */
  4260. public function isBaiduSeedanceModel(string $model): bool
  4261. {
  4262. return in_array($model, [
  4263. 'baidu-doubao-seedance-2-0-260128',
  4264. 'baidu-doubao-seedance-2-0-fast-260128',
  4265. 'baidu-doubao-seedance-2-0-mini-260615',
  4266. 'baidu-doubao-seedance-2-5-260628',
  4267. ], true);
  4268. }
  4269. /**
  4270. * 是否为海外百度Seedance(dreamina真人素材空间)模型
  4271. * 系统内使用 baidu-dreamina- 前缀名,请求网关时映射为 dreamina-* 原名
  4272. *
  4273. * @param string $model
  4274. * @return bool
  4275. */
  4276. public function isOverseasBaiduSeedanceModel(string $model): bool
  4277. {
  4278. return in_array($model, [
  4279. 'baidu-dreamina-seedance-2-0-260128',
  4280. 'baidu-dreamina-seedance-2-0-fast-260128',
  4281. 'baidu-dreamina-seedance-2-0-mini-260615',
  4282. 'baidu-dreamina-seedance-2-5-260628',
  4283. ], true);
  4284. }
  4285. /**
  4286. * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-doubao-* / baidu-dreamina-* / 快快AI seed-2 系列)
  4287. * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
  4288. *
  4289. * @param string $model
  4290. * @return bool
  4291. */
  4292. public function isSeedance20SeriesModel(string $model): bool
  4293. {
  4294. return strpos($model, 'doubao-seedance-2.0') !== false
  4295. || $this->isKuaikuaiSeedanceModel($model)
  4296. || $this->isBaiduSeedanceModel($model)
  4297. || $this->isOverseasBaiduSeedanceModel($model);
  4298. }
  4299. public function createActVideoTask($data) {
  4300. $act_id = getProp($data, 'act_id');
  4301. $first_frame_url = getProp($data, 'first_frame_url');
  4302. $tail_frame_url = getProp($data, 'tail_frame_url');
  4303. $generate_audio = getProp($data, 'generate_audio', 1);
  4304. $video_duration = getProp($data, 'video_duration');
  4305. $video_resolution = getProp($data, 'video_resolution');
  4306. $ratio = getProp($data, 'ratio');
  4307. $products = getProp($data, 'products', []);
  4308. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4309. if (!is_array($reference_images) || !is_array($products)) {
  4310. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4311. }
  4312. if (!$act_id) {
  4313. Utils::throwError('1002:片段ID不能为空');
  4314. }
  4315. // 获取片段信息
  4316. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4317. if (!$act) {
  4318. Utils::throwError('20003:片段不存在');
  4319. }
  4320. $act = (array)$act;
  4321. $anime_id = getProp($act, 'anime_id');
  4322. $episode_id = getProp($act, 'episode_id');
  4323. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4324. $ace_mode = getProp($anime, 'ace_mode');
  4325. $art_style_type = getProp($anime, 'art_style_type');
  4326. $art_style = getProp($anime, 'art_style');
  4327. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4328. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4329. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4330. // 将资产中新出现的资产放到extra_products中
  4331. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4332. if (!empty($products) && $episode) {
  4333. // 获取剧集中的角色、场景和道具列表
  4334. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4335. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4336. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4337. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4338. // 构建角色名称列表
  4339. $role_names = array_column($roles, 'role');
  4340. // 构建场景名称列表
  4341. $scene_names = array_column($scenes, 'scene');
  4342. // 构建道具名称列表
  4343. $prop_names = array_column($props, 'prop');
  4344. // 遍历传入的products
  4345. foreach ($products as $product) {
  4346. $product_name = getProp($product, 'product_name');
  4347. // 如果product_name不在roles、scenes和props中
  4348. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4349. // 查找是否在extra_products中存在同名的
  4350. $found = false;
  4351. foreach ($extra_products as $key => $extra_product) {
  4352. if (getProp($extra_product, 'product_name') === $product_name) {
  4353. // 有同名的则覆盖
  4354. $extra_products[$key] = $product;
  4355. $found = true;
  4356. break;
  4357. }
  4358. }
  4359. // 没有则新增
  4360. if (!$found) {
  4361. $extra_products[] = $product;
  4362. }
  4363. }
  4364. }
  4365. if ($extra_products) {
  4366. // 保存到数据库
  4367. DB::table('mp_anime_episodes')
  4368. ->where('id', $episode_id)
  4369. ->update([
  4370. 'extra_products' => json_encode($extra_products, 256),
  4371. 'updated_at' => date('Y-m-d H:i:s')
  4372. ]);
  4373. }
  4374. }
  4375. // 获取分镜内容
  4376. $actContent = getProp($act, 'act_show_content', '');
  4377. // 音效同出(默认使用)
  4378. $current_generate_audio = $generate_audio ? 1 : 0;
  4379. // 处理视频模型(需在构建提示词之前解析:决定角色音色是否使用参考音频)
  4380. $model = getProp($data, 'model');
  4381. if (!$model) {
  4382. $model = getProp($episode, 'video_model');
  4383. if (!$model) {
  4384. // episode表也没有,使用默认值
  4385. $model = 'seed-2';
  4386. }
  4387. }
  4388. // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
  4389. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  4390. if (!in_array($model, $valid_models)) {
  4391. $model = 'seed-2';
  4392. }
  4393. // 构建完整的提示词
  4394. $supportAudioReference = $this->isActReferenceAudioSupported($model);
  4395. $processResult = $this->processActContentWithProducts($actContent, $products, $supportAudioReference);
  4396. $fullPrompt = $processResult['content'];
  4397. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4398. // 资产参考图与调用方传入的参考图合并后统一去重(保留资产参考图在前,不影响提示词中的<图片N>编号)
  4399. $reference_images = array_values(array_unique(array_filter(array_merge($processResult['reference_images'], $reference_images))));
  4400. // 角色音色参考音频(顺序与提示词中的<音频N>标记一一对应)
  4401. $reference_audios = $supportAudioReference ? ($processResult['reference_audios'] ?? []) : [];
  4402. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4403. // 保存到episode表(仅在专用方法中更新模型)
  4404. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4405. // 'video_model' => $model,
  4406. // 'updated_at' => date('Y-m-d H:i:s')
  4407. // ]);
  4408. // 余额预检:按预估时长计算所需积分,不足直接报错
  4409. $chargeDuration = (int)$videoDuration;
  4410. if ($chargeDuration <= 0) {
  4411. $chargeDuration = 5; // 无时长时按默认5秒预估
  4412. }
  4413. $this->pointsService->checkUserPointsEnough(
  4414. $this->pointsService->getVideoChargePoints([
  4415. 'model' => $model,
  4416. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4417. 'video_duration' => $chargeDuration,
  4418. 'ratio' => $ratio,
  4419. 'generate_audio' => $current_generate_audio,
  4420. ])
  4421. );
  4422. // 构建视频生成参数
  4423. $videoParams = [
  4424. 'model' => $model,
  4425. 'alias_act_id' => $act_id,
  4426. 'prompt' => trim($fullPrompt),
  4427. 'video_duration' => $videoDuration,
  4428. 'video_resolution' => $video_resolution,
  4429. 'seed' => -1,
  4430. 'ratio' => $ratio,
  4431. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4432. 'draft' => false,
  4433. 'watermark' => false,
  4434. 'camera_fixed' => false,
  4435. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4436. ];
  4437. // 如果分镜有图片,作为首帧
  4438. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4439. $hasVideo = !empty(getProp($act, 'video_url'));
  4440. if ($hasImage) {
  4441. if ($first_frame_url) {
  4442. $videoParams['first_frame_url'] = $first_frame_url;
  4443. }else {
  4444. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4445. }
  4446. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4447. }
  4448. // 构建content数组
  4449. $videoParams['content'] = [
  4450. [
  4451. 'type' => 'text',
  4452. 'text' => $videoParams['prompt'],
  4453. ]
  4454. ];
  4455. // 如果有首帧图片,添加到content中
  4456. if ($hasImage) {
  4457. 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'])) {
  4458. $videoParams['content'][] = [
  4459. 'type' => 'image_url',
  4460. 'image_url' => [
  4461. 'url' => $videoParams['first_frame_url'],
  4462. ],
  4463. 'role' => 'reference_image',
  4464. ];
  4465. if (isset($videoParams['tail_frame_url'])) {
  4466. $videoParams['content'][] = [
  4467. 'type' => 'image_url',
  4468. 'image_url' => [
  4469. 'url' => $videoParams['tail_frame_url'],
  4470. ],
  4471. 'role' => 'reference_image',
  4472. ];
  4473. }
  4474. }else {
  4475. $videoParams['content'][] = [
  4476. 'type' => 'image_url',
  4477. 'image_url' => [
  4478. 'url' => $videoParams['first_frame_url'],
  4479. ],
  4480. 'role' => 'first_frame',
  4481. ];
  4482. if (isset($videoParams['tail_frame_url'])) {
  4483. $videoParams['content'][] = [
  4484. 'type' => 'image_url',
  4485. 'image_url' => [
  4486. 'url' => $videoParams['tail_frame_url'],
  4487. ],
  4488. 'role' => 'last_frame',
  4489. ];
  4490. }
  4491. }
  4492. }
  4493. // dd($videoParams);
  4494. // 根据模型选择不同的视频生成方法
  4495. try {
  4496. if (strpos($model, 'jimeng') !== false) {
  4497. // 即梦模型参数调整
  4498. unset($videoParams['content']); // 即梦不使用content格式
  4499. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4500. } elseif (strpos($model, 'kling') !== false) {
  4501. // Keling模型参数调整
  4502. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4503. unset($videoParams['ratio']);
  4504. unset($videoParams['content']); // Keling不使用content格式
  4505. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4506. } elseif (strpos($model, 'zhizhen') !== false) {
  4507. // 智帧20等新模型使用统一API
  4508. // 构建统一API参数
  4509. $unifiedParams = [
  4510. 'model_code' => $model,
  4511. 'alias_act_id' => $act_id,
  4512. 'prompt' => trim($fullPrompt),
  4513. 'video_duration' => $videoDuration,
  4514. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4515. 'video_ratio' => $ratio,
  4516. 'seed' => -1,
  4517. ];
  4518. // 构建parameters参数
  4519. $parameters = [
  4520. 'seconds' => $unifiedParams['video_duration'],
  4521. 'resolution' => $unifiedParams['video_resolution'],
  4522. 'ratio' => $ratio,
  4523. // 'video_mode' => 'multi_image',
  4524. // 'mode' => 'multi_image',
  4525. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4526. ];
  4527. $hasImage = false;
  4528. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4529. if ($hasImage) {
  4530. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4531. if (isset($videoParams['tail_frame_url'])) {
  4532. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4533. }
  4534. } else {
  4535. // 没有图片时,记录错误日志
  4536. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4537. 'act_id' => $act_id,
  4538. 'model' => $model
  4539. ]);
  4540. }
  4541. if ($reference_images) {
  4542. // 限制只传入9张参考图
  4543. $reference_images = array_slice($reference_images, 0, 9);
  4544. // 在处理之前先保存原始reference_images到任务参数中
  4545. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4546. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4547. $parameters['reference_images'] = $reference_images;
  4548. $parameters['video_mode'] = 'multi_image';
  4549. $parameters['mode'] = 'multi_image';
  4550. }
  4551. // 角色音色参考音频:上传为素材并传入统一API(上传失败时清理提示词中的<音频N>标记)
  4552. if ($reference_audios) {
  4553. $unifiedParams['ref_audio_url'] = json_encode($reference_audios, 256);
  4554. // 任务记录:参考图与参考音频一起存入 ref_image_url
  4555. $unifiedParams['ref_image_url'] = $this->mergeReferenceAudiosIntoRefImageUrl($unifiedParams['ref_image_url'] ?? '', $reference_audios);
  4556. $reference_audio_assets = $this->processActReferenceAudiosToAssets($reference_audios, $model, $unifiedParams['prompt']);
  4557. $parameters['reference_audios'] = $reference_audio_assets;
  4558. // 音频素材上传失败的角色回退到音色提示词
  4559. $unifiedParams['prompt'] = $this->applyAudioVoiceFallbacks($unifiedParams['prompt'], $processResult['audio_voice_fallbacks'] ?? []);
  4560. $unifiedParams['prompt'] = trim($unifiedParams['prompt']);
  4561. }
  4562. $unifiedParams['parameters'] = $parameters;
  4563. // 调用统一API创建任务
  4564. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4565. } elseif ($this->isSeedance20SeriesModel($model)) {
  4566. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4567. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4568. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4569. // 保存原始参考图用于任务记录
  4570. $videoParams['reference_images'] = $reference_images;
  4571. if ($reference_images) {
  4572. // 限制只传入9张参考图
  4573. $reference_images = array_slice($reference_images, 0, 9);
  4574. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4575. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4576. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4577. $reference_image_assets = $isKuaikuai
  4578. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4579. : ($isDreamina
  4580. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $fullPrompt)
  4581. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt));
  4582. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4583. $videoParams['prompt'] = trim($fullPrompt);
  4584. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4585. $videoParams['reference_image_assets'] = $reference_image_assets;
  4586. }
  4587. // 角色音色参考音频:上传为素材并传入网关(上传失败时清理提示词中的<音频N>标记)
  4588. if ($reference_audios) {
  4589. $videoParams['ref_audio_url'] = json_encode($reference_audios, 256);
  4590. // 任务记录:参考图与参考音频一起存入 ref_image_url
  4591. $videoParams['ref_image_url'] = $this->mergeReferenceAudiosIntoRefImageUrl($videoParams['ref_image_url'] ?? '', $reference_audios);
  4592. $reference_audio_assets = $this->processActReferenceAudiosToAssets($reference_audios, $model, $fullPrompt);
  4593. // 音频素材上传失败的角色回退到音色提示词
  4594. $fullPrompt = $this->applyAudioVoiceFallbacks($fullPrompt, $processResult['audio_voice_fallbacks'] ?? []);
  4595. $videoParams['prompt'] = trim($fullPrompt);
  4596. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4597. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4598. }
  4599. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4600. if ($isKuaikuai) {
  4601. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4602. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4603. } else {
  4604. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4605. }
  4606. } else {
  4607. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4608. }
  4609. } catch (ApiException $e) {
  4610. // 上游调用抛出的网关异常统一做友好化处理;本地业务错误(非1001)保持原提示不变
  4611. if ($e->getCode() === 1001) {
  4612. Utils::throwError('1001:' . mapErrorMessage($e->getMessage()));
  4613. }
  4614. throw $e;
  4615. } catch (\Exception $e) {
  4616. // 其他未包装的异常,同样只对报错信息做格式化,便于前端展示友好提示
  4617. Utils::throwError('20003:' . mapErrorMessage($e->getMessage()));
  4618. }
  4619. // 更新分镜表的视频任务信息
  4620. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4621. 'video_task_id' => $task->id,
  4622. 'video_task_status' => '生成中',
  4623. 'generate_audio' => $generate_audio,
  4624. 'updated_at' => date('Y-m-d H:i:s')
  4625. ]);
  4626. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4627. $episode_number = getProp($act, 'episode_number');
  4628. $act_number = getProp($act, 'act_number');
  4629. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4630. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4631. }
  4632. $result = [
  4633. 'task_id' => $task->id,
  4634. 'status' => $task->status,
  4635. 'act_id' => $act_id,
  4636. 'video_duration' => $videoDuration
  4637. ];
  4638. // 仅当任务提交阶段就已失败时,附带格式化后的错误信息;正常返回结构不受影响
  4639. if ($task->status === 'failed' && !empty($task->error_message)) {
  4640. $result['error_message'] = mapErrorMessage($task->error_message);
  4641. }
  4642. return $result;
  4643. }
  4644. /**
  4645. * 文生视频通用方法
  4646. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4647. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4648. *
  4649. * @param array $data 请求参数
  4650. * @return array
  4651. */
  4652. public function generateVideo($data) {
  4653. $prompt = getProp($data, 'prompt');
  4654. if (empty($prompt)) {
  4655. Utils::throwError('20003:提示词不能为空');
  4656. }
  4657. $model = getProp($data, 'model');
  4658. if (!$model) {
  4659. $model = 'seed-2';
  4660. }
  4661. // 验证模型是否在可用模型表中
  4662. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4663. Utils::throwError('20003:该模型已不可用,请更换!');
  4664. }
  4665. $video_duration = getProp($data, 'video_duration', 5);
  4666. // 默认超分720p档(按480p生成后本地超分到720p);480p为原始档需前端显式指定
  4667. $video_resolution = getProp($data, 'video_resolution', 'sr_720p');
  4668. $ratio = getProp($data, 'ratio', '9:16');
  4669. $generate_audio = getProp($data, 'generate_audio', 1);
  4670. $seed = getProp($data, 'seed', -1);
  4671. $first_frame_url = getProp($data, 'first_frame_url');
  4672. $tail_frame_url = getProp($data, 'tail_frame_url');
  4673. // 参考图(支持数组或JSON字符串,最多9张)
  4674. $reference_images = getProp($data, 'reference_images', []);
  4675. if (is_string($reference_images)) {
  4676. $reference_images = json_decode($reference_images, true) ?: [];
  4677. }
  4678. if (!is_array($reference_images)) {
  4679. Utils::throwError('20003:参考图格式不正确');
  4680. }
  4681. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4682. $reference_images = array_slice($reference_images, 0, 9);
  4683. // 参考视频(支持数组或JSON字符串,最多3个)
  4684. $reference_videos = getProp($data, 'reference_videos', []);
  4685. if (is_string($reference_videos)) {
  4686. $reference_videos = json_decode($reference_videos, true) ?: [];
  4687. }
  4688. if (!is_array($reference_videos)) {
  4689. Utils::throwError('20003:参考视频格式不正确');
  4690. }
  4691. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4692. if (count($reference_videos) > 3) {
  4693. Utils::throwError('20003:参考视频最多选择3个');
  4694. }
  4695. $reference_videos = array_slice($reference_videos, 0, 3);
  4696. // 参考音频(支持数组或JSON字符串,最多3个)
  4697. $reference_audios = getProp($data, 'reference_audios', []);
  4698. if (is_string($reference_audios)) {
  4699. $reference_audios = json_decode($reference_audios, true) ?: [];
  4700. }
  4701. if (!is_array($reference_audios)) {
  4702. Utils::throwError('20003:参考音频格式不正确');
  4703. }
  4704. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4705. if (count($reference_audios) > 3) {
  4706. Utils::throwError('20003:参考音频最多选择3个');
  4707. }
  4708. $reference_audios = array_slice($reference_audios, 0, 3);
  4709. // 余额预检:按预估时长计算所需积分,不足直接报错
  4710. $chargeDuration = (int)ceil((float)$video_duration);
  4711. if ($chargeDuration <= 0) {
  4712. $chargeDuration = 5; // 无时长时按默认5秒预估
  4713. }
  4714. $this->pointsService->checkUserPointsEnough(
  4715. $this->pointsService->getVideoChargePoints([
  4716. 'model' => $model,
  4717. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4718. 'video_duration' => $chargeDuration,
  4719. 'ratio' => $ratio,
  4720. 'generate_audio' => (int)$generate_audio,
  4721. ])
  4722. );
  4723. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4724. $videoParams = [
  4725. 'model' => $model,
  4726. 'prompt' => $prompt,
  4727. 'video_duration' => $video_duration,
  4728. 'video_resolution' => $video_resolution,
  4729. 'seed' => $seed,
  4730. 'ratio' => $ratio,
  4731. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4732. 'draft' => getProp($data, 'draft', false),
  4733. 'watermark' => getProp($data, 'watermark', false),
  4734. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4735. ];
  4736. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4737. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4738. // 构建content数组
  4739. $videoParams['content'] = [
  4740. [
  4741. 'type' => 'text',
  4742. 'text' => $prompt,
  4743. ]
  4744. ];
  4745. // 根据模型选择不同的视频生成方法
  4746. if (strpos($model, 'jimeng') !== false) {
  4747. // 即梦模型参数调整
  4748. unset($videoParams['content']); // 即梦不使用content格式
  4749. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4750. } elseif (strpos($model, 'kling') !== false) {
  4751. // 可灵模型参数调整
  4752. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4753. unset($videoParams['ratio']);
  4754. unset($videoParams['content']); // 可灵不使用content格式
  4755. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4756. } elseif (strpos($model, 'zhizhen') !== false) {
  4757. // 智帧等新模型使用统一API
  4758. $unifiedParams = [
  4759. 'model_code' => $model,
  4760. 'prompt' => $prompt,
  4761. 'video_duration' => $video_duration,
  4762. 'video_resolution' => strtolower($video_resolution),
  4763. 'video_ratio' => $ratio,
  4764. 'seed' => $seed,
  4765. ];
  4766. // 构建parameters参数
  4767. $parameters = [
  4768. 'seconds' => $unifiedParams['video_duration'],
  4769. 'resolution' => $unifiedParams['video_resolution'],
  4770. 'ratio' => $ratio,
  4771. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4772. ];
  4773. // 首帧和尾帧
  4774. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4775. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4776. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4777. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4778. if ($refImageUrls) {
  4779. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4780. }
  4781. // 参考图处理
  4782. if ($reference_images) {
  4783. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4784. $parameters['reference_images'] = $reference_images;
  4785. $parameters['video_mode'] = 'multi_image';
  4786. $parameters['mode'] = 'multi_image';
  4787. }
  4788. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4789. if ($reference_videos) {
  4790. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4791. $parameters['reference_videos'] = $reference_videos;
  4792. }
  4793. if ($reference_audios) {
  4794. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4795. $parameters['reference_audios'] = $reference_audios;
  4796. }
  4797. $unifiedParams['parameters'] = $parameters;
  4798. // 调用统一API创建任务
  4799. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4800. } elseif ($this->isSeedance20SeriesModel($model)) {
  4801. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4802. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4803. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4804. $videoParams['reference_images'] = $reference_images;
  4805. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4806. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4807. if ($refImageUrls) {
  4808. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4809. }
  4810. if ($reference_images) {
  4811. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI)
  4812. $reference_image_assets = $isKuaikuai
  4813. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4814. : ($isDreamina
  4815. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $videoParams['prompt'])
  4816. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']));
  4817. $videoParams['reference_image_assets'] = $reference_image_assets;
  4818. }
  4819. // 参考视频上传为素材(国内百度/海外百度dreamina/快快AI)
  4820. if ($reference_videos) {
  4821. $reference_video_assets = $isKuaikuai
  4822. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4823. : ($isDreamina
  4824. ? $this->aiVideoGenerationService->processReferenceVideosToBaiduDreaminaAssets($reference_videos, $videoParams['prompt'])
  4825. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']));
  4826. $videoParams['reference_video_assets'] = $reference_video_assets;
  4827. }
  4828. // 参考音频上传为素材(国内百度/海外百度dreamina/快快AI)
  4829. if ($reference_audios) {
  4830. $reference_audio_assets = $isKuaikuai
  4831. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4832. : ($isDreamina
  4833. ? $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($reference_audios, $videoParams['prompt'])
  4834. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']));
  4835. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4836. }
  4837. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4838. if ($reference_images || $reference_videos || $reference_audios) {
  4839. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4840. }
  4841. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4842. if ($isKuaikuai) {
  4843. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4844. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4845. } else {
  4846. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4847. }
  4848. } else {
  4849. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4850. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4851. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4852. if ($refImageUrls) {
  4853. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4854. }
  4855. if ($reference_videos) {
  4856. foreach ($reference_videos as $videoUrl) {
  4857. $videoParams['content'][] = [
  4858. 'type' => 'video_url',
  4859. 'video_url' => [
  4860. 'url' => $videoUrl,
  4861. ],
  4862. 'role' => 'reference_video',
  4863. ];
  4864. }
  4865. }
  4866. if ($reference_audios) {
  4867. foreach ($reference_audios as $audioUrl) {
  4868. $videoParams['content'][] = [
  4869. 'type' => 'audio_url',
  4870. 'audio_url' => [
  4871. 'url' => $audioUrl,
  4872. ],
  4873. 'role' => 'reference_audio',
  4874. ];
  4875. }
  4876. }
  4877. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4878. }
  4879. return [
  4880. 'task_id' => $task->id,
  4881. 'status' => $task->status,
  4882. 'model' => $model,
  4883. 'video_duration' => $video_duration,
  4884. 'video_resolution' => $video_resolution,
  4885. 'ratio' => $ratio
  4886. ];
  4887. }
  4888. /**
  4889. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4890. *
  4891. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4892. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4893. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4894. *
  4895. * @param array $data
  4896. * @return array
  4897. */
  4898. public function previewCharge(array $data): array
  4899. {
  4900. $mode = (string)getProp($data, 'mode', '');
  4901. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4902. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4903. }
  4904. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4905. $scene = (string)getProp($data, 'scene', 'video_generation');
  4906. // 未显式传scene且带参考视频时,自动按video_to_video定价
  4907. if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
  4908. $scene = 'video_to_video';
  4909. }
  4910. $items = [];
  4911. $model = '';
  4912. $resolution = '';
  4913. if ($mode === 'video') {
  4914. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4915. $model = (string)getProp($data, 'model', '');
  4916. if (!$model) {
  4917. Utils::throwError('1002:model参数不能为空');
  4918. }
  4919. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4920. $duration = (int)getProp($data, 'video_duration', 5);
  4921. if ($duration <= 0) {
  4922. $duration = 5;
  4923. }
  4924. $count = max(1, (int)getProp($data, 'count', 1));
  4925. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4926. 'model' => $model,
  4927. 'video_resolution' => $resolution,
  4928. 'video_duration' => $duration,
  4929. 'mode' => $scene,
  4930. ]);
  4931. $points = $pointsPerVideo * $count;
  4932. $items[] = [
  4933. 'type' => 'video',
  4934. 'model' => $model,
  4935. 'video_resolution' => $resolution,
  4936. 'video_duration' => $duration,
  4937. 'count' => $count,
  4938. 'points' => $points,
  4939. ];
  4940. } elseif ($mode === 'image') {
  4941. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4942. $model = (string)getProp($data, 'model', '');
  4943. if (!$model) {
  4944. Utils::throwError('1002:model参数不能为空');
  4945. }
  4946. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4947. if (!$resolution) {
  4948. $width = (int)getProp($data, 'width', 0);
  4949. $height = (int)getProp($data, 'height', 0);
  4950. if ($width <= 0 || $height <= 0) {
  4951. $width = 1600;
  4952. $height = 2848;
  4953. }
  4954. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4955. }
  4956. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4957. $points = $this->pointsService->getImageChargePoints([
  4958. 'model' => $model,
  4959. 'resolution' => $resolution,
  4960. ]) * $imageNum;
  4961. $items[] = [
  4962. 'type' => 'image',
  4963. 'model' => $model,
  4964. 'resolution' => $resolution,
  4965. 'image_num' => $imageNum,
  4966. 'points' => $points,
  4967. ];
  4968. } else {
  4969. // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
  4970. // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
  4971. $priceType = (string)getProp($data, 'price_type', 'special');
  4972. if (!in_array($priceType, ['special', 'normal'], true)) {
  4973. Utils::throwError('1003:price_type参数仅支持special或normal');
  4974. }
  4975. $count = max(1, (int)getProp($data, 'count', 1));
  4976. $animeId = getProp($data, 'anime_id');
  4977. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4978. if ($animeId && $generateEpisodes > 0) {
  4979. // 批量生成分集按 special 档预估,与实际扣费口径一致
  4980. $priceType = 'special';
  4981. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4982. ->where('anime_id', $animeId)
  4983. ->where('is_default', 1)
  4984. ->max('episode_number');
  4985. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4986. $startEpisodeNumber = $currentMaxEpisode + 1;
  4987. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4988. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4989. ->where('anime_id', $animeId)
  4990. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4991. ->whereIn('status', ['pending', 'processing', 'completed'])
  4992. ->count();
  4993. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4994. if ($count < 0) {
  4995. $count = 0;
  4996. }
  4997. }
  4998. $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
  4999. $items[] = [
  5000. 'type' => 'chat',
  5001. 'count' => $count,
  5002. 'price_type' => $priceType,
  5003. 'points' => $points,
  5004. ];
  5005. }
  5006. $totalPoints = 0;
  5007. foreach ($items as $item) {
  5008. $totalPoints += $item['points'];
  5009. }
  5010. return [
  5011. 'mode' => $mode,
  5012. 'total_points' => $totalPoints,
  5013. 'items' => $items,
  5014. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  5015. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  5016. ];
  5017. }
  5018. /**
  5019. * 根据提示词内容智能计算最优视频时长
  5020. *
  5021. * @param string $segmentContent 分镜内容
  5022. * @param string $tailFrame 尾帧描述
  5023. * @return int 视频时长(2-12秒)
  5024. */
  5025. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  5026. // 合并所有文本内容
  5027. $fullText = trim($segmentContent . ' ' . $tailFrame);
  5028. // 如果没有内容,返回默认时长
  5029. if (empty($fullText)) {
  5030. return 5;
  5031. }
  5032. // 计算文本长度(中文字符按2个字符计算)
  5033. $textLength = mb_strlen($fullText, 'UTF-8');
  5034. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  5035. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  5036. // 分析内容复杂度
  5037. $complexityScore = $this->analyzeContentComplexity($fullText);
  5038. // 基础时长计算(根据文本长度)
  5039. $baseDuration = 3; // 默认2秒
  5040. // if ($adjustedLength <= 20) {
  5041. // $baseDuration = 3;
  5042. // } elseif ($adjustedLength <= 40) {
  5043. // $baseDuration = 4;
  5044. // } elseif ($adjustedLength <= 60) {
  5045. // $baseDuration = 5;
  5046. // } elseif ($adjustedLength <= 80) {
  5047. // $baseDuration = 6;
  5048. // } elseif ($adjustedLength <= 100) {
  5049. // $baseDuration = 7;
  5050. // } elseif ($adjustedLength <= 120) {
  5051. // $baseDuration = 8;
  5052. // } else {
  5053. // $baseDuration = 9;
  5054. // }
  5055. // 根据内容复杂度调整时长
  5056. $finalDuration = $baseDuration + $complexityScore;
  5057. // 确保时长在2-12秒范围内
  5058. return max(4, min(12, $finalDuration));
  5059. }
  5060. /**
  5061. * 分析内容复杂度,返回时长调整值
  5062. *
  5063. * @param string $text 文本内容
  5064. * @return int 调整值(-2到+3)
  5065. */
  5066. private function analyzeContentComplexity($text) {
  5067. $score = 0;
  5068. // 动作关键词(需要更长时间展现)
  5069. $actionKeywords = [
  5070. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  5071. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  5072. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  5073. ];
  5074. // 静态关键词(可以用较短时间)
  5075. $staticKeywords = [
  5076. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  5077. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  5078. ];
  5079. // 复杂场景关键词(需要更长时间)
  5080. $complexSceneKeywords = [
  5081. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  5082. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  5083. ];
  5084. // 情感关键词(需要适中时间表现)
  5085. $emotionKeywords = [
  5086. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  5087. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  5088. ];
  5089. // 检查动作关键词
  5090. foreach ($actionKeywords as $keyword) {
  5091. if (strpos($text, $keyword) !== false) {
  5092. $score += 1;
  5093. break; // 避免重复加分
  5094. }
  5095. }
  5096. // 检查静态关键词
  5097. foreach ($staticKeywords as $keyword) {
  5098. if (strpos($text, $keyword) !== false) {
  5099. $score -= 1;
  5100. break;
  5101. }
  5102. }
  5103. // 检查复杂场景关键词
  5104. foreach ($complexSceneKeywords as $keyword) {
  5105. if (strpos($text, $keyword) !== false) {
  5106. $score += 1;
  5107. break;
  5108. }
  5109. }
  5110. // 检查情感关键词
  5111. foreach ($emotionKeywords as $keyword) {
  5112. if (strpos($text, $keyword) !== false) {
  5113. $score += 1;
  5114. break;
  5115. }
  5116. }
  5117. // 检查时间相关词汇
  5118. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  5119. $score += 1;
  5120. }
  5121. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  5122. $score -= 1;
  5123. }
  5124. // 检查转场词汇
  5125. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  5126. $score += 1;
  5127. }
  5128. // 检查环境描述(复杂环境需要更多时间)
  5129. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  5130. $score += 1;
  5131. }
  5132. // 检查对话内容(对话需要更多时间)
  5133. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  5134. $score += 1;
  5135. }
  5136. // 限制调整范围
  5137. return max(-1, min(4, $score));
  5138. }
  5139. /**
  5140. * 创建完整视频合成任务
  5141. *
  5142. * @param array $data
  5143. * @return array
  5144. */
  5145. public function createCompleteVideoTask($data)
  5146. {
  5147. $animeId = getProp($data, 'anime_id');
  5148. $episodeId = getProp($data, 'episode_id');
  5149. // 验证参数
  5150. if (!$animeId || !$episodeId) {
  5151. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  5152. }
  5153. // 检查是否已存在处理中的任务
  5154. $existingTask = DB::table('mp_complete_video_tasks')
  5155. ->where('anime_id', $animeId)
  5156. ->where('episode_id', $episodeId)
  5157. ->whereIn('generate_status', ['执行中'])
  5158. ->first();
  5159. if ($existingTask) {
  5160. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  5161. }
  5162. // 获取全能模式状态
  5163. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  5164. if ((int)$ace_mode === 1) {
  5165. // 获取所有片段的配音视频,按 act_number 排序
  5166. $segments = DB::table('mp_episode_segments')
  5167. ->where('anime_id', $animeId)
  5168. ->where('episode_id', $episodeId)
  5169. ->orderBy('segment_number')
  5170. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5171. ->get();
  5172. // 检查是否所有片段都有视频
  5173. $missingVideos = $segments->filter(function($segment) {
  5174. return empty($segment->video_url);
  5175. });
  5176. if ($missingVideos->isNotEmpty()) {
  5177. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  5178. }
  5179. }else {
  5180. // 获取所有分镜的配音视频,按 segment_number 排序
  5181. $segments = DB::table('mp_episode_segments')
  5182. ->where('anime_id', $animeId)
  5183. ->where('episode_id', $episodeId)
  5184. ->orderBy('segment_number')
  5185. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5186. ->get();
  5187. // 检查是否所有分镜都有配音和视频
  5188. $missingVideos = $segments->filter(function($segment) {
  5189. return empty($segment->audio_url) || empty($segment->video_url);
  5190. });
  5191. if ($missingVideos->isNotEmpty()) {
  5192. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5193. }
  5194. }
  5195. if ($segments->isEmpty()) {
  5196. Utils::throwError('20003:未找到该剧集的分镜数据');
  5197. }
  5198. // 获取当前完整视频url
  5199. $completeVideoUrl = DB::table('mp_anime_episodes')
  5200. ->where('anime_id', $animeId)
  5201. ->where('id', $episodeId)
  5202. ->value('complete_video_url');
  5203. // 构建 generate_json
  5204. $generateJson = [];
  5205. $sequence = 1;
  5206. foreach ($segments as $segment) {
  5207. if ((int)$ace_mode === 1) {
  5208. $generateJson[] = [
  5209. 'sequence' => $sequence++,
  5210. 'video_url' => $segment->video_url,
  5211. 'video_time_point_start' => $segment->video_time_point_start,
  5212. 'video_time_point_end' => $segment->video_time_point_end
  5213. ];
  5214. }else {
  5215. $generateJson[] = [
  5216. 'sequence' => $sequence++,
  5217. 'video_url' => $segment->video_url,
  5218. 'audio_url' => $segment->audio_url,
  5219. 'video_time_point_start' => $segment->video_time_point_start,
  5220. 'video_time_point_end' => $segment->video_time_point_end
  5221. ];
  5222. }
  5223. }
  5224. // 创建任务
  5225. $now = date('Y-m-d H:i:s');
  5226. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5227. 'anime_id' => $animeId,
  5228. 'episode_id' => $episodeId,
  5229. 'generate_json' => json_encode($generateJson, 256),
  5230. 'generate_status' => '执行中',
  5231. 'complete_video_url' => '',
  5232. 'created_at' => $now,
  5233. 'updated_at' => $now
  5234. ]);
  5235. if (!$taskId) {
  5236. Utils::throwError('20003:创建任务失败');
  5237. }
  5238. // 更新剧集表的任务ID和状态
  5239. $boolen = DB::table('mp_anime_episodes')
  5240. ->where('anime_id', $animeId)
  5241. ->where('id', $episodeId)
  5242. ->update([
  5243. 'complete_video_task_id' => $taskId,
  5244. 'complete_video_task_status' => '执行中',
  5245. 'updated_at' => $now
  5246. ]);
  5247. if (!$boolen) {
  5248. Utils::throwError('20003:更新剧集表失败');
  5249. }
  5250. dLog('anime')->info('创建完整视频合成任务', [
  5251. 'task_id' => $taskId,
  5252. 'anime_id' => $animeId,
  5253. 'episode_id' => $episodeId,
  5254. 'segment_count' => count($generateJson)
  5255. ]);
  5256. // 请求远程服务器执行生成
  5257. $client = new Client(['timeout' => 600, 'verify' => false]);
  5258. try {
  5259. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5260. $response = $result->getBody()->getContents();
  5261. $response_arr = json_decode($response, true);
  5262. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5263. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5264. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5265. // // 更新任务状态为失败
  5266. // DB::table('mp_complete_video_tasks')
  5267. // ->where('id', $taskId)
  5268. // ->update([
  5269. // 'generate_status' => '执行失败',
  5270. // 'error_message' => $error_msg,
  5271. // 'updated_at' => date('Y-m-d H:i:s')
  5272. // ]);
  5273. // // 同步更新剧集表状态
  5274. // DB::table('mp_anime_episodes')
  5275. // ->where('complete_video_task_id', $taskId)
  5276. // ->update([
  5277. // 'complete_video_task_status' => '执行失败',
  5278. // 'updated_at' => date('Y-m-d H:i:s')
  5279. // ]);
  5280. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5281. }
  5282. } catch (\Exception $e) {
  5283. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5284. // 更新任务状态为失败
  5285. DB::table('mp_complete_video_tasks')
  5286. ->where('id', $taskId)
  5287. ->update([
  5288. 'generate_status' => '执行失败',
  5289. 'error_message' => $e->getMessage(),
  5290. 'updated_at' => date('Y-m-d H:i:s')
  5291. ]);
  5292. // 同步更新剧集表状态
  5293. DB::table('mp_anime_episodes')
  5294. ->where('complete_video_task_id', $taskId)
  5295. ->update([
  5296. 'complete_video_task_status' => '执行失败',
  5297. 'updated_at' => date('Y-m-d H:i:s')
  5298. ]);
  5299. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5300. }
  5301. // 开始轮询任务状态
  5302. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5303. $pollInterval = 5; // 每5秒轮询一次
  5304. $attempt = 0;
  5305. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5306. while ($attempt < $maxAttempts) {
  5307. sleep($pollInterval);
  5308. $attempt++;
  5309. // 查询任务状态
  5310. $task = DB::table('mp_complete_video_tasks')
  5311. ->where('id', $taskId)
  5312. ->first();
  5313. if (!$task) {
  5314. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5315. Utils::throwError('20003:任务不存在');
  5316. }
  5317. dLog('anime')->info('轮询任务状态', [
  5318. 'task_id' => $taskId,
  5319. 'attempt' => $attempt,
  5320. 'status' => $task->generate_status
  5321. ]);
  5322. // 检查任务是否完成
  5323. if ($task->generate_status === '执行成功') {
  5324. // 同步更新剧集表状态
  5325. $boolen3 = DB::table('mp_anime_episodes')
  5326. ->where('anime_id', $animeId)
  5327. ->where('id', $episodeId)
  5328. ->update([
  5329. 'complete_video_url' => $task->complete_video_url,
  5330. 'complete_video_task_status' => '执行成功',
  5331. 'updated_at' => date('Y-m-d H:i:s')
  5332. ]);
  5333. dLog('anime')->info('视频合成任务完成', [
  5334. 'task_id' => $taskId,
  5335. 'video_url' => $task->complete_video_url,
  5336. 'attempts' => $attempt
  5337. ]);
  5338. // 如果更新成功则远程删除之前的文件
  5339. if ($boolen3 && $completeVideoUrl) {
  5340. $encode_url = urlencode($completeVideoUrl);
  5341. $client = new Client(['timeout' => 300, 'verify' => false]);
  5342. // 根据ID通过API通知合成音频
  5343. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5344. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5345. $response = $result->getBody()->getContents();
  5346. $response_arr = json_decode($response, true);
  5347. Log::info('火山删除音频返回: '.$response);
  5348. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5349. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5350. Log::info('火山删除音频失败: '.$error_msg);
  5351. // Utils::throwError('20003:火山删除音频失败');
  5352. }
  5353. }
  5354. return [
  5355. 'task_id' => $taskId,
  5356. 'anime_id' => $animeId,
  5357. 'episode_id' => $episodeId,
  5358. 'segment_count' => count($generateJson),
  5359. 'generate_status' => '执行成功',
  5360. 'complete_video_url' => $task->complete_video_url,
  5361. ];
  5362. }
  5363. // 检查任务是否失败
  5364. if ($task->generate_status === '执行失败') {
  5365. // 同步更新剧集表状态
  5366. DB::table('mp_anime_episodes')
  5367. ->where('anime_id', $animeId)
  5368. ->where('id', $episodeId)
  5369. ->update([
  5370. 'complete_video_task_status' => '执行失败',
  5371. 'updated_at' => date('Y-m-d H:i:s')
  5372. ]);
  5373. $errorMessage = $task->error_message ?? '未知错误';
  5374. dLog('anime')->error('视频合成任务失败', [
  5375. 'task_id' => $taskId,
  5376. 'error' => $errorMessage,
  5377. 'attempts' => $attempt
  5378. ]);
  5379. return [
  5380. 'task_id' => $taskId,
  5381. 'anime_id' => $animeId,
  5382. 'episode_id' => $episodeId,
  5383. 'segment_count' => count($generateJson),
  5384. 'generate_status' => '执行失败',
  5385. 'error_message' => $errorMessage
  5386. ];
  5387. }
  5388. }
  5389. // 超时处理
  5390. dLog('anime')->warning('视频合成任务超时', [
  5391. 'task_id' => $taskId,
  5392. 'max_attempts' => $maxAttempts,
  5393. 'timeout_seconds' => $maxAttempts * $pollInterval
  5394. ]);
  5395. // 更新任务状态为超时
  5396. DB::table('mp_complete_video_tasks')
  5397. ->where('id', $taskId)
  5398. ->update([
  5399. 'generate_status' => '超时',
  5400. 'error_message' => '任务执行超时(5分钟)',
  5401. 'updated_at' => date('Y-m-d H:i:s')
  5402. ]);
  5403. return [
  5404. 'task_id' => $taskId,
  5405. 'anime_id' => $animeId,
  5406. 'episode_id' => $episodeId,
  5407. 'segment_count' => count($generateJson),
  5408. 'generate_status' => '超时',
  5409. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5410. ];
  5411. }
  5412. /**
  5413. * 根据 inner_prompt_type 附加内置提示词
  5414. *
  5415. * @param string $prompt 用户提示词
  5416. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5417. * @return string 合并后的提示词
  5418. */
  5419. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5420. {
  5421. $innerPromptMap = [
  5422. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。',
  5423. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5424. ];
  5425. if (!isset($innerPromptMap[$innerPromptType])) {
  5426. return $prompt;
  5427. }
  5428. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5429. }
  5430. /**
  5431. * 根据 inner_prompt_type 获取生成图片数量
  5432. *
  5433. * @param int $innerPromptType 内置提示词类型
  5434. * @param int $imageNum 传入的图片张数
  5435. * @return int 图片数量
  5436. */
  5437. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5438. {
  5439. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5440. }
  5441. /**
  5442. * 提取图片生成结果URL
  5443. *
  5444. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5445. * @param int $innerPromptType 内置提示词类型
  5446. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5447. */
  5448. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5449. {
  5450. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5451. if (is_array($resultUrls) && !empty($resultUrls)) {
  5452. $resultUrls = array_values($resultUrls);
  5453. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5454. }
  5455. if (!empty($resultUrl)) {
  5456. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5457. }
  5458. return (int)$innerPromptType === 2 ? [] : '';
  5459. }
  5460. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5461. $prompt = getProp($data, 'prompt');
  5462. $episode_id = getProp($data, 'episode_id');
  5463. $ref_img_urls = getProp($data, 'ref_img_urls');
  5464. $ratio = getProp($data, 'ratio', '9:16');
  5465. $resolution = getProp($data, 'resolution', '2k');
  5466. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5467. $imageNum = (int)getProp($data, 'image_num', 1);
  5468. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  5469. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  5470. // 参数验证
  5471. $resolution = strtolower($resolution);
  5472. if (!isset($sizeMap[$resolution])) {
  5473. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5474. }
  5475. if (!isset($sizeMap[$resolution][$ratio])) {
  5476. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5477. }
  5478. // 根据 ratio 和 resolution 确定宽高
  5479. $width = $sizeMap[$resolution][$ratio]['width'];
  5480. $height = $sizeMap[$resolution][$ratio]['height'];
  5481. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5482. if (is_json($ref_img_urls)) {
  5483. $ref_img_urls = json_decode($ref_img_urls, true);
  5484. }else {
  5485. $ref_img_urls = explode(',', $ref_img_urls);
  5486. }
  5487. }
  5488. // 处理图片模型
  5489. $model = getProp($data, 'model');
  5490. if (!$model) {
  5491. // 用户没有输入,从episode表获取
  5492. if ($episode_id) {
  5493. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5494. $model = getProp($episode, 'image_model');
  5495. }
  5496. if (!$model) {
  5497. // episode表也没有,使用默认值
  5498. $model = 'gpt-image-2';
  5499. }
  5500. }
  5501. // 验证模型是否在可用模型表中
  5502. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5503. // $model = 'gpt-image-2';
  5504. Utils::throwError('20003:该模型已不可用,请更换!');
  5505. }
  5506. // 保存到episode表
  5507. if ($episode_id) {
  5508. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5509. 'image_model' => $model,
  5510. 'updated_at' => date('Y-m-d H:i:s')
  5511. ]);
  5512. }
  5513. // 参数验证
  5514. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5515. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5516. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5517. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5518. try {
  5519. // 创建图片生成任务
  5520. $params = [
  5521. 'prompt' => $prompt,
  5522. 'model' => $model,
  5523. 'ref_img_urls' => '',
  5524. 'width' => $width,
  5525. 'height' => $height,
  5526. 'image_num' => $imageNum,
  5527. // 计费锚点(动漫/剧集/剧本),上下文没有时不记录
  5528. 'anime_id' => getProp($data, 'anime_id'),
  5529. 'episode_id' => $episode_id,
  5530. ];
  5531. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5532. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5533. $task_id = $task->id;
  5534. if (!$task_id) {
  5535. Utils::throwError('20003:创建图片生成任务失败');
  5536. }
  5537. // 创建任务中心记录并关联图片任务ID
  5538. $taskCenter = $this->taskCenterService->createTask('image', [
  5539. 'title' => '文生图',
  5540. 'ref_task_id' => $task_id,
  5541. // 'prompt' => $prompt,
  5542. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5543. ]);
  5544. $taskCenterId = $taskCenter->id;
  5545. // 组装本次任务信息(用于init消息,类似generateVideo)
  5546. $taskInfo = [
  5547. 'task_id' => $task_id,
  5548. 'status' => getProp($task, 'status', 'processing'),
  5549. 'model' => $model,
  5550. 'ratio' => $ratio,
  5551. 'resolution' => $resolution,
  5552. 'image_num' => $imageNum,
  5553. ];
  5554. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5555. if (is_callable($onTaskCreated)) {
  5556. $onTaskCreated($taskCenterId, $taskInfo);
  5557. }
  5558. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5559. $model = getProp($task, 'model');
  5560. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5561. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5562. $isSyncModel = $isVolcModel || $isGptModel;
  5563. // 任务需要轮询获取结果(15分钟超时,每3秒查询一次)
  5564. $start_time = time();
  5565. $timeout = 900; // 15分钟
  5566. $img_url = '';
  5567. $img_urls = [];
  5568. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5569. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5570. while (time() - $start_time < $timeout) {
  5571. sleep(3);
  5572. // 每分钟发送一次队列状态消息(仅流式模式)
  5573. if (is_callable($onPoll)) {
  5574. $currentTime = time();
  5575. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5576. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5577. $lastQueueMessageTime = $currentTime;
  5578. }
  5579. }
  5580. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5581. if ($isSyncModel) {
  5582. // 刷新任务状态
  5583. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5584. if ($task->status === 'success' && $task->result_url) {
  5585. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5586. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5587. if (!empty($resultUrls)) {
  5588. $img_urls = $resultUrls;
  5589. $img_url = $resultUrls[0];
  5590. } else {
  5591. $img_url = (string)$task->result_url;
  5592. }
  5593. break;
  5594. } elseif ($task->status === 'failed') {
  5595. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5596. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5597. }
  5598. // // 如果还在处理中,提示用户稍后查看
  5599. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5600. }else {
  5601. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5602. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5603. if ($statusInfo['status'] === 'success') {
  5604. $task->updateStatus('success', [
  5605. 'result_url' => $statusInfo['result_url'],
  5606. 'result_json' => $statusInfo['result_json'] ?? []
  5607. ]);
  5608. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5609. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5610. if (!empty($resultUrls)) {
  5611. $img_urls = $resultUrls;
  5612. $img_url = $resultUrls[0];
  5613. } else {
  5614. $img_url = (string)$statusInfo['result_url'];
  5615. }
  5616. break;
  5617. } elseif ($statusInfo['status'] === 'failed') {
  5618. $task->updateStatus('failed', [
  5619. 'error_message' => $statusInfo['error_message'],
  5620. 'result_json' => $statusInfo['result_json'] ?? []
  5621. ]);
  5622. dLog('anime')->error('图片生成失败,', [
  5623. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5624. ]);
  5625. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5626. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5627. }
  5628. }
  5629. }
  5630. if (empty($img_url)) {
  5631. Utils::throwError('20003:图片生成超时,请稍后重试');
  5632. }
  5633. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5634. if (count($img_urls) > 1) {
  5635. return [
  5636. 'img_url' => $img_url,
  5637. 'image_urls' => $img_urls,
  5638. 'task_id' => $taskCenterId,
  5639. ];
  5640. }
  5641. return [
  5642. 'img_url' => $img_url,
  5643. 'task_id' => $taskCenterId,
  5644. ];
  5645. } catch (\Exception $e) {
  5646. dLog('anime')->error('更新角色或场景失败', [
  5647. 'error' => $e->getMessage()
  5648. ]);
  5649. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5650. Utils::throwError('20003:' . $e->getMessage());
  5651. }
  5652. }
  5653. /**
  5654. * 使用文生文模型解析分镜内容
  5655. */
  5656. private function parseSegmentContentWithAI($segment_content) {
  5657. try {
  5658. // 使用DeepSeek服务的公开方法解析分镜内容
  5659. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5660. } catch (\Exception $e) {
  5661. // 如果AI解析失败,记录日志并返回原内容
  5662. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5663. return $segment_content;
  5664. }
  5665. }
  5666. /**
  5667. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5668. *
  5669. * @param int $episode_id 分集ID
  5670. * @param int $anime_id 动漫ID
  5671. * @param array $roles 分集角色数组(引用传递)
  5672. * @param array $scenes 分集场景数组(引用传递)
  5673. * @param array $episode 分集数据
  5674. */
  5675. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5676. // 获取全局动漫的角色和场景数据
  5677. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5678. if (!$anime) return;
  5679. $art_style_type = getProp($anime, 'art_style_type');
  5680. $character_prefix = '';
  5681. $scene_prefix = '';
  5682. if ($art_style_type) {
  5683. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5684. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5685. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5686. }
  5687. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5688. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5689. $roles_updated = false;
  5690. $scenes_updated = false;
  5691. // 处理角色
  5692. foreach ($roles as &$role) {
  5693. $role_name = getProp($role, 'role');
  5694. $role_description = getProp($role, 'description');
  5695. $role_pic_prompt = getProp($role, 'pic_prompt');
  5696. $role_url = getProp($role, 'url');
  5697. $role_task_id = getProp($role, 'task_id');
  5698. // 如果已有URL或已有任务ID,跳过
  5699. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5700. continue;
  5701. }
  5702. $url_inherited = false;
  5703. // 尝试从全局数据中继承
  5704. foreach ($global_roles as $global_role) {
  5705. $global_role_name = getProp($global_role, 'role');
  5706. $global_role_description = getProp($global_role, 'description');
  5707. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5708. $global_role_url = getProp($global_role, 'url');
  5709. $global_role_task_id = getProp($global_role, 'task_id');
  5710. $global_role_task_status = getProp($global_role, 'task_status');
  5711. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5712. if ($role_name === $global_role_name
  5713. && $role_description === $global_role_description
  5714. && $role_pic_prompt === $global_role_pic_prompt
  5715. && !empty($global_role_url)) {
  5716. // 继承 task_id、task_status 和 url
  5717. $role['task_id'] = $global_role_task_id;
  5718. $role['task_status'] = $global_role_task_status;
  5719. $role['url'] = $global_role_url;
  5720. $roles_updated = true;
  5721. $url_inherited = true;
  5722. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5723. break;
  5724. }
  5725. }
  5726. // 如果无法继承且没有任务ID,创建新任务
  5727. if (!$url_inherited && empty($role_task_id)) {
  5728. try {
  5729. $art_style = getProp($episode, 'art_style');
  5730. // 优先使用 pic_prompt,如果没有则使用 description
  5731. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5732. // if ($art_style) {
  5733. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5734. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5735. // }
  5736. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5737. $params = [
  5738. 'prompt' => $description,
  5739. 'ref_img_urls' => [],
  5740. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  5741. 'anime_id' => $anime_id,
  5742. 'episode_id' => $episode_id,
  5743. 'episode_number' => getProp($episode, 'episode_number'),
  5744. ];
  5745. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5746. $task_id = $task->id;
  5747. if ($task_id) {
  5748. $role['task_id'] = $task_id;
  5749. $role['task_status'] = 'processing';
  5750. $roles_updated = true;
  5751. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5752. }
  5753. } catch (\Exception $e) {
  5754. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5755. }
  5756. }
  5757. }
  5758. // 处理场景
  5759. foreach ($scenes as &$scene) {
  5760. $scene_name = getProp($scene, 'scene');
  5761. $scene_description = getProp($scene, 'description');
  5762. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5763. $scene_url = getProp($scene, 'url');
  5764. $scene_task_id = getProp($scene, 'task_id');
  5765. // 如果已有URL或已有任务ID,跳过
  5766. if (!empty($scene_url) || !empty($scene_task_id)) {
  5767. continue;
  5768. }
  5769. $url_inherited = false;
  5770. // 尝试从全局数据中继承
  5771. foreach ($global_scenes as $global_scene) {
  5772. $global_scene_name = getProp($global_scene, 'scene');
  5773. $global_scene_description = getProp($global_scene, 'description');
  5774. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5775. $global_scene_url = getProp($global_scene, 'url');
  5776. $global_scene_task_id = getProp($global_scene, 'task_id');
  5777. $global_scene_task_status = getProp($global_scene, 'task_status');
  5778. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5779. if ($scene_name === $global_scene_name
  5780. && $scene_description === $global_scene_description
  5781. && $scene_pic_prompt === $global_scene_pic_prompt
  5782. && !empty($global_scene_url)) {
  5783. // 继承 task_id、task_status 和 url
  5784. $scene['task_id'] = $global_scene_task_id;
  5785. $scene['task_status'] = $global_scene_task_status;
  5786. $scene['url'] = $global_scene_url;
  5787. $scenes_updated = true;
  5788. $url_inherited = true;
  5789. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5790. break;
  5791. }
  5792. }
  5793. // 如果无法继承且没有任务ID,创建新任务
  5794. if (!$url_inherited && empty($scene_task_id)) {
  5795. try {
  5796. $art_style = getProp($episode, 'art_style');
  5797. // 优先使用 pic_prompt,如果没有则使用 description
  5798. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5799. // if ($art_style) {
  5800. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5801. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5802. // }
  5803. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5804. $params = [
  5805. 'prompt' => $description,
  5806. 'ref_img_urls' => [],
  5807. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  5808. 'anime_id' => $anime_id,
  5809. 'episode_id' => $episode_id,
  5810. 'episode_number' => getProp($episode, 'episode_number'),
  5811. ];
  5812. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5813. $task_id = $task->id;
  5814. if ($task_id) {
  5815. $scene['task_id'] = $task_id;
  5816. $scene['task_status'] = 'processing';
  5817. $scenes_updated = true;
  5818. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5819. }
  5820. } catch (\Exception $e) {
  5821. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5822. }
  5823. }
  5824. }
  5825. // 如果有更新,保存到数据库
  5826. if ($roles_updated || $scenes_updated) {
  5827. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5828. if ($roles_updated) {
  5829. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5830. }
  5831. if ($scenes_updated) {
  5832. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5833. }
  5834. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5835. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5836. }
  5837. }
  5838. /**
  5839. * 根据图片URL使用AI反推图片提示词
  5840. *
  5841. * @param string $img_url 图片URL
  5842. * @return string 反推的提示词
  5843. */
  5844. private function generateImagePromptFromUrl($img_url) {
  5845. try {
  5846. // 获取默认模型
  5847. $model = 'doubao-seed-2-0-mini-260215';
  5848. // 构建messages参数
  5849. $messages = [
  5850. [
  5851. 'role' => 'user',
  5852. 'content' => [
  5853. [
  5854. 'type' => 'text',
  5855. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5856. ],
  5857. [
  5858. 'type' => 'image_url',
  5859. 'image_url' => [
  5860. 'url' => $img_url
  5861. ]
  5862. ]
  5863. ]
  5864. ]
  5865. ];
  5866. // 构建请求参数
  5867. $params = [
  5868. 'model' => $model,
  5869. 'messages' => $messages,
  5870. 'stream' => false,
  5871. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5872. ];
  5873. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5874. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5875. // 仅记录 token 使用明细(不扣积分)
  5876. $uid = 0;
  5877. try {
  5878. $uid = (int)Site::getUid();
  5879. } catch (\Throwable $e) {
  5880. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5881. }
  5882. $this->pointsService->recordTokenOnlyDetail(
  5883. $uid,
  5884. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5885. [
  5886. 'model' => $model,
  5887. 'img_url' => $img_url,
  5888. 'source' => 'generateImagePromptFromUrl',
  5889. ],
  5890. 'chat',
  5891. $model,
  5892. ''
  5893. );
  5894. // 返回生成的内容
  5895. return getProp($result, 'fullContent', '图片描述生成失败');
  5896. } catch (\Exception $e) {
  5897. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5898. 'img_url' => $img_url
  5899. ]);
  5900. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5901. 'error' => $e->getMessage(),
  5902. 'img_url' => $img_url
  5903. ]);
  5904. return '图片描述生成失败: ' . $e->getMessage();
  5905. }
  5906. }
  5907. /**
  5908. * 音频试听接口
  5909. * 创建音频任务并轮询获取结果
  5910. *
  5911. * @param array $data 参数数组
  5912. * @return array 返回音频URL或错误信息
  5913. */
  5914. public function previewAudio($data) {
  5915. $dialogue = getProp($data, 'dialogue');
  5916. // 必填参数验证
  5917. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5918. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5919. $voice_type = getProp($data, 'voice_type');
  5920. $voice_name = getProp($data, 'voice_name');
  5921. $voice_actor = getProp($data, 'voice_actor');
  5922. $emotion_type = getProp($data, 'emotion_type');
  5923. $gender = getProp($data, 'gender', 0);
  5924. $emotion = getProp($data, 'emotion');
  5925. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5926. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5927. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5928. $pitch = getProp($data, 'pitch', 0);
  5929. try {
  5930. $now = date('Y-m-d H:i:s');
  5931. // 构建生成参数
  5932. $generate_json = json_encode([
  5933. 'text' => $dialogue,
  5934. 'role' => $voice_actor,
  5935. 'voice_type' => $voice_type,
  5936. 'voice_name' => $voice_name,
  5937. 'emotion' => $emotion,
  5938. 'emotion_type' => $emotion_type,
  5939. 'gender' => $gender,
  5940. 'speed_ratio' => $speed_ratio,
  5941. 'loudness_ratio' => $loudness_ratio,
  5942. 'emotion_scale' => $emotion_scale,
  5943. 'pitch' => $pitch,
  5944. ], 256);
  5945. // 请求远程服务器执行生成
  5946. $client = new Client(['timeout' => 600, 'verify' => false]);
  5947. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5948. $response = $result->getBody()->getContents();
  5949. $response_arr = json_decode($response, true);
  5950. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5951. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5952. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5953. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5954. }
  5955. $arr = $response_arr['data'];
  5956. $subtitle_info = $arr['subtitle_info'];
  5957. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5958. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5959. return [
  5960. 'audio_url' => $arr['url'],
  5961. 'subtitle_info' => $subtitle_info,
  5962. 'audio_duration' => round($audio_duration, 2)
  5963. ];
  5964. } catch (\Exception $e) {
  5965. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5966. Utils::throwError('20003:' . $e->getMessage());
  5967. }
  5968. }
  5969. /**
  5970. * 获取角色库列表(支持文件夹递归查询)
  5971. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5972. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5973. */
  5974. public function globalProducts($data) {
  5975. $uid = Site::getUid();
  5976. $cpid = Site::getCpid();
  5977. $role = Site::getRole();
  5978. $id = getProp($data, 'id', 0);
  5979. $parent_id = getProp($data, 'parent_id', 0);
  5980. $product_name = getProp($data, 'product_name');
  5981. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5982. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5983. if (!$product) {
  5984. Utils::throwError('20003:请选择产品类型');
  5985. }
  5986. // 根据角色和is_public参数确定查询范围
  5987. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5988. // user角色:根据is_public参数筛选
  5989. $query_user_ids = [];
  5990. if ($role === 'admin') {
  5991. // admin获取所有个人库和公共库
  5992. $query_user_ids = [$uid, 0];
  5993. } else {
  5994. // user角色根据is_public参数筛选
  5995. if ($is_public == 2) {
  5996. // 个人库+公共库
  5997. $query_user_ids = [$uid, 0];
  5998. } elseif ($is_public == 0) {
  5999. // 仅个人库
  6000. $query_user_ids = [$uid];
  6001. } elseif ($is_public == 1) {
  6002. // 仅公共库
  6003. $query_user_ids = [0];
  6004. }
  6005. }
  6006. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  6007. if ($id || $product_name) {
  6008. $query = DB::table('mp_products')
  6009. ->where('cpid', $cpid)
  6010. ->whereIn('user_id', $query_user_ids)
  6011. ->where('is_deleted', 0);
  6012. // 如果指定了 id,按 id 精确查询
  6013. if ($id) {
  6014. $query->where('id', $id);
  6015. }
  6016. // 如果指定了 product_name,按名称模糊查询
  6017. if ($product_name) {
  6018. $query->where('product_name', 'like', "%{$product_name}%");
  6019. }
  6020. // 如果指定了 product,添加筛选条件
  6021. if ($product) {
  6022. $query->where('product', $product);
  6023. }
  6024. $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')
  6025. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  6026. ->get()
  6027. ->map(function($value) {
  6028. $value = (array)$value;
  6029. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  6030. $value['type'] = (int)$value['type'];
  6031. $value['parent_id'] = (int)$value['parent_id'];
  6032. $value['level'] = (int)$value['level'];
  6033. $value['product'] = (int)($value['product'] ?? 1);
  6034. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  6035. $value['timbre_url'] = $value['timbre_url'] ?? '';
  6036. $value['versions'] = json_decode($value['versions'], true) ?: [];
  6037. unset($value['user_id']);
  6038. return $value;
  6039. })
  6040. ->toArray();
  6041. return $result;
  6042. }
  6043. // 递归获取所有子目录和角色
  6044. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  6045. }
  6046. /**
  6047. * 递归获取指定目录下的所有子目录和角色
  6048. * @param int $cpid 公司ID
  6049. * @param int $parent_id 父目录ID
  6050. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  6051. * @param array $query_user_ids 用户ID数组(支持多个)
  6052. * @param int $current_uid 当前用户ID(用于排序)
  6053. * @return array
  6054. */
  6055. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  6056. // 查询当前层级的所有项(文件夹和角色)
  6057. $query = DB::table('mp_products')
  6058. ->where('cpid', $cpid)
  6059. ->where('is_deleted', 0)
  6060. ->where('parent_id', $parent_id);
  6061. // 添加用户ID验证(支持多个user_id)
  6062. if (!empty($query_user_ids)) {
  6063. $query->whereIn('user_id', $query_user_ids);
  6064. }
  6065. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  6066. if ($product) {
  6067. $query->where('product', $product);
  6068. }
  6069. // 排序规则:
  6070. // 1. 文件夹在前(type DESC)
  6071. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  6072. // 3. 其他排序规则
  6073. $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')
  6074. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  6075. ->get();
  6076. $result = [];
  6077. foreach ($items as $item) {
  6078. $itemArray = [
  6079. 'id' => $item->id,
  6080. 'type' => (int)$item->type,
  6081. 'parent_id' => (int)$item->parent_id,
  6082. 'level' => (int)$item->level,
  6083. 'product_name' => $item->product_name,
  6084. 'url' => $item->url,
  6085. 'pic_prompt' => $item->pic_prompt ?? '',
  6086. 'three_view_image_url' => $item->three_view_image_url,
  6087. 'timbre_url' => $item->timbre_url ?? '',
  6088. 'product' => (int)($item->product ?? 1),
  6089. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  6090. 'created_at' => transDate($item->created_at, 'Y-m-d')
  6091. ];
  6092. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  6093. // 如果是文件夹,递归获取其子项
  6094. if ($item->type == 2) {
  6095. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  6096. if (!empty($children)) {
  6097. $itemArray['children'] = $children;
  6098. }
  6099. }
  6100. $result[] = $itemArray;
  6101. }
  6102. return $result;
  6103. }
  6104. /**
  6105. * 创建文件夹
  6106. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  6107. * @return int 返回新建文件夹ID
  6108. */
  6109. public function createFolder($data) {
  6110. $uid = Site::getUid();
  6111. $cpid = Site::getCpid();
  6112. $role = Site::getRole();
  6113. $parent_id = getProp($data, 'parent_id', 0);
  6114. $folder_name = getProp($data, 'product_name', '新建文件夹');
  6115. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6116. // 如果是公共库操作,需要admin权限
  6117. if ($is_public && $role !== 'admin') {
  6118. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6119. }
  6120. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6121. $store_uid = $is_public ? 0 : $uid;
  6122. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6123. $product = getProp($data, 'product');
  6124. if (!in_array($product, [1, 2, 3])) {
  6125. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  6126. }
  6127. // 验证父文件夹
  6128. $parent_level = 0;
  6129. if ($parent_id > 0) {
  6130. $parent = DB::table('mp_products')
  6131. ->where('id', $parent_id)
  6132. ->where('cpid', $cpid)
  6133. ->where('user_id', $store_uid)
  6134. ->where('type', 2)
  6135. ->where('is_deleted', 0)
  6136. ->first();
  6137. if (!$parent) {
  6138. Utils::throwError('20003:父文件夹不存在');
  6139. }
  6140. // 检查父文件夹的 product 类型是否一致
  6141. if ($parent->product != $product) {
  6142. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  6143. }
  6144. $parent_level = $parent->level;
  6145. // 检查层级限制(最多3层)
  6146. if ($parent_level >= 3) {
  6147. Utils::throwError('20003:文件夹层级不能超过3层');
  6148. }
  6149. }
  6150. // 检查当前目录下是否已存在空白文件夹
  6151. $empty_folder_exists = DB::table('mp_products')
  6152. ->where('parent_id', $parent_id)
  6153. ->where('cpid', $cpid)
  6154. ->where('user_id', $store_uid)
  6155. ->where('type', 2)
  6156. ->where('product', $product)
  6157. ->where('product_name', '新建文件夹')
  6158. ->where('is_deleted', 0)
  6159. ->exists();
  6160. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  6161. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  6162. }
  6163. // 创建文件夹
  6164. $folder_id = DB::table('mp_products')->insertGetId([
  6165. 'user_id' => $store_uid,
  6166. 'cpid' => $cpid,
  6167. 'type' => 2,
  6168. 'parent_id' => $parent_id,
  6169. 'level' => $parent_level + 1,
  6170. 'product_name' => $folder_name,
  6171. 'product' => $product,
  6172. 'sort_order' => time(), // 使用时间戳作为排序权重
  6173. 'is_deleted' => 0,
  6174. 'created_at' => date('Y-m-d H:i:s'),
  6175. 'updated_at' => date('Y-m-d H:i:s')
  6176. ]);
  6177. return [
  6178. 'id' => $folder_id,
  6179. 'type' => 2,
  6180. 'parent_id' => $parent_id,
  6181. 'level' => $parent_level + 1,
  6182. 'product_name' => $folder_name,
  6183. 'product' => $product,
  6184. ];
  6185. }
  6186. /**
  6187. * 重命名文件夹或角色
  6188. * @param array $data 包含 id、product_name(新名称)
  6189. * @return bool
  6190. */
  6191. public function renameFolder($data) {
  6192. $uid = Site::getUid();
  6193. $cpid = Site::getCpid();
  6194. $role = Site::getRole();
  6195. $id = getProp($data, 'id');
  6196. $new_name = getProp($data, 'product_name');
  6197. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6198. if (!$id || !$new_name) {
  6199. Utils::throwError('20003:参数不完整');
  6200. }
  6201. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6202. $query_uid = $is_public ? 0 : $uid;
  6203. // 如果是公共库操作,需要admin权限
  6204. if ($is_public && $role !== 'admin') {
  6205. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6206. }
  6207. // 检查是否存在
  6208. $item = DB::table('mp_products')
  6209. ->where('id', $id)
  6210. ->where('cpid', $cpid)
  6211. ->where('user_id', $query_uid)
  6212. ->where('is_deleted', 0)
  6213. ->first();
  6214. if (!$item) {
  6215. Utils::throwError('20003:项目不存在');
  6216. }
  6217. return DB::table('mp_products')
  6218. ->where('id', $id)
  6219. ->where('cpid', $cpid)
  6220. ->where('user_id', $query_uid)
  6221. ->update([
  6222. 'product_name' => $new_name,
  6223. 'updated_at' => date('Y-m-d H:i:s')
  6224. ]);
  6225. }
  6226. /**
  6227. * 移动角色或文件夹到指定文件夹
  6228. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6229. * @return bool
  6230. */
  6231. public function moveProductOrFolder($data) {
  6232. $uid = Site::getUid();
  6233. $cpid = Site::getCpid();
  6234. $role = Site::getRole();
  6235. $id = getProp($data, 'id');
  6236. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6237. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6238. if (!$id) {
  6239. Utils::throwError('20003:请选择要移动的项目');
  6240. }
  6241. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6242. $query_uid = $is_public ? 0 : $uid;
  6243. // 如果是公共库操作,需要admin权限
  6244. if ($is_public && $role !== 'admin') {
  6245. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6246. }
  6247. // 检查要移动的项目
  6248. $item = DB::table('mp_products')
  6249. ->where('id', $id)
  6250. ->where('cpid', $cpid)
  6251. ->where('user_id', $query_uid)
  6252. ->where('is_deleted', 0)
  6253. ->first();
  6254. if (!$item) {
  6255. Utils::throwError('20003:项目不存在');
  6256. }
  6257. // 验证目标文件夹
  6258. $target_level = 0;
  6259. $target_product = $item->product; // 默认使用当前项目的 product
  6260. if ($target_parent_id > 0) {
  6261. $target_parent = DB::table('mp_products')
  6262. ->where('id', $target_parent_id)
  6263. ->where('cpid', $cpid)
  6264. ->where('user_id', $query_uid)
  6265. ->where('type', 2)
  6266. ->where('is_deleted', 0)
  6267. ->first();
  6268. if (!$target_parent) {
  6269. Utils::throwError('20003:目标文件夹不存在');
  6270. }
  6271. // 检查 product 类型是否一致
  6272. if ($target_parent->product != $item->product) {
  6273. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6274. }
  6275. $target_level = $target_parent->level;
  6276. $target_product = $target_parent->product;
  6277. // 如果移动的是文件夹,需要检查层级
  6278. if ($item->type == 2) {
  6279. // 计算移动后的最大层级
  6280. $max_child_level = $this->getMaxChildLevel($id);
  6281. $depth = $max_child_level - $item->level;
  6282. if ($target_level + 1 + $depth > 3) {
  6283. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6284. }
  6285. // 不能移动到自己或自己的子文件夹下
  6286. if ($this->isDescendant($target_parent_id, $id)) {
  6287. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6288. }
  6289. }
  6290. }
  6291. // 更新父文件夹和层级
  6292. $new_level = $target_level + 1;
  6293. DB::table('mp_products')
  6294. ->where('id', $id)
  6295. ->update([
  6296. 'parent_id' => $target_parent_id,
  6297. 'level' => $new_level,
  6298. 'updated_at' => date('Y-m-d H:i:s')
  6299. ]);
  6300. // 如果是文件夹,需要递归更新所有子项的层级
  6301. if ($item->type == 2) {
  6302. $this->updateChildrenLevel($id, $new_level);
  6303. }
  6304. return true;
  6305. }
  6306. /**
  6307. * 获取文件夹下最大子层级
  6308. * @param int $folder_id
  6309. * @return int
  6310. */
  6311. private function getMaxChildLevel($folder_id) {
  6312. $max_level = DB::table('mp_products')
  6313. ->where('parent_id', $folder_id)
  6314. ->where('is_deleted', 0)
  6315. ->max('level');
  6316. if (!$max_level) {
  6317. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6318. }
  6319. // 递归查找子文件夹
  6320. $children = DB::table('mp_products')
  6321. ->where('parent_id', $folder_id)
  6322. ->where('type', 2)
  6323. ->where('is_deleted', 0)
  6324. ->pluck('id');
  6325. foreach ($children as $child_id) {
  6326. $child_max = $this->getMaxChildLevel($child_id);
  6327. if ($child_max > $max_level) {
  6328. $max_level = $child_max;
  6329. }
  6330. }
  6331. return $max_level;
  6332. }
  6333. /**
  6334. * 检查 target_id 是否是 folder_id 的后代
  6335. * @param int $target_id
  6336. * @param int $folder_id
  6337. * @return bool
  6338. */
  6339. private function isDescendant($target_id, $folder_id) {
  6340. if ($target_id == $folder_id) {
  6341. return true;
  6342. }
  6343. $parent = DB::table('mp_products')
  6344. ->where('id', $target_id)
  6345. ->where('is_deleted', 0)
  6346. ->first();
  6347. if (!$parent || $parent->parent_id == 0) {
  6348. return false;
  6349. }
  6350. return $this->isDescendant($parent->parent_id, $folder_id);
  6351. }
  6352. /**
  6353. * 递归更新子项层级
  6354. * @param int $parent_id
  6355. * @param int $parent_level
  6356. */
  6357. private function updateChildrenLevel($parent_id, $parent_level) {
  6358. $children = DB::table('mp_products')
  6359. ->where('parent_id', $parent_id)
  6360. ->where('is_deleted', 0)
  6361. ->get();
  6362. foreach ($children as $child) {
  6363. $new_level = $parent_level + 1;
  6364. DB::table('mp_products')
  6365. ->where('id', $child->id)
  6366. ->update([
  6367. 'level' => $new_level,
  6368. 'updated_at' => date('Y-m-d H:i:s')
  6369. ]);
  6370. // 如果是文件夹,继续递归
  6371. if ($child->type == 2) {
  6372. $this->updateChildrenLevel($child->id, $new_level);
  6373. }
  6374. }
  6375. }
  6376. /**
  6377. * 获取文件夹路径(面包屑导航)
  6378. * @param array $data 包含 folder_id
  6379. * @return array 返回路径数组
  6380. */
  6381. public function getFolderPath($data) {
  6382. $uid = Site::getUid();
  6383. $cpid = Site::getCpid();
  6384. $folder_id = getProp($data, 'id', 0);
  6385. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6386. if ($folder_id == 0) {
  6387. return [
  6388. ['id' => 0, 'name' => '根目录']
  6389. ];
  6390. }
  6391. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6392. $query_uid = $is_public ? 0 : $uid;
  6393. $path = [];
  6394. $current_id = $folder_id;
  6395. while ($current_id > 0) {
  6396. $folder = DB::table('mp_products')
  6397. ->where('id', $current_id)
  6398. ->where('cpid', $cpid)
  6399. ->where('user_id', $query_uid)
  6400. ->where('type', 2)
  6401. ->where('is_deleted', 0)
  6402. ->first();
  6403. if (!$folder) {
  6404. break;
  6405. }
  6406. array_unshift($path, [
  6407. 'id' => $folder->id,
  6408. 'name' => $folder->product_name
  6409. ]);
  6410. $current_id = $folder->parent_id;
  6411. }
  6412. // 添加根目录
  6413. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6414. return $path;
  6415. }
  6416. public function createProduct($data) {
  6417. $uid = Site::getUid();
  6418. $cpid = Site::getCpid();
  6419. $role = Site::getRole();
  6420. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6421. // 如果是公共库操作,需要admin权限
  6422. if ($is_public && $role !== 'admin') {
  6423. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6424. }
  6425. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6426. $store_uid = $is_public ? 0 : $uid;
  6427. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6428. $script_id = (int)getProp($data, 'script_id', 0);
  6429. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6430. if ($script_id && empty($episode_numbers)) {
  6431. Utils::throwError('20003:剧集序号不能为空');
  6432. }
  6433. if (!$script_id && !empty($episode_numbers)) {
  6434. Utils::throwError('20003:请提供剧本ID');
  6435. }
  6436. $product_name = trim(getProp($data, 'product_name'));
  6437. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6438. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6439. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6440. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6441. $url = trim(getProp($data, 'url'));
  6442. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6443. $versions = getProp($data, 'versions');
  6444. // 检查是否是正确的图片格式
  6445. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6446. $urlPath = parse_url($url, PHP_URL_PATH);
  6447. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6448. if (!in_array($extension, $allowedExtensions)) {
  6449. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6450. }
  6451. // 选填三视图图片地址,格式校验与 url 一致
  6452. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6453. if ($three_view_image_url) {
  6454. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6455. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6456. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6457. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6458. }
  6459. }
  6460. // 选填音色音频地址(兼容 timbre_url/audio_url/timbre 传参)
  6461. $timbre_url = $this->getProductTimbreUrl($data);
  6462. if ($timbre_url) {
  6463. $this->validateProductAudioUrl($timbre_url);
  6464. }
  6465. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6466. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6467. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6468. $product = getProp($data, 'product');
  6469. if (!in_array($product, [1, 2, 3])) {
  6470. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6471. }
  6472. // 获取父文件夹ID和层级
  6473. $parent_id = getProp($data, 'parent_id', 0);
  6474. $parent_level = 0;
  6475. if ($parent_id > 0) {
  6476. $parent = DB::table('mp_products')
  6477. ->where('id', $parent_id)
  6478. ->where('cpid', $cpid)
  6479. ->where('user_id', $store_uid)
  6480. ->where('type', 2)
  6481. ->where('is_deleted', 0)
  6482. ->first();
  6483. if (!$parent) {
  6484. Utils::throwError('20003:父文件夹不存在');
  6485. }
  6486. $parent_level = $parent->level;
  6487. }
  6488. // 创建资产并保存剧本资产关联关系(同一事务)
  6489. DB::beginTransaction();
  6490. try {
  6491. $id = DB::table('mp_products')->insertGetId([
  6492. 'user_id' => $store_uid,
  6493. 'cpid' => $cpid,
  6494. 'type' => 1, // 1=角色图片
  6495. 'parent_id' => $parent_id,
  6496. 'level' => $parent_level + 1,
  6497. 'product_name' => $product_name,
  6498. 'url' => $url,
  6499. 'three_view_image_url' => $three_view_image_url,
  6500. 'timbre_url' => $timbre_url,
  6501. 'pic_prompt' => $pic_prompt,
  6502. 'product' => $product,
  6503. 'versions' => json_encode($versions, 256),
  6504. 'sort_order' => time(), // 使用时间戳作为排序权重
  6505. 'created_at' => date('Y-m-d H:i:s'),
  6506. 'updated_at' => date('Y-m-d H:i:s')
  6507. ]);
  6508. if (!$id) Utils::throwError('20003:创建失败');
  6509. // 保存剧本资产关联关系
  6510. if ($script_id) {
  6511. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6512. }
  6513. DB::commit();
  6514. } catch (\Exception $e) {
  6515. DB::rollback();
  6516. throw $e;
  6517. }
  6518. return [
  6519. 'id' => $id,
  6520. 'type' => 1,
  6521. 'parent_id' => $parent_id,
  6522. 'level' => $parent_level + 1,
  6523. 'product_name' => $product_name,
  6524. 'url' => $url,
  6525. 'three_view_image_url' => $three_view_image_url,
  6526. 'timbre_url' => $timbre_url,
  6527. 'pic_prompt' => $pic_prompt,
  6528. 'product' => $product,
  6529. 'versions' => $versions
  6530. ];
  6531. }
  6532. public function editProduct($data) {
  6533. $uid = Site::getUid();
  6534. $cpid = Site::getCpid();
  6535. $role = Site::getRole();
  6536. $id = getProp($data, 'id');
  6537. if (!$id) Utils::throwError('20003:ID不能为空');
  6538. $versions = getProp($data, 'versions');
  6539. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6540. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6541. $script_id = (int)getProp($data, 'script_id', 0);
  6542. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6543. if ($script_id && empty($episode_numbers)) {
  6544. Utils::throwError('20003:剧集序号不能为空');
  6545. }
  6546. if (!$script_id && !empty($episode_numbers)) {
  6547. Utils::throwError('20003:请提供剧本ID');
  6548. }
  6549. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6550. $query_uid = $is_public ? 0 : $uid;
  6551. // 如果是公共库操作,需要admin权限
  6552. if ($is_public && $role !== 'admin') {
  6553. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6554. }
  6555. // 检查是否存在且属于当前用户或公共库
  6556. $role = DB::table('mp_products')
  6557. ->where('id', $id)
  6558. ->where('cpid', $cpid)
  6559. ->where('user_id', $query_uid)
  6560. ->where('type', 1)->first();
  6561. if (!$role) Utils::throwError('20003:记录不存在');
  6562. $updateData = [];
  6563. // $needVersionRecord = false; // 是否需要记录版本
  6564. // 名称
  6565. $product_name = trim(getProp($data, 'product_name'));
  6566. if ($product_name) {
  6567. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6568. $updateData['product_name'] = $product_name;
  6569. }
  6570. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6571. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6572. // 图片地址
  6573. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6574. $url = trim(getProp($data, 'url'));
  6575. if ($url) {
  6576. // 检查是否是正确的图片格式
  6577. $urlPath = parse_url($url, PHP_URL_PATH);
  6578. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6579. if (!in_array($extension, $allowedExtensions)) {
  6580. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6581. }
  6582. // // 如果 url 有变更,记录版本
  6583. // if ($url !== $role->url) {
  6584. // $needVersionRecord = true;
  6585. // }
  6586. $updateData['url'] = $url;
  6587. }
  6588. // 三视图图片地址(选填),格式校验与 url 一致;显式传空表示当前版本没有三视图
  6589. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6590. if ($three_view_image_url) {
  6591. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6592. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6593. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6594. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6595. }
  6596. }
  6597. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  6598. if (array_key_exists('three_view_image_url', $data)) {
  6599. $updateData['three_view_image_url'] = $three_view_image_url;
  6600. }
  6601. // 音色音频地址(选填,显式传空字符串可清除已有音色)
  6602. if (array_key_exists('timbre_url', $data) || array_key_exists('audio_url', $data) || array_key_exists('timbre', $data)) {
  6603. $timbre_url = $this->getProductTimbreUrl($data);
  6604. if ($timbre_url) {
  6605. $this->validateProductAudioUrl($timbre_url);
  6606. }
  6607. $updateData['timbre_url'] = $timbre_url;
  6608. }
  6609. // 提示词
  6610. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6611. if ($pic_prompt) {
  6612. // // 如果 pic_prompt 有变更,记录版本
  6613. // if ($pic_prompt !== $role->pic_prompt) {
  6614. // $needVersionRecord = true;
  6615. // }
  6616. $updateData['pic_prompt'] = $pic_prompt;
  6617. }else {
  6618. Utils::throwError('20003:请输入提示词');
  6619. }
  6620. if (empty($updateData) && !$script_id) {
  6621. Utils::throwError('20003:没有需要更新的数据');
  6622. }
  6623. // // 如果需要记录版本,将数据添加到 versions 数组
  6624. // if ($needVersionRecord) {
  6625. // // 获取现有的 versions 数据
  6626. // $versions = json_decode($role->versions, true) ?: [];
  6627. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6628. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6629. // if ($isFirstVersion) {
  6630. // $oldVersion = [
  6631. // 'url' => $role->url,
  6632. // 'description' => $role->pic_prompt,
  6633. // ];
  6634. // // 旧版本添加到数组末尾
  6635. // $versions[] = $oldVersion;
  6636. // }
  6637. // // 构建新版本(变更后)
  6638. // $newVersion = [
  6639. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6640. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6641. // ];
  6642. // // 检查新版本是否已存在于历史版本中
  6643. // $existingIndex = -1;
  6644. // foreach ($versions as $index => $version) {
  6645. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6646. // $existingIndex = $index;
  6647. // break;
  6648. // }
  6649. // }
  6650. // if ($existingIndex !== -1) {
  6651. // // 如果已存在,移除旧的位置
  6652. // array_splice($versions, $existingIndex, 1);
  6653. // }
  6654. // // 新版本添加到数组开头(最新的在前)
  6655. // array_unshift($versions, $newVersion);
  6656. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6657. // // if (count($versions) > 10) {
  6658. // // $versions = array_slice($versions, 0, 10);
  6659. // // }
  6660. // $updateData['versions'] = json_encode($versions, 256);
  6661. // }
  6662. if ($versions) {
  6663. $updateData['versions'] = json_encode($versions, 256);
  6664. }
  6665. if (!empty($updateData)) {
  6666. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6667. }
  6668. // 更新资产并保存剧本资产关联关系(同一事务)
  6669. DB::beginTransaction();
  6670. try {
  6671. $updated = true;
  6672. if (!empty($updateData)) {
  6673. $updated = DB::table('mp_products')
  6674. ->where('cpid', $cpid)
  6675. ->where('id', $id)
  6676. ->update($updateData);
  6677. }
  6678. // 保存剧本资产关联关系
  6679. if ($script_id) {
  6680. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6681. }
  6682. DB::commit();
  6683. } catch (\Exception $e) {
  6684. DB::rollback();
  6685. throw $e;
  6686. }
  6687. return $updated;
  6688. }
  6689. /**
  6690. * 获取资产音色音频地址
  6691. * 兼容 timbre_url/audio_url/timbre 三种传参,timbre 支持字符串或 {"url":"..."} 结构
  6692. *
  6693. * @param array $data
  6694. * @return string
  6695. */
  6696. private function getProductTimbreUrl($data) {
  6697. foreach (['timbre_url', 'audio_url', 'timbre'] as $key) {
  6698. if (!array_key_exists($key, $data)) {
  6699. continue;
  6700. }
  6701. $value = $data[$key];
  6702. if (is_array($value)) {
  6703. $value = getProp($value, 'url', $value[0] ?? '');
  6704. }
  6705. if (!is_string($value)) {
  6706. continue;
  6707. }
  6708. return trim($value);
  6709. }
  6710. return '';
  6711. }
  6712. /**
  6713. * 校验资产音色音频地址格式
  6714. *
  6715. * @param string $url 音频地址
  6716. * @return void
  6717. */
  6718. private function validateProductAudioUrl($url) {
  6719. $allowedExtensions = ['mp3', 'wav', 'm4a', 'aac', 'ogg', 'oga', 'flac', 'amr', 'wma', 'weba'];
  6720. $urlPath = parse_url($url, PHP_URL_PATH);
  6721. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6722. if (!in_array($extension, $allowedExtensions)) {
  6723. Utils::throwError('20003:音色音频格式不正确,仅支持 mp3、wav、m4a、aac、ogg、flac、amr、wma 格式');
  6724. }
  6725. }
  6726. /**
  6727. * 保存单一资产与剧本剧集的关联关系
  6728. *
  6729. * @param int $product_id 资产ID
  6730. * @param int $script_id 剧本ID
  6731. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6732. * @return int 新增关联数量
  6733. */
  6734. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6735. $uid = Site::getUid();
  6736. // 验证剧本是否存在
  6737. $script = DB::table('mp_scripts')
  6738. ->where('id', $script_id)
  6739. ->where('is_deleted', 0)
  6740. ->first();
  6741. if (!$script) {
  6742. Utils::throwError('20003:剧本不存在');
  6743. }
  6744. // 验证剧本归属:只能关联自己的剧本
  6745. if ((int)$script->user_id !== (int)$uid) {
  6746. Utils::throwError('20003:只能添加到自己的剧本');
  6747. }
  6748. // 使用 splitContent 拆分剧本内容获取总集数
  6749. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6750. // 解析剧集序号(数组)
  6751. $episodes = [];
  6752. foreach ($episode_numbers as $item) {
  6753. if (is_array($item)) {
  6754. continue;
  6755. }
  6756. $item = trim((string)$item);
  6757. if ($item === '' || !is_numeric($item)) {
  6758. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6759. }
  6760. $episodes[] = (int)$item;
  6761. }
  6762. // 去重并校验序号范围(序号从1开始)
  6763. $episodes = array_values(array_unique($episodes));
  6764. if (empty($episodes)) {
  6765. Utils::throwError('20003:剧集序号不能为空');
  6766. }
  6767. foreach ($episodes as $episode) {
  6768. if ($episode < 1 || $episode > $totalEpisodes) {
  6769. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6770. }
  6771. }
  6772. $now = now();
  6773. // 过滤已存在的关联,避免重复
  6774. $existingEpisodes = DB::table('mp_script_product_mappings')
  6775. ->where('script_id', $script_id)
  6776. ->where('product_id', $product_id)
  6777. ->whereIn('episode_number', $episodes)
  6778. ->pluck('episode_number')
  6779. ->all();
  6780. $mappingRecords = [];
  6781. foreach ($episodes as $episode) {
  6782. if (in_array($episode, $existingEpisodes)) {
  6783. continue;
  6784. }
  6785. $mappingRecords[] = [
  6786. 'script_id' => $script_id,
  6787. 'product_id' => $product_id,
  6788. 'episode_number' => $episode,
  6789. 'created_at' => $now,
  6790. 'updated_at' => $now,
  6791. ];
  6792. }
  6793. $insertedCount = 0;
  6794. if (!empty($mappingRecords)) {
  6795. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6796. }
  6797. return $insertedCount;
  6798. }
  6799. /**
  6800. * 规范化剧集序号参数,统一为数组
  6801. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6802. *
  6803. * @param mixed $episode_number 剧集序号参数
  6804. * @return array
  6805. */
  6806. private function normalizeEpisodeNumbers($episode_number) {
  6807. if (!is_array($episode_number)) {
  6808. $episode_number = explode(',', (string)$episode_number);
  6809. }
  6810. $items = [];
  6811. foreach ($episode_number as $item) {
  6812. if (is_array($item)) {
  6813. continue;
  6814. }
  6815. foreach (explode(',', (string)$item) as $part) {
  6816. $part = trim($part);
  6817. if ($part !== '') {
  6818. $items[] = $part;
  6819. }
  6820. }
  6821. }
  6822. return $items;
  6823. }
  6824. /**
  6825. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6826. *
  6827. * @param object $script 剧本记录
  6828. * @return int 总集数
  6829. */
  6830. private function getScriptTotalEpisodeCount($script) {
  6831. if (empty($script->content)) {
  6832. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6833. }
  6834. $totalEpisodes = count(splitContent($script->content));
  6835. if ($totalEpisodes < 1) {
  6836. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6837. }
  6838. return $totalEpisodes;
  6839. }
  6840. /**
  6841. * 获取剧本总集数
  6842. *
  6843. * @param array $data 包含 script_id(剧本ID)
  6844. * @return array
  6845. */
  6846. public function getScriptTotalEpisodes($data) {
  6847. $script_id = (int)getProp($data, 'script_id', 0);
  6848. if (!$script_id) {
  6849. Utils::throwError('20003:请提供剧本ID');
  6850. }
  6851. // 验证剧本是否存在
  6852. $script = DB::table('mp_scripts')
  6853. ->where('id', $script_id)
  6854. ->where('is_deleted', 0)
  6855. ->first();
  6856. if (!$script) {
  6857. Utils::throwError('20003:剧本不存在');
  6858. }
  6859. return [
  6860. 'script_id' => $script_id,
  6861. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6862. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6863. ];
  6864. }
  6865. /**
  6866. * 获取角色版本历史
  6867. * @param array $data 包含 id(角色ID)
  6868. * @return array 返回版本历史列表
  6869. */
  6870. public function getProductVersions($data) {
  6871. $cpid = Site::getCpid();
  6872. $id = getProp($data, 'id');
  6873. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6874. $role = DB::table('mp_products')
  6875. ->where('id', $id)
  6876. ->where('cpid', $cpid)
  6877. ->where('type', 1)
  6878. ->first();
  6879. if (!$role) Utils::throwError('20003:角色不存在');
  6880. // 获取版本历史
  6881. $versions = json_decode($role->versions, true) ?: [];
  6882. // 添加当前版本作为最新版本
  6883. $currentVersion = [
  6884. 'version' => 0, // 0 表示当前版本
  6885. 'url' => $role->url,
  6886. 'pic_prompt' => $role->pic_prompt,
  6887. 'updated_at' => $role->updated_at,
  6888. 'is_current' => true
  6889. ];
  6890. array_unshift($versions, $currentVersion);
  6891. return $versions;
  6892. }
  6893. /**
  6894. * 恢复到指定版本
  6895. * @param array $data 包含 id(角色ID)、version(版本号)
  6896. * @return bool
  6897. */
  6898. public function restoreProductVersion($data) {
  6899. $uid = Site::getUid();
  6900. $cpid = Site::getCpid();
  6901. $id = getProp($data, 'id');
  6902. $version = getProp($data, 'version');
  6903. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6904. if (!$version) Utils::throwError('20003:版本号不能为空');
  6905. $role = DB::table('mp_products')
  6906. ->where('id', $id)
  6907. ->where('cpid', $cpid)
  6908. ->where('type', 1)
  6909. ->first();
  6910. if (!$role) Utils::throwError('20003:角色不存在');
  6911. // 获取版本历史
  6912. $versions = json_decode($role->versions, true) ?: [];
  6913. // 查找指定版本
  6914. $targetVersion = null;
  6915. foreach ($versions as $v) {
  6916. if ($v['version'] == $version) {
  6917. $targetVersion = $v;
  6918. break;
  6919. }
  6920. }
  6921. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6922. // 先将当前版本保存到历史
  6923. $newVersion = [
  6924. 'version' => count($versions) + 1,
  6925. 'url' => $role->url,
  6926. 'pic_prompt' => $role->pic_prompt,
  6927. 'updated_at' => date('Y-m-d H:i:s'),
  6928. 'updated_by' => $uid
  6929. ];
  6930. array_unshift($versions, $newVersion);
  6931. // 限制版本数量
  6932. if (count($versions) > 10) {
  6933. $versions = array_slice($versions, 0, 10);
  6934. }
  6935. // 恢复到指定版本
  6936. return DB::table('mp_products')
  6937. ->where('id', $id)
  6938. ->where('cpid', $cpid)
  6939. ->update([
  6940. 'url' => $targetVersion['url'],
  6941. 'pic_prompt' => $targetVersion['pic_prompt'],
  6942. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6943. 'updated_at' => date('Y-m-d H:i:s')
  6944. ]);
  6945. }
  6946. public function deleteProduct($data) {
  6947. $uid = Site::getUid();
  6948. $cpid = Site::getCpid();
  6949. $role = Site::getRole();
  6950. $id = getProp($data, 'id');
  6951. if (!$id) Utils::throwError('20003:ID不能为空');
  6952. $ids = explode(',', $id);
  6953. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6954. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6955. $query_uid = $is_public ? 0 : $uid;
  6956. // 如果是公共库操作,需要admin权限
  6957. if ($is_public && $role !== 'admin') {
  6958. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6959. }
  6960. // 检查是否存在且属于当前用户或公共库
  6961. $role = DB::table('mp_products')
  6962. ->whereIn('id', $ids)
  6963. ->where('cpid', $cpid)
  6964. ->where('user_id', $query_uid)
  6965. ->get();
  6966. if (!$role) Utils::throwError('20003:记录不存在');
  6967. return DB::table('mp_products')
  6968. ->where('cpid', $cpid)
  6969. ->where('user_id', $query_uid)
  6970. ->whereIn('id', $ids)
  6971. ->update([
  6972. 'is_deleted' => 1,
  6973. 'updated_at' => date('Y-m-d H:i:s')
  6974. ]);
  6975. }
  6976. public function generateThreeView($data) {
  6977. $uid = Site::getUid();
  6978. $cpid = Site::getCpid();
  6979. $role = Site::getRole();
  6980. $id = getProp($data, 'id');
  6981. if (!$id) Utils::throwError('20003:ID不能为空');
  6982. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6983. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6984. $query_uid = $is_public ? 0 : $uid;
  6985. // 如果是公共库操作,需要admin权限
  6986. if ($is_public && $role !== 'admin') {
  6987. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6988. }
  6989. // 检查是否存在且属于当前用户或公共库
  6990. $product = DB::table('mp_products')
  6991. ->where('id', $id)
  6992. ->where('cpid', $cpid)
  6993. ->where('user_id', $query_uid)
  6994. ->where('type', 1)->first();
  6995. if (!$product) Utils::throwError('20003:资产不存在');
  6996. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。'));
  6997. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6998. if (!$ref_img_url) {
  6999. // 如果没有传入参考图,使用角色表中的图片
  7000. $ref_img_url = $product->url ?? '';
  7001. if (!$ref_img_url) {
  7002. Utils::throwError('20003:参考图不能为空');
  7003. }
  7004. }
  7005. $pic_prompt = getProp($product, 'pic_prompt');
  7006. if ($pic_prompt) {
  7007. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  7008. }
  7009. // 检查参考图是否是正确的图片格式
  7010. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  7011. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  7012. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  7013. if (!in_array($extension, $allowedExtensions)) {
  7014. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  7015. }
  7016. // 处理图片模型
  7017. $model = getProp($data, 'model');
  7018. if (!$model) {
  7019. // 使用默认模型
  7020. $model = 'gpt-image-2';
  7021. }
  7022. // 验证模型是否在可用模型表中
  7023. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7024. Utils::throwError('20003:该模型已不可用,请更换!');
  7025. }
  7026. $ratio = getProp($data, 'ratio', '16:9');
  7027. $resolution = getProp($data, 'resolution', '2k');
  7028. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  7029. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7030. // 参数验证
  7031. $resolution = strtolower($resolution);
  7032. if (!isset($sizeMap[$resolution])) {
  7033. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7034. }
  7035. if (!isset($sizeMap[$resolution][$ratio])) {
  7036. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7037. }
  7038. // 根据 ratio 和 resolution 确定宽高
  7039. $width = $sizeMap[$resolution][$ratio]['width'];
  7040. $height = $sizeMap[$resolution][$ratio]['height'];
  7041. try {
  7042. // 创建图片生成任务
  7043. $params = [
  7044. 'prompt' => $prompt,
  7045. 'model' => $model,
  7046. 'ref_img_urls' => [$ref_img_url],
  7047. 'width' => $width,
  7048. 'height' => $height
  7049. ];
  7050. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7051. $task_id = $task->id;
  7052. if (!$task_id) {
  7053. Utils::throwError('20003:创建图片生成任务失败');
  7054. }
  7055. // 轮询获取结果
  7056. // 只查询数据库,不调用API,不更新任务表
  7057. $start_time = time();
  7058. $timeout = 1800;
  7059. $img_url = '';
  7060. while (time() - $start_time < $timeout) {
  7061. sleep(5);
  7062. // 只查询数据库中的任务状态,不调用API,不更新任务表
  7063. $task = DB::table('mp_generate_pic_tasks')
  7064. ->where('id', $task_id)
  7065. ->first();
  7066. if (!$task) {
  7067. Utils::throwError('20003:任务不存在');
  7068. }
  7069. if ($task->status === 'success' && $task->result_url) {
  7070. $result_urls = is_string($task->result_url)
  7071. ? json_decode($task->result_url, true)
  7072. : $task->result_url;
  7073. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7074. break;
  7075. } elseif ($task->status === 'failed') {
  7076. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  7077. }
  7078. // 其他状态继续轮询
  7079. }
  7080. if (empty($img_url)) {
  7081. Utils::throwError('20003:三视图生成超时,请稍后重试');
  7082. }
  7083. // 更新 mp_products 表(不是任务表)
  7084. DB::table('mp_products')
  7085. ->where('id', $id)
  7086. ->where('cpid', $cpid)
  7087. ->update([
  7088. 'three_view_image_url' => $img_url,
  7089. 'updated_at' => date('Y-m-d H:i:s')
  7090. ]);
  7091. return ['three_view_image_url' => $img_url];
  7092. } catch (\Exception $e) {
  7093. dLog('anime')->error('生成三视图失败', [
  7094. 'error' => $e->getMessage()
  7095. ]);
  7096. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  7097. Utils::throwError('20003:' . $e->getMessage());
  7098. }
  7099. }
  7100. /**
  7101. * 推送(复制)资产或文件夹到目标位置
  7102. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  7103. * @return array 返回推送结果
  7104. */
  7105. public function pushProductOrFolder($data) {
  7106. $uid = Site::getUid();
  7107. $cpid = Site::getCpid();
  7108. $role = Site::getRole();
  7109. $product_id = getProp($data, 'product_id');
  7110. $target_parent_id = getProp($data, 'target_parent_id', 0);
  7111. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  7112. if (!$product_id) {
  7113. Utils::throwError('20003:请选择要推送的项目');
  7114. }
  7115. // 查询源项目(只通过cpid查询,不限制user_id)
  7116. $sourceItem = DB::table('mp_products')
  7117. ->where('id', $product_id)
  7118. ->where('cpid', $cpid)
  7119. ->where('is_deleted', 0)
  7120. ->first();
  7121. if (!$sourceItem) {
  7122. Utils::throwError('20003:要推送的项目不存在');
  7123. }
  7124. // 通过user_id判断源是公共库还是个人库
  7125. $source_uid = $sourceItem->user_id;
  7126. $source_is_public = ($source_uid == 0) ? 1 : 0;
  7127. // 验证目标文件夹并确定目标是公共库还是个人库
  7128. $target_level = 0;
  7129. $target_uid = $uid; // 默认推送到个人库
  7130. $target_is_public = 0;
  7131. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  7132. if ($target_parent_id > 0) {
  7133. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  7134. $targetParent = DB::table('mp_products')
  7135. ->where('id', $target_parent_id)
  7136. ->where('cpid', $cpid)
  7137. ->where('type', 2)
  7138. ->where('is_deleted', 0)
  7139. ->first();
  7140. if (!$targetParent) {
  7141. Utils::throwError('20003:目标文件夹不存在');
  7142. }
  7143. // 通过user_id判断目标是公共库还是个人库
  7144. $target_level = $targetParent->level;
  7145. $target_uid = $targetParent->user_id;
  7146. $target_is_public = ($target_uid == 0) ? 1 : 0;
  7147. // 使用目标文件夹的 product 类型
  7148. $final_product_type = $targetParent->product;
  7149. }
  7150. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  7151. else {
  7152. $push_to_public = getProp($data, 'push_to_public');
  7153. if ($push_to_public === '') {
  7154. Utils::throwError('20003:请选择是否推送到公共库');
  7155. }
  7156. if ($push_to_public) {
  7157. $target_uid = 0;
  7158. $target_is_public = 1;
  7159. }
  7160. // 推送到根目录时,必须指定 product 类型
  7161. if ($target_product === null || $target_product === '') {
  7162. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  7163. }
  7164. $final_product_type = $target_product;
  7165. }
  7166. // 如果目标是公共库,需要admin权限
  7167. if ($target_is_public && $role !== 'admin') {
  7168. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  7169. }
  7170. // 权限验证:验证是否符合允许的推送规则
  7171. $this->validatePushPermission($source_uid, $target_uid, $uid);
  7172. try {
  7173. DB::beginTransaction();
  7174. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  7175. if ($sourceItem->type == 1) {
  7176. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  7177. DB::commit();
  7178. return [
  7179. 'product_id' => $newId,
  7180. ];
  7181. }
  7182. // 如果是文件夹,递归复制(支持跨类型推送)
  7183. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  7184. DB::commit();
  7185. return [
  7186. 'product_id' => $newFolderId,
  7187. ];
  7188. } catch (\Exception $e) {
  7189. DB::rollBack();
  7190. dLog('anime')->error('推送失败', [
  7191. 'error' => $e->getMessage(),
  7192. 'product_id' => $product_id
  7193. ]);
  7194. Utils::throwError('20003:' . $e->getMessage());
  7195. }
  7196. }
  7197. /**
  7198. * 验证推送权限
  7199. * 允许的推送规则:
  7200. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7201. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  7202. * 3. 公共库推送给公共库(公共库 → 公共库)
  7203. *
  7204. * @param int $source_uid 源的user_id
  7205. * @param int $target_uid 目标的user_id
  7206. * @param int $current_uid 当前用户ID
  7207. * @throws \Exception
  7208. */
  7209. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  7210. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7211. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  7212. return; // 允许
  7213. }
  7214. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  7215. if ($source_uid == 0 && $target_uid == $current_uid) {
  7216. return; // 允许
  7217. }
  7218. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7219. if ($source_uid == 0 && $target_uid == 0) {
  7220. return; // 允许
  7221. }
  7222. // 其他情况都不允许
  7223. if ($source_uid != 0 && $source_uid != $current_uid) {
  7224. // 源是别人的个人库
  7225. Utils::throwError('20003:无权限访问该资产');
  7226. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7227. // 个人库推送给公共库(不允许)
  7228. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7229. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7230. // 不同用户的个人库之间推送(不允许)
  7231. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7232. } else {
  7233. // 其他未知情况
  7234. Utils::throwError('20003:不允许的推送操作');
  7235. }
  7236. }
  7237. /**
  7238. * 复制单个资产
  7239. * @param object $sourceProduct 源资产对象
  7240. * @param int $targetParentId 目标父文件夹ID
  7241. * @param int $targetLevel 目标层级
  7242. * @param int $cpid 公司ID
  7243. * @param int $targetUid 目标用户ID
  7244. * @return int 返回新资产ID
  7245. */
  7246. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7247. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7248. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7249. $newProductData = [
  7250. 'user_id' => $targetUid,
  7251. 'cpid' => $cpid,
  7252. 'type' => 1,
  7253. 'parent_id' => $targetParentId,
  7254. 'level' => $targetLevel,
  7255. 'product_name' => $sourceProduct->product_name,
  7256. 'url' => $sourceProduct->url,
  7257. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7258. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7259. 'timbre_url' => $sourceProduct->timbre_url ?? '',
  7260. 'product' => $finalProductType,
  7261. 'versions' => $sourceProduct->versions ?? '',
  7262. 'sort_order' => time(),
  7263. 'is_deleted' => 0,
  7264. 'created_at' => date('Y-m-d H:i:s'),
  7265. 'updated_at' => date('Y-m-d H:i:s')
  7266. ];
  7267. return DB::table('mp_products')->insertGetId($newProductData);
  7268. }
  7269. /**
  7270. * 递归复制文件夹及其子项
  7271. * @param object $sourceFolder 源文件夹对象
  7272. * @param int $targetParentId 目标父文件夹ID
  7273. * @param int $targetLevel 目标层级
  7274. * @param int $cpid 公司ID
  7275. * @param int $targetUid 目标用户ID
  7276. * @param int $sourceUid 源用户ID
  7277. * @return int 返回新文件夹ID
  7278. */
  7279. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7280. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7281. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7282. // 创建新文件夹
  7283. $newFolderData = [
  7284. 'user_id' => $targetUid,
  7285. 'cpid' => $cpid,
  7286. 'type' => 2,
  7287. 'parent_id' => $targetParentId,
  7288. 'level' => $targetLevel,
  7289. 'product_name' => $sourceFolder->product_name,
  7290. 'product' => $finalProductType,
  7291. 'sort_order' => time(),
  7292. 'is_deleted' => 0,
  7293. 'created_at' => date('Y-m-d H:i:s'),
  7294. 'updated_at' => date('Y-m-d H:i:s')
  7295. ];
  7296. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7297. // 获取源文件夹下的所有子项
  7298. $children = DB::table('mp_products')
  7299. ->where('parent_id', $sourceFolder->id)
  7300. ->where('cpid', $cpid)
  7301. ->where('user_id', $sourceUid)
  7302. ->where('is_deleted', 0)
  7303. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7304. ->get();
  7305. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7306. foreach ($children as $child) {
  7307. if ($child->type == 1) {
  7308. // 资产
  7309. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7310. } else {
  7311. // 文件夹
  7312. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7313. }
  7314. }
  7315. return $newFolderId;
  7316. }
  7317. /**
  7318. * 转让剧本归属(剧本及其关联资产)
  7319. *
  7320. * 仅调整 mp_scripts.user_id 与 mp_products.user_id,其他表保持不变。
  7321. * 权限:仅 admin / superadmin 可操作;目标用户必须是同组(cpid 相同)且角色为 user(组员)的用户,禁止跨组转让。
  7322. * 多个剧本逐个独立事务处理,单个剧本失败不影响其他剧本;
  7323. * 单个剧本内的剧本记录与关联资产必须全部更新成功,否则整体回滚。
  7324. *
  7325. * @param array $data 请求参数:script_ids(数组或英文逗号分隔,兼容单个 script_id)、target_user_id
  7326. * @return array
  7327. */
  7328. public function transferScriptOwner($data) {
  7329. $operatorRole = Site::getRole();
  7330. $operatorCpid = Site::getCpid();
  7331. // 1.权限校验:仅管理员和超管可操作
  7332. if (!in_array($operatorRole, ['admin', 'superadmin'], true)) {
  7333. Utils::throwError(ErrorConst::NOT_ACCESS);
  7334. }
  7335. // 2.目标用户校验:必须存在且角色为 user(组员)
  7336. $targetUserId = (int)getProp($data, 'target_user_id', 0);
  7337. if ($targetUserId < 1) {
  7338. Utils::throwError('1002:请选择转让的目标用户');
  7339. }
  7340. $targetUser = DB::table('mp_manage_users')
  7341. ->where('id', $targetUserId)
  7342. ->where('is_deleted', 0)
  7343. ->first();
  7344. if (!$targetUser) {
  7345. Utils::throwError('20003:目标用户不存在');
  7346. }
  7347. if ((string)getProp($targetUser, 'role') !== 'user') {
  7348. Utils::throwError('20003:只能转让给角色为组员(user)的用户');
  7349. }
  7350. $targetCpid = (int)getProp($targetUser, 'cpid');
  7351. // 3.规范化剧本ID列表(兼容数组、逗号分隔字符串、script_id 单值)
  7352. $rawScriptIds = getProp($data, 'script_ids');
  7353. if (empty($rawScriptIds)) {
  7354. $rawScriptIds = getProp($data, 'script_id');
  7355. }
  7356. $scriptIds = $this->normalizeIdList($rawScriptIds);
  7357. if (empty($scriptIds)) {
  7358. Utils::throwError('20003:请提供剧本ID');
  7359. }
  7360. // 预取剧本名称,便于失败结果中回显
  7361. $scriptNameMap = DB::table('mp_scripts')
  7362. ->whereIn('id', $scriptIds)
  7363. ->pluck('script_name', 'id')
  7364. ->all();
  7365. $successList = [];
  7366. $failedList = [];
  7367. // 4.逐个剧本独立事务处理,单个失败不影响其他剧本
  7368. foreach ($scriptIds as $scriptId) {
  7369. DB::beginTransaction();
  7370. try {
  7371. $successList[] = $this->transferSingleScriptOwner(
  7372. $scriptId,
  7373. $targetUserId,
  7374. $targetCpid,
  7375. $operatorRole,
  7376. $operatorCpid,
  7377. Site::getUid()
  7378. );
  7379. DB::commit();
  7380. } catch (\Throwable $e) {
  7381. DB::rollBack();
  7382. $failedList[] = [
  7383. 'script_id' => (int)$scriptId,
  7384. 'script_name' => (string)($scriptNameMap[$scriptId] ?? ''),
  7385. 'reason' => $e->getMessage() !== '' ? $e->getMessage() : '转让失败',
  7386. ];
  7387. dLog('anime')->error('剧本归属转让失败', [
  7388. 'script_id' => $scriptId,
  7389. 'target_user_id' => $targetUserId,
  7390. 'operator_uid' => Site::getUid(),
  7391. 'error' => $e->getMessage(),
  7392. ]);
  7393. }
  7394. }
  7395. return [
  7396. 'target_user_id' => $targetUserId,
  7397. 'success_count' => count($successList),
  7398. 'failed_count' => count($failedList),
  7399. 'success_list' => $successList,
  7400. 'failed_list' => $failedList,
  7401. ];
  7402. }
  7403. /**
  7404. * 单个剧本的归属转让(需在事务中调用)
  7405. *
  7406. * @param int $scriptId 剧本ID
  7407. * @param int $targetUserId 目标用户ID
  7408. * @param int $targetCpid 目标用户所属公司ID
  7409. * @param string $operatorRole 操作人角色
  7410. * @param int $operatorCpid 操作人所属公司ID
  7411. * @param int $operatorUid 操作人用户ID
  7412. * @return array
  7413. */
  7414. private function transferSingleScriptOwner($scriptId, $targetUserId, $targetCpid, $operatorRole, $operatorCpid, $operatorUid) {
  7415. $script = DB::table('mp_scripts')
  7416. ->where('id', $scriptId)
  7417. ->where('is_deleted', 0)
  7418. ->first();
  7419. if (!$script) {
  7420. Utils::throwError('20003:剧本不存在');
  7421. }
  7422. $scriptCpid = (int)getProp($script, 'cpid');
  7423. $fromUserId = (int)getProp($script, 'user_id');
  7424. // 管理员仅可操作本组剧本
  7425. if ($operatorRole !== 'superadmin' && $scriptCpid !== $operatorCpid) {
  7426. Utils::throwError(ErrorConst::NOT_ACCESS);
  7427. }
  7428. // 管理员仅可转让自己创建的剧本(超管不做此验证)
  7429. if ($operatorRole !== 'superadmin' && $fromUserId !== (int)$operatorUid) {
  7430. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7431. }
  7432. // 禁止跨组转让:目标用户必须与剧本同组
  7433. if ($targetCpid !== $scriptCpid) {
  7434. Utils::throwError('20003:不能跨组转让,目标用户与剧本不在同一组');
  7435. }
  7436. // 关联资产ID(同一资产可能关联多个剧集序号,需去重)
  7437. $productIds = $this->normalizeIdList(
  7438. DB::table('mp_script_product_mappings')
  7439. ->where('script_id', $scriptId)
  7440. ->pluck('product_id')
  7441. ->all()
  7442. );
  7443. $folderIds = [];
  7444. if (!empty($productIds)) {
  7445. $products = DB::table('mp_products')
  7446. ->whereIn('id', $productIds)
  7447. ->select('id', 'cpid', 'parent_id', 'user_id')
  7448. ->get();
  7449. // 关联资产必须全部存在,否则视为数据异常,不提交
  7450. if ($products->count() !== count($productIds)) {
  7451. Utils::throwError('20003:剧本存在已丢失的关联资产,无法完成转让');
  7452. }
  7453. foreach ($products as $product) {
  7454. // 关联资产必须与剧本同组,避免误转让跨组资产
  7455. if ((int)getProp($product, 'cpid') !== $scriptCpid) {
  7456. Utils::throwError('20003:剧本存在跨组关联资产,无法完成转让');
  7457. }
  7458. $parentId = (int)getProp($product, 'parent_id', 0);
  7459. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7460. $folderIds[] = $parentId;
  7461. }
  7462. }
  7463. // 仅转让归属于原剧本所有者的资产
  7464. $folderIds = DB::table('mp_products')
  7465. ->whereIn('id', $folderIds)
  7466. ->where('type', 2)
  7467. ->where('cpid', $scriptCpid)
  7468. ->where('user_id', $fromUserId)
  7469. ->pluck('id')
  7470. ->map('intval')
  7471. ->all();
  7472. // 管理员仅可转让自己创建的资产及其所属文件夹(超管不做此验证)
  7473. if ($operatorRole !== 'superadmin') {
  7474. foreach ($products as $product) {
  7475. if ((int)getProp($product, 'user_id') !== (int)$operatorUid) {
  7476. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7477. }
  7478. }
  7479. foreach ($products as $product) {
  7480. $parentId = (int)getProp($product, 'parent_id', 0);
  7481. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7482. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7483. }
  7484. }
  7485. }
  7486. }
  7487. $now = now();
  7488. // 5.更新剧本归属
  7489. DB::table('mp_scripts')
  7490. ->where('id', $scriptId)
  7491. ->update([
  7492. 'user_id' => $targetUserId,
  7493. 'updated_at' => $now,
  7494. ]);
  7495. // 6.更新关联资产归属
  7496. if (!empty($productIds)) {
  7497. DB::table('mp_products')
  7498. ->whereIn('id', $productIds)
  7499. ->update([
  7500. 'user_id' => $targetUserId,
  7501. 'updated_at' => $now,
  7502. ]);
  7503. }
  7504. // 7.更新资产所属的类型根文件夹归属(文件夹属于 mp_products,随资产一并转让)
  7505. if (!empty($folderIds)) {
  7506. DB::table('mp_products')
  7507. ->whereIn('id', $folderIds)
  7508. ->update([
  7509. 'user_id' => $targetUserId,
  7510. 'updated_at' => $now,
  7511. ]);
  7512. }
  7513. // 8.校验剧本与资产是否全部更新成功,任一未成功则回滚
  7514. $scriptOwner = (int)DB::table('mp_scripts')->where('id', $scriptId)->value('user_id');
  7515. if ($scriptOwner !== $targetUserId) {
  7516. Utils::throwError('20003:剧本归属更新失败');
  7517. }
  7518. if (!empty($productIds)) {
  7519. $updatedProductCount = DB::table('mp_products')
  7520. ->whereIn('id', $productIds)
  7521. ->where('user_id', $targetUserId)
  7522. ->count();
  7523. if ($updatedProductCount !== count($productIds)) {
  7524. Utils::throwError('20003:部分剧本资产转让失败,已回滚');
  7525. }
  7526. }
  7527. if (!empty($folderIds)) {
  7528. $updatedFolderCount = DB::table('mp_products')
  7529. ->whereIn('id', $folderIds)
  7530. ->where('user_id', $targetUserId)
  7531. ->count();
  7532. if ($updatedFolderCount !== count($folderIds)) {
  7533. Utils::throwError('20003:部分资产文件夹转让失败,已回滚');
  7534. }
  7535. }
  7536. return [
  7537. 'script_id' => (int)$scriptId,
  7538. 'script_name' => (string)getProp($script, 'script_name', ''),
  7539. 'from_user_id' => $fromUserId,
  7540. 'to_user_id' => $targetUserId,
  7541. 'product_count' => count($productIds),
  7542. 'folder_count' => count($folderIds),
  7543. ];
  7544. }
  7545. /**
  7546. * 规范化ID列表,兼容数组、逗号分隔字符串以及字符串数组
  7547. *
  7548. * @param mixed $ids 待处理的ID集合
  7549. * @return array 去重后的正整数ID数组
  7550. */
  7551. private function normalizeIdList($ids) {
  7552. if (!is_array($ids)) {
  7553. $ids = explode(',', (string)$ids);
  7554. }
  7555. $result = [];
  7556. foreach ($ids as $item) {
  7557. if (is_array($item)) {
  7558. continue;
  7559. }
  7560. foreach (explode(',', (string)$item) as $part) {
  7561. $part = trim($part);
  7562. if ($part !== '' && is_numeric($part) && (int)$part > 0) {
  7563. $result[] = (int)$part;
  7564. }
  7565. }
  7566. }
  7567. return array_values(array_unique($result));
  7568. }
  7569. /**
  7570. * 通过 Excel 批量导入剧本资产(独立实现,不依赖 saveScriptProducts)
  7571. *
  7572. * 流程:
  7573. * 1. 校验剧本存在且属于当前用户
  7574. * 2. 解析 Excel 并校验强制列与数据完整性(资产类型/资产名称/使用范围/参考提示词)
  7575. * 3. 名称去重(与 Excel 内及该剧本已有关联资产比对)
  7576. * 4. 事务内创建类型文件夹、资产与剧本映射
  7577. * 5. 为没有图片的资产创建图片生成任务,生成中返回 SSE 轮询
  7578. *
  7579. * @param array $data 请求参数
  7580. * @param \Illuminate\Http\UploadedFile $file 上传的 Excel 文件
  7581. * @return array|\Generator
  7582. */
  7583. public function importScriptProductsByExcel($data, $file) {
  7584. $uid = Site::getUid();
  7585. $cpid = Site::getCpid();
  7586. $script_id = (int)getProp($data, 'script_id', 0);
  7587. if (!$script_id) {
  7588. Utils::throwError('20003:请提供剧本ID');
  7589. }
  7590. // 验证剧本是否存在,且只能导入自己创建的剧本
  7591. $script = DB::table('mp_scripts')
  7592. ->where('id', $script_id)
  7593. ->where('is_deleted', 0)
  7594. ->where('user_id', $uid)
  7595. ->first();
  7596. if (!$script) {
  7597. Utils::throwError('20003:剧本不存在或无权限操作');
  7598. }
  7599. $script_name = $script->script_name ?? 'script_' . $script_id;
  7600. // 校验上传文件
  7601. if (!$file) {
  7602. Utils::throwError('20003:请上传Excel文件');
  7603. }
  7604. $extension = strtolower($file->getClientOriginalExtension());
  7605. if (!in_array($extension, ['xlsx', 'xls'])) {
  7606. Utils::throwError('20003:文件格式错误,仅支持 xlsx、xls 格式');
  7607. }
  7608. if ($file->getSize() > 10 * 1024 * 1024) {
  7609. Utils::throwError('20003:文件大小不能超过10M');
  7610. }
  7611. // 解析 Excel(第一行为表头)
  7612. $rows = $this->readImportExcelRows($file);
  7613. if (empty($rows)) {
  7614. Utils::throwError('20003:Excel内容为空');
  7615. }
  7616. $headers = array_shift($rows);
  7617. // 定位强制列
  7618. $typeColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产类型'], ['资产类型', '类型']);
  7619. $nameColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产名称'], ['资产名称', '名称']);
  7620. $rangeColumnIndex = $this->findImportExcelColumnIndex($headers, ['使用范围'], ['使用范围', '范围']);
  7621. $promptColumnIndex = $this->findImportExcelColumnIndex($headers, ['参考提示词', '提示词'], ['提示词']);
  7622. $missingColumns = [];
  7623. if ($typeColumnIndex < 0) {
  7624. $missingColumns[] = '资产类型';
  7625. }
  7626. if ($nameColumnIndex < 0) {
  7627. $missingColumns[] = '资产名称';
  7628. }
  7629. if ($rangeColumnIndex < 0) {
  7630. $missingColumns[] = '使用范围';
  7631. }
  7632. if ($promptColumnIndex < 0) {
  7633. $missingColumns[] = '参考提示词';
  7634. }
  7635. if (!empty($missingColumns)) {
  7636. Utils::throwError('20003:Excel缺少必填列:' . implode('、', $missingColumns));
  7637. }
  7638. // 先整体校验 Excel 数据,所有异常行一次性返回
  7639. $validation = $this->validateImportExcelRows(
  7640. $rows,
  7641. $typeColumnIndex,
  7642. $nameColumnIndex,
  7643. $rangeColumnIndex,
  7644. $promptColumnIndex
  7645. );
  7646. $errors = $validation['errors'];
  7647. $checkedRows = $validation['checked_rows'];
  7648. if (empty($checkedRows)) {
  7649. $errors[] = 'Excel中没有有效的数据行';
  7650. }
  7651. if (!empty($errors)) {
  7652. Utils::throwError('20003:Excel数据校验失败:' . implode(';', $errors));
  7653. }
  7654. // 名称去重:Excel 内部 + 该剧本已关联资产(按 createProduct 的名称判断逻辑)
  7655. $existingNames = $this->getScriptProductNames($script_id, $cpid);
  7656. $dedupResult = $this->deduplicateImportRows($checkedRows, $existingNames);
  7657. $validRows = $dedupResult['valid_rows'];
  7658. $skipped = $dedupResult['skipped'];
  7659. // 图片生成参数(与 saveScriptProducts 保持一致的校验规则)
  7660. $model = getProp($data, 'model');
  7661. if (!$model) {
  7662. $model = 'gpt-image-2';
  7663. }
  7664. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7665. Utils::throwError('20003:该模型已不可用,请更换!');
  7666. }
  7667. $ratio = getProp($data, 'ratio', '9:16');
  7668. $resolution = strtolower(getProp($data, 'resolution', '2k'));
  7669. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7670. if (!isset($sizeMap[$resolution])) {
  7671. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7672. }
  7673. if (!isset($sizeMap[$resolution][$ratio])) {
  7674. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7675. }
  7676. $width = $sizeMap[$resolution][$ratio]['width'];
  7677. $height = $sizeMap[$resolution][$ratio]['height'];
  7678. $autoRaw = getProp($data, 'auto_generate_images', true);
  7679. $auto_generate_images = !in_array($autoRaw, [false, 0, '0', 'false', 'False'], true);
  7680. // 创建/复用任务中心记录(md5 验重,避免重复任务)
  7681. $taskCenterId = $this->createScriptProductTaskCenter(
  7682. $uid,
  7683. $cpid,
  7684. $script_id,
  7685. $validRows,
  7686. $model,
  7687. $ratio,
  7688. $resolution,
  7689. $auto_generate_images
  7690. );
  7691. // 全部为重复项:参照 saveScriptProducts,检查已存在资产的图片状态,缺图的补建任务
  7692. if (empty($validRows)) {
  7693. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7694. $script_id,
  7695. $model,
  7696. $width,
  7697. $height,
  7698. $auto_generate_images
  7699. );
  7700. $productTaskMap = $existingTaskInfo['product_task_map'];
  7701. $typeFolderIds = $existingTaskInfo['type_folder_ids'];
  7702. if (!empty($productTaskMap)) {
  7703. $message = 'Excel中的资产均已存在,正在为缺少图片的资产生成图片';
  7704. } elseif (!$existingTaskInfo['has_all_tasks']) {
  7705. $message = 'Excel中的资产均已存在,部分资产没有参考提示词,无法生成图片';
  7706. } else {
  7707. $message = 'Excel中的资产均已存在,且图片已全部生成完成';
  7708. }
  7709. $resultData = [
  7710. 'success' => true,
  7711. 'message' => $message,
  7712. 'script_id' => $script_id,
  7713. 'script_name' => $script_name,
  7714. 'imported_count' => 0,
  7715. 'existing_products' => $existingTaskInfo['product_count'],
  7716. 'skipped_count' => count($skipped),
  7717. 'skipped' => $skipped,
  7718. 'created_products' => [],
  7719. 'type_folder_ids' => $typeFolderIds,
  7720. 'pending_tasks_count' => count($productTaskMap),
  7721. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7722. 'task_center_id' => $taskCenterId,
  7723. ];
  7724. // 有需要轮询的任务(已有任务或本次补建):走 SSE 轮询
  7725. if (!empty($productTaskMap)) {
  7726. return $this->pollProductImageTasks(
  7727. $script_id,
  7728. $script_name,
  7729. $productTaskMap,
  7730. $typeFolderIds,
  7731. $taskCenterId,
  7732. ['import_result' => $resultData],
  7733. ['import_result' => $resultData]
  7734. );
  7735. }
  7736. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7737. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7738. }
  7739. // 事务内创建资产、类型文件夹与剧本映射
  7740. $typeFolderIds = [];
  7741. $createdProducts = [];
  7742. $mappingRecords = [];
  7743. $now = now();
  7744. DB::beginTransaction();
  7745. try {
  7746. foreach ($validRows as $row) {
  7747. $type = $row['type'];
  7748. if (!isset($typeFolderIds[$type])) {
  7749. // 与 createProduct 一致:先查找该剧本已存在的类型文件夹,没有则创建
  7750. $folder = DB::table('mp_products')
  7751. ->where('cpid', $cpid)
  7752. ->where('type', 2)
  7753. ->where('product', $type)
  7754. ->where('product_name', $script_name)
  7755. ->where('parent_id', 0)
  7756. ->where('is_deleted', 0)
  7757. ->first();
  7758. if ($folder) {
  7759. $typeFolderIds[$type] = $folder->id;
  7760. } else {
  7761. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7762. 'user_id' => $uid,
  7763. 'cpid' => $cpid,
  7764. 'type' => 2, // 文件夹
  7765. 'product' => $type, // 1=角色 2=场景 3=道具
  7766. 'parent_id' => 0,
  7767. 'level' => 1,
  7768. 'product_name' => $script_name,
  7769. 'sort_order' => time() + $type,
  7770. 'is_deleted' => 0,
  7771. 'created_at' => $now,
  7772. 'updated_at' => $now,
  7773. ]);
  7774. }
  7775. }
  7776. $folder_id = $typeFolderIds[$type];
  7777. $product_id = DB::table('mp_products')->insertGetId([
  7778. 'user_id' => $uid,
  7779. 'cpid' => $cpid,
  7780. 'type' => 1, // 资产
  7781. 'product' => $type,
  7782. 'parent_id' => $folder_id,
  7783. 'level' => 2,
  7784. 'product_name' => $row['product_name'],
  7785. 'pic_prompt' => $row['pic_prompt'],
  7786. 'sort_order' => time(),
  7787. 'is_deleted' => 0,
  7788. 'created_at' => $now,
  7789. 'updated_at' => $now,
  7790. ]);
  7791. $createdProducts[] = [
  7792. 'id' => $product_id,
  7793. 'type' => $type,
  7794. 'product_name' => $row['product_name'],
  7795. 'pic_prompt' => $row['pic_prompt'],
  7796. ];
  7797. // 为每个使用范围(集数)创建映射记录
  7798. foreach ($row['episode_numbers'] as $episodeNumber) {
  7799. $mappingRecords[] = [
  7800. 'script_id' => $script_id,
  7801. 'product_id' => $product_id,
  7802. 'episode_number' => $episodeNumber,
  7803. 'created_at' => $now,
  7804. 'updated_at' => $now,
  7805. ];
  7806. }
  7807. }
  7808. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7809. DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7810. // 剧本已有资产,同步更新is_products标记
  7811. DB::table('mp_scripts')->where('id', $script_id)->update([
  7812. 'is_products' => 1,
  7813. 'updated_at' => $now,
  7814. ]);
  7815. DB::commit();
  7816. } catch (\Exception $e) {
  7817. DB::rollback();
  7818. if ($taskCenterId) {
  7819. $this->taskCenterService->updateTask($taskCenterId, [
  7820. 'status' => MpTaskCenter::STATUS_FAILED,
  7821. 'error_message' => $e->getMessage(),
  7822. ]);
  7823. }
  7824. dLog('anime')->error('Excel导入剧本资产失败: ' . $e->getMessage(), [
  7825. 'script_id' => $script_id,
  7826. 'error' => $e->getMessage(),
  7827. 'trace' => $e->getTraceAsString(),
  7828. ]);
  7829. Utils::throwError('20003:Excel导入剧本资产失败:' . $e->getMessage());
  7830. }
  7831. // 参照 saveScriptProducts:为新建资产以及已存在但缺图的资产统一补建图片生成任务
  7832. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7833. $script_id,
  7834. $model,
  7835. $width,
  7836. $height,
  7837. $auto_generate_images
  7838. );
  7839. $productTaskMap = $existingTaskInfo['product_task_map'];
  7840. $resultData = [
  7841. 'success' => true,
  7842. 'message' => '导入完成',
  7843. 'script_id' => $script_id,
  7844. 'script_name' => $script_name,
  7845. 'imported_count' => count($createdProducts),
  7846. 'skipped_count' => count($skipped),
  7847. 'skipped' => $skipped,
  7848. 'created_products' => array_map(function ($item) {
  7849. return [
  7850. 'id' => $item['id'],
  7851. 'type' => $item['type'],
  7852. 'product_name' => $item['product_name'],
  7853. ];
  7854. }, $createdProducts),
  7855. 'type_folder_ids' => $typeFolderIds,
  7856. 'pending_tasks_count' => count($productTaskMap),
  7857. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7858. 'task_center_id' => $taskCenterId,
  7859. ];
  7860. // 有待生成的图片任务:返回 SSE 轮询结果(导入统计在 init 与 complete 事件中)
  7861. if (!empty($productTaskMap)) {
  7862. return $this->pollProductImageTasks(
  7863. $script_id,
  7864. $script_name,
  7865. $productTaskMap,
  7866. $typeFolderIds,
  7867. $taskCenterId,
  7868. ['import_result' => $resultData],
  7869. ['import_result' => $resultData]
  7870. );
  7871. }
  7872. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7873. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7874. }
  7875. /**
  7876. * 校验 Excel 数据行(先校验完毕,再进行后续逻辑)
  7877. *
  7878. * @param array $rows
  7879. * @param int $typeColumnIndex
  7880. * @param int $nameColumnIndex
  7881. * @param int $rangeColumnIndex
  7882. * @param int $promptColumnIndex
  7883. * @return array ['errors' => [], 'checked_rows' => []]
  7884. */
  7885. private function validateImportExcelRows(array $rows, $typeColumnIndex, $nameColumnIndex, $rangeColumnIndex, $promptColumnIndex) {
  7886. $errors = [];
  7887. $checkedRows = [];
  7888. foreach ($rows as $rowIndex => $row) {
  7889. // 数据从第2行开始(表头占第1行)
  7890. $excelRowNo = $rowIndex + 2;
  7891. if (!is_array($row) || $this->isImportExcelRowEmpty($row)) {
  7892. continue;
  7893. }
  7894. $typeRaw = trim((string)($row[$typeColumnIndex] ?? ''));
  7895. $nameRaw = trim((string)($row[$nameColumnIndex] ?? ''));
  7896. $rangeRaw = trim((string)($row[$rangeColumnIndex] ?? ''));
  7897. $promptRaw = trim((string)($row[$promptColumnIndex] ?? ''));
  7898. $missingFields = [];
  7899. if ($typeRaw === '') {
  7900. $missingFields[] = '资产类型';
  7901. }
  7902. if ($nameRaw === '') {
  7903. $missingFields[] = '资产名称';
  7904. }
  7905. if ($rangeRaw === '') {
  7906. $missingFields[] = '使用范围';
  7907. }
  7908. if ($promptRaw === '') {
  7909. $missingFields[] = '参考提示词';
  7910. }
  7911. if (!empty($missingFields)) {
  7912. $errors[] = "第{$excelRowNo}行:" . implode('、', $missingFields) . '不能为空';
  7913. continue;
  7914. }
  7915. // 资产类型校验
  7916. $productType = $this->resolveImportProductType($typeRaw);
  7917. if (!$productType) {
  7918. $errors[] = "第{$excelRowNo}行:资产类型「{$typeRaw}」不正确,仅支持 角色/场景/道具";
  7919. continue;
  7920. }
  7921. // 资产名称去除两边特殊符号
  7922. $productName = $this->normalizeImportProductName($nameRaw);
  7923. if ($productName === '') {
  7924. $errors[] = "第{$excelRowNo}行:资产名称「{$nameRaw}」去除特殊符号后为空";
  7925. continue;
  7926. }
  7927. if (mb_strlen($productName, 'UTF-8') > 64) {
  7928. $errors[] = "第{$excelRowNo}行:资产名称「{$productName}」超过64个字符";
  7929. continue;
  7930. }
  7931. // 解析使用范围(逗号分隔的集数)
  7932. $episodeNumbers = $this->parseImportEpisodeNumbers($rangeRaw);
  7933. if (empty($episodeNumbers)) {
  7934. $errors[] = "第{$excelRowNo}行:使用范围「{$rangeRaw}」格式错误,仅支持数字或逗号分隔的数字";
  7935. continue;
  7936. }
  7937. $checkedRows[] = [
  7938. 'row' => $excelRowNo,
  7939. 'type' => $productType,
  7940. 'product_name' => $productName,
  7941. 'episode_numbers' => $episodeNumbers,
  7942. 'pic_prompt' => $promptRaw,
  7943. ];
  7944. }
  7945. return [
  7946. 'errors' => $errors,
  7947. 'checked_rows' => $checkedRows,
  7948. ];
  7949. }
  7950. /**
  7951. * Excel 资产名称去重:Excel 内部 + 剧本已有关联资产
  7952. *
  7953. * @param array $checkedRows
  7954. * @param array $existingNames 剧本已有关联资产名称集合(name => true)
  7955. * @return array ['valid_rows' => [], 'skipped' => []]
  7956. */
  7957. private function deduplicateImportRows(array $checkedRows, array $existingNames) {
  7958. $seenNames = [];
  7959. $validRows = [];
  7960. $skipped = [];
  7961. foreach ($checkedRows as $row) {
  7962. $nameKey = $row['product_name'];
  7963. $typeText = $this->getImportProductTypeText($row['type']);
  7964. if (isset($seenNames[$nameKey])) {
  7965. $skipped[] = [
  7966. 'row' => $row['row'],
  7967. 'type' => $typeText,
  7968. 'product_name' => $row['product_name'],
  7969. 'reason' => 'Excel中资产名称重复',
  7970. ];
  7971. continue;
  7972. }
  7973. if (isset($existingNames[$nameKey])) {
  7974. $skipped[] = [
  7975. 'row' => $row['row'],
  7976. 'type' => $typeText,
  7977. 'product_name' => $row['product_name'],
  7978. 'reason' => '剧本中已存在同名资产',
  7979. ];
  7980. continue;
  7981. }
  7982. $seenNames[$nameKey] = true;
  7983. $validRows[] = $row;
  7984. }
  7985. return [
  7986. 'valid_rows' => $validRows,
  7987. 'skipped' => $skipped,
  7988. ];
  7989. }
  7990. /**
  7991. * 读取 Excel 文件为二维数组(第一行为表头)
  7992. *
  7993. * @param \Illuminate\Http\UploadedFile $file
  7994. * @return array
  7995. */
  7996. private function readImportExcelRows($file) {
  7997. try {
  7998. $reader = IOFactory::createReaderForFile($file->getRealPath());
  7999. $reader->setReadDataOnly(true);
  8000. $spreadsheet = $reader->load($file->getRealPath());
  8001. $sheet = $spreadsheet->getSheet(0);
  8002. $rows = $sheet->toArray(null, true, true, false);
  8003. $spreadsheet->disconnectWorksheets();
  8004. unset($spreadsheet);
  8005. return $rows;
  8006. } catch (\Exception $e) {
  8007. dLog('anime')->error('Excel文件解析失败', [
  8008. 'error' => $e->getMessage(),
  8009. ]);
  8010. Utils::throwError('20003:Excel文件解析失败,请确认文件格式正确');
  8011. }
  8012. }
  8013. /**
  8014. * 查找 Excel 表头列索引(先精确匹配,再模糊匹配)
  8015. *
  8016. * @param array $headers
  8017. * @param array $exactKeywords
  8018. * @param array $fuzzyKeywords
  8019. * @return int
  8020. */
  8021. private function findImportExcelColumnIndex(array $headers, array $exactKeywords, array $fuzzyKeywords) {
  8022. foreach ($headers as $index => $header) {
  8023. $header = trim((string)$header);
  8024. if ($header === '') {
  8025. continue;
  8026. }
  8027. foreach ($exactKeywords as $keyword) {
  8028. if ($header === $keyword) {
  8029. return $index;
  8030. }
  8031. }
  8032. }
  8033. foreach ($headers as $index => $header) {
  8034. $header = trim((string)$header);
  8035. if ($header === '') {
  8036. continue;
  8037. }
  8038. foreach ($fuzzyKeywords as $keyword) {
  8039. if (mb_strpos($header, $keyword) !== false) {
  8040. return $index;
  8041. }
  8042. }
  8043. }
  8044. return -1;
  8045. }
  8046. /**
  8047. * 判断 Excel 行是否为空行
  8048. *
  8049. * @param array $row
  8050. * @return bool
  8051. */
  8052. private function isImportExcelRowEmpty(array $row) {
  8053. foreach ($row as $cell) {
  8054. if (trim((string)$cell) !== '') {
  8055. return false;
  8056. }
  8057. }
  8058. return true;
  8059. }
  8060. /**
  8061. * 资产名称去除两边特殊符号(与 createProduct 保持一致)
  8062. *
  8063. * @param string $name
  8064. * @return string
  8065. */
  8066. private function normalizeImportProductName($name) {
  8067. $name = trim((string)$name);
  8068. $name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $name);
  8069. if (!$name || preg_match('/^[-—_]+$/u', $name)) {
  8070. return '';
  8071. }
  8072. return $name;
  8073. }
  8074. /**
  8075. * 解析 Excel 中的资产类型
  8076. *
  8077. * @param string $value
  8078. * @return int|null 1=角色 2=场景 3=道具
  8079. */
  8080. private function resolveImportProductType($value) {
  8081. $value = trim((string)$value);
  8082. $map = [
  8083. '角色' => 1,
  8084. '主体' => 1,
  8085. '人物' => 1,
  8086. '1' => 1,
  8087. '场景' => 2,
  8088. '2' => 2,
  8089. '道具' => 3,
  8090. '3' => 3,
  8091. ];
  8092. return isset($map[$value]) ? $map[$value] : null;
  8093. }
  8094. /**
  8095. * 资产类型文案
  8096. *
  8097. * @param int $type
  8098. * @return string
  8099. */
  8100. private function getImportProductTypeText($type) {
  8101. $map = [1 => '角色', 2 => '场景', 3 => '道具'];
  8102. return isset($map[$type]) ? $map[$type] : (string)$type;
  8103. }
  8104. /**
  8105. * 解析使用范围(逗号分隔的集数)
  8106. *
  8107. * @param string $value
  8108. * @return array
  8109. */
  8110. private function parseImportEpisodeNumbers($value) {
  8111. $parts = preg_split('/[,,、\s]+/u', trim((string)$value));
  8112. $episodeNumbers = [];
  8113. foreach ($parts as $part) {
  8114. if ($part === '') {
  8115. continue;
  8116. }
  8117. if (!is_numeric($part)) {
  8118. return [];
  8119. }
  8120. $episodeNumbers[] = (int)$part;
  8121. }
  8122. $episodeNumbers = array_values(array_unique($episodeNumbers));
  8123. sort($episodeNumbers);
  8124. return $episodeNumbers;
  8125. }
  8126. /**
  8127. * 获取剧本已关联资产名称集合(按 createProduct 的名称判断逻辑)
  8128. *
  8129. * @param int $script_id
  8130. * @param int $cpid
  8131. * @return array
  8132. */
  8133. private function getScriptProductNames($script_id, $cpid) {
  8134. $products = DB::table('mp_script_product_mappings as m')
  8135. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8136. ->where('m.script_id', $script_id)
  8137. ->where('p.cpid', $cpid)
  8138. ->where('p.type', 1)
  8139. ->where('p.is_deleted', 0)
  8140. ->get(['p.product_name']);
  8141. $names = [];
  8142. foreach ($products as $product) {
  8143. $name = $this->normalizeImportProductName($product->product_name);
  8144. if ($name !== '') {
  8145. $names[$name] = true;
  8146. }
  8147. }
  8148. return $names;
  8149. }
  8150. /**
  8151. * 获取剧本已关联的资产名称(仅按剧本判重,不区分资产类型)
  8152. *
  8153. * @param int $script_id
  8154. * @return array ['资产名称' => true]
  8155. */
  8156. private function getScriptAssetNames($script_id) {
  8157. $products = DB::table('mp_script_product_mappings as m')
  8158. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8159. ->where('m.script_id', $script_id)
  8160. ->where('p.type', 1)
  8161. ->where('p.is_deleted', 0)
  8162. ->get(['p.product_name']);
  8163. $names = [];
  8164. foreach ($products as $product) {
  8165. $name = $this->normalizeImportProductName($product->product_name);
  8166. if ($name !== '') {
  8167. $names[$name] = true;
  8168. }
  8169. }
  8170. return $names;
  8171. }
  8172. /**
  8173. * 校验并提取本次入参中的新增资产行
  8174. *
  8175. * 规则:
  8176. * - 资产名称为空(或仅剩占位符):跳过
  8177. * - 同一份入参内重名(跨类型):保留最后一条
  8178. * - 与剧本已关联资产同名(跨类型判重,仅限当前剧本):不算新增
  8179. * - 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8180. *
  8181. * @param int $script_id
  8182. * @param mixed $products 入参(数组或 JSON 字符串)
  8183. * @return array [['type' => int, 'product_name' => string, 'pic_prompt' => string, 'episode_numbers' => []]]
  8184. */
  8185. private function extractNewScriptProductRows($script_id, $products) {
  8186. // 兼容 JSON 字符串;无法解析时按"没有新增行"处理,由后续创建逻辑给出原有报错
  8187. if (is_string($products)) {
  8188. $decoded = json_decode($products, true);
  8189. $products = (json_last_error() === JSON_ERROR_NONE) ? $decoded : [];
  8190. }
  8191. if (!is_array($products) || empty($products)) {
  8192. return [];
  8193. }
  8194. $rowMap = [];
  8195. foreach ($products as $productGroup) {
  8196. $type = getProp($productGroup, 'type');
  8197. $content = getProp($productGroup, 'content', []);
  8198. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8199. continue;
  8200. }
  8201. // 获取表头(第一行)并查找关键列的位置
  8202. $headers = $content[0];
  8203. $nameColumnIndex = -1;
  8204. $sequenceColumnIndex = -1;
  8205. $promptColumnIndex = -1;
  8206. $fallbackPromptColumnIndex = -1;
  8207. foreach ($headers as $index => $header) {
  8208. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8209. $nameColumnIndex = $index;
  8210. }
  8211. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8212. $sequenceColumnIndex = $index;
  8213. }
  8214. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8215. $promptColumnIndex = $index;
  8216. } elseif (strpos($header, '提示词') !== false && $fallbackPromptColumnIndex === -1) {
  8217. // 与 Excel 导入保持一致:优先"参考提示词",否则兼容"提示词"列
  8218. $fallbackPromptColumnIndex = $index;
  8219. }
  8220. }
  8221. if ($promptColumnIndex === -1) {
  8222. $promptColumnIndex = $fallbackPromptColumnIndex;
  8223. }
  8224. if ($nameColumnIndex === -1) {
  8225. continue;
  8226. }
  8227. for ($i = 1; $i < count($content); $i++) {
  8228. $row = $content[$i];
  8229. if (empty($row) || !isset($row[$nameColumnIndex])) {
  8230. continue;
  8231. }
  8232. // 处理product_name两边的符号;名称为空或仅剩占位符号则跳过
  8233. $product_name = $this->normalizeImportProductName($row[$nameColumnIndex]);
  8234. if ($product_name === '') {
  8235. continue;
  8236. }
  8237. $pic_prompt = '';
  8238. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8239. $pic_prompt = trim((string)$row[$promptColumnIndex]);
  8240. }
  8241. // 解析使用范围(逗号分隔的序号),为空时由创建逻辑写入默认映射(序号0)
  8242. $sequences = [];
  8243. $sequence_str = ($sequenceColumnIndex >= 0 && isset($row[$sequenceColumnIndex]))
  8244. ? trim((string)$row[$sequenceColumnIndex])
  8245. : '';
  8246. if ($sequence_str !== '') {
  8247. foreach (array_map('trim', explode(',', $sequence_str)) as $part) {
  8248. if (is_numeric($part)) {
  8249. $sequences[] = (int)$part;
  8250. }
  8251. }
  8252. }
  8253. // 跨类型判重,同一份入参内重名保留最后一条
  8254. $rowMap[$product_name] = [
  8255. 'type' => (int)$type,
  8256. 'product_name' => $product_name,
  8257. 'pic_prompt' => $pic_prompt,
  8258. 'episode_numbers' => $sequences,
  8259. ];
  8260. }
  8261. }
  8262. // 与剧本已关联资产判重(仅限当前剧本,跨类型)
  8263. $existingNames = $this->getScriptAssetNames($script_id);
  8264. $newRows = [];
  8265. $emptyPromptNames = [];
  8266. foreach ($rowMap as $name => $row) {
  8267. if (isset($existingNames[$name])) {
  8268. continue;
  8269. }
  8270. if ($row['pic_prompt'] === '') {
  8271. $emptyPromptNames[] = $name;
  8272. continue;
  8273. }
  8274. $newRows[] = $row;
  8275. }
  8276. // 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8277. if (!empty($emptyPromptNames)) {
  8278. Utils::throwError('20003:以下新增资产的参考提示词不能为空:' . implode('、', $emptyPromptNames));
  8279. }
  8280. return $newRows;
  8281. }
  8282. /**
  8283. * 已有关联资产的图片任务处理(参照 saveScriptProducts 的处理方式)
  8284. *
  8285. * - 已有图片任务的资产:收集任务ID,交给轮询
  8286. * - 已有图片且生成成功的资产:跳过
  8287. * - 没有图片的资产:允许自动生成时补建图片任务(需要提示词)
  8288. *
  8289. * @param int $script_id
  8290. * @param string $model
  8291. * @param int $width
  8292. * @param int $height
  8293. * @param bool $auto_generate_images
  8294. * @return array ['product_task_map' => [], 'type_folder_ids' => [], 'has_all_tasks' => bool, 'product_count' => int, 'created_count' => int]
  8295. */
  8296. private function prepareExistingScriptProductTasks($script_id, $model, $width, $height, $auto_generate_images) {
  8297. $productTaskMap = [];
  8298. $typeFolderIds = [];
  8299. $hasAllTasks = true;
  8300. $createdCount = 0;
  8301. $existingMappings = DB::table('mp_script_product_mappings')
  8302. ->where('script_id', $script_id)
  8303. ->get();
  8304. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8305. $productsWithTasks = DB::table('mp_products')
  8306. ->whereIn('id', $productIds)
  8307. ->where('is_deleted', 0)
  8308. ->get();
  8309. foreach ($productsWithTasks as $product) {
  8310. // 收集类型文件夹ID
  8311. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8312. $parentFolder = DB::table('mp_products')
  8313. ->where('id', $product->parent_id)
  8314. ->where('type', 2)
  8315. ->first();
  8316. if ($parentFolder) {
  8317. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8318. }
  8319. }
  8320. // 检查是否有图片生成任务
  8321. if (!empty($product->pic_task_id)) {
  8322. $productTaskMap[$product->id] = $product->pic_task_id;
  8323. } elseif ($product->url && $product->pic_task_status == '生成成功') {
  8324. continue;
  8325. } else {
  8326. // 有资产没有图片
  8327. $hasAllTasks = false;
  8328. }
  8329. }
  8330. // 为没有图片的资产补建图片生成任务
  8331. if (!$hasAllTasks && $auto_generate_images && $productsWithTasks->isNotEmpty()) {
  8332. DB::beginTransaction();
  8333. try {
  8334. foreach ($productsWithTasks as $product) {
  8335. // 跳过已有任务的资产
  8336. if (!empty($product->pic_task_id)) {
  8337. continue;
  8338. }
  8339. // 跳过没有提示词的资产
  8340. if (empty($product->pic_prompt)) {
  8341. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8342. 'product_id' => $product->id,
  8343. 'product_name' => $product->product_name,
  8344. ]);
  8345. continue;
  8346. }
  8347. try {
  8348. $task = $this->aiImageGenerationService->createImageGenerationTask([
  8349. 'prompt' => $product->pic_prompt,
  8350. 'model' => $model,
  8351. 'ref_img_urls' => [],
  8352. 'width' => $width,
  8353. 'height' => $height,
  8354. // 计费锚点(剧本),用于积分明细归属统计
  8355. 'script_id' => $script_id,
  8356. ]);
  8357. $task_id = $task->id;
  8358. if ($task_id) {
  8359. $productTaskMap[$product->id] = $task_id;
  8360. $createdCount++;
  8361. DB::table('mp_products')
  8362. ->where('id', $product->id)
  8363. ->update([
  8364. 'pic_task_id' => $task_id,
  8365. 'pic_task_status' => '生成中',
  8366. 'updated_at' => now(),
  8367. ]);
  8368. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8369. 'product_id' => $product->id,
  8370. 'task_id' => $task_id,
  8371. ]);
  8372. }
  8373. } catch (\Exception $e) {
  8374. dLog('anime')->error('创建资产图片生成任务失败', [
  8375. 'product_id' => $product->id,
  8376. 'error' => $e->getMessage(),
  8377. ]);
  8378. DB::table('mp_products')
  8379. ->where('id', $product->id)
  8380. ->update([
  8381. 'pic_task_status' => '生成失败',
  8382. 'updated_at' => now(),
  8383. ]);
  8384. }
  8385. }
  8386. DB::commit();
  8387. } catch (\Exception $e) {
  8388. DB::rollback();
  8389. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8390. 'script_id' => $script_id,
  8391. 'error' => $e->getMessage(),
  8392. ]);
  8393. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8394. }
  8395. }
  8396. return [
  8397. 'product_task_map' => $productTaskMap,
  8398. 'type_folder_ids' => $typeFolderIds,
  8399. 'has_all_tasks' => $hasAllTasks,
  8400. 'product_count' => count($productIds),
  8401. 'created_count' => $createdCount,
  8402. ];
  8403. }
  8404. /**
  8405. * 保存剧本资产关联关系
  8406. * @param array $data 请求参数
  8407. * @return bool
  8408. */
  8409. public function saveScriptProducts($data) {
  8410. $uid = Site::getUid();
  8411. $cpid = Site::getCpid();
  8412. $script_id = getProp($data, 'script_id');
  8413. $products = getProp($data, 'products', []);
  8414. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  8415. if (!$script_id) {
  8416. Utils::throwError('20003:请提供剧本ID');
  8417. }
  8418. // 验证剧本是否存在
  8419. $script = DB::table('mp_scripts')
  8420. ->where('id', $script_id)
  8421. ->where('is_deleted', 0)
  8422. ->first();
  8423. if (!$script) {
  8424. Utils::throwError('20003:剧本不存在');
  8425. }
  8426. // 处理图片模型
  8427. $model = getProp($data, 'model');
  8428. if (!$model) {
  8429. // 使用默认模型
  8430. $model = 'gpt-image-2';
  8431. }
  8432. // 验证模型是否在可用模型表中
  8433. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8434. Utils::throwError('20003:该模型已不可用,请更换!');
  8435. }
  8436. $ratio = getProp($data, 'ratio', '9:16');
  8437. $resolution = getProp($data, 'resolution', '2k');
  8438. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  8439. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  8440. // 参数验证
  8441. $resolution = strtolower($resolution);
  8442. if (!isset($sizeMap[$resolution])) {
  8443. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  8444. }
  8445. if (!isset($sizeMap[$resolution][$ratio])) {
  8446. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  8447. }
  8448. // 根据 ratio 和 resolution 确定宽高
  8449. $width = $sizeMap[$resolution][$ratio]['width'];
  8450. $height = $sizeMap[$resolution][$ratio]['height'];
  8451. $script_name = $script->script_name ?? 'script_' . $script_id;
  8452. // 先校验并提取本次入参中的新增资产行:
  8453. // 新增行的参考提示词为空时直接报错,不写任何数据、不创建任务中心记录
  8454. $newRows = $this->extractNewScriptProductRows($script_id, $products);
  8455. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  8456. $taskCenterId = $this->createScriptProductTaskCenter(
  8457. $uid,
  8458. $cpid,
  8459. $script_id,
  8460. $products,
  8461. $model,
  8462. $ratio,
  8463. $resolution,
  8464. $auto_generate_images
  8465. );
  8466. // 检查是否已经有该剧本的资产数据
  8467. $existingMappings = DB::table('mp_script_product_mappings')
  8468. ->where('script_id', $script_id)
  8469. ->get();
  8470. // 已有资产且本次没有新增行时,走原有的"已存在"处理;否则走下方创建逻辑
  8471. if ($existingMappings->isNotEmpty() && empty($newRows)) {
  8472. // 已存在资产映射,检查是否所有资产都有图片生成任务
  8473. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8474. // 查询这些资产的图片生成任务状态
  8475. $productsWithTasks = DB::table('mp_products')
  8476. ->whereIn('id', $productIds)
  8477. ->where('is_deleted', 0)
  8478. ->get();
  8479. $productTaskMap = [];
  8480. $typeFolderIds = [];
  8481. $hasAllTasks = true;
  8482. foreach ($productsWithTasks as $product) {
  8483. // 收集类型文件夹ID
  8484. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8485. $parentFolder = DB::table('mp_products')
  8486. ->where('id', $product->parent_id)
  8487. ->where('type', 2)
  8488. ->first();
  8489. if ($parentFolder) {
  8490. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8491. }
  8492. }
  8493. // 检查是否有图片生成任务
  8494. if (!empty($product->pic_task_id)) {
  8495. $productTaskMap[$product->id] = $product->pic_task_id;
  8496. } else if($product->url && $product->pic_task_status == '生成成功') {
  8497. continue;
  8498. } else {
  8499. // 有资产没有图片任务
  8500. $hasAllTasks = false;
  8501. }
  8502. }
  8503. // 如果所有资产都有任务ID,直接轮询返回结果
  8504. if ($hasAllTasks && !empty($productTaskMap)) {
  8505. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  8506. 'script_id' => $script_id,
  8507. 'script_name' => $script_name,
  8508. 'product_count' => count($productTaskMap)
  8509. ]);
  8510. // 直接返回 SSE 流轮询结果
  8511. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8512. }
  8513. // 如果部分资产没有任务ID,只为这些资产创建任务
  8514. if (!$hasAllTasks && $auto_generate_images) {
  8515. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  8516. 'script_id' => $script_id,
  8517. 'script_name' => $script_name
  8518. ]);
  8519. // 开启事务
  8520. DB::beginTransaction();
  8521. try {
  8522. foreach ($productsWithTasks as $product) {
  8523. // 跳过已有任务的资产
  8524. if (!empty($product->pic_task_id)) {
  8525. continue;
  8526. }
  8527. // 跳过没有提示词的资产
  8528. if (empty($product->pic_prompt)) {
  8529. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8530. 'product_id' => $product->id,
  8531. 'product_name' => $product->product_name
  8532. ]);
  8533. continue;
  8534. }
  8535. try {
  8536. // 创建图片生成任务
  8537. $params = [
  8538. 'prompt' => $product->pic_prompt,
  8539. 'model' => $model,
  8540. 'ref_img_urls' => [],
  8541. 'width' => $width,
  8542. 'height' => $height,
  8543. // 计费锚点(剧本),用于积分明细归属统计
  8544. 'script_id' => $script_id,
  8545. ];
  8546. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8547. $task_id = $task->id;
  8548. if ($task_id) {
  8549. $productTaskMap[$product->id] = $task_id;
  8550. // 在事务中更新资产表的任务ID和状态
  8551. DB::table('mp_products')
  8552. ->where('id', $product->id)
  8553. ->update([
  8554. 'pic_task_id' => $task_id,
  8555. 'pic_task_status' => '生成中',
  8556. 'updated_at' => now()
  8557. ]);
  8558. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8559. 'product_id' => $product->id,
  8560. 'task_id' => $task_id
  8561. ]);
  8562. }
  8563. } catch (\Exception $e) {
  8564. dLog('anime')->error('创建资产图片生成任务失败', [
  8565. 'product_id' => $product->id,
  8566. 'error' => $e->getMessage()
  8567. ]);
  8568. // 标记为失败(仍在事务中)
  8569. DB::table('mp_products')
  8570. ->where('id', $product->id)
  8571. ->update([
  8572. 'pic_task_status' => '生成失败',
  8573. 'updated_at' => now()
  8574. ]);
  8575. }
  8576. }
  8577. // 提交事务
  8578. DB::commit();
  8579. // 如果有新创建的任务,返回 SSE 流
  8580. if (!empty($productTaskMap)) {
  8581. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8582. }
  8583. } catch (\Exception $e) {
  8584. // 回滚事务
  8585. DB::rollback();
  8586. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8587. 'script_id' => $script_id,
  8588. 'error' => $e->getMessage()
  8589. ]);
  8590. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8591. }
  8592. }
  8593. // 如果不需要生成图片,返回已存在的信息
  8594. $resultData = [
  8595. 'success' => true,
  8596. 'message' => '剧本资产已存在',
  8597. 'script_id' => $script_id,
  8598. 'script_name' => $script_name,
  8599. 'type_folder_ids' => $typeFolderIds,
  8600. 'existing_products' => count($productIds),
  8601. 'tasks_count' => count($productTaskMap),
  8602. 'task_center_id' => $taskCenterId
  8603. ];
  8604. // 接口已正常完成,更新任务中心状态和结果
  8605. if ($taskCenterId) {
  8606. $this->taskCenterService->updateTask($taskCenterId, [
  8607. 'status' => MpTaskCenter::STATUS_SUCCESS,
  8608. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  8609. 'error_message' => null
  8610. ]);
  8611. }
  8612. return $resultData;
  8613. }
  8614. // 走到这里说明有新行需要创建(或剧本还没有任何资产),保留原有的入参校验报错
  8615. if (empty($newRows)) {
  8616. $decodedProducts = $products;
  8617. if (is_string($decodedProducts)) {
  8618. $decodedProducts = json_decode($decodedProducts, true);
  8619. if (json_last_error() !== JSON_ERROR_NONE) {
  8620. Utils::throwError('20003:产品数据格式错误');
  8621. }
  8622. }
  8623. if (!is_array($decodedProducts) || empty($decodedProducts)) {
  8624. Utils::throwError('20003:产品数据不能为空');
  8625. }
  8626. Utils::throwError('20003:没有有效的产品数据');
  8627. }
  8628. // 仅保留本次新增的资产行,复用下方原有的创建逻辑
  8629. $products = [];
  8630. foreach ($newRows as $newRow) {
  8631. if (!isset($products[$newRow['type']])) {
  8632. $products[$newRow['type']] = [
  8633. 'type' => $newRow['type'],
  8634. 'content' => [['资产名称', '使用范围', '参考提示词']],
  8635. ];
  8636. }
  8637. $products[$newRow['type']]['content'][] = [
  8638. $newRow['product_name'],
  8639. implode(',', $newRow['episode_numbers']),
  8640. $newRow['pic_prompt'],
  8641. ];
  8642. }
  8643. $products = array_values($products);
  8644. // 以下是原有的创建逻辑...
  8645. // 开启事务
  8646. DB::beginTransaction();
  8647. try {
  8648. $now = now();
  8649. $mappingRecords = [];
  8650. $createdProductIds = []; // 记录所有创建的资产ID
  8651. // 获取剧本名称
  8652. $script_name = $script->script_name ?? 'script_' . $script_id;
  8653. // 存储每个类型的根文件夹ID
  8654. $typeFolderIds = [];
  8655. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  8656. foreach ($products as $productGroup) {
  8657. $type = getProp($productGroup, 'type');
  8658. $title = getProp($productGroup, 'title', '');
  8659. $content = getProp($productGroup, 'content', []);
  8660. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8661. continue;
  8662. }
  8663. // 为当前类型获取根文件夹:该剧本已存在则复用,避免重复创建根文件夹
  8664. if (!isset($typeFolderIds[$type])) {
  8665. $folder = DB::table('mp_products')
  8666. ->where('cpid', $cpid)
  8667. ->where('type', 2)
  8668. ->where('product', $type)
  8669. ->where('product_name', $script_name)
  8670. ->where('parent_id', 0)
  8671. ->where('is_deleted', 0)
  8672. ->first();
  8673. if ($folder) {
  8674. $typeFolderIds[$type] = $folder->id;
  8675. } else {
  8676. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  8677. 'user_id' => $uid,
  8678. 'cpid' => $cpid,
  8679. 'type' => 2, // 1.资产 2文件夹
  8680. 'product' => $type, // 1.主体 2.场景 3.道具
  8681. 'parent_id' => 0, // 根文件夹,parent_id=0
  8682. 'level' => 1, // 第一层级
  8683. 'product_name' => $script_name,
  8684. 'sort_order' => time() + $type,
  8685. 'is_deleted' => 0,
  8686. 'created_at' => $now,
  8687. 'updated_at' => $now
  8688. ]);
  8689. }
  8690. }
  8691. $folder_id = $typeFolderIds[$type];
  8692. // 获取表头(第一行)并查找关键列的位置
  8693. $headers = $content[0];
  8694. $nameColumnIndex = -1; // 资产名称列索引
  8695. $sequenceColumnIndex = -1; // 使用范围列索引
  8696. $promptColumnIndex = -1; // 参考提示词列索引
  8697. foreach ($headers as $index => $header) {
  8698. // 查找"资产名称"列
  8699. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8700. $nameColumnIndex = $index;
  8701. }
  8702. // 查找"使用范围"列
  8703. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8704. $sequenceColumnIndex = $index;
  8705. }
  8706. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  8707. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8708. $promptColumnIndex = $index;
  8709. }
  8710. }
  8711. // 验证必要的列是否都找到了
  8712. if ($nameColumnIndex === -1) {
  8713. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  8714. continue;
  8715. }
  8716. if ($sequenceColumnIndex === -1) {
  8717. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  8718. continue;
  8719. }
  8720. // 跳过表头,解析每一行数据
  8721. for ($i = 1; $i < count($content); $i++) {
  8722. $row = $content[$i];
  8723. // 确保行数据有效
  8724. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  8725. continue;
  8726. }
  8727. // 根据动态查找的列索引提取数据
  8728. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  8729. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  8730. $pic_prompt = '';
  8731. // 提取参考提示词(如果找到了该列)
  8732. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8733. $pic_prompt = trim($row[$promptColumnIndex]);
  8734. }
  8735. // 解析使用范围(逗号分隔的序号)
  8736. $sequences = [];
  8737. if (!empty($sequence_str)) {
  8738. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  8739. foreach ($sequenceParts as $part) {
  8740. if (is_numeric($part)) {
  8741. $sequences[] = (int)$part;
  8742. }
  8743. }
  8744. }
  8745. if (empty($product_name)) {
  8746. continue;
  8747. }
  8748. // 处理product_name两边的符号
  8749. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8750. // 如果名称不存在或仅剩占位符号,则跳过
  8751. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  8752. dLog('anime')->warning('资产名称无效,跳过保存', [
  8753. 'script_id' => $script_id,
  8754. 'type' => $type,
  8755. 'product_name' => $product_name
  8756. ]);
  8757. continue;
  8758. }
  8759. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  8760. $product_id = DB::table('mp_products')->insertGetId([
  8761. 'product_name' => $product_name,
  8762. 'type' => 1, // 1=资产 2.文件夹
  8763. 'product' => $type, // 1=角色, 2=场景, 3=道具
  8764. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  8765. 'level' => 2, // 第二层级
  8766. 'pic_prompt' => $pic_prompt,
  8767. 'user_id' => $uid,
  8768. 'cpid' => $cpid,
  8769. 'sort_order' => time(),
  8770. 'is_deleted' => 0,
  8771. 'created_at' => $now,
  8772. 'updated_at' => $now,
  8773. ]);
  8774. // 记录创建的资产ID
  8775. $createdProductIds[] = $product_id;
  8776. // 为每个序号创建映射记录
  8777. if (!empty($sequences)) {
  8778. foreach ($sequences as $sequence) {
  8779. $mappingRecords[] = [
  8780. 'script_id' => $script_id,
  8781. 'product_id' => $product_id,
  8782. 'episode_number' => $sequence,
  8783. 'created_at' => $now,
  8784. 'updated_at' => $now,
  8785. ];
  8786. }
  8787. } else {
  8788. // 如果没有指定序号,创建一个默认映射(序号为0)
  8789. $mappingRecords[] = [
  8790. 'script_id' => $script_id,
  8791. 'product_id' => $product_id,
  8792. 'episode_number' => 0,
  8793. 'created_at' => $now,
  8794. 'updated_at' => $now,
  8795. ];
  8796. }
  8797. }
  8798. }
  8799. if (empty($mappingRecords)) {
  8800. Utils::throwError('20003:没有有效的产品数据');
  8801. }
  8802. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  8803. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  8804. // 剧本已有资产,同步更新is_products标记
  8805. DB::table('mp_scripts')->where('id', $script_id)->update([
  8806. 'is_products' => 1,
  8807. 'updated_at' => $now
  8808. ]);
  8809. // 如果需要自动生成图片,在事务中创建图片生成任务
  8810. $productTaskMap = [];
  8811. if ($auto_generate_images && !empty($createdProductIds)) {
  8812. // 查询所有创建的资产
  8813. $productsToGenerate = DB::table('mp_products')
  8814. ->whereIn('id', $createdProductIds)
  8815. ->where('is_deleted', 0)
  8816. ->get();
  8817. foreach ($productsToGenerate as $product) {
  8818. if (empty($product->pic_prompt)) {
  8819. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8820. 'product_id' => $product->id,
  8821. 'product_name' => $product->product_name
  8822. ]);
  8823. continue;
  8824. }
  8825. try {
  8826. // 创建图片生成任务
  8827. $params = [
  8828. 'prompt' => $product->pic_prompt,
  8829. 'model' => $model,
  8830. 'ref_img_urls' => [],
  8831. 'width' => $width,
  8832. 'height' => $height,
  8833. // 计费锚点(剧本),用于积分明细归属统计
  8834. 'script_id' => $script_id,
  8835. ];
  8836. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8837. $task_id = $task->id;
  8838. if ($task_id) {
  8839. $productTaskMap[$product->id] = $task_id;
  8840. // 在事务中更新资产表的任务ID和状态
  8841. DB::table('mp_products')
  8842. ->where('id', $product->id)
  8843. ->update([
  8844. 'pic_task_id' => $task_id,
  8845. 'pic_task_status' => '生成中',
  8846. 'updated_at' => now()
  8847. ]);
  8848. dLog('anime')->info('创建资产图片生成任务', [
  8849. 'product_id' => $product->id,
  8850. 'task_id' => $task_id
  8851. ]);
  8852. }
  8853. } catch (\Exception $e) {
  8854. dLog('anime')->error('创建资产图片生成任务失败', [
  8855. 'product_id' => $product->id,
  8856. 'error' => $e->getMessage()
  8857. ]);
  8858. // 标记为失败(仍在事务中)
  8859. DB::table('mp_products')
  8860. ->where('id', $product->id)
  8861. ->update([
  8862. 'pic_task_status' => '生成失败',
  8863. 'updated_at' => now()
  8864. ]);
  8865. }
  8866. }
  8867. }
  8868. // 提交事务
  8869. DB::commit();
  8870. // 本次新增资产创建的图片任务
  8871. $createdTaskMap = $productTaskMap;
  8872. } catch (\Exception $e) {
  8873. // 回滚事务
  8874. DB::rollback();
  8875. // 更新任务中心状态为失败
  8876. if (!empty($taskCenterId)) {
  8877. $this->taskCenterService->updateTask($taskCenterId, [
  8878. 'status' => MpTaskCenter::STATUS_FAILED,
  8879. 'error_message' => $e->getMessage()
  8880. ]);
  8881. }
  8882. // 记录错误日志
  8883. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  8884. 'script_id' => $script_id,
  8885. 'error' => $e->getMessage(),
  8886. 'trace' => $e->getTraceAsString()
  8887. ]);
  8888. // 统一使用 Utils::throwError 抛出错误
  8889. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  8890. }
  8891. // 落库成功后统一处理图片任务:
  8892. // 1) 本次新增资产的图片任务已在上方事务中创建
  8893. // 2) 剧本内已存在但缺图的资产在此补建,并与新增资产的任务一并收集为待轮询任务
  8894. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  8895. $script_id,
  8896. $model,
  8897. $width,
  8898. $height,
  8899. $auto_generate_images
  8900. );
  8901. $productTaskMap = $existingTaskInfo['product_task_map'];
  8902. // 创建阶段解析到的类型根文件夹优先
  8903. $typeFolderIds = $typeFolderIds + $existingTaskInfo['type_folder_ids'];
  8904. // 保存结果(SSE 的 init / complete 事件会携带该结构)
  8905. $resultData = [
  8906. 'success' => true,
  8907. 'message' => '保存完成',
  8908. 'script_id' => $script_id,
  8909. 'script_name' => $script_name,
  8910. 'type_folder_ids' => $typeFolderIds,
  8911. 'inserted_count' => $insertedCount,
  8912. 'total_records' => count($mappingRecords),
  8913. 'created_products' => count($createdProductIds),
  8914. 'pending_tasks_count' => count($productTaskMap),
  8915. 'image_tasks_created' => count($createdTaskMap) + $existingTaskInfo['created_count'],
  8916. 'task_center_id' => $taskCenterId,
  8917. ];
  8918. // 有待完成的图片任务:返回 SSE 轮询流(事务外轮询)
  8919. if ($auto_generate_images && !empty($productTaskMap)) {
  8920. return $this->pollProductImageTasks(
  8921. $script_id,
  8922. $script_name,
  8923. $productTaskMap,
  8924. $typeFolderIds,
  8925. $taskCenterId,
  8926. ['import_result' => $resultData],
  8927. ['import_result' => $resultData]
  8928. );
  8929. }
  8930. // 没有需要轮询的任务:通过 SSE complete 事件返回保存结果
  8931. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  8932. }
  8933. /**
  8934. * 根据入参创建或复用任务中心记录
  8935. *
  8936. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  8937. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  8938. * 避免生成重复任务。
  8939. *
  8940. * @param int|string $uid
  8941. * @param int|string $cpid
  8942. * @param int|string $script_id
  8943. * @param mixed $products
  8944. * @param string $model
  8945. * @param string $ratio
  8946. * @param string $resolution
  8947. * @param mixed $auto_generate_images
  8948. * @return int 任务中心ID
  8949. */
  8950. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  8951. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  8952. if (is_string($products)) {
  8953. $decoded = json_decode($products, true);
  8954. if (json_last_error() === JSON_ERROR_NONE) {
  8955. $products = $decoded;
  8956. }
  8957. }
  8958. $params = [
  8959. 'script_id' => (int)$script_id,
  8960. 'products' => $products,
  8961. 'model' => $model,
  8962. 'ratio' => $ratio,
  8963. 'resolution' => $resolution,
  8964. 'auto_generate_images' => (bool)$auto_generate_images,
  8965. ];
  8966. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  8967. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  8968. $existing = DB::table('mp_task_center')
  8969. ->where('uid', (int)$uid)
  8970. ->where('cpid', (int)$cpid)
  8971. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8972. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  8973. ->where('params_md5', $paramsMd5)
  8974. ->orderBy('id', 'desc')
  8975. ->first();
  8976. if ($existing) {
  8977. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  8978. 'script_id' => $script_id,
  8979. 'task_center_id' => $existing->id,
  8980. 'params_md5' => $paramsMd5,
  8981. ]);
  8982. return (int)$existing->id;
  8983. }
  8984. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  8985. $now = date('Y-m-d H:i:s');
  8986. DB::table('mp_task_center')->insertOrIgnore([
  8987. 'uid' => (int)$uid,
  8988. 'cpid' => (int)$cpid,
  8989. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  8990. 'title' => '剧本资产图片生成',
  8991. 'ref_task_id' => 0,
  8992. 'status' => MpTaskCenter::STATUS_PROCESSING,
  8993. 'result' => null,
  8994. 'error_message' => null,
  8995. 'prompt' => null,
  8996. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  8997. 'params_md5' => $paramsMd5,
  8998. 'created_at' => $now,
  8999. 'updated_at' => $now,
  9000. ]);
  9001. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  9002. $taskId = (int)DB::table('mp_task_center')
  9003. ->where('uid', (int)$uid)
  9004. ->where('cpid', (int)$cpid)
  9005. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9006. ->where('params_md5', $paramsMd5)
  9007. ->orderBy('id', 'desc')
  9008. ->value('id');
  9009. dLog('anime')->info('创建任务中心记录', [
  9010. 'script_id' => $script_id,
  9011. 'task_center_id' => $taskId,
  9012. 'params_md5' => $paramsMd5,
  9013. ]);
  9014. return $taskId;
  9015. }
  9016. /**
  9017. * 任务结束时更新任务中心记录的状态和结果
  9018. *
  9019. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  9020. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  9021. *
  9022. * @param int|null $taskCenterId
  9023. * @param array $resultData 接口返回结果数组
  9024. * @param bool $timeout 是否超时未完成
  9025. */
  9026. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  9027. if (!$taskCenterId) {
  9028. return;
  9029. }
  9030. $stats = $resultData['stats'] ?? [];
  9031. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  9032. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  9033. $failedCount = $completedCount - $successCount;
  9034. // 与接口返回给客户端的结果保持一致
  9035. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  9036. if ($timeout) {
  9037. $this->taskCenterService->updateTask((int)$taskCenterId, [
  9038. 'status' => MpTaskCenter::STATUS_FAILED,
  9039. 'result' => $result,
  9040. 'error_message' => '部分任务超时,请稍后查看结果',
  9041. ]);
  9042. return;
  9043. }
  9044. $this->taskCenterService->updateTask((int)$taskCenterId, [
  9045. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  9046. 'result' => $result,
  9047. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  9048. ]);
  9049. }
  9050. /**
  9051. * 批量为剧本资产生成图片
  9052. *
  9053. * @param array $data 请求参数
  9054. * @return \Generator 返回 SSE 流
  9055. */
  9056. public function batchGenerateProductImages($data) {
  9057. $script_id = getProp($data, 'script_id');
  9058. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  9059. if (!$script_id) {
  9060. Utils::throwError('20003:请提供剧本ID');
  9061. }
  9062. // 验证剧本是否存在
  9063. $script = DB::table('mp_scripts')
  9064. ->where('id', $script_id)
  9065. ->where('is_deleted', 0)
  9066. ->first();
  9067. if (!$script) {
  9068. Utils::throwError('20003:剧本不存在');
  9069. }
  9070. $script_name = $script->script_name ?? 'script_' . $script_id;
  9071. // 获取需要生成图片的所有资产
  9072. $products = DB::table('mp_products')
  9073. ->whereIn('parent_id', array_values($type_folder_ids))
  9074. ->where('is_deleted', 0)
  9075. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  9076. ->get();
  9077. if ($products->isEmpty()) {
  9078. Utils::throwError('20003:没有找到需要生成图片的资产');
  9079. }
  9080. // 默认参数
  9081. $model = 'gpt-image-2';
  9082. $width = 1600;
  9083. $height = 2848;
  9084. // 开始为每个资产创建图片生成任务
  9085. $taskIds = [];
  9086. $productTaskMap = []; // 资产ID到任务ID的映射
  9087. foreach ($products as $product) {
  9088. if (empty($product->pic_prompt)) {
  9089. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  9090. continue;
  9091. }
  9092. try {
  9093. // 创建图片生成任务
  9094. $params = [
  9095. 'prompt' => $product->pic_prompt,
  9096. 'model' => $model,
  9097. 'ref_img_urls' => [],
  9098. 'width' => $width,
  9099. 'height' => $height,
  9100. // 计费锚点(剧本),用于积分明细归属统计
  9101. 'script_id' => $script_id,
  9102. ];
  9103. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9104. $task_id = $task->id;
  9105. if ($task_id) {
  9106. $taskIds[] = $task_id;
  9107. $productTaskMap[$product->id] = $task_id;
  9108. // 更新资产表的任务ID和状态
  9109. DB::table('mp_products')
  9110. ->where('id', $product->id)
  9111. ->update([
  9112. 'pic_task_id' => $task_id,
  9113. 'pic_task_status' => '生成中',
  9114. 'updated_at' => now()
  9115. ]);
  9116. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  9117. }
  9118. } catch (\Exception $e) {
  9119. dLog('anime')->error('创建资产图片生成任务失败', [
  9120. 'product_id' => $product->id,
  9121. 'error' => $e->getMessage()
  9122. ]);
  9123. // 标记为失败
  9124. DB::table('mp_products')
  9125. ->where('id', $product->id)
  9126. ->update([
  9127. 'pic_task_status' => '生成失败',
  9128. 'updated_at' => now()
  9129. ]);
  9130. }
  9131. }
  9132. if (empty($taskIds)) {
  9133. Utils::throwError('20003:没有成功创建任何图片生成任务');
  9134. }
  9135. // 返回 SSE 流
  9136. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  9137. }
  9138. /**
  9139. * 无需轮询时的 SSE 返回:直接通过 complete 事件返回导入结果
  9140. *
  9141. * @param int $script_id
  9142. * @param string $script_name
  9143. * @param array $resultData 导入结果(原普通 JSON 的 data 内容)
  9144. * @param array $type_folder_ids
  9145. * @param int|null $taskCenterId
  9146. * @return \Generator
  9147. */
  9148. private function streamImportComplete($script_id, $script_name, array $resultData, $type_folder_ids, $taskCenterId = null) {
  9149. if ($taskCenterId) {
  9150. $initResponse = [
  9151. 'type' => 'init',
  9152. 'script_id' => $script_id,
  9153. 'script_name' => $script_name,
  9154. 'timestamp' => date('Y-m-d H:i:s'),
  9155. 'task_center_id' => (int)$taskCenterId,
  9156. 'import_result' => $resultData,
  9157. ];
  9158. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9159. }
  9160. $stats = $this->collectScriptProductStats($script_id);
  9161. $response = [
  9162. 'type' => 'complete',
  9163. 'script_id' => $script_id,
  9164. 'script_name' => $script_name,
  9165. 'stats' => $stats,
  9166. 'timestamp' => date('Y-m-d H:i:s'),
  9167. 'import_result' => $resultData,
  9168. ];
  9169. if ($taskCenterId) {
  9170. $response['task_center_id'] = (int)$taskCenterId;
  9171. }
  9172. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9173. // 更新任务中心状态和结果
  9174. $this->finishScriptProductTask($taskCenterId, $response);
  9175. }
  9176. /**
  9177. * 统计剧本资产的图片生成状态(仅按 mp_products 当前状态统计,不驱动任务)
  9178. *
  9179. * @param int $script_id
  9180. * @return array
  9181. */
  9182. private function collectScriptProductStats($script_id) {
  9183. $stats = [
  9184. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9185. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9186. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9187. ];
  9188. $typeNames = [1 => 'roles', 2 => 'scenes', 3 => 'props'];
  9189. $productIds = DB::table('mp_script_product_mappings')
  9190. ->where('script_id', $script_id)
  9191. ->pluck('product_id')
  9192. ->unique()
  9193. ->toArray();
  9194. if (empty($productIds)) {
  9195. return [];
  9196. }
  9197. $products = DB::table('mp_products')
  9198. ->whereIn('id', $productIds)
  9199. ->where('is_deleted', 0)
  9200. ->get();
  9201. foreach ($products as $product) {
  9202. $typeName = $typeNames[$product->product] ?? 'unknown';
  9203. if (!isset($stats[$typeName])) {
  9204. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9205. }
  9206. $stats[$typeName]['total']++;
  9207. if ($product->pic_task_status === '生成成功') {
  9208. $stats[$typeName]['success']++;
  9209. $stats[$typeName]['completed']++;
  9210. } elseif ($product->pic_task_status === '生成失败') {
  9211. $stats[$typeName]['completed']++;
  9212. }
  9213. }
  9214. foreach ($stats as $typeName => $stat) {
  9215. if ($stat['total'] === 0) {
  9216. unset($stats[$typeName]);
  9217. }
  9218. }
  9219. return $stats;
  9220. }
  9221. /**
  9222. * 轮询资产图片生成任务状态(SSE流式返回)
  9223. * 只通过查询数据库获取任务状态,不主动调用API
  9224. *
  9225. * @param int $script_id 剧本ID
  9226. * @param string $script_name 剧本名称
  9227. * @param array $productTaskMap 资产ID到任务ID的映射
  9228. * @param array $type_folder_ids 类型文件夹ID映射
  9229. * @param int|null $taskCenterId 任务中心ID
  9230. * @param array $initExtra 追加到 init 事件中的额外数据
  9231. * @param array $completeExtra 追加到 complete、timeout 事件中的额外数据
  9232. * @return \Generator
  9233. */
  9234. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null, array $initExtra = [], array $completeExtra = []) {
  9235. $startTime = time();
  9236. $timeout = 1800; // 30分钟超时
  9237. $pollInterval = 10; // 10秒轮询一次
  9238. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  9239. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  9240. if ($taskCenterId) {
  9241. $initResponse = array_merge([
  9242. 'type' => 'init',
  9243. 'script_id' => $script_id,
  9244. 'script_name' => $script_name,
  9245. 'timestamp' => date('Y-m-d H:i:s'),
  9246. 'task_center_id' => (int)$taskCenterId,
  9247. ], $initExtra);
  9248. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9249. }
  9250. // 定义类型名称映射
  9251. $typeNames = [
  9252. 1 => 'roles', // 角色
  9253. 2 => 'scenes', // 场景
  9254. 3 => 'props' // 道具
  9255. ];
  9256. while (time() - $startTime < $timeout) {
  9257. sleep($pollInterval);
  9258. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  9259. $mappings = DB::table('mp_script_product_mappings')
  9260. ->where('script_id', $script_id)
  9261. ->pluck('product_id')
  9262. ->unique()
  9263. ->toArray();
  9264. if (empty($mappings)) {
  9265. dLog('anime')->warning('该剧本没有关联的资产', [
  9266. 'script_id' => $script_id,
  9267. 'script_name' => $script_name
  9268. ]);
  9269. break;
  9270. }
  9271. // 查询所有资产的当前状态
  9272. $products = DB::table('mp_products')
  9273. ->whereIn('id', $mappings)
  9274. ->where('is_deleted', 0)
  9275. ->get();
  9276. // 统计各类型的状态(使用类型名称作为键名)
  9277. $stats = [
  9278. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  9279. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  9280. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  9281. ];
  9282. $allCompleted = true;
  9283. $hasStatusChange = false;
  9284. foreach ($products as $product) {
  9285. $type = $product->product;
  9286. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  9287. // 如果类型名称不在 stats 中,初始化
  9288. if (!isset($stats[$typeName])) {
  9289. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9290. }
  9291. $stats[$typeName]['total']++;
  9292. $task_id = $product->pic_task_id;
  9293. $currentStatus = $product->pic_task_status;
  9294. // 检查状态是否有变化
  9295. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  9296. $hasStatusChange = true;
  9297. $lastStatus[$product->id] = $currentStatus;
  9298. }
  9299. // 如果是生成中,查询任务表状态
  9300. if ($currentStatus === '生成中' && $task_id) {
  9301. // 只查询数据库,不调用API
  9302. $task = DB::table('mp_generate_pic_tasks')
  9303. ->where('id', $task_id)
  9304. ->first();
  9305. if ($task) {
  9306. // 检查任务状态
  9307. if ($task->status === 'success' && $task->result_url) {
  9308. // 解析图片URL
  9309. $result_urls = $task->result_url;
  9310. if (is_string($result_urls)) {
  9311. $result_urls = json_decode($result_urls, true);
  9312. }
  9313. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  9314. // 更新资产表状态
  9315. DB::table('mp_products')
  9316. ->where('id', $product->id)
  9317. ->update([
  9318. 'pic_task_status' => '生成成功',
  9319. 'url' => $img_url,
  9320. 'updated_at' => now()
  9321. ]);
  9322. $stats[$typeName]['success']++;
  9323. $stats[$typeName]['completed']++;
  9324. $hasStatusChange = true;
  9325. dLog('anime')->info('资产图片生成成功', [
  9326. 'product_id' => $product->id,
  9327. 'task_id' => $task_id,
  9328. 'img_url' => $img_url
  9329. ]);
  9330. } elseif ($task->status === 'failed') {
  9331. // 更新资产表状态
  9332. DB::table('mp_products')
  9333. ->where('id', $product->id)
  9334. ->update([
  9335. 'pic_task_status' => '生成失败',
  9336. 'updated_at' => now()
  9337. ]);
  9338. $stats[$typeName]['completed']++;
  9339. $hasStatusChange = true;
  9340. dLog('anime')->warning('资产图片生成失败', [
  9341. 'product_id' => $product->id,
  9342. 'task_id' => $task_id,
  9343. 'error' => $task->error_message ?? '未知错误'
  9344. ]);
  9345. } else {
  9346. // 任务还在处理中
  9347. $allCompleted = false;
  9348. }
  9349. } else {
  9350. // 任务不存在,标记为失败
  9351. DB::table('mp_products')
  9352. ->where('id', $product->id)
  9353. ->update([
  9354. 'pic_task_status' => '生成失败',
  9355. 'updated_at' => now()
  9356. ]);
  9357. $stats[$typeName]['completed']++;
  9358. $hasStatusChange = true;
  9359. dLog('anime')->error('图片生成任务不存在', [
  9360. 'product_id' => $product->id,
  9361. 'task_id' => $task_id
  9362. ]);
  9363. }
  9364. } elseif ($currentStatus === '生成成功') {
  9365. $stats[$typeName]['success']++;
  9366. $stats[$typeName]['completed']++;
  9367. } elseif ($currentStatus === '生成失败') {
  9368. $stats[$typeName]['completed']++;
  9369. } else {
  9370. // 其他状态也认为未完成
  9371. $allCompleted = false;
  9372. }
  9373. }
  9374. // 移除没有数据的类型(total=0)
  9375. foreach ($stats as $typeName => $stat) {
  9376. if ($stat['total'] === 0) {
  9377. unset($stats[$typeName]);
  9378. }
  9379. }
  9380. // 如果有状态变化,发送 SSE 更新
  9381. if ($hasStatusChange) {
  9382. $eventType = $allCompleted ? 'complete' : 'update';
  9383. $response = [
  9384. 'type' => $eventType,
  9385. 'script_id' => $script_id,
  9386. 'script_name' => $script_name,
  9387. 'stats' => $stats,
  9388. 'timestamp' => date('Y-m-d H:i:s')
  9389. ];
  9390. if ($taskCenterId) {
  9391. $response['task_center_id'] = $taskCenterId;
  9392. }
  9393. if ($eventType === 'complete') {
  9394. $response = array_merge($response, $completeExtra);
  9395. }
  9396. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9397. dLog('anime')->info('SSE更新', [
  9398. 'event_type' => $eventType,
  9399. 'script_id' => $script_id,
  9400. 'script_name' => $script_name,
  9401. 'stats' => $stats
  9402. ]);
  9403. if ($allCompleted) {
  9404. dLog('anime')->info('所有资产图片生成任务已完成', [
  9405. 'script_id' => $script_id,
  9406. 'script_name' => $script_name,
  9407. 'stats' => $stats
  9408. ]);
  9409. // 全部任务完成,更新任务中心状态和结果
  9410. $this->finishScriptProductTask($taskCenterId, $response);
  9411. break;
  9412. }
  9413. }
  9414. }
  9415. // 超时处理
  9416. if (time() - $startTime >= $timeout && !$allCompleted) {
  9417. $response = [
  9418. 'type' => 'timeout',
  9419. 'message' => '部分任务超时,请稍后查看结果',
  9420. 'script_id' => $script_id,
  9421. 'script_name' => $script_name,
  9422. 'timestamp' => date('Y-m-d H:i:s')
  9423. ];
  9424. if ($taskCenterId) {
  9425. $response['task_center_id'] = $taskCenterId;
  9426. }
  9427. $response = array_merge($response, $completeExtra);
  9428. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9429. dLog('anime')->warning('资产图片生成任务超时', [
  9430. 'script_id' => $script_id,
  9431. 'script_name' => $script_name,
  9432. 'timeout' => $timeout
  9433. ]);
  9434. // 超时未完成,更新任务中心状态和结果
  9435. $this->finishScriptProductTask($taskCenterId, $response, true);
  9436. }
  9437. }
  9438. /**
  9439. * 定时任务:检查产品图片生成任务状态并更新产品记录
  9440. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  9441. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  9442. *
  9443. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  9444. */
  9445. public function checkProductPicTasks() {
  9446. // 查询所有生成中的产品图片任务
  9447. $products = DB::table('mp_products')
  9448. ->whereNotNull('pic_task_id')
  9449. ->where('pic_task_status', '生成中')
  9450. ->where('is_deleted', 0)
  9451. ->get();
  9452. $stats = [
  9453. 'total' => $products->count(),
  9454. 'success' => 0,
  9455. 'failed' => 0,
  9456. 'pending' => 0,
  9457. ];
  9458. foreach ($products as $product) {
  9459. try {
  9460. $task_id = $product->pic_task_id;
  9461. // 通过 pic_task_id 查询图片生成任务结果
  9462. $task = DB::table('mp_generate_pic_tasks')
  9463. ->where('id', $task_id)
  9464. ->first();
  9465. if ($task) {
  9466. if ($task->status === 'success' && $task->result_url) {
  9467. // 解析图片URL
  9468. $result_urls = $task->result_url;
  9469. if (is_string($result_urls)) {
  9470. $result_urls = json_decode($result_urls, true);
  9471. }
  9472. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  9473. // 更新资产表状态
  9474. DB::table('mp_products')
  9475. ->where('id', $product->id)
  9476. ->update([
  9477. 'pic_task_status' => '生成成功',
  9478. 'url' => $img_url,
  9479. 'updated_at' => now()
  9480. ]);
  9481. $stats['success']++;
  9482. dLog('anime')->info('资产图片生成成功', [
  9483. 'product_id' => $product->id,
  9484. 'task_id' => $task_id,
  9485. 'img_url' => $img_url
  9486. ]);
  9487. } elseif ($task->status === 'failed') {
  9488. // 更新资产表状态
  9489. DB::table('mp_products')
  9490. ->where('id', $product->id)
  9491. ->update([
  9492. 'pic_task_status' => '生成失败',
  9493. 'updated_at' => now()
  9494. ]);
  9495. $stats['failed']++;
  9496. dLog('anime')->warning('资产图片生成失败', [
  9497. 'product_id' => $product->id,
  9498. 'task_id' => $task_id,
  9499. 'error' => $task->error_message ?? '未知错误'
  9500. ]);
  9501. } else {
  9502. // 任务还在处理中
  9503. $stats['pending']++;
  9504. }
  9505. } else {
  9506. // 任务不存在,标记为失败
  9507. DB::table('mp_products')
  9508. ->where('id', $product->id)
  9509. ->update([
  9510. 'pic_task_status' => '生成失败',
  9511. 'updated_at' => now()
  9512. ]);
  9513. $stats['failed']++;
  9514. dLog('anime')->error('图片生成任务不存在', [
  9515. 'product_id' => $product->id,
  9516. 'task_id' => $task_id
  9517. ]);
  9518. }
  9519. } catch (\Exception $e) {
  9520. dLog('anime')->error('检查产品图片生成任务异常', [
  9521. 'product_id' => $product->id,
  9522. 'task_id' => $product->pic_task_id ?? null,
  9523. 'error' => $e->getMessage()
  9524. ]);
  9525. }
  9526. }
  9527. return $stats;
  9528. }
  9529. /**
  9530. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  9531. *
  9532. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  9533. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  9534. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  9535. *
  9536. * @return int 更新的任务中心记录数
  9537. */
  9538. public function checkSaveScriptProductTaskCenters() {
  9539. $updated = 0;
  9540. // 只扫描尚未结束的 saveScriptProducts 任务
  9541. $tasks = DB::table('mp_task_center')
  9542. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9543. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  9544. ->orderBy('id', 'desc')
  9545. ->limit(500)
  9546. ->get();
  9547. // 与 pollProductImageTasks 保持一致的类型名称映射
  9548. $typeNames = [
  9549. 1 => 'roles', // 角色
  9550. 2 => 'scenes', // 场景
  9551. 3 => 'props', // 道具
  9552. ];
  9553. foreach ($tasks as $task) {
  9554. try {
  9555. $taskParams = json_decode((string)$task->params, true);
  9556. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  9557. if (!$script_id) {
  9558. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  9559. 'task_center_id' => $task->id,
  9560. ]);
  9561. continue;
  9562. }
  9563. // 获取该剧本关联的全部资产ID
  9564. $productIds = DB::table('mp_script_product_mappings')
  9565. ->where('script_id', $script_id)
  9566. ->pluck('product_id')
  9567. ->unique()
  9568. ->toArray();
  9569. if (empty($productIds)) {
  9570. // 剧本没有关联资产,不视为完成,等待下一次检查
  9571. continue;
  9572. }
  9573. $products = DB::table('mp_products')
  9574. ->whereIn('id', $productIds)
  9575. ->where('is_deleted', 0)
  9576. ->get();
  9577. $stats = [];
  9578. $allCompleted = true;
  9579. foreach ($products as $product) {
  9580. $typeName = $typeNames[$product->product] ?? 'unknown';
  9581. if (!isset($stats[$typeName])) {
  9582. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9583. }
  9584. $stats[$typeName]['total']++;
  9585. if ($product->pic_task_status === '生成成功') {
  9586. $stats[$typeName]['success']++;
  9587. $stats[$typeName]['completed']++;
  9588. } elseif ($product->pic_task_status === '生成失败') {
  9589. $stats[$typeName]['completed']++;
  9590. } else {
  9591. // 仍有资产在生成中或未生成,任务未完成
  9592. $allCompleted = false;
  9593. }
  9594. }
  9595. if (!$allCompleted) {
  9596. continue;
  9597. }
  9598. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  9599. $script = DB::table('mp_scripts')
  9600. ->where('id', $script_id)
  9601. ->where('is_deleted', 0)
  9602. ->first();
  9603. $script_name = $script->script_name ?? 'script_' . $script_id;
  9604. $this->finishScriptProductTask($task->id, [
  9605. 'type' => 'complete',
  9606. 'script_id' => $script_id,
  9607. 'script_name' => $script_name,
  9608. 'stats' => $stats,
  9609. 'timestamp' => date('Y-m-d H:i:s'),
  9610. 'task_center_id' => (int)$task->id,
  9611. ]);
  9612. $updated++;
  9613. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  9614. 'task_center_id' => $task->id,
  9615. 'script_id' => $script_id,
  9616. 'stats' => $stats,
  9617. ]);
  9618. } catch (\Exception $e) {
  9619. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  9620. 'task_center_id' => $task->id,
  9621. 'error' => $e->getMessage(),
  9622. ]);
  9623. }
  9624. }
  9625. return $updated;
  9626. }
  9627. /**
  9628. * 获取剧本关联的资产列表
  9629. * @param array $data 请求参数
  9630. * @return array
  9631. */
  9632. public function getScriptProducts($data) {
  9633. $uid = Site::getUid();
  9634. $cpid = Site::getCpid();
  9635. $script_id = getProp($data, 'script_id');
  9636. $episode_number = getProp($data, 'episode_number');
  9637. if (!$script_id) {
  9638. Utils::throwError('20003:请提供剧本ID');
  9639. }
  9640. // 验证剧本是否存在
  9641. $script = DB::table('mp_scripts')
  9642. ->where('id', $script_id)
  9643. ->where('is_deleted', 0)
  9644. ->first();
  9645. if (!$script) {
  9646. Utils::throwError('20003:剧本不存在');
  9647. }
  9648. // 联表查询资产信息
  9649. $query = DB::table('mp_script_product_mappings as mapping')
  9650. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9651. ->where('mapping.script_id', $script_id)
  9652. ->where('product.cpid', $cpid)
  9653. ->where('product.is_deleted', 0);
  9654. // 如果提供了 episode_number,则过滤指定集数
  9655. if ($episode_number !== null && $episode_number !== '') {
  9656. $query->where('mapping.episode_number', $episode_number);
  9657. }
  9658. $mappings = $query->select(
  9659. 'mapping.script_id',
  9660. 'mapping.product_id',
  9661. 'mapping.episode_number',
  9662. 'product.product_name',
  9663. 'product.type',
  9664. 'product.product',
  9665. 'product.pic_prompt',
  9666. 'product.url',
  9667. 'product.pic_task_id',
  9668. 'product.pic_task_status',
  9669. 'product.three_view_image_url',
  9670. 'product.timbre_url',
  9671. 'mapping.created_at'
  9672. )
  9673. ->orderBy('mapping.product_id', 'asc')
  9674. ->orderBy('mapping.episode_number', 'asc')
  9675. ->get();
  9676. // 按 product_id 分组,合并 episode_number
  9677. $productMap = [];
  9678. foreach ($mappings as $item) {
  9679. $product_id = $item->product_id;
  9680. if (!isset($productMap[$product_id])) {
  9681. $productMap[$product_id] = [
  9682. 'product_id' => $product_id,
  9683. 'product_name' => $item->product_name,
  9684. 'type' => (int)$item->type,
  9685. 'product' => (int)$item->product,
  9686. 'pic_prompt' => $item->pic_prompt,
  9687. 'url' => $item->url,
  9688. 'timbre_url' => $item->timbre_url,
  9689. 'pic_task_id' => $item->pic_task_id,
  9690. 'pic_task_status' => $item->pic_task_status,
  9691. 'episode_numbers' => [],
  9692. 'created_at' => $item->created_at,
  9693. ];
  9694. }
  9695. // 添加 episode_number(去重)
  9696. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  9697. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  9698. }
  9699. }
  9700. // 按类型分组
  9701. $roles = []; // type=1 角色/主体
  9702. $scenes = []; // type=2 场景
  9703. $props = []; // type=3 道具
  9704. foreach ($productMap as $product) {
  9705. // 将 episode_numbers 数组转换为逗号分隔的字符串
  9706. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  9707. // 构造返回数据
  9708. $productData = [
  9709. 'product_id' => $product['product_id'],
  9710. 'product_name' => $product['product_name'],
  9711. 'product' => $product['product'],
  9712. 'pic_prompt' => $product['pic_prompt'],
  9713. 'url' => $product['url'],
  9714. 'timbre_url' => $product['timbre_url'] ?? '',
  9715. 'pic_task_id' => $product['pic_task_id'],
  9716. 'pic_task_status' => $product['pic_task_status'],
  9717. 'episode_numbers' => $episodeNumbersStr,
  9718. 'created_at' => $product['created_at'],
  9719. ];
  9720. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  9721. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  9722. switch ($product['product']) {
  9723. case 1:
  9724. $roles[] = $productData;
  9725. break;
  9726. case 2:
  9727. $scenes[] = $productData;
  9728. break;
  9729. case 3:
  9730. $props[] = $productData;
  9731. break;
  9732. }
  9733. }
  9734. return [
  9735. 'script_id' => $script_id,
  9736. 'script_name' => $script->script_name ?? '',
  9737. 'roles' => $roles, // 主体
  9738. 'scenes' => $scenes, // 场景
  9739. 'props' => $props, // 道具
  9740. ];
  9741. }
  9742. /**
  9743. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  9744. * @param string $actContent 原始内容
  9745. * @param array $products 产品数组(包含product_name和url)
  9746. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  9747. */
  9748. /**
  9749. * 根据片段内容与资产构建提示词、参考图、参考音频
  9750. *
  9751. * @param string $actContent 片段内容
  9752. * @param array $products 资产数组(角色/场景/道具)
  9753. * @param bool $supportAudioReference 模型是否支持参考音频;支持时角色音色优先使用 timbre_url
  9754. * @return array
  9755. */
  9756. public function processActContentWithProducts($actContent, $products, $supportAudioReference = false) {
  9757. if (empty($actContent) || empty($products)) {
  9758. return [
  9759. 'content' => $actContent,
  9760. 'reference_images' => [],
  9761. 'reference_audios' => [],
  9762. 'audio_voice_fallbacks' => []
  9763. ];
  9764. }
  9765. // 构建产品名称到产品信息的映射
  9766. $product_dict = [];
  9767. foreach ($products as $product) {
  9768. $product_name = getProp($product, 'product_name');
  9769. if ($product_name) {
  9770. $product_dict[$product_name] = [
  9771. // 优先使用三视图图片作为素材/参考图,否则使用原图 url
  9772. 'url' => getProp($product, 'three_view_image_url') ?: getProp($product, 'url'),
  9773. 'voice_prompt' => getProp($product, 'voice_prompt'),
  9774. // 角色音色参考音频(选填),有值时优先于 voice_prompt
  9775. 'timbre_url' => trim((string)getProp($product, 'timbre_url', '')),
  9776. 'product' => (int)getProp($product, 'product', 1)
  9777. ];
  9778. }
  9779. }
  9780. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  9781. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  9782. $reference_images = [];
  9783. $product_index_map = []; // 产品名称 => 图片序号的映射
  9784. $reference_audios = [];
  9785. $product_audio_index_map = []; // 产品名称 => 音频序号的映射(与图片序号互相独立)
  9786. $audio_voice_fallbacks = []; // 产品名称 => voice_prompt(参考音频素材不可用时兜底使用)
  9787. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  9788. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  9789. $current_index = 1;
  9790. $current_audio_index = 1;
  9791. if (!empty($matches[1])) {
  9792. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  9793. $seen_products = []; // 用于去重
  9794. foreach ($matches[1] as $product_name) {
  9795. // 跳过已处理的产品
  9796. if (isset($seen_products[$product_name])) {
  9797. continue;
  9798. }
  9799. $seen_products[$product_name] = true;
  9800. // 检查产品是否在字典中
  9801. if (isset($product_dict[$product_name])) {
  9802. $url = $product_dict[$product_name]['url'];
  9803. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  9804. $timbre_url = $product_dict[$product_name]['timbre_url'];
  9805. // 分配音频序号(与图片序号互相独立;相同音频URL复用同一序号,保证角色与音频一一对应)
  9806. if ($supportAudioReference && !empty($timbre_url)) {
  9807. if (!in_array($timbre_url, $reference_audios)) {
  9808. $reference_audios[] = $timbre_url;
  9809. $product_audio_index_map[$product_name] = $current_audio_index;
  9810. $current_audio_index++;
  9811. } else {
  9812. $existing_audio_index = array_search($timbre_url, $reference_audios) + 1;
  9813. $product_audio_index_map[$product_name] = $existing_audio_index;
  9814. }
  9815. // 记录该角色的音色提示词:参考音频素材不可用时用它兜底(无提示词时记录空串,用于清理残留说明行)
  9816. $audio_voice_fallbacks[$product_name] = $voice_prompt ?? '';
  9817. }
  9818. // 处理voice_prompt:模型支持参考音频且角色有音频时优先使用音频,不再输出音色提示词(旁白是公共的在后面单独处理)
  9819. if ((!$supportAudioReference || empty($timbre_url)) && !empty($voice_prompt) && $product_name !== '旁白') {
  9820. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  9821. }
  9822. // 只有URL非空才分配序号和添加到参考图片
  9823. if (!empty($url)) {
  9824. // 检查URL是否已经在reference_images中(去重)
  9825. if (!in_array($url, $reference_images)) {
  9826. $reference_images[] = $url;
  9827. $product_index_map[$product_name] = $current_index;
  9828. $current_index++;
  9829. } else {
  9830. // URL重复,找到已有的序号
  9831. $existing_index = array_search($url, $reference_images) + 1;
  9832. $product_index_map[$product_name] = $existing_index;
  9833. }
  9834. } else {
  9835. // URL为空,不分配序号(后续直接去掉{})
  9836. $product_index_map[$product_name] = 0;
  9837. }
  9838. } else {
  9839. // 产品不在字典中,不分配序号
  9840. $product_index_map[$product_name] = 0;
  9841. }
  9842. }
  9843. }
  9844. // 第二步:替换内容中的 {产品名称}
  9845. $processedContent = $actContent;
  9846. foreach ($product_index_map as $product_name => $index) {
  9847. $escaped_name = preg_quote($product_name, '/');
  9848. if ($index > 0) {
  9849. // 有图片,替换为:产品名称<图片X>
  9850. $replacement = $product_name . '<图片' . $index . '>';
  9851. } else {
  9852. // 无图片,只保留产品名称
  9853. $replacement = $product_name;
  9854. }
  9855. // 有参考音频的角色追加音频标记(如 角色A<图片1><音频1>),保证角色与音频一一对应
  9856. $audio_index = $product_audio_index_map[$product_name] ?? 0;
  9857. if ($audio_index > 0) {
  9858. $replacement .= '<音频' . $audio_index . '>';
  9859. }
  9860. // 替换所有 {产品名称} 为处理后的格式
  9861. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  9862. }
  9863. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  9864. foreach ($products as $product) {
  9865. $product_name = getProp($product, 'product_name');
  9866. $voice_prompt = getProp($product, 'voice_prompt');
  9867. if ($product_name === '旁白' && !empty($voice_prompt) && empty($product_audio_index_map['旁白'])) {
  9868. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  9869. break; // 找到旁白后退出循环
  9870. }
  9871. }
  9872. // 第四步:将参考音频音色信息和voice_prompt信息添加到内容最前面
  9873. $voice_prompt_prefix = '';
  9874. // 有参考音频的角色:声明"角色名 对应 音频N",统一使用<音频N>标记,
  9875. // 素材上传失败时与正文标记一起被清理/重排,保证角色与音频始终对应
  9876. foreach ($product_audio_index_map as $product_name => $audio_index) {
  9877. $voice_prompt_prefix .= $product_name . ':全程使用<音频' . $audio_index . '>的音色进行配音' . "\n";
  9878. }
  9879. if (!empty($voice_prompts)) {
  9880. $voice_prompt_prefix .= implode('', $voice_prompts);
  9881. }
  9882. // 旁白的voice_prompt放在最后
  9883. if (!empty($narrator_voice_prompt)) {
  9884. $voice_prompt_prefix .= $narrator_voice_prompt;
  9885. }
  9886. // 如果有voice_prompt信息,添加到内容开头
  9887. if (!empty($voice_prompt_prefix)) {
  9888. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  9889. }
  9890. return [
  9891. 'content' => $processedContent,
  9892. 'reference_images' => $reference_images,
  9893. 'reference_audios' => $reference_audios,
  9894. 'audio_voice_fallbacks' => $audio_voice_fallbacks
  9895. ];
  9896. }
  9897. /**
  9898. * 用剧本资产关联(mappings)的数据补齐资产数组
  9899. * 批量转视频时资产取值的优先级:剧本资产关联(mappings) > extra_products > 剧集单独设置
  9900. * 资产库对应字段为空时不覆盖,避免把分集里的有效数据清空
  9901. *
  9902. * @param array $products 资产数组
  9903. * @param int $script_id 剧本ID
  9904. * @param bool $overwrite 资产库有值时是否覆盖数组中的已有值(true 表示 mappings 优先级最高)
  9905. * @return array
  9906. */
  9907. public function fillProductsFromMapping($products, $script_id, $overwrite = false) {
  9908. if (empty($products) || !$script_id) {
  9909. return $products;
  9910. }
  9911. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  9912. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9913. ->where('mapping.script_id', $script_id)
  9914. ->where('product.is_deleted', 0)
  9915. ->select(
  9916. 'mapping.product_id',
  9917. 'product.product_name',
  9918. 'product.product',
  9919. 'product.pic_prompt',
  9920. 'product.url',
  9921. 'product.three_view_image_url',
  9922. 'product.timbre_url'
  9923. )
  9924. ->get();
  9925. if ($mappingItems->isEmpty()) {
  9926. return $products;
  9927. }
  9928. $mappingMap = [];
  9929. foreach ($mappingItems as $item) {
  9930. $normalized_name = $this->normalizeProductName($item->product_name);
  9931. if ($normalized_name === '' || isset($mappingMap[$normalized_name])) {
  9932. continue;
  9933. }
  9934. // 资产库字段有值才纳入覆盖范围(三视图、音色等为选填,可能为空)
  9935. $mappingProduct = [];
  9936. if (!empty($item->product_id)) {
  9937. $mappingProduct['product_id'] = (int)$item->product_id;
  9938. }
  9939. if (!empty($item->product)) {
  9940. $mappingProduct['product'] = (int)$item->product;
  9941. }
  9942. if (!empty($item->pic_prompt)) {
  9943. $mappingProduct['pic_prompt'] = $item->pic_prompt;
  9944. }
  9945. if (!empty($item->url)) {
  9946. $mappingProduct['url'] = $item->url;
  9947. }
  9948. if (!empty($item->three_view_image_url)) {
  9949. $mappingProduct['three_view_image_url'] = $item->three_view_image_url;
  9950. }
  9951. if (!empty($item->timbre_url)) {
  9952. $mappingProduct['timbre_url'] = $item->timbre_url;
  9953. }
  9954. if (!empty($mappingProduct)) {
  9955. $mappingMap[$normalized_name] = $mappingProduct;
  9956. }
  9957. }
  9958. if (empty($mappingMap)) {
  9959. return $products;
  9960. }
  9961. foreach ($products as &$product) {
  9962. $normalized_name = $this->normalizeProductName(getProp($product, 'product_name'));
  9963. if ($normalized_name === '' || empty($mappingMap[$normalized_name])) {
  9964. continue;
  9965. }
  9966. foreach ($mappingMap[$normalized_name] as $key => $value) {
  9967. // 不覆盖模式:只补齐数组中缺失的字段
  9968. if (!$overwrite && !empty(getProp($product, $key))) {
  9969. continue;
  9970. }
  9971. $product[$key] = $value;
  9972. }
  9973. }
  9974. unset($product);
  9975. return $products;
  9976. }
  9977. /**
  9978. * 资产名称归一化(去掉首尾空白、方括号、花括号等符号)
  9979. *
  9980. * @param string $name
  9981. * @return string
  9982. */
  9983. private function normalizeProductName($name) {
  9984. return trim(preg_replace(
  9985. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  9986. '',
  9987. trim((string)$name)
  9988. ));
  9989. }
  9990. /**
  9991. * 判断视频模型是否支持角色参考音频(音色)
  9992. * 目前支持:智帧统一API、Seedance 2.0 系列(国内百度/海外百度/快快AI)
  9993. *
  9994. * @param string $model
  9995. * @return bool
  9996. */
  9997. public function isActReferenceAudioSupported($model) {
  9998. if (!$model) {
  9999. return false;
  10000. }
  10001. return strpos($model, 'zhizhen') !== false || $this->isSeedance20SeriesModel($model);
  10002. }
  10003. /**
  10004. * 将角色音色参考音频按模型分支上传为素材
  10005. * 上传失败时对应素材的<音频N>标记会从 $prompt 中清理(引用传递),与参考图处理保持一致
  10006. *
  10007. * @param array $referenceAudios 参考音频URL数组(顺序与<音频N>标记一一对应)
  10008. * @param string $model 视频模型
  10009. * @param string $prompt 完整提示词(引用传递)
  10010. * @return array 素材数组(asset://格式),非支持模型返回空数组
  10011. */
  10012. public function processActReferenceAudiosToAssets(array $referenceAudios, $model, &$prompt) {
  10013. if (empty($referenceAudios)) {
  10014. return [];
  10015. }
  10016. if (strpos($model, 'zhizhen') !== false) {
  10017. return $this->aiImageGenerationService->processReferenceAudiosToAssets($referenceAudios, $prompt);
  10018. }
  10019. if ($this->isSeedance20SeriesModel($model)) {
  10020. if ($this->isKuaikuaiSeedanceModel($model)) {
  10021. return $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($referenceAudios, $prompt);
  10022. }
  10023. if ($this->isOverseasBaiduSeedanceModel($model)) {
  10024. return $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($referenceAudios, $prompt);
  10025. }
  10026. return $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($referenceAudios, $prompt);
  10027. }
  10028. return [];
  10029. }
  10030. /**
  10031. * 参考音频素材上传失败时,用该角色原本的音色提示词兜底
  10032. * 说明行中的<音频N>标记被清理即代表该角色的音频素材不可用
  10033. *
  10034. * @param string $prompt 完整提示词
  10035. * @param array $audioVoiceFallbacks 角色名 => voice_prompt(仅包含配置了参考音频的角色)
  10036. * @return string
  10037. */
  10038. public function applyAudioVoiceFallbacks($prompt, array $audioVoiceFallbacks) {
  10039. if (empty($prompt) || empty($audioVoiceFallbacks)) {
  10040. return $prompt;
  10041. }
  10042. foreach ($audioVoiceFallbacks as $product_name => $voice_prompt) {
  10043. $voice_prompt = trim((string)$voice_prompt);
  10044. if ($product_name === '') {
  10045. continue;
  10046. }
  10047. $escaped_name = preg_quote($product_name, '/');
  10048. // 说明行中仍有<音频N>标记,说明该角色的音频素材可用,无需兜底
  10049. if (preg_match('/^' . $escaped_name . ':全程使用<音频\d+>的音色进行配音[^\n]*$/mu', $prompt)) {
  10050. continue;
  10051. }
  10052. $linePattern = '/^' . $escaped_name . ':全程使用[^\n]*的音色进行配音[^\n]*$/mu';
  10053. if (!preg_match($linePattern, $prompt)) {
  10054. continue;
  10055. }
  10056. if ($voice_prompt === '') {
  10057. // 该角色没有音色提示词,素材不可用时直接移除残留的说明行
  10058. $prompt = preg_replace('/^' . $escaped_name . ':全程使用[^\n]*的音色进行配音[^\n]*\n?/mu', '', $prompt, 1);
  10059. } else {
  10060. // 素材不可用:把说明行替换为该角色原本的音色提示词
  10061. $prompt = preg_replace_callback($linePattern, function () use ($product_name, $voice_prompt) {
  10062. return $product_name . ':' . $voice_prompt;
  10063. }, $prompt, 1);
  10064. }
  10065. dLog('anime')->info('参考音频素材不可用,使用音色提示词兜底', [
  10066. 'product_name' => $product_name,
  10067. 'has_voice_prompt' => $voice_prompt === '' ? 0 : 1,
  10068. ]);
  10069. }
  10070. return $prompt;
  10071. }
  10072. /**
  10073. * 整段配音音频素材不可用时,移除对应的提示语句,避免出现残句
  10074. *
  10075. * @param string $prompt 完整提示词
  10076. * @return string
  10077. */
  10078. public function removeUnavailableSegmentAudioPrompt($prompt) {
  10079. if (empty($prompt) || strpos($prompt, '作为视频配音') === false) {
  10080. return $prompt;
  10081. }
  10082. return preg_replace_callback('/^全程使用[^\n]*?作为视频配音。\n?/mu', function ($matches) {
  10083. return strpos($matches[0], '<音频') === false ? '' : $matches[0];
  10084. }, $prompt);
  10085. }
  10086. /**
  10087. * 生成整段配音音频的提示词引用,并返回合并后的参考音频数组
  10088. * 角色音色音频排在前面(音频1..N,与提示词中的<音频N>一一对应),整段配音音频排在其后
  10089. *
  10090. * @param string $prompt 当前提示词
  10091. * @param array $referenceAudios 角色音色参考音频URL数组
  10092. * @param string $segmentAudioUrl 整段配音音频URL(为空表示无整段配音)
  10093. * @return array ['prompt' => 新提示词, 'has_audio_mark' => 是否使用<音频N>标记, 'reference_audios' => 合并后的音频数组]
  10094. */
  10095. public function buildSegmentAudioReference($prompt, array $referenceAudios, $segmentAudioUrl) {
  10096. $result = [
  10097. 'prompt' => $prompt,
  10098. 'has_audio_mark' => false,
  10099. 'reference_audios' => $referenceAudios,
  10100. ];
  10101. if (empty($segmentAudioUrl)) {
  10102. return $result;
  10103. }
  10104. // 有角色音色时整段配音排在角色音色之后,使用<音频N>标记交由素材上传统一做失败清理与序号重排;
  10105. // 没有角色音色时保持原有文案
  10106. $audioReference = $referenceAudios
  10107. ? "使用<音频" . (count($referenceAudios) + 1) . ">"
  10108. : "使用音频1";
  10109. $hasAudioMark = strpos($audioReference, '<音频') !== false;
  10110. // 有角色音色时整段配音独占一行,便于失败时按行清理
  10111. $result['prompt'] = $hasAudioMark
  10112. ? "全程" . $audioReference . "作为视频配音。\n" . $prompt
  10113. : "全程" . $audioReference . "作为视频配音。" . $prompt;
  10114. $result['has_audio_mark'] = $hasAudioMark;
  10115. $result['reference_audios'] = array_merge($referenceAudios, [$segmentAudioUrl]);
  10116. return $result;
  10117. }
  10118. /**
  10119. * 任务记录用:把参考音频追加到 ref_image_url 中
  10120. * 参考图与参考音色音频一起保存,便于后续核对任务实际使用的素材
  10121. * 合并后统一去重并过滤空值,保证同一素材只出现一次
  10122. *
  10123. * @param string $refImageUrlJson 当前 ref_image_url(JSON数组字符串)
  10124. * @param array $referenceAudios 参考音频URL数组
  10125. * @return string
  10126. */
  10127. public function mergeReferenceAudiosIntoRefImageUrl($refImageUrlJson, array $referenceAudios) {
  10128. $refImageUrls = json_decode((string)$refImageUrlJson, true) ?: [];
  10129. if (!is_array($refImageUrls)) {
  10130. $refImageUrls = [];
  10131. }
  10132. // 参考图在前、参考音频在后,合并后去重并过滤空值
  10133. $merged = array_values(array_unique(array_filter(array_merge($refImageUrls, $referenceAudios))));
  10134. return json_encode($merged, 256);
  10135. }
  10136. public function saveActVideoGenerateParams($data) {
  10137. $episode_id = getProp($data, 'episode_id');
  10138. $model = getProp($data, 'video_model');
  10139. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  10140. if (!in_array($model, $valid_models)) {
  10141. Utils::throwError('20003:该模型不可用');
  10142. }
  10143. // 验证模型是否在可用模型表中
  10144. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10145. Utils::throwError('20003:该模型已不可用,请更换!');
  10146. }
  10147. $video_resolution = getProp($data, 'video_resolution', '720p');
  10148. $ratio = getProp($data, 'ratio');
  10149. if (!$ratio) $ratio = '9:16';
  10150. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  10151. if (!$episode) {
  10152. Utils::throwError('20003:分集不存在');
  10153. }
  10154. dLog('anime')->info('保存分集视频参数', $data);
  10155. try {
  10156. DB::beginTransaction();
  10157. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10158. 'video_model' => $model,
  10159. 'video_resolution' => $video_resolution,
  10160. 'ratio' => $ratio,
  10161. 'updated_at' => date('Y-m-d H:i:s')
  10162. ]);
  10163. if ($result === false) {
  10164. Utils::throwError('20003:分集视频参数保存失败');
  10165. }
  10166. // 同步更新mp_animes表
  10167. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  10168. 'video_model' => $model,
  10169. 'video_resolution' => $video_resolution,
  10170. 'video_ratio' => $ratio,
  10171. 'updated_at' => date('Y-m-d H:i:s')
  10172. ]);
  10173. if ($anime_result === false) {
  10174. Utils::throwError('20003:动漫视频参数保存失败');
  10175. }
  10176. } catch (\Exception $e) {
  10177. DB::rollBack();
  10178. Utils::throwError('20003:'.$e->getMessage());
  10179. }
  10180. DB::commit();
  10181. return $result;
  10182. }
  10183. public function confirmActs($data) {
  10184. $episode_id = getProp($data, 'episode_id');
  10185. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  10186. if (!$episode) {
  10187. Utils::throwError('20003:分集不存在');
  10188. }
  10189. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10190. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10191. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  10192. // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
  10193. $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
  10194. // 获取所有片段数据
  10195. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  10196. // 先构建完整的 products(角色、场景、道具、extra_products,并用资产库映射覆盖),
  10197. // 再处理每个片段的 act_content,避免 extra_products 等资产名未被格式化为 {资产名}
  10198. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  10199. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  10200. $products = [];
  10201. // 先处理角色数组
  10202. foreach ($roles as $role) {
  10203. $product = $role;
  10204. // 将role字段重命名为product_name
  10205. if (isset($product['role'])) {
  10206. $product['product_name'] = $product['role'];
  10207. unset($product['role']);
  10208. $product['product'] = 1; // 标记类型为角色
  10209. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10210. }
  10211. }
  10212. // 处理场景数组
  10213. foreach ($scenes as $scene) {
  10214. $product = $scene;
  10215. // 将scene字段重命名为product_name
  10216. if (isset($product['scene'])) {
  10217. $product['product_name'] = $product['scene'];
  10218. unset($product['scene']);
  10219. $product['product'] = 2; // 标记类型为场景
  10220. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10221. }
  10222. }
  10223. // 处理道具数组(逻辑与场景一致)
  10224. foreach ($props as $prop) {
  10225. $product = $prop;
  10226. // 将prop字段重命名为product_name
  10227. if (isset($product['prop'])) {
  10228. $product['product_name'] = $product['prop'];
  10229. unset($product['prop']);
  10230. $product['product'] = 3; // 标记类型为道具
  10231. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10232. }
  10233. }
  10234. // extra_products优先级更高,直接覆盖同名的roles和scenes
  10235. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  10236. foreach ($extra_products as $extra_product) {
  10237. $product_name = getProp($extra_product, 'product_name');
  10238. if ($product_name) {
  10239. $products[$product_name] = $extra_product; // 覆盖同名数据
  10240. }
  10241. }
  10242. // mp_script_product_mappings 信息优先级更高:
  10243. // 获取当前剧集所属动漫剧本下、与本集资产同名的资产库最新数据(url/三视图/提示词等),
  10244. // 覆盖分集 JSON 中保存的同名旧快照;分集内独有的 description、voice_prompt 等字段保留
  10245. $anime = DB::table('mp_animes')->where('id', getProp($episode, 'anime_id'))->first();
  10246. $script_id = $anime ? (int)getProp($anime, 'script_id', 0) : 0;
  10247. if ($script_id && !empty($products)) {
  10248. $currentProductNames = array_keys($products);
  10249. $normalizeName = function($name) {
  10250. return trim(preg_replace(
  10251. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  10252. '',
  10253. trim((string)$name)
  10254. ));
  10255. };
  10256. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  10257. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  10258. ->where('mapping.script_id', $script_id)
  10259. ->where('product.is_deleted', 0)
  10260. ->whereIn('product.product_name', $currentProductNames)
  10261. ->select(
  10262. 'mapping.product_id',
  10263. 'product.product_name',
  10264. 'product.product',
  10265. 'product.pic_prompt',
  10266. 'product.url',
  10267. 'product.three_view_image_url',
  10268. 'product.timbre_url',
  10269. )
  10270. ->get();
  10271. $mappingByName = [];
  10272. foreach ($mappingItems as $mappingItem) {
  10273. $normalizedName = $normalizeName($mappingItem->product_name);
  10274. if (!$normalizedName) continue;
  10275. $mappingProduct = [
  10276. 'product_id' => (int)$mappingItem->product_id,
  10277. 'product_name' => $mappingItem->product_name,
  10278. 'product' => (int)$mappingItem->product,
  10279. 'pic_prompt' => $mappingItem->pic_prompt ?? '',
  10280. 'url' => $mappingItem->url ?? '',
  10281. 'three_view_image_url' => $mappingItem->three_view_image_url ?? '',
  10282. ];
  10283. // 音色音频:资产库有值时才覆盖分集自带的值,避免空值把已有音色清掉
  10284. if (!empty($mappingItem->timbre_url)) {
  10285. $mappingProduct['timbre_url'] = $mappingItem->timbre_url;
  10286. }
  10287. $mappingByName[$normalizedName] = $mappingProduct;
  10288. }
  10289. foreach ($products as $key => &$product) {
  10290. $normalizedKey = $normalizeName($key);
  10291. if ($normalizedKey && isset($mappingByName[$normalizedKey])) {
  10292. $product = array_merge($product, $mappingByName[$normalizedKey]);
  10293. }
  10294. }
  10295. unset($product);
  10296. }
  10297. // 兼容返回 three_view_image_url / timbre_url 字段(旧数据可能没有该键,统一补空值)
  10298. foreach ($products as &$product) {
  10299. if (!isset($product['three_view_image_url'])) {
  10300. $product['three_view_image_url'] = '';
  10301. }
  10302. if (!isset($product['timbre_url'])) {
  10303. $product['timbre_url'] = '';
  10304. }
  10305. }
  10306. unset($product);
  10307. // 重新索引数组(去除key)
  10308. $products = array_values($products);
  10309. // 基于构建完成的 products 收集所有资产名称(含 extra_products 中的资产)
  10310. $product_names = [];
  10311. foreach ($products as $product) {
  10312. $product_name = getProp($product, 'product_name');
  10313. if ($product_name && $product_name !== '旁白') {
  10314. $product_names[] = $product_name;
  10315. }
  10316. }
  10317. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  10318. $product_names = array_unique($product_names);
  10319. usort($product_names, function($a, $b) {
  10320. return mb_strlen($b) - mb_strlen($a);
  10321. });
  10322. try {
  10323. DB::beginTransaction();
  10324. // 处理每个片段
  10325. foreach ($acts as $act) {
  10326. $act_content = getProp($act, 'act_content');
  10327. if (!$act_content) continue;
  10328. $processed_content = $act_content;
  10329. // 统一替换所有资产名称为 {资产名} 格式
  10330. // 使用占位符避免嵌套替换问题
  10331. $placeholder_map = [];
  10332. $placeholder_index = 0;
  10333. foreach ($product_names as $product_name) {
  10334. // 转义特殊字符
  10335. $escaped_product = preg_quote($product_name, '/');
  10336. // 检查是否匹配且未被 {} 包裹
  10337. $processed_content = preg_replace_callback(
  10338. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  10339. function($matches) use (&$placeholder_map, &$placeholder_index) {
  10340. // 使用唯一占位符
  10341. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  10342. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  10343. $placeholder_index++;
  10344. return $placeholder;
  10345. },
  10346. $processed_content
  10347. );
  10348. }
  10349. // 将所有占位符替换回实际内容
  10350. foreach ($placeholder_map as $placeholder => $replacement) {
  10351. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  10352. }
  10353. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  10354. $shot_counter = 0;
  10355. $processed_content = preg_replace_callback(
  10356. '/【(?:镜头|分镜)(\d+)】/u',
  10357. function($matches) use (&$shot_counter) {
  10358. $shot_counter++;
  10359. return '【镜头' . $shot_counter . '】';
  10360. },
  10361. $processed_content
  10362. );
  10363. // 更新数据库
  10364. $boolen = DB::table('mp_episode_segments')
  10365. ->where('id', $act->id)
  10366. ->update([
  10367. 'act_show_content' => $processed_content,
  10368. 'updated_at' => date('Y-m-d H:i:s')
  10369. ]);
  10370. if (!$boolen) {
  10371. Utils::throwError('20003:片段处理失败');
  10372. }
  10373. }
  10374. }catch (\Exception $e) {
  10375. DB::rollBack();
  10376. Utils::throwError('20003:'.$e->getMessage());
  10377. }
  10378. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10379. 'is_generated' => 1,
  10380. 'updated_at' => date('Y-m-d H:i:s')
  10381. ]);
  10382. if (!$boolen1) {
  10383. DB::rollBack();
  10384. Utils::throwError('20003:分集处理失败!');
  10385. }
  10386. DB::commit();
  10387. // 重新查询更新后的片段数据
  10388. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  10389. // 构建返回的acts数组
  10390. $return_acts = [];
  10391. foreach ($acts as $act) {
  10392. $return_acts[] = [
  10393. 'act_id' => getProp($act, 'id'),
  10394. 'act_number' => getProp($act, 'act_number'),
  10395. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  10396. 'act_show_content' => getProp($act, 'act_show_content'),
  10397. 'video_url' => getProp($act, 'video_url'),
  10398. 'video_duration' => getProp($act, 'video_duration'),
  10399. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  10400. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  10401. ];
  10402. }
  10403. return [
  10404. 'anime_id' => getProp($episode, 'anime_id'),
  10405. 'episode_id' => $episode_id,
  10406. 'title' => getProp($episode, 'title'),
  10407. 'episode_number' => getProp($episode, 'episode_number'),
  10408. 'is_generated' => getProp($episode, 'is_generated'),
  10409. 'video_params' => [
  10410. 'video_model' => getProp($episode, 'video_model'),
  10411. 'video_resolution' => getProp($episode, 'video_resolution'),
  10412. 'ratio' => getProp($episode, 'ratio'),
  10413. ],
  10414. 'products' => $products,
  10415. 'acts' => $return_acts
  10416. ];
  10417. }
  10418. /**
  10419. * 参照 episodePicsInfo 的更新与监控逻辑:
  10420. * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
  10421. * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
  10422. */
  10423. private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
  10424. $pollInterval = 5; // 每5秒查询一次
  10425. $maxWaitSeconds = 60; // 最多持续1分钟
  10426. $startTime = time();
  10427. while (true) {
  10428. // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
  10429. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  10430. if (!$episode) {
  10431. Utils::throwError('20003:分集不存在');
  10432. }
  10433. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10434. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10435. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  10436. $updated = false;
  10437. $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
  10438. $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
  10439. $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
  10440. $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
  10441. $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
  10442. // 有图片任务结果更新时写回分集表
  10443. if ($updated) {
  10444. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10445. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  10446. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  10447. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  10448. 'updated_at' => date('Y-m-d H:i:s')
  10449. ]);
  10450. }
  10451. // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
  10452. if (empty($waitingAssets) && empty($missingAssets)) {
  10453. return;
  10454. }
  10455. // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
  10456. if (empty($waitingAssets)) {
  10457. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10458. }
  10459. // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
  10460. if (time() - $startTime >= $maxWaitSeconds) {
  10461. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10462. }
  10463. sleep($pollInterval);
  10464. }
  10465. }
  10466. /**
  10467. * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
  10468. * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
  10469. * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
  10470. */
  10471. private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
  10472. foreach ($assets as &$asset) {
  10473. $assetName = getProp($asset, $nameKey);
  10474. if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
  10475. continue;
  10476. }
  10477. // 已有图片URL的资产视为已生成
  10478. if (getProp($asset, 'url')) {
  10479. continue;
  10480. }
  10481. $task_id = getProp($asset, 'task_id');
  10482. // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
  10483. if (!$task_id) {
  10484. $missingAssets[] = $assetName;
  10485. continue;
  10486. }
  10487. $task = DB::table('mp_generate_pic_tasks')
  10488. ->where('id', $task_id)
  10489. ->select('status', 'result_url')
  10490. ->first();
  10491. // 任务不存在:同样记录为缺失项,不在此处直接报错
  10492. if (!$task) {
  10493. $missingAssets[] = $assetName;
  10494. continue;
  10495. }
  10496. if ($task->status === 'success') {
  10497. $result_url = getProp($task, 'result_url');
  10498. if ($result_url) {
  10499. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  10500. if (is_array($result_urls) && !empty($result_urls[0])) {
  10501. $asset['url'] = $result_urls[0];
  10502. $asset['task_status'] = 'success';
  10503. $updated = true;
  10504. continue;
  10505. }
  10506. }
  10507. // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
  10508. $waitingAssets[] = $assetName;
  10509. } elseif ($task->status === 'failed') {
  10510. // 生成失败:记录为缺失项,待其他任务处理完后统一报错
  10511. $missingAssets[] = $assetName;
  10512. } else {
  10513. // 任务仍在生成中,等待下一次轮询
  10514. $waitingAssets[] = $assetName;
  10515. }
  10516. }
  10517. unset($asset);
  10518. }
  10519. /**
  10520. * 导出动漫剧本为PDF(参照示例PDF版式)
  10521. * @param int $animeId 动漫ID
  10522. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  10523. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  10524. * @return string|null
  10525. */
  10526. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  10527. // 图片下载与转换可能占用较多内存
  10528. ini_set('memory_limit', '512M');
  10529. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  10530. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  10531. $anime = (array)$anime;
  10532. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  10533. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  10534. // 获取分集(默认展示版本,按集数升序)
  10535. $episodeQuery = DB::table('mp_anime_episodes')
  10536. ->where('anime_id', $animeId)
  10537. ->where('is_default', 1)
  10538. ->orderBy('episode_number')
  10539. ->orderBy('id');
  10540. if ($episodeCount > 0) {
  10541. $episodeQuery->limit($episodeCount);
  10542. }
  10543. $episodes = $episodeQuery->get()->map(function ($value) {
  10544. return (array)$value;
  10545. })->toArray();
  10546. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  10547. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  10548. $roles = $this->mergeEpisodeItems($episodes, 'role');
  10549. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  10550. $props = $this->mergeEpisodeItems($episodes, 'prop');
  10551. // 组装分集剧本数据
  10552. $episodeScripts = [];
  10553. foreach ($episodes as $episode) {
  10554. $segments = DB::table('mp_episode_segments')
  10555. ->where('anime_id', $animeId)
  10556. ->where('episode_id', $episode['id'])
  10557. ->get();
  10558. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  10559. $acts = [];
  10560. foreach ($segments as $segment) {
  10561. $segment = (array)$segment;
  10562. $actNumber = (int)getProp($segment, 'act_number', 0);
  10563. if ($actNumber <= 0) continue;
  10564. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  10565. $acts[$actNumber] = [
  10566. 'id' => (int)$segment['id'],
  10567. 'act_number' => $actNumber,
  10568. 'duration' => getProp($segment, 'act_duration', ''),
  10569. 'content' => getProp($segment, 'act_content', ''),
  10570. ];
  10571. }
  10572. }
  10573. ksort($acts);
  10574. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  10575. $segmentCounter = 0;
  10576. foreach ($acts as &$act) {
  10577. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  10578. }
  10579. unset($act);
  10580. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  10581. $narratorVoice = '';
  10582. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  10583. foreach ($episodeRoles as $role) {
  10584. if (getProp($role, 'role') === '旁白') {
  10585. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  10586. break;
  10587. }
  10588. }
  10589. if ($narratorVoice === '') {
  10590. foreach ($acts as $act) {
  10591. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  10592. $narratorVoice = trim($match[1]);
  10593. break;
  10594. }
  10595. }
  10596. }
  10597. $episodeScripts[] = [
  10598. 'episode_number' => getProp($episode, 'episode_number'),
  10599. 'title' => getProp($episode, 'title', ''),
  10600. 'act_count' => count($acts),
  10601. 'narrator_voice' => $narratorVoice,
  10602. 'acts' => array_values($acts),
  10603. ];
  10604. }
  10605. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  10606. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  10607. // 构建PDF
  10608. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  10609. // 图片已嵌入PDF,清理临时文件
  10610. foreach ($imageCache as $imgFile) {
  10611. @unlink($imgFile);
  10612. }
  10613. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  10614. if ($savePath) {
  10615. $pdf->Output($savePath, 'F');
  10616. return $savePath;
  10617. }
  10618. // 直接下载输出
  10619. header('Content-Type: application/pdf');
  10620. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  10621. $pdf->Output($filename . '.pdf', 'D');
  10622. exit();
  10623. }
  10624. /**
  10625. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  10626. * @param array $episodes 分集数据
  10627. * @param string $nameKey role|scene|prop
  10628. * @return array
  10629. */
  10630. private function mergeEpisodeItems(array $episodes, $nameKey) {
  10631. $fieldMap = [
  10632. 'role' => 'roles',
  10633. 'scene' => 'scenes',
  10634. 'prop' => 'props',
  10635. ];
  10636. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  10637. $items = [];
  10638. foreach ($episodes as $episode) {
  10639. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  10640. foreach ($list as $item) {
  10641. if (!is_array($item)) continue;
  10642. $name = trim((string)getProp($item, $nameKey, ''));
  10643. if ($name === '') continue;
  10644. // 旁白不进入主体列表(仅作为旁白音色来源)
  10645. if ($nameKey === 'role' && $name === '旁白') continue;
  10646. if (!isset($items[$name])) {
  10647. $items[$name] = $item;
  10648. }
  10649. }
  10650. }
  10651. return array_values($items);
  10652. }
  10653. /**
  10654. * 构建动漫剧本PDF
  10655. * @param array $anime 动漫信息
  10656. * @param array $roles 主体列表
  10657. * @param array $scenes 场景列表
  10658. * @param array $props 道具列表
  10659. * @param array $episodeScripts 分集剧本数据
  10660. * @param array $imageCache 图片缓存(url => 临时文件路径)
  10661. * @return \TCPDF
  10662. */
  10663. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  10664. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  10665. $pdf->SetCreator('动漫剧本导出系统');
  10666. $pdf->SetAuthor('系统');
  10667. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  10668. $pdf->SetSubject('动漫剧本导出');
  10669. $pdf->SetMargins(15, 15, 15);
  10670. $pdf->SetAutoPageBreak(true, 15);
  10671. // 剧本名
  10672. $pdf->AddPage();
  10673. $pdf->SetFont('simsun', 'B', 20);
  10674. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  10675. $pdf->Ln(5);
  10676. // 故事梗概
  10677. $intro = trim((string)getProp($anime, 'intro', ''));
  10678. if ($intro !== '') {
  10679. $this->pdfSectionTitle($pdf, '故事梗概');
  10680. $this->pdfBody($pdf, $intro);
  10681. }
  10682. // 美术风格
  10683. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  10684. if ($artStyle !== '') {
  10685. $this->pdfSectionTitle($pdf, '美术风格');
  10686. $this->pdfBody($pdf, $artStyle);
  10687. }
  10688. // 主体列表(文字+图片)
  10689. $this->pdfSectionTitle($pdf, '主体列表');
  10690. foreach ($roles as $index => $role) {
  10691. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  10692. }
  10693. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  10694. // 场景列表(文字+图片)
  10695. $this->pdfSectionTitle($pdf, '场景列表');
  10696. foreach ($scenes as $index => $scene) {
  10697. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  10698. }
  10699. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  10700. // 道具列表(文字+图片)
  10701. $this->pdfSectionTitle($pdf, '道具列表');
  10702. foreach ($props as $index => $prop) {
  10703. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  10704. }
  10705. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  10706. // 分镜剧本
  10707. $this->pdfSectionTitle($pdf, '分镜剧本');
  10708. foreach ($episodeScripts as $episodeScript) {
  10709. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  10710. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  10711. if ($episodeTitleRaw !== '') {
  10712. // title 字段可能已带"第N集"前缀,避免重复
  10713. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  10714. $episodeTitle = $episodeTitleRaw;
  10715. } else {
  10716. $episodeTitle .= ':' . $episodeTitleRaw;
  10717. }
  10718. }
  10719. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  10720. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  10721. if (getProp($episodeScript, 'narrator_voice') !== '') {
  10722. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  10723. }
  10724. foreach (getProp($episodeScript, 'acts', []) as $act) {
  10725. $actTitle = '片段' . getProp($act, 'act_number');
  10726. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  10727. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  10728. }
  10729. $this->pdfSubTitle($pdf, $actTitle, 12);
  10730. if (getProp($act, 'content') !== '') {
  10731. $this->pdfBody($pdf, getProp($act, 'content'));
  10732. }
  10733. }
  10734. }
  10735. return $pdf;
  10736. }
  10737. /**
  10738. * PDF章节标题(带分隔线)
  10739. */
  10740. private function pdfSectionTitle($pdf, $title) {
  10741. if ($pdf->GetY() > 230) {
  10742. $pdf->AddPage();
  10743. }
  10744. $pdf->SetFont('simsun', 'B', 15);
  10745. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  10746. $y = $pdf->GetY();
  10747. $pdf->SetLineWidth(0.4);
  10748. $pdf->Line(15, $y, 195, $y);
  10749. $pdf->Ln(4);
  10750. }
  10751. /**
  10752. * PDF子标题(集数/片段标题)
  10753. */
  10754. private function pdfSubTitle($pdf, $title, $size = 13) {
  10755. if ($pdf->GetY() > 240) {
  10756. $pdf->AddPage();
  10757. }
  10758. $pdf->SetFont('simsun', 'B', $size);
  10759. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  10760. $pdf->Ln(1);
  10761. }
  10762. /**
  10763. * PDF正文段落
  10764. */
  10765. private function pdfBody($pdf, $text) {
  10766. $pdf->SetFont('simsun', '', 11);
  10767. $pdf->MultiCell(0, 6, $text, 0, 'L');
  10768. $pdf->Ln(2);
  10769. }
  10770. /**
  10771. * 输出列表项图片(每张图单独一页,图下标注名称)
  10772. * @param \TCPDF $pdf
  10773. * @param array $items 列表项
  10774. * @param string $nameKey role|scene|prop
  10775. * @param array $imageCache 图片缓存(url => 临时文件路径)
  10776. */
  10777. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  10778. foreach ($items as $item) {
  10779. $url = trim((string)getProp($item, 'url', ''));
  10780. $name = trim((string)getProp($item, $nameKey, ''));
  10781. if ($url === '' || !isset($imageCache[$url])) continue;
  10782. $imgPath = $imageCache[$url];
  10783. $size = @getimagesize($imgPath);
  10784. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  10785. continue;
  10786. }
  10787. $pdf->AddPage();
  10788. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  10789. $maxW = 160;
  10790. $maxH = 170;
  10791. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  10792. $drawW = $size[0] * $ratio;
  10793. $drawH = $size[1] * $ratio;
  10794. $x = (210 - $drawW) / 2;
  10795. $y = max(15, (297 - $drawH) / 2 - 10);
  10796. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  10797. // 图下标注名称
  10798. $pdf->SetFont('simsun', 'B', 13);
  10799. $pdf->SetY(297 - 28);
  10800. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  10801. }
  10802. }
  10803. /**
  10804. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  10805. * @param array $items 包含url字段的列表项
  10806. * @return array url => 临时文件路径
  10807. */
  10808. private function downloadImagesConcurrently(array $items) {
  10809. // 收集唯一的图片URL
  10810. $urls = [];
  10811. foreach ($items as $item) {
  10812. $url = trim((string)getProp($item, 'url', ''));
  10813. if ($url !== '') $urls[$url] = true;
  10814. }
  10815. if (!$urls) return [];
  10816. $urls = array_keys($urls);
  10817. $tmpDir = sys_get_temp_dir();
  10818. $rawFiles = [];
  10819. foreach ($urls as $url) {
  10820. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  10821. $rawFiles[$url] = $rawFile;
  10822. }
  10823. $client = new Client(['timeout' => 180, 'verify' => false]);
  10824. // 低并发下载,sink写入文件避免大图占用内存
  10825. $generator = (function () use ($urls, $client, $rawFiles) {
  10826. foreach ($urls as $url) {
  10827. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  10828. }
  10829. })();
  10830. $errors = [];
  10831. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  10832. 'concurrency' => 4,
  10833. 'rejected' => function ($reason, $url) use (&$errors) {
  10834. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  10835. },
  10836. ]);
  10837. $each->promise()->wait();
  10838. // 失败的图片串行重试一次(独占带宽,提高成功率)
  10839. foreach ($urls as $url) {
  10840. if (!isset($errors[$url])) continue;
  10841. try {
  10842. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  10843. unset($errors[$url]);
  10844. } catch (\Throwable $e) {
  10845. // 重试仍失败
  10846. }
  10847. }
  10848. $cache = [];
  10849. foreach ($urls as $url) {
  10850. $rawFile = $rawFiles[$url];
  10851. if (isset($errors[$url])) {
  10852. dLog('anime')->error('导出PDF图片下载失败', [
  10853. 'url' => $url,
  10854. 'error' => $errors[$url],
  10855. ]);
  10856. @unlink($rawFile);
  10857. continue;
  10858. }
  10859. $converted = $this->convertImageFile($rawFile, $url);
  10860. if ($converted !== null) {
  10861. $cache[$url] = $converted;
  10862. } else {
  10863. @unlink($rawFile);
  10864. }
  10865. }
  10866. return $cache;
  10867. }
  10868. /**
  10869. * 将已下载的图片文件缩放并转为JPEG
  10870. * @param string $rawFile 原始图片临时文件
  10871. * @param string $url 图片地址(用于命名)
  10872. * @return string|null 转换后的文件路径,转换失败返回null
  10873. */
  10874. private function convertImageFile($rawFile, $url) {
  10875. $content = @file_get_contents($rawFile);
  10876. if ($content === false || $content === '') return null;
  10877. if (!function_exists('imagecreatefromstring')) return null;
  10878. $image = @imagecreatefromstring($content);
  10879. if ($image === false) return null;
  10880. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  10881. imagedestroy($image);
  10882. if ($jpeg !== null) {
  10883. @unlink($rawFile);
  10884. }
  10885. return $jpeg;
  10886. }
  10887. /**
  10888. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  10889. * @param resource $srcImage GD图片资源
  10890. * @param string $rawFile 原始图片临时文件
  10891. * @param string $url 图片地址(用于命名)
  10892. * @return string|null 压缩后的JPEG文件路径
  10893. */
  10894. private function compressImageForPdf($srcImage, $rawFile, $url) {
  10895. $maxBytes = 2 * 1024 * 1024; // 2MB
  10896. $sizes = [2048, 1600, 1280, 1024, 800];
  10897. $qualities = [85, 70, 55, 40];
  10898. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  10899. foreach ($sizes as $size) {
  10900. $resized = $this->copyAndResize($srcImage, $size);
  10901. $flat = $this->flattenToWhite($resized);
  10902. imagedestroy($resized);
  10903. foreach ($qualities as $quality) {
  10904. ob_start();
  10905. $saved = imagejpeg($flat, null, $quality);
  10906. $data = ob_get_clean();
  10907. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  10908. file_put_contents($jpeg, $data);
  10909. imagedestroy($flat);
  10910. dLog('anime')->info('导出PDF图片压缩完成', [
  10911. 'url' => $url,
  10912. 'size' => filesize($jpeg),
  10913. 'edge' => $size,
  10914. 'quality' => $quality,
  10915. ]);
  10916. return $jpeg;
  10917. }
  10918. }
  10919. imagedestroy($flat);
  10920. }
  10921. // 兜底:最小尺寸、最低质量强制输出
  10922. $resized = $this->copyAndResize($srcImage, 800);
  10923. $flat = $this->flattenToWhite($resized);
  10924. imagedestroy($resized);
  10925. $saved = imagejpeg($flat, $jpeg, 30);
  10926. imagedestroy($flat);
  10927. if (!$saved) return null;
  10928. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  10929. 'url' => $url,
  10930. 'size' => filesize($jpeg),
  10931. ]);
  10932. return $jpeg;
  10933. }
  10934. /**
  10935. * 等比缩放图片副本(不销毁原图)
  10936. * @param resource $srcImage GD图片资源
  10937. * @param int $maxEdge 最大边长
  10938. * @return resource
  10939. */
  10940. private function copyAndResize($srcImage, $maxEdge) {
  10941. $width = imagesx($srcImage);
  10942. $height = imagesy($srcImage);
  10943. $max = max($width, $height);
  10944. if ($max <= $maxEdge) {
  10945. $copy = imagecreatetruecolor($width, $height);
  10946. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  10947. return $copy;
  10948. }
  10949. $ratio = $maxEdge / $max;
  10950. $newWidth = max(1, (int)round($width * $ratio));
  10951. $newHeight = max(1, (int)round($height * $ratio));
  10952. $resized = imagecreatetruecolor($newWidth, $newHeight);
  10953. imagealphablending($resized, false);
  10954. imagesavealpha($resized, true);
  10955. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  10956. return $resized;
  10957. }
  10958. /**
  10959. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  10960. * @param resource $image GD图片资源
  10961. * @return resource
  10962. */
  10963. private function flattenToWhite($image) {
  10964. $width = imagesx($image);
  10965. $height = imagesy($image);
  10966. $flat = imagecreatetruecolor($width, $height);
  10967. $white = imagecolorallocate($flat, 255, 255, 255);
  10968. imagefill($flat, 0, 0, $white);
  10969. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  10970. return $flat;
  10971. }
  10972. /**
  10973. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  10974. * @param string $content 片段内容
  10975. * @param int $counter 当前已编号数量(引用传递,整集累计)
  10976. * @return string
  10977. */
  10978. private function renumberSegmentBlocks($content, &$counter) {
  10979. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  10980. $counter++;
  10981. return '【' . $match[1] . $counter . '】';
  10982. }, $content);
  10983. }
  10984. }