AnimeService.php 567 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242
  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 = buildStylePromptPrefix($character_prefix) . "主体描述:{$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 = buildStylePromptPrefix($scene_prefix) . "场景描述:{$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. $timbre_url = trim(getProp($target_roles, 'timbre_url', ''));
  1048. // 兼容 versions 传入数组或 JSON 字符串
  1049. $versions = getProp($target_roles, 'versions', null);
  1050. if (is_string($versions) && $versions !== '') {
  1051. $decoded_versions = json_decode($versions, true);
  1052. if (is_array($decoded_versions)) {
  1053. $versions = $decoded_versions;
  1054. }
  1055. }
  1056. $product_type = 1; // 1=角色
  1057. // 查找或创建以script_name命名的文件夹
  1058. $folder = DB::table('mp_products')
  1059. ->where('cpid', $cpid)
  1060. ->where('type', 2) // 文件夹类型
  1061. ->where('product', $product_type) // 角色类型
  1062. ->where('product_name', $script_name)
  1063. ->where('parent_id', 0)
  1064. ->where('is_deleted', 0)
  1065. ->first();
  1066. if (!$folder) {
  1067. // 创建文件夹
  1068. $folder_id = DB::table('mp_products')->insertGetId([
  1069. 'user_id' => $uid,
  1070. 'cpid' => $cpid,
  1071. 'type' => 2, // 文件夹
  1072. 'product' => $product_type, // 角色类型
  1073. 'parent_id' => 0,
  1074. 'level' => 1,
  1075. 'product_name' => $script_name,
  1076. 'sort_order' => time(),
  1077. 'is_deleted' => 0,
  1078. 'created_at' => date('Y-m-d H:i:s'),
  1079. 'updated_at' => date('Y-m-d H:i:s')
  1080. ]);
  1081. } else {
  1082. $folder_id = $folder->id;
  1083. }
  1084. // 查找该文件夹下是否已存在同名资产
  1085. $existing_product = DB::table('mp_products')
  1086. ->where('cpid', $cpid)
  1087. ->where('type', 1) // 资产类型
  1088. ->where('product', $product_type)
  1089. ->where('parent_id', $folder_id)
  1090. ->where('product_name', $product_name)
  1091. ->where('is_deleted', 0)
  1092. ->first();
  1093. if ($existing_product) {
  1094. // 更新已存在的资产
  1095. $updateData = [
  1096. 'pic_task_status' => '生成成功',
  1097. ];
  1098. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1099. if ($url) $updateData['url'] = $url;
  1100. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1101. if (is_array($target_roles) && array_key_exists('three_view_image_url', $target_roles)) {
  1102. $updateData['three_view_image_url'] = trim(getProp($target_roles, 'three_view_image_url', ''));
  1103. }
  1104. // 显式传入音色(含空值)时同步写入,空值表示清除该资产的音色
  1105. if (is_array($target_roles) && array_key_exists('timbre_url', $target_roles)) {
  1106. $updateData['timbre_url'] = trim(getProp($target_roles, 'timbre_url', ''));
  1107. }
  1108. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1109. if (is_array($versions)) {
  1110. $updateData['versions'] = json_encode($versions, 256);
  1111. }
  1112. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1113. DB::table('mp_products')
  1114. ->where('id', $existing_product->id)
  1115. ->update($updateData);
  1116. $product_id = $existing_product->id;
  1117. } else {
  1118. // 创建新资产
  1119. $product_id = DB::table('mp_products')->insertGetId([
  1120. 'user_id' => $uid,
  1121. 'cpid' => $cpid,
  1122. 'type' => 1, // 资产
  1123. 'product' => $product_type, // 角色
  1124. 'parent_id' => $folder_id,
  1125. 'level' => 2,
  1126. 'product_name' => $product_name,
  1127. 'url' => $url,
  1128. 'three_view_image_url' => $three_view_image_url,
  1129. 'timbre_url' => $timbre_url,
  1130. 'pic_prompt' => $pic_prompt,
  1131. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1132. 'sort_order' => time(),
  1133. 'is_deleted' => 0,
  1134. 'pic_task_status' => '生成成功',
  1135. 'created_at' => date('Y-m-d H:i:s'),
  1136. 'updated_at' => date('Y-m-d H:i:s')
  1137. ]);
  1138. }
  1139. // 建立或更新绑定关系
  1140. $existing_mapping = DB::table('mp_script_product_mappings')
  1141. ->where('script_id', $script_id)
  1142. ->where('product_id', $product_id)
  1143. ->where('episode_number', $episode_number)
  1144. ->first();
  1145. if (!$existing_mapping) {
  1146. // 创建绑定关系
  1147. DB::table('mp_script_product_mappings')->insert([
  1148. 'script_id' => $script_id,
  1149. 'product_id' => $product_id,
  1150. 'episode_number' => $episode_number,
  1151. 'created_at' => date('Y-m-d H:i:s'),
  1152. 'updated_at' => date('Y-m-d H:i:s')
  1153. ]);
  1154. }
  1155. }
  1156. }
  1157. }
  1158. } catch (\Exception $e) {
  1159. dLog('anime')->error('更新剧集角色失败', [
  1160. 'anime_id' => $anime_id,
  1161. 'episode_id' => $episode_id,
  1162. 'error' => $e->getMessage()
  1163. ]);
  1164. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1165. }
  1166. return true;
  1167. }
  1168. public function changeEpisodeScenes($data) {
  1169. $anime_id = getProp($data, 'anime_id');
  1170. $episode_id = getProp($data, 'episode_id');
  1171. $target_scenes = getProp($data, 'scenes');
  1172. // 删除标志优先取最外层入参 is_deleted,兼容场景对象内部(scenes.is_deleted)的传参
  1173. $is_deleted = getProp($data, 'is_deleted', getProp($target_scenes, 'is_deleted', 0));
  1174. // 控制字段不随场景内容写入分集scenes存储
  1175. if (is_array($target_scenes)) {
  1176. unset($target_scenes['is_deleted']);
  1177. }
  1178. // 参数验证
  1179. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1180. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1181. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1182. // 验证剧集是否存在
  1183. $episode = DB::table('mp_anime_episodes')
  1184. ->where('anime_id', $anime_id)
  1185. ->where('id', $episode_id)
  1186. ->first();
  1187. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1188. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1189. // 获取anime信息,检查是否有关联的script_id
  1190. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1191. if (!$anime) Utils::throwError('20003:动漫不存在');
  1192. $script_id = getProp($anime, 'script_id');
  1193. $episode_number = getProp($episode, 'episode_number', 1);
  1194. $uid = Site::getUid();
  1195. $cpid = Site::getCpid();
  1196. try {
  1197. $target_scene_name = getProp($target_scenes, 'scene');
  1198. if (empty($target_scene_name)) {
  1199. Utils::throwError('20003:场景名称不能为空');
  1200. }
  1201. // 如果是删除操作
  1202. if ($is_deleted == 1) {
  1203. // 从场景列表中移除该场景
  1204. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1205. return getProp($scene, 'scene') !== $target_scene_name;
  1206. }));
  1207. // 更新场景列表
  1208. $result = DB::table('mp_anime_episodes')
  1209. ->where('anime_id', $anime_id)
  1210. ->where('id', $episode_id)
  1211. ->update([
  1212. 'scenes' => json_encode($scenes, 256),
  1213. 'updated_at' => date('Y-m-d H:i:s')
  1214. ]);
  1215. if ($result === false) {
  1216. Utils::throwError('20003:删除场景失败');
  1217. }
  1218. } else {
  1219. // 新增或更新操作
  1220. $scene_found = false;
  1221. $is_new_scene = false;
  1222. // 查找并更新已存在的场景
  1223. foreach($scenes as &$scene) {
  1224. if (getProp($scene, 'scene') === $target_scene_name) {
  1225. $scene = $target_scenes;
  1226. $scene_found = true;
  1227. break;
  1228. }
  1229. }
  1230. // 如果场景不存在,则新增
  1231. if (!$scene_found) {
  1232. $scenes[] = $target_scenes;
  1233. $is_new_scene = true;
  1234. }
  1235. // 更新场景列表
  1236. $result = DB::table('mp_anime_episodes')
  1237. ->where('anime_id', $anime_id)
  1238. ->where('id', $episode_id)
  1239. ->update([
  1240. 'scenes' => json_encode($scenes, 256),
  1241. 'updated_at' => date('Y-m-d H:i:s')
  1242. ]);
  1243. if ($result === false) {
  1244. Utils::throwError('20003:更新场景列表失败');
  1245. }
  1246. // 如果有关联的script_id,则同步到mp_products表
  1247. if ($script_id) {
  1248. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1249. $script = DB::table('mp_scripts')
  1250. ->where('id', $script_id)
  1251. ->where('user_id', $uid)
  1252. ->where('is_deleted', 0)
  1253. ->first();
  1254. if ($script) {
  1255. $script_name = $script->script_name ?? 'script_' . $script_id;
  1256. $product_name = getProp($target_scenes, 'scene');
  1257. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1258. $url = getProp($target_scenes, 'url', '');
  1259. $three_view_image_url = trim(getProp($target_scenes, 'three_view_image_url', ''));
  1260. $timbre_url = trim(getProp($target_scenes, 'timbre_url', ''));
  1261. // 兼容 versions 传入数组或 JSON 字符串
  1262. $versions = getProp($target_scenes, 'versions', null);
  1263. if (is_string($versions) && $versions !== '') {
  1264. $decoded_versions = json_decode($versions, true);
  1265. if (is_array($decoded_versions)) {
  1266. $versions = $decoded_versions;
  1267. }
  1268. }
  1269. $product_type = 2; // 2=场景
  1270. // 查找或创建以script_name命名的文件夹
  1271. $folder = DB::table('mp_products')
  1272. ->where('cpid', $cpid)
  1273. ->where('type', 2) // 文件夹类型
  1274. ->where('product', $product_type) // 场景类型
  1275. ->where('product_name', $script_name)
  1276. ->where('parent_id', 0)
  1277. ->where('is_deleted', 0)
  1278. ->first();
  1279. if (!$folder) {
  1280. // 创建文件夹
  1281. $folder_id = DB::table('mp_products')->insertGetId([
  1282. 'user_id' => $uid,
  1283. 'cpid' => $cpid,
  1284. 'type' => 2, // 文件夹
  1285. 'product' => $product_type, // 场景类型
  1286. 'parent_id' => 0,
  1287. 'level' => 1,
  1288. 'product_name' => $script_name,
  1289. 'sort_order' => time(),
  1290. 'is_deleted' => 0,
  1291. 'created_at' => date('Y-m-d H:i:s'),
  1292. 'updated_at' => date('Y-m-d H:i:s')
  1293. ]);
  1294. } else {
  1295. $folder_id = $folder->id;
  1296. }
  1297. // 查找该文件夹下是否已存在同名资产
  1298. $existing_product = DB::table('mp_products')
  1299. ->where('cpid', $cpid)
  1300. ->where('type', 1) // 资产类型
  1301. ->where('product', $product_type)
  1302. ->where('parent_id', $folder_id)
  1303. ->where('product_name', $product_name)
  1304. ->where('is_deleted', 0)
  1305. ->first();
  1306. if ($existing_product) {
  1307. // 更新已存在的资产
  1308. $updateData = [
  1309. 'pic_task_status' => '生成成功'
  1310. ];
  1311. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1312. if ($url) $updateData['url'] = $url;
  1313. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1314. if (is_array($target_scenes) && array_key_exists('three_view_image_url', $target_scenes)) {
  1315. $updateData['three_view_image_url'] = trim(getProp($target_scenes, 'three_view_image_url', ''));
  1316. }
  1317. // 显式传入音色(含空值)时同步写入,空值表示清除该资产的音色
  1318. if (is_array($target_scenes) && array_key_exists('timbre_url', $target_scenes)) {
  1319. $updateData['timbre_url'] = trim(getProp($target_scenes, 'timbre_url', ''));
  1320. }
  1321. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1322. if (is_array($versions)) {
  1323. $updateData['versions'] = json_encode($versions, 256);
  1324. }
  1325. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1326. DB::table('mp_products')
  1327. ->where('id', $existing_product->id)
  1328. ->update($updateData);
  1329. $product_id = $existing_product->id;
  1330. } else {
  1331. // 创建新资产
  1332. $product_id = DB::table('mp_products')->insertGetId([
  1333. 'user_id' => $uid,
  1334. 'cpid' => $cpid,
  1335. 'type' => 1, // 资产
  1336. 'product' => $product_type, // 场景
  1337. 'parent_id' => $folder_id,
  1338. 'level' => 2,
  1339. 'product_name' => $product_name,
  1340. 'url' => $url,
  1341. 'three_view_image_url' => $three_view_image_url,
  1342. 'timbre_url' => $timbre_url,
  1343. 'pic_prompt' => $pic_prompt,
  1344. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1345. 'sort_order' => time(),
  1346. 'is_deleted' => 0,
  1347. 'pic_task_status' => '生成成功',
  1348. 'created_at' => date('Y-m-d H:i:s'),
  1349. 'updated_at' => date('Y-m-d H:i:s')
  1350. ]);
  1351. }
  1352. // 建立或更新绑定关系
  1353. $existing_mapping = DB::table('mp_script_product_mappings')
  1354. ->where('script_id', $script_id)
  1355. ->where('product_id', $product_id)
  1356. ->where('episode_number', $episode_number)
  1357. ->first();
  1358. if (!$existing_mapping) {
  1359. // 创建绑定关系
  1360. DB::table('mp_script_product_mappings')->insert([
  1361. 'script_id' => $script_id,
  1362. 'product_id' => $product_id,
  1363. 'episode_number' => $episode_number,
  1364. 'created_at' => date('Y-m-d H:i:s'),
  1365. 'updated_at' => date('Y-m-d H:i:s')
  1366. ]);
  1367. }
  1368. }
  1369. }
  1370. }
  1371. } catch (\Exception $e) {
  1372. dLog('anime')->error('更新剧集场景失败', [
  1373. 'anime_id' => $anime_id,
  1374. 'episode_id' => $episode_id,
  1375. 'error' => $e->getMessage()
  1376. ]);
  1377. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1378. }
  1379. return true;
  1380. }
  1381. public function changeEpisodeProps($data) {
  1382. $anime_id = getProp($data, 'anime_id');
  1383. $episode_id = getProp($data, 'episode_id');
  1384. $target_props = getProp($data, 'props');
  1385. // 删除标志优先取最外层入参 is_deleted,兼容道具对象内部(props.is_deleted)的传参
  1386. $is_deleted = getProp($data, 'is_deleted', getProp($target_props, 'is_deleted', 0));
  1387. // 控制字段不随道具内容写入分集props存储
  1388. if (is_array($target_props)) {
  1389. unset($target_props['is_deleted']);
  1390. }
  1391. // 参数验证
  1392. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1393. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1394. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1395. // 验证剧集是否存在
  1396. $episode = DB::table('mp_anime_episodes')
  1397. ->where('anime_id', $anime_id)
  1398. ->where('id', $episode_id)
  1399. ->first();
  1400. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1401. $props = json_decode(getProp($episode, 'props'), true);
  1402. // 获取anime信息,检查是否有关联的script_id
  1403. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1404. if (!$anime) Utils::throwError('20003:动漫不存在');
  1405. $script_id = getProp($anime, 'script_id');
  1406. $episode_number = getProp($episode, 'episode_number', 1);
  1407. $uid = Site::getUid();
  1408. $cpid = Site::getCpid();
  1409. try {
  1410. $target_prop_name = getProp($target_props, 'prop');
  1411. if (empty($target_prop_name)) {
  1412. Utils::throwError('20003:道具名称不能为空');
  1413. }
  1414. // 如果是删除操作
  1415. if ($is_deleted == 1) {
  1416. // 从道具列表中移除该道具
  1417. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1418. return getProp($prop, 'prop') !== $target_prop_name;
  1419. }));
  1420. // 更新道具列表
  1421. $result = DB::table('mp_anime_episodes')
  1422. ->where('anime_id', $anime_id)
  1423. ->where('id', $episode_id)
  1424. ->update([
  1425. 'props' => json_encode($props, 256),
  1426. 'updated_at' => date('Y-m-d H:i:s')
  1427. ]);
  1428. if ($result === false) {
  1429. Utils::throwError('20003:删除道具失败');
  1430. }
  1431. } else {
  1432. // 新增或更新操作
  1433. $prop_found = false;
  1434. $is_new_prop = false;
  1435. // 查找并更新已存在的道具
  1436. foreach($props as &$prop) {
  1437. if (getProp($prop, 'prop') === $target_prop_name) {
  1438. $prop = $target_props;
  1439. $prop_found = true;
  1440. break;
  1441. }
  1442. }
  1443. // 如果道具不存在,则新增
  1444. if (!$prop_found) {
  1445. $props[] = $target_props;
  1446. $is_new_prop = true;
  1447. }
  1448. // 更新道具列表
  1449. $result = DB::table('mp_anime_episodes')
  1450. ->where('anime_id', $anime_id)
  1451. ->where('id', $episode_id)
  1452. ->update([
  1453. 'props' => json_encode($props, 256),
  1454. 'updated_at' => date('Y-m-d H:i:s')
  1455. ]);
  1456. if ($result === false) {
  1457. Utils::throwError('20003:更新道具列表失败');
  1458. }
  1459. // 如果有关联的script_id,则同步到mp_products表
  1460. if ($script_id) {
  1461. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1462. $script = DB::table('mp_scripts')
  1463. ->where('id', $script_id)
  1464. ->where('user_id', $uid)
  1465. ->where('is_deleted', 0)
  1466. ->first();
  1467. if ($script) {
  1468. $script_name = $script->script_name ?? 'script_' . $script_id;
  1469. $product_name = getProp($target_props, 'prop');
  1470. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1471. $url = getProp($target_props, 'url', '');
  1472. $three_view_image_url = trim(getProp($target_props, 'three_view_image_url', ''));
  1473. $timbre_url = trim(getProp($target_props, 'timbre_url', ''));
  1474. // 兼容 versions 传入数组或 JSON 字符串
  1475. $versions = getProp($target_props, 'versions', null);
  1476. if (is_string($versions) && $versions !== '') {
  1477. $decoded_versions = json_decode($versions, true);
  1478. if (is_array($decoded_versions)) {
  1479. $versions = $decoded_versions;
  1480. }
  1481. }
  1482. $product_type = 3; // 3=道具
  1483. // 查找或创建以script_name命名的文件夹
  1484. $folder = DB::table('mp_products')
  1485. ->where('cpid', $cpid)
  1486. ->where('type', 2) // 文件夹类型
  1487. ->where('product', $product_type) // 道具类型
  1488. ->where('product_name', $script_name)
  1489. ->where('parent_id', 0)
  1490. ->where('is_deleted', 0)
  1491. ->first();
  1492. if (!$folder) {
  1493. // 创建文件夹
  1494. $folder_id = DB::table('mp_products')->insertGetId([
  1495. 'user_id' => $uid,
  1496. 'cpid' => $cpid,
  1497. 'type' => 2, // 文件夹
  1498. 'product' => $product_type, // 道具类型
  1499. 'parent_id' => 0,
  1500. 'level' => 1,
  1501. 'product_name' => $script_name,
  1502. 'sort_order' => time(),
  1503. 'is_deleted' => 0,
  1504. 'created_at' => date('Y-m-d H:i:s'),
  1505. 'updated_at' => date('Y-m-d H:i:s')
  1506. ]);
  1507. } else {
  1508. $folder_id = $folder->id;
  1509. }
  1510. // 查找该文件夹下是否已存在同名资产
  1511. $existing_product = DB::table('mp_products')
  1512. ->where('cpid', $cpid)
  1513. ->where('type', 1) // 资产类型
  1514. ->where('product', $product_type)
  1515. ->where('parent_id', $folder_id)
  1516. ->where('product_name', $product_name)
  1517. ->where('is_deleted', 0)
  1518. ->first();
  1519. if ($existing_product) {
  1520. // 更新已存在的资产
  1521. $updateData = [
  1522. 'pic_task_status' => '生成成功'
  1523. ];
  1524. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1525. if ($url) $updateData['url'] = $url;
  1526. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1527. if (is_array($target_props) && array_key_exists('three_view_image_url', $target_props)) {
  1528. $updateData['three_view_image_url'] = trim(getProp($target_props, 'three_view_image_url', ''));
  1529. }
  1530. // 显式传入音色(含空值)时同步写入,空值表示清除该资产的音色
  1531. if (is_array($target_props) && array_key_exists('timbre_url', $target_props)) {
  1532. $updateData['timbre_url'] = trim(getProp($target_props, 'timbre_url', ''));
  1533. }
  1534. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1535. if (is_array($versions)) {
  1536. $updateData['versions'] = json_encode($versions, 256);
  1537. }
  1538. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1539. DB::table('mp_products')
  1540. ->where('id', $existing_product->id)
  1541. ->update($updateData);
  1542. $product_id = $existing_product->id;
  1543. } else {
  1544. // 创建新资产
  1545. $product_id = DB::table('mp_products')->insertGetId([
  1546. 'user_id' => $uid,
  1547. 'cpid' => $cpid,
  1548. 'type' => 1, // 资产
  1549. 'product' => $product_type, // 道具
  1550. 'parent_id' => $folder_id,
  1551. 'level' => 2,
  1552. 'product_name' => $product_name,
  1553. 'url' => $url,
  1554. 'three_view_image_url' => $three_view_image_url,
  1555. 'timbre_url' => $timbre_url,
  1556. 'pic_prompt' => $pic_prompt,
  1557. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1558. 'sort_order' => time(),
  1559. 'is_deleted' => 0,
  1560. 'pic_task_status' => '生成成功',
  1561. 'created_at' => date('Y-m-d H:i:s'),
  1562. 'updated_at' => date('Y-m-d H:i:s')
  1563. ]);
  1564. }
  1565. // 建立或更新绑定关系
  1566. $existing_mapping = DB::table('mp_script_product_mappings')
  1567. ->where('script_id', $script_id)
  1568. ->where('product_id', $product_id)
  1569. ->where('episode_number', $episode_number)
  1570. ->first();
  1571. if (!$existing_mapping) {
  1572. // 创建绑定关系
  1573. DB::table('mp_script_product_mappings')->insert([
  1574. 'script_id' => $script_id,
  1575. 'product_id' => $product_id,
  1576. 'episode_number' => $episode_number,
  1577. 'created_at' => date('Y-m-d H:i:s'),
  1578. 'updated_at' => date('Y-m-d H:i:s')
  1579. ]);
  1580. }
  1581. }
  1582. }
  1583. }
  1584. } catch (\Exception $e) {
  1585. dLog('anime')->error('更新剧集道具失败', [
  1586. 'anime_id' => $anime_id,
  1587. 'episode_id' => $episode_id,
  1588. 'error' => $e->getMessage()
  1589. ]);
  1590. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1591. }
  1592. return true;
  1593. }
  1594. public function editSegment($data) {
  1595. $segment_id = getProp($data, 'segment_id');
  1596. $segment_content = getProp($data, 'segment_content');
  1597. $image_url = getProp($data, 'image_url');
  1598. $video_url = getProp($data, 'video_url');
  1599. // 参数验证
  1600. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1601. // 验证分镜是否存在
  1602. $segment = DB::table('mp_episode_segments')
  1603. ->where('segment_id', $segment_id)
  1604. ->first();
  1605. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1606. $dubTaskId = 0;
  1607. try {
  1608. DB::beginTransaction();
  1609. // 准备更新数据
  1610. $update_data = [
  1611. 'updated_at' => date('Y-m-d H:i:s')
  1612. ];
  1613. if ($segment_content) {
  1614. // 先将segment_content赋值到update_data
  1615. $update_data['segment_content'] = $segment_content;
  1616. // 使用现有方法分析segment_content,提取各个字段
  1617. $this->handleSegmentContent($update_data);
  1618. // 如果有对话内容,创建视频配音合成任务
  1619. $dialogue = getProp($update_data, 'dialogue');
  1620. if (!empty($dialogue)) {
  1621. $now = date('Y-m-d H:i:s');
  1622. $generate_json = [
  1623. 'text' => $dialogue,
  1624. 'role' => getProp($update_data, 'voice_actor'),
  1625. 'voice_type' => getProp($update_data, 'voice_type'),
  1626. 'voice_name' => getProp($update_data, 'voice_name'),
  1627. 'emotion' => getProp($update_data, 'emotion'),
  1628. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1629. 'gender' => getProp($update_data, 'gender'),
  1630. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1631. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1632. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1633. 'pitch' => getProp($update_data, 'pitch', 0),
  1634. ];
  1635. // 插入视频配音合成任务
  1636. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1637. 'alias_segment_id' => $segment_id,
  1638. 'generate_status' => '执行中',
  1639. 'audio_url' => '',
  1640. 'generate_json' => json_encode($generate_json, 256),
  1641. 'created_at' => $now,
  1642. 'updated_at' => $now,
  1643. ]);
  1644. if (!$dubTaskId) {
  1645. Utils::throwError('20003:创建配音任务失败!');
  1646. }
  1647. $update_data['audio_url'] = '';
  1648. } else {
  1649. // dialogue为空时,直接写入默认音频信息
  1650. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1651. $update_data['audio_duration'] = 2.0;
  1652. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1653. }
  1654. }
  1655. if ($image_url) {
  1656. $update_data['img_url'] = $image_url;
  1657. // 同时写入一个简单的图片生成任务
  1658. $pic_task = [
  1659. 'alias_segment_id' => $segment_id,
  1660. 'ref_img_url' => json_encode([]),
  1661. 'status' => 'success',
  1662. 'result_url' => json_encode([$image_url], 256),
  1663. 'model' => '',
  1664. 'created_at' => date('Y-m-d H:i:s'),
  1665. 'updated_at' => date('Y-m-d H:i:s'),
  1666. ];
  1667. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1668. }
  1669. if ($video_url) {
  1670. $update_data['origin_video_url'] = $video_url;
  1671. $compressed_video_url = compressVideo($video_url);
  1672. $update_data['current_type'] = 2;
  1673. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1674. // 同时写入一个简单的视频生成任务
  1675. $video_task = [
  1676. 'alias_segment_id' => $segment_id,
  1677. 'status' => 'success',
  1678. 'result_url' => $update_data['origin_video_url'],
  1679. 'compressed_url' => $update_data['video_url'],
  1680. 'created_at' => date('Y-m-d H:i:s'),
  1681. 'updated_at' => date('Y-m-d H:i:s'),
  1682. ];
  1683. DB::table('mp_generate_video_tasks')->insert($video_task);
  1684. }
  1685. // 更新分镜信息
  1686. $result = DB::table('mp_episode_segments')
  1687. ->where('segment_id', $segment_id)
  1688. ->update($update_data);
  1689. if ($result === false) {
  1690. Utils::throwError('20003:更新分镜剧本失败');
  1691. }
  1692. DB::commit();
  1693. // 如果有创建音频生成任务则调用API
  1694. if ($dubTaskId) {
  1695. // 请求远程服务器执行生成
  1696. $client = new Client(['timeout' => 300, 'verify' => false]);
  1697. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1698. $response = $result->getBody()->getContents();
  1699. $response_arr = json_decode($response, true);
  1700. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1701. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1702. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1703. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1704. Utils::throwError('20003:火山生成音频失败');
  1705. }
  1706. }
  1707. return true;
  1708. } catch (\Exception $e) {
  1709. DB::rollBack();
  1710. dLog('anime')->error('更新分镜剧本失败', [
  1711. 'segment_id' => $segment_id,
  1712. 'error' => $e->getMessage()
  1713. ]);
  1714. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1715. }
  1716. }
  1717. public function batchSetSegmentPics($data) {
  1718. $anime_id = getProp($data, 'anime_id');
  1719. $episode_id = getProp($data, 'episode_id');
  1720. $ratio = getProp($data, 'ratio');
  1721. $dimensions = $this->getRatioDimensions($ratio);
  1722. $width = $dimensions['width'];
  1723. $height = $dimensions['height'];
  1724. if (!$anime_id || !$episode_id) {
  1725. Utils::throwError('1002:请选择剧集');
  1726. }
  1727. // 获取剧集信息
  1728. $episode = DB::table('mp_anime_episodes')
  1729. ->where('anime_id', $anime_id)
  1730. ->where('id', $episode_id)
  1731. ->where('is_default', 1)
  1732. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1733. ->first();
  1734. if (!$episode) {
  1735. Utils::throwError('20003:该剧集不存在');
  1736. }
  1737. $model = getProp($data, 'model');
  1738. if (!$model) {
  1739. $model = getProp($episode, 'image_model');
  1740. if (!$model) {
  1741. // episode表也没有,使用默认值
  1742. $model = 'gpt-image-2';
  1743. }
  1744. }
  1745. // 验证模型是否在可用模型表中
  1746. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1747. $model = 'gpt-image-2';
  1748. }
  1749. $roles = json_decode(getProp($episode, 'roles'), true);
  1750. if (!$roles) {
  1751. Utils::throwError('20003:角色信息格式错误');
  1752. }
  1753. // 构建角色名称到参考图的映射
  1754. $role_map = [];
  1755. foreach ($roles as $role) {
  1756. $role_name = getProp($role, 'role');
  1757. $role_url = getProp($role, 'url');
  1758. if (!empty($role_name) && !empty($role_url)) {
  1759. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1760. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1761. // $role_map[$base_name] = $role_url;
  1762. // 同时保存完整名称的映射
  1763. $role_map[$role_name] = $role_url;
  1764. }
  1765. }
  1766. $scenes = json_decode(getProp($episode, 'roles'), true);
  1767. if (!$scenes) {
  1768. Utils::throwError('20003:场景信息格式错误');
  1769. }
  1770. // 构建角色名称到参考图的映射
  1771. $scene_map = [];
  1772. foreach ($scenes as $scene) {
  1773. $scene_name = getProp($scene, 'scene');
  1774. $scene_url = getProp($scene, 'url');
  1775. if (!empty($scene_name) && !empty($scene_url)) {
  1776. $scene_map[$scene_name] = $scene_url;
  1777. }
  1778. }
  1779. // 获取所有分镜信息
  1780. $segments = DB::table('mp_episode_segments')
  1781. ->where('anime_id', $anime_id)
  1782. ->where('episode_id', $episode_id)
  1783. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1784. ->orderBy('segment_number')
  1785. ->get()
  1786. ->toArray();
  1787. if (empty($segments)) {
  1788. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1789. }
  1790. // 保存图片比例
  1791. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1792. $updated_segments = [];
  1793. $failed_segments = [];
  1794. // 批量为每个分镜生成图片任务
  1795. foreach ($segments as $segment) {
  1796. $segment_id = $segment->segment_id;
  1797. $segment_content = $segment->segment_content;
  1798. if (empty($segment_content)) {
  1799. $failed_segments[] = [
  1800. 'segment_id' => $segment_id,
  1801. 'error' => '分镜内容为空'
  1802. ];
  1803. continue;
  1804. }
  1805. try {
  1806. $dubTaskId = 0;
  1807. // 解析分镜内容,提取画面描述作为主要提示词
  1808. $prompt = $segment_content;
  1809. $ref_img_urls = [];
  1810. // 分镜场景
  1811. $scene = getProp($segment, 'scene');
  1812. $matched_scene = '';
  1813. if (isset($scene_map[$scene])) {
  1814. $img_index = count($ref_img_urls) + 1;
  1815. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1816. $ref_img_urls[] = $scene_map[$scene];
  1817. $matched_scene = $scene;
  1818. }
  1819. // 分镜角色
  1820. $characters = getProp($segment, 'characters');
  1821. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1822. $roles = explode(',', $characters);
  1823. // 从分镜内容中提取涉及的角色
  1824. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1825. // 获取匹配角色的参考图
  1826. foreach ($segment_characters as $character) {
  1827. if (isset($role_map[$character])) {
  1828. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1829. $img_index = count($ref_img_urls) + 1;
  1830. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1831. $ref_img_urls[] = $role_map[$character];
  1832. }
  1833. }
  1834. // 如果没有找到匹配的角色参考图,不使用参考图
  1835. if (empty($ref_img_urls)) {
  1836. $ref_img_urls = [];
  1837. }
  1838. // 准备生成任务参数
  1839. $params = [
  1840. 'model' => $model,
  1841. 'alias_segment_id' => $segment_id,
  1842. 'prompt' => $prompt,
  1843. 'ref_img_urls' => $ref_img_urls,
  1844. 'width' => $width,
  1845. 'height' => $height,
  1846. ];
  1847. // 优化提示词(不要生成字幕)
  1848. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1849. // $task_id = mt_rand(100000, 999999);
  1850. // 调用AI图片生成服务
  1851. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1852. $task_id = $task->id;
  1853. if (!$task_id) {
  1854. $failed_segments[] = [
  1855. 'segment_id' => $segment_id,
  1856. 'error' => '创建生成任务失败'
  1857. ];
  1858. continue;
  1859. }
  1860. $update_data = [
  1861. 'pic_task_id' => $task_id,
  1862. 'pic_task_status' => '生成中',
  1863. 'audio_url' => '',
  1864. 'updated_at' => date('Y-m-d H:i:s')
  1865. ];
  1866. // 如果有对话内容,创建视频配音合成任务
  1867. $dialogue = getProp($segment, 'dialogue');
  1868. if (!empty($dialogue)) {
  1869. $now = date('Y-m-d H:i:s');
  1870. $generate_json = [
  1871. 'text' => $dialogue,
  1872. 'role' => getProp($segment, 'voice_actor'),
  1873. 'voice_type' => getProp($segment, 'voice_type'),
  1874. 'voice_name' => getProp($segment, 'voice_name'),
  1875. 'emotion' => getProp($segment, 'emotion'),
  1876. 'emotion_type' => getProp($segment, 'emotion_type'),
  1877. 'gender' => getProp($segment, 'gender'),
  1878. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1879. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1880. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1881. 'pitch' => getProp($segment, 'pitch', 0),
  1882. ];
  1883. // 插入视频配音合成任务
  1884. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1885. 'alias_segment_id' => $segment_id,
  1886. 'generate_status' => '执行中',
  1887. 'audio_url' => '',
  1888. 'generate_json' => json_encode($generate_json, 256),
  1889. 'created_at' => $now,
  1890. 'updated_at' => $now,
  1891. ]);
  1892. if (!$dubTaskId) {
  1893. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1894. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1895. // Utils::throwError('20003:创建配音任务失败!');
  1896. }
  1897. } else {
  1898. // dialogue为空时,直接写入默认音频信息到分镜表
  1899. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1900. $update_data['audio_duration'] = 2.0;
  1901. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1902. }
  1903. // 更新分镜的任务信息
  1904. $update_result = DB::table('mp_episode_segments')
  1905. ->where('segment_id', $segment_id)
  1906. ->update($update_data);
  1907. // 如果是第一集的首帧图片,则存入待更新数组
  1908. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1909. Redis::sadd('anime_first_frame_urls', $segment_id);
  1910. }
  1911. if ($update_result) {
  1912. $updated_segments[] = [
  1913. 'segment_id' => $segment_id,
  1914. 'task_id' => $task_id,
  1915. 'status' => '生成中',
  1916. 'matched_scenes' => $matched_scene,
  1917. 'matched_roles' => $segment_characters,
  1918. 'ref_urls_count' => count($ref_img_urls)
  1919. ];
  1920. } else {
  1921. $failed_segments[] = [
  1922. 'segment_id' => $segment_id,
  1923. 'error' => '更新分镜任务状态失败'
  1924. ];
  1925. }
  1926. if ($dubTaskId) {
  1927. sleep(1);
  1928. // 请求远程服务器执行生成
  1929. $client = new Client(['timeout' => 300, 'verify' => false]);
  1930. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1931. $response = $result->getBody()->getContents();
  1932. $response_arr = json_decode($response, true);
  1933. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1934. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1935. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1936. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1937. }
  1938. }
  1939. } catch (\Exception $e) {
  1940. $failed_segments[] = [
  1941. 'segment_id' => $segment_id,
  1942. 'error' => $e->getMessage()
  1943. ];
  1944. }
  1945. }
  1946. // 更新剧集生成状态
  1947. if (!empty($updated_segments)) {
  1948. DB::table('mp_anime_episodes')
  1949. ->where('id', $episode_id)
  1950. ->update([
  1951. 'is_generated' => 1,
  1952. 'updated_at' => date('Y-m-d H:i:s')
  1953. ]);
  1954. }
  1955. return [
  1956. 'success_count' => count($updated_segments),
  1957. 'failed_count' => count($failed_segments),
  1958. 'success_segments' => $updated_segments,
  1959. 'failed_segments' => $failed_segments,
  1960. 'total_segments' => count($segments)
  1961. ];
  1962. }
  1963. public function reGenerateSegment($data) {
  1964. $segment_id = getProp($data, 'segment_id');
  1965. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1966. $anime_id = getProp($segment, 'anime_id');
  1967. $episode_id = getProp($segment, 'episode_id');
  1968. $episode_number = getProp($segment, 'episode_number');
  1969. $segment_content = getProp($data, 'segment_content');
  1970. $ratio = getProp($data, 'ratio');
  1971. if (!$ratio) {
  1972. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1973. if (!$ratio) $ratio = '9:16';
  1974. }
  1975. $dimensions = $this->getRatioDimensions($ratio);
  1976. $width = $dimensions['width'];
  1977. $height = $dimensions['height'];
  1978. if (!$anime_id || !$episode_id) {
  1979. Utils::throwError('1002:请选择分镜');
  1980. }
  1981. // 使用文生文模型重新解析segment_content
  1982. if (!empty($segment_content)) {
  1983. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1984. }
  1985. // 获取动漫的角色信息(包含参考图)
  1986. $anime = DB::table('mp_animes')
  1987. ->where('id', $anime_id)
  1988. ->select('roles', 'scenes')
  1989. ->first();
  1990. if (!$anime || !$anime->roles) {
  1991. Utils::throwError('20003:未找到角色信息');
  1992. }
  1993. $roles = json_decode($anime->roles, true);
  1994. if (!$roles) {
  1995. Utils::throwError('20003:角色信息格式错误');
  1996. }
  1997. // 构建角色名称到参考图的映射
  1998. $role_map = [];
  1999. foreach ($roles as $role) {
  2000. $role_name = getProp($role, 'role');
  2001. $role_url = getProp($role, 'url');
  2002. if (!empty($role_name) && !empty($role_url)) {
  2003. $role_map[$role_name] = $role_url;
  2004. }
  2005. }
  2006. $scenes = json_decode($anime->scenes, true);
  2007. if (!$scenes) {
  2008. Utils::throwError('20003:角色信息格式错误');
  2009. }
  2010. // 构建角色名称到参考图的映射
  2011. $scene_map = [];
  2012. foreach ($scenes as $scene) {
  2013. $scene_name = getProp($scene, 'scene');
  2014. $scene_url = getProp($scene, 'url');
  2015. if (!empty($scene_name) && !empty($scene_url)) {
  2016. $scene_map[$scene_name] = $scene_url;
  2017. }
  2018. }
  2019. $segment_id = $segment->segment_id;
  2020. $original_segment_content = $segment->segment_content;
  2021. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2022. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2023. if (empty($final_segment_content)) {
  2024. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2025. }
  2026. try {
  2027. $dubTaskId = 0;
  2028. // 分镜剧本数组
  2029. $update_data = [
  2030. 'segment_content' => $final_segment_content,
  2031. 'pic_task_status' => '生成中',
  2032. 'updated_at' => date('Y-m-d H:i:s')
  2033. ];
  2034. // 解析分镜内容,提取画面描述作为主要提示词
  2035. $prompt = $final_segment_content;
  2036. $ref_img_urls = [];
  2037. // 分镜场景
  2038. $scene = getProp($data, 'scene');
  2039. if ($scene) {
  2040. $matched_scene = '';
  2041. if (isset($scene_map[$scene])) {
  2042. $img_index = count($ref_img_urls) + 1;
  2043. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2044. $ref_img_urls[] = $scene_map[$scene];
  2045. $matched_scene = $scene;
  2046. }
  2047. $update_data['scene'] = $scene;
  2048. }
  2049. // 分镜角色
  2050. $characters = getProp($data, 'characters');
  2051. if ($characters) {
  2052. $update_data['characters'] = $characters;
  2053. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2054. $characters = explode(',', $characters);
  2055. // 从分镜内容中提取涉及的角色
  2056. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2057. // 获取匹配角色的参考图
  2058. foreach ($segment_characters as $character) {
  2059. if (isset($role_map[$character])) {
  2060. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2061. $img_index = count($ref_img_urls) + 1;
  2062. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2063. $ref_img_urls[] = $role_map[$character];
  2064. }
  2065. }
  2066. }
  2067. // 如果没有找到匹配的角色参考图,不使用参考图
  2068. if (empty($ref_img_urls)) {
  2069. $ref_img_urls = [];
  2070. }
  2071. // 准备生成任务参数
  2072. $params = [
  2073. 'alias_segment_id' => $segment_id,
  2074. 'prompt' => $prompt,
  2075. 'ref_img_urls' => $ref_img_urls,
  2076. 'width' => $width,
  2077. 'height' => $height,
  2078. ];
  2079. // 优化提示词(不要生成字幕)
  2080. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  2081. // 调用AI图片生成服务
  2082. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2083. $task_id = $task->id;
  2084. if (!$task_id) {
  2085. Utils::throwError('20003:创建生成任务失败!');
  2086. }
  2087. $update_data['pic_task_id'] = $task_id;
  2088. // 更新分镜剧本信息
  2089. $this->handleSegmentContent($update_data);
  2090. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2091. if ($segment_content) {
  2092. $dialogue = getProp($update_data, 'dialogue');
  2093. if (!empty($dialogue)) {
  2094. $now = date('Y-m-d H:i:s');
  2095. $generate_json = [
  2096. 'text' => $dialogue,
  2097. 'role' => getProp($update_data, 'voice_actor'),
  2098. 'voice_type' => getProp($update_data, 'voice_type'),
  2099. 'voice_name' => getProp($update_data, 'voice_name'),
  2100. 'emotion' => getProp($update_data, 'emotion'),
  2101. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2102. 'gender' => getProp($update_data, 'gender'),
  2103. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2104. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2105. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2106. 'pitch' => getProp($update_data, 'pitch', 0),
  2107. ];
  2108. // 插入视频配音合成任务
  2109. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2110. 'alias_segment_id' => $segment_id,
  2111. 'generate_status' => '执行中',
  2112. 'audio_url' => '',
  2113. 'generate_json' => json_encode($generate_json, 256),
  2114. 'created_at' => date('Y-m-d H:i:s'),
  2115. 'updated_at' => date('Y-m-d H:i:s'),
  2116. ]);
  2117. if (!$dubTaskId) {
  2118. Utils::throwError('20003:创建配音任务失败!');
  2119. }
  2120. $update_data['audio_url'] = '';
  2121. } else {
  2122. // dialogue为空时,直接写入默认音频信息
  2123. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2124. $update_data['audio_duration'] = 2.0;
  2125. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2126. }
  2127. }
  2128. $boolen = DB::table('mp_episode_segments')
  2129. ->where('segment_id', $segment_id)
  2130. ->update($update_data);
  2131. // 如果是第一集的首帧图片,则存入待更新数组
  2132. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2133. Redis::sadd('anime_first_frame_urls', $segment_id);
  2134. }
  2135. if ($dubTaskId) {
  2136. // 请求远程服务器执行生成
  2137. $client = new Client(['timeout' => 300, 'verify' => false]);
  2138. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2139. $response = $result->getBody()->getContents();
  2140. $response_arr = json_decode($response, true);
  2141. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2142. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2143. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2144. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2145. Utils::throwError('20003:火山生成音频失败');
  2146. }
  2147. }
  2148. } catch (\Exception $e) {
  2149. $failed_segments[] = [
  2150. 'segment_id' => $segment_id,
  2151. 'error' => $e->getMessage()
  2152. ];
  2153. }
  2154. // 创建任务之后先暂停10s等待异步任务完成
  2155. sleep(10);
  2156. $img_url = $this->loopGetPicTaskResult($task_id);
  2157. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2158. // 图片生成后新增对话记录
  2159. try {
  2160. $uid = Site::getUid();
  2161. $now = date('Y-m-d H:i:s');
  2162. // 使用AI反推图片提示词
  2163. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2164. // 保存对话记录
  2165. $records = [
  2166. [
  2167. 'uid' => $uid,
  2168. 'anime_id' => $anime_id,
  2169. 'sequence' => $episode_number,
  2170. 'role' => 'user',
  2171. 'content' => '重新生成',
  2172. 'segment_id' => $segment_id,
  2173. 'pic_task_id' => $task_id,
  2174. 'image_url' => '',
  2175. 'created_at' => $now,
  2176. 'updated_at' => $now
  2177. ],
  2178. [
  2179. 'uid' => $uid,
  2180. 'anime_id' => $anime_id,
  2181. 'sequence' => $episode_number,
  2182. 'role' => 'assistant',
  2183. 'content' => $pic_prompt,
  2184. 'segment_id' => $segment_id,
  2185. 'pic_task_id' => $task_id,
  2186. 'image_url' => $img_url,
  2187. 'created_at' => $now,
  2188. 'updated_at' => $now
  2189. ]
  2190. ];
  2191. DB::table('mp_anime_records')->insert($records);
  2192. } catch (\Exception $e) {
  2193. // 记录日志但不影响主流程
  2194. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2195. 'segment_id' => $segment_id,
  2196. 'img_url' => $img_url
  2197. ]);
  2198. }
  2199. return $img_url;
  2200. }
  2201. public function addSegment($data) {
  2202. $prev_segment_id = getProp($data, 'prev_segment_id');
  2203. $img_url = getProp($data, 'img_url');
  2204. $video_url = getProp($data, 'video_url');
  2205. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2206. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2207. $anime_id = getProp($segment, 'anime_id');
  2208. $episode_id = getProp($segment, 'episode_id');
  2209. $episode_number = getProp($segment, 'episode_number');
  2210. $segment_number = getProp($segment, 'segment_number');
  2211. $new_segment_number = $segment_number + 1;
  2212. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2213. // 分镜剧本数组
  2214. $insert_data = [
  2215. 'anime_id' => $anime_id,
  2216. 'episode_id' => $episode_id,
  2217. 'episode_number' => $episode_number,
  2218. 'act_number' => getProp($segment, 'act_number'),
  2219. 'act_title' => getProp($segment, 'act_title'),
  2220. 'segment_id' => $segment_id,
  2221. 'segment_number' => $new_segment_number,
  2222. 'segment_content' => '',
  2223. 'img_url' => '',
  2224. 'video_url' => '',
  2225. 'created_at' => date('Y-m-d H:i:s'),
  2226. 'updated_at' => date('Y-m-d H:i:s')
  2227. ];
  2228. if ($img_url) $insert_data['img_url'] = $img_url;
  2229. if ($video_url) {
  2230. $insert_data['origin_video_url'] = $video_url;
  2231. $insert_data['current_type'] = 2;
  2232. $compressed_video_url = compressVideo($video_url);
  2233. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2234. }
  2235. try {
  2236. DB::beginTransaction();
  2237. // 先更新序号
  2238. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2239. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2240. if (!$id) {
  2241. Utils::throwError('20003:新增分镜失败!');
  2242. }
  2243. }catch (\Exception $e) {
  2244. DB::rollBack();
  2245. Utils::throwError('20003:'.$e->getMessage());
  2246. }
  2247. DB::commit();
  2248. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2249. $segment = $segment ? (array)$segment : [];
  2250. return $segment;
  2251. // 以下代码暂弃用
  2252. $anime_id = getProp($segment, 'anime_id');
  2253. $episode_id = getProp($segment, 'episode_id');
  2254. $episode_number = getProp($segment, 'episode_number');
  2255. $segment_number = getProp($segment, 'segment_number');
  2256. $segment_content = getProp($data, 'segment_content');
  2257. $img_url = getProp($data, 'img_url');
  2258. $video_url = getProp($data, 'video_url');
  2259. $ratio = getProp($data, 'ratio');
  2260. $dimensions = $this->getRatioDimensions($ratio);
  2261. $width = $dimensions['width'];
  2262. $height = $dimensions['height'];
  2263. if (!$anime_id || !$episode_id) {
  2264. Utils::throwError('1002:请选择分镜');
  2265. }
  2266. // 使用文生文模型重新解析segment_content
  2267. if (!empty($segment_content)) {
  2268. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2269. }
  2270. // 获取动漫的角色信息(包含参考图)
  2271. $anime = DB::table('mp_animes')
  2272. ->where('id', $anime_id)
  2273. ->select('roles', 'scenes')
  2274. ->first();
  2275. if (!$anime || !$anime->roles) {
  2276. Utils::throwError('20003:未找到角色信息');
  2277. }
  2278. $roles = json_decode($anime->roles, true);
  2279. if (!$roles) {
  2280. Utils::throwError('20003:角色信息格式错误');
  2281. }
  2282. // 构建角色名称到参考图的映射
  2283. $role_map = [];
  2284. foreach ($roles as $role) {
  2285. $role_name = getProp($role, 'role');
  2286. $role_url = getProp($role, 'url');
  2287. if (!empty($role_name) && !empty($role_url)) {
  2288. $role_map[$role_name] = $role_url;
  2289. }
  2290. }
  2291. $scenes = json_decode($anime->scenes, true);
  2292. if (!$scenes) {
  2293. Utils::throwError('20003:角色信息格式错误');
  2294. }
  2295. // 构建角色名称到参考图的映射
  2296. $scene_map = [];
  2297. foreach ($scenes as $scene) {
  2298. $scene_name = getProp($scene, 'scene');
  2299. $scene_url = getProp($scene, 'url');
  2300. if (!empty($scene_name) && !empty($scene_url)) {
  2301. $scene_map[$scene_name] = $scene_url;
  2302. }
  2303. }
  2304. $segment_id = $segment->segment_id;
  2305. $original_segment_content = $segment->segment_content;
  2306. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2307. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2308. if (empty($final_segment_content)) {
  2309. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2310. }
  2311. try {
  2312. $dubTaskId = 0;
  2313. DB::beginTransaction();
  2314. $new_segment_number = $segment_number + 1;
  2315. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2316. // 分镜剧本数组
  2317. $insert_data = [
  2318. 'anime_id' => $anime_id,
  2319. 'episode_id' => $episode_id,
  2320. 'episode_number' => $episode_number,
  2321. 'act_number' => getProp($segment, 'act_number'),
  2322. 'act_title' => getProp($segment, 'act_title'),
  2323. 'segment_id' => $segment_id,
  2324. 'segment_number' => $new_segment_number,
  2325. 'segment_content' => $final_segment_content,
  2326. 'img_url' => $img_url,
  2327. 'video_url' => $video_url,
  2328. 'created_at' => date('Y-m-d H:i:s'),
  2329. 'updated_at' => date('Y-m-d H:i:s')
  2330. ];
  2331. // 更新分镜剧本信息
  2332. $this->handleSegmentContent($insert_data);
  2333. // 如果有对话内容,创建视频配音合成任务
  2334. $dialogue = getProp($insert_data, 'dialogue');
  2335. if (!empty($dialogue)) {
  2336. $now = date('Y-m-d H:i:s');
  2337. $generate_json = [
  2338. 'text' => $dialogue,
  2339. 'role' => getProp($insert_data, 'voice_actor'),
  2340. 'voice_type' => getProp($insert_data, 'voice_type'),
  2341. 'voice_name' => getProp($insert_data, 'voice_name'),
  2342. 'emotion' => getProp($insert_data, 'emotion'),
  2343. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2344. 'gender' => getProp($insert_data, 'gender'),
  2345. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2346. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2347. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2348. 'pitch' => getProp($insert_data, 'pitch', 0),
  2349. ];
  2350. // 插入视频配音合成任务
  2351. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2352. 'alias_segment_id' => $segment_id,
  2353. 'generate_status' => '执行中',
  2354. 'audio_url' => '',
  2355. 'generate_json' => json_encode($generate_json, 256),
  2356. 'created_at' => $now,
  2357. 'updated_at' => $now,
  2358. ]);
  2359. if (!$dubTaskId) {
  2360. Utils::throwError('20003:创建配音任务失败!');
  2361. }
  2362. $insert_data['audio_url'] = '';
  2363. } else {
  2364. // dialogue为空时,直接写入默认音频信息
  2365. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2366. $insert_data['audio_duration'] = 2.0;
  2367. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2368. }
  2369. // 如果没有上传图片则使用当前描述进行生成
  2370. if (!$img_url) {
  2371. // 解析分镜内容,提取画面描述作为主要提示词
  2372. $prompt = $final_segment_content;
  2373. $ref_img_urls = [];
  2374. // 分镜场景
  2375. $scene = getProp($insert_data, 'scene');
  2376. if ($scene) {
  2377. $matched_scene = '';
  2378. if (isset($scene_map[$scene])) {
  2379. $img_index = count($ref_img_urls) + 1;
  2380. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2381. $ref_img_urls[] = $scene_map[$scene];
  2382. $matched_scene = $scene;
  2383. }
  2384. $update_data['scene'] = $scene;
  2385. }
  2386. // 分镜角色
  2387. $characters = getProp($insert_data, 'characters');
  2388. if ($characters) {
  2389. $update_data['characters'] = $characters;
  2390. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2391. $characters = explode(',', $characters);
  2392. // 从分镜内容中提取涉及的角色
  2393. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2394. // 获取匹配角色的参考图
  2395. foreach ($segment_characters as $character) {
  2396. if (isset($role_map[$character])) {
  2397. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2398. $img_index = count($ref_img_urls) + 1;
  2399. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2400. $ref_img_urls[] = $role_map[$character];
  2401. }
  2402. }
  2403. }
  2404. // 如果没有找到匹配的角色参考图,不使用参考图
  2405. if (empty($ref_img_urls)) {
  2406. $ref_img_urls = [];
  2407. }
  2408. // 准备生成任务参数
  2409. $params = [
  2410. 'alias_segment_id' => $segment_id,
  2411. 'prompt' => $prompt,
  2412. 'ref_img_urls' => $ref_img_urls,
  2413. 'width' => $width,
  2414. 'height' => $height,
  2415. ];
  2416. // 调用AI图片生成服务
  2417. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2418. $task_id = $task->id;
  2419. // $task_id = 'whatever';
  2420. if (!$task_id) {
  2421. Utils::throwError('20003:创建生成任务失败!');
  2422. }
  2423. $insert_data['pic_task_status'] = '生成中';
  2424. $insert_data['pic_task_id'] = $task_id;
  2425. }
  2426. // 先更新序号
  2427. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2428. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2429. if (!$boolen) {
  2430. Utils::throwError('20003:新增分镜失败!');
  2431. }
  2432. // 如果是第一集的首帧图片,则存入待更新数组
  2433. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2434. Redis::sadd('anime_first_frame_urls', $segment_id);
  2435. }
  2436. if ($dubTaskId) {
  2437. // 请求远程服务器执行生成
  2438. $client = new Client(['timeout' => 300, 'verify' => false]);
  2439. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2440. $response = $result->getBody()->getContents();
  2441. $response_arr = json_decode($response, true);
  2442. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2443. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2444. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2445. Utils::throwError('20003:火山生成音频失败');
  2446. }
  2447. }
  2448. } catch (\Exception $e) {
  2449. DB::rollBack();
  2450. Utils::throwError('20003:'.$e->getMessage());
  2451. }
  2452. DB::commit();
  2453. // 创建任务之后先暂停10s等待异步任务完成
  2454. sleep(10);
  2455. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2456. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2457. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2458. $segment = $segment ? (array)$segment : [];
  2459. return $segment;
  2460. }
  2461. public function copySegment($data) {
  2462. $segment_id = getProp($data, 'segment_id');
  2463. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2464. if (!$segment) Utils::throwError('20003:请选择分镜');
  2465. $anime_id = getProp($segment, 'anime_id');
  2466. $episode_id = getProp($segment, 'episode_id');
  2467. $episode_number = getProp($segment, 'episode_number');
  2468. $segment_number = getProp($segment, 'segment_number');
  2469. $new_segment_id = 0;
  2470. try {
  2471. DB::beginTransaction();
  2472. $segment = (array)$segment;
  2473. unset($segment['id']);
  2474. $segment['segment_number'] += 1;
  2475. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2476. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2477. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2478. // 更新其他分镜序号
  2479. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2480. // 复制分镜
  2481. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2482. if (!$id) {
  2483. Utils::throwError('20003:复制分镜失败');
  2484. }
  2485. }catch (\Exception $e) {
  2486. DB::rollBack();
  2487. Utils::throwError('20003:'.$e->getMessage());
  2488. }
  2489. DB::commit();
  2490. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2491. $segment = $segment ? (array)$segment : [];
  2492. return $segment;
  2493. }
  2494. public function moveSegment($data) {
  2495. $segment_id = getProp($data, 'segment_id');
  2496. $target_segment_id = getProp($data, 'target_segment_id');
  2497. // 获取源分镜信息
  2498. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2499. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2500. // 获取目标分镜信息
  2501. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2502. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2503. $anime_id = getProp($source_segment, 'anime_id');
  2504. $episode_id = getProp($source_segment, 'episode_id');
  2505. $episode_number = getProp($source_segment, 'episode_number');
  2506. $source_segment_number = getProp($source_segment, 'segment_number');
  2507. $target_segment_number = getProp($target_segment, 'segment_number');
  2508. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2509. $target_anime_id = getProp($target_segment, 'anime_id');
  2510. $target_episode_number = getProp($target_segment, 'episode_number');
  2511. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2512. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2513. }
  2514. // 如果源分镜和目标分镜相同,无需移动
  2515. if ($source_segment_number == $target_segment_number) {
  2516. return true;
  2517. }
  2518. try {
  2519. DB::beginTransaction();
  2520. if ($source_segment_number < $target_segment_number) {
  2521. // 向后移动:源分镜移动到目标分镜之后
  2522. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2523. DB::table('mp_episode_segments')
  2524. ->where('anime_id', $anime_id)
  2525. ->where('episode_id', $episode_id)
  2526. ->where('segment_number', '>', $source_segment_number)
  2527. ->where('segment_number', '<=', $target_segment_number)
  2528. ->decrement('segment_number');
  2529. // 2. 将源分镜移动到目标分镜之后
  2530. $new_segment_number = $target_segment_number;
  2531. } else {
  2532. // 向前移动:源分镜移动到目标分镜之后
  2533. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2534. DB::table('mp_episode_segments')
  2535. ->where('anime_id', $anime_id)
  2536. ->where('episode_id', $episode_id)
  2537. ->where('segment_number', '>', $target_segment_number)
  2538. ->where('segment_number', '<', $source_segment_number)
  2539. ->increment('segment_number');
  2540. // 2. 将源分镜移动到目标分镜之后
  2541. $new_segment_number = $target_segment_number + 1;
  2542. }
  2543. // 3. 更新源分镜的序号
  2544. $update_result = DB::table('mp_episode_segments')
  2545. ->where('segment_id', $segment_id)
  2546. ->update([
  2547. 'segment_number' => $new_segment_number,
  2548. 'updated_at' => date('Y-m-d H:i:s')
  2549. ]);
  2550. if (!$update_result) {
  2551. Utils::throwError('20003:更新分镜序号失败');
  2552. }
  2553. DB::commit();
  2554. return true;
  2555. } catch (\Exception $e) {
  2556. DB::rollBack();
  2557. Utils::throwError('20003:' . $e->getMessage());
  2558. }
  2559. }
  2560. public function delSegment($data) {
  2561. $segment_id = getProp($data, 'segment_id');
  2562. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2563. if (!$segment) Utils::throwError('20003:请选择分镜');
  2564. $anime_id = getProp($segment, 'anime_id');
  2565. $episode_id = getProp($segment, 'episode_id');
  2566. $episode_number = getProp($segment, 'episode_number');
  2567. $segment_number = getProp($segment, 'segment_number');
  2568. try {
  2569. DB::beginTransaction();
  2570. // 删除分镜
  2571. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2572. if (!$boolen) {
  2573. Utils::throwError('20003:删除分镜失败');
  2574. }
  2575. // 更新其他分镜序号
  2576. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2577. }catch (\Exception $e) {
  2578. DB::rollBack();
  2579. Utils::throwError('20003:'.$e->getMessage());
  2580. }
  2581. DB::commit();
  2582. return true;
  2583. }
  2584. public function applySegment($data) {
  2585. $segment_id = getProp($data, 'segment_id');
  2586. $url = getProp($data, 'url');
  2587. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2588. if (!$url) Utils::throwError('20003:URL不能为空');
  2589. // 获取URL的文件扩展名
  2590. $urlPath = parse_url($url, PHP_URL_PATH);
  2591. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2592. // 定义图片和视频的扩展名
  2593. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2594. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2595. // 判断是图片还是视频
  2596. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2597. if (in_array($extension, $imageExtensions)) {
  2598. // 图片类型
  2599. $updateData['img_url'] = $url;
  2600. $updateData['current_type'] = 1;
  2601. } elseif (in_array($extension, $videoExtensions)) {
  2602. // 视频类型
  2603. $updateData['video_url'] = $url;
  2604. $updateData['current_type'] = 2;
  2605. } else {
  2606. Utils::throwError('20003:不支持的文件类型');
  2607. }
  2608. // 更新分镜表
  2609. $result = DB::table('mp_episode_segments')
  2610. ->where('segment_id', $segment_id)
  2611. ->update($updateData);
  2612. if (!$result) {
  2613. Utils::throwError('20003:更新分镜失败');
  2614. }
  2615. return true;
  2616. }
  2617. public function segmentHistory($data) {
  2618. $segment_id = getProp($data, 'segment_id');
  2619. // 获取历史图片
  2620. $pics = [];
  2621. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2622. foreach($pic_history as $task) {
  2623. $result_url = getProp($task, 'result_url');
  2624. if (is_json($result_url)) {
  2625. $pics = array_merge($pics, json_decode($result_url, true));
  2626. }else {
  2627. $pics[] = $result_url;
  2628. }
  2629. }
  2630. // 获取历史视频
  2631. $videos = [];
  2632. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2633. foreach($video_history as $task) {
  2634. $result_url = getProp($task, 'result_url');
  2635. if (is_json($result_url)) {
  2636. $videos = array_merge($videos, json_decode($result_url, true));
  2637. }else {
  2638. $videos[] = $result_url;
  2639. }
  2640. }
  2641. return compact('pics', 'videos');
  2642. }
  2643. public function addAct($data) {
  2644. $prev_act_id = getProp($data, 'prev_act_id');
  2645. $act_title = getProp($data, 'act_title', '');
  2646. $act_content = getProp($data, 'act_content', '');
  2647. $act_duration = getProp($data, 'act_duration', 5);
  2648. $video_url = getProp($data, 'video_url');
  2649. // 根据prev_act_id获取记录
  2650. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2651. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2652. $anime_id = getProp($prev_segment, 'anime_id');
  2653. $episode_id = getProp($prev_segment, 'episode_id');
  2654. $episode_number = getProp($prev_segment, 'episode_number');
  2655. $prev_act_number = getProp($prev_segment, 'act_number');
  2656. // 获取新的act_number
  2657. $new_act_number = $prev_act_number + 1;
  2658. try {
  2659. DB::beginTransaction();
  2660. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2661. DB::table('mp_episode_segments')
  2662. ->where('anime_id', $anime_id)
  2663. ->where('episode_id', $episode_id)
  2664. ->where('act_number', '>', $prev_act_number)
  2665. ->increment('act_number');
  2666. // 插入新片段记录
  2667. $insert_data = [
  2668. 'anime_id' => $anime_id,
  2669. 'episode_id' => $episode_id,
  2670. 'episode_number' => $episode_number,
  2671. 'act_number' => $new_act_number,
  2672. 'created_at' => date('Y-m-d H:i:s'),
  2673. 'updated_at' => date('Y-m-d H:i:s')
  2674. ];
  2675. if ($act_title) {
  2676. $insert_data['act_title'] = $act_title;
  2677. }
  2678. if ($act_content) {
  2679. $insert_data['act_content'] = $act_content;
  2680. }
  2681. if ($act_duration) {
  2682. $insert_data['act_duration'] = $act_duration;
  2683. }
  2684. if ($video_url) {
  2685. $insert_data['origin_video_url'] = $video_url;
  2686. $insert_data['current_type'] = 2;
  2687. $compressed_video_url = compressVideo($video_url);
  2688. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2689. }
  2690. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2691. if (!$id) {
  2692. Utils::throwError('20003:新增片段失败!');
  2693. }
  2694. DB::commit();
  2695. }catch (\Exception $e) {
  2696. DB::rollBack();
  2697. Utils::throwError('20003:'.$e->getMessage());
  2698. }
  2699. $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();
  2700. $segment = $segment ? (array)$segment : [];
  2701. return $segment;
  2702. }
  2703. public function editAct($data) {
  2704. $act_id = getProp($data, 'act_id');
  2705. $act_content = getProp($data, 'act_content');
  2706. $act_duration = getProp($data, 'act_duration');
  2707. $act_title = getProp($data, 'act_title');
  2708. $image_url = getProp($data, 'image_url');
  2709. $video_url = getProp($data, 'video_url');
  2710. // 参数验证
  2711. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2712. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2713. $segment = DB::table('mp_episode_segments')
  2714. ->where('id', $act_id)
  2715. ->first();
  2716. if (!$segment) Utils::throwError('20003:该片段不存在');
  2717. try {
  2718. DB::beginTransaction();
  2719. // 准备更新数据
  2720. $update_data = [
  2721. 'updated_at' => date('Y-m-d H:i:s')
  2722. ];
  2723. // 更新act相关字段
  2724. if (!empty($act_content)) {
  2725. $update_data['act_show_content'] = $act_content;
  2726. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2727. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2728. $shot_counter = 0;
  2729. $update_data['act_show_content'] = preg_replace_callback(
  2730. '/【(?:镜头|分镜)(\d+)】/u',
  2731. function($matches) use (&$shot_counter) {
  2732. $shot_counter++;
  2733. return '【镜头' . $shot_counter . '】';
  2734. },
  2735. $update_data['act_show_content']
  2736. );
  2737. }
  2738. if (!empty($act_duration)) {
  2739. $update_data['act_duration'] = $act_duration;
  2740. }
  2741. if (!empty($act_title)) {
  2742. $update_data['act_title'] = $act_title;
  2743. }
  2744. // 处理图片上传
  2745. if ($image_url) {
  2746. $update_data['img_url'] = $image_url;
  2747. $update_data['current_type'] = 1;
  2748. // 同时写入一个图片生成任务记录
  2749. if ($act_id) {
  2750. $pic_task = [
  2751. 'alias_act_id' => $act_id,
  2752. 'ref_img_url' => json_encode([]),
  2753. 'status' => 'success',
  2754. 'result_url' => json_encode([$image_url], 256),
  2755. 'model' => '',
  2756. 'created_at' => date('Y-m-d H:i:s'),
  2757. 'updated_at' => date('Y-m-d H:i:s'),
  2758. ];
  2759. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2760. }
  2761. }
  2762. // 处理视频上传
  2763. if ($video_url) {
  2764. $update_data['origin_video_url'] = $video_url;
  2765. $compressed_video_url = compressVideo($video_url);
  2766. $update_data['current_type'] = 2;
  2767. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2768. // 同时写入一个视频生成任务记录
  2769. if ($act_id) {
  2770. $video_task = [
  2771. 'alias_act_id' => $act_id,
  2772. 'status' => 'success',
  2773. 'result_url' => $update_data['origin_video_url'],
  2774. 'compressed_url' => $update_data['video_url'],
  2775. 'created_at' => date('Y-m-d H:i:s'),
  2776. 'updated_at' => date('Y-m-d H:i:s'),
  2777. ];
  2778. DB::table('mp_generate_video_tasks')->insert($video_task);
  2779. }
  2780. }
  2781. // 更新片段信息
  2782. $result = DB::table('mp_episode_segments')
  2783. ->where('id', $act_id)
  2784. ->update($update_data);
  2785. if ($result === false) {
  2786. Utils::throwError('20003:更新片段失败');
  2787. }
  2788. DB::commit();
  2789. // 返回新复制的记录
  2790. $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();
  2791. $new_segment = (array)$new_segment;
  2792. return $new_segment;
  2793. } catch (\Exception $e) {
  2794. DB::rollBack();
  2795. dLog('anime')->error('更新片段失败', [
  2796. 'act_id' => $act_id,
  2797. 'error' => $e->getMessage()
  2798. ]);
  2799. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2800. }
  2801. }
  2802. public function copyAct($data) {
  2803. $act_id = getProp($data, 'act_id');
  2804. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2805. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2806. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2807. $anime_id = getProp($source_segment, 'anime_id');
  2808. $episode_id = getProp($source_segment, 'episode_id');
  2809. $episode_number = getProp($source_segment, 'episode_number');
  2810. $act_number = getProp($source_segment, 'act_number');
  2811. try {
  2812. DB::beginTransaction();
  2813. // 新act的编号
  2814. $new_act_number = $act_number + 1;
  2815. // 更新后续所有act的act_number
  2816. DB::table('mp_episode_segments')
  2817. ->where('anime_id', $anime_id)
  2818. ->where('episode_id', $episode_id)
  2819. ->where('act_number', '>', $act_number)
  2820. ->increment('act_number');
  2821. // 复制该片段记录
  2822. $segment_data = (array)$source_segment;
  2823. unset($segment_data['id']);
  2824. $segment_data['video_url'] = '';
  2825. $segment_data['video_task_id'] = '';
  2826. $segment_data['video_task_status'] = '';
  2827. $segment_data['act_number'] = $new_act_number;
  2828. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2829. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2830. if (!$id) {
  2831. Utils::throwError('20003:复制片段失败');
  2832. }
  2833. DB::commit();
  2834. }catch (\Exception $e) {
  2835. DB::rollBack();
  2836. Utils::throwError('20003:'.$e->getMessage());
  2837. }
  2838. // 返回新复制的记录
  2839. $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();
  2840. $new_segment = $new_segment ? (array)$new_segment : [];
  2841. $new_segment['act_id'] = $id;
  2842. return $new_segment;
  2843. }
  2844. public function moveAct($data) {
  2845. $act_id = getProp($data, 'act_id');
  2846. $target_act_id = getProp($data, 'target_act_id');
  2847. // 获取源片段信息
  2848. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2849. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2850. // 获取目标片段信息
  2851. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2852. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2853. $anime_id = getProp($source_segment, 'anime_id');
  2854. $episode_id = getProp($source_segment, 'episode_id');
  2855. $source_act_number = getProp($source_segment, 'act_number');
  2856. $target_act_number = getProp($target_segment, 'act_number');
  2857. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2858. $target_anime_id = getProp($target_segment, 'anime_id');
  2859. $target_episode_id = getProp($target_segment, 'episode_id');
  2860. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2861. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2862. }
  2863. // 如果源片段和目标片段相同,无需移动
  2864. if ($source_act_number == $target_act_number) {
  2865. return true;
  2866. }
  2867. try {
  2868. DB::beginTransaction();
  2869. if ($source_act_number < $target_act_number) {
  2870. // 向后移动:源片段移动到目标片段之后
  2871. // 1. 将源片段和目标片段之间的所有片段编号减1
  2872. DB::table('mp_episode_segments')
  2873. ->where('anime_id', $anime_id)
  2874. ->where('episode_id', $episode_id)
  2875. ->where('act_number', '>', $source_act_number)
  2876. ->where('act_number', '<=', $target_act_number)
  2877. ->decrement('act_number');
  2878. // 2. 将源片段移动到目标片段之后
  2879. $new_act_number = $target_act_number;
  2880. } else {
  2881. // 向前移动:源片段移动到目标片段之后
  2882. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2883. DB::table('mp_episode_segments')
  2884. ->where('anime_id', $anime_id)
  2885. ->where('episode_id', $episode_id)
  2886. ->where('act_number', '>', $target_act_number)
  2887. ->where('act_number', '<', $source_act_number)
  2888. ->increment('act_number');
  2889. // 2. 将源片段移动到目标片段之后
  2890. $new_act_number = $target_act_number + 1;
  2891. }
  2892. // 3. 更新源片段的编号
  2893. $update_result = DB::table('mp_episode_segments')
  2894. ->where('id', $act_id)
  2895. ->update([
  2896. 'act_number' => $new_act_number,
  2897. 'updated_at' => date('Y-m-d H:i:s')
  2898. ]);
  2899. if (!$update_result) {
  2900. Utils::throwError('20003:更新片段编号失败');
  2901. }
  2902. DB::commit();
  2903. return true;
  2904. } catch (\Exception $e) {
  2905. DB::rollBack();
  2906. Utils::throwError('20003:' . $e->getMessage());
  2907. }
  2908. }
  2909. public function delAct($data) {
  2910. $act_id = getProp($data, 'act_id');
  2911. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2912. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2913. if (!$segment) Utils::throwError('20003:请选择片段');
  2914. $anime_id = getProp($segment, 'anime_id');
  2915. $episode_id = getProp($segment, 'episode_id');
  2916. $act_number = getProp($segment, 'act_number');
  2917. try {
  2918. DB::beginTransaction();
  2919. // 删除该片段记录
  2920. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2921. if (!$deleted) {
  2922. Utils::throwError('20003:删除片段失败');
  2923. }
  2924. // 更新后续act的编号
  2925. DB::table('mp_episode_segments')
  2926. ->where('anime_id', $anime_id)
  2927. ->where('episode_id', $episode_id)
  2928. ->where('act_number', '>', $act_number)
  2929. ->decrement('act_number');
  2930. DB::commit();
  2931. }catch (\Exception $e) {
  2932. DB::rollBack();
  2933. Utils::throwError('20003:'.$e->getMessage());
  2934. }
  2935. return true;
  2936. }
  2937. public function applyAct($data) {
  2938. $act_id = getProp($data, 'act_id');
  2939. $url = getProp($data, 'url');
  2940. if (!$act_id) Utils::throwError('20003:请选择片段');
  2941. if (!$url) Utils::throwError('20003:URL不能为空');
  2942. // 获取URL的文件扩展名
  2943. $urlPath = parse_url($url, PHP_URL_PATH);
  2944. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2945. // 定义图片和视频的扩展名
  2946. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2947. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2948. // 判断是图片还是视频
  2949. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2950. if (in_array($extension, $imageExtensions)) {
  2951. // 图片类型
  2952. $updateData['img_url'] = $url;
  2953. $updateData['current_type'] = 1;
  2954. } elseif (in_array($extension, $videoExtensions)) {
  2955. // 视频类型
  2956. $updateData['video_url'] = $url;
  2957. $updateData['current_type'] = 2;
  2958. } else {
  2959. Utils::throwError('20003:不支持的文件类型');
  2960. }
  2961. // 更新片段记录(全能模式下每个act只有一条记录)
  2962. $result = DB::table('mp_episode_segments')
  2963. ->where('id', $act_id)
  2964. ->update($updateData);
  2965. if (!$result) {
  2966. Utils::throwError('20003:更新片段失败');
  2967. }
  2968. return true;
  2969. }
  2970. public function actChatHistory($data) {
  2971. $act_id = getProp($data, 'act_id');
  2972. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2973. $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');
  2974. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2975. $value = (array)$value;
  2976. $value['created_at'] = transDate($value['created_at']);
  2977. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2978. else $value['reference_images'] = [];
  2979. return $value;
  2980. })->toArray();
  2981. // 获取历史图片
  2982. $url = [];
  2983. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2984. foreach($pic_history as $task) {
  2985. $result_url = getProp($task, 'result_url');
  2986. if (is_json($result_url)) {
  2987. $url = array_merge($url, json_decode($result_url, true));
  2988. }else {
  2989. $url[] = $result_url;
  2990. }
  2991. }
  2992. // 获取历史视频
  2993. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2994. foreach($video_history as $task) {
  2995. $result_url = getProp($task, 'result_url');
  2996. if (is_json($result_url)) {
  2997. $url = array_merge($url, json_decode($result_url, true));
  2998. }else {
  2999. $url[] = $result_url;
  3000. }
  3001. }
  3002. // 获取资产库
  3003. $products = [];
  3004. // 通过act_id查询片段信息获取episode_id
  3005. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  3006. if ($segment) {
  3007. $episode_id = getProp($segment, 'episode_id');
  3008. // 查询剧集信息获取roles、scenes和extra_products
  3009. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3010. if ($episode) {
  3011. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  3012. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  3013. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  3014. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  3015. // 先合并roles、scenes和props
  3016. // 处理角色数组
  3017. foreach ($roles as $role) {
  3018. $product = $role;
  3019. // 将role字段重命名为product_name
  3020. if (is_array($product) && !empty($product['role'] ?? null)) {
  3021. $product['product_name'] = $product['role'];
  3022. unset($product['role']);
  3023. $product['product'] = 1; // 标记类型为角色
  3024. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3025. }
  3026. }
  3027. // 处理场景数组
  3028. foreach ($scenes as $scene) {
  3029. $product = $scene;
  3030. // 将scene字段重命名为product_name
  3031. if (is_array($product) && !empty($product['scene'] ?? null)) {
  3032. $product['product_name'] = $product['scene'];
  3033. unset($product['scene']);
  3034. $product['product'] = 2; // 标记类型为场景
  3035. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3036. }
  3037. }
  3038. // 处理道具数组
  3039. foreach ($props as $prop) {
  3040. $product = $prop;
  3041. // 将prop字段重命名为product_name
  3042. if (is_array($product) && !empty($product['prop'] ?? null)) {
  3043. $product['product_name'] = $product['prop'];
  3044. unset($product['prop']);
  3045. $product['product'] = 3; // 标记类型为道具
  3046. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3047. }
  3048. }
  3049. // extra_products优先级更高,直接覆盖同名的roles和scenes
  3050. foreach ($extra_products as $extra_product) {
  3051. $product_name = getProp($extra_product, 'product_name');
  3052. if ($product_name) {
  3053. $products[$product_name] = $extra_product; // 覆盖同名数据
  3054. }
  3055. }
  3056. // 重新索引数组(去除key)
  3057. $products = array_values($products);
  3058. }
  3059. }
  3060. // 获取执行中的任务
  3061. $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) {
  3062. $value = (array)$value;
  3063. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  3064. else $value['ref_image_url'] = [];
  3065. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  3066. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  3067. if (!empty($value['prompt'])) {
  3068. $prompt = $value['prompt'];
  3069. // 查找第一个【镜头】的位置
  3070. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  3071. // 从【镜头】开始截取
  3072. $prompt = substr($prompt, $matches[0][1]);
  3073. }
  3074. // 去除所有<图片X>格式的标记(X可以是任意数字)
  3075. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  3076. $value['prompt'] = $prompt;
  3077. }
  3078. return $value;
  3079. })->toArray();
  3080. return compact('chat', 'url', 'products', 'tasks');
  3081. }
  3082. public function applyAudioData($data) {
  3083. $segment_id = getProp($data, 'segment_id');
  3084. $global_data = getProp($data, 'global_data');
  3085. $segment_data = getProp($data, 'segment_data');
  3086. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3087. $global_data = is_array($global_data) ? $global_data : [];
  3088. $segment_data = is_array($segment_data) ? $segment_data : [];
  3089. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3090. $dialogue_item = null;
  3091. foreach ($global_data as $key => $item) {
  3092. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3093. $dialogue_item = $item;
  3094. unset($global_data[$key]);
  3095. break;
  3096. }
  3097. }
  3098. if ($dialogue_item) {
  3099. $segment_data[] = $dialogue_item;
  3100. }
  3101. // 特殊参数: audio_url,audio_duration,subtitle_info
  3102. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3103. // 如果不是全部存在,则仍需创建音频任务
  3104. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3105. $special_update_data = [];
  3106. $has_all_special_params = false;
  3107. // 从segment_data中提取特殊参数
  3108. $filtered_segment_data = [];
  3109. foreach ($segment_data as $item) {
  3110. $field_name = trim((string)getProp($item, 'name'));
  3111. if (in_array($field_name, $special_fields)) {
  3112. $special_update_data[$field_name] = getProp($item, 'value');
  3113. } else {
  3114. // 非特殊参数保留,继续后续处理
  3115. $filtered_segment_data[] = $item;
  3116. }
  3117. }
  3118. // 检查是否三个特殊参数都存在
  3119. if (count($special_update_data) === 3 &&
  3120. isset($special_update_data['audio_url']) &&
  3121. isset($special_update_data['audio_duration']) &&
  3122. isset($special_update_data['subtitle_info'])) {
  3123. $has_all_special_params = true;
  3124. // 立即更新到当前分镜
  3125. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3126. DB::table('mp_episode_segments')
  3127. ->where('segment_id', $segment_id)
  3128. ->update($special_update_data);
  3129. }
  3130. // 使用过滤后的segment_data继续处理其他参数
  3131. $segment_data = $filtered_segment_data;
  3132. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3133. $global_update_data = [];
  3134. $segment_update_data = [];
  3135. $global_voice_type = '';
  3136. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3137. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3138. $episode_id = getProp($target_segment, 'episode_id');
  3139. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3140. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3141. if (!$episode) Utils::throwError('20003:分集不存在');
  3142. foreach ($global_data as $item) {
  3143. $field_name = trim((string)getProp($item, 'name'));
  3144. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3145. continue;
  3146. }
  3147. $global_update_data[$field_name] = getProp($item, 'value');
  3148. if ($field_name === 'voice_type') {
  3149. $global_voice_type = trim((string)getProp($item, 'value'));
  3150. }
  3151. }
  3152. foreach ($segment_data as $item) {
  3153. $field_name = trim((string)getProp($item, 'name'));
  3154. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3155. continue;
  3156. }
  3157. $segment_update_data[$field_name] = getProp($item, 'value');
  3158. }
  3159. if ($global_voice_type) {
  3160. $timbre_info = DB::table('mp_timbres')
  3161. ->where('timbre_type', $global_voice_type)
  3162. ->select('audio_url', 'timbre_name')
  3163. ->first();
  3164. if ($timbre_info) {
  3165. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3166. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3167. }
  3168. }
  3169. try {
  3170. DB::beginTransaction();
  3171. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3172. $segment_ids_to_create_task = [];
  3173. $segments_data = [];
  3174. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3175. if (!empty($global_update_data)) {
  3176. // 如果角色不存在,则只更新当前分镜
  3177. if (!$target_voice_actor) {
  3178. // 只处理当前分镜
  3179. $affected_segments = DB::table('mp_episode_segments')
  3180. ->where('segment_id', $segment_id)
  3181. ->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')
  3182. ->get();
  3183. } else {
  3184. // 获取该角色的所有分镜
  3185. $affected_segments = DB::table('mp_episode_segments')
  3186. ->where('episode_id', $episode_id)
  3187. ->where('voice_actor', $target_voice_actor)
  3188. ->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')
  3189. ->get();
  3190. }
  3191. foreach ($affected_segments as $seg) {
  3192. $seg = (array)$seg;
  3193. $sid = getProp($seg, 'segment_id');
  3194. // 检查参数是否发生变化
  3195. $has_changed = false;
  3196. foreach ($global_update_data as $field => $new_value) {
  3197. $old_value = getProp($seg, $field);
  3198. if ($old_value != $new_value) {
  3199. $has_changed = true;
  3200. break;
  3201. }
  3202. }
  3203. if ($has_changed) {
  3204. $segment_ids_to_create_task[] = $sid;
  3205. $segments_data[$sid] = $seg;
  3206. }
  3207. }
  3208. // 只有在有变化的分镜时才更新
  3209. if (!empty($segment_ids_to_create_task)) {
  3210. $global_segment_update_data = $global_update_data;
  3211. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3212. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3213. DB::table('mp_episode_segments')
  3214. ->where('episode_id', $episode_id)
  3215. ->where('voice_actor', $target_voice_actor)
  3216. ->whereIn('segment_id', $segment_ids_to_create_task)
  3217. ->update($global_segment_update_data);
  3218. }
  3219. if ($global_voice_type) {
  3220. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3221. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3222. $roles_updated = false;
  3223. foreach ($episode_roles as &$role) {
  3224. // 通过 role 字段匹配角色名,而不是 voice_name
  3225. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3226. continue;
  3227. }
  3228. $role['voice_type'] = $global_voice_type;
  3229. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3230. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3231. $roles_updated = true;
  3232. }
  3233. unset($role);
  3234. if ($roles_updated) {
  3235. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3236. 'roles' => json_encode($episode_roles, 256),
  3237. 'updated_at' => date('Y-m-d H:i:s'),
  3238. ]);
  3239. }
  3240. }
  3241. }
  3242. // 如果有单个分镜更新,检查是否有变化
  3243. if (!empty($segment_update_data)) {
  3244. // 获取当前分镜数据
  3245. $current_segment = DB::table('mp_episode_segments')
  3246. ->where('segment_id', $segment_id)
  3247. ->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')
  3248. ->first();
  3249. if ($current_segment) {
  3250. $current_segment = (array)$current_segment;
  3251. // 检查参数是否发生变化
  3252. $has_changed = false;
  3253. foreach ($segment_update_data as $field => $new_value) {
  3254. $old_value = getProp($current_segment, $field);
  3255. if ($old_value != $new_value) {
  3256. $has_changed = true;
  3257. break;
  3258. }
  3259. }
  3260. if ($has_changed) {
  3261. // 如果该分镜还未在列表中,添加进去
  3262. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3263. $segment_ids_to_create_task[] = $segment_id;
  3264. $segments_data[$segment_id] = $current_segment;
  3265. }
  3266. // 更新分镜数据并清空音频URL
  3267. $segment_update_data['audio_url'] = '';
  3268. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3269. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3270. }
  3271. }
  3272. }
  3273. // 为所有有变化的分镜创建音频合成任务
  3274. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3275. if (!empty($segment_ids_to_create_task)) {
  3276. foreach ($segment_ids_to_create_task as $sid) {
  3277. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3278. if ($sid === $segment_id && $has_all_special_params) {
  3279. continue;
  3280. }
  3281. // 重新获取更新后的分镜数据
  3282. $updated_segment = DB::table('mp_episode_segments')
  3283. ->where('segment_id', $sid)
  3284. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3285. ->first();
  3286. if (!$updated_segment) continue;
  3287. $updated_segment = (array)$updated_segment;
  3288. // 检查dialogue是否为空
  3289. $dialogue = getProp($updated_segment, 'dialogue');
  3290. if (empty($dialogue)) {
  3291. // dialogue为空时,直接写入默认音频信息
  3292. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3293. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3294. 'audio_duration' => 2.0,
  3295. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3296. 'updated_at' => date('Y-m-d H:i:s')
  3297. ]);
  3298. continue;
  3299. }
  3300. $generate_json = [
  3301. 'text' => $dialogue,
  3302. 'role' => getProp($updated_segment, 'voice_actor'),
  3303. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3304. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3305. 'emotion' => getProp($updated_segment, 'emotion'),
  3306. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3307. 'gender' => getProp($updated_segment, 'gender'),
  3308. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3309. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3310. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3311. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3312. ];
  3313. // 插入视频配音合成任务
  3314. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3315. 'alias_segment_id' => $sid,
  3316. 'generate_status' => '执行中',
  3317. 'audio_url' => '',
  3318. 'generate_json' => json_encode($generate_json, 256),
  3319. 'created_at' => date('Y-m-d H:i:s'),
  3320. 'updated_at' => date('Y-m-d H:i:s'),
  3321. ]);
  3322. if (!$dubTaskId) {
  3323. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3324. continue;
  3325. }
  3326. // 将任务ID添加到Redis列表中
  3327. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3328. // 请求远程服务器执行生成
  3329. try {
  3330. sleep(1);
  3331. $client = new Client(['timeout' => 300, 'verify' => false]);
  3332. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3333. $response = $result->getBody()->getContents();
  3334. $response_arr = json_decode($response, true);
  3335. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3336. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3337. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3338. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3339. }
  3340. } catch (\Exception $e) {
  3341. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3342. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3343. }
  3344. }
  3345. }
  3346. DB::commit();
  3347. } catch (\Exception $e) {
  3348. DB::rollBack();
  3349. Utils::throwError('20003:'.$e->getMessage());
  3350. }
  3351. return true;
  3352. }
  3353. public function episodePicsInfo($data) {
  3354. $anime_id = getProp($data, 'anime_id');
  3355. $episode_id = getProp($data, 'episode_id');
  3356. // 参数验证
  3357. if (!$anime_id && !$episode_id) {
  3358. Utils::throwError('20003:请提供动漫ID或分集ID');
  3359. }
  3360. // 根据参数获取数据源
  3361. if ($episode_id) {
  3362. // 从剧集表获取
  3363. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3364. if (!$source) Utils::throwError('20003:该剧集不存在');
  3365. $table_name = 'mp_anime_episodes';
  3366. $id_field = 'id';
  3367. $id_value = $episode_id;
  3368. // 获取剧集的anime_id用于继承全局数据
  3369. $anime_id = getProp($source, 'anime_id');
  3370. } else {
  3371. // 从动漫表获取
  3372. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3373. if (!$source) Utils::throwError('20003:该动漫不存在');
  3374. $table_name = 'mp_animes';
  3375. $id_field = 'id';
  3376. $id_value = $anime_id;
  3377. }
  3378. $source = (array)$source;
  3379. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3380. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3381. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3382. // 如果是分集数据,需要处理继承和任务创建逻辑
  3383. if ($episode_id) {
  3384. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3385. }
  3386. // 返回生成器函数,用于 SSE 流式输出
  3387. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3388. $startTime = time();
  3389. $maxDuration = 600; // 10分钟超时
  3390. $checkInterval = 3; // 每3秒检查一次
  3391. // Redis 缓存键
  3392. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3393. // 生成当前数据的哈希值用于比较
  3394. $generateHash = function($roles, $scenes, $props) {
  3395. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3396. };
  3397. // 发送初始数据
  3398. $currentHash = $generateHash($roles, $scenes, $props);
  3399. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3400. echo "data: " . json_encode([
  3401. 'type' => 'init',
  3402. 'data' => [
  3403. 'roles' => $roles,
  3404. 'scenes' => $scenes,
  3405. 'props' => $props,
  3406. 'start_time' => $startTime
  3407. ]
  3408. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3409. if (ob_get_level() > 0) {
  3410. ob_flush();
  3411. }
  3412. flush();
  3413. // 持续轮询任务状态
  3414. while (time() - $startTime < $maxDuration) {
  3415. $hasProcessing = false;
  3416. $updated = false;
  3417. // 检查角色任务状态
  3418. foreach ($roles as $index => &$role) {
  3419. $task_id = getProp($role, 'task_id');
  3420. $task_status = getProp($role, 'task_status');
  3421. $existing_url = getProp($role, 'url');
  3422. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3423. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3424. $hasProcessing = ($task_status === 'processing');
  3425. // 查询任务状态
  3426. $task = DB::table('mp_generate_pic_tasks')
  3427. ->where('id', $task_id)
  3428. ->select('id', 'status', 'result_url', 'error_message')
  3429. ->first();
  3430. if ($task) {
  3431. $task = (array)$task;
  3432. $status = getProp($task, 'status');
  3433. // 如果任务完成或失败
  3434. if (in_array($status, ['success', 'failed'])) {
  3435. $role['task_status'] = $status;
  3436. if ($status === 'success') {
  3437. $result_url = getProp($task, 'result_url');
  3438. if ($result_url) {
  3439. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3440. if (is_array($result_urls) && !empty($result_urls[0])) {
  3441. $role['url'] = $result_urls[0];
  3442. }
  3443. }
  3444. }
  3445. $updated = true;
  3446. } else if ($status === 'processing') {
  3447. $hasProcessing = true;
  3448. }
  3449. }
  3450. }
  3451. }
  3452. // 检查场景任务状态
  3453. foreach ($scenes as $index => &$scene) {
  3454. $task_id = getProp($scene, 'task_id');
  3455. $task_status = getProp($scene, 'task_status');
  3456. $existing_url = getProp($scene, 'url');
  3457. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3458. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3459. $hasProcessing = ($task_status === 'processing');
  3460. // 查询任务状态
  3461. $task = DB::table('mp_generate_pic_tasks')
  3462. ->where('id', $task_id)
  3463. ->select('id', 'status', 'result_url', 'error_message')
  3464. ->first();
  3465. if ($task) {
  3466. $task = (array)$task;
  3467. $status = getProp($task, 'status');
  3468. // 如果任务完成或失败
  3469. if (in_array($status, ['success', 'failed'])) {
  3470. $scene['task_status'] = $status;
  3471. if ($status === 'success') {
  3472. $result_url = getProp($task, 'result_url');
  3473. if ($result_url) {
  3474. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3475. if (is_array($result_urls) && !empty($result_urls[0])) {
  3476. $scene['url'] = $result_urls[0];
  3477. }
  3478. }
  3479. }
  3480. $updated = true;
  3481. } else if ($status === 'processing') {
  3482. $hasProcessing = true;
  3483. }
  3484. }
  3485. }
  3486. }
  3487. // 检查道具任务状态
  3488. foreach ($props as $index => &$prop) {
  3489. $task_id = getProp($prop, 'task_id');
  3490. $task_status = getProp($prop, 'task_status');
  3491. $existing_url = getProp($prop, 'url');
  3492. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3493. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3494. $hasProcessing = ($task_status === 'processing');
  3495. // 查询任务状态
  3496. $task = DB::table('mp_generate_pic_tasks')
  3497. ->where('id', $task_id)
  3498. ->select('id', 'status', 'result_url', 'error_message')
  3499. ->first();
  3500. if ($task) {
  3501. $task = (array)$task;
  3502. $status = getProp($task, 'status');
  3503. // 如果任务完成或失败
  3504. if (in_array($status, ['success', 'failed'])) {
  3505. $prop['task_status'] = $status;
  3506. if ($status === 'success') {
  3507. $result_url = getProp($task, 'result_url');
  3508. if ($result_url) {
  3509. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3510. if (is_array($result_urls) && !empty($result_urls[0])) {
  3511. $prop['url'] = $result_urls[0];
  3512. }
  3513. }
  3514. }
  3515. $updated = true;
  3516. } else if ($status === 'processing') {
  3517. $hasProcessing = true;
  3518. }
  3519. }
  3520. }
  3521. }
  3522. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3523. if ($updated) {
  3524. $newHash = $generateHash($roles, $scenes, $props);
  3525. $cachedHash = Redis::get($cacheKey);
  3526. // 只有当数据真正变化时才更新数据库和发送事件
  3527. if ($newHash !== $cachedHash) {
  3528. try {
  3529. // 更新数据库
  3530. DB::table($table_name)->where($id_field, $id_value)->update([
  3531. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3532. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3533. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3534. 'updated_at' => date('Y-m-d H:i:s')
  3535. ]);
  3536. // 更新缓存
  3537. Redis::setex($cacheKey, 600, $newHash);
  3538. // 发送更新事件
  3539. echo "data: " . json_encode([
  3540. 'type' => 'update',
  3541. 'data' => [
  3542. 'roles' => $roles,
  3543. 'scenes' => $scenes,
  3544. 'props' => $props,
  3545. 'elapsed_time' => time() - $startTime
  3546. ]
  3547. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3548. if (ob_get_level() > 0) {
  3549. ob_flush();
  3550. }
  3551. flush();
  3552. } catch (\Exception $e) {
  3553. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3554. }
  3555. } else {
  3556. // 即使哈希相同,如果有URL更新也要发送事件
  3557. $hasUrlUpdate = false;
  3558. foreach ($roles as $role) {
  3559. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3560. $hasUrlUpdate = true;
  3561. break;
  3562. }
  3563. }
  3564. if (!$hasUrlUpdate) {
  3565. foreach ($scenes as $scene) {
  3566. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3567. $hasUrlUpdate = true;
  3568. break;
  3569. }
  3570. }
  3571. }
  3572. if (!$hasUrlUpdate) {
  3573. foreach ($props as $prop) {
  3574. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3575. $hasUrlUpdate = true;
  3576. break;
  3577. }
  3578. }
  3579. }
  3580. if ($hasUrlUpdate) {
  3581. // 强制更新数据库和发送事件
  3582. try {
  3583. DB::table($table_name)->where($id_field, $id_value)->update([
  3584. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3585. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3586. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3587. 'updated_at' => date('Y-m-d H:i:s')
  3588. ]);
  3589. // 更新缓存
  3590. Redis::setex($cacheKey, 600, $newHash);
  3591. // 发送更新事件
  3592. echo "data: " . json_encode([
  3593. 'type' => 'update',
  3594. 'data' => [
  3595. 'roles' => $roles,
  3596. 'scenes' => $scenes,
  3597. 'props' => $props,
  3598. 'elapsed_time' => time() - $startTime
  3599. ]
  3600. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3601. if (ob_get_level() > 0) {
  3602. ob_flush();
  3603. }
  3604. flush();
  3605. } catch (\Exception $e) {
  3606. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3607. }
  3608. }
  3609. }
  3610. }
  3611. // 如果所有任务都已完成,发送完成事件并退出
  3612. if (!$hasProcessing) {
  3613. // 查询数据库中的最终数据,确保返回最新的完整数据
  3614. try {
  3615. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3616. if ($finalSource) {
  3617. $finalSource = (array)$finalSource;
  3618. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3619. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3620. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3621. // 使用数据库中的最终数据
  3622. $roles = $finalRoles;
  3623. $scenes = $finalScenes;
  3624. $props = $finalProps;
  3625. }
  3626. } catch (\Exception $e) {
  3627. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3628. // 如果查询失败,继续使用内存中的数据
  3629. }
  3630. // 清理缓存
  3631. Redis::del($cacheKey);
  3632. echo "data: " . json_encode([
  3633. 'type' => 'completed',
  3634. 'data' => [
  3635. 'roles' => $roles,
  3636. 'scenes' => $scenes,
  3637. 'props' => $props,
  3638. 'total_time' => time() - $startTime
  3639. ]
  3640. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3641. if (ob_get_level() > 0) {
  3642. ob_flush();
  3643. }
  3644. flush();
  3645. break;
  3646. }
  3647. // 等待下次检查
  3648. sleep($checkInterval);
  3649. }
  3650. // 超时处理
  3651. if (time() - $startTime >= $maxDuration) {
  3652. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3653. try {
  3654. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3655. if ($finalSource) {
  3656. $finalSource = (array)$finalSource;
  3657. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3658. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3659. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3660. // 使用数据库中的最终数据
  3661. $roles = $finalRoles;
  3662. $scenes = $finalScenes;
  3663. $props = $finalProps;
  3664. }
  3665. } catch (\Exception $e) {
  3666. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3667. // 如果查询失败,继续使用内存中的数据
  3668. }
  3669. // 清理缓存
  3670. Redis::del($cacheKey);
  3671. echo "data: " . json_encode([
  3672. 'type' => 'timeout',
  3673. 'message' => '轮询超时,请刷新页面查看最新状态',
  3674. 'data' => [
  3675. 'roles' => $roles,
  3676. 'scenes' => $scenes,
  3677. 'props' => $props
  3678. ]
  3679. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3680. if (ob_get_level() > 0) {
  3681. ob_flush();
  3682. }
  3683. flush();
  3684. }
  3685. };
  3686. }
  3687. public function clipSegmentVideo($data) {
  3688. $segment_id = getProp($data, 'segment_id');
  3689. $video_time_point_start = getProp($data, 'video_time_point_start');
  3690. $video_time_point_end = getProp($data, 'video_time_point_end');
  3691. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3692. Utils::throwError('20003:参数异常');
  3693. }
  3694. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3695. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3696. }
  3697. $video_duration = $video_time_point_end - $video_time_point_start;
  3698. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3699. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3700. 'video_duration' => $video_duration,
  3701. 'video_time_point_start' => $video_time_point_start,
  3702. 'video_time_point_end' => $video_time_point_end,
  3703. 'updated_at' => date('Y-m-d H:i:s')
  3704. ]);
  3705. }
  3706. // 轮训获取图片任务结果
  3707. private function loopGetPicTaskResult($task_id) {
  3708. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3709. if (!$task) {
  3710. return '';
  3711. }
  3712. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3713. $model = getProp($task, 'model');
  3714. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3715. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3716. $isSyncModel = $isVolcModel || $isGptModel;
  3717. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3718. $start_count = 0;
  3719. $img_url = '';
  3720. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3721. sleep(3);
  3722. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3723. // 如果任务已经完成,直接返回结果
  3724. if ($task->status === 'success' && $task->result_url) {
  3725. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3726. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3727. }
  3728. // 如果任务已失败,返回空
  3729. if ($task->status === 'failed') {
  3730. return '';
  3731. }
  3732. if ($isSyncModel) continue;
  3733. // 查询任务状态
  3734. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3735. if ($statusInfo['status'] === 'success') {
  3736. $task->updateStatus('success', [
  3737. 'result_url' => $statusInfo['result_url'],
  3738. 'result_json' => $statusInfo['result_json'] ?? []
  3739. ]);
  3740. // 同步调整分镜图片状态和结果
  3741. if (getProp($task, 'alias_segment_id')) {
  3742. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3743. 'img_url' => $statusInfo['result_url'][0],
  3744. 'pic_task_status' => '已完成',
  3745. ]);
  3746. }
  3747. $img_url = $statusInfo['result_url'][0];
  3748. break;
  3749. } elseif ($statusInfo['status'] === 'failed') {
  3750. $task->updateStatus('failed', [
  3751. 'error_message' => $statusInfo['error_message'],
  3752. 'result_json' => $statusInfo['result_json'] ?? []
  3753. ]);
  3754. if (getProp($task, 'alias_segment_id')) {
  3755. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3756. 'pic_task_status' => '失败',
  3757. ]);
  3758. }
  3759. break;
  3760. }
  3761. $start_count++;
  3762. }
  3763. return $img_url;
  3764. }
  3765. /**
  3766. * 从分镜内容中提取涉及的角色
  3767. */
  3768. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3769. $found_characters = [];
  3770. foreach ($available_characters as $character) {
  3771. // 检查角色名称是否在分镜内容中出现
  3772. if (strpos($segment_content, $character) !== false) {
  3773. $found_characters[] = $character;
  3774. }
  3775. }
  3776. if (!$found_characters) {
  3777. foreach ($roles as $character) {
  3778. // 检查角色名称是否在分镜内容中出现
  3779. if (strpos($segment_content, $character) !== false) {
  3780. $found_characters[] = $character;
  3781. }
  3782. }
  3783. }
  3784. return array_unique($found_characters);
  3785. }
  3786. // 从分镜剧本中提取关键字段
  3787. private function handleSegmentContent(&$data) {
  3788. $segmentContent = getProp($data, 'segment_content');
  3789. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3790. $segmentData = [
  3791. 'description' => '',
  3792. 'composition' => '',
  3793. 'camera_movement' => '',
  3794. 'voice_actor' => '',
  3795. 'dialogue' => '',
  3796. 'frame_type' => '',
  3797. 'scene' => '', // 场景
  3798. 'characters' => '', // 出镜角色
  3799. 'tail_frame' => '', // 尾帧描述
  3800. 'emotion' => '中性', // 情感
  3801. 'gender' => '0', // 性别(0未知,1男,2女)
  3802. 'speed_ratio' => 0, // 语速
  3803. 'loudness_ratio' => 0, // 音量
  3804. 'emotion_scale' => 4, // 情感强度
  3805. 'pitch' => 0, // 音调
  3806. ];
  3807. // 用于存储需要从 segment_content 中移除的匹配项
  3808. $replaceEmptyArr = [];
  3809. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3810. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3811. $segmentData['description'] = trim($descMatch[1]);
  3812. $data['description'] = trim($descMatch[1]);
  3813. }
  3814. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3815. $segmentData['composition'] = trim($compMatch[1]);
  3816. $data['composition'] = trim($compMatch[1]);
  3817. }
  3818. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3819. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3820. $data['camera_movement'] = trim($cameraMatch[1]);
  3821. }
  3822. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3823. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3824. $data['voice_actor'] = trim($voiceMatch[1]);
  3825. }
  3826. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3827. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3828. $data['dialogue'] = trim($dialogueMatch[1]);
  3829. }
  3830. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3831. $segmentData['frame_type'] = trim($frameMatch[1]);
  3832. $data['frame_type'] = trim($frameMatch[1]);
  3833. }
  3834. // 场景字段
  3835. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3836. $segmentData['scene'] = trim($sceneMatch[1]);
  3837. $data['scene'] = trim($sceneMatch[1]);
  3838. }
  3839. // 出镜角色字段
  3840. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3841. $segmentData['characters'] = trim($charactersMatch[1]);
  3842. $data['characters'] = trim($charactersMatch[1]);
  3843. }
  3844. // 尾帧描述字段
  3845. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3846. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3847. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3848. }
  3849. // 情感字段
  3850. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3851. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3852. $segmentData['emotion'] = trim($emotionMatch[1]);
  3853. $data['emotion'] = trim($emotionMatch[1]);
  3854. }
  3855. // 性别字段
  3856. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3857. $replaceEmptyArr[] = trim($genderMatch[0]);
  3858. $genderStr = trim($genderMatch[1]);
  3859. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3860. $segmentData['gender'] = '1';
  3861. $data['gender'] = '1';
  3862. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3863. $segmentData['gender'] = '2';
  3864. $data['gender'] = '2';
  3865. } else {
  3866. $segmentData['gender'] = '0';
  3867. $data['gender'] = '0';
  3868. }
  3869. }
  3870. // 语速字段
  3871. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3872. $replaceEmptyArr[] = trim($speedMatch[0]);
  3873. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3874. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3875. }
  3876. // 音量字段
  3877. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3878. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3879. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3880. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3881. }
  3882. // 情感强度字段
  3883. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3884. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3885. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3886. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3887. }
  3888. // 音调字段
  3889. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3890. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3891. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3892. $data['pitch'] = (int)trim($pitchMatch[1]);
  3893. }
  3894. // 从 segment_content 中移除已提取的配音参数字段
  3895. if (!empty($replaceEmptyArr)) {
  3896. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3897. }
  3898. // 如果有配音角色,查询音色信息并验证情感
  3899. $voice_actor = $segmentData['voice_actor'];
  3900. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3901. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3902. $anime_id = getProp($data, 'anime_id');
  3903. $episode_id = getProp($data, 'episode_id');
  3904. // 优先从剧集的角色列表中查找
  3905. $roles = [];
  3906. if ($episode_id) {
  3907. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3908. if ($episode && getProp($episode, 'roles')) {
  3909. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3910. }
  3911. }
  3912. // 如果剧集中没有,从动漫的角色列表中查找
  3913. if (empty($roles) && $anime_id) {
  3914. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3915. if ($anime && getProp($anime, 'roles')) {
  3916. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3917. }
  3918. }
  3919. // 查找匹配的角色音色信息
  3920. $timbre_info = null;
  3921. foreach ($roles as $role) {
  3922. if (getProp($role, 'role') === $voice_actor) {
  3923. $timbre_info = $role;
  3924. break;
  3925. }
  3926. }
  3927. // 如果找到音色信息,添加到数据中
  3928. if ($timbre_info) {
  3929. $voice_type = getProp($timbre_info, 'voice_type');
  3930. $voice_name = getProp($timbre_info, 'voice_name');
  3931. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3932. if ($voice_type) {
  3933. $data['voice_type'] = $voice_type;
  3934. $segmentData['voice_type'] = $voice_type;
  3935. }
  3936. if ($voice_name) {
  3937. $data['voice_name'] = $voice_name;
  3938. $segmentData['voice_name'] = $voice_name;
  3939. }
  3940. if ($voice_audio_url) {
  3941. $data['voice_audio_url'] = $voice_audio_url;
  3942. $segmentData['voice_audio_url'] = $voice_audio_url;
  3943. }
  3944. // 验证情感是否在音色支持的情感列表中
  3945. if ($voice_type) {
  3946. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3947. if ($timbre_emotion) {
  3948. $timbre_emotion = explode(',', $timbre_emotion);
  3949. } else {
  3950. $timbre_emotion = [];
  3951. }
  3952. $emotion = getProp($segmentData, 'emotion', '中性');
  3953. if (!in_array($emotion, $timbre_emotion)) {
  3954. $emotion = '中性';
  3955. }
  3956. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3957. $emotion_list = array_flip($emotion_list);
  3958. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3959. $data['emotion_type'] = $emotion_type;
  3960. $segmentData['emotion_type'] = $emotion_type;
  3961. }
  3962. }
  3963. }
  3964. return $segmentData;
  3965. }
  3966. public function createSegmentVideoTask($data) {
  3967. $segment_id = getProp($data, 'segment_id');
  3968. $tail_frame = getProp($data, 'tail_frame');
  3969. $first_frame_url = getProp($data, 'first_frame_url');
  3970. $tail_frame_url = getProp($data, 'tail_frame_url');
  3971. $generate_audio = getProp($data, 'generate_audio', 0);
  3972. if (!$segment_id) {
  3973. Utils::throwError('1002:分镜ID不能为空');
  3974. }
  3975. // 获取分镜信息
  3976. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3977. if (!$segment) {
  3978. Utils::throwError('20003:分镜不存在');
  3979. }
  3980. $segment = (array)$segment;
  3981. $episode_id = getProp($segment, 'episode_id');
  3982. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3983. if (!$ratio) $ratio = '9:16';
  3984. // 获取分镜内容
  3985. $segmentContent = getProp($segment, 'segment_content', '');
  3986. // 检查 $segmentContent 中是否已有尾帧描述
  3987. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3988. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3989. $finalTailFrame = '';
  3990. if ($tail_frame) {
  3991. // 用户输入了尾帧描述,优先使用
  3992. $finalTailFrame = $tail_frame;
  3993. // 如果 segmentContent 中已有尾帧描述,需要替换
  3994. if ($contentHasTailFrame) {
  3995. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3996. }
  3997. } elseif ($contentHasTailFrame) {
  3998. // segmentContent 中有尾帧描述,使用它
  3999. $finalTailFrame = trim($contentTailFrameMatch[1]);
  4000. } else {
  4001. // 两者都没有,使用分镜表中的尾帧描述
  4002. $finalTailFrame = getProp($segment, 'tail_frame', '');
  4003. }
  4004. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  4005. $hasDialogue = false;
  4006. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  4007. $dialogue = trim($dialogueMatch[1]);
  4008. // 如果台词不为空且不是"无"
  4009. if (!empty($dialogue) && $dialogue !== '无') {
  4010. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  4011. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  4012. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  4013. $hasDialogue = true;
  4014. }
  4015. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  4016. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  4017. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  4018. if (!preg_match('/^[“]/', $dialogue)) {
  4019. $dialogue = '“' . $dialogue;
  4020. }
  4021. if (!preg_match('/[”]$/', $dialogue)) {
  4022. $dialogue .= '”';
  4023. }
  4024. // 将修改后的台词替换回 $segmentContent
  4025. $originalDialogue = $dialogueMatch[1];
  4026. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  4027. }
  4028. }
  4029. // 构建完整的提示词
  4030. $fullPrompt = $segmentContent;
  4031. if ($finalTailFrame && !$contentHasTailFrame) {
  4032. // 只有当 segmentContent 中没有尾帧描述时才追加
  4033. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  4034. }
  4035. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  4036. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  4037. $fullPrompt = trim($fullPrompt);
  4038. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  4039. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  4040. // 智能选择视频时长
  4041. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  4042. $videoDuration = -1;
  4043. // 处理视频模型
  4044. $model = getProp($data, 'model');
  4045. if (!$model) {
  4046. // 用户没有输入,从episode表获取
  4047. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  4048. $model = getProp($episode, 'video_model');
  4049. if (!$model) {
  4050. // episode表也没有,使用默认值
  4051. $model = 'doubao-seedance-1-5-pro-251215';
  4052. }
  4053. }
  4054. // 验证模型是否在可用模型表中
  4055. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4056. $model = 'doubao-seedance-1-5-pro-251215';
  4057. }
  4058. // 保存到episode表
  4059. $episode_id = getProp($segment, 'episode_id');
  4060. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4061. 'video_model' => $model,
  4062. 'updated_at' => date('Y-m-d H:i:s')
  4063. ]);
  4064. // 构建视频生成参数
  4065. $videoParams = [
  4066. 'model' => $model,
  4067. 'alias_segment_id' => $segment_id,
  4068. 'prompt' => trim($fullPrompt),
  4069. 'video_duration' => $videoDuration,
  4070. 'video_resolution' => '720P',
  4071. 'seed' => -1,
  4072. 'ratio' => $ratio,
  4073. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4074. 'draft' => false,
  4075. 'watermark' => false,
  4076. 'camera_fixed' => false,
  4077. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4078. ];
  4079. // 如果分镜有图片,作为首帧
  4080. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  4081. $hasVideo = !empty(getProp($segment, 'video_url'));
  4082. if ($hasImage) {
  4083. if ($first_frame_url) {
  4084. $videoParams['first_frame_url'] = $first_frame_url;
  4085. }else {
  4086. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4087. }
  4088. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4089. }
  4090. // 构建content数组
  4091. $videoParams['content'] = [
  4092. [
  4093. 'type' => 'text',
  4094. 'text' => $videoParams['prompt'],
  4095. ]
  4096. ];
  4097. // 如果有首帧图片,添加到content中
  4098. if ($hasImage) {
  4099. 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'])) {
  4100. $videoParams['content'][] = [
  4101. 'type' => 'image_url',
  4102. 'image_url' => [
  4103. 'url' => $videoParams['first_frame_url'],
  4104. ],
  4105. 'role' => 'reference_image',
  4106. ];
  4107. if (isset($videoParams['tail_frame_url'])) {
  4108. $videoParams['content'][] = [
  4109. 'type' => 'image_url',
  4110. 'image_url' => [
  4111. 'url' => $videoParams['tail_frame_url'],
  4112. ],
  4113. 'role' => 'reference_image',
  4114. ];
  4115. }
  4116. }else {
  4117. $videoParams['content'][] = [
  4118. 'type' => 'image_url',
  4119. 'image_url' => [
  4120. 'url' => $videoParams['first_frame_url'],
  4121. ],
  4122. 'role' => 'first_frame',
  4123. ];
  4124. if (isset($videoParams['tail_frame_url'])) {
  4125. $videoParams['content'][] = [
  4126. 'type' => 'image_url',
  4127. 'image_url' => [
  4128. 'url' => $videoParams['tail_frame_url'],
  4129. ],
  4130. 'role' => 'last_frame',
  4131. ];
  4132. }
  4133. }
  4134. }
  4135. // 获取配音音频URL
  4136. $audioUrl = getProp($segment, 'audio_url');
  4137. $audioDuration = getProp($segment, 'audio_duration');
  4138. // 音频传入的前提:必须有至少一张图片或一个视频
  4139. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4140. // 余额预检:按预估时长计算所需积分,不足直接报错
  4141. $chargeDuration = (int)ceil((float)$audioDuration);
  4142. if ($chargeDuration <= 0) {
  4143. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4144. }
  4145. $this->pointsService->checkUserPointsEnough(
  4146. $this->pointsService->getVideoChargePoints([
  4147. 'model' => $model,
  4148. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4149. 'video_duration' => $chargeDuration,
  4150. 'ratio' => $ratio,
  4151. 'generate_audio' => $current_generate_audio,
  4152. ])
  4153. );
  4154. // dd($videoParams);
  4155. // 根据模型选择不同的视频生成方法
  4156. if (strpos($model, 'jimeng') !== false) {
  4157. // 即梦模型参数调整
  4158. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4159. unset($videoParams['content']); // 即梦不使用content格式
  4160. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4161. } elseif (strpos($model, 'kling') !== false) {
  4162. // Keling模型参数调整
  4163. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4164. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4165. unset($videoParams['ratio']);
  4166. unset($videoParams['content']); // Keling不使用content格式
  4167. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4168. } elseif (strpos($model, 'zhizhen') !== false) {
  4169. // 智帧20等新模型使用统一API
  4170. // 构建统一API参数
  4171. $unifiedParams = [
  4172. 'model_code' => $model,
  4173. 'alias_segment_id' => $segment_id,
  4174. 'prompt' => trim($fullPrompt),
  4175. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4176. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4177. 'video_ratio' => $ratio,
  4178. 'seed' => -1,
  4179. ];
  4180. // 构建parameters参数
  4181. $parameters = [
  4182. 'seconds' => $unifiedParams['video_duration'],
  4183. 'resolution' => $unifiedParams['video_resolution'],
  4184. 'ratio' => $ratio,
  4185. // 'video_mode' => 'multi_image',
  4186. // 'mode' => 'multi_image',
  4187. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4188. ];
  4189. $hasImage = false;
  4190. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4191. if ($hasImage) {
  4192. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4193. if (isset($videoParams['tail_frame_url'])) {
  4194. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4195. }
  4196. // 只有在有图片的情况下才能添加参考音频
  4197. if ($audioUrl) {
  4198. // $parameters['reference_audios'] = [$audioUrl];
  4199. }
  4200. } else {
  4201. // 没有图片时,记录错误日志
  4202. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4203. 'segment_id' => $segment_id,
  4204. 'model' => $model
  4205. ]);
  4206. }
  4207. $unifiedParams['parameters'] = $parameters;
  4208. // 调用统一API创建任务
  4209. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4210. } else {
  4211. // Seedance模型(默认)
  4212. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4213. if ($this->isKuaikuaiSeedanceModel($model)) {
  4214. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4215. if ($canUseAudio && $audioUrl) {
  4216. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4217. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4218. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4219. // 优化提示词,增加音频相关描述
  4220. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4221. $videoParams['prompt'] = $audioPrompt;
  4222. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4223. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4224. }
  4225. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4226. } 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'])) {
  4227. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4228. // 添加配音音频到content中
  4229. $videoParams['content'][] = [
  4230. 'type' => 'audio_url',
  4231. 'audio_url' => [
  4232. 'url' => $audioUrl,
  4233. ],
  4234. 'role' => 'reference_audio',
  4235. ];
  4236. // 优化提示词,增加音频相关描述
  4237. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4238. $videoParams['prompt'] = $audioPrompt;
  4239. $videoParams['content'][0]['text'] = $audioPrompt;
  4240. } else {
  4241. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4242. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4243. }
  4244. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4245. }
  4246. }
  4247. // 更新分镜表的视频任务信息
  4248. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4249. 'video_task_id' => $task->id,
  4250. 'video_task_status' => '生成中',
  4251. 'generate_audio' => $generate_audio,
  4252. 'updated_at' => date('Y-m-d H:i:s')
  4253. ]);
  4254. return [
  4255. 'task_id' => $task->id,
  4256. 'status' => $task->status,
  4257. 'segment_id' => $segment_id,
  4258. 'video_duration' => $videoDuration
  4259. ];
  4260. }
  4261. /**
  4262. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4263. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4264. *
  4265. * @param string $model
  4266. * @return bool
  4267. */
  4268. public function isKuaikuaiSeedanceModel(string $model): bool
  4269. {
  4270. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4271. }
  4272. /**
  4273. * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
  4274. *
  4275. * @param string $model
  4276. * @return bool
  4277. */
  4278. public function isBaiduSeedanceModel(string $model): bool
  4279. {
  4280. return in_array($model, [
  4281. 'baidu-doubao-seedance-2-0-260128',
  4282. 'baidu-doubao-seedance-2-0-fast-260128',
  4283. 'baidu-doubao-seedance-2-0-mini-260615',
  4284. 'baidu-doubao-seedance-2-5-260628',
  4285. ], true);
  4286. }
  4287. /**
  4288. * 是否为海外百度Seedance(dreamina真人素材空间)模型
  4289. * 系统内使用 baidu-dreamina- 前缀名,请求网关时映射为 dreamina-* 原名
  4290. *
  4291. * @param string $model
  4292. * @return bool
  4293. */
  4294. public function isOverseasBaiduSeedanceModel(string $model): bool
  4295. {
  4296. return in_array($model, [
  4297. 'baidu-dreamina-seedance-2-0-260128',
  4298. 'baidu-dreamina-seedance-2-0-fast-260128',
  4299. 'baidu-dreamina-seedance-2-0-mini-260615',
  4300. 'baidu-dreamina-seedance-2-5-260628',
  4301. ], true);
  4302. }
  4303. /**
  4304. * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-doubao-* / baidu-dreamina-* / 快快AI seed-2 系列)
  4305. * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
  4306. *
  4307. * @param string $model
  4308. * @return bool
  4309. */
  4310. public function isSeedance20SeriesModel(string $model): bool
  4311. {
  4312. return strpos($model, 'doubao-seedance-2.0') !== false
  4313. || $this->isKuaikuaiSeedanceModel($model)
  4314. || $this->isBaiduSeedanceModel($model)
  4315. || $this->isOverseasBaiduSeedanceModel($model);
  4316. }
  4317. public function createActVideoTask($data) {
  4318. $act_id = getProp($data, 'act_id');
  4319. $first_frame_url = getProp($data, 'first_frame_url');
  4320. $tail_frame_url = getProp($data, 'tail_frame_url');
  4321. $generate_audio = getProp($data, 'generate_audio', 1);
  4322. $video_duration = getProp($data, 'video_duration');
  4323. $video_resolution = getProp($data, 'video_resolution');
  4324. $ratio = getProp($data, 'ratio');
  4325. $products = getProp($data, 'products', []);
  4326. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4327. if (!is_array($reference_images) || !is_array($products)) {
  4328. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4329. }
  4330. if (!$act_id) {
  4331. Utils::throwError('1002:片段ID不能为空');
  4332. }
  4333. // 获取片段信息
  4334. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4335. if (!$act) {
  4336. Utils::throwError('20003:片段不存在');
  4337. }
  4338. $act = (array)$act;
  4339. $anime_id = getProp($act, 'anime_id');
  4340. $episode_id = getProp($act, 'episode_id');
  4341. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4342. $ace_mode = getProp($anime, 'ace_mode');
  4343. $art_style_type = getProp($anime, 'art_style_type');
  4344. $art_style = getProp($anime, 'art_style');
  4345. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4346. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4347. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4348. // 将资产中新出现的资产放到extra_products中
  4349. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4350. if (!empty($products) && $episode) {
  4351. // 获取剧集中的角色、场景和道具列表
  4352. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4353. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4354. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4355. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4356. // 构建角色名称列表
  4357. $role_names = array_column($roles, 'role');
  4358. // 构建场景名称列表
  4359. $scene_names = array_column($scenes, 'scene');
  4360. // 构建道具名称列表
  4361. $prop_names = array_column($props, 'prop');
  4362. // 遍历传入的products
  4363. foreach ($products as $product) {
  4364. $product_name = getProp($product, 'product_name');
  4365. // 如果product_name不在roles、scenes和props中
  4366. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4367. // 查找是否在extra_products中存在同名的
  4368. $found = false;
  4369. foreach ($extra_products as $key => $extra_product) {
  4370. if (getProp($extra_product, 'product_name') === $product_name) {
  4371. // 有同名的则覆盖
  4372. $extra_products[$key] = $product;
  4373. $found = true;
  4374. break;
  4375. }
  4376. }
  4377. // 没有则新增
  4378. if (!$found) {
  4379. $extra_products[] = $product;
  4380. }
  4381. }
  4382. }
  4383. if ($extra_products) {
  4384. // 保存到数据库
  4385. DB::table('mp_anime_episodes')
  4386. ->where('id', $episode_id)
  4387. ->update([
  4388. 'extra_products' => json_encode($extra_products, 256),
  4389. 'updated_at' => date('Y-m-d H:i:s')
  4390. ]);
  4391. }
  4392. }
  4393. // 获取分镜内容
  4394. $actContent = getProp($act, 'act_show_content', '');
  4395. // 音效同出(默认使用)
  4396. $current_generate_audio = $generate_audio ? 1 : 0;
  4397. // 处理视频模型(需在构建提示词之前解析:决定角色音色是否使用参考音频)
  4398. $model = getProp($data, 'model');
  4399. if (!$model) {
  4400. $model = getProp($episode, 'video_model');
  4401. if (!$model) {
  4402. // episode表也没有,使用默认值
  4403. $model = 'seed-2';
  4404. }
  4405. }
  4406. // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
  4407. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  4408. if (!in_array($model, $valid_models)) {
  4409. $model = 'seed-2';
  4410. }
  4411. // 构建完整的提示词
  4412. // 参考音频开关:调用方传 enable_reference_audio 优先,未传则读 ENABLE_REFERENCE_AUDIO(默认开启)
  4413. $supportAudioReference = $this->isReferenceAudioEnabled($data) && $this->isActReferenceAudioSupported($model);
  4414. // 先在提示词转换之前完成参考音频校验与截断(超出模型段数/时长上限的角色回退使用音色提示词)
  4415. $audioPlan = $supportAudioReference
  4416. ? $this->resolveActReferenceAudios($actContent, $products, $model)
  4417. : ['allowed' => [], 'excluded' => [], 'total_duration' => 0];
  4418. // 资产参考图同样先按模型上限(2.0=9张、2.5=30张)截断,保证提示词中的<图片N>与实际素材一一对应
  4419. $imagePlan = $this->resolveActReferenceImages($actContent, $products, $model);
  4420. $processResult = $this->processActContentWithProducts($actContent, $products, $supportAudioReference, $audioPlan['allowed'], $imagePlan['allowed']);
  4421. $fullPrompt = $processResult['content'];
  4422. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4423. // 参考图合并:资产参考图(已按模型上限截断)优先,调用方显式传入的参考图按剩余额度补充,超出时优先截断调用方传入的图
  4424. $asset_reference_images = $processResult['reference_images'];
  4425. $frontend_reference_images_all = array_values(array_unique(array_filter($reference_images)));
  4426. $frontend_reference_images = $frontend_reference_images_all;
  4427. if (!empty($imagePlan['limit'])) {
  4428. $remaining = max(0, $imagePlan['limit'] - count($asset_reference_images));
  4429. $frontend_reference_images = array_slice($frontend_reference_images, 0, $remaining);
  4430. }
  4431. $reference_images = array_values(array_unique(array_filter(array_merge($asset_reference_images, $frontend_reference_images))));
  4432. // 任务记录用:截断前的完整合并数组(正文内出现的资产图 + 调用方传入的参考图),便于追溯前端入参
  4433. $reference_images_all = array_values(array_unique(array_filter(array_merge(
  4434. $processResult['reference_images_all'] ?? $asset_reference_images,
  4435. $frontend_reference_images_all
  4436. ))));
  4437. // 角色音色参考音频(顺序与提示词中的<音频N>标记一一对应)
  4438. $reference_audios = $supportAudioReference ? ($processResult['reference_audios'] ?? []) : [];
  4439. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4440. // 保存到episode表(仅在专用方法中更新模型)
  4441. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4442. // 'video_model' => $model,
  4443. // 'updated_at' => date('Y-m-d H:i:s')
  4444. // ]);
  4445. // 余额预检:按预估时长计算所需积分,不足直接报错
  4446. $chargeDuration = (int)$videoDuration;
  4447. if ($chargeDuration <= 0) {
  4448. $chargeDuration = 5; // 无时长时按默认5秒预估
  4449. }
  4450. $this->pointsService->checkUserPointsEnough(
  4451. $this->pointsService->getVideoChargePoints([
  4452. 'model' => $model,
  4453. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4454. 'video_duration' => $chargeDuration,
  4455. 'ratio' => $ratio,
  4456. 'generate_audio' => $current_generate_audio,
  4457. ])
  4458. );
  4459. // 构建视频生成参数
  4460. $videoParams = [
  4461. 'model' => $model,
  4462. 'alias_act_id' => $act_id,
  4463. 'prompt' => trim($fullPrompt),
  4464. 'video_duration' => $videoDuration,
  4465. 'video_resolution' => $video_resolution,
  4466. 'seed' => -1,
  4467. 'ratio' => $ratio,
  4468. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4469. 'draft' => false,
  4470. 'watermark' => false,
  4471. 'camera_fixed' => false,
  4472. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4473. ];
  4474. // 如果分镜有图片,作为首帧
  4475. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4476. $hasVideo = !empty(getProp($act, 'video_url'));
  4477. if ($hasImage) {
  4478. if ($first_frame_url) {
  4479. $videoParams['first_frame_url'] = $first_frame_url;
  4480. }else {
  4481. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4482. }
  4483. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4484. }
  4485. // 构建content数组
  4486. $videoParams['content'] = [
  4487. [
  4488. 'type' => 'text',
  4489. 'text' => $videoParams['prompt'],
  4490. ]
  4491. ];
  4492. // 如果有首帧图片,添加到content中
  4493. if ($hasImage) {
  4494. 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'])) {
  4495. $videoParams['content'][] = [
  4496. 'type' => 'image_url',
  4497. 'image_url' => [
  4498. 'url' => $videoParams['first_frame_url'],
  4499. ],
  4500. 'role' => 'reference_image',
  4501. ];
  4502. if (isset($videoParams['tail_frame_url'])) {
  4503. $videoParams['content'][] = [
  4504. 'type' => 'image_url',
  4505. 'image_url' => [
  4506. 'url' => $videoParams['tail_frame_url'],
  4507. ],
  4508. 'role' => 'reference_image',
  4509. ];
  4510. }
  4511. }else {
  4512. $videoParams['content'][] = [
  4513. 'type' => 'image_url',
  4514. 'image_url' => [
  4515. 'url' => $videoParams['first_frame_url'],
  4516. ],
  4517. 'role' => 'first_frame',
  4518. ];
  4519. if (isset($videoParams['tail_frame_url'])) {
  4520. $videoParams['content'][] = [
  4521. 'type' => 'image_url',
  4522. 'image_url' => [
  4523. 'url' => $videoParams['tail_frame_url'],
  4524. ],
  4525. 'role' => 'last_frame',
  4526. ];
  4527. }
  4528. }
  4529. }
  4530. // dd($videoParams);
  4531. // 根据模型选择不同的视频生成方法
  4532. try {
  4533. if (strpos($model, 'jimeng') !== false) {
  4534. // 即梦模型参数调整
  4535. unset($videoParams['content']); // 即梦不使用content格式
  4536. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4537. } elseif (strpos($model, 'kling') !== false) {
  4538. // Keling模型参数调整
  4539. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4540. unset($videoParams['ratio']);
  4541. unset($videoParams['content']); // Keling不使用content格式
  4542. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4543. } elseif (strpos($model, 'zhizhen') !== false) {
  4544. // 智帧20等新模型使用统一API
  4545. // 构建统一API参数
  4546. $unifiedParams = [
  4547. 'model_code' => $model,
  4548. 'alias_act_id' => $act_id,
  4549. 'prompt' => trim($fullPrompt),
  4550. 'video_duration' => $videoDuration,
  4551. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4552. 'video_ratio' => $ratio,
  4553. 'seed' => -1,
  4554. ];
  4555. // 构建parameters参数
  4556. $parameters = [
  4557. 'seconds' => $unifiedParams['video_duration'],
  4558. 'resolution' => $unifiedParams['video_resolution'],
  4559. 'ratio' => $ratio,
  4560. // 'video_mode' => 'multi_image',
  4561. // 'mode' => 'multi_image',
  4562. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4563. ];
  4564. $hasImage = false;
  4565. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4566. if ($hasImage) {
  4567. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4568. if (isset($videoParams['tail_frame_url'])) {
  4569. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4570. }
  4571. } else {
  4572. // 没有图片时,记录错误日志
  4573. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4574. 'act_id' => $act_id,
  4575. 'model' => $model
  4576. ]);
  4577. }
  4578. if ($reference_images) {
  4579. // 参考图按模型上限截断(Seedance 2.0 系列=9张,2.5=30张)
  4580. $imageLimit = $this->getActReferenceImageLimit($model);
  4581. if ($imageLimit > 0) {
  4582. $reference_images = array_slice($reference_images, 0, $imageLimit);
  4583. }
  4584. // 任务记录用:保存截断前的完整参考图(含调用方传入),便于追溯前端入参
  4585. $unifiedParams['reference_images'] = $reference_images_all;
  4586. // 实际提交给大模型的参考图(截断后)
  4587. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4588. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4589. $parameters['reference_images'] = $reference_images;
  4590. $parameters['video_mode'] = 'multi_image';
  4591. $parameters['mode'] = 'multi_image';
  4592. }
  4593. // 角色音色参考音频:上传为素材并传入统一API(上传失败时清理提示词中的<音频N>标记)
  4594. if ($reference_audios) {
  4595. $unifiedParams['ref_audio_url'] = json_encode($reference_audios, 256);
  4596. // 任务记录:参考图与参考音频一起存入 ref_image_url
  4597. $unifiedParams['ref_image_url'] = $this->mergeReferenceAudiosIntoRefImageUrl($unifiedParams['ref_image_url'] ?? '', $reference_audios);
  4598. $reference_audio_assets = $this->processActReferenceAudiosToAssets($reference_audios, $model, $unifiedParams['prompt']);
  4599. $parameters['reference_audios'] = $reference_audio_assets;
  4600. // 音频素材上传失败的角色回退到音色提示词
  4601. $unifiedParams['prompt'] = $this->applyAudioVoiceFallbacks($unifiedParams['prompt'], $processResult['audio_voice_fallbacks'] ?? []);
  4602. $unifiedParams['prompt'] = trim($unifiedParams['prompt']);
  4603. }
  4604. $unifiedParams['parameters'] = $parameters;
  4605. // 调用统一API创建任务
  4606. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4607. } elseif ($this->isSeedance20SeriesModel($model)) {
  4608. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4609. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4610. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4611. // 任务记录用:保存截断前的完整合并数组(正文内资产图 + 调用方传入的参考图),便于追溯前端入参
  4612. $videoParams['reference_images'] = $reference_images_all;
  4613. if ($reference_images) {
  4614. // 参考图按模型上限截断(Seedance 2.0 系列=9张,2.5=30张)
  4615. $imageLimit = $this->getActReferenceImageLimit($model);
  4616. if ($imageLimit > 0) {
  4617. $reference_images = array_slice($reference_images, 0, $imageLimit);
  4618. }
  4619. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4620. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4621. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4622. $reference_image_assets = $isKuaikuai
  4623. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4624. : ($isDreamina
  4625. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $fullPrompt)
  4626. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt));
  4627. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4628. $videoParams['prompt'] = trim($fullPrompt);
  4629. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4630. $videoParams['reference_image_assets'] = $reference_image_assets;
  4631. }
  4632. // 角色音色参考音频:上传为素材并传入网关(上传失败时清理提示词中的<音频N>标记)
  4633. if ($reference_audios) {
  4634. $videoParams['ref_audio_url'] = json_encode($reference_audios, 256);
  4635. // 任务记录:参考图与参考音频一起存入 ref_image_url
  4636. $videoParams['ref_image_url'] = $this->mergeReferenceAudiosIntoRefImageUrl($videoParams['ref_image_url'] ?? '', $reference_audios);
  4637. $reference_audio_assets = $this->processActReferenceAudiosToAssets($reference_audios, $model, $fullPrompt);
  4638. // 音频素材上传失败的角色回退到音色提示词
  4639. $fullPrompt = $this->applyAudioVoiceFallbacks($fullPrompt, $processResult['audio_voice_fallbacks'] ?? []);
  4640. $videoParams['prompt'] = trim($fullPrompt);
  4641. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4642. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4643. }
  4644. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4645. if ($isKuaikuai) {
  4646. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4647. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4648. } else {
  4649. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4650. }
  4651. } else {
  4652. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4653. }
  4654. } catch (ApiException $e) {
  4655. // 上游调用抛出的网关异常统一做友好化处理;本地业务错误(非1001)保持原提示不变
  4656. if ($e->getCode() === 1001) {
  4657. Utils::throwError('1001:' . mapErrorMessage($e->getMessage()));
  4658. }
  4659. throw $e;
  4660. } catch (\Exception $e) {
  4661. // 其他未包装的异常,同样只对报错信息做格式化,便于前端展示友好提示
  4662. Utils::throwError('20003:' . mapErrorMessage($e->getMessage()));
  4663. }
  4664. // 更新分镜表的视频任务信息
  4665. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4666. 'video_task_id' => $task->id,
  4667. 'video_task_status' => '生成中',
  4668. 'generate_audio' => $generate_audio,
  4669. 'updated_at' => date('Y-m-d H:i:s')
  4670. ]);
  4671. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4672. $episode_number = getProp($act, 'episode_number');
  4673. $act_number = getProp($act, 'act_number');
  4674. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4675. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4676. }
  4677. $result = [
  4678. 'task_id' => $task->id,
  4679. 'status' => $task->status,
  4680. 'act_id' => $act_id,
  4681. 'video_duration' => $videoDuration
  4682. ];
  4683. // 仅当任务提交阶段就已失败时,附带格式化后的错误信息;正常返回结构不受影响
  4684. if ($task->status === 'failed' && !empty($task->error_message)) {
  4685. $result['error_message'] = mapErrorMessage($task->error_message);
  4686. }
  4687. return $result;
  4688. }
  4689. /**
  4690. * 文生视频通用方法
  4691. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4692. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4693. *
  4694. * @param array $data 请求参数
  4695. * @return array
  4696. */
  4697. public function generateVideo($data) {
  4698. $prompt = getProp($data, 'prompt');
  4699. if (empty($prompt)) {
  4700. Utils::throwError('20003:提示词不能为空');
  4701. }
  4702. $model = getProp($data, 'model');
  4703. if (!$model) {
  4704. $model = 'baidu-doubao-seedance-2-0-260128';
  4705. }
  4706. // 验证模型是否在可用模型表中
  4707. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4708. Utils::throwError('20003:该模型已不可用,请更换!');
  4709. }
  4710. $video_duration = getProp($data, 'video_duration', 5);
  4711. // 默认超分720p档(按480p生成后本地超分到720p);480p为原始档需前端显式指定
  4712. $video_resolution = getProp($data, 'video_resolution', 'sr_720p');
  4713. $ratio = getProp($data, 'ratio', '9:16');
  4714. $generate_audio = getProp($data, 'generate_audio', 1);
  4715. $seed = getProp($data, 'seed', -1);
  4716. $first_frame_url = getProp($data, 'first_frame_url');
  4717. $tail_frame_url = getProp($data, 'tail_frame_url');
  4718. // 参考图(支持数组或JSON字符串,最多9张)
  4719. $reference_images = getProp($data, 'reference_images', []);
  4720. if (is_string($reference_images)) {
  4721. $reference_images = json_decode($reference_images, true) ?: [];
  4722. }
  4723. if (!is_array($reference_images)) {
  4724. Utils::throwError('20003:参考图格式不正确');
  4725. }
  4726. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4727. $reference_images = array_slice($reference_images, 0, 9);
  4728. // 参考视频(支持数组或JSON字符串,最多3个)
  4729. $reference_videos = getProp($data, 'reference_videos', []);
  4730. if (is_string($reference_videos)) {
  4731. $reference_videos = json_decode($reference_videos, true) ?: [];
  4732. }
  4733. if (!is_array($reference_videos)) {
  4734. Utils::throwError('20003:参考视频格式不正确');
  4735. }
  4736. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4737. if (count($reference_videos) > 3) {
  4738. Utils::throwError('20003:参考视频最多选择3个');
  4739. }
  4740. $reference_videos = array_slice($reference_videos, 0, 3);
  4741. // 参考音频:以传入的 reference_audios 为准,有值即视为启用,无值即关闭
  4742. $reference_audios = getProp($data, 'reference_audios', []);
  4743. if (is_string($reference_audios)) {
  4744. $reference_audios = json_decode($reference_audios, true) ?: [];
  4745. }
  4746. if (!is_array($reference_audios)) {
  4747. Utils::throwError('20003:参考音频格式不正确');
  4748. }
  4749. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4750. $audioLimits = $this->getActAudioLimits($model);
  4751. if ($audioLimits) {
  4752. $reference_audios = $this->filterActReferenceAudios($reference_audios, $audioLimits);
  4753. } else {
  4754. // 非多模态参考音频模型:保留原有最多3段的限制
  4755. $reference_audios = array_slice($reference_audios, 0, 3);
  4756. }
  4757. // 余额预检:按预估时长计算所需积分,不足直接报错
  4758. $chargeDuration = (int)ceil((float)$video_duration);
  4759. if ($chargeDuration <= 0) {
  4760. $chargeDuration = 5; // 无时长时按默认5秒预估
  4761. }
  4762. $this->pointsService->checkUserPointsEnough(
  4763. $this->pointsService->getVideoChargePoints([
  4764. 'model' => $model,
  4765. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4766. 'video_duration' => $chargeDuration,
  4767. 'ratio' => $ratio,
  4768. 'generate_audio' => (int)$generate_audio,
  4769. ])
  4770. );
  4771. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4772. $videoParams = [
  4773. 'model' => $model,
  4774. 'prompt' => $prompt,
  4775. 'video_duration' => $video_duration,
  4776. 'video_resolution' => $video_resolution,
  4777. 'seed' => $seed,
  4778. 'ratio' => $ratio,
  4779. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4780. 'draft' => getProp($data, 'draft', false),
  4781. 'watermark' => getProp($data, 'watermark', false),
  4782. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4783. ];
  4784. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4785. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4786. // 构建content数组
  4787. $videoParams['content'] = [
  4788. [
  4789. 'type' => 'text',
  4790. 'text' => $prompt,
  4791. ]
  4792. ];
  4793. // 根据模型选择不同的视频生成方法
  4794. if (strpos($model, 'jimeng') !== false) {
  4795. // 即梦模型参数调整
  4796. unset($videoParams['content']); // 即梦不使用content格式
  4797. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4798. } elseif (strpos($model, 'kling') !== false) {
  4799. // 可灵模型参数调整
  4800. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4801. unset($videoParams['ratio']);
  4802. unset($videoParams['content']); // 可灵不使用content格式
  4803. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4804. } elseif (strpos($model, 'zhizhen') !== false) {
  4805. // 智帧等新模型使用统一API
  4806. $unifiedParams = [
  4807. 'model_code' => $model,
  4808. 'prompt' => $prompt,
  4809. 'video_duration' => $video_duration,
  4810. 'video_resolution' => strtolower($video_resolution),
  4811. 'video_ratio' => $ratio,
  4812. 'seed' => $seed,
  4813. ];
  4814. // 构建parameters参数
  4815. $parameters = [
  4816. 'seconds' => $unifiedParams['video_duration'],
  4817. 'resolution' => $unifiedParams['video_resolution'],
  4818. 'ratio' => $ratio,
  4819. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4820. ];
  4821. // 首帧和尾帧
  4822. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4823. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4824. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4825. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4826. if ($refImageUrls) {
  4827. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4828. }
  4829. // 参考图处理
  4830. if ($reference_images) {
  4831. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4832. $parameters['reference_images'] = $reference_images;
  4833. $parameters['video_mode'] = 'multi_image';
  4834. $parameters['mode'] = 'multi_image';
  4835. }
  4836. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4837. if ($reference_videos) {
  4838. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4839. $parameters['reference_videos'] = $reference_videos;
  4840. }
  4841. if ($reference_audios) {
  4842. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4843. $parameters['reference_audios'] = $reference_audios;
  4844. }
  4845. $unifiedParams['parameters'] = $parameters;
  4846. // 调用统一API创建任务
  4847. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4848. } elseif ($this->isSeedance20SeriesModel($model)) {
  4849. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4850. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4851. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4852. $videoParams['reference_images'] = $reference_images;
  4853. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4854. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4855. if ($refImageUrls) {
  4856. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4857. }
  4858. if ($reference_images) {
  4859. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI)
  4860. $reference_image_assets = $isKuaikuai
  4861. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4862. : ($isDreamina
  4863. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $videoParams['prompt'])
  4864. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']));
  4865. $videoParams['reference_image_assets'] = $reference_image_assets;
  4866. }
  4867. // 参考视频上传为素材(国内百度/海外百度dreamina/快快AI)
  4868. if ($reference_videos) {
  4869. $reference_video_assets = $isKuaikuai
  4870. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4871. : ($isDreamina
  4872. ? $this->aiVideoGenerationService->processReferenceVideosToBaiduDreaminaAssets($reference_videos, $videoParams['prompt'])
  4873. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']));
  4874. $videoParams['reference_video_assets'] = $reference_video_assets;
  4875. }
  4876. // 参考音频上传为素材(国内百度/海外百度dreamina/快快AI)
  4877. if ($reference_audios) {
  4878. $reference_audio_assets = $isKuaikuai
  4879. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4880. : ($isDreamina
  4881. ? $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($reference_audios, $videoParams['prompt'])
  4882. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']));
  4883. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4884. }
  4885. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4886. if ($reference_images || $reference_videos || $reference_audios) {
  4887. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4888. }
  4889. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4890. if ($isKuaikuai) {
  4891. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4892. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4893. } else {
  4894. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4895. }
  4896. } else {
  4897. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4898. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4899. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4900. if ($refImageUrls) {
  4901. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4902. }
  4903. if ($reference_videos) {
  4904. foreach ($reference_videos as $videoUrl) {
  4905. $videoParams['content'][] = [
  4906. 'type' => 'video_url',
  4907. 'video_url' => [
  4908. 'url' => $videoUrl,
  4909. ],
  4910. 'role' => 'reference_video',
  4911. ];
  4912. }
  4913. }
  4914. if ($reference_audios) {
  4915. foreach ($reference_audios as $audioUrl) {
  4916. $videoParams['content'][] = [
  4917. 'type' => 'audio_url',
  4918. 'audio_url' => [
  4919. 'url' => $audioUrl,
  4920. ],
  4921. 'role' => 'reference_audio',
  4922. ];
  4923. }
  4924. }
  4925. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4926. }
  4927. return [
  4928. 'task_id' => $task->id,
  4929. 'status' => $task->status,
  4930. 'model' => $model,
  4931. 'video_duration' => $video_duration,
  4932. 'video_resolution' => $video_resolution,
  4933. 'ratio' => $ratio
  4934. ];
  4935. }
  4936. /**
  4937. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4938. *
  4939. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4940. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4941. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4942. *
  4943. * @param array $data
  4944. * @return array
  4945. */
  4946. public function previewCharge(array $data): array
  4947. {
  4948. $mode = (string)getProp($data, 'mode', '');
  4949. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4950. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4951. }
  4952. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4953. $scene = (string)getProp($data, 'scene', 'video_generation');
  4954. // 未显式传scene且带参考视频时,自动按video_to_video定价
  4955. if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
  4956. $scene = 'video_to_video';
  4957. }
  4958. $items = [];
  4959. $model = '';
  4960. $resolution = '';
  4961. if ($mode === 'video') {
  4962. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4963. $model = (string)getProp($data, 'model', '');
  4964. if (!$model) {
  4965. Utils::throwError('1002:model参数不能为空');
  4966. }
  4967. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4968. $duration = (int)getProp($data, 'video_duration', 5);
  4969. if ($duration <= 0) {
  4970. $duration = 5;
  4971. }
  4972. $count = max(1, (int)getProp($data, 'count', 1));
  4973. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4974. 'model' => $model,
  4975. 'video_resolution' => $resolution,
  4976. 'video_duration' => $duration,
  4977. 'mode' => $scene,
  4978. ]);
  4979. $points = $pointsPerVideo * $count;
  4980. $items[] = [
  4981. 'type' => 'video',
  4982. 'model' => $model,
  4983. 'video_resolution' => $resolution,
  4984. 'video_duration' => $duration,
  4985. 'count' => $count,
  4986. 'points' => $points,
  4987. ];
  4988. } elseif ($mode === 'image') {
  4989. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4990. $model = (string)getProp($data, 'model', '');
  4991. if (!$model) {
  4992. Utils::throwError('1002:model参数不能为空');
  4993. }
  4994. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4995. if (!$resolution) {
  4996. $width = (int)getProp($data, 'width', 0);
  4997. $height = (int)getProp($data, 'height', 0);
  4998. if ($width <= 0 || $height <= 0) {
  4999. $width = 1600;
  5000. $height = 2848;
  5001. }
  5002. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  5003. }
  5004. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  5005. $points = $this->pointsService->getImageChargePoints([
  5006. 'model' => $model,
  5007. 'resolution' => $resolution,
  5008. ]) * $imageNum;
  5009. $items[] = [
  5010. 'type' => 'image',
  5011. 'model' => $model,
  5012. 'resolution' => $resolution,
  5013. 'image_num' => $imageNum,
  5014. 'points' => $points,
  5015. ];
  5016. } else {
  5017. // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
  5018. // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
  5019. $priceType = (string)getProp($data, 'price_type', 'special');
  5020. if (!in_array($priceType, ['special', 'normal'], true)) {
  5021. Utils::throwError('1003:price_type参数仅支持special或normal');
  5022. }
  5023. $count = max(1, (int)getProp($data, 'count', 1));
  5024. $animeId = getProp($data, 'anime_id');
  5025. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  5026. if ($animeId && $generateEpisodes > 0) {
  5027. // 批量生成分集按 special 档预估,与实际扣费口径一致
  5028. $priceType = 'special';
  5029. $currentMaxEpisode = DB::table('mp_anime_episodes')
  5030. ->where('anime_id', $animeId)
  5031. ->where('is_default', 1)
  5032. ->max('episode_number');
  5033. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  5034. $startEpisodeNumber = $currentMaxEpisode + 1;
  5035. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  5036. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  5037. ->where('anime_id', $animeId)
  5038. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  5039. ->whereIn('status', ['pending', 'processing', 'completed'])
  5040. ->count();
  5041. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  5042. if ($count < 0) {
  5043. $count = 0;
  5044. }
  5045. }
  5046. $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
  5047. $items[] = [
  5048. 'type' => 'chat',
  5049. 'count' => $count,
  5050. 'price_type' => $priceType,
  5051. 'points' => $points,
  5052. ];
  5053. }
  5054. $totalPoints = 0;
  5055. foreach ($items as $item) {
  5056. $totalPoints += $item['points'];
  5057. }
  5058. return [
  5059. 'mode' => $mode,
  5060. 'total_points' => $totalPoints,
  5061. 'items' => $items,
  5062. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  5063. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  5064. ];
  5065. }
  5066. /**
  5067. * 根据提示词内容智能计算最优视频时长
  5068. *
  5069. * @param string $segmentContent 分镜内容
  5070. * @param string $tailFrame 尾帧描述
  5071. * @return int 视频时长(2-12秒)
  5072. */
  5073. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  5074. // 合并所有文本内容
  5075. $fullText = trim($segmentContent . ' ' . $tailFrame);
  5076. // 如果没有内容,返回默认时长
  5077. if (empty($fullText)) {
  5078. return 5;
  5079. }
  5080. // 计算文本长度(中文字符按2个字符计算)
  5081. $textLength = mb_strlen($fullText, 'UTF-8');
  5082. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  5083. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  5084. // 分析内容复杂度
  5085. $complexityScore = $this->analyzeContentComplexity($fullText);
  5086. // 基础时长计算(根据文本长度)
  5087. $baseDuration = 3; // 默认2秒
  5088. // if ($adjustedLength <= 20) {
  5089. // $baseDuration = 3;
  5090. // } elseif ($adjustedLength <= 40) {
  5091. // $baseDuration = 4;
  5092. // } elseif ($adjustedLength <= 60) {
  5093. // $baseDuration = 5;
  5094. // } elseif ($adjustedLength <= 80) {
  5095. // $baseDuration = 6;
  5096. // } elseif ($adjustedLength <= 100) {
  5097. // $baseDuration = 7;
  5098. // } elseif ($adjustedLength <= 120) {
  5099. // $baseDuration = 8;
  5100. // } else {
  5101. // $baseDuration = 9;
  5102. // }
  5103. // 根据内容复杂度调整时长
  5104. $finalDuration = $baseDuration + $complexityScore;
  5105. // 确保时长在2-12秒范围内
  5106. return max(4, min(12, $finalDuration));
  5107. }
  5108. /**
  5109. * 分析内容复杂度,返回时长调整值
  5110. *
  5111. * @param string $text 文本内容
  5112. * @return int 调整值(-2到+3)
  5113. */
  5114. private function analyzeContentComplexity($text) {
  5115. $score = 0;
  5116. // 动作关键词(需要更长时间展现)
  5117. $actionKeywords = [
  5118. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  5119. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  5120. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  5121. ];
  5122. // 静态关键词(可以用较短时间)
  5123. $staticKeywords = [
  5124. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  5125. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  5126. ];
  5127. // 复杂场景关键词(需要更长时间)
  5128. $complexSceneKeywords = [
  5129. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  5130. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  5131. ];
  5132. // 情感关键词(需要适中时间表现)
  5133. $emotionKeywords = [
  5134. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  5135. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  5136. ];
  5137. // 检查动作关键词
  5138. foreach ($actionKeywords as $keyword) {
  5139. if (strpos($text, $keyword) !== false) {
  5140. $score += 1;
  5141. break; // 避免重复加分
  5142. }
  5143. }
  5144. // 检查静态关键词
  5145. foreach ($staticKeywords as $keyword) {
  5146. if (strpos($text, $keyword) !== false) {
  5147. $score -= 1;
  5148. break;
  5149. }
  5150. }
  5151. // 检查复杂场景关键词
  5152. foreach ($complexSceneKeywords as $keyword) {
  5153. if (strpos($text, $keyword) !== false) {
  5154. $score += 1;
  5155. break;
  5156. }
  5157. }
  5158. // 检查情感关键词
  5159. foreach ($emotionKeywords as $keyword) {
  5160. if (strpos($text, $keyword) !== false) {
  5161. $score += 1;
  5162. break;
  5163. }
  5164. }
  5165. // 检查时间相关词汇
  5166. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  5167. $score += 1;
  5168. }
  5169. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  5170. $score -= 1;
  5171. }
  5172. // 检查转场词汇
  5173. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  5174. $score += 1;
  5175. }
  5176. // 检查环境描述(复杂环境需要更多时间)
  5177. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  5178. $score += 1;
  5179. }
  5180. // 检查对话内容(对话需要更多时间)
  5181. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  5182. $score += 1;
  5183. }
  5184. // 限制调整范围
  5185. return max(-1, min(4, $score));
  5186. }
  5187. /**
  5188. * 创建完整视频合成任务
  5189. *
  5190. * @param array $data
  5191. * @return array
  5192. */
  5193. public function createCompleteVideoTask($data)
  5194. {
  5195. $animeId = getProp($data, 'anime_id');
  5196. $episodeId = getProp($data, 'episode_id');
  5197. // 验证参数
  5198. if (!$animeId || !$episodeId) {
  5199. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  5200. }
  5201. // 检查是否已存在处理中的任务
  5202. $existingTask = DB::table('mp_complete_video_tasks')
  5203. ->where('anime_id', $animeId)
  5204. ->where('episode_id', $episodeId)
  5205. ->whereIn('generate_status', ['执行中'])
  5206. ->first();
  5207. if ($existingTask) {
  5208. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  5209. }
  5210. // 获取全能模式状态
  5211. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  5212. if ((int)$ace_mode === 1) {
  5213. // 获取所有片段的配音视频,按 act_number 排序
  5214. $segments = DB::table('mp_episode_segments')
  5215. ->where('anime_id', $animeId)
  5216. ->where('episode_id', $episodeId)
  5217. ->orderBy('segment_number')
  5218. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5219. ->get();
  5220. // 检查是否所有片段都有视频
  5221. $missingVideos = $segments->filter(function($segment) {
  5222. return empty($segment->video_url);
  5223. });
  5224. if ($missingVideos->isNotEmpty()) {
  5225. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  5226. }
  5227. }else {
  5228. // 获取所有分镜的配音视频,按 segment_number 排序
  5229. $segments = DB::table('mp_episode_segments')
  5230. ->where('anime_id', $animeId)
  5231. ->where('episode_id', $episodeId)
  5232. ->orderBy('segment_number')
  5233. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5234. ->get();
  5235. // 检查是否所有分镜都有配音和视频
  5236. $missingVideos = $segments->filter(function($segment) {
  5237. return empty($segment->audio_url) || empty($segment->video_url);
  5238. });
  5239. if ($missingVideos->isNotEmpty()) {
  5240. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5241. }
  5242. }
  5243. if ($segments->isEmpty()) {
  5244. Utils::throwError('20003:未找到该剧集的分镜数据');
  5245. }
  5246. // 获取当前完整视频url
  5247. $completeVideoUrl = DB::table('mp_anime_episodes')
  5248. ->where('anime_id', $animeId)
  5249. ->where('id', $episodeId)
  5250. ->value('complete_video_url');
  5251. // 构建 generate_json
  5252. $generateJson = [];
  5253. $sequence = 1;
  5254. foreach ($segments as $segment) {
  5255. if ((int)$ace_mode === 1) {
  5256. $generateJson[] = [
  5257. 'sequence' => $sequence++,
  5258. 'video_url' => $segment->video_url,
  5259. 'video_time_point_start' => $segment->video_time_point_start,
  5260. 'video_time_point_end' => $segment->video_time_point_end
  5261. ];
  5262. }else {
  5263. $generateJson[] = [
  5264. 'sequence' => $sequence++,
  5265. 'video_url' => $segment->video_url,
  5266. 'audio_url' => $segment->audio_url,
  5267. 'video_time_point_start' => $segment->video_time_point_start,
  5268. 'video_time_point_end' => $segment->video_time_point_end
  5269. ];
  5270. }
  5271. }
  5272. // 创建任务
  5273. $now = date('Y-m-d H:i:s');
  5274. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5275. 'anime_id' => $animeId,
  5276. 'episode_id' => $episodeId,
  5277. 'generate_json' => json_encode($generateJson, 256),
  5278. 'generate_status' => '执行中',
  5279. 'complete_video_url' => '',
  5280. 'created_at' => $now,
  5281. 'updated_at' => $now
  5282. ]);
  5283. if (!$taskId) {
  5284. Utils::throwError('20003:创建任务失败');
  5285. }
  5286. // 更新剧集表的任务ID和状态
  5287. $boolen = DB::table('mp_anime_episodes')
  5288. ->where('anime_id', $animeId)
  5289. ->where('id', $episodeId)
  5290. ->update([
  5291. 'complete_video_task_id' => $taskId,
  5292. 'complete_video_task_status' => '执行中',
  5293. 'updated_at' => $now
  5294. ]);
  5295. if (!$boolen) {
  5296. Utils::throwError('20003:更新剧集表失败');
  5297. }
  5298. dLog('anime')->info('创建完整视频合成任务', [
  5299. 'task_id' => $taskId,
  5300. 'anime_id' => $animeId,
  5301. 'episode_id' => $episodeId,
  5302. 'segment_count' => count($generateJson)
  5303. ]);
  5304. // 请求远程服务器执行生成
  5305. $client = new Client(['timeout' => 600, 'verify' => false]);
  5306. try {
  5307. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5308. $response = $result->getBody()->getContents();
  5309. $response_arr = json_decode($response, true);
  5310. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5311. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5312. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5313. // // 更新任务状态为失败
  5314. // DB::table('mp_complete_video_tasks')
  5315. // ->where('id', $taskId)
  5316. // ->update([
  5317. // 'generate_status' => '执行失败',
  5318. // 'error_message' => $error_msg,
  5319. // 'updated_at' => date('Y-m-d H:i:s')
  5320. // ]);
  5321. // // 同步更新剧集表状态
  5322. // DB::table('mp_anime_episodes')
  5323. // ->where('complete_video_task_id', $taskId)
  5324. // ->update([
  5325. // 'complete_video_task_status' => '执行失败',
  5326. // 'updated_at' => date('Y-m-d H:i:s')
  5327. // ]);
  5328. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5329. }
  5330. } catch (\Exception $e) {
  5331. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5332. // 更新任务状态为失败
  5333. DB::table('mp_complete_video_tasks')
  5334. ->where('id', $taskId)
  5335. ->update([
  5336. 'generate_status' => '执行失败',
  5337. 'error_message' => $e->getMessage(),
  5338. 'updated_at' => date('Y-m-d H:i:s')
  5339. ]);
  5340. // 同步更新剧集表状态
  5341. DB::table('mp_anime_episodes')
  5342. ->where('complete_video_task_id', $taskId)
  5343. ->update([
  5344. 'complete_video_task_status' => '执行失败',
  5345. 'updated_at' => date('Y-m-d H:i:s')
  5346. ]);
  5347. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5348. }
  5349. // 开始轮询任务状态
  5350. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5351. $pollInterval = 5; // 每5秒轮询一次
  5352. $attempt = 0;
  5353. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5354. while ($attempt < $maxAttempts) {
  5355. sleep($pollInterval);
  5356. $attempt++;
  5357. // 查询任务状态
  5358. $task = DB::table('mp_complete_video_tasks')
  5359. ->where('id', $taskId)
  5360. ->first();
  5361. if (!$task) {
  5362. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5363. Utils::throwError('20003:任务不存在');
  5364. }
  5365. dLog('anime')->info('轮询任务状态', [
  5366. 'task_id' => $taskId,
  5367. 'attempt' => $attempt,
  5368. 'status' => $task->generate_status
  5369. ]);
  5370. // 检查任务是否完成
  5371. if ($task->generate_status === '执行成功') {
  5372. // 同步更新剧集表状态
  5373. $boolen3 = DB::table('mp_anime_episodes')
  5374. ->where('anime_id', $animeId)
  5375. ->where('id', $episodeId)
  5376. ->update([
  5377. 'complete_video_url' => $task->complete_video_url,
  5378. 'complete_video_task_status' => '执行成功',
  5379. 'updated_at' => date('Y-m-d H:i:s')
  5380. ]);
  5381. dLog('anime')->info('视频合成任务完成', [
  5382. 'task_id' => $taskId,
  5383. 'video_url' => $task->complete_video_url,
  5384. 'attempts' => $attempt
  5385. ]);
  5386. // 如果更新成功则远程删除之前的文件
  5387. if ($boolen3 && $completeVideoUrl) {
  5388. $encode_url = urlencode($completeVideoUrl);
  5389. $client = new Client(['timeout' => 300, 'verify' => false]);
  5390. // 根据ID通过API通知合成音频
  5391. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5392. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5393. $response = $result->getBody()->getContents();
  5394. $response_arr = json_decode($response, true);
  5395. Log::info('火山删除音频返回: '.$response);
  5396. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5397. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5398. Log::info('火山删除音频失败: '.$error_msg);
  5399. // Utils::throwError('20003:火山删除音频失败');
  5400. }
  5401. }
  5402. return [
  5403. 'task_id' => $taskId,
  5404. 'anime_id' => $animeId,
  5405. 'episode_id' => $episodeId,
  5406. 'segment_count' => count($generateJson),
  5407. 'generate_status' => '执行成功',
  5408. 'complete_video_url' => $task->complete_video_url,
  5409. ];
  5410. }
  5411. // 检查任务是否失败
  5412. if ($task->generate_status === '执行失败') {
  5413. // 同步更新剧集表状态
  5414. DB::table('mp_anime_episodes')
  5415. ->where('anime_id', $animeId)
  5416. ->where('id', $episodeId)
  5417. ->update([
  5418. 'complete_video_task_status' => '执行失败',
  5419. 'updated_at' => date('Y-m-d H:i:s')
  5420. ]);
  5421. $errorMessage = $task->error_message ?? '未知错误';
  5422. dLog('anime')->error('视频合成任务失败', [
  5423. 'task_id' => $taskId,
  5424. 'error' => $errorMessage,
  5425. 'attempts' => $attempt
  5426. ]);
  5427. return [
  5428. 'task_id' => $taskId,
  5429. 'anime_id' => $animeId,
  5430. 'episode_id' => $episodeId,
  5431. 'segment_count' => count($generateJson),
  5432. 'generate_status' => '执行失败',
  5433. 'error_message' => $errorMessage
  5434. ];
  5435. }
  5436. }
  5437. // 超时处理
  5438. dLog('anime')->warning('视频合成任务超时', [
  5439. 'task_id' => $taskId,
  5440. 'max_attempts' => $maxAttempts,
  5441. 'timeout_seconds' => $maxAttempts * $pollInterval
  5442. ]);
  5443. // 更新任务状态为超时
  5444. DB::table('mp_complete_video_tasks')
  5445. ->where('id', $taskId)
  5446. ->update([
  5447. 'generate_status' => '超时',
  5448. 'error_message' => '任务执行超时(5分钟)',
  5449. 'updated_at' => date('Y-m-d H:i:s')
  5450. ]);
  5451. return [
  5452. 'task_id' => $taskId,
  5453. 'anime_id' => $animeId,
  5454. 'episode_id' => $episodeId,
  5455. 'segment_count' => count($generateJson),
  5456. 'generate_status' => '超时',
  5457. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5458. ];
  5459. }
  5460. /**
  5461. * 根据 inner_prompt_type 附加内置提示词
  5462. *
  5463. * @param string $prompt 用户提示词
  5464. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5465. * @return string 合并后的提示词
  5466. */
  5467. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5468. {
  5469. $innerPromptMap = [
  5470. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。',
  5471. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5472. ];
  5473. if (!isset($innerPromptMap[$innerPromptType])) {
  5474. return $prompt;
  5475. }
  5476. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5477. }
  5478. /**
  5479. * 根据 inner_prompt_type 获取生成图片数量
  5480. *
  5481. * @param int $innerPromptType 内置提示词类型
  5482. * @param int $imageNum 传入的图片张数
  5483. * @return int 图片数量
  5484. */
  5485. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5486. {
  5487. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5488. }
  5489. /**
  5490. * 提取图片生成结果URL
  5491. *
  5492. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5493. * @param int $innerPromptType 内置提示词类型
  5494. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5495. */
  5496. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5497. {
  5498. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5499. if (is_array($resultUrls) && !empty($resultUrls)) {
  5500. $resultUrls = array_values($resultUrls);
  5501. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5502. }
  5503. if (!empty($resultUrl)) {
  5504. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5505. }
  5506. return (int)$innerPromptType === 2 ? [] : '';
  5507. }
  5508. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5509. $prompt = getProp($data, 'prompt');
  5510. $episode_id = getProp($data, 'episode_id');
  5511. $ref_img_urls = getProp($data, 'ref_img_urls');
  5512. $ratio = getProp($data, 'ratio', '9:16');
  5513. $resolution = getProp($data, 'resolution', '2k');
  5514. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5515. $imageNum = (int)getProp($data, 'image_num', 1);
  5516. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  5517. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  5518. // 参数验证
  5519. $resolution = strtolower($resolution);
  5520. if (!isset($sizeMap[$resolution])) {
  5521. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5522. }
  5523. if (!isset($sizeMap[$resolution][$ratio])) {
  5524. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5525. }
  5526. // 根据 ratio 和 resolution 确定宽高
  5527. $width = $sizeMap[$resolution][$ratio]['width'];
  5528. $height = $sizeMap[$resolution][$ratio]['height'];
  5529. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5530. if (is_json($ref_img_urls)) {
  5531. $ref_img_urls = json_decode($ref_img_urls, true);
  5532. }else {
  5533. $ref_img_urls = explode(',', $ref_img_urls);
  5534. }
  5535. }
  5536. // 处理图片模型
  5537. $model = getProp($data, 'model');
  5538. if (!$model) {
  5539. // 用户没有输入,从episode表获取
  5540. if ($episode_id) {
  5541. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5542. $model = getProp($episode, 'image_model');
  5543. }
  5544. if (!$model) {
  5545. // episode表也没有,使用默认值
  5546. $model = 'gpt-image-2';
  5547. }
  5548. }
  5549. // 验证模型是否在可用模型表中
  5550. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5551. // $model = 'gpt-image-2';
  5552. Utils::throwError('20003:该模型已不可用,请更换!');
  5553. }
  5554. // 保存到episode表
  5555. if ($episode_id) {
  5556. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5557. 'image_model' => $model,
  5558. 'updated_at' => date('Y-m-d H:i:s')
  5559. ]);
  5560. }
  5561. // 参数验证
  5562. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5563. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5564. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5565. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5566. try {
  5567. // 创建图片生成任务
  5568. $params = [
  5569. 'prompt' => $prompt,
  5570. 'model' => $model,
  5571. 'ref_img_urls' => '',
  5572. 'width' => $width,
  5573. 'height' => $height,
  5574. 'image_num' => $imageNum,
  5575. // 计费锚点(动漫/剧集/剧本),上下文没有时不记录
  5576. 'anime_id' => getProp($data, 'anime_id'),
  5577. 'episode_id' => $episode_id,
  5578. ];
  5579. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5580. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5581. $task_id = $task->id;
  5582. if (!$task_id) {
  5583. Utils::throwError('20003:创建图片生成任务失败');
  5584. }
  5585. // 创建任务中心记录并关联图片任务ID
  5586. $taskCenter = $this->taskCenterService->createTask('image', [
  5587. 'title' => '文生图',
  5588. 'ref_task_id' => $task_id,
  5589. // 'prompt' => $prompt,
  5590. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5591. ]);
  5592. $taskCenterId = $taskCenter->id;
  5593. // 组装本次任务信息(用于init消息,类似generateVideo)
  5594. $taskInfo = [
  5595. 'task_id' => $task_id,
  5596. 'status' => getProp($task, 'status', 'processing'),
  5597. 'model' => $model,
  5598. 'ratio' => $ratio,
  5599. 'resolution' => $resolution,
  5600. 'image_num' => $imageNum,
  5601. ];
  5602. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5603. if (is_callable($onTaskCreated)) {
  5604. $onTaskCreated($taskCenterId, $taskInfo);
  5605. }
  5606. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5607. $model = getProp($task, 'model');
  5608. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5609. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5610. $isSyncModel = $isVolcModel || $isGptModel;
  5611. // 任务需要轮询获取结果(15分钟超时,每3秒查询一次)
  5612. $start_time = time();
  5613. $timeout = 900; // 15分钟
  5614. $img_url = '';
  5615. $img_urls = [];
  5616. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5617. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5618. while (time() - $start_time < $timeout) {
  5619. sleep(3);
  5620. // 每分钟发送一次队列状态消息(仅流式模式)
  5621. if (is_callable($onPoll)) {
  5622. $currentTime = time();
  5623. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5624. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5625. $lastQueueMessageTime = $currentTime;
  5626. }
  5627. }
  5628. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5629. if ($isSyncModel) {
  5630. // 刷新任务状态
  5631. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5632. if ($task->status === 'success' && $task->result_url) {
  5633. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5634. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5635. if (!empty($resultUrls)) {
  5636. $img_urls = $resultUrls;
  5637. $img_url = $resultUrls[0];
  5638. } else {
  5639. $img_url = (string)$task->result_url;
  5640. }
  5641. break;
  5642. } elseif ($task->status === 'failed') {
  5643. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5644. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5645. }
  5646. // // 如果还在处理中,提示用户稍后查看
  5647. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5648. }else {
  5649. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5650. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5651. if ($statusInfo['status'] === 'success') {
  5652. $task->updateStatus('success', [
  5653. 'result_url' => $statusInfo['result_url'],
  5654. 'result_json' => $statusInfo['result_json'] ?? []
  5655. ]);
  5656. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5657. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5658. if (!empty($resultUrls)) {
  5659. $img_urls = $resultUrls;
  5660. $img_url = $resultUrls[0];
  5661. } else {
  5662. $img_url = (string)$statusInfo['result_url'];
  5663. }
  5664. break;
  5665. } elseif ($statusInfo['status'] === 'failed') {
  5666. $task->updateStatus('failed', [
  5667. 'error_message' => $statusInfo['error_message'],
  5668. 'result_json' => $statusInfo['result_json'] ?? []
  5669. ]);
  5670. dLog('anime')->error('图片生成失败,', [
  5671. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5672. ]);
  5673. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5674. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5675. }
  5676. }
  5677. }
  5678. if (empty($img_url)) {
  5679. Utils::throwError('20003:图片生成超时,请稍后重试');
  5680. }
  5681. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5682. if (count($img_urls) > 1) {
  5683. return [
  5684. 'img_url' => $img_url,
  5685. 'image_urls' => $img_urls,
  5686. 'task_id' => $taskCenterId,
  5687. ];
  5688. }
  5689. return [
  5690. 'img_url' => $img_url,
  5691. 'task_id' => $taskCenterId,
  5692. ];
  5693. } catch (\Exception $e) {
  5694. dLog('anime')->error('更新角色或场景失败', [
  5695. 'error' => $e->getMessage()
  5696. ]);
  5697. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5698. Utils::throwError('20003:' . $e->getMessage());
  5699. }
  5700. }
  5701. /**
  5702. * 使用文生文模型解析分镜内容
  5703. */
  5704. private function parseSegmentContentWithAI($segment_content) {
  5705. try {
  5706. // 使用DeepSeek服务的公开方法解析分镜内容
  5707. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5708. } catch (\Exception $e) {
  5709. // 如果AI解析失败,记录日志并返回原内容
  5710. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5711. return $segment_content;
  5712. }
  5713. }
  5714. /**
  5715. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5716. *
  5717. * @param int $episode_id 分集ID
  5718. * @param int $anime_id 动漫ID
  5719. * @param array $roles 分集角色数组(引用传递)
  5720. * @param array $scenes 分集场景数组(引用传递)
  5721. * @param array $episode 分集数据
  5722. */
  5723. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5724. // 获取全局动漫的角色和场景数据
  5725. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5726. if (!$anime) return;
  5727. $art_style_type = getProp($anime, 'art_style_type');
  5728. $character_prefix = '';
  5729. $scene_prefix = '';
  5730. if ($art_style_type) {
  5731. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5732. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5733. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5734. }
  5735. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5736. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5737. $roles_updated = false;
  5738. $scenes_updated = false;
  5739. // 处理角色
  5740. foreach ($roles as &$role) {
  5741. $role_name = getProp($role, 'role');
  5742. $role_description = getProp($role, 'description');
  5743. $role_pic_prompt = getProp($role, 'pic_prompt');
  5744. $role_url = getProp($role, 'url');
  5745. $role_task_id = getProp($role, 'task_id');
  5746. // 如果已有URL或已有任务ID,跳过
  5747. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5748. continue;
  5749. }
  5750. $url_inherited = false;
  5751. // 尝试从全局数据中继承
  5752. foreach ($global_roles as $global_role) {
  5753. $global_role_name = getProp($global_role, 'role');
  5754. $global_role_description = getProp($global_role, 'description');
  5755. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5756. $global_role_url = getProp($global_role, 'url');
  5757. $global_role_task_id = getProp($global_role, 'task_id');
  5758. $global_role_task_status = getProp($global_role, 'task_status');
  5759. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5760. if ($role_name === $global_role_name
  5761. && $role_description === $global_role_description
  5762. && $role_pic_prompt === $global_role_pic_prompt
  5763. && !empty($global_role_url)) {
  5764. // 继承 task_id、task_status 和 url
  5765. $role['task_id'] = $global_role_task_id;
  5766. $role['task_status'] = $global_role_task_status;
  5767. $role['url'] = $global_role_url;
  5768. $roles_updated = true;
  5769. $url_inherited = true;
  5770. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5771. break;
  5772. }
  5773. }
  5774. // 如果无法继承且没有任务ID,创建新任务
  5775. if (!$url_inherited && empty($role_task_id)) {
  5776. try {
  5777. $art_style = getProp($episode, 'art_style');
  5778. // 优先使用 pic_prompt,如果没有则使用 description
  5779. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5780. // if ($art_style) {
  5781. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5782. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5783. // }
  5784. $description = buildStylePromptPrefix($character_prefix) . "主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5785. $params = [
  5786. 'prompt' => $description,
  5787. 'ref_img_urls' => [],
  5788. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  5789. 'anime_id' => $anime_id,
  5790. 'episode_id' => $episode_id,
  5791. 'episode_number' => getProp($episode, 'episode_number'),
  5792. ];
  5793. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5794. $task_id = $task->id;
  5795. if ($task_id) {
  5796. $role['task_id'] = $task_id;
  5797. $role['task_status'] = 'processing';
  5798. $roles_updated = true;
  5799. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5800. }
  5801. } catch (\Exception $e) {
  5802. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5803. }
  5804. }
  5805. }
  5806. // 处理场景
  5807. foreach ($scenes as &$scene) {
  5808. $scene_name = getProp($scene, 'scene');
  5809. $scene_description = getProp($scene, 'description');
  5810. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5811. $scene_url = getProp($scene, 'url');
  5812. $scene_task_id = getProp($scene, 'task_id');
  5813. // 如果已有URL或已有任务ID,跳过
  5814. if (!empty($scene_url) || !empty($scene_task_id)) {
  5815. continue;
  5816. }
  5817. $url_inherited = false;
  5818. // 尝试从全局数据中继承
  5819. foreach ($global_scenes as $global_scene) {
  5820. $global_scene_name = getProp($global_scene, 'scene');
  5821. $global_scene_description = getProp($global_scene, 'description');
  5822. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5823. $global_scene_url = getProp($global_scene, 'url');
  5824. $global_scene_task_id = getProp($global_scene, 'task_id');
  5825. $global_scene_task_status = getProp($global_scene, 'task_status');
  5826. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5827. if ($scene_name === $global_scene_name
  5828. && $scene_description === $global_scene_description
  5829. && $scene_pic_prompt === $global_scene_pic_prompt
  5830. && !empty($global_scene_url)) {
  5831. // 继承 task_id、task_status 和 url
  5832. $scene['task_id'] = $global_scene_task_id;
  5833. $scene['task_status'] = $global_scene_task_status;
  5834. $scene['url'] = $global_scene_url;
  5835. $scenes_updated = true;
  5836. $url_inherited = true;
  5837. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5838. break;
  5839. }
  5840. }
  5841. // 如果无法继承且没有任务ID,创建新任务
  5842. if (!$url_inherited && empty($scene_task_id)) {
  5843. try {
  5844. $art_style = getProp($episode, 'art_style');
  5845. // 优先使用 pic_prompt,如果没有则使用 description
  5846. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5847. // if ($art_style) {
  5848. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5849. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5850. // }
  5851. $description = buildStylePromptPrefix($scene_prefix) . "场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5852. $params = [
  5853. 'prompt' => $description,
  5854. 'ref_img_urls' => [],
  5855. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  5856. 'anime_id' => $anime_id,
  5857. 'episode_id' => $episode_id,
  5858. 'episode_number' => getProp($episode, 'episode_number'),
  5859. ];
  5860. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5861. $task_id = $task->id;
  5862. if ($task_id) {
  5863. $scene['task_id'] = $task_id;
  5864. $scene['task_status'] = 'processing';
  5865. $scenes_updated = true;
  5866. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5867. }
  5868. } catch (\Exception $e) {
  5869. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5870. }
  5871. }
  5872. }
  5873. // 如果有更新,保存到数据库
  5874. if ($roles_updated || $scenes_updated) {
  5875. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5876. if ($roles_updated) {
  5877. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5878. }
  5879. if ($scenes_updated) {
  5880. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5881. }
  5882. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5883. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5884. }
  5885. }
  5886. /**
  5887. * 根据图片URL使用AI反推图片提示词
  5888. *
  5889. * @param string $img_url 图片URL
  5890. * @return string 反推的提示词
  5891. */
  5892. private function generateImagePromptFromUrl($img_url) {
  5893. try {
  5894. // 获取默认模型
  5895. $model = 'doubao-seed-2-0-mini-260215';
  5896. // 构建messages参数
  5897. $messages = [
  5898. [
  5899. 'role' => 'user',
  5900. 'content' => [
  5901. [
  5902. 'type' => 'text',
  5903. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5904. ],
  5905. [
  5906. 'type' => 'image_url',
  5907. 'image_url' => [
  5908. 'url' => $img_url
  5909. ]
  5910. ]
  5911. ]
  5912. ]
  5913. ];
  5914. // 构建请求参数
  5915. $params = [
  5916. 'model' => $model,
  5917. 'messages' => $messages,
  5918. 'stream' => false,
  5919. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5920. ];
  5921. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5922. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5923. // 仅记录 token 使用明细(不扣积分)
  5924. $uid = 0;
  5925. try {
  5926. $uid = (int)Site::getUid();
  5927. } catch (\Throwable $e) {
  5928. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5929. }
  5930. $this->pointsService->recordTokenOnlyDetail(
  5931. $uid,
  5932. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5933. [
  5934. 'model' => $model,
  5935. 'img_url' => $img_url,
  5936. 'source' => 'generateImagePromptFromUrl',
  5937. ],
  5938. 'chat',
  5939. $model,
  5940. ''
  5941. );
  5942. // 返回生成的内容
  5943. return getProp($result, 'fullContent', '图片描述生成失败');
  5944. } catch (\Exception $e) {
  5945. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5946. 'img_url' => $img_url
  5947. ]);
  5948. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5949. 'error' => $e->getMessage(),
  5950. 'img_url' => $img_url
  5951. ]);
  5952. return '图片描述生成失败: ' . $e->getMessage();
  5953. }
  5954. }
  5955. /**
  5956. * 音频试听接口
  5957. * 创建音频任务并轮询获取结果
  5958. *
  5959. * @param array $data 参数数组
  5960. * @return array 返回音频URL或错误信息
  5961. */
  5962. public function previewAudio($data) {
  5963. $dialogue = getProp($data, 'dialogue');
  5964. // 必填参数验证
  5965. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5966. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5967. $voice_type = getProp($data, 'voice_type');
  5968. $voice_name = getProp($data, 'voice_name');
  5969. $voice_actor = getProp($data, 'voice_actor');
  5970. $emotion_type = getProp($data, 'emotion_type');
  5971. $gender = getProp($data, 'gender', 0);
  5972. $emotion = getProp($data, 'emotion');
  5973. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5974. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5975. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5976. $pitch = getProp($data, 'pitch', 0);
  5977. try {
  5978. $now = date('Y-m-d H:i:s');
  5979. // 构建生成参数
  5980. $generate_json = json_encode([
  5981. 'text' => $dialogue,
  5982. 'role' => $voice_actor,
  5983. 'voice_type' => $voice_type,
  5984. 'voice_name' => $voice_name,
  5985. 'emotion' => $emotion,
  5986. 'emotion_type' => $emotion_type,
  5987. 'gender' => $gender,
  5988. 'speed_ratio' => $speed_ratio,
  5989. 'loudness_ratio' => $loudness_ratio,
  5990. 'emotion_scale' => $emotion_scale,
  5991. 'pitch' => $pitch,
  5992. ], 256);
  5993. // 请求远程服务器执行生成
  5994. $client = new Client(['timeout' => 600, 'verify' => false]);
  5995. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5996. $response = $result->getBody()->getContents();
  5997. $response_arr = json_decode($response, true);
  5998. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5999. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  6000. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  6001. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  6002. }
  6003. $arr = $response_arr['data'];
  6004. $subtitle_info = $arr['subtitle_info'];
  6005. $audio_duration = json_decode($subtitle_info, true)['duration'];
  6006. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  6007. return [
  6008. 'audio_url' => $arr['url'],
  6009. 'subtitle_info' => $subtitle_info,
  6010. 'audio_duration' => round($audio_duration, 2)
  6011. ];
  6012. } catch (\Exception $e) {
  6013. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  6014. Utils::throwError('20003:' . $e->getMessage());
  6015. }
  6016. }
  6017. /**
  6018. * 获取角色库列表(支持文件夹递归查询)
  6019. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  6020. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  6021. */
  6022. public function globalProducts($data) {
  6023. $uid = Site::getUid();
  6024. $cpid = Site::getCpid();
  6025. $role = Site::getRole();
  6026. $id = getProp($data, 'id', 0);
  6027. $parent_id = getProp($data, 'parent_id', 0);
  6028. $product_name = getProp($data, 'product_name');
  6029. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  6030. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  6031. if (!$product) {
  6032. Utils::throwError('20003:请选择产品类型');
  6033. }
  6034. // 根据角色和is_public参数确定查询范围
  6035. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  6036. // user角色:根据is_public参数筛选
  6037. $query_user_ids = [];
  6038. if ($role === 'admin') {
  6039. // admin获取所有个人库和公共库
  6040. $query_user_ids = [$uid, 0];
  6041. } else {
  6042. // user角色根据is_public参数筛选
  6043. if ($is_public == 2) {
  6044. // 个人库+公共库
  6045. $query_user_ids = [$uid, 0];
  6046. } elseif ($is_public == 0) {
  6047. // 仅个人库
  6048. $query_user_ids = [$uid];
  6049. } elseif ($is_public == 1) {
  6050. // 仅公共库
  6051. $query_user_ids = [0];
  6052. }
  6053. }
  6054. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  6055. if ($id || $product_name) {
  6056. $query = DB::table('mp_products')
  6057. ->where('cpid', $cpid)
  6058. ->whereIn('user_id', $query_user_ids)
  6059. ->where('is_deleted', 0);
  6060. // 如果指定了 id,按 id 精确查询
  6061. if ($id) {
  6062. $query->where('id', $id);
  6063. }
  6064. // 如果指定了 product_name,按名称模糊查询
  6065. if ($product_name) {
  6066. $query->where('product_name', 'like', "%{$product_name}%");
  6067. }
  6068. // 如果指定了 product,添加筛选条件
  6069. if ($product) {
  6070. $query->where('product', $product);
  6071. }
  6072. $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')
  6073. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  6074. ->get()
  6075. ->map(function($value) {
  6076. $value = (array)$value;
  6077. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  6078. $value['type'] = (int)$value['type'];
  6079. $value['parent_id'] = (int)$value['parent_id'];
  6080. $value['level'] = (int)$value['level'];
  6081. $value['product'] = (int)($value['product'] ?? 1);
  6082. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  6083. $value['timbre_url'] = $value['timbre_url'] ?? '';
  6084. $value['versions'] = json_decode($value['versions'], true) ?: [];
  6085. unset($value['user_id']);
  6086. return $value;
  6087. })
  6088. ->toArray();
  6089. return $result;
  6090. }
  6091. // 递归获取所有子目录和角色
  6092. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  6093. }
  6094. /**
  6095. * 递归获取指定目录下的所有子目录和角色
  6096. * @param int $cpid 公司ID
  6097. * @param int $parent_id 父目录ID
  6098. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  6099. * @param array $query_user_ids 用户ID数组(支持多个)
  6100. * @param int $current_uid 当前用户ID(用于排序)
  6101. * @return array
  6102. */
  6103. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  6104. // 查询当前层级的所有项(文件夹和角色)
  6105. $query = DB::table('mp_products')
  6106. ->where('cpid', $cpid)
  6107. ->where('is_deleted', 0)
  6108. ->where('parent_id', $parent_id);
  6109. // 添加用户ID验证(支持多个user_id)
  6110. if (!empty($query_user_ids)) {
  6111. $query->whereIn('user_id', $query_user_ids);
  6112. }
  6113. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  6114. if ($product) {
  6115. $query->where('product', $product);
  6116. }
  6117. // 排序规则:
  6118. // 1. 文件夹在前(type DESC)
  6119. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  6120. // 3. 其他排序规则
  6121. $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')
  6122. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  6123. ->get();
  6124. $result = [];
  6125. foreach ($items as $item) {
  6126. $itemArray = [
  6127. 'id' => $item->id,
  6128. 'type' => (int)$item->type,
  6129. 'parent_id' => (int)$item->parent_id,
  6130. 'level' => (int)$item->level,
  6131. 'product_name' => $item->product_name,
  6132. 'url' => $item->url,
  6133. 'pic_prompt' => $item->pic_prompt ?? '',
  6134. 'three_view_image_url' => $item->three_view_image_url,
  6135. 'timbre_url' => $item->timbre_url ?? '',
  6136. 'product' => (int)($item->product ?? 1),
  6137. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  6138. 'created_at' => transDate($item->created_at, 'Y-m-d')
  6139. ];
  6140. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  6141. // 如果是文件夹,递归获取其子项
  6142. if ($item->type == 2) {
  6143. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  6144. if (!empty($children)) {
  6145. $itemArray['children'] = $children;
  6146. }
  6147. }
  6148. $result[] = $itemArray;
  6149. }
  6150. return $result;
  6151. }
  6152. /**
  6153. * 创建文件夹
  6154. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  6155. * @return int 返回新建文件夹ID
  6156. */
  6157. public function createFolder($data) {
  6158. $uid = Site::getUid();
  6159. $cpid = Site::getCpid();
  6160. $role = Site::getRole();
  6161. $parent_id = getProp($data, 'parent_id', 0);
  6162. $folder_name = getProp($data, 'product_name', '新建文件夹');
  6163. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6164. // 如果是公共库操作,需要admin权限
  6165. if ($is_public && $role !== 'admin') {
  6166. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6167. }
  6168. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6169. $store_uid = $is_public ? 0 : $uid;
  6170. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6171. $product = getProp($data, 'product');
  6172. if (!in_array($product, [1, 2, 3])) {
  6173. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  6174. }
  6175. // 验证父文件夹
  6176. $parent_level = 0;
  6177. if ($parent_id > 0) {
  6178. $parent = DB::table('mp_products')
  6179. ->where('id', $parent_id)
  6180. ->where('cpid', $cpid)
  6181. ->where('user_id', $store_uid)
  6182. ->where('type', 2)
  6183. ->where('is_deleted', 0)
  6184. ->first();
  6185. if (!$parent) {
  6186. Utils::throwError('20003:父文件夹不存在');
  6187. }
  6188. // 检查父文件夹的 product 类型是否一致
  6189. if ($parent->product != $product) {
  6190. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  6191. }
  6192. $parent_level = $parent->level;
  6193. // 检查层级限制(最多3层)
  6194. if ($parent_level >= 3) {
  6195. Utils::throwError('20003:文件夹层级不能超过3层');
  6196. }
  6197. }
  6198. // 检查当前目录下是否已存在空白文件夹
  6199. $empty_folder_exists = DB::table('mp_products')
  6200. ->where('parent_id', $parent_id)
  6201. ->where('cpid', $cpid)
  6202. ->where('user_id', $store_uid)
  6203. ->where('type', 2)
  6204. ->where('product', $product)
  6205. ->where('product_name', '新建文件夹')
  6206. ->where('is_deleted', 0)
  6207. ->exists();
  6208. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  6209. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  6210. }
  6211. // 创建文件夹
  6212. $folder_id = DB::table('mp_products')->insertGetId([
  6213. 'user_id' => $store_uid,
  6214. 'cpid' => $cpid,
  6215. 'type' => 2,
  6216. 'parent_id' => $parent_id,
  6217. 'level' => $parent_level + 1,
  6218. 'product_name' => $folder_name,
  6219. 'product' => $product,
  6220. 'sort_order' => time(), // 使用时间戳作为排序权重
  6221. 'is_deleted' => 0,
  6222. 'created_at' => date('Y-m-d H:i:s'),
  6223. 'updated_at' => date('Y-m-d H:i:s')
  6224. ]);
  6225. return [
  6226. 'id' => $folder_id,
  6227. 'type' => 2,
  6228. 'parent_id' => $parent_id,
  6229. 'level' => $parent_level + 1,
  6230. 'product_name' => $folder_name,
  6231. 'product' => $product,
  6232. ];
  6233. }
  6234. /**
  6235. * 重命名文件夹或角色
  6236. * @param array $data 包含 id、product_name(新名称)
  6237. * @return bool
  6238. */
  6239. public function renameFolder($data) {
  6240. $uid = Site::getUid();
  6241. $cpid = Site::getCpid();
  6242. $role = Site::getRole();
  6243. $id = getProp($data, 'id');
  6244. $new_name = getProp($data, 'product_name');
  6245. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6246. if (!$id || !$new_name) {
  6247. Utils::throwError('20003:参数不完整');
  6248. }
  6249. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6250. $query_uid = $is_public ? 0 : $uid;
  6251. // 如果是公共库操作,需要admin权限
  6252. if ($is_public && $role !== 'admin') {
  6253. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6254. }
  6255. // 检查是否存在
  6256. $item = DB::table('mp_products')
  6257. ->where('id', $id)
  6258. ->where('cpid', $cpid)
  6259. ->where('user_id', $query_uid)
  6260. ->where('is_deleted', 0)
  6261. ->first();
  6262. if (!$item) {
  6263. Utils::throwError('20003:项目不存在');
  6264. }
  6265. return DB::table('mp_products')
  6266. ->where('id', $id)
  6267. ->where('cpid', $cpid)
  6268. ->where('user_id', $query_uid)
  6269. ->update([
  6270. 'product_name' => $new_name,
  6271. 'updated_at' => date('Y-m-d H:i:s')
  6272. ]);
  6273. }
  6274. /**
  6275. * 移动角色或文件夹到指定文件夹
  6276. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6277. * @return bool
  6278. */
  6279. public function moveProductOrFolder($data) {
  6280. $uid = Site::getUid();
  6281. $cpid = Site::getCpid();
  6282. $role = Site::getRole();
  6283. $id = getProp($data, 'id');
  6284. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6285. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6286. if (!$id) {
  6287. Utils::throwError('20003:请选择要移动的项目');
  6288. }
  6289. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6290. $query_uid = $is_public ? 0 : $uid;
  6291. // 如果是公共库操作,需要admin权限
  6292. if ($is_public && $role !== 'admin') {
  6293. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6294. }
  6295. // 检查要移动的项目
  6296. $item = DB::table('mp_products')
  6297. ->where('id', $id)
  6298. ->where('cpid', $cpid)
  6299. ->where('user_id', $query_uid)
  6300. ->where('is_deleted', 0)
  6301. ->first();
  6302. if (!$item) {
  6303. Utils::throwError('20003:项目不存在');
  6304. }
  6305. // 验证目标文件夹
  6306. $target_level = 0;
  6307. $target_product = $item->product; // 默认使用当前项目的 product
  6308. if ($target_parent_id > 0) {
  6309. $target_parent = DB::table('mp_products')
  6310. ->where('id', $target_parent_id)
  6311. ->where('cpid', $cpid)
  6312. ->where('user_id', $query_uid)
  6313. ->where('type', 2)
  6314. ->where('is_deleted', 0)
  6315. ->first();
  6316. if (!$target_parent) {
  6317. Utils::throwError('20003:目标文件夹不存在');
  6318. }
  6319. // 检查 product 类型是否一致
  6320. if ($target_parent->product != $item->product) {
  6321. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6322. }
  6323. $target_level = $target_parent->level;
  6324. $target_product = $target_parent->product;
  6325. // 如果移动的是文件夹,需要检查层级
  6326. if ($item->type == 2) {
  6327. // 计算移动后的最大层级
  6328. $max_child_level = $this->getMaxChildLevel($id);
  6329. $depth = $max_child_level - $item->level;
  6330. if ($target_level + 1 + $depth > 3) {
  6331. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6332. }
  6333. // 不能移动到自己或自己的子文件夹下
  6334. if ($this->isDescendant($target_parent_id, $id)) {
  6335. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6336. }
  6337. }
  6338. }
  6339. // 更新父文件夹和层级
  6340. $new_level = $target_level + 1;
  6341. DB::table('mp_products')
  6342. ->where('id', $id)
  6343. ->update([
  6344. 'parent_id' => $target_parent_id,
  6345. 'level' => $new_level,
  6346. 'updated_at' => date('Y-m-d H:i:s')
  6347. ]);
  6348. // 如果是文件夹,需要递归更新所有子项的层级
  6349. if ($item->type == 2) {
  6350. $this->updateChildrenLevel($id, $new_level);
  6351. }
  6352. return true;
  6353. }
  6354. /**
  6355. * 获取文件夹下最大子层级
  6356. * @param int $folder_id
  6357. * @return int
  6358. */
  6359. private function getMaxChildLevel($folder_id) {
  6360. $max_level = DB::table('mp_products')
  6361. ->where('parent_id', $folder_id)
  6362. ->where('is_deleted', 0)
  6363. ->max('level');
  6364. if (!$max_level) {
  6365. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6366. }
  6367. // 递归查找子文件夹
  6368. $children = DB::table('mp_products')
  6369. ->where('parent_id', $folder_id)
  6370. ->where('type', 2)
  6371. ->where('is_deleted', 0)
  6372. ->pluck('id');
  6373. foreach ($children as $child_id) {
  6374. $child_max = $this->getMaxChildLevel($child_id);
  6375. if ($child_max > $max_level) {
  6376. $max_level = $child_max;
  6377. }
  6378. }
  6379. return $max_level;
  6380. }
  6381. /**
  6382. * 检查 target_id 是否是 folder_id 的后代
  6383. * @param int $target_id
  6384. * @param int $folder_id
  6385. * @return bool
  6386. */
  6387. private function isDescendant($target_id, $folder_id) {
  6388. if ($target_id == $folder_id) {
  6389. return true;
  6390. }
  6391. $parent = DB::table('mp_products')
  6392. ->where('id', $target_id)
  6393. ->where('is_deleted', 0)
  6394. ->first();
  6395. if (!$parent || $parent->parent_id == 0) {
  6396. return false;
  6397. }
  6398. return $this->isDescendant($parent->parent_id, $folder_id);
  6399. }
  6400. /**
  6401. * 递归更新子项层级
  6402. * @param int $parent_id
  6403. * @param int $parent_level
  6404. */
  6405. private function updateChildrenLevel($parent_id, $parent_level) {
  6406. $children = DB::table('mp_products')
  6407. ->where('parent_id', $parent_id)
  6408. ->where('is_deleted', 0)
  6409. ->get();
  6410. foreach ($children as $child) {
  6411. $new_level = $parent_level + 1;
  6412. DB::table('mp_products')
  6413. ->where('id', $child->id)
  6414. ->update([
  6415. 'level' => $new_level,
  6416. 'updated_at' => date('Y-m-d H:i:s')
  6417. ]);
  6418. // 如果是文件夹,继续递归
  6419. if ($child->type == 2) {
  6420. $this->updateChildrenLevel($child->id, $new_level);
  6421. }
  6422. }
  6423. }
  6424. /**
  6425. * 获取文件夹路径(面包屑导航)
  6426. * @param array $data 包含 folder_id
  6427. * @return array 返回路径数组
  6428. */
  6429. public function getFolderPath($data) {
  6430. $uid = Site::getUid();
  6431. $cpid = Site::getCpid();
  6432. $folder_id = getProp($data, 'id', 0);
  6433. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6434. if ($folder_id == 0) {
  6435. return [
  6436. ['id' => 0, 'name' => '根目录']
  6437. ];
  6438. }
  6439. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6440. $query_uid = $is_public ? 0 : $uid;
  6441. $path = [];
  6442. $current_id = $folder_id;
  6443. while ($current_id > 0) {
  6444. $folder = DB::table('mp_products')
  6445. ->where('id', $current_id)
  6446. ->where('cpid', $cpid)
  6447. ->where('user_id', $query_uid)
  6448. ->where('type', 2)
  6449. ->where('is_deleted', 0)
  6450. ->first();
  6451. if (!$folder) {
  6452. break;
  6453. }
  6454. array_unshift($path, [
  6455. 'id' => $folder->id,
  6456. 'name' => $folder->product_name
  6457. ]);
  6458. $current_id = $folder->parent_id;
  6459. }
  6460. // 添加根目录
  6461. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6462. return $path;
  6463. }
  6464. public function createProduct($data) {
  6465. $uid = Site::getUid();
  6466. $cpid = Site::getCpid();
  6467. $role = Site::getRole();
  6468. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6469. // 如果是公共库操作,需要admin权限
  6470. if ($is_public && $role !== 'admin') {
  6471. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6472. }
  6473. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6474. $store_uid = $is_public ? 0 : $uid;
  6475. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6476. $script_id = (int)getProp($data, 'script_id', 0);
  6477. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6478. if ($script_id && empty($episode_numbers)) {
  6479. Utils::throwError('20003:剧集序号不能为空');
  6480. }
  6481. if (!$script_id && !empty($episode_numbers)) {
  6482. Utils::throwError('20003:请提供剧本ID');
  6483. }
  6484. $product_name = trim(getProp($data, 'product_name'));
  6485. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6486. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6487. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6488. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6489. $url = trim(getProp($data, 'url'));
  6490. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6491. $versions = getProp($data, 'versions');
  6492. // 检查是否是正确的图片格式
  6493. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6494. $urlPath = parse_url($url, PHP_URL_PATH);
  6495. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6496. if (!in_array($extension, $allowedExtensions)) {
  6497. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6498. }
  6499. // 选填三视图图片地址,格式校验与 url 一致
  6500. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6501. if ($three_view_image_url) {
  6502. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6503. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6504. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6505. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6506. }
  6507. }
  6508. // 选填音色音频地址(兼容 timbre_url/audio_url/timbre 传参)
  6509. $timbre_url = $this->getProductTimbreUrl($data);
  6510. if ($timbre_url) {
  6511. $this->validateProductAudioUrl($timbre_url);
  6512. }
  6513. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6514. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6515. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6516. $product = getProp($data, 'product');
  6517. if (!in_array($product, [1, 2, 3])) {
  6518. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6519. }
  6520. // 获取父文件夹ID和层级
  6521. $parent_id = getProp($data, 'parent_id', 0);
  6522. $parent_level = 0;
  6523. if ($parent_id > 0) {
  6524. $parent = DB::table('mp_products')
  6525. ->where('id', $parent_id)
  6526. ->where('cpid', $cpid)
  6527. ->where('user_id', $store_uid)
  6528. ->where('type', 2)
  6529. ->where('is_deleted', 0)
  6530. ->first();
  6531. if (!$parent) {
  6532. Utils::throwError('20003:父文件夹不存在');
  6533. }
  6534. $parent_level = $parent->level;
  6535. }
  6536. // 创建资产并保存剧本资产关联关系(同一事务)
  6537. DB::beginTransaction();
  6538. try {
  6539. $id = DB::table('mp_products')->insertGetId([
  6540. 'user_id' => $store_uid,
  6541. 'cpid' => $cpid,
  6542. 'type' => 1, // 1=角色图片
  6543. 'parent_id' => $parent_id,
  6544. 'level' => $parent_level + 1,
  6545. 'product_name' => $product_name,
  6546. 'url' => $url,
  6547. 'three_view_image_url' => $three_view_image_url,
  6548. 'timbre_url' => $timbre_url,
  6549. 'pic_prompt' => $pic_prompt,
  6550. 'product' => $product,
  6551. 'versions' => json_encode($versions, 256),
  6552. 'sort_order' => time(), // 使用时间戳作为排序权重
  6553. 'created_at' => date('Y-m-d H:i:s'),
  6554. 'updated_at' => date('Y-m-d H:i:s')
  6555. ]);
  6556. if (!$id) Utils::throwError('20003:创建失败');
  6557. // 保存剧本资产关联关系
  6558. if ($script_id) {
  6559. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6560. }
  6561. DB::commit();
  6562. } catch (\Exception $e) {
  6563. DB::rollback();
  6564. throw $e;
  6565. }
  6566. return [
  6567. 'id' => $id,
  6568. 'type' => 1,
  6569. 'parent_id' => $parent_id,
  6570. 'level' => $parent_level + 1,
  6571. 'product_name' => $product_name,
  6572. 'url' => $url,
  6573. 'three_view_image_url' => $three_view_image_url,
  6574. 'timbre_url' => $timbre_url,
  6575. 'pic_prompt' => $pic_prompt,
  6576. 'product' => $product,
  6577. 'versions' => $versions
  6578. ];
  6579. }
  6580. public function editProduct($data) {
  6581. $uid = Site::getUid();
  6582. $cpid = Site::getCpid();
  6583. $role = Site::getRole();
  6584. $id = getProp($data, 'id');
  6585. if (!$id) Utils::throwError('20003:ID不能为空');
  6586. $versions = getProp($data, 'versions');
  6587. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6588. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6589. $script_id = (int)getProp($data, 'script_id', 0);
  6590. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6591. if ($script_id && empty($episode_numbers)) {
  6592. Utils::throwError('20003:剧集序号不能为空');
  6593. }
  6594. if (!$script_id && !empty($episode_numbers)) {
  6595. Utils::throwError('20003:请提供剧本ID');
  6596. }
  6597. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6598. $query_uid = $is_public ? 0 : $uid;
  6599. // 如果是公共库操作,需要admin权限
  6600. if ($is_public && $role !== 'admin') {
  6601. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6602. }
  6603. // 检查是否存在且属于当前用户或公共库
  6604. $role = DB::table('mp_products')
  6605. ->where('id', $id)
  6606. ->where('cpid', $cpid)
  6607. ->where('user_id', $query_uid)
  6608. ->where('type', 1)->first();
  6609. if (!$role) Utils::throwError('20003:记录不存在');
  6610. $updateData = [];
  6611. // $needVersionRecord = false; // 是否需要记录版本
  6612. // 名称
  6613. $product_name = trim(getProp($data, 'product_name'));
  6614. if ($product_name) {
  6615. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6616. $updateData['product_name'] = $product_name;
  6617. }
  6618. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6619. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6620. // 图片地址
  6621. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6622. $url = trim(getProp($data, 'url'));
  6623. if ($url) {
  6624. // 检查是否是正确的图片格式
  6625. $urlPath = parse_url($url, PHP_URL_PATH);
  6626. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6627. if (!in_array($extension, $allowedExtensions)) {
  6628. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6629. }
  6630. // // 如果 url 有变更,记录版本
  6631. // if ($url !== $role->url) {
  6632. // $needVersionRecord = true;
  6633. // }
  6634. $updateData['url'] = $url;
  6635. }
  6636. // 三视图图片地址(选填),格式校验与 url 一致;显式传空表示当前版本没有三视图
  6637. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6638. if ($three_view_image_url) {
  6639. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6640. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6641. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6642. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6643. }
  6644. }
  6645. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  6646. if (array_key_exists('three_view_image_url', $data)) {
  6647. $updateData['three_view_image_url'] = $three_view_image_url;
  6648. }
  6649. // 音色音频地址(选填,显式传空字符串可清除已有音色)
  6650. if (array_key_exists('timbre_url', $data) || array_key_exists('audio_url', $data) || array_key_exists('timbre', $data)) {
  6651. $timbre_url = $this->getProductTimbreUrl($data);
  6652. if ($timbre_url) {
  6653. $this->validateProductAudioUrl($timbre_url);
  6654. }
  6655. $updateData['timbre_url'] = $timbre_url;
  6656. }
  6657. // 提示词
  6658. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6659. if ($pic_prompt) {
  6660. // // 如果 pic_prompt 有变更,记录版本
  6661. // if ($pic_prompt !== $role->pic_prompt) {
  6662. // $needVersionRecord = true;
  6663. // }
  6664. $updateData['pic_prompt'] = $pic_prompt;
  6665. }else {
  6666. Utils::throwError('20003:请输入提示词');
  6667. }
  6668. if (empty($updateData) && !$script_id) {
  6669. Utils::throwError('20003:没有需要更新的数据');
  6670. }
  6671. // // 如果需要记录版本,将数据添加到 versions 数组
  6672. // if ($needVersionRecord) {
  6673. // // 获取现有的 versions 数据
  6674. // $versions = json_decode($role->versions, true) ?: [];
  6675. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6676. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6677. // if ($isFirstVersion) {
  6678. // $oldVersion = [
  6679. // 'url' => $role->url,
  6680. // 'description' => $role->pic_prompt,
  6681. // ];
  6682. // // 旧版本添加到数组末尾
  6683. // $versions[] = $oldVersion;
  6684. // }
  6685. // // 构建新版本(变更后)
  6686. // $newVersion = [
  6687. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6688. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6689. // ];
  6690. // // 检查新版本是否已存在于历史版本中
  6691. // $existingIndex = -1;
  6692. // foreach ($versions as $index => $version) {
  6693. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6694. // $existingIndex = $index;
  6695. // break;
  6696. // }
  6697. // }
  6698. // if ($existingIndex !== -1) {
  6699. // // 如果已存在,移除旧的位置
  6700. // array_splice($versions, $existingIndex, 1);
  6701. // }
  6702. // // 新版本添加到数组开头(最新的在前)
  6703. // array_unshift($versions, $newVersion);
  6704. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6705. // // if (count($versions) > 10) {
  6706. // // $versions = array_slice($versions, 0, 10);
  6707. // // }
  6708. // $updateData['versions'] = json_encode($versions, 256);
  6709. // }
  6710. if ($versions) {
  6711. $updateData['versions'] = json_encode($versions, 256);
  6712. }
  6713. if (!empty($updateData)) {
  6714. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6715. }
  6716. // 更新资产并保存剧本资产关联关系(同一事务)
  6717. DB::beginTransaction();
  6718. try {
  6719. $updated = true;
  6720. if (!empty($updateData)) {
  6721. $updated = DB::table('mp_products')
  6722. ->where('cpid', $cpid)
  6723. ->where('id', $id)
  6724. ->update($updateData);
  6725. }
  6726. // 保存剧本资产关联关系
  6727. if ($script_id) {
  6728. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6729. }
  6730. DB::commit();
  6731. } catch (\Exception $e) {
  6732. DB::rollback();
  6733. throw $e;
  6734. }
  6735. return $updated;
  6736. }
  6737. /**
  6738. * 获取资产音色音频地址
  6739. * 兼容 timbre_url/audio_url/timbre 三种传参,timbre 支持字符串或 {"url":"..."} 结构
  6740. *
  6741. * @param array $data
  6742. * @return string
  6743. */
  6744. private function getProductTimbreUrl($data) {
  6745. foreach (['timbre_url', 'audio_url', 'timbre'] as $key) {
  6746. if (!array_key_exists($key, $data)) {
  6747. continue;
  6748. }
  6749. $value = $data[$key];
  6750. if (is_array($value)) {
  6751. $value = getProp($value, 'url', $value[0] ?? '');
  6752. }
  6753. if (!is_string($value)) {
  6754. continue;
  6755. }
  6756. return trim($value);
  6757. }
  6758. return '';
  6759. }
  6760. /**
  6761. * 校验资产音色音频地址格式
  6762. *
  6763. * @param string $url 音频地址
  6764. * @return void
  6765. */
  6766. private function validateProductAudioUrl($url) {
  6767. $allowedExtensions = ['mp3', 'wav', 'm4a', 'aac', 'ogg', 'oga', 'flac', 'amr', 'wma', 'weba'];
  6768. $urlPath = parse_url($url, PHP_URL_PATH);
  6769. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6770. if (!in_array($extension, $allowedExtensions)) {
  6771. Utils::throwError('20003:音色音频格式不正确,仅支持 mp3、wav、m4a、aac、ogg、flac、amr、wma 格式');
  6772. }
  6773. }
  6774. /**
  6775. * 保存单一资产与剧本剧集的关联关系
  6776. *
  6777. * @param int $product_id 资产ID
  6778. * @param int $script_id 剧本ID
  6779. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6780. * @return int 新增关联数量
  6781. */
  6782. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6783. $uid = Site::getUid();
  6784. // 验证剧本是否存在
  6785. $script = DB::table('mp_scripts')
  6786. ->where('id', $script_id)
  6787. ->where('is_deleted', 0)
  6788. ->first();
  6789. if (!$script) {
  6790. Utils::throwError('20003:剧本不存在');
  6791. }
  6792. // 验证剧本归属:只能关联自己的剧本
  6793. if ((int)$script->user_id !== (int)$uid) {
  6794. Utils::throwError('20003:只能添加到自己的剧本');
  6795. }
  6796. // 使用 splitContent 拆分剧本内容获取总集数
  6797. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6798. // 解析剧集序号(数组)
  6799. $episodes = [];
  6800. foreach ($episode_numbers as $item) {
  6801. if (is_array($item)) {
  6802. continue;
  6803. }
  6804. $item = trim((string)$item);
  6805. if ($item === '' || !is_numeric($item)) {
  6806. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6807. }
  6808. $episodes[] = (int)$item;
  6809. }
  6810. // 去重并校验序号范围(序号从1开始)
  6811. $episodes = array_values(array_unique($episodes));
  6812. if (empty($episodes)) {
  6813. Utils::throwError('20003:剧集序号不能为空');
  6814. }
  6815. foreach ($episodes as $episode) {
  6816. if ($episode < 1 || $episode > $totalEpisodes) {
  6817. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6818. }
  6819. }
  6820. $now = now();
  6821. // 过滤已存在的关联,避免重复
  6822. $existingEpisodes = DB::table('mp_script_product_mappings')
  6823. ->where('script_id', $script_id)
  6824. ->where('product_id', $product_id)
  6825. ->whereIn('episode_number', $episodes)
  6826. ->pluck('episode_number')
  6827. ->all();
  6828. $mappingRecords = [];
  6829. foreach ($episodes as $episode) {
  6830. if (in_array($episode, $existingEpisodes)) {
  6831. continue;
  6832. }
  6833. $mappingRecords[] = [
  6834. 'script_id' => $script_id,
  6835. 'product_id' => $product_id,
  6836. 'episode_number' => $episode,
  6837. 'created_at' => $now,
  6838. 'updated_at' => $now,
  6839. ];
  6840. }
  6841. $insertedCount = 0;
  6842. if (!empty($mappingRecords)) {
  6843. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6844. }
  6845. return $insertedCount;
  6846. }
  6847. /**
  6848. * 规范化剧集序号参数,统一为数组
  6849. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6850. *
  6851. * @param mixed $episode_number 剧集序号参数
  6852. * @return array
  6853. */
  6854. private function normalizeEpisodeNumbers($episode_number) {
  6855. if (!is_array($episode_number)) {
  6856. $episode_number = explode(',', (string)$episode_number);
  6857. }
  6858. $items = [];
  6859. foreach ($episode_number as $item) {
  6860. if (is_array($item)) {
  6861. continue;
  6862. }
  6863. foreach (explode(',', (string)$item) as $part) {
  6864. $part = trim($part);
  6865. if ($part !== '') {
  6866. $items[] = $part;
  6867. }
  6868. }
  6869. }
  6870. return $items;
  6871. }
  6872. /**
  6873. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6874. *
  6875. * @param object $script 剧本记录
  6876. * @return int 总集数
  6877. */
  6878. private function getScriptTotalEpisodeCount($script) {
  6879. if (empty($script->content)) {
  6880. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6881. }
  6882. $totalEpisodes = count(splitContent($script->content));
  6883. if ($totalEpisodes < 1) {
  6884. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6885. }
  6886. return $totalEpisodes;
  6887. }
  6888. /**
  6889. * 获取剧本总集数
  6890. *
  6891. * @param array $data 包含 script_id(剧本ID)
  6892. * @return array
  6893. */
  6894. public function getScriptTotalEpisodes($data) {
  6895. $script_id = (int)getProp($data, 'script_id', 0);
  6896. if (!$script_id) {
  6897. Utils::throwError('20003:请提供剧本ID');
  6898. }
  6899. // 验证剧本是否存在
  6900. $script = DB::table('mp_scripts')
  6901. ->where('id', $script_id)
  6902. ->where('is_deleted', 0)
  6903. ->first();
  6904. if (!$script) {
  6905. Utils::throwError('20003:剧本不存在');
  6906. }
  6907. return [
  6908. 'script_id' => $script_id,
  6909. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6910. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6911. ];
  6912. }
  6913. /**
  6914. * 获取角色版本历史
  6915. * @param array $data 包含 id(角色ID)
  6916. * @return array 返回版本历史列表
  6917. */
  6918. public function getProductVersions($data) {
  6919. $cpid = Site::getCpid();
  6920. $id = getProp($data, 'id');
  6921. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6922. $role = DB::table('mp_products')
  6923. ->where('id', $id)
  6924. ->where('cpid', $cpid)
  6925. ->where('type', 1)
  6926. ->first();
  6927. if (!$role) Utils::throwError('20003:角色不存在');
  6928. // 获取版本历史
  6929. $versions = json_decode($role->versions, true) ?: [];
  6930. // 添加当前版本作为最新版本
  6931. $currentVersion = [
  6932. 'version' => 0, // 0 表示当前版本
  6933. 'url' => $role->url,
  6934. 'pic_prompt' => $role->pic_prompt,
  6935. 'updated_at' => $role->updated_at,
  6936. 'is_current' => true
  6937. ];
  6938. array_unshift($versions, $currentVersion);
  6939. return $versions;
  6940. }
  6941. /**
  6942. * 恢复到指定版本
  6943. * @param array $data 包含 id(角色ID)、version(版本号)
  6944. * @return bool
  6945. */
  6946. public function restoreProductVersion($data) {
  6947. $uid = Site::getUid();
  6948. $cpid = Site::getCpid();
  6949. $id = getProp($data, 'id');
  6950. $version = getProp($data, 'version');
  6951. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6952. if (!$version) Utils::throwError('20003:版本号不能为空');
  6953. $role = DB::table('mp_products')
  6954. ->where('id', $id)
  6955. ->where('cpid', $cpid)
  6956. ->where('type', 1)
  6957. ->first();
  6958. if (!$role) Utils::throwError('20003:角色不存在');
  6959. // 获取版本历史
  6960. $versions = json_decode($role->versions, true) ?: [];
  6961. // 查找指定版本
  6962. $targetVersion = null;
  6963. foreach ($versions as $v) {
  6964. if ($v['version'] == $version) {
  6965. $targetVersion = $v;
  6966. break;
  6967. }
  6968. }
  6969. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6970. // 先将当前版本保存到历史
  6971. $newVersion = [
  6972. 'version' => count($versions) + 1,
  6973. 'url' => $role->url,
  6974. 'pic_prompt' => $role->pic_prompt,
  6975. 'updated_at' => date('Y-m-d H:i:s'),
  6976. 'updated_by' => $uid
  6977. ];
  6978. array_unshift($versions, $newVersion);
  6979. // 限制版本数量
  6980. if (count($versions) > 10) {
  6981. $versions = array_slice($versions, 0, 10);
  6982. }
  6983. // 恢复到指定版本
  6984. return DB::table('mp_products')
  6985. ->where('id', $id)
  6986. ->where('cpid', $cpid)
  6987. ->update([
  6988. 'url' => $targetVersion['url'],
  6989. 'pic_prompt' => $targetVersion['pic_prompt'],
  6990. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6991. 'updated_at' => date('Y-m-d H:i:s')
  6992. ]);
  6993. }
  6994. public function deleteProduct($data) {
  6995. $uid = Site::getUid();
  6996. $cpid = Site::getCpid();
  6997. $role = Site::getRole();
  6998. $id = getProp($data, 'id');
  6999. if (!$id) Utils::throwError('20003:ID不能为空');
  7000. $ids = explode(',', $id);
  7001. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  7002. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  7003. $query_uid = $is_public ? 0 : $uid;
  7004. // 如果是公共库操作,需要admin权限
  7005. if ($is_public && $role !== 'admin') {
  7006. Utils::throwError('20003:只有管理员才能操作公共资产库');
  7007. }
  7008. // 检查是否存在且属于当前用户或公共库
  7009. $role = DB::table('mp_products')
  7010. ->whereIn('id', $ids)
  7011. ->where('cpid', $cpid)
  7012. ->where('user_id', $query_uid)
  7013. ->get();
  7014. if (!$role) Utils::throwError('20003:记录不存在');
  7015. return DB::table('mp_products')
  7016. ->where('cpid', $cpid)
  7017. ->where('user_id', $query_uid)
  7018. ->whereIn('id', $ids)
  7019. ->update([
  7020. 'is_deleted' => 1,
  7021. 'updated_at' => date('Y-m-d H:i:s')
  7022. ]);
  7023. }
  7024. public function generateThreeView($data) {
  7025. $uid = Site::getUid();
  7026. $cpid = Site::getCpid();
  7027. $role = Site::getRole();
  7028. $id = getProp($data, 'id');
  7029. if (!$id) Utils::throwError('20003:ID不能为空');
  7030. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  7031. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  7032. $query_uid = $is_public ? 0 : $uid;
  7033. // 如果是公共库操作,需要admin权限
  7034. if ($is_public && $role !== 'admin') {
  7035. Utils::throwError('20003:只有管理员才能操作公共资产库');
  7036. }
  7037. // 检查是否存在且属于当前用户或公共库
  7038. $product = DB::table('mp_products')
  7039. ->where('id', $id)
  7040. ->where('cpid', $cpid)
  7041. ->where('user_id', $query_uid)
  7042. ->where('type', 1)->first();
  7043. if (!$product) Utils::throwError('20003:资产不存在');
  7044. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。'));
  7045. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  7046. if (!$ref_img_url) {
  7047. // 如果没有传入参考图,使用角色表中的图片
  7048. $ref_img_url = $product->url ?? '';
  7049. if (!$ref_img_url) {
  7050. Utils::throwError('20003:参考图不能为空');
  7051. }
  7052. }
  7053. $pic_prompt = getProp($product, 'pic_prompt');
  7054. if ($pic_prompt) {
  7055. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  7056. }
  7057. // 检查参考图是否是正确的图片格式
  7058. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  7059. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  7060. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  7061. if (!in_array($extension, $allowedExtensions)) {
  7062. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  7063. }
  7064. // 处理图片模型
  7065. $model = getProp($data, 'model');
  7066. if (!$model) {
  7067. // 使用默认模型
  7068. $model = 'gpt-image-2';
  7069. }
  7070. // 验证模型是否在可用模型表中
  7071. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7072. Utils::throwError('20003:该模型已不可用,请更换!');
  7073. }
  7074. $ratio = getProp($data, 'ratio', '16:9');
  7075. $resolution = getProp($data, 'resolution', '2k');
  7076. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  7077. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7078. // 参数验证
  7079. $resolution = strtolower($resolution);
  7080. if (!isset($sizeMap[$resolution])) {
  7081. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7082. }
  7083. if (!isset($sizeMap[$resolution][$ratio])) {
  7084. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7085. }
  7086. // 根据 ratio 和 resolution 确定宽高
  7087. $width = $sizeMap[$resolution][$ratio]['width'];
  7088. $height = $sizeMap[$resolution][$ratio]['height'];
  7089. try {
  7090. // 创建图片生成任务
  7091. $params = [
  7092. 'prompt' => $prompt,
  7093. 'model' => $model,
  7094. 'ref_img_urls' => [$ref_img_url],
  7095. 'width' => $width,
  7096. 'height' => $height
  7097. ];
  7098. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7099. $task_id = $task->id;
  7100. if (!$task_id) {
  7101. Utils::throwError('20003:创建图片生成任务失败');
  7102. }
  7103. // 轮询获取结果
  7104. // 只查询数据库,不调用API,不更新任务表
  7105. $start_time = time();
  7106. $timeout = 1800;
  7107. $img_url = '';
  7108. while (time() - $start_time < $timeout) {
  7109. sleep(5);
  7110. // 只查询数据库中的任务状态,不调用API,不更新任务表
  7111. $task = DB::table('mp_generate_pic_tasks')
  7112. ->where('id', $task_id)
  7113. ->first();
  7114. if (!$task) {
  7115. Utils::throwError('20003:任务不存在');
  7116. }
  7117. if ($task->status === 'success' && $task->result_url) {
  7118. $result_urls = is_string($task->result_url)
  7119. ? json_decode($task->result_url, true)
  7120. : $task->result_url;
  7121. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7122. break;
  7123. } elseif ($task->status === 'failed') {
  7124. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  7125. }
  7126. // 其他状态继续轮询
  7127. }
  7128. if (empty($img_url)) {
  7129. Utils::throwError('20003:三视图生成超时,请稍后重试');
  7130. }
  7131. // 更新 mp_products 表(不是任务表)
  7132. DB::table('mp_products')
  7133. ->where('id', $id)
  7134. ->where('cpid', $cpid)
  7135. ->update([
  7136. 'three_view_image_url' => $img_url,
  7137. 'updated_at' => date('Y-m-d H:i:s')
  7138. ]);
  7139. return ['three_view_image_url' => $img_url];
  7140. } catch (\Exception $e) {
  7141. dLog('anime')->error('生成三视图失败', [
  7142. 'error' => $e->getMessage()
  7143. ]);
  7144. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  7145. Utils::throwError('20003:' . $e->getMessage());
  7146. }
  7147. }
  7148. /**
  7149. * 推送(复制)资产或文件夹到目标位置
  7150. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  7151. * @return array 返回推送结果
  7152. */
  7153. public function pushProductOrFolder($data) {
  7154. $uid = Site::getUid();
  7155. $cpid = Site::getCpid();
  7156. $role = Site::getRole();
  7157. $product_id = getProp($data, 'product_id');
  7158. $target_parent_id = getProp($data, 'target_parent_id', 0);
  7159. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  7160. if (!$product_id) {
  7161. Utils::throwError('20003:请选择要推送的项目');
  7162. }
  7163. // 查询源项目(只通过cpid查询,不限制user_id)
  7164. $sourceItem = DB::table('mp_products')
  7165. ->where('id', $product_id)
  7166. ->where('cpid', $cpid)
  7167. ->where('is_deleted', 0)
  7168. ->first();
  7169. if (!$sourceItem) {
  7170. Utils::throwError('20003:要推送的项目不存在');
  7171. }
  7172. // 通过user_id判断源是公共库还是个人库
  7173. $source_uid = $sourceItem->user_id;
  7174. $source_is_public = ($source_uid == 0) ? 1 : 0;
  7175. // 验证目标文件夹并确定目标是公共库还是个人库
  7176. $target_level = 0;
  7177. $target_uid = $uid; // 默认推送到个人库
  7178. $target_is_public = 0;
  7179. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  7180. if ($target_parent_id > 0) {
  7181. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  7182. $targetParent = DB::table('mp_products')
  7183. ->where('id', $target_parent_id)
  7184. ->where('cpid', $cpid)
  7185. ->where('type', 2)
  7186. ->where('is_deleted', 0)
  7187. ->first();
  7188. if (!$targetParent) {
  7189. Utils::throwError('20003:目标文件夹不存在');
  7190. }
  7191. // 通过user_id判断目标是公共库还是个人库
  7192. $target_level = $targetParent->level;
  7193. $target_uid = $targetParent->user_id;
  7194. $target_is_public = ($target_uid == 0) ? 1 : 0;
  7195. // 使用目标文件夹的 product 类型
  7196. $final_product_type = $targetParent->product;
  7197. }
  7198. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  7199. else {
  7200. $push_to_public = getProp($data, 'push_to_public');
  7201. if ($push_to_public === '') {
  7202. Utils::throwError('20003:请选择是否推送到公共库');
  7203. }
  7204. if ($push_to_public) {
  7205. $target_uid = 0;
  7206. $target_is_public = 1;
  7207. }
  7208. // 推送到根目录时,必须指定 product 类型
  7209. if ($target_product === null || $target_product === '') {
  7210. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  7211. }
  7212. $final_product_type = $target_product;
  7213. }
  7214. // 如果目标是公共库,需要admin权限
  7215. if ($target_is_public && $role !== 'admin') {
  7216. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  7217. }
  7218. // 权限验证:验证是否符合允许的推送规则
  7219. $this->validatePushPermission($source_uid, $target_uid, $uid);
  7220. try {
  7221. DB::beginTransaction();
  7222. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  7223. if ($sourceItem->type == 1) {
  7224. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  7225. DB::commit();
  7226. return [
  7227. 'product_id' => $newId,
  7228. ];
  7229. }
  7230. // 如果是文件夹,递归复制(支持跨类型推送)
  7231. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  7232. DB::commit();
  7233. return [
  7234. 'product_id' => $newFolderId,
  7235. ];
  7236. } catch (\Exception $e) {
  7237. DB::rollBack();
  7238. dLog('anime')->error('推送失败', [
  7239. 'error' => $e->getMessage(),
  7240. 'product_id' => $product_id
  7241. ]);
  7242. Utils::throwError('20003:' . $e->getMessage());
  7243. }
  7244. }
  7245. /**
  7246. * 验证推送权限
  7247. * 允许的推送规则:
  7248. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7249. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  7250. * 3. 公共库推送给公共库(公共库 → 公共库)
  7251. *
  7252. * @param int $source_uid 源的user_id
  7253. * @param int $target_uid 目标的user_id
  7254. * @param int $current_uid 当前用户ID
  7255. * @throws \Exception
  7256. */
  7257. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  7258. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7259. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  7260. return; // 允许
  7261. }
  7262. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  7263. if ($source_uid == 0 && $target_uid == $current_uid) {
  7264. return; // 允许
  7265. }
  7266. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7267. if ($source_uid == 0 && $target_uid == 0) {
  7268. return; // 允许
  7269. }
  7270. // 其他情况都不允许
  7271. if ($source_uid != 0 && $source_uid != $current_uid) {
  7272. // 源是别人的个人库
  7273. Utils::throwError('20003:无权限访问该资产');
  7274. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7275. // 个人库推送给公共库(不允许)
  7276. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7277. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7278. // 不同用户的个人库之间推送(不允许)
  7279. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7280. } else {
  7281. // 其他未知情况
  7282. Utils::throwError('20003:不允许的推送操作');
  7283. }
  7284. }
  7285. /**
  7286. * 复制单个资产
  7287. * @param object $sourceProduct 源资产对象
  7288. * @param int $targetParentId 目标父文件夹ID
  7289. * @param int $targetLevel 目标层级
  7290. * @param int $cpid 公司ID
  7291. * @param int $targetUid 目标用户ID
  7292. * @return int 返回新资产ID
  7293. */
  7294. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7295. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7296. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7297. $newProductData = [
  7298. 'user_id' => $targetUid,
  7299. 'cpid' => $cpid,
  7300. 'type' => 1,
  7301. 'parent_id' => $targetParentId,
  7302. 'level' => $targetLevel,
  7303. 'product_name' => $sourceProduct->product_name,
  7304. 'url' => $sourceProduct->url,
  7305. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7306. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7307. 'timbre_url' => $sourceProduct->timbre_url ?? '',
  7308. 'product' => $finalProductType,
  7309. 'versions' => $sourceProduct->versions ?? '',
  7310. 'sort_order' => time(),
  7311. 'is_deleted' => 0,
  7312. 'created_at' => date('Y-m-d H:i:s'),
  7313. 'updated_at' => date('Y-m-d H:i:s')
  7314. ];
  7315. return DB::table('mp_products')->insertGetId($newProductData);
  7316. }
  7317. /**
  7318. * 递归复制文件夹及其子项
  7319. * @param object $sourceFolder 源文件夹对象
  7320. * @param int $targetParentId 目标父文件夹ID
  7321. * @param int $targetLevel 目标层级
  7322. * @param int $cpid 公司ID
  7323. * @param int $targetUid 目标用户ID
  7324. * @param int $sourceUid 源用户ID
  7325. * @return int 返回新文件夹ID
  7326. */
  7327. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7328. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7329. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7330. // 创建新文件夹
  7331. $newFolderData = [
  7332. 'user_id' => $targetUid,
  7333. 'cpid' => $cpid,
  7334. 'type' => 2,
  7335. 'parent_id' => $targetParentId,
  7336. 'level' => $targetLevel,
  7337. 'product_name' => $sourceFolder->product_name,
  7338. 'product' => $finalProductType,
  7339. 'sort_order' => time(),
  7340. 'is_deleted' => 0,
  7341. 'created_at' => date('Y-m-d H:i:s'),
  7342. 'updated_at' => date('Y-m-d H:i:s')
  7343. ];
  7344. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7345. // 获取源文件夹下的所有子项
  7346. $children = DB::table('mp_products')
  7347. ->where('parent_id', $sourceFolder->id)
  7348. ->where('cpid', $cpid)
  7349. ->where('user_id', $sourceUid)
  7350. ->where('is_deleted', 0)
  7351. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7352. ->get();
  7353. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7354. foreach ($children as $child) {
  7355. if ($child->type == 1) {
  7356. // 资产
  7357. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7358. } else {
  7359. // 文件夹
  7360. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7361. }
  7362. }
  7363. return $newFolderId;
  7364. }
  7365. /**
  7366. * 转让剧本归属(剧本及其关联资产)
  7367. *
  7368. * 仅调整 mp_scripts.user_id 与 mp_products.user_id,其他表保持不变。
  7369. * 权限:仅 admin / superadmin 可操作;目标用户必须是同组(cpid 相同)且角色为 user(组员)的用户,禁止跨组转让。
  7370. * 多个剧本逐个独立事务处理,单个剧本失败不影响其他剧本;
  7371. * 单个剧本内的剧本记录与关联资产必须全部更新成功,否则整体回滚。
  7372. *
  7373. * @param array $data 请求参数:script_ids(数组或英文逗号分隔,兼容单个 script_id)、target_user_id
  7374. * @return array
  7375. */
  7376. public function transferScriptOwner($data) {
  7377. $operatorRole = Site::getRole();
  7378. $operatorCpid = Site::getCpid();
  7379. // 1.权限校验:仅管理员和超管可操作
  7380. if (!in_array($operatorRole, ['admin', 'superadmin'], true)) {
  7381. Utils::throwError(ErrorConst::NOT_ACCESS);
  7382. }
  7383. // 2.目标用户校验:必须存在且角色为 user(组员)
  7384. $targetUserId = (int)getProp($data, 'target_user_id', 0);
  7385. if ($targetUserId < 1) {
  7386. Utils::throwError('1002:请选择转让的目标用户');
  7387. }
  7388. $targetUser = DB::table('mp_manage_users')
  7389. ->where('id', $targetUserId)
  7390. ->where('is_deleted', 0)
  7391. ->first();
  7392. if (!$targetUser) {
  7393. Utils::throwError('20003:目标用户不存在');
  7394. }
  7395. if ((string)getProp($targetUser, 'role') !== 'user') {
  7396. Utils::throwError('20003:只能转让给角色为组员(user)的用户');
  7397. }
  7398. $targetCpid = (int)getProp($targetUser, 'cpid');
  7399. // 3.规范化剧本ID列表(兼容数组、逗号分隔字符串、script_id 单值)
  7400. $rawScriptIds = getProp($data, 'script_ids');
  7401. if (empty($rawScriptIds)) {
  7402. $rawScriptIds = getProp($data, 'script_id');
  7403. }
  7404. $scriptIds = $this->normalizeIdList($rawScriptIds);
  7405. if (empty($scriptIds)) {
  7406. Utils::throwError('20003:请提供剧本ID');
  7407. }
  7408. // 预取剧本名称,便于失败结果中回显
  7409. $scriptNameMap = DB::table('mp_scripts')
  7410. ->whereIn('id', $scriptIds)
  7411. ->pluck('script_name', 'id')
  7412. ->all();
  7413. $successList = [];
  7414. $failedList = [];
  7415. // 4.逐个剧本独立事务处理,单个失败不影响其他剧本
  7416. foreach ($scriptIds as $scriptId) {
  7417. DB::beginTransaction();
  7418. try {
  7419. $successList[] = $this->transferSingleScriptOwner(
  7420. $scriptId,
  7421. $targetUserId,
  7422. $targetCpid,
  7423. $operatorRole,
  7424. $operatorCpid,
  7425. Site::getUid()
  7426. );
  7427. DB::commit();
  7428. } catch (\Throwable $e) {
  7429. DB::rollBack();
  7430. $failedList[] = [
  7431. 'script_id' => (int)$scriptId,
  7432. 'script_name' => (string)($scriptNameMap[$scriptId] ?? ''),
  7433. 'reason' => $e->getMessage() !== '' ? $e->getMessage() : '转让失败',
  7434. ];
  7435. dLog('anime')->error('剧本归属转让失败', [
  7436. 'script_id' => $scriptId,
  7437. 'target_user_id' => $targetUserId,
  7438. 'operator_uid' => Site::getUid(),
  7439. 'error' => $e->getMessage(),
  7440. ]);
  7441. }
  7442. }
  7443. return [
  7444. 'target_user_id' => $targetUserId,
  7445. 'success_count' => count($successList),
  7446. 'failed_count' => count($failedList),
  7447. 'success_list' => $successList,
  7448. 'failed_list' => $failedList,
  7449. ];
  7450. }
  7451. /**
  7452. * 单个剧本的归属转让(需在事务中调用)
  7453. *
  7454. * @param int $scriptId 剧本ID
  7455. * @param int $targetUserId 目标用户ID
  7456. * @param int $targetCpid 目标用户所属公司ID
  7457. * @param string $operatorRole 操作人角色
  7458. * @param int $operatorCpid 操作人所属公司ID
  7459. * @param int $operatorUid 操作人用户ID
  7460. * @return array
  7461. */
  7462. private function transferSingleScriptOwner($scriptId, $targetUserId, $targetCpid, $operatorRole, $operatorCpid, $operatorUid) {
  7463. $script = DB::table('mp_scripts')
  7464. ->where('id', $scriptId)
  7465. ->where('is_deleted', 0)
  7466. ->first();
  7467. if (!$script) {
  7468. Utils::throwError('20003:剧本不存在');
  7469. }
  7470. $scriptCpid = (int)getProp($script, 'cpid');
  7471. $fromUserId = (int)getProp($script, 'user_id');
  7472. // 管理员仅可操作本组剧本
  7473. if ($operatorRole !== 'superadmin' && $scriptCpid !== $operatorCpid) {
  7474. Utils::throwError(ErrorConst::NOT_ACCESS);
  7475. }
  7476. // 管理员仅可转让自己创建的剧本(超管不做此验证)
  7477. if ($operatorRole !== 'superadmin' && $fromUserId !== (int)$operatorUid) {
  7478. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7479. }
  7480. // 禁止跨组转让:目标用户必须与剧本同组
  7481. if ($targetCpid !== $scriptCpid) {
  7482. Utils::throwError('20003:不能跨组转让,目标用户与剧本不在同一组');
  7483. }
  7484. // 关联资产ID(同一资产可能关联多个剧集序号,需去重)
  7485. $productIds = $this->normalizeIdList(
  7486. DB::table('mp_script_product_mappings')
  7487. ->where('script_id', $scriptId)
  7488. ->pluck('product_id')
  7489. ->all()
  7490. );
  7491. $folderIds = [];
  7492. if (!empty($productIds)) {
  7493. $products = DB::table('mp_products')
  7494. ->whereIn('id', $productIds)
  7495. ->select('id', 'cpid', 'parent_id', 'user_id')
  7496. ->get();
  7497. // 关联资产必须全部存在,否则视为数据异常,不提交
  7498. if ($products->count() !== count($productIds)) {
  7499. Utils::throwError('20003:剧本存在已丢失的关联资产,无法完成转让');
  7500. }
  7501. foreach ($products as $product) {
  7502. // 关联资产必须与剧本同组,避免误转让跨组资产
  7503. if ((int)getProp($product, 'cpid') !== $scriptCpid) {
  7504. Utils::throwError('20003:剧本存在跨组关联资产,无法完成转让');
  7505. }
  7506. $parentId = (int)getProp($product, 'parent_id', 0);
  7507. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7508. $folderIds[] = $parentId;
  7509. }
  7510. }
  7511. // 仅转让归属于原剧本所有者的资产
  7512. $folderIds = DB::table('mp_products')
  7513. ->whereIn('id', $folderIds)
  7514. ->where('type', 2)
  7515. ->where('cpid', $scriptCpid)
  7516. ->where('user_id', $fromUserId)
  7517. ->pluck('id')
  7518. ->map('intval')
  7519. ->all();
  7520. // 管理员仅可转让自己创建的资产及其所属文件夹(超管不做此验证)
  7521. if ($operatorRole !== 'superadmin') {
  7522. foreach ($products as $product) {
  7523. if ((int)getProp($product, 'user_id') !== (int)$operatorUid) {
  7524. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7525. }
  7526. }
  7527. foreach ($products as $product) {
  7528. $parentId = (int)getProp($product, 'parent_id', 0);
  7529. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7530. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7531. }
  7532. }
  7533. }
  7534. }
  7535. $now = now();
  7536. // 5.更新剧本归属
  7537. DB::table('mp_scripts')
  7538. ->where('id', $scriptId)
  7539. ->update([
  7540. 'user_id' => $targetUserId,
  7541. 'updated_at' => $now,
  7542. ]);
  7543. // 6.更新关联资产归属
  7544. if (!empty($productIds)) {
  7545. DB::table('mp_products')
  7546. ->whereIn('id', $productIds)
  7547. ->update([
  7548. 'user_id' => $targetUserId,
  7549. 'updated_at' => $now,
  7550. ]);
  7551. }
  7552. // 7.更新资产所属的类型根文件夹归属(文件夹属于 mp_products,随资产一并转让)
  7553. if (!empty($folderIds)) {
  7554. DB::table('mp_products')
  7555. ->whereIn('id', $folderIds)
  7556. ->update([
  7557. 'user_id' => $targetUserId,
  7558. 'updated_at' => $now,
  7559. ]);
  7560. }
  7561. // 8.校验剧本与资产是否全部更新成功,任一未成功则回滚
  7562. $scriptOwner = (int)DB::table('mp_scripts')->where('id', $scriptId)->value('user_id');
  7563. if ($scriptOwner !== $targetUserId) {
  7564. Utils::throwError('20003:剧本归属更新失败');
  7565. }
  7566. if (!empty($productIds)) {
  7567. $updatedProductCount = DB::table('mp_products')
  7568. ->whereIn('id', $productIds)
  7569. ->where('user_id', $targetUserId)
  7570. ->count();
  7571. if ($updatedProductCount !== count($productIds)) {
  7572. Utils::throwError('20003:部分剧本资产转让失败,已回滚');
  7573. }
  7574. }
  7575. if (!empty($folderIds)) {
  7576. $updatedFolderCount = DB::table('mp_products')
  7577. ->whereIn('id', $folderIds)
  7578. ->where('user_id', $targetUserId)
  7579. ->count();
  7580. if ($updatedFolderCount !== count($folderIds)) {
  7581. Utils::throwError('20003:部分资产文件夹转让失败,已回滚');
  7582. }
  7583. }
  7584. return [
  7585. 'script_id' => (int)$scriptId,
  7586. 'script_name' => (string)getProp($script, 'script_name', ''),
  7587. 'from_user_id' => $fromUserId,
  7588. 'to_user_id' => $targetUserId,
  7589. 'product_count' => count($productIds),
  7590. 'folder_count' => count($folderIds),
  7591. ];
  7592. }
  7593. /**
  7594. * 规范化ID列表,兼容数组、逗号分隔字符串以及字符串数组
  7595. *
  7596. * @param mixed $ids 待处理的ID集合
  7597. * @return array 去重后的正整数ID数组
  7598. */
  7599. private function normalizeIdList($ids) {
  7600. if (!is_array($ids)) {
  7601. $ids = explode(',', (string)$ids);
  7602. }
  7603. $result = [];
  7604. foreach ($ids as $item) {
  7605. if (is_array($item)) {
  7606. continue;
  7607. }
  7608. foreach (explode(',', (string)$item) as $part) {
  7609. $part = trim($part);
  7610. if ($part !== '' && is_numeric($part) && (int)$part > 0) {
  7611. $result[] = (int)$part;
  7612. }
  7613. }
  7614. }
  7615. return array_values(array_unique($result));
  7616. }
  7617. /**
  7618. * 通过 Excel 批量导入剧本资产(独立实现,不依赖 saveScriptProducts)
  7619. *
  7620. * 流程:
  7621. * 1. 校验剧本存在且属于当前用户
  7622. * 2. 解析 Excel 并校验强制列与数据完整性(资产类型/资产名称/使用范围/参考提示词)
  7623. * 3. 名称去重(与 Excel 内及该剧本已有关联资产比对)
  7624. * 4. 事务内创建类型文件夹、资产与剧本映射
  7625. * 5. 为没有图片的资产创建图片生成任务,生成中返回 SSE 轮询
  7626. *
  7627. * @param array $data 请求参数
  7628. * @param \Illuminate\Http\UploadedFile $file 上传的 Excel 文件
  7629. * @return array|\Generator
  7630. */
  7631. public function importScriptProductsByExcel($data, $file) {
  7632. $uid = Site::getUid();
  7633. $cpid = Site::getCpid();
  7634. $script_id = (int)getProp($data, 'script_id', 0);
  7635. if (!$script_id) {
  7636. Utils::throwError('20003:请提供剧本ID');
  7637. }
  7638. // 验证剧本是否存在,且只能导入自己创建的剧本
  7639. $script = DB::table('mp_scripts')
  7640. ->where('id', $script_id)
  7641. ->where('is_deleted', 0)
  7642. ->where('user_id', $uid)
  7643. ->first();
  7644. if (!$script) {
  7645. Utils::throwError('20003:剧本不存在或无权限操作');
  7646. }
  7647. $script_name = $script->script_name ?? 'script_' . $script_id;
  7648. // 校验上传文件
  7649. if (!$file) {
  7650. Utils::throwError('20003:请上传Excel文件');
  7651. }
  7652. $extension = strtolower($file->getClientOriginalExtension());
  7653. if (!in_array($extension, ['xlsx', 'xls'])) {
  7654. Utils::throwError('20003:文件格式错误,仅支持 xlsx、xls 格式');
  7655. }
  7656. if ($file->getSize() > 10 * 1024 * 1024) {
  7657. Utils::throwError('20003:文件大小不能超过10M');
  7658. }
  7659. // 解析 Excel(第一行为表头)
  7660. $rows = $this->readImportExcelRows($file);
  7661. if (empty($rows)) {
  7662. Utils::throwError('20003:Excel内容为空');
  7663. }
  7664. $headers = array_shift($rows);
  7665. // 定位强制列
  7666. $typeColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产类型'], ['资产类型', '类型']);
  7667. $nameColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产名称'], ['资产名称', '名称']);
  7668. $rangeColumnIndex = $this->findImportExcelColumnIndex($headers, ['使用范围'], ['使用范围', '范围']);
  7669. $promptColumnIndex = $this->findImportExcelColumnIndex($headers, ['参考提示词', '提示词'], ['提示词']);
  7670. $missingColumns = [];
  7671. if ($typeColumnIndex < 0) {
  7672. $missingColumns[] = '资产类型';
  7673. }
  7674. if ($nameColumnIndex < 0) {
  7675. $missingColumns[] = '资产名称';
  7676. }
  7677. if ($rangeColumnIndex < 0) {
  7678. $missingColumns[] = '使用范围';
  7679. }
  7680. if ($promptColumnIndex < 0) {
  7681. $missingColumns[] = '参考提示词';
  7682. }
  7683. if (!empty($missingColumns)) {
  7684. Utils::throwError('20003:Excel缺少必填列:' . implode('、', $missingColumns));
  7685. }
  7686. // 先整体校验 Excel 数据,所有异常行一次性返回
  7687. $validation = $this->validateImportExcelRows(
  7688. $rows,
  7689. $typeColumnIndex,
  7690. $nameColumnIndex,
  7691. $rangeColumnIndex,
  7692. $promptColumnIndex
  7693. );
  7694. $errors = $validation['errors'];
  7695. $checkedRows = $validation['checked_rows'];
  7696. if (empty($checkedRows)) {
  7697. $errors[] = 'Excel中没有有效的数据行';
  7698. }
  7699. if (!empty($errors)) {
  7700. Utils::throwError('20003:Excel数据校验失败:' . implode(';', $errors));
  7701. }
  7702. // 名称去重:Excel 内部 + 该剧本已关联资产(按 createProduct 的名称判断逻辑)
  7703. $existingNames = $this->getScriptProductNames($script_id, $cpid);
  7704. $dedupResult = $this->deduplicateImportRows($checkedRows, $existingNames);
  7705. $validRows = $dedupResult['valid_rows'];
  7706. $skipped = $dedupResult['skipped'];
  7707. // 图片生成参数(与 saveScriptProducts 保持一致的校验规则)
  7708. $model = getProp($data, 'model');
  7709. if (!$model) {
  7710. $model = 'gpt-image-2';
  7711. }
  7712. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7713. Utils::throwError('20003:该模型已不可用,请更换!');
  7714. }
  7715. $ratio = getProp($data, 'ratio', '9:16');
  7716. $resolution = strtolower(getProp($data, 'resolution', '2k'));
  7717. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7718. if (!isset($sizeMap[$resolution])) {
  7719. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7720. }
  7721. if (!isset($sizeMap[$resolution][$ratio])) {
  7722. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7723. }
  7724. $width = $sizeMap[$resolution][$ratio]['width'];
  7725. $height = $sizeMap[$resolution][$ratio]['height'];
  7726. $autoRaw = getProp($data, 'auto_generate_images', true);
  7727. $auto_generate_images = !in_array($autoRaw, [false, 0, '0', 'false', 'False'], true);
  7728. // 创建/复用任务中心记录(md5 验重,避免重复任务)
  7729. $taskCenterId = $this->createScriptProductTaskCenter(
  7730. $uid,
  7731. $cpid,
  7732. $script_id,
  7733. $validRows,
  7734. $model,
  7735. $ratio,
  7736. $resolution,
  7737. $auto_generate_images
  7738. );
  7739. // 全部为重复项:参照 saveScriptProducts,检查已存在资产的图片状态,缺图的补建任务
  7740. if (empty($validRows)) {
  7741. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7742. $script_id,
  7743. $model,
  7744. $width,
  7745. $height,
  7746. $auto_generate_images
  7747. );
  7748. $productTaskMap = $existingTaskInfo['product_task_map'];
  7749. $typeFolderIds = $existingTaskInfo['type_folder_ids'];
  7750. if (!empty($productTaskMap)) {
  7751. $message = 'Excel中的资产均已存在,正在为缺少图片的资产生成图片';
  7752. } elseif (!$existingTaskInfo['has_all_tasks']) {
  7753. $message = 'Excel中的资产均已存在,部分资产没有参考提示词,无法生成图片';
  7754. } else {
  7755. $message = 'Excel中的资产均已存在,且图片已全部生成完成';
  7756. }
  7757. $resultData = [
  7758. 'success' => true,
  7759. 'message' => $message,
  7760. 'script_id' => $script_id,
  7761. 'script_name' => $script_name,
  7762. 'imported_count' => 0,
  7763. 'existing_products' => $existingTaskInfo['product_count'],
  7764. 'skipped_count' => count($skipped),
  7765. 'skipped' => $skipped,
  7766. 'created_products' => [],
  7767. 'type_folder_ids' => $typeFolderIds,
  7768. 'pending_tasks_count' => count($productTaskMap),
  7769. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7770. 'task_center_id' => $taskCenterId,
  7771. ];
  7772. // 有需要轮询的任务(已有任务或本次补建):走 SSE 轮询
  7773. if (!empty($productTaskMap)) {
  7774. return $this->pollProductImageTasks(
  7775. $script_id,
  7776. $script_name,
  7777. $productTaskMap,
  7778. $typeFolderIds,
  7779. $taskCenterId,
  7780. ['import_result' => $resultData],
  7781. ['import_result' => $resultData]
  7782. );
  7783. }
  7784. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7785. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7786. }
  7787. // 事务内创建资产、类型文件夹与剧本映射
  7788. $typeFolderIds = [];
  7789. $createdProducts = [];
  7790. $mappingRecords = [];
  7791. $now = now();
  7792. DB::beginTransaction();
  7793. try {
  7794. foreach ($validRows as $row) {
  7795. $type = $row['type'];
  7796. if (!isset($typeFolderIds[$type])) {
  7797. // 与 createProduct 一致:先查找该剧本已存在的类型文件夹,没有则创建
  7798. $folder = DB::table('mp_products')
  7799. ->where('cpid', $cpid)
  7800. ->where('type', 2)
  7801. ->where('product', $type)
  7802. ->where('product_name', $script_name)
  7803. ->where('parent_id', 0)
  7804. ->where('is_deleted', 0)
  7805. ->first();
  7806. if ($folder) {
  7807. $typeFolderIds[$type] = $folder->id;
  7808. } else {
  7809. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7810. 'user_id' => $uid,
  7811. 'cpid' => $cpid,
  7812. 'type' => 2, // 文件夹
  7813. 'product' => $type, // 1=角色 2=场景 3=道具
  7814. 'parent_id' => 0,
  7815. 'level' => 1,
  7816. 'product_name' => $script_name,
  7817. 'sort_order' => time() + $type,
  7818. 'is_deleted' => 0,
  7819. 'created_at' => $now,
  7820. 'updated_at' => $now,
  7821. ]);
  7822. }
  7823. }
  7824. $folder_id = $typeFolderIds[$type];
  7825. $product_id = DB::table('mp_products')->insertGetId([
  7826. 'user_id' => $uid,
  7827. 'cpid' => $cpid,
  7828. 'type' => 1, // 资产
  7829. 'product' => $type,
  7830. 'parent_id' => $folder_id,
  7831. 'level' => 2,
  7832. 'product_name' => $row['product_name'],
  7833. 'pic_prompt' => $row['pic_prompt'],
  7834. 'sort_order' => time(),
  7835. 'is_deleted' => 0,
  7836. 'created_at' => $now,
  7837. 'updated_at' => $now,
  7838. ]);
  7839. $createdProducts[] = [
  7840. 'id' => $product_id,
  7841. 'type' => $type,
  7842. 'product_name' => $row['product_name'],
  7843. 'pic_prompt' => $row['pic_prompt'],
  7844. ];
  7845. // 为每个使用范围(集数)创建映射记录
  7846. foreach ($row['episode_numbers'] as $episodeNumber) {
  7847. $mappingRecords[] = [
  7848. 'script_id' => $script_id,
  7849. 'product_id' => $product_id,
  7850. 'episode_number' => $episodeNumber,
  7851. 'created_at' => $now,
  7852. 'updated_at' => $now,
  7853. ];
  7854. }
  7855. }
  7856. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7857. DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7858. // 剧本已有资产,同步更新is_products标记
  7859. DB::table('mp_scripts')->where('id', $script_id)->update([
  7860. 'is_products' => 1,
  7861. 'updated_at' => $now,
  7862. ]);
  7863. DB::commit();
  7864. } catch (\Exception $e) {
  7865. DB::rollback();
  7866. if ($taskCenterId) {
  7867. $this->taskCenterService->updateTask($taskCenterId, [
  7868. 'status' => MpTaskCenter::STATUS_FAILED,
  7869. 'error_message' => $e->getMessage(),
  7870. ]);
  7871. }
  7872. dLog('anime')->error('Excel导入剧本资产失败: ' . $e->getMessage(), [
  7873. 'script_id' => $script_id,
  7874. 'error' => $e->getMessage(),
  7875. 'trace' => $e->getTraceAsString(),
  7876. ]);
  7877. Utils::throwError('20003:Excel导入剧本资产失败:' . $e->getMessage());
  7878. }
  7879. // 参照 saveScriptProducts:为新建资产以及已存在但缺图的资产统一补建图片生成任务
  7880. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7881. $script_id,
  7882. $model,
  7883. $width,
  7884. $height,
  7885. $auto_generate_images
  7886. );
  7887. $productTaskMap = $existingTaskInfo['product_task_map'];
  7888. $resultData = [
  7889. 'success' => true,
  7890. 'message' => '导入完成',
  7891. 'script_id' => $script_id,
  7892. 'script_name' => $script_name,
  7893. 'imported_count' => count($createdProducts),
  7894. 'skipped_count' => count($skipped),
  7895. 'skipped' => $skipped,
  7896. 'created_products' => array_map(function ($item) {
  7897. return [
  7898. 'id' => $item['id'],
  7899. 'type' => $item['type'],
  7900. 'product_name' => $item['product_name'],
  7901. ];
  7902. }, $createdProducts),
  7903. 'type_folder_ids' => $typeFolderIds,
  7904. 'pending_tasks_count' => count($productTaskMap),
  7905. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7906. 'task_center_id' => $taskCenterId,
  7907. ];
  7908. // 有待生成的图片任务:返回 SSE 轮询结果(导入统计在 init 与 complete 事件中)
  7909. if (!empty($productTaskMap)) {
  7910. return $this->pollProductImageTasks(
  7911. $script_id,
  7912. $script_name,
  7913. $productTaskMap,
  7914. $typeFolderIds,
  7915. $taskCenterId,
  7916. ['import_result' => $resultData],
  7917. ['import_result' => $resultData]
  7918. );
  7919. }
  7920. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7921. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7922. }
  7923. /**
  7924. * 校验 Excel 数据行(先校验完毕,再进行后续逻辑)
  7925. *
  7926. * @param array $rows
  7927. * @param int $typeColumnIndex
  7928. * @param int $nameColumnIndex
  7929. * @param int $rangeColumnIndex
  7930. * @param int $promptColumnIndex
  7931. * @return array ['errors' => [], 'checked_rows' => []]
  7932. */
  7933. private function validateImportExcelRows(array $rows, $typeColumnIndex, $nameColumnIndex, $rangeColumnIndex, $promptColumnIndex) {
  7934. $errors = [];
  7935. $checkedRows = [];
  7936. foreach ($rows as $rowIndex => $row) {
  7937. // 数据从第2行开始(表头占第1行)
  7938. $excelRowNo = $rowIndex + 2;
  7939. if (!is_array($row) || $this->isImportExcelRowEmpty($row)) {
  7940. continue;
  7941. }
  7942. $typeRaw = trim((string)($row[$typeColumnIndex] ?? ''));
  7943. $nameRaw = trim((string)($row[$nameColumnIndex] ?? ''));
  7944. $rangeRaw = trim((string)($row[$rangeColumnIndex] ?? ''));
  7945. $promptRaw = trim((string)($row[$promptColumnIndex] ?? ''));
  7946. $missingFields = [];
  7947. if ($typeRaw === '') {
  7948. $missingFields[] = '资产类型';
  7949. }
  7950. if ($nameRaw === '') {
  7951. $missingFields[] = '资产名称';
  7952. }
  7953. if ($rangeRaw === '') {
  7954. $missingFields[] = '使用范围';
  7955. }
  7956. if ($promptRaw === '') {
  7957. $missingFields[] = '参考提示词';
  7958. }
  7959. if (!empty($missingFields)) {
  7960. $errors[] = "第{$excelRowNo}行:" . implode('、', $missingFields) . '不能为空';
  7961. continue;
  7962. }
  7963. // 资产类型校验
  7964. $productType = $this->resolveImportProductType($typeRaw);
  7965. if (!$productType) {
  7966. $errors[] = "第{$excelRowNo}行:资产类型「{$typeRaw}」不正确,仅支持 角色/场景/道具";
  7967. continue;
  7968. }
  7969. // 资产名称去除两边特殊符号
  7970. $productName = $this->normalizeImportProductName($nameRaw);
  7971. if ($productName === '') {
  7972. $errors[] = "第{$excelRowNo}行:资产名称「{$nameRaw}」去除特殊符号后为空";
  7973. continue;
  7974. }
  7975. if (mb_strlen($productName, 'UTF-8') > 64) {
  7976. $errors[] = "第{$excelRowNo}行:资产名称「{$productName}」超过64个字符";
  7977. continue;
  7978. }
  7979. // 解析使用范围(逗号分隔的集数)
  7980. $episodeNumbers = $this->parseImportEpisodeNumbers($rangeRaw);
  7981. if (empty($episodeNumbers)) {
  7982. $errors[] = "第{$excelRowNo}行:使用范围「{$rangeRaw}」格式错误,仅支持数字或逗号分隔的数字";
  7983. continue;
  7984. }
  7985. $checkedRows[] = [
  7986. 'row' => $excelRowNo,
  7987. 'type' => $productType,
  7988. 'product_name' => $productName,
  7989. 'episode_numbers' => $episodeNumbers,
  7990. 'pic_prompt' => $promptRaw,
  7991. ];
  7992. }
  7993. return [
  7994. 'errors' => $errors,
  7995. 'checked_rows' => $checkedRows,
  7996. ];
  7997. }
  7998. /**
  7999. * Excel 资产名称去重:Excel 内部 + 剧本已有关联资产
  8000. *
  8001. * @param array $checkedRows
  8002. * @param array $existingNames 剧本已有关联资产名称集合(name => true)
  8003. * @return array ['valid_rows' => [], 'skipped' => []]
  8004. */
  8005. private function deduplicateImportRows(array $checkedRows, array $existingNames) {
  8006. $seenNames = [];
  8007. $validRows = [];
  8008. $skipped = [];
  8009. foreach ($checkedRows as $row) {
  8010. $nameKey = $row['product_name'];
  8011. $typeText = $this->getImportProductTypeText($row['type']);
  8012. if (isset($seenNames[$nameKey])) {
  8013. $skipped[] = [
  8014. 'row' => $row['row'],
  8015. 'type' => $typeText,
  8016. 'product_name' => $row['product_name'],
  8017. 'reason' => 'Excel中资产名称重复',
  8018. ];
  8019. continue;
  8020. }
  8021. if (isset($existingNames[$nameKey])) {
  8022. $skipped[] = [
  8023. 'row' => $row['row'],
  8024. 'type' => $typeText,
  8025. 'product_name' => $row['product_name'],
  8026. 'reason' => '剧本中已存在同名资产',
  8027. ];
  8028. continue;
  8029. }
  8030. $seenNames[$nameKey] = true;
  8031. $validRows[] = $row;
  8032. }
  8033. return [
  8034. 'valid_rows' => $validRows,
  8035. 'skipped' => $skipped,
  8036. ];
  8037. }
  8038. /**
  8039. * 读取 Excel 文件为二维数组(第一行为表头)
  8040. *
  8041. * @param \Illuminate\Http\UploadedFile $file
  8042. * @return array
  8043. */
  8044. private function readImportExcelRows($file) {
  8045. try {
  8046. $reader = IOFactory::createReaderForFile($file->getRealPath());
  8047. $reader->setReadDataOnly(true);
  8048. $spreadsheet = $reader->load($file->getRealPath());
  8049. $sheet = $spreadsheet->getSheet(0);
  8050. $rows = $sheet->toArray(null, true, true, false);
  8051. $spreadsheet->disconnectWorksheets();
  8052. unset($spreadsheet);
  8053. return $rows;
  8054. } catch (\Exception $e) {
  8055. dLog('anime')->error('Excel文件解析失败', [
  8056. 'error' => $e->getMessage(),
  8057. ]);
  8058. Utils::throwError('20003:Excel文件解析失败,请确认文件格式正确');
  8059. }
  8060. }
  8061. /**
  8062. * 查找 Excel 表头列索引(先精确匹配,再模糊匹配)
  8063. *
  8064. * @param array $headers
  8065. * @param array $exactKeywords
  8066. * @param array $fuzzyKeywords
  8067. * @return int
  8068. */
  8069. private function findImportExcelColumnIndex(array $headers, array $exactKeywords, array $fuzzyKeywords) {
  8070. foreach ($headers as $index => $header) {
  8071. $header = trim((string)$header);
  8072. if ($header === '') {
  8073. continue;
  8074. }
  8075. foreach ($exactKeywords as $keyword) {
  8076. if ($header === $keyword) {
  8077. return $index;
  8078. }
  8079. }
  8080. }
  8081. foreach ($headers as $index => $header) {
  8082. $header = trim((string)$header);
  8083. if ($header === '') {
  8084. continue;
  8085. }
  8086. foreach ($fuzzyKeywords as $keyword) {
  8087. if (mb_strpos($header, $keyword) !== false) {
  8088. return $index;
  8089. }
  8090. }
  8091. }
  8092. return -1;
  8093. }
  8094. /**
  8095. * 判断 Excel 行是否为空行
  8096. *
  8097. * @param array $row
  8098. * @return bool
  8099. */
  8100. private function isImportExcelRowEmpty(array $row) {
  8101. foreach ($row as $cell) {
  8102. if (trim((string)$cell) !== '') {
  8103. return false;
  8104. }
  8105. }
  8106. return true;
  8107. }
  8108. /**
  8109. * 资产名称去除两边特殊符号(与 createProduct 保持一致)
  8110. *
  8111. * @param string $name
  8112. * @return string
  8113. */
  8114. private function normalizeImportProductName($name) {
  8115. $name = trim((string)$name);
  8116. $name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $name);
  8117. if (!$name || preg_match('/^[-—_]+$/u', $name)) {
  8118. return '';
  8119. }
  8120. return $name;
  8121. }
  8122. /**
  8123. * 解析 Excel 中的资产类型
  8124. *
  8125. * @param string $value
  8126. * @return int|null 1=角色 2=场景 3=道具
  8127. */
  8128. private function resolveImportProductType($value) {
  8129. $value = trim((string)$value);
  8130. $map = [
  8131. '角色' => 1,
  8132. '主体' => 1,
  8133. '人物' => 1,
  8134. '1' => 1,
  8135. '场景' => 2,
  8136. '2' => 2,
  8137. '道具' => 3,
  8138. '3' => 3,
  8139. ];
  8140. return isset($map[$value]) ? $map[$value] : null;
  8141. }
  8142. /**
  8143. * 资产类型文案
  8144. *
  8145. * @param int $type
  8146. * @return string
  8147. */
  8148. private function getImportProductTypeText($type) {
  8149. $map = [1 => '角色', 2 => '场景', 3 => '道具'];
  8150. return isset($map[$type]) ? $map[$type] : (string)$type;
  8151. }
  8152. /**
  8153. * 解析使用范围(逗号分隔的集数)
  8154. *
  8155. * @param string $value
  8156. * @return array
  8157. */
  8158. private function parseImportEpisodeNumbers($value) {
  8159. $parts = preg_split('/[,,、\s]+/u', trim((string)$value));
  8160. $episodeNumbers = [];
  8161. foreach ($parts as $part) {
  8162. if ($part === '') {
  8163. continue;
  8164. }
  8165. if (!is_numeric($part)) {
  8166. return [];
  8167. }
  8168. $episodeNumbers[] = (int)$part;
  8169. }
  8170. $episodeNumbers = array_values(array_unique($episodeNumbers));
  8171. sort($episodeNumbers);
  8172. return $episodeNumbers;
  8173. }
  8174. /**
  8175. * 获取剧本已关联资产名称集合(按 createProduct 的名称判断逻辑)
  8176. *
  8177. * @param int $script_id
  8178. * @param int $cpid
  8179. * @return array
  8180. */
  8181. private function getScriptProductNames($script_id, $cpid) {
  8182. $products = DB::table('mp_script_product_mappings as m')
  8183. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8184. ->where('m.script_id', $script_id)
  8185. ->where('p.cpid', $cpid)
  8186. ->where('p.type', 1)
  8187. ->where('p.is_deleted', 0)
  8188. ->get(['p.product_name']);
  8189. $names = [];
  8190. foreach ($products as $product) {
  8191. $name = $this->normalizeImportProductName($product->product_name);
  8192. if ($name !== '') {
  8193. $names[$name] = true;
  8194. }
  8195. }
  8196. return $names;
  8197. }
  8198. /**
  8199. * 获取剧本已关联的资产名称(仅按剧本判重,不区分资产类型)
  8200. *
  8201. * @param int $script_id
  8202. * @return array ['资产名称' => true]
  8203. */
  8204. private function getScriptAssetNames($script_id) {
  8205. $products = DB::table('mp_script_product_mappings as m')
  8206. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8207. ->where('m.script_id', $script_id)
  8208. ->where('p.type', 1)
  8209. ->where('p.is_deleted', 0)
  8210. ->get(['p.product_name']);
  8211. $names = [];
  8212. foreach ($products as $product) {
  8213. $name = $this->normalizeImportProductName($product->product_name);
  8214. if ($name !== '') {
  8215. $names[$name] = true;
  8216. }
  8217. }
  8218. return $names;
  8219. }
  8220. /**
  8221. * 校验并提取本次入参中的新增资产行
  8222. *
  8223. * 规则:
  8224. * - 资产名称为空(或仅剩占位符):跳过
  8225. * - 同一份入参内重名(跨类型):保留最后一条
  8226. * - 与剧本已关联资产同名(跨类型判重,仅限当前剧本):不算新增
  8227. * - 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8228. *
  8229. * @param int $script_id
  8230. * @param mixed $products 入参(数组或 JSON 字符串)
  8231. * @return array [['type' => int, 'product_name' => string, 'pic_prompt' => string, 'episode_numbers' => []]]
  8232. */
  8233. private function extractNewScriptProductRows($script_id, $products) {
  8234. // 兼容 JSON 字符串;无法解析时按"没有新增行"处理,由后续创建逻辑给出原有报错
  8235. if (is_string($products)) {
  8236. $decoded = json_decode($products, true);
  8237. $products = (json_last_error() === JSON_ERROR_NONE) ? $decoded : [];
  8238. }
  8239. if (!is_array($products) || empty($products)) {
  8240. return [];
  8241. }
  8242. $rowMap = [];
  8243. foreach ($products as $productGroup) {
  8244. $type = getProp($productGroup, 'type');
  8245. $content = getProp($productGroup, 'content', []);
  8246. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8247. continue;
  8248. }
  8249. // 获取表头(第一行)并查找关键列的位置
  8250. $headers = $content[0];
  8251. $nameColumnIndex = -1;
  8252. $sequenceColumnIndex = -1;
  8253. $promptColumnIndex = -1;
  8254. $fallbackPromptColumnIndex = -1;
  8255. foreach ($headers as $index => $header) {
  8256. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8257. $nameColumnIndex = $index;
  8258. }
  8259. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8260. $sequenceColumnIndex = $index;
  8261. }
  8262. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8263. $promptColumnIndex = $index;
  8264. } elseif (strpos($header, '提示词') !== false && $fallbackPromptColumnIndex === -1) {
  8265. // 与 Excel 导入保持一致:优先"参考提示词",否则兼容"提示词"列
  8266. $fallbackPromptColumnIndex = $index;
  8267. }
  8268. }
  8269. if ($promptColumnIndex === -1) {
  8270. $promptColumnIndex = $fallbackPromptColumnIndex;
  8271. }
  8272. if ($nameColumnIndex === -1) {
  8273. continue;
  8274. }
  8275. for ($i = 1; $i < count($content); $i++) {
  8276. $row = $content[$i];
  8277. if (empty($row) || !isset($row[$nameColumnIndex])) {
  8278. continue;
  8279. }
  8280. // 处理product_name两边的符号;名称为空或仅剩占位符号则跳过
  8281. $product_name = $this->normalizeImportProductName($row[$nameColumnIndex]);
  8282. if ($product_name === '') {
  8283. continue;
  8284. }
  8285. $pic_prompt = '';
  8286. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8287. $pic_prompt = trim((string)$row[$promptColumnIndex]);
  8288. }
  8289. // 解析使用范围(逗号分隔的序号),为空时由创建逻辑写入默认映射(序号0)
  8290. $sequences = [];
  8291. $sequence_str = ($sequenceColumnIndex >= 0 && isset($row[$sequenceColumnIndex]))
  8292. ? trim((string)$row[$sequenceColumnIndex])
  8293. : '';
  8294. if ($sequence_str !== '') {
  8295. foreach (array_map('trim', explode(',', $sequence_str)) as $part) {
  8296. if (is_numeric($part)) {
  8297. $sequences[] = (int)$part;
  8298. }
  8299. }
  8300. }
  8301. // 跨类型判重,同一份入参内重名保留最后一条
  8302. $rowMap[$product_name] = [
  8303. 'type' => (int)$type,
  8304. 'product_name' => $product_name,
  8305. 'pic_prompt' => $pic_prompt,
  8306. 'episode_numbers' => $sequences,
  8307. ];
  8308. }
  8309. }
  8310. // 与剧本已关联资产判重(仅限当前剧本,跨类型)
  8311. $existingNames = $this->getScriptAssetNames($script_id);
  8312. $newRows = [];
  8313. $emptyPromptNames = [];
  8314. foreach ($rowMap as $name => $row) {
  8315. if (isset($existingNames[$name])) {
  8316. continue;
  8317. }
  8318. if ($row['pic_prompt'] === '') {
  8319. $emptyPromptNames[] = $name;
  8320. continue;
  8321. }
  8322. $newRows[] = $row;
  8323. }
  8324. // 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8325. if (!empty($emptyPromptNames)) {
  8326. Utils::throwError('20003:以下新增资产的参考提示词不能为空:' . implode('、', $emptyPromptNames));
  8327. }
  8328. return $newRows;
  8329. }
  8330. /**
  8331. * 已有关联资产的图片任务处理(参照 saveScriptProducts 的处理方式)
  8332. *
  8333. * - 已有图片任务的资产:收集任务ID,交给轮询
  8334. * - 已有图片且生成成功的资产:跳过
  8335. * - 没有图片的资产:允许自动生成时补建图片任务(需要提示词)
  8336. *
  8337. * @param int $script_id
  8338. * @param string $model
  8339. * @param int $width
  8340. * @param int $height
  8341. * @param bool $auto_generate_images
  8342. * @return array ['product_task_map' => [], 'type_folder_ids' => [], 'has_all_tasks' => bool, 'product_count' => int, 'created_count' => int]
  8343. */
  8344. private function prepareExistingScriptProductTasks($script_id, $model, $width, $height, $auto_generate_images) {
  8345. $productTaskMap = [];
  8346. $typeFolderIds = [];
  8347. $hasAllTasks = true;
  8348. $createdCount = 0;
  8349. $existingMappings = DB::table('mp_script_product_mappings')
  8350. ->where('script_id', $script_id)
  8351. ->get();
  8352. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8353. $productsWithTasks = DB::table('mp_products')
  8354. ->whereIn('id', $productIds)
  8355. ->where('is_deleted', 0)
  8356. ->get();
  8357. foreach ($productsWithTasks as $product) {
  8358. // 收集类型文件夹ID
  8359. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8360. $parentFolder = DB::table('mp_products')
  8361. ->where('id', $product->parent_id)
  8362. ->where('type', 2)
  8363. ->first();
  8364. if ($parentFolder) {
  8365. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8366. }
  8367. }
  8368. // 检查是否有图片生成任务
  8369. if (!empty($product->pic_task_id)) {
  8370. $productTaskMap[$product->id] = $product->pic_task_id;
  8371. } elseif ($product->url && $product->pic_task_status == '生成成功') {
  8372. continue;
  8373. } else {
  8374. // 有资产没有图片
  8375. $hasAllTasks = false;
  8376. }
  8377. }
  8378. // 为没有图片的资产补建图片生成任务
  8379. if (!$hasAllTasks && $auto_generate_images && $productsWithTasks->isNotEmpty()) {
  8380. DB::beginTransaction();
  8381. try {
  8382. foreach ($productsWithTasks as $product) {
  8383. // 跳过已有任务的资产
  8384. if (!empty($product->pic_task_id)) {
  8385. continue;
  8386. }
  8387. // 跳过没有提示词的资产
  8388. if (empty($product->pic_prompt)) {
  8389. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8390. 'product_id' => $product->id,
  8391. 'product_name' => $product->product_name,
  8392. ]);
  8393. continue;
  8394. }
  8395. try {
  8396. $task = $this->aiImageGenerationService->createImageGenerationTask([
  8397. 'prompt' => $product->pic_prompt,
  8398. 'model' => $model,
  8399. 'ref_img_urls' => [],
  8400. 'width' => $width,
  8401. 'height' => $height,
  8402. // 计费锚点(剧本),用于积分明细归属统计
  8403. 'script_id' => $script_id,
  8404. ]);
  8405. $task_id = $task->id;
  8406. if ($task_id) {
  8407. $productTaskMap[$product->id] = $task_id;
  8408. $createdCount++;
  8409. DB::table('mp_products')
  8410. ->where('id', $product->id)
  8411. ->update([
  8412. 'pic_task_id' => $task_id,
  8413. 'pic_task_status' => '生成中',
  8414. 'updated_at' => now(),
  8415. ]);
  8416. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8417. 'product_id' => $product->id,
  8418. 'task_id' => $task_id,
  8419. ]);
  8420. }
  8421. } catch (\Exception $e) {
  8422. dLog('anime')->error('创建资产图片生成任务失败', [
  8423. 'product_id' => $product->id,
  8424. 'error' => $e->getMessage(),
  8425. ]);
  8426. DB::table('mp_products')
  8427. ->where('id', $product->id)
  8428. ->update([
  8429. 'pic_task_status' => '生成失败',
  8430. 'updated_at' => now(),
  8431. ]);
  8432. }
  8433. }
  8434. DB::commit();
  8435. } catch (\Exception $e) {
  8436. DB::rollback();
  8437. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8438. 'script_id' => $script_id,
  8439. 'error' => $e->getMessage(),
  8440. ]);
  8441. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8442. }
  8443. }
  8444. return [
  8445. 'product_task_map' => $productTaskMap,
  8446. 'type_folder_ids' => $typeFolderIds,
  8447. 'has_all_tasks' => $hasAllTasks,
  8448. 'product_count' => count($productIds),
  8449. 'created_count' => $createdCount,
  8450. ];
  8451. }
  8452. /**
  8453. * 保存剧本资产关联关系
  8454. * @param array $data 请求参数
  8455. * @return bool
  8456. */
  8457. public function saveScriptProducts($data) {
  8458. $uid = Site::getUid();
  8459. $cpid = Site::getCpid();
  8460. $script_id = getProp($data, 'script_id');
  8461. $products = getProp($data, 'products', []);
  8462. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  8463. if (!$script_id) {
  8464. Utils::throwError('20003:请提供剧本ID');
  8465. }
  8466. // 验证剧本是否存在
  8467. $script = DB::table('mp_scripts')
  8468. ->where('id', $script_id)
  8469. ->where('is_deleted', 0)
  8470. ->first();
  8471. if (!$script) {
  8472. Utils::throwError('20003:剧本不存在');
  8473. }
  8474. // 处理图片模型
  8475. $model = getProp($data, 'model');
  8476. if (!$model) {
  8477. // 使用默认模型
  8478. $model = 'gpt-image-2';
  8479. }
  8480. // 验证模型是否在可用模型表中
  8481. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8482. Utils::throwError('20003:该模型已不可用,请更换!');
  8483. }
  8484. $ratio = getProp($data, 'ratio', '9:16');
  8485. $resolution = getProp($data, 'resolution', '2k');
  8486. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  8487. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  8488. // 参数验证
  8489. $resolution = strtolower($resolution);
  8490. if (!isset($sizeMap[$resolution])) {
  8491. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  8492. }
  8493. if (!isset($sizeMap[$resolution][$ratio])) {
  8494. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  8495. }
  8496. // 根据 ratio 和 resolution 确定宽高
  8497. $width = $sizeMap[$resolution][$ratio]['width'];
  8498. $height = $sizeMap[$resolution][$ratio]['height'];
  8499. $script_name = $script->script_name ?? 'script_' . $script_id;
  8500. // 先校验并提取本次入参中的新增资产行:
  8501. // 新增行的参考提示词为空时直接报错,不写任何数据、不创建任务中心记录
  8502. $newRows = $this->extractNewScriptProductRows($script_id, $products);
  8503. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  8504. $taskCenterId = $this->createScriptProductTaskCenter(
  8505. $uid,
  8506. $cpid,
  8507. $script_id,
  8508. $products,
  8509. $model,
  8510. $ratio,
  8511. $resolution,
  8512. $auto_generate_images
  8513. );
  8514. // 检查是否已经有该剧本的资产数据
  8515. $existingMappings = DB::table('mp_script_product_mappings')
  8516. ->where('script_id', $script_id)
  8517. ->get();
  8518. // 已有资产且本次没有新增行时,走原有的"已存在"处理;否则走下方创建逻辑
  8519. if ($existingMappings->isNotEmpty() && empty($newRows)) {
  8520. // 已存在资产映射,检查是否所有资产都有图片生成任务
  8521. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8522. // 查询这些资产的图片生成任务状态
  8523. $productsWithTasks = DB::table('mp_products')
  8524. ->whereIn('id', $productIds)
  8525. ->where('is_deleted', 0)
  8526. ->get();
  8527. $productTaskMap = [];
  8528. $typeFolderIds = [];
  8529. $hasAllTasks = true;
  8530. foreach ($productsWithTasks as $product) {
  8531. // 收集类型文件夹ID
  8532. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8533. $parentFolder = DB::table('mp_products')
  8534. ->where('id', $product->parent_id)
  8535. ->where('type', 2)
  8536. ->first();
  8537. if ($parentFolder) {
  8538. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8539. }
  8540. }
  8541. // 检查是否有图片生成任务
  8542. if (!empty($product->pic_task_id)) {
  8543. $productTaskMap[$product->id] = $product->pic_task_id;
  8544. } else if($product->url && $product->pic_task_status == '生成成功') {
  8545. continue;
  8546. } else {
  8547. // 有资产没有图片任务
  8548. $hasAllTasks = false;
  8549. }
  8550. }
  8551. // 如果所有资产都有任务ID,直接轮询返回结果
  8552. if ($hasAllTasks && !empty($productTaskMap)) {
  8553. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  8554. 'script_id' => $script_id,
  8555. 'script_name' => $script_name,
  8556. 'product_count' => count($productTaskMap)
  8557. ]);
  8558. // 直接返回 SSE 流轮询结果
  8559. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8560. }
  8561. // 如果部分资产没有任务ID,只为这些资产创建任务
  8562. if (!$hasAllTasks && $auto_generate_images) {
  8563. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  8564. 'script_id' => $script_id,
  8565. 'script_name' => $script_name
  8566. ]);
  8567. // 开启事务
  8568. DB::beginTransaction();
  8569. try {
  8570. foreach ($productsWithTasks as $product) {
  8571. // 跳过已有任务的资产
  8572. if (!empty($product->pic_task_id)) {
  8573. continue;
  8574. }
  8575. // 跳过没有提示词的资产
  8576. if (empty($product->pic_prompt)) {
  8577. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8578. 'product_id' => $product->id,
  8579. 'product_name' => $product->product_name
  8580. ]);
  8581. continue;
  8582. }
  8583. try {
  8584. // 创建图片生成任务
  8585. $params = [
  8586. 'prompt' => $product->pic_prompt,
  8587. 'model' => $model,
  8588. 'ref_img_urls' => [],
  8589. 'width' => $width,
  8590. 'height' => $height,
  8591. // 计费锚点(剧本),用于积分明细归属统计
  8592. 'script_id' => $script_id,
  8593. ];
  8594. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8595. $task_id = $task->id;
  8596. if ($task_id) {
  8597. $productTaskMap[$product->id] = $task_id;
  8598. // 在事务中更新资产表的任务ID和状态
  8599. DB::table('mp_products')
  8600. ->where('id', $product->id)
  8601. ->update([
  8602. 'pic_task_id' => $task_id,
  8603. 'pic_task_status' => '生成中',
  8604. 'updated_at' => now()
  8605. ]);
  8606. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8607. 'product_id' => $product->id,
  8608. 'task_id' => $task_id
  8609. ]);
  8610. }
  8611. } catch (\Exception $e) {
  8612. dLog('anime')->error('创建资产图片生成任务失败', [
  8613. 'product_id' => $product->id,
  8614. 'error' => $e->getMessage()
  8615. ]);
  8616. // 标记为失败(仍在事务中)
  8617. DB::table('mp_products')
  8618. ->where('id', $product->id)
  8619. ->update([
  8620. 'pic_task_status' => '生成失败',
  8621. 'updated_at' => now()
  8622. ]);
  8623. }
  8624. }
  8625. // 提交事务
  8626. DB::commit();
  8627. // 如果有新创建的任务,返回 SSE 流
  8628. if (!empty($productTaskMap)) {
  8629. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8630. }
  8631. } catch (\Exception $e) {
  8632. // 回滚事务
  8633. DB::rollback();
  8634. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8635. 'script_id' => $script_id,
  8636. 'error' => $e->getMessage()
  8637. ]);
  8638. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8639. }
  8640. }
  8641. // 如果不需要生成图片,返回已存在的信息
  8642. $resultData = [
  8643. 'success' => true,
  8644. 'message' => '剧本资产已存在',
  8645. 'script_id' => $script_id,
  8646. 'script_name' => $script_name,
  8647. 'type_folder_ids' => $typeFolderIds,
  8648. 'existing_products' => count($productIds),
  8649. 'tasks_count' => count($productTaskMap),
  8650. 'task_center_id' => $taskCenterId
  8651. ];
  8652. // 接口已正常完成,更新任务中心状态和结果
  8653. if ($taskCenterId) {
  8654. $this->taskCenterService->updateTask($taskCenterId, [
  8655. 'status' => MpTaskCenter::STATUS_SUCCESS,
  8656. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  8657. 'error_message' => null
  8658. ]);
  8659. }
  8660. return $resultData;
  8661. }
  8662. // 走到这里说明有新行需要创建(或剧本还没有任何资产),保留原有的入参校验报错
  8663. if (empty($newRows)) {
  8664. $decodedProducts = $products;
  8665. if (is_string($decodedProducts)) {
  8666. $decodedProducts = json_decode($decodedProducts, true);
  8667. if (json_last_error() !== JSON_ERROR_NONE) {
  8668. Utils::throwError('20003:产品数据格式错误');
  8669. }
  8670. }
  8671. if (!is_array($decodedProducts) || empty($decodedProducts)) {
  8672. Utils::throwError('20003:产品数据不能为空');
  8673. }
  8674. Utils::throwError('20003:没有有效的产品数据');
  8675. }
  8676. // 仅保留本次新增的资产行,复用下方原有的创建逻辑
  8677. $products = [];
  8678. foreach ($newRows as $newRow) {
  8679. if (!isset($products[$newRow['type']])) {
  8680. $products[$newRow['type']] = [
  8681. 'type' => $newRow['type'],
  8682. 'content' => [['资产名称', '使用范围', '参考提示词']],
  8683. ];
  8684. }
  8685. $products[$newRow['type']]['content'][] = [
  8686. $newRow['product_name'],
  8687. implode(',', $newRow['episode_numbers']),
  8688. $newRow['pic_prompt'],
  8689. ];
  8690. }
  8691. $products = array_values($products);
  8692. // 以下是原有的创建逻辑...
  8693. // 开启事务
  8694. DB::beginTransaction();
  8695. try {
  8696. $now = now();
  8697. $mappingRecords = [];
  8698. $createdProductIds = []; // 记录所有创建的资产ID
  8699. // 获取剧本名称
  8700. $script_name = $script->script_name ?? 'script_' . $script_id;
  8701. // 存储每个类型的根文件夹ID
  8702. $typeFolderIds = [];
  8703. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  8704. foreach ($products as $productGroup) {
  8705. $type = getProp($productGroup, 'type');
  8706. $title = getProp($productGroup, 'title', '');
  8707. $content = getProp($productGroup, 'content', []);
  8708. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8709. continue;
  8710. }
  8711. // 为当前类型获取根文件夹:该剧本已存在则复用,避免重复创建根文件夹
  8712. if (!isset($typeFolderIds[$type])) {
  8713. $folder = DB::table('mp_products')
  8714. ->where('cpid', $cpid)
  8715. ->where('type', 2)
  8716. ->where('product', $type)
  8717. ->where('product_name', $script_name)
  8718. ->where('parent_id', 0)
  8719. ->where('is_deleted', 0)
  8720. ->first();
  8721. if ($folder) {
  8722. $typeFolderIds[$type] = $folder->id;
  8723. } else {
  8724. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  8725. 'user_id' => $uid,
  8726. 'cpid' => $cpid,
  8727. 'type' => 2, // 1.资产 2文件夹
  8728. 'product' => $type, // 1.主体 2.场景 3.道具
  8729. 'parent_id' => 0, // 根文件夹,parent_id=0
  8730. 'level' => 1, // 第一层级
  8731. 'product_name' => $script_name,
  8732. 'sort_order' => time() + $type,
  8733. 'is_deleted' => 0,
  8734. 'created_at' => $now,
  8735. 'updated_at' => $now
  8736. ]);
  8737. }
  8738. }
  8739. $folder_id = $typeFolderIds[$type];
  8740. // 获取表头(第一行)并查找关键列的位置
  8741. $headers = $content[0];
  8742. $nameColumnIndex = -1; // 资产名称列索引
  8743. $sequenceColumnIndex = -1; // 使用范围列索引
  8744. $promptColumnIndex = -1; // 参考提示词列索引
  8745. foreach ($headers as $index => $header) {
  8746. // 查找"资产名称"列
  8747. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8748. $nameColumnIndex = $index;
  8749. }
  8750. // 查找"使用范围"列
  8751. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8752. $sequenceColumnIndex = $index;
  8753. }
  8754. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  8755. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8756. $promptColumnIndex = $index;
  8757. }
  8758. }
  8759. // 验证必要的列是否都找到了
  8760. if ($nameColumnIndex === -1) {
  8761. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  8762. continue;
  8763. }
  8764. if ($sequenceColumnIndex === -1) {
  8765. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  8766. continue;
  8767. }
  8768. // 跳过表头,解析每一行数据
  8769. for ($i = 1; $i < count($content); $i++) {
  8770. $row = $content[$i];
  8771. // 确保行数据有效
  8772. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  8773. continue;
  8774. }
  8775. // 根据动态查找的列索引提取数据
  8776. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  8777. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  8778. $pic_prompt = '';
  8779. // 提取参考提示词(如果找到了该列)
  8780. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8781. $pic_prompt = trim($row[$promptColumnIndex]);
  8782. }
  8783. // 解析使用范围(逗号分隔的序号)
  8784. $sequences = [];
  8785. if (!empty($sequence_str)) {
  8786. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  8787. foreach ($sequenceParts as $part) {
  8788. if (is_numeric($part)) {
  8789. $sequences[] = (int)$part;
  8790. }
  8791. }
  8792. }
  8793. if (empty($product_name)) {
  8794. continue;
  8795. }
  8796. // 处理product_name两边的符号
  8797. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8798. // 如果名称不存在或仅剩占位符号,则跳过
  8799. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  8800. dLog('anime')->warning('资产名称无效,跳过保存', [
  8801. 'script_id' => $script_id,
  8802. 'type' => $type,
  8803. 'product_name' => $product_name
  8804. ]);
  8805. continue;
  8806. }
  8807. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  8808. $product_id = DB::table('mp_products')->insertGetId([
  8809. 'product_name' => $product_name,
  8810. 'type' => 1, // 1=资产 2.文件夹
  8811. 'product' => $type, // 1=角色, 2=场景, 3=道具
  8812. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  8813. 'level' => 2, // 第二层级
  8814. 'pic_prompt' => $pic_prompt,
  8815. 'user_id' => $uid,
  8816. 'cpid' => $cpid,
  8817. 'sort_order' => time(),
  8818. 'is_deleted' => 0,
  8819. 'created_at' => $now,
  8820. 'updated_at' => $now,
  8821. ]);
  8822. // 记录创建的资产ID
  8823. $createdProductIds[] = $product_id;
  8824. // 为每个序号创建映射记录
  8825. if (!empty($sequences)) {
  8826. foreach ($sequences as $sequence) {
  8827. $mappingRecords[] = [
  8828. 'script_id' => $script_id,
  8829. 'product_id' => $product_id,
  8830. 'episode_number' => $sequence,
  8831. 'created_at' => $now,
  8832. 'updated_at' => $now,
  8833. ];
  8834. }
  8835. } else {
  8836. // 如果没有指定序号,创建一个默认映射(序号为0)
  8837. $mappingRecords[] = [
  8838. 'script_id' => $script_id,
  8839. 'product_id' => $product_id,
  8840. 'episode_number' => 0,
  8841. 'created_at' => $now,
  8842. 'updated_at' => $now,
  8843. ];
  8844. }
  8845. }
  8846. }
  8847. if (empty($mappingRecords)) {
  8848. Utils::throwError('20003:没有有效的产品数据');
  8849. }
  8850. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  8851. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  8852. // 剧本已有资产,同步更新is_products标记
  8853. DB::table('mp_scripts')->where('id', $script_id)->update([
  8854. 'is_products' => 1,
  8855. 'updated_at' => $now
  8856. ]);
  8857. // 如果需要自动生成图片,在事务中创建图片生成任务
  8858. $productTaskMap = [];
  8859. if ($auto_generate_images && !empty($createdProductIds)) {
  8860. // 查询所有创建的资产
  8861. $productsToGenerate = DB::table('mp_products')
  8862. ->whereIn('id', $createdProductIds)
  8863. ->where('is_deleted', 0)
  8864. ->get();
  8865. foreach ($productsToGenerate as $product) {
  8866. if (empty($product->pic_prompt)) {
  8867. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8868. 'product_id' => $product->id,
  8869. 'product_name' => $product->product_name
  8870. ]);
  8871. continue;
  8872. }
  8873. try {
  8874. // 创建图片生成任务
  8875. $params = [
  8876. 'prompt' => $product->pic_prompt,
  8877. 'model' => $model,
  8878. 'ref_img_urls' => [],
  8879. 'width' => $width,
  8880. 'height' => $height,
  8881. // 计费锚点(剧本),用于积分明细归属统计
  8882. 'script_id' => $script_id,
  8883. ];
  8884. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8885. $task_id = $task->id;
  8886. if ($task_id) {
  8887. $productTaskMap[$product->id] = $task_id;
  8888. // 在事务中更新资产表的任务ID和状态
  8889. DB::table('mp_products')
  8890. ->where('id', $product->id)
  8891. ->update([
  8892. 'pic_task_id' => $task_id,
  8893. 'pic_task_status' => '生成中',
  8894. 'updated_at' => now()
  8895. ]);
  8896. dLog('anime')->info('创建资产图片生成任务', [
  8897. 'product_id' => $product->id,
  8898. 'task_id' => $task_id
  8899. ]);
  8900. }
  8901. } catch (\Exception $e) {
  8902. dLog('anime')->error('创建资产图片生成任务失败', [
  8903. 'product_id' => $product->id,
  8904. 'error' => $e->getMessage()
  8905. ]);
  8906. // 标记为失败(仍在事务中)
  8907. DB::table('mp_products')
  8908. ->where('id', $product->id)
  8909. ->update([
  8910. 'pic_task_status' => '生成失败',
  8911. 'updated_at' => now()
  8912. ]);
  8913. }
  8914. }
  8915. }
  8916. // 提交事务
  8917. DB::commit();
  8918. // 本次新增资产创建的图片任务
  8919. $createdTaskMap = $productTaskMap;
  8920. } catch (\Exception $e) {
  8921. // 回滚事务
  8922. DB::rollback();
  8923. // 更新任务中心状态为失败
  8924. if (!empty($taskCenterId)) {
  8925. $this->taskCenterService->updateTask($taskCenterId, [
  8926. 'status' => MpTaskCenter::STATUS_FAILED,
  8927. 'error_message' => $e->getMessage()
  8928. ]);
  8929. }
  8930. // 记录错误日志
  8931. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  8932. 'script_id' => $script_id,
  8933. 'error' => $e->getMessage(),
  8934. 'trace' => $e->getTraceAsString()
  8935. ]);
  8936. // 统一使用 Utils::throwError 抛出错误
  8937. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  8938. }
  8939. // 落库成功后统一处理图片任务:
  8940. // 1) 本次新增资产的图片任务已在上方事务中创建
  8941. // 2) 剧本内已存在但缺图的资产在此补建,并与新增资产的任务一并收集为待轮询任务
  8942. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  8943. $script_id,
  8944. $model,
  8945. $width,
  8946. $height,
  8947. $auto_generate_images
  8948. );
  8949. $productTaskMap = $existingTaskInfo['product_task_map'];
  8950. // 创建阶段解析到的类型根文件夹优先
  8951. $typeFolderIds = $typeFolderIds + $existingTaskInfo['type_folder_ids'];
  8952. // 保存结果(SSE 的 init / complete 事件会携带该结构)
  8953. $resultData = [
  8954. 'success' => true,
  8955. 'message' => '保存完成',
  8956. 'script_id' => $script_id,
  8957. 'script_name' => $script_name,
  8958. 'type_folder_ids' => $typeFolderIds,
  8959. 'inserted_count' => $insertedCount,
  8960. 'total_records' => count($mappingRecords),
  8961. 'created_products' => count($createdProductIds),
  8962. 'pending_tasks_count' => count($productTaskMap),
  8963. 'image_tasks_created' => count($createdTaskMap) + $existingTaskInfo['created_count'],
  8964. 'task_center_id' => $taskCenterId,
  8965. ];
  8966. // 有待完成的图片任务:返回 SSE 轮询流(事务外轮询)
  8967. if ($auto_generate_images && !empty($productTaskMap)) {
  8968. return $this->pollProductImageTasks(
  8969. $script_id,
  8970. $script_name,
  8971. $productTaskMap,
  8972. $typeFolderIds,
  8973. $taskCenterId,
  8974. ['import_result' => $resultData],
  8975. ['import_result' => $resultData]
  8976. );
  8977. }
  8978. // 没有需要轮询的任务:通过 SSE complete 事件返回保存结果
  8979. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  8980. }
  8981. /**
  8982. * 根据入参创建或复用任务中心记录
  8983. *
  8984. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  8985. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  8986. * 避免生成重复任务。
  8987. *
  8988. * @param int|string $uid
  8989. * @param int|string $cpid
  8990. * @param int|string $script_id
  8991. * @param mixed $products
  8992. * @param string $model
  8993. * @param string $ratio
  8994. * @param string $resolution
  8995. * @param mixed $auto_generate_images
  8996. * @return int 任务中心ID
  8997. */
  8998. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  8999. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  9000. if (is_string($products)) {
  9001. $decoded = json_decode($products, true);
  9002. if (json_last_error() === JSON_ERROR_NONE) {
  9003. $products = $decoded;
  9004. }
  9005. }
  9006. $params = [
  9007. 'script_id' => (int)$script_id,
  9008. 'products' => $products,
  9009. 'model' => $model,
  9010. 'ratio' => $ratio,
  9011. 'resolution' => $resolution,
  9012. 'auto_generate_images' => (bool)$auto_generate_images,
  9013. ];
  9014. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  9015. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  9016. $existing = DB::table('mp_task_center')
  9017. ->where('uid', (int)$uid)
  9018. ->where('cpid', (int)$cpid)
  9019. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9020. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  9021. ->where('params_md5', $paramsMd5)
  9022. ->orderBy('id', 'desc')
  9023. ->first();
  9024. if ($existing) {
  9025. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  9026. 'script_id' => $script_id,
  9027. 'task_center_id' => $existing->id,
  9028. 'params_md5' => $paramsMd5,
  9029. ]);
  9030. return (int)$existing->id;
  9031. }
  9032. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  9033. $now = date('Y-m-d H:i:s');
  9034. DB::table('mp_task_center')->insertOrIgnore([
  9035. 'uid' => (int)$uid,
  9036. 'cpid' => (int)$cpid,
  9037. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  9038. 'title' => '剧本资产图片生成',
  9039. 'ref_task_id' => 0,
  9040. 'status' => MpTaskCenter::STATUS_PROCESSING,
  9041. 'result' => null,
  9042. 'error_message' => null,
  9043. 'prompt' => null,
  9044. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  9045. 'params_md5' => $paramsMd5,
  9046. 'created_at' => $now,
  9047. 'updated_at' => $now,
  9048. ]);
  9049. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  9050. $taskId = (int)DB::table('mp_task_center')
  9051. ->where('uid', (int)$uid)
  9052. ->where('cpid', (int)$cpid)
  9053. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9054. ->where('params_md5', $paramsMd5)
  9055. ->orderBy('id', 'desc')
  9056. ->value('id');
  9057. dLog('anime')->info('创建任务中心记录', [
  9058. 'script_id' => $script_id,
  9059. 'task_center_id' => $taskId,
  9060. 'params_md5' => $paramsMd5,
  9061. ]);
  9062. return $taskId;
  9063. }
  9064. /**
  9065. * 任务结束时更新任务中心记录的状态和结果
  9066. *
  9067. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  9068. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  9069. *
  9070. * @param int|null $taskCenterId
  9071. * @param array $resultData 接口返回结果数组
  9072. * @param bool $timeout 是否超时未完成
  9073. */
  9074. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  9075. if (!$taskCenterId) {
  9076. return;
  9077. }
  9078. $stats = $resultData['stats'] ?? [];
  9079. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  9080. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  9081. $failedCount = $completedCount - $successCount;
  9082. // 与接口返回给客户端的结果保持一致
  9083. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  9084. if ($timeout) {
  9085. $this->taskCenterService->updateTask((int)$taskCenterId, [
  9086. 'status' => MpTaskCenter::STATUS_FAILED,
  9087. 'result' => $result,
  9088. 'error_message' => '部分任务超时,请稍后查看结果',
  9089. ]);
  9090. return;
  9091. }
  9092. $this->taskCenterService->updateTask((int)$taskCenterId, [
  9093. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  9094. 'result' => $result,
  9095. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  9096. ]);
  9097. }
  9098. /**
  9099. * 批量为剧本资产生成图片
  9100. *
  9101. * @param array $data 请求参数
  9102. * @return \Generator 返回 SSE 流
  9103. */
  9104. public function batchGenerateProductImages($data) {
  9105. $script_id = getProp($data, 'script_id');
  9106. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  9107. if (!$script_id) {
  9108. Utils::throwError('20003:请提供剧本ID');
  9109. }
  9110. // 验证剧本是否存在
  9111. $script = DB::table('mp_scripts')
  9112. ->where('id', $script_id)
  9113. ->where('is_deleted', 0)
  9114. ->first();
  9115. if (!$script) {
  9116. Utils::throwError('20003:剧本不存在');
  9117. }
  9118. $script_name = $script->script_name ?? 'script_' . $script_id;
  9119. // 获取需要生成图片的所有资产
  9120. $products = DB::table('mp_products')
  9121. ->whereIn('parent_id', array_values($type_folder_ids))
  9122. ->where('is_deleted', 0)
  9123. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  9124. ->get();
  9125. if ($products->isEmpty()) {
  9126. Utils::throwError('20003:没有找到需要生成图片的资产');
  9127. }
  9128. // 默认参数
  9129. $model = 'gpt-image-2';
  9130. $width = 1600;
  9131. $height = 2848;
  9132. // 开始为每个资产创建图片生成任务
  9133. $taskIds = [];
  9134. $productTaskMap = []; // 资产ID到任务ID的映射
  9135. foreach ($products as $product) {
  9136. if (empty($product->pic_prompt)) {
  9137. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  9138. continue;
  9139. }
  9140. try {
  9141. // 创建图片生成任务
  9142. $params = [
  9143. 'prompt' => $product->pic_prompt,
  9144. 'model' => $model,
  9145. 'ref_img_urls' => [],
  9146. 'width' => $width,
  9147. 'height' => $height,
  9148. // 计费锚点(剧本),用于积分明细归属统计
  9149. 'script_id' => $script_id,
  9150. ];
  9151. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9152. $task_id = $task->id;
  9153. if ($task_id) {
  9154. $taskIds[] = $task_id;
  9155. $productTaskMap[$product->id] = $task_id;
  9156. // 更新资产表的任务ID和状态
  9157. DB::table('mp_products')
  9158. ->where('id', $product->id)
  9159. ->update([
  9160. 'pic_task_id' => $task_id,
  9161. 'pic_task_status' => '生成中',
  9162. 'updated_at' => now()
  9163. ]);
  9164. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  9165. }
  9166. } catch (\Exception $e) {
  9167. dLog('anime')->error('创建资产图片生成任务失败', [
  9168. 'product_id' => $product->id,
  9169. 'error' => $e->getMessage()
  9170. ]);
  9171. // 标记为失败
  9172. DB::table('mp_products')
  9173. ->where('id', $product->id)
  9174. ->update([
  9175. 'pic_task_status' => '生成失败',
  9176. 'updated_at' => now()
  9177. ]);
  9178. }
  9179. }
  9180. if (empty($taskIds)) {
  9181. Utils::throwError('20003:没有成功创建任何图片生成任务');
  9182. }
  9183. // 返回 SSE 流
  9184. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  9185. }
  9186. /**
  9187. * 无需轮询时的 SSE 返回:直接通过 complete 事件返回导入结果
  9188. *
  9189. * @param int $script_id
  9190. * @param string $script_name
  9191. * @param array $resultData 导入结果(原普通 JSON 的 data 内容)
  9192. * @param array $type_folder_ids
  9193. * @param int|null $taskCenterId
  9194. * @return \Generator
  9195. */
  9196. private function streamImportComplete($script_id, $script_name, array $resultData, $type_folder_ids, $taskCenterId = null) {
  9197. if ($taskCenterId) {
  9198. $initResponse = [
  9199. 'type' => 'init',
  9200. 'script_id' => $script_id,
  9201. 'script_name' => $script_name,
  9202. 'timestamp' => date('Y-m-d H:i:s'),
  9203. 'task_center_id' => (int)$taskCenterId,
  9204. 'import_result' => $resultData,
  9205. ];
  9206. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9207. }
  9208. $stats = $this->collectScriptProductStats($script_id);
  9209. $response = [
  9210. 'type' => 'complete',
  9211. 'script_id' => $script_id,
  9212. 'script_name' => $script_name,
  9213. 'stats' => $stats,
  9214. 'timestamp' => date('Y-m-d H:i:s'),
  9215. 'import_result' => $resultData,
  9216. ];
  9217. if ($taskCenterId) {
  9218. $response['task_center_id'] = (int)$taskCenterId;
  9219. }
  9220. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9221. // 更新任务中心状态和结果
  9222. $this->finishScriptProductTask($taskCenterId, $response);
  9223. }
  9224. /**
  9225. * 统计剧本资产的图片生成状态(仅按 mp_products 当前状态统计,不驱动任务)
  9226. *
  9227. * @param int $script_id
  9228. * @return array
  9229. */
  9230. private function collectScriptProductStats($script_id) {
  9231. $stats = [
  9232. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9233. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9234. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9235. ];
  9236. $typeNames = [1 => 'roles', 2 => 'scenes', 3 => 'props'];
  9237. $productIds = DB::table('mp_script_product_mappings')
  9238. ->where('script_id', $script_id)
  9239. ->pluck('product_id')
  9240. ->unique()
  9241. ->toArray();
  9242. if (empty($productIds)) {
  9243. return [];
  9244. }
  9245. $products = DB::table('mp_products')
  9246. ->whereIn('id', $productIds)
  9247. ->where('is_deleted', 0)
  9248. ->get();
  9249. foreach ($products as $product) {
  9250. $typeName = $typeNames[$product->product] ?? 'unknown';
  9251. if (!isset($stats[$typeName])) {
  9252. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9253. }
  9254. $stats[$typeName]['total']++;
  9255. if ($product->pic_task_status === '生成成功') {
  9256. $stats[$typeName]['success']++;
  9257. $stats[$typeName]['completed']++;
  9258. } elseif ($product->pic_task_status === '生成失败') {
  9259. $stats[$typeName]['completed']++;
  9260. }
  9261. }
  9262. foreach ($stats as $typeName => $stat) {
  9263. if ($stat['total'] === 0) {
  9264. unset($stats[$typeName]);
  9265. }
  9266. }
  9267. return $stats;
  9268. }
  9269. /**
  9270. * 轮询资产图片生成任务状态(SSE流式返回)
  9271. * 只通过查询数据库获取任务状态,不主动调用API
  9272. *
  9273. * @param int $script_id 剧本ID
  9274. * @param string $script_name 剧本名称
  9275. * @param array $productTaskMap 资产ID到任务ID的映射
  9276. * @param array $type_folder_ids 类型文件夹ID映射
  9277. * @param int|null $taskCenterId 任务中心ID
  9278. * @param array $initExtra 追加到 init 事件中的额外数据
  9279. * @param array $completeExtra 追加到 complete、timeout 事件中的额外数据
  9280. * @return \Generator
  9281. */
  9282. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null, array $initExtra = [], array $completeExtra = []) {
  9283. $startTime = time();
  9284. $timeout = 1800; // 30分钟超时
  9285. $pollInterval = 10; // 10秒轮询一次
  9286. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  9287. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  9288. if ($taskCenterId) {
  9289. $initResponse = array_merge([
  9290. 'type' => 'init',
  9291. 'script_id' => $script_id,
  9292. 'script_name' => $script_name,
  9293. 'timestamp' => date('Y-m-d H:i:s'),
  9294. 'task_center_id' => (int)$taskCenterId,
  9295. ], $initExtra);
  9296. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9297. }
  9298. // 定义类型名称映射
  9299. $typeNames = [
  9300. 1 => 'roles', // 角色
  9301. 2 => 'scenes', // 场景
  9302. 3 => 'props' // 道具
  9303. ];
  9304. while (time() - $startTime < $timeout) {
  9305. sleep($pollInterval);
  9306. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  9307. $mappings = DB::table('mp_script_product_mappings')
  9308. ->where('script_id', $script_id)
  9309. ->pluck('product_id')
  9310. ->unique()
  9311. ->toArray();
  9312. if (empty($mappings)) {
  9313. dLog('anime')->warning('该剧本没有关联的资产', [
  9314. 'script_id' => $script_id,
  9315. 'script_name' => $script_name
  9316. ]);
  9317. break;
  9318. }
  9319. // 查询所有资产的当前状态
  9320. $products = DB::table('mp_products')
  9321. ->whereIn('id', $mappings)
  9322. ->where('is_deleted', 0)
  9323. ->get();
  9324. // 统计各类型的状态(使用类型名称作为键名)
  9325. $stats = [
  9326. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  9327. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  9328. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  9329. ];
  9330. $allCompleted = true;
  9331. $hasStatusChange = false;
  9332. foreach ($products as $product) {
  9333. $type = $product->product;
  9334. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  9335. // 如果类型名称不在 stats 中,初始化
  9336. if (!isset($stats[$typeName])) {
  9337. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9338. }
  9339. $stats[$typeName]['total']++;
  9340. $task_id = $product->pic_task_id;
  9341. $currentStatus = $product->pic_task_status;
  9342. // 检查状态是否有变化
  9343. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  9344. $hasStatusChange = true;
  9345. $lastStatus[$product->id] = $currentStatus;
  9346. }
  9347. // 如果是生成中,查询任务表状态
  9348. if ($currentStatus === '生成中' && $task_id) {
  9349. // 只查询数据库,不调用API
  9350. $task = DB::table('mp_generate_pic_tasks')
  9351. ->where('id', $task_id)
  9352. ->first();
  9353. if ($task) {
  9354. // 检查任务状态
  9355. if ($task->status === 'success' && $task->result_url) {
  9356. // 解析图片URL
  9357. $result_urls = $task->result_url;
  9358. if (is_string($result_urls)) {
  9359. $result_urls = json_decode($result_urls, true);
  9360. }
  9361. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  9362. // 更新资产表状态
  9363. DB::table('mp_products')
  9364. ->where('id', $product->id)
  9365. ->update([
  9366. 'pic_task_status' => '生成成功',
  9367. 'url' => $img_url,
  9368. 'updated_at' => now()
  9369. ]);
  9370. $stats[$typeName]['success']++;
  9371. $stats[$typeName]['completed']++;
  9372. $hasStatusChange = true;
  9373. dLog('anime')->info('资产图片生成成功', [
  9374. 'product_id' => $product->id,
  9375. 'task_id' => $task_id,
  9376. 'img_url' => $img_url
  9377. ]);
  9378. } elseif ($task->status === 'failed') {
  9379. // 更新资产表状态
  9380. DB::table('mp_products')
  9381. ->where('id', $product->id)
  9382. ->update([
  9383. 'pic_task_status' => '生成失败',
  9384. 'updated_at' => now()
  9385. ]);
  9386. $stats[$typeName]['completed']++;
  9387. $hasStatusChange = true;
  9388. dLog('anime')->warning('资产图片生成失败', [
  9389. 'product_id' => $product->id,
  9390. 'task_id' => $task_id,
  9391. 'error' => $task->error_message ?? '未知错误'
  9392. ]);
  9393. } else {
  9394. // 任务还在处理中
  9395. $allCompleted = false;
  9396. }
  9397. } else {
  9398. // 任务不存在,标记为失败
  9399. DB::table('mp_products')
  9400. ->where('id', $product->id)
  9401. ->update([
  9402. 'pic_task_status' => '生成失败',
  9403. 'updated_at' => now()
  9404. ]);
  9405. $stats[$typeName]['completed']++;
  9406. $hasStatusChange = true;
  9407. dLog('anime')->error('图片生成任务不存在', [
  9408. 'product_id' => $product->id,
  9409. 'task_id' => $task_id
  9410. ]);
  9411. }
  9412. } elseif ($currentStatus === '生成成功') {
  9413. $stats[$typeName]['success']++;
  9414. $stats[$typeName]['completed']++;
  9415. } elseif ($currentStatus === '生成失败') {
  9416. $stats[$typeName]['completed']++;
  9417. } else {
  9418. // 其他状态也认为未完成
  9419. $allCompleted = false;
  9420. }
  9421. }
  9422. // 移除没有数据的类型(total=0)
  9423. foreach ($stats as $typeName => $stat) {
  9424. if ($stat['total'] === 0) {
  9425. unset($stats[$typeName]);
  9426. }
  9427. }
  9428. // 如果有状态变化,发送 SSE 更新
  9429. if ($hasStatusChange) {
  9430. $eventType = $allCompleted ? 'complete' : 'update';
  9431. $response = [
  9432. 'type' => $eventType,
  9433. 'script_id' => $script_id,
  9434. 'script_name' => $script_name,
  9435. 'stats' => $stats,
  9436. 'timestamp' => date('Y-m-d H:i:s')
  9437. ];
  9438. if ($taskCenterId) {
  9439. $response['task_center_id'] = $taskCenterId;
  9440. }
  9441. if ($eventType === 'complete') {
  9442. $response = array_merge($response, $completeExtra);
  9443. }
  9444. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9445. dLog('anime')->info('SSE更新', [
  9446. 'event_type' => $eventType,
  9447. 'script_id' => $script_id,
  9448. 'script_name' => $script_name,
  9449. 'stats' => $stats
  9450. ]);
  9451. if ($allCompleted) {
  9452. dLog('anime')->info('所有资产图片生成任务已完成', [
  9453. 'script_id' => $script_id,
  9454. 'script_name' => $script_name,
  9455. 'stats' => $stats
  9456. ]);
  9457. // 全部任务完成,更新任务中心状态和结果
  9458. $this->finishScriptProductTask($taskCenterId, $response);
  9459. break;
  9460. }
  9461. }
  9462. }
  9463. // 超时处理
  9464. if (time() - $startTime >= $timeout && !$allCompleted) {
  9465. $response = [
  9466. 'type' => 'timeout',
  9467. 'message' => '部分任务超时,请稍后查看结果',
  9468. 'script_id' => $script_id,
  9469. 'script_name' => $script_name,
  9470. 'timestamp' => date('Y-m-d H:i:s')
  9471. ];
  9472. if ($taskCenterId) {
  9473. $response['task_center_id'] = $taskCenterId;
  9474. }
  9475. $response = array_merge($response, $completeExtra);
  9476. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9477. dLog('anime')->warning('资产图片生成任务超时', [
  9478. 'script_id' => $script_id,
  9479. 'script_name' => $script_name,
  9480. 'timeout' => $timeout
  9481. ]);
  9482. // 超时未完成,更新任务中心状态和结果
  9483. $this->finishScriptProductTask($taskCenterId, $response, true);
  9484. }
  9485. }
  9486. /**
  9487. * 定时任务:检查产品图片生成任务状态并更新产品记录
  9488. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  9489. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  9490. *
  9491. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  9492. */
  9493. public function checkProductPicTasks() {
  9494. // 查询所有生成中的产品图片任务
  9495. $products = DB::table('mp_products')
  9496. ->whereNotNull('pic_task_id')
  9497. ->where('pic_task_status', '生成中')
  9498. ->where('is_deleted', 0)
  9499. ->get();
  9500. $stats = [
  9501. 'total' => $products->count(),
  9502. 'success' => 0,
  9503. 'failed' => 0,
  9504. 'pending' => 0,
  9505. ];
  9506. foreach ($products as $product) {
  9507. try {
  9508. $task_id = $product->pic_task_id;
  9509. // 通过 pic_task_id 查询图片生成任务结果
  9510. $task = DB::table('mp_generate_pic_tasks')
  9511. ->where('id', $task_id)
  9512. ->first();
  9513. if ($task) {
  9514. if ($task->status === 'success' && $task->result_url) {
  9515. // 解析图片URL
  9516. $result_urls = $task->result_url;
  9517. if (is_string($result_urls)) {
  9518. $result_urls = json_decode($result_urls, true);
  9519. }
  9520. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  9521. // 更新资产表状态
  9522. DB::table('mp_products')
  9523. ->where('id', $product->id)
  9524. ->update([
  9525. 'pic_task_status' => '生成成功',
  9526. 'url' => $img_url,
  9527. 'updated_at' => now()
  9528. ]);
  9529. $stats['success']++;
  9530. dLog('anime')->info('资产图片生成成功', [
  9531. 'product_id' => $product->id,
  9532. 'task_id' => $task_id,
  9533. 'img_url' => $img_url
  9534. ]);
  9535. } elseif ($task->status === 'failed') {
  9536. // 更新资产表状态
  9537. DB::table('mp_products')
  9538. ->where('id', $product->id)
  9539. ->update([
  9540. 'pic_task_status' => '生成失败',
  9541. 'updated_at' => now()
  9542. ]);
  9543. $stats['failed']++;
  9544. dLog('anime')->warning('资产图片生成失败', [
  9545. 'product_id' => $product->id,
  9546. 'task_id' => $task_id,
  9547. 'error' => $task->error_message ?? '未知错误'
  9548. ]);
  9549. } else {
  9550. // 任务还在处理中
  9551. $stats['pending']++;
  9552. }
  9553. } else {
  9554. // 任务不存在,标记为失败
  9555. DB::table('mp_products')
  9556. ->where('id', $product->id)
  9557. ->update([
  9558. 'pic_task_status' => '生成失败',
  9559. 'updated_at' => now()
  9560. ]);
  9561. $stats['failed']++;
  9562. dLog('anime')->error('图片生成任务不存在', [
  9563. 'product_id' => $product->id,
  9564. 'task_id' => $task_id
  9565. ]);
  9566. }
  9567. } catch (\Exception $e) {
  9568. dLog('anime')->error('检查产品图片生成任务异常', [
  9569. 'product_id' => $product->id,
  9570. 'task_id' => $product->pic_task_id ?? null,
  9571. 'error' => $e->getMessage()
  9572. ]);
  9573. }
  9574. }
  9575. return $stats;
  9576. }
  9577. /**
  9578. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  9579. *
  9580. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  9581. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  9582. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  9583. *
  9584. * @return int 更新的任务中心记录数
  9585. */
  9586. public function checkSaveScriptProductTaskCenters() {
  9587. $updated = 0;
  9588. // 只扫描尚未结束的 saveScriptProducts 任务
  9589. $tasks = DB::table('mp_task_center')
  9590. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9591. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  9592. ->orderBy('id', 'desc')
  9593. ->limit(500)
  9594. ->get();
  9595. // 与 pollProductImageTasks 保持一致的类型名称映射
  9596. $typeNames = [
  9597. 1 => 'roles', // 角色
  9598. 2 => 'scenes', // 场景
  9599. 3 => 'props', // 道具
  9600. ];
  9601. foreach ($tasks as $task) {
  9602. try {
  9603. $taskParams = json_decode((string)$task->params, true);
  9604. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  9605. if (!$script_id) {
  9606. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  9607. 'task_center_id' => $task->id,
  9608. ]);
  9609. continue;
  9610. }
  9611. // 获取该剧本关联的全部资产ID
  9612. $productIds = DB::table('mp_script_product_mappings')
  9613. ->where('script_id', $script_id)
  9614. ->pluck('product_id')
  9615. ->unique()
  9616. ->toArray();
  9617. if (empty($productIds)) {
  9618. // 剧本没有关联资产,不视为完成,等待下一次检查
  9619. continue;
  9620. }
  9621. $products = DB::table('mp_products')
  9622. ->whereIn('id', $productIds)
  9623. ->where('is_deleted', 0)
  9624. ->get();
  9625. $stats = [];
  9626. $allCompleted = true;
  9627. foreach ($products as $product) {
  9628. $typeName = $typeNames[$product->product] ?? 'unknown';
  9629. if (!isset($stats[$typeName])) {
  9630. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9631. }
  9632. $stats[$typeName]['total']++;
  9633. if ($product->pic_task_status === '生成成功') {
  9634. $stats[$typeName]['success']++;
  9635. $stats[$typeName]['completed']++;
  9636. } elseif ($product->pic_task_status === '生成失败') {
  9637. $stats[$typeName]['completed']++;
  9638. } else {
  9639. // 仍有资产在生成中或未生成,任务未完成
  9640. $allCompleted = false;
  9641. }
  9642. }
  9643. if (!$allCompleted) {
  9644. continue;
  9645. }
  9646. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  9647. $script = DB::table('mp_scripts')
  9648. ->where('id', $script_id)
  9649. ->where('is_deleted', 0)
  9650. ->first();
  9651. $script_name = $script->script_name ?? 'script_' . $script_id;
  9652. $this->finishScriptProductTask($task->id, [
  9653. 'type' => 'complete',
  9654. 'script_id' => $script_id,
  9655. 'script_name' => $script_name,
  9656. 'stats' => $stats,
  9657. 'timestamp' => date('Y-m-d H:i:s'),
  9658. 'task_center_id' => (int)$task->id,
  9659. ]);
  9660. $updated++;
  9661. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  9662. 'task_center_id' => $task->id,
  9663. 'script_id' => $script_id,
  9664. 'stats' => $stats,
  9665. ]);
  9666. } catch (\Exception $e) {
  9667. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  9668. 'task_center_id' => $task->id,
  9669. 'error' => $e->getMessage(),
  9670. ]);
  9671. }
  9672. }
  9673. return $updated;
  9674. }
  9675. /**
  9676. * 获取剧本关联的资产列表
  9677. * @param array $data 请求参数
  9678. * @return array
  9679. */
  9680. public function getScriptProducts($data) {
  9681. $uid = Site::getUid();
  9682. $cpid = Site::getCpid();
  9683. $script_id = getProp($data, 'script_id');
  9684. $episode_number = getProp($data, 'episode_number');
  9685. if (!$script_id) {
  9686. Utils::throwError('20003:请提供剧本ID');
  9687. }
  9688. // 验证剧本是否存在
  9689. $script = DB::table('mp_scripts')
  9690. ->where('id', $script_id)
  9691. ->where('is_deleted', 0)
  9692. ->first();
  9693. if (!$script) {
  9694. Utils::throwError('20003:剧本不存在');
  9695. }
  9696. // 联表查询资产信息
  9697. $query = DB::table('mp_script_product_mappings as mapping')
  9698. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9699. ->where('mapping.script_id', $script_id)
  9700. ->where('product.cpid', $cpid)
  9701. ->where('product.is_deleted', 0);
  9702. // 如果提供了 episode_number,则过滤指定集数
  9703. if ($episode_number !== null && $episode_number !== '') {
  9704. $query->where('mapping.episode_number', $episode_number);
  9705. }
  9706. $mappings = $query->select(
  9707. 'mapping.script_id',
  9708. 'mapping.product_id',
  9709. 'mapping.episode_number',
  9710. 'product.product_name',
  9711. 'product.type',
  9712. 'product.product',
  9713. 'product.pic_prompt',
  9714. 'product.url',
  9715. 'product.pic_task_id',
  9716. 'product.pic_task_status',
  9717. 'product.three_view_image_url',
  9718. 'product.timbre_url',
  9719. 'mapping.created_at'
  9720. )
  9721. ->orderBy('mapping.product_id', 'asc')
  9722. ->orderBy('mapping.episode_number', 'asc')
  9723. ->get();
  9724. // 按 product_id 分组,合并 episode_number
  9725. $productMap = [];
  9726. foreach ($mappings as $item) {
  9727. $product_id = $item->product_id;
  9728. if (!isset($productMap[$product_id])) {
  9729. $productMap[$product_id] = [
  9730. 'product_id' => $product_id,
  9731. 'product_name' => $item->product_name,
  9732. 'type' => (int)$item->type,
  9733. 'product' => (int)$item->product,
  9734. 'pic_prompt' => $item->pic_prompt,
  9735. 'url' => $item->url,
  9736. 'timbre_url' => $item->timbre_url,
  9737. 'pic_task_id' => $item->pic_task_id,
  9738. 'pic_task_status' => $item->pic_task_status,
  9739. 'episode_numbers' => [],
  9740. 'created_at' => $item->created_at,
  9741. ];
  9742. }
  9743. // 添加 episode_number(去重)
  9744. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  9745. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  9746. }
  9747. }
  9748. // 按类型分组
  9749. $roles = []; // type=1 角色/主体
  9750. $scenes = []; // type=2 场景
  9751. $props = []; // type=3 道具
  9752. foreach ($productMap as $product) {
  9753. // 将 episode_numbers 数组转换为逗号分隔的字符串
  9754. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  9755. // 构造返回数据
  9756. $productData = [
  9757. 'product_id' => $product['product_id'],
  9758. 'product_name' => $product['product_name'],
  9759. 'product' => $product['product'],
  9760. 'pic_prompt' => $product['pic_prompt'],
  9761. 'url' => $product['url'],
  9762. 'timbre_url' => $product['timbre_url'] ?? '',
  9763. 'pic_task_id' => $product['pic_task_id'],
  9764. 'pic_task_status' => $product['pic_task_status'],
  9765. 'episode_numbers' => $episodeNumbersStr,
  9766. 'created_at' => $product['created_at'],
  9767. ];
  9768. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  9769. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  9770. switch ($product['product']) {
  9771. case 1:
  9772. $roles[] = $productData;
  9773. break;
  9774. case 2:
  9775. $scenes[] = $productData;
  9776. break;
  9777. case 3:
  9778. $props[] = $productData;
  9779. break;
  9780. }
  9781. }
  9782. return [
  9783. 'script_id' => $script_id,
  9784. 'script_name' => $script->script_name ?? '',
  9785. 'roles' => $roles, // 主体
  9786. 'scenes' => $scenes, // 场景
  9787. 'props' => $props, // 道具
  9788. ];
  9789. }
  9790. /**
  9791. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  9792. * @param string $actContent 原始内容
  9793. * @param array $products 产品数组(包含product_name和url)
  9794. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  9795. */
  9796. /**
  9797. * 根据片段内容与资产构建提示词、参考图、参考音频
  9798. *
  9799. * @param string $actContent 片段内容
  9800. * @param array $products 资产数组(角色/场景/道具)
  9801. * @param bool $supportAudioReference 模型是否支持参考音频;支持时角色音色优先使用 timbre_url
  9802. * @return array
  9803. */
  9804. public function processActContentWithProducts($actContent, $products, $supportAudioReference = false, $allowedAudioProducts = null, $allowedImageProducts = null) {
  9805. if (empty($actContent) || empty($products)) {
  9806. return [
  9807. 'content' => $actContent,
  9808. 'reference_images' => [],
  9809. 'reference_images_all' => [],
  9810. 'reference_audios' => [],
  9811. 'audio_voice_fallbacks' => []
  9812. ];
  9813. }
  9814. // 构建产品名称到产品信息的映射
  9815. $product_dict = [];
  9816. foreach ($products as $product) {
  9817. $product_name = getProp($product, 'product_name');
  9818. if ($product_name) {
  9819. $product_dict[$product_name] = [
  9820. // 优先使用三视图图片作为素材/参考图,否则使用原图 url
  9821. 'url' => getProp($product, 'three_view_image_url') ?: getProp($product, 'url'),
  9822. 'voice_prompt' => getProp($product, 'voice_prompt'),
  9823. // 角色音色参考音频(选填),有值时优先于 voice_prompt
  9824. 'timbre_url' => trim((string)getProp($product, 'timbre_url', '')),
  9825. 'product' => (int)getProp($product, 'product', 1)
  9826. ];
  9827. }
  9828. }
  9829. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  9830. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  9831. $reference_images = [];
  9832. $reference_images_all = []; // 正文中出现且有图的资产图(不受模型上限影响,用于任务记录)
  9833. $product_index_map = []; // 产品名称 => 图片序号的映射
  9834. $reference_audios = [];
  9835. $product_audio_index_map = []; // 产品名称 => 音频序号的映射(与图片序号互相独立)
  9836. $audio_voice_fallbacks = []; // 产品名称 => voice_prompt(参考音频素材不可用时兜底使用)
  9837. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  9838. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  9839. $current_index = 1;
  9840. $current_audio_index = 1;
  9841. if (!empty($matches[1])) {
  9842. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  9843. $seen_products = []; // 用于去重
  9844. foreach ($matches[1] as $product_name) {
  9845. // 跳过已处理的产品
  9846. if (isset($seen_products[$product_name])) {
  9847. continue;
  9848. }
  9849. $seen_products[$product_name] = true;
  9850. // 检查产品是否在字典中
  9851. if (isset($product_dict[$product_name])) {
  9852. $url = $product_dict[$product_name]['url'];
  9853. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  9854. $timbre_url = $product_dict[$product_name]['timbre_url'];
  9855. // 判断该角色的参考音频是否可用(模型支持 + 配置了音色 + 未超出模型段数/时长限制)
  9856. $audio_allowed = $supportAudioReference && !empty($timbre_url);
  9857. if ($audio_allowed && is_array($allowedAudioProducts)) {
  9858. $audio_allowed = isset($allowedAudioProducts[$product_name])
  9859. && $allowedAudioProducts[$product_name] === $timbre_url;
  9860. }
  9861. // 分配音频序号(与图片序号互相独立;相同音频URL复用同一序号,保证角色与音频一一对应)
  9862. if ($audio_allowed) {
  9863. if (!in_array($timbre_url, $reference_audios)) {
  9864. $reference_audios[] = $timbre_url;
  9865. $product_audio_index_map[$product_name] = $current_audio_index;
  9866. $current_audio_index++;
  9867. } else {
  9868. $existing_audio_index = array_search($timbre_url, $reference_audios) + 1;
  9869. $product_audio_index_map[$product_name] = $existing_audio_index;
  9870. }
  9871. // 记录该角色的音色提示词:参考音频素材不可用时用它兜底(无提示词时记录空串,用于清理残留说明行)
  9872. $audio_voice_fallbacks[$product_name] = $voice_prompt ?? '';
  9873. }
  9874. // 处理voice_prompt:有可用参考音频的角色优先使用音频,不再输出音色提示词(旁白是公共的在后面单独处理)
  9875. if (!$audio_allowed && !empty($voice_prompt) && $product_name !== '旁白') {
  9876. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  9877. }
  9878. // 只有URL非空且未被模型参考图上限截断,才分配序号并加入参考图片
  9879. if (!empty($url)) {
  9880. // 任务记录用:正文中出现且有图的资产图全部记录(不受模型上限影响)
  9881. if (!in_array($url, $reference_images_all)) {
  9882. $reference_images_all[] = $url;
  9883. }
  9884. $image_allowed = true;
  9885. if (is_array($allowedImageProducts)) {
  9886. $image_allowed = isset($allowedImageProducts[$product_name])
  9887. && $allowedImageProducts[$product_name] === $url;
  9888. }
  9889. if (!$image_allowed) {
  9890. // 超出模型参考图上限的资产不分配序号,提示词中不会出现<图片N>
  9891. $product_index_map[$product_name] = 0;
  9892. } elseif (!in_array($url, $reference_images)) {
  9893. $reference_images[] = $url;
  9894. $product_index_map[$product_name] = $current_index;
  9895. $current_index++;
  9896. } else {
  9897. // URL重复,找到已有的序号
  9898. $existing_index = array_search($url, $reference_images) + 1;
  9899. $product_index_map[$product_name] = $existing_index;
  9900. }
  9901. } else {
  9902. // URL为空,不分配序号(后续直接去掉{})
  9903. $product_index_map[$product_name] = 0;
  9904. }
  9905. } else {
  9906. // 产品不在字典中,不分配序号
  9907. $product_index_map[$product_name] = 0;
  9908. }
  9909. }
  9910. }
  9911. // 第二步:替换内容中的 {产品名称}
  9912. $processedContent = $actContent;
  9913. foreach ($product_index_map as $product_name => $index) {
  9914. $escaped_name = preg_quote($product_name, '/');
  9915. if ($index > 0) {
  9916. // 有图片,替换为:产品名称<图片X>
  9917. $replacement = $product_name . '<图片' . $index . '>';
  9918. } else {
  9919. // 无图片,只保留产品名称
  9920. $replacement = $product_name;
  9921. }
  9922. // 有参考音频的角色追加音频标记(如 角色A<图片1><音频1>),保证角色与音频一一对应
  9923. $audio_index = $product_audio_index_map[$product_name] ?? 0;
  9924. if ($audio_index > 0) {
  9925. $replacement .= '<音频' . $audio_index . '>';
  9926. }
  9927. // 替换所有 {产品名称} 为处理后的格式
  9928. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  9929. }
  9930. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  9931. foreach ($products as $product) {
  9932. $product_name = getProp($product, 'product_name');
  9933. $voice_prompt = getProp($product, 'voice_prompt');
  9934. if ($product_name === '旁白' && !empty($voice_prompt) && empty($product_audio_index_map['旁白'])) {
  9935. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  9936. break; // 找到旁白后退出循环
  9937. }
  9938. }
  9939. // 第四步:将参考音频音色信息和voice_prompt信息添加到内容最前面
  9940. $voice_prompt_prefix = '';
  9941. // 有参考音频的角色:按官方推荐句式"参考<音频N>中的音色"声明对应关系,
  9942. // 素材上传失败时与正文标记一起被清理/重排,保证角色与音频始终对应
  9943. foreach ($product_audio_index_map as $product_name => $audio_index) {
  9944. $voice_prompt_prefix .= '参考<音频' . $audio_index . '>中的音色,为' . $product_name . '配音' . "\n";
  9945. }
  9946. if (!empty($voice_prompts)) {
  9947. $voice_prompt_prefix .= implode('', $voice_prompts);
  9948. }
  9949. // 旁白的voice_prompt放在最后
  9950. if (!empty($narrator_voice_prompt)) {
  9951. $voice_prompt_prefix .= $narrator_voice_prompt;
  9952. }
  9953. // 如果有voice_prompt信息,添加到内容开头
  9954. if (!empty($voice_prompt_prefix)) {
  9955. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  9956. }
  9957. return [
  9958. 'content' => $processedContent,
  9959. 'reference_images' => $reference_images,
  9960. 'reference_images_all' => $reference_images_all,
  9961. 'reference_audios' => $reference_audios,
  9962. 'audio_voice_fallbacks' => $audio_voice_fallbacks
  9963. ];
  9964. }
  9965. /**
  9966. * 用剧本资产关联(mappings)的数据补齐资产数组
  9967. * 批量转视频时资产取值的优先级:剧本资产关联(mappings) > extra_products > 剧集单独设置
  9968. * 资产库对应字段为空时不覆盖,避免把分集里的有效数据清空
  9969. *
  9970. * @param array $products 资产数组
  9971. * @param int $script_id 剧本ID
  9972. * @param bool $overwrite 资产库有值时是否覆盖数组中的已有值(true 表示 mappings 优先级最高)
  9973. * @return array
  9974. */
  9975. public function fillProductsFromMapping($products, $script_id, $overwrite = false) {
  9976. if (empty($products) || !$script_id) {
  9977. return $products;
  9978. }
  9979. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  9980. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9981. ->where('mapping.script_id', $script_id)
  9982. ->where('product.is_deleted', 0)
  9983. ->select(
  9984. 'mapping.product_id',
  9985. 'product.product_name',
  9986. 'product.product',
  9987. 'product.pic_prompt',
  9988. 'product.url',
  9989. 'product.three_view_image_url',
  9990. 'product.timbre_url'
  9991. )
  9992. ->get();
  9993. if ($mappingItems->isEmpty()) {
  9994. return $products;
  9995. }
  9996. $mappingMap = [];
  9997. foreach ($mappingItems as $item) {
  9998. $normalized_name = $this->normalizeProductName($item->product_name);
  9999. if ($normalized_name === '' || isset($mappingMap[$normalized_name])) {
  10000. continue;
  10001. }
  10002. // 资产库字段有值才纳入覆盖范围(三视图、音色等为选填,可能为空)
  10003. $mappingProduct = [];
  10004. if (!empty($item->product_id)) {
  10005. $mappingProduct['product_id'] = (int)$item->product_id;
  10006. }
  10007. if (!empty($item->product)) {
  10008. $mappingProduct['product'] = (int)$item->product;
  10009. }
  10010. if (!empty($item->pic_prompt)) {
  10011. $mappingProduct['pic_prompt'] = $item->pic_prompt;
  10012. }
  10013. if (!empty($item->url)) {
  10014. $mappingProduct['url'] = $item->url;
  10015. }
  10016. if (!empty($item->three_view_image_url)) {
  10017. $mappingProduct['three_view_image_url'] = $item->three_view_image_url;
  10018. }
  10019. if (!empty($item->timbre_url)) {
  10020. $mappingProduct['timbre_url'] = $item->timbre_url;
  10021. }
  10022. if (!empty($mappingProduct)) {
  10023. $mappingMap[$normalized_name] = $mappingProduct;
  10024. }
  10025. }
  10026. if (empty($mappingMap)) {
  10027. return $products;
  10028. }
  10029. foreach ($products as &$product) {
  10030. $normalized_name = $this->normalizeProductName(getProp($product, 'product_name'));
  10031. if ($normalized_name === '' || empty($mappingMap[$normalized_name])) {
  10032. continue;
  10033. }
  10034. foreach ($mappingMap[$normalized_name] as $key => $value) {
  10035. // 不覆盖模式:只补齐数组中缺失的字段
  10036. if (!$overwrite && !empty(getProp($product, $key))) {
  10037. continue;
  10038. }
  10039. $product[$key] = $value;
  10040. }
  10041. }
  10042. unset($product);
  10043. return $products;
  10044. }
  10045. /**
  10046. * 资产名称归一化(去掉首尾空白、方括号、花括号等符号)
  10047. *
  10048. * @param string $name
  10049. * @return string
  10050. */
  10051. private function normalizeProductName($name) {
  10052. return trim(preg_replace(
  10053. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  10054. '',
  10055. trim((string)$name)
  10056. ));
  10057. }
  10058. /**
  10059. * 是否启用参考音频(角色音色)
  10060. * 优先取调用方传入的 enable_reference_audio,未传时读取环境变量 ENABLE_REFERENCE_AUDIO,默认开启
  10061. *
  10062. * @param array $data 调用方入参
  10063. * @return bool
  10064. */
  10065. public function isReferenceAudioEnabled($data) {
  10066. // 环境变量兜底:兼容 true/false/1/0/on/off/yes/no 等写法,无法识别时按默认开启
  10067. $envValue = env('ENABLE_REFERENCE_AUDIO', true);
  10068. $envDefault = is_bool($envValue)
  10069. ? $envValue
  10070. : filter_var($envValue, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
  10071. if ($envDefault === null) {
  10072. $envDefault = true;
  10073. }
  10074. $value = getProp($data, 'enable_reference_audio', null);
  10075. if ($value === null || $value === '') {
  10076. return $envDefault;
  10077. }
  10078. $bool = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
  10079. return $bool === null ? $envDefault : $bool;
  10080. }
  10081. /**
  10082. * 判断视频模型是否支持角色参考音频(音色)
  10083. * 目前支持:智帧统一API、Seedance 2.0 系列(国内百度/海外百度/快快AI)
  10084. *
  10085. * @param string $model
  10086. * @return bool
  10087. */
  10088. public function isActReferenceAudioSupported($model) {
  10089. if (!$model) {
  10090. return false;
  10091. }
  10092. return strpos($model, 'zhizhen') !== false || $this->isSeedance20SeriesModel($model);
  10093. }
  10094. /**
  10095. * 获取模型对参考图片的数量上限
  10096. * Seedance 2.0(含 2.0 mini/fast)与智帧:9 张;Seedance 2.5:30 张
  10097. *
  10098. * @param string $model
  10099. * @return int 0 表示该模型不走参考图逻辑(不做限制)
  10100. */
  10101. public function getActReferenceImageLimit($model) {
  10102. if (!$this->isActReferenceAudioSupported($model)) {
  10103. return 0;
  10104. }
  10105. if (strpos($model, '2.5') !== false || strpos($model, '2-5') !== false) {
  10106. return 30;
  10107. }
  10108. return 9;
  10109. }
  10110. /**
  10111. * 生成提示词之前解析可用的资产参考图
  10112. * 按正文中{资产名}首次出现的顺序取有图片的资产(相同图片URL复用同一编号);
  10113. * 超过模型上限的资产不分配图片编号,提示词中也不会出现<图片N>引用
  10114. * 调用方显式传入的 reference_images 不占用这里的额度,由调用方按剩余额度补充
  10115. *
  10116. * @param string $actContent 片段内容
  10117. * @param array $products 资产数组
  10118. * @param string $model 视频模型
  10119. * @return array ['allowed' => [产品名 => 图片URL], 'excluded' => [产品名 => 原因], 'limit' => 上限]
  10120. */
  10121. public function resolveActReferenceImages($actContent, $products, $model) {
  10122. $result = ['allowed' => [], 'excluded' => [], 'limit' => 0];
  10123. $limit = $this->getActReferenceImageLimit($model);
  10124. if ($limit <= 0 || empty($actContent) || empty($products)) {
  10125. return $result;
  10126. }
  10127. $result['limit'] = $limit;
  10128. // 产品名 => 图片(优先三视图,其次原图)
  10129. $imageMap = [];
  10130. foreach ($products as $product) {
  10131. $name = getProp($product, 'product_name');
  10132. if (!$name) {
  10133. continue;
  10134. }
  10135. $url = trim((string)(getProp($product, 'three_view_image_url') ?: getProp($product, 'url')));
  10136. if ($url !== '') {
  10137. $imageMap[$name] = $url;
  10138. }
  10139. }
  10140. if (empty($imageMap)) {
  10141. return $result;
  10142. }
  10143. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  10144. $orderedNames = [];
  10145. foreach (($matches[1] ?? []) as $name) {
  10146. if (!isset($orderedNames[$name])) {
  10147. $orderedNames[$name] = true;
  10148. }
  10149. }
  10150. $usedUrls = [];
  10151. foreach (array_keys($orderedNames) as $name) {
  10152. $url = $imageMap[$name] ?? '';
  10153. if ($url === '') {
  10154. continue;
  10155. }
  10156. // 相同图片复用同一编号,不重复计数
  10157. if (isset($usedUrls[$url])) {
  10158. $result['allowed'][$name] = $url;
  10159. continue;
  10160. }
  10161. if (count($usedUrls) >= $limit) {
  10162. $result['excluded'][$name] = '超过参考图数量上限(' . $limit . '张)';
  10163. continue;
  10164. }
  10165. $usedUrls[$url] = true;
  10166. $result['allowed'][$name] = $url;
  10167. }
  10168. if (!empty($result['excluded'])) {
  10169. dLog('anime')->info('资产参考图超出模型限制,已截断', [
  10170. 'model' => $model,
  10171. 'limit' => $limit,
  10172. 'allowed' => array_keys($result['allowed']),
  10173. 'excluded' => $result['excluded'],
  10174. ]);
  10175. }
  10176. return $result;
  10177. }
  10178. /**
  10179. * 获取模型对参考音频的限制
  10180. * Seedance 2.0(含 2.0 lite / 2.0 fast):最多3段,单个[2,15]s,总时长不超过15s
  10181. * Seedance 2.5:最多10段,单个[2,30]s,总时长不超过30s
  10182. *
  10183. * @param string $model
  10184. * @return array|null 非参考音频模型返回 null
  10185. */
  10186. public function getActAudioLimits($model) {
  10187. if (!$this->isActReferenceAudioSupported($model)) {
  10188. return null;
  10189. }
  10190. if (strpos($model, '2.5') !== false || strpos($model, '2-5') !== false) {
  10191. return ['max_count' => 10, 'max_single' => 30, 'max_total' => 30];
  10192. }
  10193. return ['max_count' => 3, 'max_single' => 15, 'max_total' => 15];
  10194. }
  10195. /**
  10196. * 生成提示词之前解析可用的参考音频
  10197. * 按正文中{资产名}首次出现的顺序,逐个校验单个音频时长、段数与总时长,超出限制的部分直接截断;
  10198. * 被截断(或单个时长超限)的角色不会出现在提示词的<音频N>引用中,会自动回退使用音色提示词
  10199. *
  10200. * @param string $actContent 片段内容
  10201. * @param array $products 资产数组
  10202. * @param string $model 视频模型
  10203. * @return array ['allowed' => [产品名 => 音频URL], 'excluded' => [产品名 => 原因], 'total_duration' => 秒]
  10204. */
  10205. public function resolveActReferenceAudios($actContent, $products, $model) {
  10206. $result = ['allowed' => [], 'excluded' => [], 'total_duration' => 0];
  10207. $limits = $this->getActAudioLimits($model);
  10208. if (!$limits || empty($actContent) || empty($products)) {
  10209. return $result;
  10210. }
  10211. // 产品名 => 音色音频
  10212. $timbreMap = [];
  10213. foreach ($products as $product) {
  10214. $name = getProp($product, 'product_name');
  10215. if (!$name) {
  10216. continue;
  10217. }
  10218. $timbre = trim((string)getProp($product, 'timbre_url', ''));
  10219. if ($timbre !== '') {
  10220. $timbreMap[$name] = $timbre;
  10221. }
  10222. }
  10223. if (empty($timbreMap)) {
  10224. return $result;
  10225. }
  10226. // 按正文中{资产名}首次出现的顺序确定音频编号顺序(与提示词生成保持一致)
  10227. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  10228. $orderedNames = [];
  10229. foreach (($matches[1] ?? []) as $name) {
  10230. if (!isset($orderedNames[$name])) {
  10231. $orderedNames[$name] = true;
  10232. }
  10233. }
  10234. // 收集候选音频(同一音频可能被多个角色复用,只保留首次出现的URL用于筛选)
  10235. $orderedUrls = [];
  10236. foreach (array_keys($orderedNames) as $name) {
  10237. $timbre = $timbreMap[$name] ?? '';
  10238. if ($timbre !== '' && !in_array($timbre, $orderedUrls, true)) {
  10239. $orderedUrls[] = $timbre;
  10240. }
  10241. }
  10242. if (empty($orderedUrls)) {
  10243. return $result;
  10244. }
  10245. // 复用统一的筛选逻辑:单个音频时长 → 段数 → 总时长(与通用接口 generateVideo 共用)
  10246. $filtered = $this->filterActReferenceAudiosWithDetail($orderedUrls, $limits);
  10247. $result['total_duration'] = $filtered['total_duration'];
  10248. // 按角色在正文中的出现顺序回填结果,保证键顺序与提示词编号顺序一致
  10249. foreach (array_keys($orderedNames) as $name) {
  10250. $timbre = $timbreMap[$name] ?? '';
  10251. if ($timbre === '') {
  10252. continue;
  10253. }
  10254. if (isset($filtered['durations'][$timbre])) {
  10255. $result['allowed'][$name] = $timbre;
  10256. } elseif (isset($filtered['rejected'][$timbre])) {
  10257. $result['excluded'][$name] = $filtered['rejected'][$timbre];
  10258. }
  10259. }
  10260. if (!empty($result['excluded'])) {
  10261. dLog('anime')->info('参考音频超出模型限制,已截断', [
  10262. 'model' => $model,
  10263. 'limits' => $limits,
  10264. 'allowed' => array_keys($result['allowed']),
  10265. 'excluded' => $result['excluded'],
  10266. 'total_duration' => $result['total_duration'],
  10267. ]);
  10268. }
  10269. return $result;
  10270. }
  10271. /**
  10272. * 按模型限制逐条筛选参考音频(片段转视频与通用文生视频共用的判断逻辑)
  10273. * 顺序:单个音频时长 → 段数上限 → 总时长上限;相同URL复用同一段素材,不重复计数
  10274. *
  10275. * @param array $referenceAudios 参考音频URL数组
  10276. * @param array $limits 限制,如 ['max_count'=>3,'max_single'=>15,'max_total'=>15]
  10277. * @return array ['allowed' => [url...], 'durations' => [url=>秒], 'rejected' => [url=>原因], 'total_duration' => 秒]
  10278. */
  10279. public function filterActReferenceAudiosWithDetail(array $referenceAudios, array $limits) {
  10280. $allowed = [];
  10281. $durations = [];
  10282. $rejected = [];
  10283. $totalDuration = 0;
  10284. foreach ($referenceAudios as $url) {
  10285. if (!is_string($url) || trim($url) === '' || isset($durations[$url]) || isset($rejected[$url])) {
  10286. continue;
  10287. }
  10288. $duration = $this->getRemoteAudioDurationSeconds($url);
  10289. if ($duration > 0 && $duration > $limits['max_single']) {
  10290. $rejected[$url] = '单个音频时长超限(' . $duration . 's > ' . $limits['max_single'] . 's)';
  10291. continue;
  10292. }
  10293. if (count($allowed) >= $limits['max_count']) {
  10294. $rejected[$url] = '超过参考音频段数上限(' . $limits['max_count'] . '段)';
  10295. continue;
  10296. }
  10297. if ($duration > 0 && ($totalDuration + $duration) > $limits['max_total']) {
  10298. $rejected[$url] = '超过参考音频总时长上限(' . $limits['max_total'] . 's)';
  10299. continue;
  10300. }
  10301. $allowed[] = $url;
  10302. $durations[$url] = max(0, $duration);
  10303. $totalDuration += max(0, $duration);
  10304. }
  10305. return [
  10306. 'allowed' => $allowed,
  10307. 'durations' => $durations,
  10308. 'rejected' => $rejected,
  10309. 'total_duration' => round($totalDuration, 2),
  10310. ];
  10311. }
  10312. /**
  10313. * 按模型限制过滤参考音频(通用接口用,仅返回通过的URL数组)
  10314. *
  10315. * @param array $referenceAudios 参考音频URL数组
  10316. * @param array $limits 限制
  10317. * @return array 过滤后的音频URL数组
  10318. */
  10319. public function filterActReferenceAudios(array $referenceAudios, array $limits) {
  10320. $filtered = $this->filterActReferenceAudiosWithDetail($referenceAudios, $limits);
  10321. if (!empty($filtered['rejected'])) {
  10322. dLog('anime')->info('参考音频超出模型限制,已截断', [
  10323. 'limits' => $limits,
  10324. 'allowed' => $filtered['allowed'],
  10325. 'rejected' => $filtered['rejected'],
  10326. 'total_duration' => $filtered['total_duration'],
  10327. ]);
  10328. }
  10329. return $filtered['allowed'];
  10330. }
  10331. /**
  10332. * 探测远程音频时长(wav 精确解析;mp3 按首帧码率估算)
  10333. *
  10334. * @param string $url 音频URL
  10335. * @return float 秒;无法探测时返回 0
  10336. */
  10337. public function getRemoteAudioDurationSeconds($url) {
  10338. try {
  10339. // 使用 Guzzle(不依赖 allow_url_fopen,LNMP 环境下同样可用)
  10340. $client = new \GuzzleHttp\Client(['verify' => false, 'timeout' => 20, 'connect_timeout' => 10]);
  10341. $response = $client->get($url, [
  10342. 'headers' => ['Range' => 'bytes=0-1048575'],
  10343. 'http_errors' => false,
  10344. ]);
  10345. $data = (string)$response->getBody();
  10346. if (strlen($data) < 64) {
  10347. return 0;
  10348. }
  10349. // 文件总大小:206 时取 Content-Range 的分母,否则用 Content-Length
  10350. $totalSize = 0;
  10351. $contentRange = $response->getHeaderLine('Content-Range');
  10352. if ($contentRange !== '' && preg_match('#/(\d+)#', $contentRange, $m)) {
  10353. $totalSize = (int)$m[1];
  10354. } else {
  10355. $contentLength = $response->getHeaderLine('Content-Length');
  10356. if ($contentLength !== '') {
  10357. $totalSize = (int)$contentLength;
  10358. }
  10359. }
  10360. // WAV:解析 fmt/data chunk 精确计算
  10361. if (substr($data, 0, 4) === 'RIFF' && substr($data, 8, 4) === 'WAVE') {
  10362. $offset = 12;
  10363. $byteRate = 0;
  10364. $dataSize = 0;
  10365. while ($offset + 8 <= strlen($data)) {
  10366. $chunkId = substr($data, $offset, 4);
  10367. $chunkSize = unpack('V', substr($data, $offset + 4, 4))[1];
  10368. if ($chunkId === 'fmt ' && $offset + 8 + 12 <= strlen($data)) {
  10369. $byteRate = unpack('V', substr($data, $offset + 16, 4))[1];
  10370. } elseif ($chunkId === 'data') {
  10371. $dataSize = $chunkSize;
  10372. break;
  10373. }
  10374. $offset += 8 + $chunkSize + ($chunkSize % 2);
  10375. }
  10376. if ($byteRate > 0 && $dataSize > 0) {
  10377. return round($dataSize / $byteRate, 2);
  10378. }
  10379. return 0;
  10380. }
  10381. // MP3:优先 Xing/Info 帧数,其次逐帧统计,最后按码率估算
  10382. $scanStart = 0;
  10383. if (strlen($data) >= 10 && substr($data, 0, 3) === 'ID3') {
  10384. // 跳过 ID3v2 标签,避免命中标签数据中的伪同步字
  10385. $tagSize = ((ord($data[6]) & 0x7F) << 21) | ((ord($data[7]) & 0x7F) << 14)
  10386. | ((ord($data[8]) & 0x7F) << 7) | (ord($data[9]) & 0x7F);
  10387. $scanStart = 10 + $tagSize;
  10388. }
  10389. $mpeg1Layer3 = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320];
  10390. $mpeg2Layer3 = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
  10391. $sampleRatesV1 = [44100, 48000, 32000, 0];
  10392. $sampleRatesV2 = [22050, 24000, 16000, 0];
  10393. $parseFrame = function ($buffer, $offset) use ($mpeg1Layer3, $mpeg2Layer3, $sampleRatesV1, $sampleRatesV2) {
  10394. if ($offset < 0 || $offset + 4 > strlen($buffer)) {
  10395. return null;
  10396. }
  10397. if (ord($buffer[$offset]) !== 0xFF) {
  10398. return null;
  10399. }
  10400. $b1 = ord($buffer[$offset + 1]);
  10401. if (($b1 & 0xE0) !== 0xE0) {
  10402. return null;
  10403. }
  10404. $b2 = ord($buffer[$offset + 2]);
  10405. $b3 = ord($buffer[$offset + 3]);
  10406. $versionBits = ($b1 >> 3) & 0x03; // 3=MPEG1, 2=MPEG2, 0=MPEG2.5
  10407. $layerBits = ($b1 >> 1) & 0x03; // 1=Layer3
  10408. $bitrateIndex = ($b2 >> 4) & 0x0F;
  10409. $sampleIndex = ($b2 >> 2) & 0x03;
  10410. $channelMode = ($b3 >> 6) & 0x03; // 3=单声道
  10411. if ($versionBits === 1 || $layerBits !== 1 || $bitrateIndex === 0 || $bitrateIndex === 15 || $sampleIndex === 3) {
  10412. return null;
  10413. }
  10414. $bitrate = $versionBits === 3 ? $mpeg1Layer3[$bitrateIndex] : $mpeg2Layer3[$bitrateIndex];
  10415. $rate = $versionBits === 3 ? $sampleRatesV1[$sampleIndex] : $sampleRatesV2[$sampleIndex];
  10416. if ($bitrate <= 0 || $rate <= 0) {
  10417. return null;
  10418. }
  10419. $samplesPerFrame = $versionBits === 3 ? 1152 : 576;
  10420. $frameLen = (int)(($samplesPerFrame / 8 * $bitrate * 1000) / $rate);
  10421. if ($frameLen <= 4) {
  10422. return null;
  10423. }
  10424. return [
  10425. 'version' => $versionBits,
  10426. 'bitrate' => $bitrate,
  10427. 'rate' => $rate,
  10428. 'samples' => $samplesPerFrame,
  10429. 'length' => $frameLen,
  10430. 'channel_mode' => $channelMode,
  10431. ];
  10432. };
  10433. // 定位首个有效帧,并校验下一帧也合法(避免命中伪同步字)
  10434. $firstFrame = null;
  10435. $frameOffset = -1;
  10436. for ($i = $scanStart; $i + 4 <= strlen($data); $i++) {
  10437. $frame = $parseFrame($data, $i);
  10438. if (!$frame) {
  10439. continue;
  10440. }
  10441. $nextOffset = $i + $frame['length'];
  10442. if ($nextOffset + 4 <= strlen($data) && !$parseFrame($data, $nextOffset)) {
  10443. continue;
  10444. }
  10445. $firstFrame = $frame;
  10446. $frameOffset = $i;
  10447. break;
  10448. }
  10449. if (!$firstFrame) {
  10450. return 0;
  10451. }
  10452. // 1) Xing/Info 头包含总帧数,可直接精确计算
  10453. $sideInfoSize = $firstFrame['version'] === 3
  10454. ? ($firstFrame['channel_mode'] === 3 ? 17 : 32)
  10455. : ($firstFrame['channel_mode'] === 3 ? 9 : 17);
  10456. $xingOffset = $frameOffset + 4 + $sideInfoSize;
  10457. $xingTag = substr($data, $xingOffset, 4);
  10458. if (($xingTag === 'Xing' || $xingTag === 'Info') && strlen($data) >= $xingOffset + 12) {
  10459. $flags = unpack('N', substr($data, $xingOffset + 4, 4))[1];
  10460. if ($flags & 0x01) {
  10461. $frameCount = unpack('N', substr($data, $xingOffset + 8, 4))[1];
  10462. if ($frameCount > 0) {
  10463. return round($frameCount * $firstFrame['samples'] / $firstFrame['rate'], 2);
  10464. }
  10465. }
  10466. }
  10467. // 2) 文件不大时下载完整内容逐帧统计(精确)
  10468. $fullData = $data;
  10469. if ($totalSize > 0 && strlen($data) < $totalSize && $totalSize <= 10485760) {
  10470. $fullData = (string)$client->get($url, ['http_errors' => false])->getBody();
  10471. }
  10472. if ($totalSize > 0 && strlen($fullData) >= $totalSize) {
  10473. $samples = 0;
  10474. $i = $frameOffset;
  10475. $bufferLength = strlen($fullData);
  10476. while ($i + 4 <= $bufferLength) {
  10477. $frame = $parseFrame($fullData, $i);
  10478. if (!$frame) {
  10479. $i++;
  10480. continue;
  10481. }
  10482. $samples += $frame['samples'];
  10483. $i += $frame['length'];
  10484. }
  10485. if ($samples > 0) {
  10486. return round($samples / $firstFrame['rate'], 2);
  10487. }
  10488. }
  10489. // 3) 回退:按首帧码率估算(仅用于无法读取完整文件的极端情况)
  10490. return round(($totalSize * 8) / ($firstFrame['bitrate'] * 1000), 2);
  10491. } catch (\Throwable $e) {
  10492. dLog('anime')->warning('参考音频时长探测失败', ['url' => $url, 'error' => $e->getMessage()]);
  10493. return 0;
  10494. }
  10495. }
  10496. /**
  10497. * 将角色音色参考音频按模型分支上传为素材
  10498. * 上传失败时对应素材的<音频N>标记会从 $prompt 中清理(引用传递),与参考图处理保持一致
  10499. *
  10500. * @param array $referenceAudios 参考音频URL数组(顺序与<音频N>标记一一对应)
  10501. * @param string $model 视频模型
  10502. * @param string $prompt 完整提示词(引用传递)
  10503. * @return array 素材数组(asset://格式),非支持模型返回空数组
  10504. */
  10505. public function processActReferenceAudiosToAssets(array $referenceAudios, $model, &$prompt) {
  10506. if (empty($referenceAudios)) {
  10507. return [];
  10508. }
  10509. if (strpos($model, 'zhizhen') !== false) {
  10510. return $this->aiImageGenerationService->processReferenceAudiosToAssets($referenceAudios, $prompt);
  10511. }
  10512. if ($this->isSeedance20SeriesModel($model)) {
  10513. if ($this->isKuaikuaiSeedanceModel($model)) {
  10514. return $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($referenceAudios, $prompt);
  10515. }
  10516. if ($this->isOverseasBaiduSeedanceModel($model)) {
  10517. return $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($referenceAudios, $prompt);
  10518. }
  10519. return $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($referenceAudios, $prompt);
  10520. }
  10521. return [];
  10522. }
  10523. /**
  10524. * 参考音频素材上传失败时,用该角色原本的音色提示词兜底
  10525. * 说明行中的<音频N>标记被清理即代表该角色的音频素材不可用
  10526. *
  10527. * @param string $prompt 完整提示词
  10528. * @param array $audioVoiceFallbacks 角色名 => voice_prompt(仅包含配置了参考音频的角色)
  10529. * @return string
  10530. */
  10531. public function applyAudioVoiceFallbacks($prompt, array $audioVoiceFallbacks) {
  10532. if (empty($prompt) || empty($audioVoiceFallbacks)) {
  10533. return $prompt;
  10534. }
  10535. foreach ($audioVoiceFallbacks as $product_name => $voice_prompt) {
  10536. $voice_prompt = trim((string)$voice_prompt);
  10537. if ($product_name === '') {
  10538. continue;
  10539. }
  10540. $escaped_name = preg_quote($product_name, '/');
  10541. // 说明行中仍有<音频N>标记,说明该角色的音频素材可用,无需兜底
  10542. if (preg_match('/^参考<音频\d+>中的音色,为' . $escaped_name . '配音[^\n]*$/mu', $prompt)) {
  10543. continue;
  10544. }
  10545. $linePattern = '/^参考<音频\d+>中的音色,为' . $escaped_name . '配音[^\n]*$/mu';
  10546. if (!preg_match($linePattern, $prompt)) {
  10547. continue;
  10548. }
  10549. if ($voice_prompt === '') {
  10550. // 该角色没有音色提示词,素材不可用时直接移除残留的说明行
  10551. $prompt = preg_replace('/^参考<音频\d+>中的音色,为' . $escaped_name . '配音[^\n]*\n?/mu', '', $prompt, 1);
  10552. } else {
  10553. // 素材不可用:把说明行替换为该角色原本的音色提示词
  10554. $prompt = preg_replace_callback($linePattern, function () use ($product_name, $voice_prompt) {
  10555. return $product_name . ':' . $voice_prompt;
  10556. }, $prompt, 1);
  10557. }
  10558. dLog('anime')->info('参考音频素材不可用,使用音色提示词兜底', [
  10559. 'product_name' => $product_name,
  10560. 'has_voice_prompt' => $voice_prompt === '' ? 0 : 1,
  10561. ]);
  10562. }
  10563. return $prompt;
  10564. }
  10565. /**
  10566. * 整段配音音频素材不可用时,移除对应的提示语句,避免出现残句
  10567. *
  10568. * @param string $prompt 完整提示词
  10569. * @return string
  10570. */
  10571. public function removeUnavailableSegmentAudioPrompt($prompt) {
  10572. if (empty($prompt) || strpos($prompt, '作为视频配音') === false) {
  10573. return $prompt;
  10574. }
  10575. return preg_replace_callback('/^全程使用[^\n]*?作为视频配音。\n?/mu', function ($matches) {
  10576. return strpos($matches[0], '<音频') === false ? '' : $matches[0];
  10577. }, $prompt);
  10578. }
  10579. /**
  10580. * 生成整段配音音频的提示词引用,并返回合并后的参考音频数组
  10581. * 角色音色音频排在前面(音频1..N,与提示词中的<音频N>一一对应),整段配音音频排在其后
  10582. *
  10583. * @param string $prompt 当前提示词
  10584. * @param array $referenceAudios 角色音色参考音频URL数组
  10585. * @param string $segmentAudioUrl 整段配音音频URL(为空表示无整段配音)
  10586. * @return array ['prompt' => 新提示词, 'has_audio_mark' => 是否使用<音频N>标记, 'reference_audios' => 合并后的音频数组]
  10587. */
  10588. public function buildSegmentAudioReference($prompt, array $referenceAudios, $segmentAudioUrl) {
  10589. $result = [
  10590. 'prompt' => $prompt,
  10591. 'has_audio_mark' => false,
  10592. 'reference_audios' => $referenceAudios,
  10593. ];
  10594. if (empty($segmentAudioUrl)) {
  10595. return $result;
  10596. }
  10597. // 有角色音色时整段配音排在角色音色之后,使用<音频N>标记交由素材上传统一做失败清理与序号重排;
  10598. // 没有角色音色时保持原有文案
  10599. $audioReference = $referenceAudios
  10600. ? "使用<音频" . (count($referenceAudios) + 1) . ">"
  10601. : "使用音频1";
  10602. $hasAudioMark = strpos($audioReference, '<音频') !== false;
  10603. // 有角色音色时整段配音独占一行,便于失败时按行清理
  10604. $result['prompt'] = $hasAudioMark
  10605. ? "全程" . $audioReference . "作为视频配音。\n" . $prompt
  10606. : "全程" . $audioReference . "作为视频配音。" . $prompt;
  10607. $result['has_audio_mark'] = $hasAudioMark;
  10608. $result['reference_audios'] = array_merge($referenceAudios, [$segmentAudioUrl]);
  10609. return $result;
  10610. }
  10611. /**
  10612. * 任务记录用:把参考音频追加到 ref_image_url 中
  10613. * 参考图与参考音色音频一起保存,便于后续核对任务实际使用的素材
  10614. * 合并后统一去重并过滤空值,保证同一素材只出现一次
  10615. *
  10616. * @param string $refImageUrlJson 当前 ref_image_url(JSON数组字符串)
  10617. * @param array $referenceAudios 参考音频URL数组
  10618. * @return string
  10619. */
  10620. public function mergeReferenceAudiosIntoRefImageUrl($refImageUrlJson, array $referenceAudios) {
  10621. $refImageUrls = json_decode((string)$refImageUrlJson, true) ?: [];
  10622. if (!is_array($refImageUrls)) {
  10623. $refImageUrls = [];
  10624. }
  10625. // 参考图在前、参考音频在后,合并后去重并过滤空值
  10626. $merged = array_values(array_unique(array_filter(array_merge($refImageUrls, $referenceAudios))));
  10627. return json_encode($merged, 256);
  10628. }
  10629. public function saveActVideoGenerateParams($data) {
  10630. $episode_id = getProp($data, 'episode_id');
  10631. $model = getProp($data, 'video_model');
  10632. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  10633. if (!in_array($model, $valid_models)) {
  10634. Utils::throwError('20003:该模型不可用');
  10635. }
  10636. // 验证模型是否在可用模型表中
  10637. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10638. Utils::throwError('20003:该模型已不可用,请更换!');
  10639. }
  10640. $video_resolution = getProp($data, 'video_resolution', '720p');
  10641. $ratio = getProp($data, 'ratio');
  10642. if (!$ratio) $ratio = '9:16';
  10643. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  10644. if (!$episode) {
  10645. Utils::throwError('20003:分集不存在');
  10646. }
  10647. dLog('anime')->info('保存分集视频参数', $data);
  10648. try {
  10649. DB::beginTransaction();
  10650. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10651. 'video_model' => $model,
  10652. 'video_resolution' => $video_resolution,
  10653. 'ratio' => $ratio,
  10654. 'updated_at' => date('Y-m-d H:i:s')
  10655. ]);
  10656. if ($result === false) {
  10657. Utils::throwError('20003:分集视频参数保存失败');
  10658. }
  10659. // 同步更新mp_animes表
  10660. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  10661. 'video_model' => $model,
  10662. 'video_resolution' => $video_resolution,
  10663. 'video_ratio' => $ratio,
  10664. 'updated_at' => date('Y-m-d H:i:s')
  10665. ]);
  10666. if ($anime_result === false) {
  10667. Utils::throwError('20003:动漫视频参数保存失败');
  10668. }
  10669. } catch (\Exception $e) {
  10670. DB::rollBack();
  10671. Utils::throwError('20003:'.$e->getMessage());
  10672. }
  10673. DB::commit();
  10674. return $result;
  10675. }
  10676. public function confirmActs($data) {
  10677. $episode_id = getProp($data, 'episode_id');
  10678. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  10679. if (!$episode) {
  10680. Utils::throwError('20003:分集不存在');
  10681. }
  10682. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10683. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10684. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  10685. // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
  10686. $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
  10687. // 获取所有片段数据
  10688. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  10689. // 先构建完整的 products(角色、场景、道具、extra_products,并用资产库映射覆盖),
  10690. // 再处理每个片段的 act_content,避免 extra_products 等资产名未被格式化为 {资产名}
  10691. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  10692. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  10693. $products = [];
  10694. // 先处理角色数组
  10695. foreach ($roles as $role) {
  10696. $product = $role;
  10697. // 将role字段重命名为product_name
  10698. if (isset($product['role'])) {
  10699. $product['product_name'] = $product['role'];
  10700. unset($product['role']);
  10701. $product['product'] = 1; // 标记类型为角色
  10702. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10703. }
  10704. }
  10705. // 处理场景数组
  10706. foreach ($scenes as $scene) {
  10707. $product = $scene;
  10708. // 将scene字段重命名为product_name
  10709. if (isset($product['scene'])) {
  10710. $product['product_name'] = $product['scene'];
  10711. unset($product['scene']);
  10712. $product['product'] = 2; // 标记类型为场景
  10713. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10714. }
  10715. }
  10716. // 处理道具数组(逻辑与场景一致)
  10717. foreach ($props as $prop) {
  10718. $product = $prop;
  10719. // 将prop字段重命名为product_name
  10720. if (isset($product['prop'])) {
  10721. $product['product_name'] = $product['prop'];
  10722. unset($product['prop']);
  10723. $product['product'] = 3; // 标记类型为道具
  10724. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10725. }
  10726. }
  10727. // extra_products优先级更高,直接覆盖同名的roles和scenes
  10728. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  10729. foreach ($extra_products as $extra_product) {
  10730. $product_name = getProp($extra_product, 'product_name');
  10731. if ($product_name) {
  10732. $products[$product_name] = $extra_product; // 覆盖同名数据
  10733. }
  10734. }
  10735. // mp_script_product_mappings 信息优先级更高:
  10736. // 获取当前剧集所属动漫剧本下、与本集资产同名的资产库最新数据(url/三视图/提示词等),
  10737. // 覆盖分集 JSON 中保存的同名旧快照;分集内独有的 description、voice_prompt 等字段保留
  10738. $anime = DB::table('mp_animes')->where('id', getProp($episode, 'anime_id'))->first();
  10739. $script_id = $anime ? (int)getProp($anime, 'script_id', 0) : 0;
  10740. if ($script_id && !empty($products)) {
  10741. $currentProductNames = array_keys($products);
  10742. $normalizeName = function($name) {
  10743. return trim(preg_replace(
  10744. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  10745. '',
  10746. trim((string)$name)
  10747. ));
  10748. };
  10749. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  10750. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  10751. ->where('mapping.script_id', $script_id)
  10752. ->where('product.is_deleted', 0)
  10753. ->whereIn('product.product_name', $currentProductNames)
  10754. ->select(
  10755. 'mapping.product_id',
  10756. 'product.product_name',
  10757. 'product.product',
  10758. 'product.pic_prompt',
  10759. 'product.url',
  10760. 'product.three_view_image_url',
  10761. 'product.timbre_url',
  10762. )
  10763. ->get();
  10764. $mappingByName = [];
  10765. foreach ($mappingItems as $mappingItem) {
  10766. $normalizedName = $normalizeName($mappingItem->product_name);
  10767. if (!$normalizedName) continue;
  10768. $mappingProduct = [
  10769. 'product_id' => (int)$mappingItem->product_id,
  10770. 'product_name' => $mappingItem->product_name,
  10771. 'product' => (int)$mappingItem->product,
  10772. 'pic_prompt' => $mappingItem->pic_prompt ?? '',
  10773. 'url' => $mappingItem->url ?? '',
  10774. 'three_view_image_url' => $mappingItem->three_view_image_url ?? '',
  10775. ];
  10776. // 音色音频:资产库有值时才覆盖分集自带的值,避免空值把已有音色清掉
  10777. if (!empty($mappingItem->timbre_url)) {
  10778. $mappingProduct['timbre_url'] = $mappingItem->timbre_url;
  10779. }
  10780. $mappingByName[$normalizedName] = $mappingProduct;
  10781. }
  10782. foreach ($products as $key => &$product) {
  10783. $normalizedKey = $normalizeName($key);
  10784. if ($normalizedKey && isset($mappingByName[$normalizedKey])) {
  10785. $product = array_merge($product, $mappingByName[$normalizedKey]);
  10786. }
  10787. }
  10788. unset($product);
  10789. }
  10790. // 兼容返回 three_view_image_url / timbre_url 字段(旧数据可能没有该键,统一补空值)
  10791. foreach ($products as &$product) {
  10792. if (!isset($product['three_view_image_url'])) {
  10793. $product['three_view_image_url'] = '';
  10794. }
  10795. if (!isset($product['timbre_url'])) {
  10796. $product['timbre_url'] = '';
  10797. }
  10798. }
  10799. unset($product);
  10800. // 重新索引数组(去除key)
  10801. $products = array_values($products);
  10802. // 基于构建完成的 products 收集所有资产名称(含 extra_products 中的资产)
  10803. $product_names = [];
  10804. foreach ($products as $product) {
  10805. $product_name = getProp($product, 'product_name');
  10806. if ($product_name && $product_name !== '旁白') {
  10807. $product_names[] = $product_name;
  10808. }
  10809. }
  10810. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  10811. $product_names = array_unique($product_names);
  10812. usort($product_names, function($a, $b) {
  10813. return mb_strlen($b) - mb_strlen($a);
  10814. });
  10815. try {
  10816. DB::beginTransaction();
  10817. // 处理每个片段
  10818. foreach ($acts as $act) {
  10819. $act_content = getProp($act, 'act_content');
  10820. if (!$act_content) continue;
  10821. $processed_content = $act_content;
  10822. // 统一替换所有资产名称为 {资产名} 格式
  10823. // 使用占位符避免嵌套替换问题
  10824. $placeholder_map = [];
  10825. $placeholder_index = 0;
  10826. foreach ($product_names as $product_name) {
  10827. // 转义特殊字符
  10828. $escaped_product = preg_quote($product_name, '/');
  10829. // 检查是否匹配且未被 {} 包裹
  10830. $processed_content = preg_replace_callback(
  10831. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  10832. function($matches) use (&$placeholder_map, &$placeholder_index) {
  10833. // 使用唯一占位符
  10834. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  10835. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  10836. $placeholder_index++;
  10837. return $placeholder;
  10838. },
  10839. $processed_content
  10840. );
  10841. }
  10842. // 将所有占位符替换回实际内容
  10843. foreach ($placeholder_map as $placeholder => $replacement) {
  10844. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  10845. }
  10846. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  10847. $shot_counter = 0;
  10848. $processed_content = preg_replace_callback(
  10849. '/【(?:镜头|分镜)(\d+)】/u',
  10850. function($matches) use (&$shot_counter) {
  10851. $shot_counter++;
  10852. return '【镜头' . $shot_counter . '】';
  10853. },
  10854. $processed_content
  10855. );
  10856. // 更新数据库
  10857. $boolen = DB::table('mp_episode_segments')
  10858. ->where('id', $act->id)
  10859. ->update([
  10860. 'act_show_content' => $processed_content,
  10861. 'updated_at' => date('Y-m-d H:i:s')
  10862. ]);
  10863. if (!$boolen) {
  10864. Utils::throwError('20003:片段处理失败');
  10865. }
  10866. }
  10867. }catch (\Exception $e) {
  10868. DB::rollBack();
  10869. Utils::throwError('20003:'.$e->getMessage());
  10870. }
  10871. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10872. 'is_generated' => 1,
  10873. 'updated_at' => date('Y-m-d H:i:s')
  10874. ]);
  10875. if (!$boolen1) {
  10876. DB::rollBack();
  10877. Utils::throwError('20003:分集处理失败!');
  10878. }
  10879. DB::commit();
  10880. // 重新查询更新后的片段数据
  10881. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  10882. // 构建返回的acts数组
  10883. $return_acts = [];
  10884. foreach ($acts as $act) {
  10885. $return_acts[] = [
  10886. 'act_id' => getProp($act, 'id'),
  10887. 'act_number' => getProp($act, 'act_number'),
  10888. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  10889. 'act_show_content' => getProp($act, 'act_show_content'),
  10890. 'video_url' => getProp($act, 'video_url'),
  10891. 'video_duration' => getProp($act, 'video_duration'),
  10892. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  10893. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  10894. ];
  10895. }
  10896. return [
  10897. 'anime_id' => getProp($episode, 'anime_id'),
  10898. 'episode_id' => $episode_id,
  10899. 'title' => getProp($episode, 'title'),
  10900. 'episode_number' => getProp($episode, 'episode_number'),
  10901. 'is_generated' => getProp($episode, 'is_generated'),
  10902. 'video_params' => [
  10903. 'video_model' => getProp($episode, 'video_model'),
  10904. 'video_resolution' => getProp($episode, 'video_resolution'),
  10905. 'ratio' => getProp($episode, 'ratio'),
  10906. ],
  10907. 'products' => $products,
  10908. 'acts' => $return_acts
  10909. ];
  10910. }
  10911. /**
  10912. * 参照 episodePicsInfo 的更新与监控逻辑:
  10913. * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
  10914. * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
  10915. */
  10916. private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
  10917. $pollInterval = 5; // 每5秒查询一次
  10918. $maxWaitSeconds = 60; // 最多持续1分钟
  10919. $startTime = time();
  10920. while (true) {
  10921. // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
  10922. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  10923. if (!$episode) {
  10924. Utils::throwError('20003:分集不存在');
  10925. }
  10926. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10927. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10928. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  10929. $updated = false;
  10930. $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
  10931. $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
  10932. $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
  10933. $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
  10934. $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
  10935. // 有图片任务结果更新时写回分集表
  10936. if ($updated) {
  10937. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10938. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  10939. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  10940. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  10941. 'updated_at' => date('Y-m-d H:i:s')
  10942. ]);
  10943. }
  10944. // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
  10945. if (empty($waitingAssets) && empty($missingAssets)) {
  10946. return;
  10947. }
  10948. // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
  10949. if (empty($waitingAssets)) {
  10950. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10951. }
  10952. // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
  10953. if (time() - $startTime >= $maxWaitSeconds) {
  10954. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10955. }
  10956. sleep($pollInterval);
  10957. }
  10958. }
  10959. /**
  10960. * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
  10961. * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
  10962. * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
  10963. */
  10964. private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
  10965. foreach ($assets as &$asset) {
  10966. $assetName = getProp($asset, $nameKey);
  10967. if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
  10968. continue;
  10969. }
  10970. // 已有图片URL的资产视为已生成
  10971. if (getProp($asset, 'url')) {
  10972. continue;
  10973. }
  10974. $task_id = getProp($asset, 'task_id');
  10975. // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
  10976. if (!$task_id) {
  10977. $missingAssets[] = $assetName;
  10978. continue;
  10979. }
  10980. $task = DB::table('mp_generate_pic_tasks')
  10981. ->where('id', $task_id)
  10982. ->select('status', 'result_url')
  10983. ->first();
  10984. // 任务不存在:同样记录为缺失项,不在此处直接报错
  10985. if (!$task) {
  10986. $missingAssets[] = $assetName;
  10987. continue;
  10988. }
  10989. if ($task->status === 'success') {
  10990. $result_url = getProp($task, 'result_url');
  10991. if ($result_url) {
  10992. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  10993. if (is_array($result_urls) && !empty($result_urls[0])) {
  10994. $asset['url'] = $result_urls[0];
  10995. $asset['task_status'] = 'success';
  10996. $updated = true;
  10997. continue;
  10998. }
  10999. }
  11000. // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
  11001. $waitingAssets[] = $assetName;
  11002. } elseif ($task->status === 'failed') {
  11003. // 生成失败:记录为缺失项,待其他任务处理完后统一报错
  11004. $missingAssets[] = $assetName;
  11005. } else {
  11006. // 任务仍在生成中,等待下一次轮询
  11007. $waitingAssets[] = $assetName;
  11008. }
  11009. }
  11010. unset($asset);
  11011. }
  11012. /**
  11013. * 导出动漫剧本为PDF(参照示例PDF版式)
  11014. * @param int $animeId 动漫ID
  11015. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  11016. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  11017. * @return string|null
  11018. */
  11019. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  11020. // 图片下载与转换可能占用较多内存
  11021. ini_set('memory_limit', '512M');
  11022. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  11023. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  11024. $anime = (array)$anime;
  11025. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  11026. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  11027. // 获取分集(默认展示版本,按集数升序)
  11028. $episodeQuery = DB::table('mp_anime_episodes')
  11029. ->where('anime_id', $animeId)
  11030. ->where('is_default', 1)
  11031. ->orderBy('episode_number')
  11032. ->orderBy('id');
  11033. if ($episodeCount > 0) {
  11034. $episodeQuery->limit($episodeCount);
  11035. }
  11036. $episodes = $episodeQuery->get()->map(function ($value) {
  11037. return (array)$value;
  11038. })->toArray();
  11039. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  11040. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  11041. $roles = $this->mergeEpisodeItems($episodes, 'role');
  11042. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  11043. $props = $this->mergeEpisodeItems($episodes, 'prop');
  11044. // 组装分集剧本数据
  11045. $episodeScripts = [];
  11046. foreach ($episodes as $episode) {
  11047. $segments = DB::table('mp_episode_segments')
  11048. ->where('anime_id', $animeId)
  11049. ->where('episode_id', $episode['id'])
  11050. ->get();
  11051. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  11052. $acts = [];
  11053. foreach ($segments as $segment) {
  11054. $segment = (array)$segment;
  11055. $actNumber = (int)getProp($segment, 'act_number', 0);
  11056. if ($actNumber <= 0) continue;
  11057. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  11058. $acts[$actNumber] = [
  11059. 'id' => (int)$segment['id'],
  11060. 'act_number' => $actNumber,
  11061. 'duration' => getProp($segment, 'act_duration', ''),
  11062. 'content' => getProp($segment, 'act_content', ''),
  11063. ];
  11064. }
  11065. }
  11066. ksort($acts);
  11067. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  11068. $segmentCounter = 0;
  11069. foreach ($acts as &$act) {
  11070. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  11071. }
  11072. unset($act);
  11073. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  11074. $narratorVoice = '';
  11075. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  11076. foreach ($episodeRoles as $role) {
  11077. if (getProp($role, 'role') === '旁白') {
  11078. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  11079. break;
  11080. }
  11081. }
  11082. if ($narratorVoice === '') {
  11083. foreach ($acts as $act) {
  11084. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  11085. $narratorVoice = trim($match[1]);
  11086. break;
  11087. }
  11088. }
  11089. }
  11090. $episodeScripts[] = [
  11091. 'episode_number' => getProp($episode, 'episode_number'),
  11092. 'title' => getProp($episode, 'title', ''),
  11093. 'act_count' => count($acts),
  11094. 'narrator_voice' => $narratorVoice,
  11095. 'acts' => array_values($acts),
  11096. ];
  11097. }
  11098. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  11099. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  11100. // 构建PDF
  11101. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  11102. // 图片已嵌入PDF,清理临时文件
  11103. foreach ($imageCache as $imgFile) {
  11104. @unlink($imgFile);
  11105. }
  11106. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  11107. if ($savePath) {
  11108. $pdf->Output($savePath, 'F');
  11109. return $savePath;
  11110. }
  11111. // 直接下载输出
  11112. header('Content-Type: application/pdf');
  11113. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  11114. $pdf->Output($filename . '.pdf', 'D');
  11115. exit();
  11116. }
  11117. /**
  11118. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  11119. * @param array $episodes 分集数据
  11120. * @param string $nameKey role|scene|prop
  11121. * @return array
  11122. */
  11123. private function mergeEpisodeItems(array $episodes, $nameKey) {
  11124. $fieldMap = [
  11125. 'role' => 'roles',
  11126. 'scene' => 'scenes',
  11127. 'prop' => 'props',
  11128. ];
  11129. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  11130. $items = [];
  11131. foreach ($episodes as $episode) {
  11132. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  11133. foreach ($list as $item) {
  11134. if (!is_array($item)) continue;
  11135. $name = trim((string)getProp($item, $nameKey, ''));
  11136. if ($name === '') continue;
  11137. // 旁白不进入主体列表(仅作为旁白音色来源)
  11138. if ($nameKey === 'role' && $name === '旁白') continue;
  11139. if (!isset($items[$name])) {
  11140. $items[$name] = $item;
  11141. }
  11142. }
  11143. }
  11144. return array_values($items);
  11145. }
  11146. /**
  11147. * 构建动漫剧本PDF
  11148. * @param array $anime 动漫信息
  11149. * @param array $roles 主体列表
  11150. * @param array $scenes 场景列表
  11151. * @param array $props 道具列表
  11152. * @param array $episodeScripts 分集剧本数据
  11153. * @param array $imageCache 图片缓存(url => 临时文件路径)
  11154. * @return \TCPDF
  11155. */
  11156. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  11157. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  11158. $pdf->SetCreator('动漫剧本导出系统');
  11159. $pdf->SetAuthor('系统');
  11160. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  11161. $pdf->SetSubject('动漫剧本导出');
  11162. $pdf->SetMargins(15, 15, 15);
  11163. $pdf->SetAutoPageBreak(true, 15);
  11164. // 剧本名
  11165. $pdf->AddPage();
  11166. $pdf->SetFont('simsun', 'B', 20);
  11167. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  11168. $pdf->Ln(5);
  11169. // 故事梗概
  11170. $intro = trim((string)getProp($anime, 'intro', ''));
  11171. if ($intro !== '') {
  11172. $this->pdfSectionTitle($pdf, '故事梗概');
  11173. $this->pdfBody($pdf, $intro);
  11174. }
  11175. // 美术风格
  11176. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  11177. if ($artStyle !== '') {
  11178. $this->pdfSectionTitle($pdf, '美术风格');
  11179. $this->pdfBody($pdf, $artStyle);
  11180. }
  11181. // 主体列表(文字+图片)
  11182. $this->pdfSectionTitle($pdf, '主体列表');
  11183. foreach ($roles as $index => $role) {
  11184. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  11185. }
  11186. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  11187. // 场景列表(文字+图片)
  11188. $this->pdfSectionTitle($pdf, '场景列表');
  11189. foreach ($scenes as $index => $scene) {
  11190. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  11191. }
  11192. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  11193. // 道具列表(文字+图片)
  11194. $this->pdfSectionTitle($pdf, '道具列表');
  11195. foreach ($props as $index => $prop) {
  11196. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  11197. }
  11198. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  11199. // 分镜剧本
  11200. $this->pdfSectionTitle($pdf, '分镜剧本');
  11201. foreach ($episodeScripts as $episodeScript) {
  11202. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  11203. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  11204. if ($episodeTitleRaw !== '') {
  11205. // title 字段可能已带"第N集"前缀,避免重复
  11206. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  11207. $episodeTitle = $episodeTitleRaw;
  11208. } else {
  11209. $episodeTitle .= ':' . $episodeTitleRaw;
  11210. }
  11211. }
  11212. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  11213. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  11214. if (getProp($episodeScript, 'narrator_voice') !== '') {
  11215. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  11216. }
  11217. foreach (getProp($episodeScript, 'acts', []) as $act) {
  11218. $actTitle = '片段' . getProp($act, 'act_number');
  11219. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  11220. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  11221. }
  11222. $this->pdfSubTitle($pdf, $actTitle, 12);
  11223. if (getProp($act, 'content') !== '') {
  11224. $this->pdfBody($pdf, getProp($act, 'content'));
  11225. }
  11226. }
  11227. }
  11228. return $pdf;
  11229. }
  11230. /**
  11231. * PDF章节标题(带分隔线)
  11232. */
  11233. private function pdfSectionTitle($pdf, $title) {
  11234. if ($pdf->GetY() > 230) {
  11235. $pdf->AddPage();
  11236. }
  11237. $pdf->SetFont('simsun', 'B', 15);
  11238. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  11239. $y = $pdf->GetY();
  11240. $pdf->SetLineWidth(0.4);
  11241. $pdf->Line(15, $y, 195, $y);
  11242. $pdf->Ln(4);
  11243. }
  11244. /**
  11245. * PDF子标题(集数/片段标题)
  11246. */
  11247. private function pdfSubTitle($pdf, $title, $size = 13) {
  11248. if ($pdf->GetY() > 240) {
  11249. $pdf->AddPage();
  11250. }
  11251. $pdf->SetFont('simsun', 'B', $size);
  11252. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  11253. $pdf->Ln(1);
  11254. }
  11255. /**
  11256. * PDF正文段落
  11257. */
  11258. private function pdfBody($pdf, $text) {
  11259. $pdf->SetFont('simsun', '', 11);
  11260. $pdf->MultiCell(0, 6, $text, 0, 'L');
  11261. $pdf->Ln(2);
  11262. }
  11263. /**
  11264. * 输出列表项图片(每张图单独一页,图下标注名称)
  11265. * @param \TCPDF $pdf
  11266. * @param array $items 列表项
  11267. * @param string $nameKey role|scene|prop
  11268. * @param array $imageCache 图片缓存(url => 临时文件路径)
  11269. */
  11270. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  11271. foreach ($items as $item) {
  11272. $url = trim((string)getProp($item, 'url', ''));
  11273. $name = trim((string)getProp($item, $nameKey, ''));
  11274. if ($url === '' || !isset($imageCache[$url])) continue;
  11275. $imgPath = $imageCache[$url];
  11276. $size = @getimagesize($imgPath);
  11277. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  11278. continue;
  11279. }
  11280. $pdf->AddPage();
  11281. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  11282. $maxW = 160;
  11283. $maxH = 170;
  11284. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  11285. $drawW = $size[0] * $ratio;
  11286. $drawH = $size[1] * $ratio;
  11287. $x = (210 - $drawW) / 2;
  11288. $y = max(15, (297 - $drawH) / 2 - 10);
  11289. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  11290. // 图下标注名称
  11291. $pdf->SetFont('simsun', 'B', 13);
  11292. $pdf->SetY(297 - 28);
  11293. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  11294. }
  11295. }
  11296. /**
  11297. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  11298. * @param array $items 包含url字段的列表项
  11299. * @return array url => 临时文件路径
  11300. */
  11301. private function downloadImagesConcurrently(array $items) {
  11302. // 收集唯一的图片URL
  11303. $urls = [];
  11304. foreach ($items as $item) {
  11305. $url = trim((string)getProp($item, 'url', ''));
  11306. if ($url !== '') $urls[$url] = true;
  11307. }
  11308. if (!$urls) return [];
  11309. $urls = array_keys($urls);
  11310. $tmpDir = sys_get_temp_dir();
  11311. $rawFiles = [];
  11312. foreach ($urls as $url) {
  11313. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  11314. $rawFiles[$url] = $rawFile;
  11315. }
  11316. $client = new Client(['timeout' => 180, 'verify' => false]);
  11317. // 低并发下载,sink写入文件避免大图占用内存
  11318. $generator = (function () use ($urls, $client, $rawFiles) {
  11319. foreach ($urls as $url) {
  11320. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  11321. }
  11322. })();
  11323. $errors = [];
  11324. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  11325. 'concurrency' => 4,
  11326. 'rejected' => function ($reason, $url) use (&$errors) {
  11327. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  11328. },
  11329. ]);
  11330. $each->promise()->wait();
  11331. // 失败的图片串行重试一次(独占带宽,提高成功率)
  11332. foreach ($urls as $url) {
  11333. if (!isset($errors[$url])) continue;
  11334. try {
  11335. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  11336. unset($errors[$url]);
  11337. } catch (\Throwable $e) {
  11338. // 重试仍失败
  11339. }
  11340. }
  11341. $cache = [];
  11342. foreach ($urls as $url) {
  11343. $rawFile = $rawFiles[$url];
  11344. if (isset($errors[$url])) {
  11345. dLog('anime')->error('导出PDF图片下载失败', [
  11346. 'url' => $url,
  11347. 'error' => $errors[$url],
  11348. ]);
  11349. @unlink($rawFile);
  11350. continue;
  11351. }
  11352. $converted = $this->convertImageFile($rawFile, $url);
  11353. if ($converted !== null) {
  11354. $cache[$url] = $converted;
  11355. } else {
  11356. @unlink($rawFile);
  11357. }
  11358. }
  11359. return $cache;
  11360. }
  11361. /**
  11362. * 将已下载的图片文件缩放并转为JPEG
  11363. * @param string $rawFile 原始图片临时文件
  11364. * @param string $url 图片地址(用于命名)
  11365. * @return string|null 转换后的文件路径,转换失败返回null
  11366. */
  11367. private function convertImageFile($rawFile, $url) {
  11368. $content = @file_get_contents($rawFile);
  11369. if ($content === false || $content === '') return null;
  11370. if (!function_exists('imagecreatefromstring')) return null;
  11371. $image = @imagecreatefromstring($content);
  11372. if ($image === false) return null;
  11373. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  11374. imagedestroy($image);
  11375. if ($jpeg !== null) {
  11376. @unlink($rawFile);
  11377. }
  11378. return $jpeg;
  11379. }
  11380. /**
  11381. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  11382. * @param resource $srcImage GD图片资源
  11383. * @param string $rawFile 原始图片临时文件
  11384. * @param string $url 图片地址(用于命名)
  11385. * @return string|null 压缩后的JPEG文件路径
  11386. */
  11387. private function compressImageForPdf($srcImage, $rawFile, $url) {
  11388. $maxBytes = 2 * 1024 * 1024; // 2MB
  11389. $sizes = [2048, 1600, 1280, 1024, 800];
  11390. $qualities = [85, 70, 55, 40];
  11391. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  11392. foreach ($sizes as $size) {
  11393. $resized = $this->copyAndResize($srcImage, $size);
  11394. $flat = $this->flattenToWhite($resized);
  11395. imagedestroy($resized);
  11396. foreach ($qualities as $quality) {
  11397. ob_start();
  11398. $saved = imagejpeg($flat, null, $quality);
  11399. $data = ob_get_clean();
  11400. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  11401. file_put_contents($jpeg, $data);
  11402. imagedestroy($flat);
  11403. dLog('anime')->info('导出PDF图片压缩完成', [
  11404. 'url' => $url,
  11405. 'size' => filesize($jpeg),
  11406. 'edge' => $size,
  11407. 'quality' => $quality,
  11408. ]);
  11409. return $jpeg;
  11410. }
  11411. }
  11412. imagedestroy($flat);
  11413. }
  11414. // 兜底:最小尺寸、最低质量强制输出
  11415. $resized = $this->copyAndResize($srcImage, 800);
  11416. $flat = $this->flattenToWhite($resized);
  11417. imagedestroy($resized);
  11418. $saved = imagejpeg($flat, $jpeg, 30);
  11419. imagedestroy($flat);
  11420. if (!$saved) return null;
  11421. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  11422. 'url' => $url,
  11423. 'size' => filesize($jpeg),
  11424. ]);
  11425. return $jpeg;
  11426. }
  11427. /**
  11428. * 等比缩放图片副本(不销毁原图)
  11429. * @param resource $srcImage GD图片资源
  11430. * @param int $maxEdge 最大边长
  11431. * @return resource
  11432. */
  11433. private function copyAndResize($srcImage, $maxEdge) {
  11434. $width = imagesx($srcImage);
  11435. $height = imagesy($srcImage);
  11436. $max = max($width, $height);
  11437. if ($max <= $maxEdge) {
  11438. $copy = imagecreatetruecolor($width, $height);
  11439. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  11440. return $copy;
  11441. }
  11442. $ratio = $maxEdge / $max;
  11443. $newWidth = max(1, (int)round($width * $ratio));
  11444. $newHeight = max(1, (int)round($height * $ratio));
  11445. $resized = imagecreatetruecolor($newWidth, $newHeight);
  11446. imagealphablending($resized, false);
  11447. imagesavealpha($resized, true);
  11448. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  11449. return $resized;
  11450. }
  11451. /**
  11452. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  11453. * @param resource $image GD图片资源
  11454. * @return resource
  11455. */
  11456. private function flattenToWhite($image) {
  11457. $width = imagesx($image);
  11458. $height = imagesy($image);
  11459. $flat = imagecreatetruecolor($width, $height);
  11460. $white = imagecolorallocate($flat, 255, 255, 255);
  11461. imagefill($flat, 0, 0, $white);
  11462. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  11463. return $flat;
  11464. }
  11465. /**
  11466. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  11467. * @param string $content 片段内容
  11468. * @param int $counter 当前已编号数量(引用传递,整集累计)
  11469. * @return string
  11470. */
  11471. private function renumberSegmentBlocks($content, &$counter) {
  11472. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  11473. $counter++;
  11474. return '【' . $match[1] . $counter . '】';
  11475. }, $content);
  11476. }
  11477. }