AnimeService.php 452 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Models\MpTaskCenter;
  9. use App\Services\AIGeneration\AIImageGenerationService;
  10. use App\Services\AIGeneration\AIVideoGenerationService;
  11. use App\Services\DeepSeek\DeepSeekService;
  12. use App\Services\PointsService;
  13. use App\Services\TaskCenterService;
  14. use Dflydev\DotAccessData\Util;
  15. use GuzzleHttp\Client;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Log;
  18. use Illuminate\Support\Facades\Redis;
  19. use OSS\Core\OssException;
  20. use OSS\OssClient;
  21. class AnimeService
  22. {
  23. protected $aiImageGenerationService;
  24. protected $aiVideoGenerationService;
  25. protected $DeepSeekService;
  26. protected $pointsService;
  27. protected $taskCenterService;
  28. private $url;
  29. private $api_key;
  30. private $headers;
  31. public function __construct(
  32. AIImageGenerationService $aiImageGenerationService,
  33. AIVideoGenerationService $aiVideoGenerationService,
  34. DeepSeekService $DeepSeekService,
  35. PointsService $pointsService,
  36. TaskCenterService $taskCenterService
  37. ) {
  38. $this->aiImageGenerationService = $aiImageGenerationService;
  39. $this->aiVideoGenerationService = $aiVideoGenerationService;
  40. $this->DeepSeekService = $DeepSeekService;
  41. $this->pointsService = $pointsService;
  42. $this->taskCenterService = $taskCenterService;
  43. $this->url = 'https://api.deepseek.com/chat/completions';
  44. $this->api_key = env('DEEPSEEK_API_KEY');
  45. $this->headers = [
  46. 'Authorization' => 'Bearer '.$this->api_key,
  47. 'Content-Type' => 'application/json; charset=UTF-8'
  48. ];
  49. }
  50. /**
  51. * 构建统一的分镜数据结构(episodeInfo格式)
  52. * @param array $segments 分镜数据数组
  53. * @return array 返回包含acts和total_duration的数组
  54. */
  55. public function buildEpisodeSegmentsStructure($segments) {
  56. $acts = [];
  57. $totalDuration = 0; // 初始化总时长
  58. foreach($segments as $segment) {
  59. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  60. $videoDuration = getProp($segment, 'video_duration');
  61. $audioDuration = getProp($segment, 'audio_duration');
  62. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  63. $totalDuration += floatval($videoDuration);
  64. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  65. $totalDuration += floatval($audioDuration);
  66. } else {
  67. $totalDuration += 5; // 默认5秒
  68. }
  69. $segment_content = getProp($segment, 'segment_content');
  70. // 判断是否有尾帧描述,如果有则去掉这部分内容
  71. if (strpos($segment_content, '尾帧') !== false) {
  72. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  73. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  74. }
  75. // 构建分镜信息
  76. $segmentInfo = [
  77. 'segment_id' => getProp($segment, 'segment_id'),
  78. 'segment_number' => getProp($segment, 'segment_number'),
  79. 'segment_content' => $segment_content,
  80. 'description' => getProp($segment, 'description'),
  81. 'composition' => getProp($segment, 'composition'),
  82. 'camera_movement' => getProp($segment, 'camera_movement'),
  83. 'voice_actor' => getProp($segment, 'voice_actor'),
  84. 'dialogue' => getProp($segment, 'dialogue'),
  85. 'frame_type' => getProp($segment, 'frame_type'),
  86. 'scene' => getProp($segment, 'scene'),
  87. 'characters' => getProp($segment, 'characters'),
  88. 'tail_frame' => getProp($segment, 'tail_frame'),
  89. 'emotion' => getProp($segment, 'emotion'),
  90. 'emotion_type' => getProp($segment, 'emotion_type'),
  91. 'gender' => getProp($segment, 'gender'),
  92. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  93. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  94. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  95. 'pitch' => getProp($segment, 'pitch'),
  96. 'voice_name' => getProp($segment, 'voice_name'),
  97. 'voice_type' => getProp($segment, 'voice_type'),
  98. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  99. 'img_url' => getProp($segment, 'img_url'),
  100. 'audio_url' => getProp($segment, 'audio_url'),
  101. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  102. 'video_url' => getProp($segment, 'video_url'),
  103. 'video_duration' => getProp($segment, 'video_duration', 0),
  104. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  105. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  106. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  107. 'current_type' => getProp($segment, 'current_type'),
  108. ];
  109. $actNumber = getProp($segment, 'act_number');
  110. if (isset($acts[$actNumber])) {
  111. $acts[$actNumber]['segments'][] = $segmentInfo;
  112. } else {
  113. $acts[$actNumber] = [
  114. 'act_number' => $actNumber,
  115. 'act_title' => getProp($segment, 'act_title'),
  116. 'act_duration' => getProp($segment, 'act_duration'),
  117. 'segments' => [$segmentInfo]
  118. ];
  119. }
  120. }
  121. return [
  122. 'acts' => array_values($acts),
  123. 'total_duration' => intval(round($totalDuration))
  124. ];
  125. }
  126. /**
  127. * 构建统一的分段数据结构(episodeInfoForAce格式)
  128. * @param array $segments 分段数据数组
  129. * @return array 返回包含acts和total_duration的数组
  130. */
  131. public function buildEpisodeActsStructureForAce($segments) {
  132. $acts = [];
  133. $totalDuration = 0; // 初始化总时长
  134. foreach($segments as $segment) {
  135. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  136. $videoDuration = getProp($segment, 'video_duration');
  137. $actDuration = getProp($segment, 'act_duration');
  138. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  139. $totalDuration += floatval($videoDuration);
  140. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  141. $totalDuration += floatval($actDuration);
  142. } else {
  143. $totalDuration += 5; // 默认5秒
  144. }
  145. // 构建分镜信息
  146. $segmentInfo = [
  147. 'act_id' => getProp($segment, 'id'),
  148. 'act_number' => getProp($segment, 'act_number'),
  149. 'act_title' => getProp($segment, 'act_title'),
  150. 'act_duration' => getProp($segment, 'act_duration'),
  151. 'act_content' => getProp($segment, 'act_content'),
  152. 'video_url' => getProp($segment, 'video_url'),
  153. 'video_duration' => getProp($segment, 'video_duration', 0),
  154. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  155. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  156. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  157. 'current_type' => getProp($segment, 'current_type'),
  158. ];
  159. $acts[] = $segmentInfo;
  160. }
  161. return [
  162. 'acts' => array_values($acts),
  163. 'total_duration' => intval(round($totalDuration))
  164. ];
  165. }
  166. /**
  167. * 验证画面比例是否有效
  168. * @param string $ratio 画面比例
  169. * @return bool
  170. */
  171. public function validateRatio($ratio) {
  172. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  173. }
  174. /**
  175. * 获取画面比例对应的宽高
  176. * @param string $ratio 画面比例
  177. * @return array ['width' => int, 'height' => int]
  178. * @throws \Exception
  179. */
  180. private function getRatioDimensions($ratio) {
  181. if ($ratio && !$this->validateRatio($ratio)) {
  182. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  183. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  184. }
  185. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  186. }
  187. public function createAnime($data) {
  188. $uid = Site::getUid();
  189. $cpid = Site::getCpid();
  190. $input_art_style = getProp($data, 'art_style');
  191. $file = getProp($data, 'file');
  192. $content = getProp($data, 'content', '');
  193. $bid = getProp($data, 'bid', 0);
  194. $script_id = getProp($data, 'script_id', 0);
  195. $ace_mode = getProp($data, 'ace_mode', 0);
  196. $extra_products = getProp($data, 'products', []);
  197. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  198. if (!is_array($extra_products)) {
  199. Utils::throwError('20003:传入的资产格式不正确');
  200. }
  201. // 替换美术风格
  202. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  203. // 提取文件内容
  204. if ($file) {
  205. $content = $this->DeepSeekService->extractFileContent($file);
  206. if (!$content) {
  207. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  208. }
  209. } elseif ($script_id) {
  210. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  211. if (!$content) {
  212. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  213. }
  214. } elseif ($bid) {
  215. $content = $this->DeepSeekService->getContentByBid($bid);
  216. if (!$content) {
  217. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  218. }
  219. } elseif ($content) {
  220. $content = filterContent($content);
  221. }else {
  222. $content = '';
  223. }
  224. $anime_data = [
  225. 'user_id' => $uid,
  226. 'cpid' => $cpid,
  227. 'anime_name' => '新剧本策划',
  228. 'is_multi' => getProp($data, 'is_multi', 1),
  229. 'content' => $content,
  230. 'art_style_type' => $input_art_style,
  231. 'ace_mode' => $ace_mode,
  232. 'script_id' => $script_id,
  233. 'extra_products' => json_encode($extra_products, 256),
  234. 'created_at' => date('Y-m-d H:i:s'),
  235. 'updated_at' => date('Y-m-d H:i:s'),
  236. ];
  237. // 处理文本模型
  238. $model = getProp($data, 'model');
  239. if (!$model) {
  240. // 用户没有输入,使用默认值
  241. $model = 'deepseek-v4-pro';
  242. }
  243. // 验证模型是否在可用模型表中
  244. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  245. $model = 'deepseek-v4-pro';
  246. }
  247. $anime_data['model'] = $model;
  248. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  249. return DB::table('mp_animes')->insertGetId($anime_data);
  250. }
  251. public function chatList($data) {
  252. $uid = Site::getUid();
  253. $anime_name = getProp($data, 'anime_name');
  254. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  255. if ($anime_name) {
  256. $query->where('anime_name', 'like', "%$anime_name%");
  257. }
  258. return $query->orderBy('id', 'desc')->paginate();
  259. }
  260. public function chatHistory($data) {
  261. $anime_id = getProp($data, 'anime_id');
  262. $sequence = getProp($data, 'sequence', 0);
  263. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  264. $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)
  265. ->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');
  266. return $query->orderBy('ar.id')->get()->map(function ($value) {
  267. $value = (array)$value;
  268. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  269. $value['created_at'] = transDate($value['created_at']);
  270. $value['episode_created_at'] = transDate($value['episode_created_at']);
  271. return $value;
  272. })->toArray();
  273. }
  274. public function batchSetRoleImg($data) {
  275. $episode_id = getProp($data, 'episode_id');
  276. if (!$episode_id) Utils::throwError('1002:请选择分集');
  277. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  278. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  279. $art_style = getProp($episode, 'art_style');
  280. $anime_id = getProp($episode, 'anime_id');
  281. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  282. $art_style_type = getProp($anime, 'art_style_type');
  283. $character_prefix = '';
  284. $scene_prefix = '';
  285. if ($art_style_type) {
  286. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  287. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  288. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  289. }
  290. foreach ($roles as &$role) {
  291. $role_name = getProp($role, 'role');
  292. if ($role_name == '旁白') continue;
  293. // 优先使用 pic_prompt,如果没有则使用 description
  294. $pic_prompt = getProp($role, 'pic_prompt');
  295. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  296. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  297. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  298. // 参考图地址
  299. $ref_img_url = getProp($role, 'url');
  300. if ($ref_img_url) continue; // 已有图片则跳过
  301. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  302. try {
  303. $params = [
  304. 'prompt' => $description,
  305. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  306. ];
  307. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  308. $task_id = $task->id;
  309. if (!$task_id) {
  310. Utils::throwError("20003:角色({$role_name})生成图片失败");
  311. }
  312. $role['task_id'] = $task_id;
  313. $role['task_status'] = 'processing';
  314. } catch (\Exception $e) {
  315. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  316. Utils::throwError("20003:" . $e->getMessage());
  317. }
  318. }
  319. // 保存角色信息
  320. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  321. 'roles' => json_encode($roles, 256),
  322. 'generate_status' => '执行中',
  323. 'generate_at' => date('Y-m-d H:i:s'),
  324. 'updated_at' => date('Y-m-d H:i:s')
  325. ]);
  326. if (!$boolen) {
  327. Utils::throwError('20003:保存角色信息失败');
  328. }
  329. return $boolen;
  330. }
  331. public function batchSetSceneImg($data) {
  332. $episode_id = getProp($data, 'episode_id');
  333. if (!$episode_id) Utils::throwError('1002:请选择分集');
  334. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  335. $scenes = json_decode(getProp($episode, 'scenes'), true);
  336. $art_style = getProp($episode, 'art_style');
  337. $target_scene = getProp($data, 'target_scene');
  338. $anime_id = getProp($episode, 'anime_id');
  339. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  340. $art_style_type = getProp($anime, 'art_style_type');
  341. $character_prefix = '';
  342. $scene_prefix = '';
  343. if ($art_style_type) {
  344. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  345. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  346. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  347. }
  348. foreach ($scenes as &$scene) {
  349. $scene_name = getProp($scene, 'scene');
  350. if ($scene_name != $target_scene) continue;
  351. // 优先使用 pic_prompt,如果没有则使用 description
  352. $pic_prompt = getProp($scene, 'pic_prompt');
  353. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  354. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  355. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  356. // 参考图地址
  357. $ref_img_url = getProp($scene, 'url');
  358. if ($ref_img_url) continue; // 已有图片则跳过
  359. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  360. try {
  361. $params = [
  362. 'prompt' => $description,
  363. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  364. ];
  365. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  366. $task_id = $task->id;
  367. if (!$task_id) {
  368. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  369. }
  370. $scene['task_id'] = $task_id;
  371. $scene['task_status'] = 'processing';
  372. } catch (\Exception $e) {
  373. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  374. Utils::throwError("20003:" . $e->getMessage());
  375. }
  376. }
  377. // 保存场景信息
  378. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  379. 'scenes' => json_encode($scenes, 256),
  380. 'generate_status' => '执行中',
  381. 'generate_at' => date('Y-m-d H:i:s'),
  382. 'updated_at' => date('Y-m-d H:i:s')
  383. ]);
  384. if (!$boolen) {
  385. Utils::throwError('20003:保存角色信息失败');
  386. }
  387. return $boolen;
  388. }
  389. public function editAnime($data) {
  390. $anime_id = getProp($data, 'anime_id');
  391. $anime_name = trim(getProp($data, 'anime_name'));
  392. // 确认对话名称唯一性
  393. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  394. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  395. }
  396. if (!$anime_id || !$anime_name) {
  397. Utils::throwError('20003:参数异常');
  398. }
  399. return DB::table('mp_animes')->where('id', $anime_id)->update([
  400. 'anime_name' => $anime_name,
  401. 'updated_at' => date('Y-m-d H:i:s')
  402. ]);
  403. // $script_arr =getProp($data, 'script', []);
  404. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  405. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  406. // $anime_id = getProp($data, 'anime_id');
  407. // try {
  408. // DB::beginTransaction();
  409. // $table_data = [
  410. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  411. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  412. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  413. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  414. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  415. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  416. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  417. // 'status' => 3,
  418. // 'start_episode_sequence' => $start_episode_sequence,
  419. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  420. // 'episode_num' => count($script_arr['episodes']),
  421. // 'updated_at' => date('Y-m-d H:i:s')
  422. // ];
  423. // // 保存剧本内容
  424. // if (!empty($anime_id)) {
  425. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  426. // if (!$boolen) {
  427. // dLog('anime')->info('对话保存失败', $table_data);
  428. // Utils::throwError('20003:对话保存失败');
  429. // }
  430. // }else {
  431. // $table['created_at'] = $table_data['updated_at'];
  432. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  433. // if (!$anime_id) {
  434. // dLog('anime')->info('对话保存失败', $table_data);
  435. // Utils::throwError('20003:对话保存失败');
  436. // }
  437. // }
  438. // // 保存分集内容
  439. // // 删除历史分集内容
  440. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  441. // $episodes = [];
  442. // $sequence = 1;
  443. // foreach ($script_arr['episodes'] as $episode) {
  444. // $segment_number = 1;
  445. // foreach($episode['segments'] as $segment) {
  446. // $episodes[] = [
  447. // 'anime_id' => $anime_id,
  448. // 'episode_number' => $episode['episode_number'],
  449. // 'title' => $episode['title'],
  450. // // 'content' => $episode['content'],
  451. // 'content' => '',
  452. // 'segment_number' => $segment_number,
  453. // 'segment_content' => $segment['segment_content'],
  454. // 'sequence' => $sequence,
  455. // 'created_at' => date('Y-m-d H:i:s'),
  456. // 'updated_at' => date('Y-m-d H:i:s')
  457. // ];
  458. // $sequence++;
  459. // $segment_number++;
  460. // }
  461. // }
  462. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  463. // if (!$boolen2) {
  464. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  465. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  466. // Utils::throwError('20003:分集内容保存失败');
  467. // }
  468. // } catch (\Exception $e) {
  469. // DB::rollBack();
  470. // Utils::throwError('20003:'.$e->getMessage());
  471. // }
  472. // DB::commit();
  473. // return true;
  474. }
  475. public function delAnime($data) {
  476. $anime_id = getProp($data, 'anime_id');
  477. if (!$anime_id) {
  478. Utils::throwError('20003:请选择剧本');
  479. }
  480. return DB::table('mp_animes')->where('id', $anime_id)->update([
  481. 'is_deleted' => 1,
  482. 'updated_at' => date('Y-m-d H:i:s')
  483. ]);
  484. }
  485. public function animeDetail($data) {
  486. $uid = Site::getUid();
  487. $anime_id = getProp($data, 'anime_id');
  488. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  489. ->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();
  490. if (!$anime) Utils::throwError('20003:权限不足');
  491. $anime = (array)$anime;
  492. $anime['roles'] = json_decode($anime['roles']);
  493. $anime['scenes'] = json_decode($anime['scenes']);
  494. // 获取分集信息
  495. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  496. ->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"))
  497. ->orderBy('episode_number')->get()->map(function ($value) {
  498. return (array)$value;
  499. })->toArray();
  500. $anime['episodes'] = $episodes;
  501. // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
  502. $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
  503. $episodeTasks = DB::table('mp_batch_episode_generation_details')
  504. ->where('anime_id', $anime_id)
  505. ->orderBy('episode_number')
  506. ->get()
  507. ->map(function ($task) use ($episodeNumbers) {
  508. if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
  509. return null;
  510. }
  511. $item = [
  512. 'episode_number' => (int)$task->episode_number,
  513. 'status' => $task->status,
  514. 'error_message' => $task->status === 'failed' ? ($task->error_message ?? '') : '',
  515. ];
  516. return $item;
  517. })
  518. ->filter()
  519. ->values()
  520. ->toArray();
  521. $anime['episode_tasks'] = $episodeTasks;
  522. return $anime;
  523. }
  524. public function episodeInfo($data) {
  525. $uid = Site::getUid();
  526. $anime_id = getProp($data, 'anime_id');
  527. $episode_id = getProp($data, 'episode_id');
  528. if (!$anime_id || !$episode_id) {
  529. Utils::throwError('1002:请选择剧集');
  530. }
  531. // 验证用户权限
  532. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  533. if (!$anime) Utils::throwError('20003:权限不足');
  534. $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();
  535. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  536. $episode = (array)$episode;
  537. $episode['roles'] = json_decode($episode['roles'], true);
  538. // foreach($episode['roles'] as &$item) {
  539. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  540. // }
  541. $episode['scenes'] = json_decode($episode['scenes'], true);
  542. // foreach($episode['scenes'] as &$item) {
  543. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  544. // }
  545. // 获取分镜信息
  546. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  547. ->select('*')->get()->map(function ($value) {
  548. return (array)$value;
  549. })->toArray();
  550. // 使用公共方法构建分镜结构
  551. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  552. $episode['acts'] = $segmentsStructure['acts'];
  553. $episode['total_duration'] = $segmentsStructure['total_duration'];
  554. return $episode;
  555. }
  556. public function episodeInfoForAce($data) {
  557. $anime_id = getProp($data, 'anime_id');
  558. $episode_id = getProp($data, 'episode_id');
  559. if (!$anime_id || !$episode_id) {
  560. Utils::throwError('1002:请选择剧集');
  561. }
  562. $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();
  563. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  564. $episode = (array)$episode;
  565. $episode['roles'] = json_decode($episode['roles'], true);
  566. // foreach($episode['roles'] as &$item) {
  567. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  568. // }
  569. $episode['scenes'] = json_decode($episode['scenes'], true);
  570. // foreach($episode['scenes'] as &$item) {
  571. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  572. // }
  573. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  574. // 获取分镜信息
  575. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  576. ->select('*')->get()->map(function ($value) {
  577. return (array)$value;
  578. })->toArray();
  579. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  580. $episode['acts'] = $segmentsStructure['acts'];
  581. $episode['total_duration'] = $segmentsStructure['total_duration'];
  582. // 获取mp_animes表中的视频参数
  583. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  584. $episode['video_params'] = [
  585. 'video_model' => getProp($anime, 'video_model'),
  586. 'video_resolution' => getProp($anime, 'video_resolution'),
  587. 'ratio' => getProp($anime, 'video_ratio'),
  588. ];
  589. return $episode;
  590. }
  591. public function segmentInfo($data) {
  592. $uid = Site::getUid();
  593. $segment_id = getProp($data, 'segment_id');
  594. if (!$segment_id) {
  595. Utils::throwError('1002:请选择分镜');
  596. }
  597. // 获取分镜信息
  598. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  599. // 验证用户权限
  600. if ($segment) {
  601. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  602. if (!$anime) Utils::throwError('20003:权限不足');
  603. }
  604. $result = [
  605. 'segment_id' => getProp($segment, 'segment_id'),
  606. 'segment_number' => getProp($segment, 'segment_number'),
  607. 'segment_content' => getProp($segment, 'segment_content'),
  608. 'description' => getProp($segment, 'description'),
  609. 'composition' => getProp($segment, 'composition'),
  610. 'camera_movement' => getProp($segment, 'camera_movement'),
  611. 'voice_actor' => getProp($segment, 'voice_actor'),
  612. 'dialogue' => getProp($segment, 'dialogue'),
  613. 'frame_type' => getProp($segment, 'frame_type'),
  614. 'scene' => getProp($segment, 'scene'),
  615. 'characters' => getProp($segment, 'characters'),
  616. 'tail_frame' => getProp($segment, 'tail_frame'),
  617. 'emotion' => getProp($segment, 'emotion'),
  618. 'emotion_type' => getProp($segment, 'emotion_type'),
  619. 'gender' => getProp($segment, 'gender'),
  620. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  621. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  622. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  623. 'pitch' => getProp($segment, 'pitch'),
  624. 'voice_name' => getProp($segment, 'voice_name'),
  625. 'voice_type' => getProp($segment, 'voice_type'),
  626. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  627. 'img_url' => getProp($segment, 'img_url'),
  628. 'video_url' => getProp($segment, 'video_url'),
  629. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  630. ];
  631. return $result;
  632. }
  633. public function copyEpisodeVersion($data) {
  634. $episode_id = getProp($data, 'episode_id');
  635. $uid = Site::getUid();
  636. $cpid = Site::getCpid();
  637. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  638. if (!$episode) Utils::throwError('20003:该剧集不存在');
  639. $episode = (array)$episode;
  640. $anime_id = $episode['anime_id'];
  641. $episode_number = $episode['episode_number'];
  642. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  643. $sequence = $count + 1;
  644. unset($episode['id']);
  645. $now = date('Y-m-d H:i:s');
  646. $episode['created_at'] = $now;
  647. $episode['updated_at'] = $now;
  648. $episode['is_default'] = 1;
  649. // 获取版本中含有"(副本"字样的个数
  650. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  651. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  652. $episode['sequence'] = $sequence;
  653. $episode['is_generated'] = 0;
  654. $episode['cpid'] = $cpid;
  655. // 获取ace_mode
  656. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  657. try {
  658. DB::beginTransaction();
  659. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  660. // 新增副本
  661. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  662. if (!$new_episode_id) {
  663. Utils::throwError('20003:创建副本失败!');
  664. }
  665. // 获取分镜数据并准备插入
  666. $segments_for_insert = DB::table('mp_episode_segments')
  667. ->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')
  668. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  669. $item = (array)$item;
  670. $item['episode_id'] = $new_episode_id;
  671. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  672. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  673. return $item;
  674. })->toArray();
  675. // 写入分镜数据
  676. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  677. if (!$boolen2) {
  678. Utils::throwError('20003:写入分镜数据失败!');
  679. }
  680. // 写入对话历史
  681. $records = [
  682. [
  683. 'uid' => $uid,
  684. 'anime_id' => $anime_id,
  685. 'role' => 'user',
  686. 'content' => '创建副本',
  687. 'sequence' => $episode_number,
  688. 'episode_id' => $new_episode_id,
  689. 'created_at' => $now,
  690. 'updated_at' => $now
  691. ],
  692. [
  693. 'uid' => $uid,
  694. 'anime_id' => $anime_id,
  695. 'role' => 'assistant',
  696. 'content' => '好的,已为您创建副本',
  697. 'sequence' => $episode_number,
  698. 'episode_id' => $new_episode_id,
  699. 'created_at' => $now,
  700. 'updated_at' => $now
  701. ]
  702. ];
  703. $boolen3 = DB::table('mp_anime_records')->insert($records);
  704. if (!$boolen3) {
  705. Utils::throwError('20003:对话记录保存失败');
  706. }
  707. }catch (\Exception $e) {
  708. DB::rollBack();
  709. Utils::throwError('20003:'.$e->getMessage());
  710. }
  711. DB::commit();
  712. // 构建与 episodeInfo 方法一致的返回数据结构
  713. $result = [
  714. 'episode_id' => $new_episode_id,
  715. 'anime_id' => $anime_id,
  716. 'episode_number' => $episode_number,
  717. 'title' => $episode['title'],
  718. 'intro' => $episode['intro'],
  719. 'art_style' => $episode['art_style'],
  720. 'roles' => json_decode($episode['roles'], true),
  721. 'scenes' => json_decode($episode['scenes'], true),
  722. 'is_generated' => (int)$episode['is_generated']
  723. ];
  724. if ((int)$ace_mode === 1) {
  725. // 获取分镜信息
  726. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  727. ->select('*')->get()->map(function ($value) {
  728. return (array)$value;
  729. })->toArray();
  730. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  731. }else {
  732. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  733. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  734. }
  735. $result['acts'] = $segmentsStructure['acts'];
  736. $result['total_duration'] = $segmentsStructure['total_duration'];
  737. return $result;
  738. }
  739. public function episodeVersions($data) {
  740. $anime_id = getProp($data, 'anime_id');
  741. $episode_id = getProp($data, 'episode_id');
  742. if (!$anime_id || !$episode_id) {
  743. Utils::throwError('1002:请选择剧集');
  744. }
  745. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  746. $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) {
  747. return (array)$value;
  748. })->toArray();
  749. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  750. foreach($episodes as &$episode) {
  751. $episode['version'] = 'V'.$episode['sequence'];
  752. $episode['roles'] = json_decode($episode['roles'], true);
  753. $episode['scenes'] = json_decode($episode['scenes'], true);
  754. // 获取分镜信息
  755. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  756. ->select('*')->get()->map(function ($value) {
  757. return (array)$value;
  758. })->toArray();
  759. // 使用公共方法构建分镜结构
  760. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  761. $episode['acts'] = $segmentsStructure['acts'];
  762. $episode['total_duration'] = $segmentsStructure['total_duration'];
  763. }
  764. return $episodes;
  765. }
  766. public function bindEpisodeVersion($data) {
  767. $episode_id = getProp($data, 'episode_id');
  768. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  769. if (!$episode) Utils::throwError('20003:该剧集不存在');
  770. $episode = (array)$episode;
  771. if ((int)$episode['is_default'] === 1) return true;
  772. try {
  773. DB::beginTransaction();
  774. // 移除is_default标志
  775. $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')]);
  776. if (!$boolen) {
  777. Utils::throwError('20003:更新失败!');
  778. }
  779. // 绑定副本
  780. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  781. if (!$boolen2) {
  782. Utils::throwError('20003:绑定失败!');
  783. }
  784. }catch (\Exception $e) {
  785. DB::rollBack();
  786. Utils::throwError('20003:'.$e->getMessage());
  787. }
  788. DB::commit();
  789. return true;
  790. }
  791. public function chatChangeImg($data) {
  792. $segment_id = getProp($data, 'segment_id');
  793. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  794. $prompt = getProp($data, 'prompt');
  795. if (!$prompt || !$segment_id) {
  796. Utils::throwError('1002:请输入提示词,并且选择分镜');
  797. }
  798. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  799. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  800. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  801. else $ref_img_url = '';
  802. // $ref_img_url = '';
  803. if (empty($prompt)) {
  804. if (empty($ref_img_url)) {
  805. $prompt = getProp($segment, 'segment_content');
  806. }else {
  807. $prompt = '请根据图片生成';
  808. }
  809. }
  810. $anime_id = getProp($segment, 'anime_id');
  811. $episode_id = getProp($segment, 'episode_id');
  812. $episode_number = getProp($segment, 'episode_number');
  813. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  814. $ratio = getProp($data, 'ratio');
  815. if (!$ratio) {
  816. $ratio = getProp($episode, 'ratio');
  817. if (!$ratio) $ratio = '9:16';
  818. }
  819. $art_style = getProp($episode, 'art_style');
  820. if ($art_style) {
  821. $prompt = "美术风格:{$art_style}\n{$prompt}";
  822. }
  823. $dimensions = $this->getRatioDimensions($ratio);
  824. $width = $dimensions['width'];
  825. $height = $dimensions['height'];
  826. try {
  827. $params = [
  828. 'alias_segment_id' => $segment_id,
  829. 'prompt' => $prompt,
  830. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  831. 'width' => $width,
  832. 'height' => $height
  833. ];
  834. // 优化提示词(不要生成字幕)
  835. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  836. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  837. $task_id = $task->id;
  838. if (!$task_id) {
  839. Utils::throwError("20003:生成图片失败");
  840. }
  841. // 更新任务ID
  842. $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')]);
  843. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  844. } catch (\Exception $e) {
  845. Utils::throwError("20003:" . $e->getMessage());
  846. }
  847. // 创建任务之后先暂停10s等待异步任务完成
  848. sleep(10);
  849. $img_url = $this->loopGetPicTaskResult($task_id);
  850. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  851. // 图片生成后新增对话记录
  852. try {
  853. $uid = Site::getUid();
  854. $now = date('Y-m-d H:i:s');
  855. // 使用AI反推图片提示词
  856. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  857. // 保存对话记录
  858. $records = [
  859. [
  860. 'uid' => $uid,
  861. 'anime_id' => $anime_id,
  862. 'sequence' => $episode_number,
  863. 'role' => 'user',
  864. 'content' => $prompt,
  865. 'segment_id' => $segment_id,
  866. 'pic_task_id' => $task_id,
  867. 'image_url' => '',
  868. 'created_at' => $now,
  869. 'updated_at' => $now
  870. ],
  871. [
  872. 'uid' => $uid,
  873. 'anime_id' => $anime_id,
  874. 'sequence' => $episode_number,
  875. 'role' => 'assistant',
  876. 'content' => $pic_prompt,
  877. 'segment_id' => $segment_id,
  878. 'pic_task_id' => $task_id,
  879. 'image_url' => $img_url,
  880. 'created_at' => $now,
  881. 'updated_at' => $now
  882. ]
  883. ];
  884. DB::table('mp_anime_records')->insert($records);
  885. } catch (\Exception $e) {
  886. // 记录日志但不影响主流程
  887. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  888. 'segment_id' => $segment_id,
  889. 'img_url' => $img_url
  890. ]);
  891. logDB('anime', 'error', '保存对话记录失败', [
  892. 'segment_id' => $segment_id,
  893. 'img_url' => $img_url,
  894. 'error' => $e->getMessage()
  895. ]);
  896. }
  897. return $img_url;
  898. }
  899. public function segmentChatHistory($data) {
  900. $segment_id = getProp($data, 'segment_id');
  901. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  902. $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');
  903. $chat = $query->orderBy('id')->get()->map(function ($value) {
  904. $value = (array)$value;
  905. $value['created_at'] = transDate($value['created_at']);
  906. return $value;
  907. })->toArray();
  908. // 获取历史图片
  909. $url = [];
  910. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  911. foreach($pic_history as $task) {
  912. $result_url = getProp($task, 'result_url');
  913. if (is_json($result_url)) {
  914. $url = array_merge($url, json_decode($result_url, true));
  915. }else {
  916. $url[] = $result_url;
  917. }
  918. }
  919. // 获取历史视频
  920. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  921. foreach($video_history as $task) {
  922. $result_url = getProp($task, 'compressed_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. return compact('chat', 'url');
  930. }
  931. public function changeEpisodeRoles($data) {
  932. $anime_id = getProp($data, 'anime_id');
  933. $episode_id = getProp($data, 'episode_id');
  934. $target_roles = getProp($data, 'roles');
  935. $is_deleted = getProp($data, 'is_deleted', 0);
  936. // 参数验证
  937. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  938. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  939. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  940. // 验证剧集是否存在
  941. $episode = DB::table('mp_anime_episodes')
  942. ->where('anime_id', $anime_id)
  943. ->where('id', $episode_id)
  944. ->first();
  945. if (!$episode) Utils::throwError('20003:该剧集不存在');
  946. $roles = json_decode(getProp($episode, 'roles'), true);
  947. // 获取anime信息,检查是否有关联的script_id
  948. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  949. if (!$anime) Utils::throwError('20003:动漫不存在');
  950. $script_id = getProp($anime, 'script_id');
  951. $episode_number = getProp($episode, 'episode_number', 1);
  952. $uid = Site::getUid();
  953. $cpid = Site::getCpid();
  954. try {
  955. $target_role_name = getProp($target_roles, 'role');
  956. if (empty($target_role_name)) {
  957. Utils::throwError('20003:角色名称不能为空');
  958. }
  959. // 如果是删除操作
  960. if ($is_deleted == 1) {
  961. // 从角色列表中移除该角色
  962. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  963. return getProp($role, 'role') !== $target_role_name;
  964. }));
  965. // 更新角色列表
  966. $result = DB::table('mp_anime_episodes')
  967. ->where('anime_id', $anime_id)
  968. ->where('id', $episode_id)
  969. ->update([
  970. 'roles' => json_encode($roles, 256),
  971. 'updated_at' => date('Y-m-d H:i:s')
  972. ]);
  973. if ($result === false) {
  974. Utils::throwError('20003:删除角色失败');
  975. }
  976. } else {
  977. // 新增或更新操作
  978. $role_found = false;
  979. $is_new_role = false;
  980. // 查找并更新已存在的角色
  981. foreach($roles as &$role) {
  982. if (getProp($role, 'role') === $target_role_name) {
  983. $role = $target_roles;
  984. $role_found = true;
  985. break;
  986. }
  987. }
  988. // 如果角色不存在,则新增
  989. if (!$role_found) {
  990. $roles[] = $target_roles;
  991. $is_new_role = true;
  992. }
  993. // 更新角色列表
  994. $result = DB::table('mp_anime_episodes')
  995. ->where('anime_id', $anime_id)
  996. ->where('id', $episode_id)
  997. ->update([
  998. 'roles' => json_encode($roles, 256),
  999. 'updated_at' => date('Y-m-d H:i:s')
  1000. ]);
  1001. if ($result === false) {
  1002. Utils::throwError('20003:更新角色列表失败');
  1003. }
  1004. // 同步更新分镜表中对应主体的音色信息
  1005. $voice_name = getProp($target_roles, 'voice_name');
  1006. $voice_type = getProp($target_roles, 'voice_type');
  1007. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  1008. DB::table('mp_episode_segments')
  1009. ->where('anime_id', $anime_id)
  1010. ->where('episode_id', $episode_id)
  1011. ->where('voice_actor', $target_role_name)
  1012. ->update([
  1013. 'voice_name' => $voice_name,
  1014. 'voice_type' => $voice_type,
  1015. 'voice_audio_url' => $voice_audio_url,
  1016. 'updated_at' => date('Y-m-d H:i:s')
  1017. ]);
  1018. // 如果有关联的script_id,则同步到mp_products表
  1019. if ($script_id) {
  1020. // 查询剧本信息
  1021. $script = DB::table('mp_scripts')
  1022. ->where('id', $script_id)
  1023. ->where('is_deleted', 0)
  1024. ->first();
  1025. if ($script) {
  1026. $script_name = $script->script_name ?? 'script_' . $script_id;
  1027. $product_name = getProp($target_roles, 'role');
  1028. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1029. $url = getProp($target_roles, 'url', '');
  1030. $product_type = 1; // 1=角色
  1031. // 查找或创建以script_name命名的文件夹
  1032. $folder = DB::table('mp_products')
  1033. ->where('cpid', $cpid)
  1034. ->where('type', 2) // 文件夹类型
  1035. ->where('product', $product_type) // 角色类型
  1036. ->where('product_name', $script_name)
  1037. ->where('parent_id', 0)
  1038. ->where('is_deleted', 0)
  1039. ->first();
  1040. if (!$folder) {
  1041. // 创建文件夹
  1042. $folder_id = DB::table('mp_products')->insertGetId([
  1043. 'user_id' => $uid,
  1044. 'cpid' => $cpid,
  1045. 'type' => 2, // 文件夹
  1046. 'product' => $product_type, // 角色类型
  1047. 'parent_id' => 0,
  1048. 'level' => 1,
  1049. 'product_name' => $script_name,
  1050. 'sort_order' => time(),
  1051. 'is_deleted' => 0,
  1052. 'created_at' => date('Y-m-d H:i:s'),
  1053. 'updated_at' => date('Y-m-d H:i:s')
  1054. ]);
  1055. } else {
  1056. $folder_id = $folder->id;
  1057. }
  1058. // 查找该文件夹下是否已存在同名资产
  1059. $existing_product = DB::table('mp_products')
  1060. ->where('cpid', $cpid)
  1061. ->where('type', 1) // 资产类型
  1062. ->where('product', $product_type)
  1063. ->where('parent_id', $folder_id)
  1064. ->where('product_name', $product_name)
  1065. ->where('is_deleted', 0)
  1066. ->first();
  1067. if ($existing_product) {
  1068. // 更新已存在的资产
  1069. $updateData = [
  1070. 'pic_task_status' => '生成成功',
  1071. ];
  1072. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1073. if ($url) $updateData['url'] = $url;
  1074. // 处理versions字段
  1075. $versions = getProp($target_roles, 'versions', []);
  1076. if ($versions && is_array($versions)) {
  1077. $updateData['versions'] = json_encode($versions, 256);
  1078. }
  1079. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1080. DB::table('mp_products')
  1081. ->where('id', $existing_product->id)
  1082. ->update($updateData);
  1083. $product_id = $existing_product->id;
  1084. } else {
  1085. // 创建新资产
  1086. $versions = getProp($target_roles, 'versions', []);
  1087. $product_id = DB::table('mp_products')->insertGetId([
  1088. 'user_id' => $uid,
  1089. 'cpid' => $cpid,
  1090. 'type' => 1, // 资产
  1091. 'product' => $product_type, // 角色
  1092. 'parent_id' => $folder_id,
  1093. 'level' => 2,
  1094. 'product_name' => $product_name,
  1095. 'url' => $url,
  1096. 'pic_prompt' => $pic_prompt,
  1097. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1098. 'sort_order' => time(),
  1099. 'is_deleted' => 0,
  1100. 'pic_task_status' => '生成成功',
  1101. 'created_at' => date('Y-m-d H:i:s'),
  1102. 'updated_at' => date('Y-m-d H:i:s')
  1103. ]);
  1104. }
  1105. // 建立或更新绑定关系
  1106. $existing_mapping = DB::table('mp_script_product_mappings')
  1107. ->where('script_id', $script_id)
  1108. ->where('product_id', $product_id)
  1109. ->where('episode_number', $episode_number)
  1110. ->first();
  1111. if (!$existing_mapping) {
  1112. // 创建绑定关系
  1113. DB::table('mp_script_product_mappings')->insert([
  1114. 'script_id' => $script_id,
  1115. 'product_id' => $product_id,
  1116. 'episode_number' => $episode_number,
  1117. 'created_at' => date('Y-m-d H:i:s'),
  1118. 'updated_at' => date('Y-m-d H:i:s')
  1119. ]);
  1120. }
  1121. }
  1122. }
  1123. }
  1124. } catch (\Exception $e) {
  1125. dLog('anime')->error('更新剧集角色失败', [
  1126. 'anime_id' => $anime_id,
  1127. 'episode_id' => $episode_id,
  1128. 'error' => $e->getMessage()
  1129. ]);
  1130. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1131. }
  1132. return true;
  1133. }
  1134. public function changeEpisodeScenes($data) {
  1135. $anime_id = getProp($data, 'anime_id');
  1136. $episode_id = getProp($data, 'episode_id');
  1137. $target_scenes = getProp($data, 'scenes');
  1138. $is_deleted = getProp($data, 'is_deleted', 0);
  1139. // 参数验证
  1140. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1141. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1142. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1143. // 验证剧集是否存在
  1144. $episode = DB::table('mp_anime_episodes')
  1145. ->where('anime_id', $anime_id)
  1146. ->where('id', $episode_id)
  1147. ->first();
  1148. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1149. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1150. // 获取anime信息,检查是否有关联的script_id
  1151. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1152. if (!$anime) Utils::throwError('20003:动漫不存在');
  1153. $script_id = getProp($anime, 'script_id');
  1154. $episode_number = getProp($episode, 'episode_number', 1);
  1155. $uid = Site::getUid();
  1156. $cpid = Site::getCpid();
  1157. try {
  1158. $target_scene_name = getProp($target_scenes, 'scene');
  1159. if (empty($target_scene_name)) {
  1160. Utils::throwError('20003:场景名称不能为空');
  1161. }
  1162. // 如果是删除操作
  1163. if ($is_deleted == 1) {
  1164. // 从场景列表中移除该场景
  1165. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1166. return getProp($scene, 'scene') !== $target_scene_name;
  1167. }));
  1168. // 更新场景列表
  1169. $result = DB::table('mp_anime_episodes')
  1170. ->where('anime_id', $anime_id)
  1171. ->where('id', $episode_id)
  1172. ->update([
  1173. 'scenes' => json_encode($scenes, 256),
  1174. 'updated_at' => date('Y-m-d H:i:s')
  1175. ]);
  1176. if ($result === false) {
  1177. Utils::throwError('20003:删除场景失败');
  1178. }
  1179. } else {
  1180. // 新增或更新操作
  1181. $scene_found = false;
  1182. $is_new_scene = false;
  1183. // 查找并更新已存在的场景
  1184. foreach($scenes as &$scene) {
  1185. if (getProp($scene, 'scene') === $target_scene_name) {
  1186. $scene = $target_scenes;
  1187. $scene_found = true;
  1188. break;
  1189. }
  1190. }
  1191. // 如果场景不存在,则新增
  1192. if (!$scene_found) {
  1193. $scenes[] = $target_scenes;
  1194. $is_new_scene = true;
  1195. }
  1196. // 更新场景列表
  1197. $result = DB::table('mp_anime_episodes')
  1198. ->where('anime_id', $anime_id)
  1199. ->where('id', $episode_id)
  1200. ->update([
  1201. 'scenes' => json_encode($scenes, 256),
  1202. 'updated_at' => date('Y-m-d H:i:s')
  1203. ]);
  1204. if ($result === false) {
  1205. Utils::throwError('20003:更新场景列表失败');
  1206. }
  1207. // 如果有关联的script_id,则同步到mp_products表
  1208. if ($script_id) {
  1209. // 查询剧本信息
  1210. $script = DB::table('mp_scripts')
  1211. ->where('id', $script_id)
  1212. ->where('is_deleted', 0)
  1213. ->first();
  1214. if ($script) {
  1215. $script_name = $script->script_name ?? 'script_' . $script_id;
  1216. $product_name = getProp($target_scenes, 'scene');
  1217. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1218. $url = getProp($target_scenes, 'url', '');
  1219. $product_type = 2; // 2=场景
  1220. // 查找或创建以script_name命名的文件夹
  1221. $folder = DB::table('mp_products')
  1222. ->where('cpid', $cpid)
  1223. ->where('type', 2) // 文件夹类型
  1224. ->where('product', $product_type) // 场景类型
  1225. ->where('product_name', $script_name)
  1226. ->where('parent_id', 0)
  1227. ->where('is_deleted', 0)
  1228. ->first();
  1229. if (!$folder) {
  1230. // 创建文件夹
  1231. $folder_id = DB::table('mp_products')->insertGetId([
  1232. 'user_id' => $uid,
  1233. 'cpid' => $cpid,
  1234. 'type' => 2, // 文件夹
  1235. 'product' => $product_type, // 场景类型
  1236. 'parent_id' => 0,
  1237. 'level' => 1,
  1238. 'product_name' => $script_name,
  1239. 'sort_order' => time(),
  1240. 'is_deleted' => 0,
  1241. 'created_at' => date('Y-m-d H:i:s'),
  1242. 'updated_at' => date('Y-m-d H:i:s')
  1243. ]);
  1244. } else {
  1245. $folder_id = $folder->id;
  1246. }
  1247. // 查找该文件夹下是否已存在同名资产
  1248. $existing_product = DB::table('mp_products')
  1249. ->where('cpid', $cpid)
  1250. ->where('type', 1) // 资产类型
  1251. ->where('product', $product_type)
  1252. ->where('parent_id', $folder_id)
  1253. ->where('product_name', $product_name)
  1254. ->where('is_deleted', 0)
  1255. ->first();
  1256. if ($existing_product) {
  1257. // 更新已存在的资产
  1258. $updateData = [
  1259. 'pic_task_status' => '生成成功'
  1260. ];
  1261. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1262. if ($url) $updateData['url'] = $url;
  1263. // 处理versions字段
  1264. $versions = getProp($target_scenes, 'versions', []);
  1265. if ($versions && is_array($versions)) {
  1266. $updateData['versions'] = json_encode($versions, 256);
  1267. }
  1268. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1269. DB::table('mp_products')
  1270. ->where('id', $existing_product->id)
  1271. ->update($updateData);
  1272. $product_id = $existing_product->id;
  1273. } else {
  1274. // 创建新资产
  1275. $versions = getProp($target_scenes, 'versions', []);
  1276. $product_id = DB::table('mp_products')->insertGetId([
  1277. 'user_id' => $uid,
  1278. 'cpid' => $cpid,
  1279. 'type' => 1, // 资产
  1280. 'product' => $product_type, // 场景
  1281. 'parent_id' => $folder_id,
  1282. 'level' => 2,
  1283. 'product_name' => $product_name,
  1284. 'url' => $url,
  1285. 'pic_prompt' => $pic_prompt,
  1286. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1287. 'sort_order' => time(),
  1288. 'is_deleted' => 0,
  1289. 'pic_task_status' => '生成成功',
  1290. 'created_at' => date('Y-m-d H:i:s'),
  1291. 'updated_at' => date('Y-m-d H:i:s')
  1292. ]);
  1293. }
  1294. // 建立或更新绑定关系
  1295. $existing_mapping = DB::table('mp_script_product_mappings')
  1296. ->where('script_id', $script_id)
  1297. ->where('product_id', $product_id)
  1298. ->where('episode_number', $episode_number)
  1299. ->first();
  1300. if (!$existing_mapping) {
  1301. // 创建绑定关系
  1302. DB::table('mp_script_product_mappings')->insert([
  1303. 'script_id' => $script_id,
  1304. 'product_id' => $product_id,
  1305. 'episode_number' => $episode_number,
  1306. 'created_at' => date('Y-m-d H:i:s'),
  1307. 'updated_at' => date('Y-m-d H:i:s')
  1308. ]);
  1309. }
  1310. }
  1311. }
  1312. }
  1313. } catch (\Exception $e) {
  1314. dLog('anime')->error('更新剧集场景失败', [
  1315. 'anime_id' => $anime_id,
  1316. 'episode_id' => $episode_id,
  1317. 'error' => $e->getMessage()
  1318. ]);
  1319. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1320. }
  1321. return true;
  1322. }
  1323. public function changeEpisodeProps($data) {
  1324. $anime_id = getProp($data, 'anime_id');
  1325. $episode_id = getProp($data, 'episode_id');
  1326. $target_props = getProp($data, 'props');
  1327. $is_deleted = getProp($data, 'is_deleted', 0);
  1328. // 参数验证
  1329. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1330. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1331. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1332. // 验证剧集是否存在
  1333. $episode = DB::table('mp_anime_episodes')
  1334. ->where('anime_id', $anime_id)
  1335. ->where('id', $episode_id)
  1336. ->first();
  1337. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1338. $props = json_decode(getProp($episode, 'props'), true);
  1339. // 获取anime信息,检查是否有关联的script_id
  1340. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1341. if (!$anime) Utils::throwError('20003:动漫不存在');
  1342. $script_id = getProp($anime, 'script_id');
  1343. $episode_number = getProp($episode, 'episode_number', 1);
  1344. $uid = Site::getUid();
  1345. $cpid = Site::getCpid();
  1346. try {
  1347. $target_prop_name = getProp($target_props, 'prop');
  1348. if (empty($target_prop_name)) {
  1349. Utils::throwError('20003:道具名称不能为空');
  1350. }
  1351. // 如果是删除操作
  1352. if ($is_deleted == 1) {
  1353. // 从道具列表中移除该道具
  1354. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1355. return getProp($prop, 'prop') !== $target_prop_name;
  1356. }));
  1357. // 更新道具列表
  1358. $result = DB::table('mp_anime_episodes')
  1359. ->where('anime_id', $anime_id)
  1360. ->where('id', $episode_id)
  1361. ->update([
  1362. 'props' => json_encode($props, 256),
  1363. 'updated_at' => date('Y-m-d H:i:s')
  1364. ]);
  1365. if ($result === false) {
  1366. Utils::throwError('20003:删除道具失败');
  1367. }
  1368. } else {
  1369. // 新增或更新操作
  1370. $prop_found = false;
  1371. $is_new_prop = false;
  1372. // 查找并更新已存在的道具
  1373. foreach($props as &$prop) {
  1374. if (getProp($prop, 'prop') === $target_prop_name) {
  1375. $prop = $target_props;
  1376. $prop_found = true;
  1377. break;
  1378. }
  1379. }
  1380. // 如果道具不存在,则新增
  1381. if (!$prop_found) {
  1382. $props[] = $target_props;
  1383. $is_new_prop = true;
  1384. }
  1385. // 更新道具列表
  1386. $result = DB::table('mp_anime_episodes')
  1387. ->where('anime_id', $anime_id)
  1388. ->where('id', $episode_id)
  1389. ->update([
  1390. 'props' => json_encode($props, 256),
  1391. 'updated_at' => date('Y-m-d H:i:s')
  1392. ]);
  1393. if ($result === false) {
  1394. Utils::throwError('20003:更新道具列表失败');
  1395. }
  1396. // 如果有关联的script_id,则同步到mp_products表
  1397. if ($script_id) {
  1398. // 查询剧本信息
  1399. $script = DB::table('mp_scripts')
  1400. ->where('id', $script_id)
  1401. ->where('is_deleted', 0)
  1402. ->first();
  1403. if ($script) {
  1404. $script_name = $script->script_name ?? 'script_' . $script_id;
  1405. $product_name = getProp($target_props, 'prop');
  1406. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1407. $url = getProp($target_props, 'url', '');
  1408. $product_type = 3; // 3=道具
  1409. // 查找或创建以script_name命名的文件夹
  1410. $folder = DB::table('mp_products')
  1411. ->where('cpid', $cpid)
  1412. ->where('type', 2) // 文件夹类型
  1413. ->where('product', $product_type) // 道具类型
  1414. ->where('product_name', $script_name)
  1415. ->where('parent_id', 0)
  1416. ->where('is_deleted', 0)
  1417. ->first();
  1418. if (!$folder) {
  1419. // 创建文件夹
  1420. $folder_id = DB::table('mp_products')->insertGetId([
  1421. 'user_id' => $uid,
  1422. 'cpid' => $cpid,
  1423. 'type' => 2, // 文件夹
  1424. 'product' => $product_type, // 道具类型
  1425. 'parent_id' => 0,
  1426. 'level' => 1,
  1427. 'product_name' => $script_name,
  1428. 'sort_order' => time(),
  1429. 'is_deleted' => 0,
  1430. 'created_at' => date('Y-m-d H:i:s'),
  1431. 'updated_at' => date('Y-m-d H:i:s')
  1432. ]);
  1433. } else {
  1434. $folder_id = $folder->id;
  1435. }
  1436. // 查找该文件夹下是否已存在同名资产
  1437. $existing_product = DB::table('mp_products')
  1438. ->where('cpid', $cpid)
  1439. ->where('type', 1) // 资产类型
  1440. ->where('product', $product_type)
  1441. ->where('parent_id', $folder_id)
  1442. ->where('product_name', $product_name)
  1443. ->where('is_deleted', 0)
  1444. ->first();
  1445. if ($existing_product) {
  1446. // 更新已存在的资产
  1447. $updateData = [
  1448. 'pic_task_status' => '生成成功'
  1449. ];
  1450. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1451. if ($url) $updateData['url'] = $url;
  1452. // 处理versions字段
  1453. $versions = getProp($target_props, 'versions', []);
  1454. if ($versions && is_array($versions)) {
  1455. $updateData['versions'] = json_encode($versions, 256);
  1456. }
  1457. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1458. DB::table('mp_products')
  1459. ->where('id', $existing_product->id)
  1460. ->update($updateData);
  1461. $product_id = $existing_product->id;
  1462. } else {
  1463. // 创建新资产
  1464. $versions = getProp($target_props, 'versions', []);
  1465. $product_id = DB::table('mp_products')->insertGetId([
  1466. 'user_id' => $uid,
  1467. 'cpid' => $cpid,
  1468. 'type' => 1, // 资产
  1469. 'product' => $product_type, // 道具
  1470. 'parent_id' => $folder_id,
  1471. 'level' => 2,
  1472. 'product_name' => $product_name,
  1473. 'url' => $url,
  1474. 'pic_prompt' => $pic_prompt,
  1475. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1476. 'sort_order' => time(),
  1477. 'is_deleted' => 0,
  1478. 'pic_task_status' => '生成成功',
  1479. 'created_at' => date('Y-m-d H:i:s'),
  1480. 'updated_at' => date('Y-m-d H:i:s')
  1481. ]);
  1482. }
  1483. // 建立或更新绑定关系
  1484. $existing_mapping = DB::table('mp_script_product_mappings')
  1485. ->where('script_id', $script_id)
  1486. ->where('product_id', $product_id)
  1487. ->where('episode_number', $episode_number)
  1488. ->first();
  1489. if (!$existing_mapping) {
  1490. // 创建绑定关系
  1491. DB::table('mp_script_product_mappings')->insert([
  1492. 'script_id' => $script_id,
  1493. 'product_id' => $product_id,
  1494. 'episode_number' => $episode_number,
  1495. 'created_at' => date('Y-m-d H:i:s'),
  1496. 'updated_at' => date('Y-m-d H:i:s')
  1497. ]);
  1498. }
  1499. }
  1500. }
  1501. }
  1502. } catch (\Exception $e) {
  1503. dLog('anime')->error('更新剧集道具失败', [
  1504. 'anime_id' => $anime_id,
  1505. 'episode_id' => $episode_id,
  1506. 'error' => $e->getMessage()
  1507. ]);
  1508. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1509. }
  1510. return true;
  1511. }
  1512. public function editSegment($data) {
  1513. $segment_id = getProp($data, 'segment_id');
  1514. $segment_content = getProp($data, 'segment_content');
  1515. $image_url = getProp($data, 'image_url');
  1516. $video_url = getProp($data, 'video_url');
  1517. // 参数验证
  1518. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1519. // 验证分镜是否存在
  1520. $segment = DB::table('mp_episode_segments')
  1521. ->where('segment_id', $segment_id)
  1522. ->first();
  1523. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1524. $dubTaskId = 0;
  1525. try {
  1526. DB::beginTransaction();
  1527. // 准备更新数据
  1528. $update_data = [
  1529. 'updated_at' => date('Y-m-d H:i:s')
  1530. ];
  1531. if ($segment_content) {
  1532. // 先将segment_content赋值到update_data
  1533. $update_data['segment_content'] = $segment_content;
  1534. // 使用现有方法分析segment_content,提取各个字段
  1535. $this->handleSegmentContent($update_data);
  1536. // 如果有对话内容,创建视频配音合成任务
  1537. $dialogue = getProp($update_data, 'dialogue');
  1538. if (!empty($dialogue)) {
  1539. $now = date('Y-m-d H:i:s');
  1540. $generate_json = [
  1541. 'text' => $dialogue,
  1542. 'role' => getProp($update_data, 'voice_actor'),
  1543. 'voice_type' => getProp($update_data, 'voice_type'),
  1544. 'voice_name' => getProp($update_data, 'voice_name'),
  1545. 'emotion' => getProp($update_data, 'emotion'),
  1546. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1547. 'gender' => getProp($update_data, 'gender'),
  1548. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1549. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1550. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1551. 'pitch' => getProp($update_data, 'pitch', 0),
  1552. ];
  1553. // 插入视频配音合成任务
  1554. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1555. 'alias_segment_id' => $segment_id,
  1556. 'generate_status' => '执行中',
  1557. 'audio_url' => '',
  1558. 'generate_json' => json_encode($generate_json, 256),
  1559. 'created_at' => $now,
  1560. 'updated_at' => $now,
  1561. ]);
  1562. if (!$dubTaskId) {
  1563. Utils::throwError('20003:创建配音任务失败!');
  1564. }
  1565. $update_data['audio_url'] = '';
  1566. } else {
  1567. // dialogue为空时,直接写入默认音频信息
  1568. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1569. $update_data['audio_duration'] = 2.0;
  1570. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1571. }
  1572. }
  1573. if ($image_url) {
  1574. $update_data['img_url'] = $image_url;
  1575. // 同时写入一个简单的图片生成任务
  1576. $pic_task = [
  1577. 'alias_segment_id' => $segment_id,
  1578. 'ref_img_url' => json_encode([]),
  1579. 'status' => 'success',
  1580. 'result_url' => json_encode([$image_url], 256),
  1581. 'model' => '',
  1582. 'created_at' => date('Y-m-d H:i:s'),
  1583. 'updated_at' => date('Y-m-d H:i:s'),
  1584. ];
  1585. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1586. }
  1587. if ($video_url) {
  1588. $update_data['origin_video_url'] = $video_url;
  1589. $compressed_video_url = compressVideo($video_url);
  1590. $update_data['current_type'] = 2;
  1591. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1592. // 同时写入一个简单的视频生成任务
  1593. $video_task = [
  1594. 'alias_segment_id' => $segment_id,
  1595. 'status' => 'success',
  1596. 'result_url' => $update_data['origin_video_url'],
  1597. 'compressed_url' => $update_data['video_url'],
  1598. 'created_at' => date('Y-m-d H:i:s'),
  1599. 'updated_at' => date('Y-m-d H:i:s'),
  1600. ];
  1601. DB::table('mp_generate_video_tasks')->insert($video_task);
  1602. }
  1603. // 更新分镜信息
  1604. $result = DB::table('mp_episode_segments')
  1605. ->where('segment_id', $segment_id)
  1606. ->update($update_data);
  1607. if ($result === false) {
  1608. Utils::throwError('20003:更新分镜剧本失败');
  1609. }
  1610. DB::commit();
  1611. // 如果有创建音频生成任务则调用API
  1612. if ($dubTaskId) {
  1613. // 请求远程服务器执行生成
  1614. $client = new Client(['timeout' => 300, 'verify' => false]);
  1615. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1616. $response = $result->getBody()->getContents();
  1617. $response_arr = json_decode($response, true);
  1618. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1619. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1620. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1621. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1622. Utils::throwError('20003:火山生成音频失败');
  1623. }
  1624. }
  1625. return true;
  1626. } catch (\Exception $e) {
  1627. DB::rollBack();
  1628. dLog('anime')->error('更新分镜剧本失败', [
  1629. 'segment_id' => $segment_id,
  1630. 'error' => $e->getMessage()
  1631. ]);
  1632. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1633. }
  1634. }
  1635. public function batchSetSegmentPics($data) {
  1636. $anime_id = getProp($data, 'anime_id');
  1637. $episode_id = getProp($data, 'episode_id');
  1638. $ratio = getProp($data, 'ratio');
  1639. $dimensions = $this->getRatioDimensions($ratio);
  1640. $width = $dimensions['width'];
  1641. $height = $dimensions['height'];
  1642. if (!$anime_id || !$episode_id) {
  1643. Utils::throwError('1002:请选择剧集');
  1644. }
  1645. // 获取剧集信息
  1646. $episode = DB::table('mp_anime_episodes')
  1647. ->where('anime_id', $anime_id)
  1648. ->where('id', $episode_id)
  1649. ->where('is_default', 1)
  1650. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1651. ->first();
  1652. if (!$episode) {
  1653. Utils::throwError('20003:该剧集不存在');
  1654. }
  1655. $model = getProp($data, 'model');
  1656. if (!$model) {
  1657. $model = getProp($episode, 'image_model');
  1658. if (!$model) {
  1659. // episode表也没有,使用默认值
  1660. $model = 'doubao-seedream-5-0-lite-260128';
  1661. }
  1662. }
  1663. // 验证模型是否在可用模型表中
  1664. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1665. $model = 'doubao-seedream-5-0-lite-260128';
  1666. }
  1667. $roles = json_decode(getProp($episode, 'roles'), true);
  1668. if (!$roles) {
  1669. Utils::throwError('20003:角色信息格式错误');
  1670. }
  1671. // 构建角色名称到参考图的映射
  1672. $role_map = [];
  1673. foreach ($roles as $role) {
  1674. $role_name = getProp($role, 'role');
  1675. $role_url = getProp($role, 'url');
  1676. if (!empty($role_name) && !empty($role_url)) {
  1677. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1678. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1679. // $role_map[$base_name] = $role_url;
  1680. // 同时保存完整名称的映射
  1681. $role_map[$role_name] = $role_url;
  1682. }
  1683. }
  1684. $scenes = json_decode(getProp($episode, 'roles'), true);
  1685. if (!$scenes) {
  1686. Utils::throwError('20003:场景信息格式错误');
  1687. }
  1688. // 构建角色名称到参考图的映射
  1689. $scene_map = [];
  1690. foreach ($scenes as $scene) {
  1691. $scene_name = getProp($scene, 'scene');
  1692. $scene_url = getProp($scene, 'url');
  1693. if (!empty($scene_name) && !empty($scene_url)) {
  1694. $scene_map[$scene_name] = $scene_url;
  1695. }
  1696. }
  1697. // 获取所有分镜信息
  1698. $segments = DB::table('mp_episode_segments')
  1699. ->where('anime_id', $anime_id)
  1700. ->where('episode_id', $episode_id)
  1701. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1702. ->orderBy('segment_number')
  1703. ->get()
  1704. ->toArray();
  1705. if (empty($segments)) {
  1706. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1707. }
  1708. // 保存图片比例
  1709. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1710. $updated_segments = [];
  1711. $failed_segments = [];
  1712. // 批量为每个分镜生成图片任务
  1713. foreach ($segments as $segment) {
  1714. $segment_id = $segment->segment_id;
  1715. $segment_content = $segment->segment_content;
  1716. if (empty($segment_content)) {
  1717. $failed_segments[] = [
  1718. 'segment_id' => $segment_id,
  1719. 'error' => '分镜内容为空'
  1720. ];
  1721. continue;
  1722. }
  1723. try {
  1724. $dubTaskId = 0;
  1725. // 解析分镜内容,提取画面描述作为主要提示词
  1726. $prompt = $segment_content;
  1727. $ref_img_urls = [];
  1728. // 分镜场景
  1729. $scene = getProp($segment, 'scene');
  1730. $matched_scene = '';
  1731. if (isset($scene_map[$scene])) {
  1732. $img_index = count($ref_img_urls) + 1;
  1733. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1734. $ref_img_urls[] = $scene_map[$scene];
  1735. $matched_scene = $scene;
  1736. }
  1737. // 分镜角色
  1738. $characters = getProp($segment, 'characters');
  1739. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1740. $roles = explode(',', $characters);
  1741. // 从分镜内容中提取涉及的角色
  1742. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1743. // 获取匹配角色的参考图
  1744. foreach ($segment_characters as $character) {
  1745. if (isset($role_map[$character])) {
  1746. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1747. $img_index = count($ref_img_urls) + 1;
  1748. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1749. $ref_img_urls[] = $role_map[$character];
  1750. }
  1751. }
  1752. // 如果没有找到匹配的角色参考图,不使用参考图
  1753. if (empty($ref_img_urls)) {
  1754. $ref_img_urls = [];
  1755. }
  1756. // 准备生成任务参数
  1757. $params = [
  1758. 'model' => $model,
  1759. 'alias_segment_id' => $segment_id,
  1760. 'prompt' => $prompt,
  1761. 'ref_img_urls' => $ref_img_urls,
  1762. 'width' => $width,
  1763. 'height' => $height,
  1764. ];
  1765. // 优化提示词(不要生成字幕)
  1766. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1767. // $task_id = mt_rand(100000, 999999);
  1768. // 调用AI图片生成服务
  1769. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1770. $task_id = $task->id;
  1771. if (!$task_id) {
  1772. $failed_segments[] = [
  1773. 'segment_id' => $segment_id,
  1774. 'error' => '创建生成任务失败'
  1775. ];
  1776. continue;
  1777. }
  1778. $update_data = [
  1779. 'pic_task_id' => $task_id,
  1780. 'pic_task_status' => '生成中',
  1781. 'audio_url' => '',
  1782. 'updated_at' => date('Y-m-d H:i:s')
  1783. ];
  1784. // 如果有对话内容,创建视频配音合成任务
  1785. $dialogue = getProp($segment, 'dialogue');
  1786. if (!empty($dialogue)) {
  1787. $now = date('Y-m-d H:i:s');
  1788. $generate_json = [
  1789. 'text' => $dialogue,
  1790. 'role' => getProp($segment, 'voice_actor'),
  1791. 'voice_type' => getProp($segment, 'voice_type'),
  1792. 'voice_name' => getProp($segment, 'voice_name'),
  1793. 'emotion' => getProp($segment, 'emotion'),
  1794. 'emotion_type' => getProp($segment, 'emotion_type'),
  1795. 'gender' => getProp($segment, 'gender'),
  1796. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1797. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1798. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1799. 'pitch' => getProp($segment, 'pitch', 0),
  1800. ];
  1801. // 插入视频配音合成任务
  1802. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1803. 'alias_segment_id' => $segment_id,
  1804. 'generate_status' => '执行中',
  1805. 'audio_url' => '',
  1806. 'generate_json' => json_encode($generate_json, 256),
  1807. 'created_at' => $now,
  1808. 'updated_at' => $now,
  1809. ]);
  1810. if (!$dubTaskId) {
  1811. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1812. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1813. // Utils::throwError('20003:创建配音任务失败!');
  1814. }
  1815. } else {
  1816. // dialogue为空时,直接写入默认音频信息到分镜表
  1817. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1818. $update_data['audio_duration'] = 2.0;
  1819. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1820. }
  1821. // 更新分镜的任务信息
  1822. $update_result = DB::table('mp_episode_segments')
  1823. ->where('segment_id', $segment_id)
  1824. ->update($update_data);
  1825. // 如果是第一集的首帧图片,则存入待更新数组
  1826. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1827. Redis::sadd('anime_first_frame_urls', $segment_id);
  1828. }
  1829. if ($update_result) {
  1830. $updated_segments[] = [
  1831. 'segment_id' => $segment_id,
  1832. 'task_id' => $task_id,
  1833. 'status' => '生成中',
  1834. 'matched_scenes' => $matched_scene,
  1835. 'matched_roles' => $segment_characters,
  1836. 'ref_urls_count' => count($ref_img_urls)
  1837. ];
  1838. } else {
  1839. $failed_segments[] = [
  1840. 'segment_id' => $segment_id,
  1841. 'error' => '更新分镜任务状态失败'
  1842. ];
  1843. }
  1844. if ($dubTaskId) {
  1845. sleep(1);
  1846. // 请求远程服务器执行生成
  1847. $client = new Client(['timeout' => 300, 'verify' => false]);
  1848. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1849. $response = $result->getBody()->getContents();
  1850. $response_arr = json_decode($response, true);
  1851. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1852. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1853. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1854. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1855. }
  1856. }
  1857. } catch (\Exception $e) {
  1858. $failed_segments[] = [
  1859. 'segment_id' => $segment_id,
  1860. 'error' => $e->getMessage()
  1861. ];
  1862. }
  1863. }
  1864. // 更新剧集生成状态
  1865. if (!empty($updated_segments)) {
  1866. DB::table('mp_anime_episodes')
  1867. ->where('id', $episode_id)
  1868. ->update([
  1869. 'is_generated' => 1,
  1870. 'updated_at' => date('Y-m-d H:i:s')
  1871. ]);
  1872. }
  1873. return [
  1874. 'success_count' => count($updated_segments),
  1875. 'failed_count' => count($failed_segments),
  1876. 'success_segments' => $updated_segments,
  1877. 'failed_segments' => $failed_segments,
  1878. 'total_segments' => count($segments)
  1879. ];
  1880. }
  1881. public function reGenerateSegment($data) {
  1882. $segment_id = getProp($data, 'segment_id');
  1883. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1884. $anime_id = getProp($segment, 'anime_id');
  1885. $episode_id = getProp($segment, 'episode_id');
  1886. $episode_number = getProp($segment, 'episode_number');
  1887. $segment_content = getProp($data, 'segment_content');
  1888. $ratio = getProp($data, 'ratio');
  1889. if (!$ratio) {
  1890. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1891. if (!$ratio) $ratio = '9:16';
  1892. }
  1893. $dimensions = $this->getRatioDimensions($ratio);
  1894. $width = $dimensions['width'];
  1895. $height = $dimensions['height'];
  1896. if (!$anime_id || !$episode_id) {
  1897. Utils::throwError('1002:请选择分镜');
  1898. }
  1899. // 使用文生文模型重新解析segment_content
  1900. if (!empty($segment_content)) {
  1901. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1902. }
  1903. // 获取动漫的角色信息(包含参考图)
  1904. $anime = DB::table('mp_animes')
  1905. ->where('id', $anime_id)
  1906. ->select('roles', 'scenes')
  1907. ->first();
  1908. if (!$anime || !$anime->roles) {
  1909. Utils::throwError('20003:未找到角色信息');
  1910. }
  1911. $roles = json_decode($anime->roles, true);
  1912. if (!$roles) {
  1913. Utils::throwError('20003:角色信息格式错误');
  1914. }
  1915. // 构建角色名称到参考图的映射
  1916. $role_map = [];
  1917. foreach ($roles as $role) {
  1918. $role_name = getProp($role, 'role');
  1919. $role_url = getProp($role, 'url');
  1920. if (!empty($role_name) && !empty($role_url)) {
  1921. $role_map[$role_name] = $role_url;
  1922. }
  1923. }
  1924. $scenes = json_decode($anime->scenes, true);
  1925. if (!$scenes) {
  1926. Utils::throwError('20003:角色信息格式错误');
  1927. }
  1928. // 构建角色名称到参考图的映射
  1929. $scene_map = [];
  1930. foreach ($scenes as $scene) {
  1931. $scene_name = getProp($scene, 'scene');
  1932. $scene_url = getProp($scene, 'url');
  1933. if (!empty($scene_name) && !empty($scene_url)) {
  1934. $scene_map[$scene_name] = $scene_url;
  1935. }
  1936. }
  1937. $segment_id = $segment->segment_id;
  1938. $original_segment_content = $segment->segment_content;
  1939. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1940. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1941. if (empty($final_segment_content)) {
  1942. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1943. }
  1944. try {
  1945. $dubTaskId = 0;
  1946. // 分镜剧本数组
  1947. $update_data = [
  1948. 'segment_content' => $final_segment_content,
  1949. 'pic_task_status' => '生成中',
  1950. 'updated_at' => date('Y-m-d H:i:s')
  1951. ];
  1952. // 解析分镜内容,提取画面描述作为主要提示词
  1953. $prompt = $final_segment_content;
  1954. $ref_img_urls = [];
  1955. // 分镜场景
  1956. $scene = getProp($data, 'scene');
  1957. if ($scene) {
  1958. $matched_scene = '';
  1959. if (isset($scene_map[$scene])) {
  1960. $img_index = count($ref_img_urls) + 1;
  1961. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1962. $ref_img_urls[] = $scene_map[$scene];
  1963. $matched_scene = $scene;
  1964. }
  1965. $update_data['scene'] = $scene;
  1966. }
  1967. // 分镜角色
  1968. $characters = getProp($data, 'characters');
  1969. if ($characters) {
  1970. $update_data['characters'] = $characters;
  1971. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1972. $characters = explode(',', $characters);
  1973. // 从分镜内容中提取涉及的角色
  1974. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1975. // 获取匹配角色的参考图
  1976. foreach ($segment_characters as $character) {
  1977. if (isset($role_map[$character])) {
  1978. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1979. $img_index = count($ref_img_urls) + 1;
  1980. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1981. $ref_img_urls[] = $role_map[$character];
  1982. }
  1983. }
  1984. }
  1985. // 如果没有找到匹配的角色参考图,不使用参考图
  1986. if (empty($ref_img_urls)) {
  1987. $ref_img_urls = [];
  1988. }
  1989. // 准备生成任务参数
  1990. $params = [
  1991. 'alias_segment_id' => $segment_id,
  1992. 'prompt' => $prompt,
  1993. 'ref_img_urls' => $ref_img_urls,
  1994. 'width' => $width,
  1995. 'height' => $height,
  1996. ];
  1997. // 优化提示词(不要生成字幕)
  1998. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1999. // 调用AI图片生成服务
  2000. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2001. $task_id = $task->id;
  2002. if (!$task_id) {
  2003. Utils::throwError('20003:创建生成任务失败!');
  2004. }
  2005. $update_data['pic_task_id'] = $task_id;
  2006. // 更新分镜剧本信息
  2007. $this->handleSegmentContent($update_data);
  2008. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2009. if ($segment_content) {
  2010. $dialogue = getProp($update_data, 'dialogue');
  2011. if (!empty($dialogue)) {
  2012. $now = date('Y-m-d H:i:s');
  2013. $generate_json = [
  2014. 'text' => $dialogue,
  2015. 'role' => getProp($update_data, 'voice_actor'),
  2016. 'voice_type' => getProp($update_data, 'voice_type'),
  2017. 'voice_name' => getProp($update_data, 'voice_name'),
  2018. 'emotion' => getProp($update_data, 'emotion'),
  2019. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2020. 'gender' => getProp($update_data, 'gender'),
  2021. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2022. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2023. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2024. 'pitch' => getProp($update_data, 'pitch', 0),
  2025. ];
  2026. // 插入视频配音合成任务
  2027. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2028. 'alias_segment_id' => $segment_id,
  2029. 'generate_status' => '执行中',
  2030. 'audio_url' => '',
  2031. 'generate_json' => json_encode($generate_json, 256),
  2032. 'created_at' => date('Y-m-d H:i:s'),
  2033. 'updated_at' => date('Y-m-d H:i:s'),
  2034. ]);
  2035. if (!$dubTaskId) {
  2036. Utils::throwError('20003:创建配音任务失败!');
  2037. }
  2038. $update_data['audio_url'] = '';
  2039. } else {
  2040. // dialogue为空时,直接写入默认音频信息
  2041. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2042. $update_data['audio_duration'] = 2.0;
  2043. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2044. }
  2045. }
  2046. $boolen = DB::table('mp_episode_segments')
  2047. ->where('segment_id', $segment_id)
  2048. ->update($update_data);
  2049. // 如果是第一集的首帧图片,则存入待更新数组
  2050. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2051. Redis::sadd('anime_first_frame_urls', $segment_id);
  2052. }
  2053. if ($dubTaskId) {
  2054. // 请求远程服务器执行生成
  2055. $client = new Client(['timeout' => 300, 'verify' => false]);
  2056. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2057. $response = $result->getBody()->getContents();
  2058. $response_arr = json_decode($response, true);
  2059. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2060. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2061. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2062. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2063. Utils::throwError('20003:火山生成音频失败');
  2064. }
  2065. }
  2066. } catch (\Exception $e) {
  2067. $failed_segments[] = [
  2068. 'segment_id' => $segment_id,
  2069. 'error' => $e->getMessage()
  2070. ];
  2071. }
  2072. // 创建任务之后先暂停10s等待异步任务完成
  2073. sleep(10);
  2074. $img_url = $this->loopGetPicTaskResult($task_id);
  2075. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2076. // 图片生成后新增对话记录
  2077. try {
  2078. $uid = Site::getUid();
  2079. $now = date('Y-m-d H:i:s');
  2080. // 使用AI反推图片提示词
  2081. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2082. // 保存对话记录
  2083. $records = [
  2084. [
  2085. 'uid' => $uid,
  2086. 'anime_id' => $anime_id,
  2087. 'sequence' => $episode_number,
  2088. 'role' => 'user',
  2089. 'content' => '重新生成',
  2090. 'segment_id' => $segment_id,
  2091. 'pic_task_id' => $task_id,
  2092. 'image_url' => '',
  2093. 'created_at' => $now,
  2094. 'updated_at' => $now
  2095. ],
  2096. [
  2097. 'uid' => $uid,
  2098. 'anime_id' => $anime_id,
  2099. 'sequence' => $episode_number,
  2100. 'role' => 'assistant',
  2101. 'content' => $pic_prompt,
  2102. 'segment_id' => $segment_id,
  2103. 'pic_task_id' => $task_id,
  2104. 'image_url' => $img_url,
  2105. 'created_at' => $now,
  2106. 'updated_at' => $now
  2107. ]
  2108. ];
  2109. DB::table('mp_anime_records')->insert($records);
  2110. } catch (\Exception $e) {
  2111. // 记录日志但不影响主流程
  2112. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2113. 'segment_id' => $segment_id,
  2114. 'img_url' => $img_url
  2115. ]);
  2116. }
  2117. return $img_url;
  2118. }
  2119. public function addSegment($data) {
  2120. $prev_segment_id = getProp($data, 'prev_segment_id');
  2121. $img_url = getProp($data, 'img_url');
  2122. $video_url = getProp($data, 'video_url');
  2123. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2124. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2125. $anime_id = getProp($segment, 'anime_id');
  2126. $episode_id = getProp($segment, 'episode_id');
  2127. $episode_number = getProp($segment, 'episode_number');
  2128. $segment_number = getProp($segment, 'segment_number');
  2129. $new_segment_number = $segment_number + 1;
  2130. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2131. // 分镜剧本数组
  2132. $insert_data = [
  2133. 'anime_id' => $anime_id,
  2134. 'episode_id' => $episode_id,
  2135. 'episode_number' => $episode_number,
  2136. 'act_number' => getProp($segment, 'act_number'),
  2137. 'act_title' => getProp($segment, 'act_title'),
  2138. 'segment_id' => $segment_id,
  2139. 'segment_number' => $new_segment_number,
  2140. 'segment_content' => '',
  2141. 'img_url' => '',
  2142. 'video_url' => '',
  2143. 'created_at' => date('Y-m-d H:i:s'),
  2144. 'updated_at' => date('Y-m-d H:i:s')
  2145. ];
  2146. if ($img_url) $insert_data['img_url'] = $img_url;
  2147. if ($video_url) {
  2148. $insert_data['origin_video_url'] = $video_url;
  2149. $insert_data['current_type'] = 2;
  2150. $compressed_video_url = compressVideo($video_url);
  2151. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2152. }
  2153. try {
  2154. DB::beginTransaction();
  2155. // 先更新序号
  2156. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2157. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2158. if (!$id) {
  2159. Utils::throwError('20003:新增分镜失败!');
  2160. }
  2161. }catch (\Exception $e) {
  2162. DB::rollBack();
  2163. Utils::throwError('20003:'.$e->getMessage());
  2164. }
  2165. DB::commit();
  2166. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2167. $segment = $segment ? (array)$segment : [];
  2168. return $segment;
  2169. // 以下代码暂弃用
  2170. $anime_id = getProp($segment, 'anime_id');
  2171. $episode_id = getProp($segment, 'episode_id');
  2172. $episode_number = getProp($segment, 'episode_number');
  2173. $segment_number = getProp($segment, 'segment_number');
  2174. $segment_content = getProp($data, 'segment_content');
  2175. $img_url = getProp($data, 'img_url');
  2176. $video_url = getProp($data, 'video_url');
  2177. $ratio = getProp($data, 'ratio');
  2178. $dimensions = $this->getRatioDimensions($ratio);
  2179. $width = $dimensions['width'];
  2180. $height = $dimensions['height'];
  2181. if (!$anime_id || !$episode_id) {
  2182. Utils::throwError('1002:请选择分镜');
  2183. }
  2184. // 使用文生文模型重新解析segment_content
  2185. if (!empty($segment_content)) {
  2186. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2187. }
  2188. // 获取动漫的角色信息(包含参考图)
  2189. $anime = DB::table('mp_animes')
  2190. ->where('id', $anime_id)
  2191. ->select('roles', 'scenes')
  2192. ->first();
  2193. if (!$anime || !$anime->roles) {
  2194. Utils::throwError('20003:未找到角色信息');
  2195. }
  2196. $roles = json_decode($anime->roles, true);
  2197. if (!$roles) {
  2198. Utils::throwError('20003:角色信息格式错误');
  2199. }
  2200. // 构建角色名称到参考图的映射
  2201. $role_map = [];
  2202. foreach ($roles as $role) {
  2203. $role_name = getProp($role, 'role');
  2204. $role_url = getProp($role, 'url');
  2205. if (!empty($role_name) && !empty($role_url)) {
  2206. $role_map[$role_name] = $role_url;
  2207. }
  2208. }
  2209. $scenes = json_decode($anime->scenes, true);
  2210. if (!$scenes) {
  2211. Utils::throwError('20003:角色信息格式错误');
  2212. }
  2213. // 构建角色名称到参考图的映射
  2214. $scene_map = [];
  2215. foreach ($scenes as $scene) {
  2216. $scene_name = getProp($scene, 'scene');
  2217. $scene_url = getProp($scene, 'url');
  2218. if (!empty($scene_name) && !empty($scene_url)) {
  2219. $scene_map[$scene_name] = $scene_url;
  2220. }
  2221. }
  2222. $segment_id = $segment->segment_id;
  2223. $original_segment_content = $segment->segment_content;
  2224. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2225. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2226. if (empty($final_segment_content)) {
  2227. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2228. }
  2229. try {
  2230. $dubTaskId = 0;
  2231. DB::beginTransaction();
  2232. $new_segment_number = $segment_number + 1;
  2233. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2234. // 分镜剧本数组
  2235. $insert_data = [
  2236. 'anime_id' => $anime_id,
  2237. 'episode_id' => $episode_id,
  2238. 'episode_number' => $episode_number,
  2239. 'act_number' => getProp($segment, 'act_number'),
  2240. 'act_title' => getProp($segment, 'act_title'),
  2241. 'segment_id' => $segment_id,
  2242. 'segment_number' => $new_segment_number,
  2243. 'segment_content' => $final_segment_content,
  2244. 'img_url' => $img_url,
  2245. 'video_url' => $video_url,
  2246. 'created_at' => date('Y-m-d H:i:s'),
  2247. 'updated_at' => date('Y-m-d H:i:s')
  2248. ];
  2249. // 更新分镜剧本信息
  2250. $this->handleSegmentContent($insert_data);
  2251. // 如果有对话内容,创建视频配音合成任务
  2252. $dialogue = getProp($insert_data, 'dialogue');
  2253. if (!empty($dialogue)) {
  2254. $now = date('Y-m-d H:i:s');
  2255. $generate_json = [
  2256. 'text' => $dialogue,
  2257. 'role' => getProp($insert_data, 'voice_actor'),
  2258. 'voice_type' => getProp($insert_data, 'voice_type'),
  2259. 'voice_name' => getProp($insert_data, 'voice_name'),
  2260. 'emotion' => getProp($insert_data, 'emotion'),
  2261. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2262. 'gender' => getProp($insert_data, 'gender'),
  2263. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2264. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2265. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2266. 'pitch' => getProp($insert_data, 'pitch', 0),
  2267. ];
  2268. // 插入视频配音合成任务
  2269. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2270. 'alias_segment_id' => $segment_id,
  2271. 'generate_status' => '执行中',
  2272. 'audio_url' => '',
  2273. 'generate_json' => json_encode($generate_json, 256),
  2274. 'created_at' => $now,
  2275. 'updated_at' => $now,
  2276. ]);
  2277. if (!$dubTaskId) {
  2278. Utils::throwError('20003:创建配音任务失败!');
  2279. }
  2280. $insert_data['audio_url'] = '';
  2281. } else {
  2282. // dialogue为空时,直接写入默认音频信息
  2283. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2284. $insert_data['audio_duration'] = 2.0;
  2285. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2286. }
  2287. // 如果没有上传图片则使用当前描述进行生成
  2288. if (!$img_url) {
  2289. // 解析分镜内容,提取画面描述作为主要提示词
  2290. $prompt = $final_segment_content;
  2291. $ref_img_urls = [];
  2292. // 分镜场景
  2293. $scene = getProp($insert_data, 'scene');
  2294. if ($scene) {
  2295. $matched_scene = '';
  2296. if (isset($scene_map[$scene])) {
  2297. $img_index = count($ref_img_urls) + 1;
  2298. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2299. $ref_img_urls[] = $scene_map[$scene];
  2300. $matched_scene = $scene;
  2301. }
  2302. $update_data['scene'] = $scene;
  2303. }
  2304. // 分镜角色
  2305. $characters = getProp($insert_data, 'characters');
  2306. if ($characters) {
  2307. $update_data['characters'] = $characters;
  2308. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2309. $characters = explode(',', $characters);
  2310. // 从分镜内容中提取涉及的角色
  2311. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2312. // 获取匹配角色的参考图
  2313. foreach ($segment_characters as $character) {
  2314. if (isset($role_map[$character])) {
  2315. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2316. $img_index = count($ref_img_urls) + 1;
  2317. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2318. $ref_img_urls[] = $role_map[$character];
  2319. }
  2320. }
  2321. }
  2322. // 如果没有找到匹配的角色参考图,不使用参考图
  2323. if (empty($ref_img_urls)) {
  2324. $ref_img_urls = [];
  2325. }
  2326. // 准备生成任务参数
  2327. $params = [
  2328. 'alias_segment_id' => $segment_id,
  2329. 'prompt' => $prompt,
  2330. 'ref_img_urls' => $ref_img_urls,
  2331. 'width' => $width,
  2332. 'height' => $height,
  2333. ];
  2334. // 调用AI图片生成服务
  2335. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2336. $task_id = $task->id;
  2337. // $task_id = 'whatever';
  2338. if (!$task_id) {
  2339. Utils::throwError('20003:创建生成任务失败!');
  2340. }
  2341. $insert_data['pic_task_status'] = '生成中';
  2342. $insert_data['pic_task_id'] = $task_id;
  2343. }
  2344. // 先更新序号
  2345. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2346. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2347. if (!$boolen) {
  2348. Utils::throwError('20003:新增分镜失败!');
  2349. }
  2350. // 如果是第一集的首帧图片,则存入待更新数组
  2351. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2352. Redis::sadd('anime_first_frame_urls', $segment_id);
  2353. }
  2354. if ($dubTaskId) {
  2355. // 请求远程服务器执行生成
  2356. $client = new Client(['timeout' => 300, 'verify' => false]);
  2357. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2358. $response = $result->getBody()->getContents();
  2359. $response_arr = json_decode($response, true);
  2360. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2361. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2362. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2363. Utils::throwError('20003:火山生成音频失败');
  2364. }
  2365. }
  2366. } catch (\Exception $e) {
  2367. DB::rollBack();
  2368. Utils::throwError('20003:'.$e->getMessage());
  2369. }
  2370. DB::commit();
  2371. // 创建任务之后先暂停10s等待异步任务完成
  2372. sleep(10);
  2373. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2374. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2375. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2376. $segment = $segment ? (array)$segment : [];
  2377. return $segment;
  2378. }
  2379. public function copySegment($data) {
  2380. $segment_id = getProp($data, 'segment_id');
  2381. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2382. if (!$segment) Utils::throwError('20003:请选择分镜');
  2383. $anime_id = getProp($segment, 'anime_id');
  2384. $episode_id = getProp($segment, 'episode_id');
  2385. $episode_number = getProp($segment, 'episode_number');
  2386. $segment_number = getProp($segment, 'segment_number');
  2387. $new_segment_id = 0;
  2388. try {
  2389. DB::beginTransaction();
  2390. $segment = (array)$segment;
  2391. unset($segment['id']);
  2392. $segment['segment_number'] += 1;
  2393. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2394. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2395. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2396. // 更新其他分镜序号
  2397. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2398. // 复制分镜
  2399. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2400. if (!$id) {
  2401. Utils::throwError('20003:复制分镜失败');
  2402. }
  2403. }catch (\Exception $e) {
  2404. DB::rollBack();
  2405. Utils::throwError('20003:'.$e->getMessage());
  2406. }
  2407. DB::commit();
  2408. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2409. $segment = $segment ? (array)$segment : [];
  2410. return $segment;
  2411. }
  2412. public function moveSegment($data) {
  2413. $segment_id = getProp($data, 'segment_id');
  2414. $target_segment_id = getProp($data, 'target_segment_id');
  2415. // 获取源分镜信息
  2416. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2417. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2418. // 获取目标分镜信息
  2419. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2420. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2421. $anime_id = getProp($source_segment, 'anime_id');
  2422. $episode_id = getProp($source_segment, 'episode_id');
  2423. $episode_number = getProp($source_segment, 'episode_number');
  2424. $source_segment_number = getProp($source_segment, 'segment_number');
  2425. $target_segment_number = getProp($target_segment, 'segment_number');
  2426. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2427. $target_anime_id = getProp($target_segment, 'anime_id');
  2428. $target_episode_number = getProp($target_segment, 'episode_number');
  2429. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2430. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2431. }
  2432. // 如果源分镜和目标分镜相同,无需移动
  2433. if ($source_segment_number == $target_segment_number) {
  2434. return true;
  2435. }
  2436. try {
  2437. DB::beginTransaction();
  2438. if ($source_segment_number < $target_segment_number) {
  2439. // 向后移动:源分镜移动到目标分镜之后
  2440. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2441. DB::table('mp_episode_segments')
  2442. ->where('anime_id', $anime_id)
  2443. ->where('episode_id', $episode_id)
  2444. ->where('segment_number', '>', $source_segment_number)
  2445. ->where('segment_number', '<=', $target_segment_number)
  2446. ->decrement('segment_number');
  2447. // 2. 将源分镜移动到目标分镜之后
  2448. $new_segment_number = $target_segment_number;
  2449. } else {
  2450. // 向前移动:源分镜移动到目标分镜之后
  2451. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2452. DB::table('mp_episode_segments')
  2453. ->where('anime_id', $anime_id)
  2454. ->where('episode_id', $episode_id)
  2455. ->where('segment_number', '>', $target_segment_number)
  2456. ->where('segment_number', '<', $source_segment_number)
  2457. ->increment('segment_number');
  2458. // 2. 将源分镜移动到目标分镜之后
  2459. $new_segment_number = $target_segment_number + 1;
  2460. }
  2461. // 3. 更新源分镜的序号
  2462. $update_result = DB::table('mp_episode_segments')
  2463. ->where('segment_id', $segment_id)
  2464. ->update([
  2465. 'segment_number' => $new_segment_number,
  2466. 'updated_at' => date('Y-m-d H:i:s')
  2467. ]);
  2468. if (!$update_result) {
  2469. Utils::throwError('20003:更新分镜序号失败');
  2470. }
  2471. DB::commit();
  2472. return true;
  2473. } catch (\Exception $e) {
  2474. DB::rollBack();
  2475. Utils::throwError('20003:' . $e->getMessage());
  2476. }
  2477. }
  2478. public function delSegment($data) {
  2479. $segment_id = getProp($data, 'segment_id');
  2480. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2481. if (!$segment) Utils::throwError('20003:请选择分镜');
  2482. $anime_id = getProp($segment, 'anime_id');
  2483. $episode_id = getProp($segment, 'episode_id');
  2484. $episode_number = getProp($segment, 'episode_number');
  2485. $segment_number = getProp($segment, 'segment_number');
  2486. try {
  2487. DB::beginTransaction();
  2488. // 删除分镜
  2489. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2490. if (!$boolen) {
  2491. Utils::throwError('20003:删除分镜失败');
  2492. }
  2493. // 更新其他分镜序号
  2494. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2495. }catch (\Exception $e) {
  2496. DB::rollBack();
  2497. Utils::throwError('20003:'.$e->getMessage());
  2498. }
  2499. DB::commit();
  2500. return true;
  2501. }
  2502. public function applySegment($data) {
  2503. $segment_id = getProp($data, 'segment_id');
  2504. $url = getProp($data, 'url');
  2505. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2506. if (!$url) Utils::throwError('20003:URL不能为空');
  2507. // 获取URL的文件扩展名
  2508. $urlPath = parse_url($url, PHP_URL_PATH);
  2509. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2510. // 定义图片和视频的扩展名
  2511. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2512. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2513. // 判断是图片还是视频
  2514. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2515. if (in_array($extension, $imageExtensions)) {
  2516. // 图片类型
  2517. $updateData['img_url'] = $url;
  2518. $updateData['current_type'] = 1;
  2519. } elseif (in_array($extension, $videoExtensions)) {
  2520. // 视频类型
  2521. $updateData['video_url'] = $url;
  2522. $updateData['current_type'] = 2;
  2523. } else {
  2524. Utils::throwError('20003:不支持的文件类型');
  2525. }
  2526. // 更新分镜表
  2527. $result = DB::table('mp_episode_segments')
  2528. ->where('segment_id', $segment_id)
  2529. ->update($updateData);
  2530. if (!$result) {
  2531. Utils::throwError('20003:更新分镜失败');
  2532. }
  2533. return true;
  2534. }
  2535. public function segmentHistory($data) {
  2536. $segment_id = getProp($data, 'segment_id');
  2537. // 获取历史图片
  2538. $pics = [];
  2539. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2540. foreach($pic_history as $task) {
  2541. $result_url = getProp($task, 'result_url');
  2542. if (is_json($result_url)) {
  2543. $pics = array_merge($pics, json_decode($result_url, true));
  2544. }else {
  2545. $pics[] = $result_url;
  2546. }
  2547. }
  2548. // 获取历史视频
  2549. $videos = [];
  2550. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2551. foreach($video_history as $task) {
  2552. $result_url = getProp($task, 'result_url');
  2553. if (is_json($result_url)) {
  2554. $videos = array_merge($videos, json_decode($result_url, true));
  2555. }else {
  2556. $videos[] = $result_url;
  2557. }
  2558. }
  2559. return compact('pics', 'videos');
  2560. }
  2561. public function addAct($data) {
  2562. $prev_act_id = getProp($data, 'prev_act_id');
  2563. $act_title = getProp($data, 'act_title', '');
  2564. $act_content = getProp($data, 'act_content', '');
  2565. $act_duration = getProp($data, 'act_duration', 5);
  2566. $video_url = getProp($data, 'video_url');
  2567. // 根据prev_act_id获取记录
  2568. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2569. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2570. $anime_id = getProp($prev_segment, 'anime_id');
  2571. $episode_id = getProp($prev_segment, 'episode_id');
  2572. $episode_number = getProp($prev_segment, 'episode_number');
  2573. $prev_act_number = getProp($prev_segment, 'act_number');
  2574. // 获取新的act_number
  2575. $new_act_number = $prev_act_number + 1;
  2576. try {
  2577. DB::beginTransaction();
  2578. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2579. DB::table('mp_episode_segments')
  2580. ->where('anime_id', $anime_id)
  2581. ->where('episode_id', $episode_id)
  2582. ->where('act_number', '>', $prev_act_number)
  2583. ->increment('act_number');
  2584. // 插入新片段记录
  2585. $insert_data = [
  2586. 'anime_id' => $anime_id,
  2587. 'episode_id' => $episode_id,
  2588. 'episode_number' => $episode_number,
  2589. 'act_number' => $new_act_number,
  2590. 'created_at' => date('Y-m-d H:i:s'),
  2591. 'updated_at' => date('Y-m-d H:i:s')
  2592. ];
  2593. if ($act_title) {
  2594. $insert_data['act_title'] = $act_title;
  2595. }
  2596. if ($act_content) {
  2597. $insert_data['act_content'] = $act_content;
  2598. }
  2599. if ($act_duration) {
  2600. $insert_data['act_duration'] = $act_duration;
  2601. }
  2602. if ($video_url) {
  2603. $insert_data['origin_video_url'] = $video_url;
  2604. $insert_data['current_type'] = 2;
  2605. $compressed_video_url = compressVideo($video_url);
  2606. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2607. }
  2608. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2609. if (!$id) {
  2610. Utils::throwError('20003:新增片段失败!');
  2611. }
  2612. DB::commit();
  2613. }catch (\Exception $e) {
  2614. DB::rollBack();
  2615. Utils::throwError('20003:'.$e->getMessage());
  2616. }
  2617. $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();
  2618. $segment = $segment ? (array)$segment : [];
  2619. return $segment;
  2620. }
  2621. public function editAct($data) {
  2622. $act_id = getProp($data, 'act_id');
  2623. $act_content = getProp($data, 'act_content');
  2624. $act_duration = getProp($data, 'act_duration');
  2625. $act_title = getProp($data, 'act_title');
  2626. $image_url = getProp($data, 'image_url');
  2627. $video_url = getProp($data, 'video_url');
  2628. // 参数验证
  2629. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2630. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2631. $segment = DB::table('mp_episode_segments')
  2632. ->where('id', $act_id)
  2633. ->first();
  2634. if (!$segment) Utils::throwError('20003:该片段不存在');
  2635. try {
  2636. DB::beginTransaction();
  2637. // 准备更新数据
  2638. $update_data = [
  2639. 'updated_at' => date('Y-m-d H:i:s')
  2640. ];
  2641. // 更新act相关字段
  2642. if (!empty($act_content)) {
  2643. $update_data['act_show_content'] = $act_content;
  2644. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2645. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2646. $shot_counter = 0;
  2647. $update_data['act_show_content'] = preg_replace_callback(
  2648. '/【(?:镜头|分镜)(\d+)】/u',
  2649. function($matches) use (&$shot_counter) {
  2650. $shot_counter++;
  2651. return '【镜头' . $shot_counter . '】';
  2652. },
  2653. $update_data['act_show_content']
  2654. );
  2655. }
  2656. if (!empty($act_duration)) {
  2657. $update_data['act_duration'] = $act_duration;
  2658. }
  2659. if (!empty($act_title)) {
  2660. $update_data['act_title'] = $act_title;
  2661. }
  2662. // 处理图片上传
  2663. if ($image_url) {
  2664. $update_data['img_url'] = $image_url;
  2665. $update_data['current_type'] = 1;
  2666. // 同时写入一个图片生成任务记录
  2667. if ($act_id) {
  2668. $pic_task = [
  2669. 'alias_act_id' => $act_id,
  2670. 'ref_img_url' => json_encode([]),
  2671. 'status' => 'success',
  2672. 'result_url' => json_encode([$image_url], 256),
  2673. 'model' => '',
  2674. 'created_at' => date('Y-m-d H:i:s'),
  2675. 'updated_at' => date('Y-m-d H:i:s'),
  2676. ];
  2677. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2678. }
  2679. }
  2680. // 处理视频上传
  2681. if ($video_url) {
  2682. $update_data['origin_video_url'] = $video_url;
  2683. $compressed_video_url = compressVideo($video_url);
  2684. $update_data['current_type'] = 2;
  2685. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2686. // 同时写入一个视频生成任务记录
  2687. if ($act_id) {
  2688. $video_task = [
  2689. 'alias_act_id' => $act_id,
  2690. 'status' => 'success',
  2691. 'result_url' => $update_data['origin_video_url'],
  2692. 'compressed_url' => $update_data['video_url'],
  2693. 'created_at' => date('Y-m-d H:i:s'),
  2694. 'updated_at' => date('Y-m-d H:i:s'),
  2695. ];
  2696. DB::table('mp_generate_video_tasks')->insert($video_task);
  2697. }
  2698. }
  2699. // 更新片段信息
  2700. $result = DB::table('mp_episode_segments')
  2701. ->where('id', $act_id)
  2702. ->update($update_data);
  2703. if ($result === false) {
  2704. Utils::throwError('20003:更新片段失败');
  2705. }
  2706. DB::commit();
  2707. // 返回新复制的记录
  2708. $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();
  2709. $new_segment = (array)$new_segment;
  2710. return $new_segment;
  2711. } catch (\Exception $e) {
  2712. DB::rollBack();
  2713. dLog('anime')->error('更新片段失败', [
  2714. 'act_id' => $act_id,
  2715. 'error' => $e->getMessage()
  2716. ]);
  2717. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2718. }
  2719. }
  2720. public function copyAct($data) {
  2721. $act_id = getProp($data, 'act_id');
  2722. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2723. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2724. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2725. $anime_id = getProp($source_segment, 'anime_id');
  2726. $episode_id = getProp($source_segment, 'episode_id');
  2727. $episode_number = getProp($source_segment, 'episode_number');
  2728. $act_number = getProp($source_segment, 'act_number');
  2729. try {
  2730. DB::beginTransaction();
  2731. // 新act的编号
  2732. $new_act_number = $act_number + 1;
  2733. // 更新后续所有act的act_number
  2734. DB::table('mp_episode_segments')
  2735. ->where('anime_id', $anime_id)
  2736. ->where('episode_id', $episode_id)
  2737. ->where('act_number', '>', $act_number)
  2738. ->increment('act_number');
  2739. // 复制该片段记录
  2740. $segment_data = (array)$source_segment;
  2741. unset($segment_data['id']);
  2742. $segment_data['video_url'] = '';
  2743. $segment_data['video_task_id'] = '';
  2744. $segment_data['video_task_status'] = '';
  2745. $segment_data['act_number'] = $new_act_number;
  2746. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2747. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2748. if (!$id) {
  2749. Utils::throwError('20003:复制片段失败');
  2750. }
  2751. DB::commit();
  2752. }catch (\Exception $e) {
  2753. DB::rollBack();
  2754. Utils::throwError('20003:'.$e->getMessage());
  2755. }
  2756. // 返回新复制的记录
  2757. $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();
  2758. $new_segment = $new_segment ? (array)$new_segment : [];
  2759. $new_segment['act_id'] = $id;
  2760. return $new_segment;
  2761. }
  2762. public function moveAct($data) {
  2763. $act_id = getProp($data, 'act_id');
  2764. $target_act_id = getProp($data, 'target_act_id');
  2765. // 获取源片段信息
  2766. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2767. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2768. // 获取目标片段信息
  2769. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2770. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2771. $anime_id = getProp($source_segment, 'anime_id');
  2772. $episode_id = getProp($source_segment, 'episode_id');
  2773. $source_act_number = getProp($source_segment, 'act_number');
  2774. $target_act_number = getProp($target_segment, 'act_number');
  2775. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2776. $target_anime_id = getProp($target_segment, 'anime_id');
  2777. $target_episode_id = getProp($target_segment, 'episode_id');
  2778. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2779. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2780. }
  2781. // 如果源片段和目标片段相同,无需移动
  2782. if ($source_act_number == $target_act_number) {
  2783. return true;
  2784. }
  2785. try {
  2786. DB::beginTransaction();
  2787. if ($source_act_number < $target_act_number) {
  2788. // 向后移动:源片段移动到目标片段之后
  2789. // 1. 将源片段和目标片段之间的所有片段编号减1
  2790. DB::table('mp_episode_segments')
  2791. ->where('anime_id', $anime_id)
  2792. ->where('episode_id', $episode_id)
  2793. ->where('act_number', '>', $source_act_number)
  2794. ->where('act_number', '<=', $target_act_number)
  2795. ->decrement('act_number');
  2796. // 2. 将源片段移动到目标片段之后
  2797. $new_act_number = $target_act_number;
  2798. } else {
  2799. // 向前移动:源片段移动到目标片段之后
  2800. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2801. DB::table('mp_episode_segments')
  2802. ->where('anime_id', $anime_id)
  2803. ->where('episode_id', $episode_id)
  2804. ->where('act_number', '>', $target_act_number)
  2805. ->where('act_number', '<', $source_act_number)
  2806. ->increment('act_number');
  2807. // 2. 将源片段移动到目标片段之后
  2808. $new_act_number = $target_act_number + 1;
  2809. }
  2810. // 3. 更新源片段的编号
  2811. $update_result = DB::table('mp_episode_segments')
  2812. ->where('id', $act_id)
  2813. ->update([
  2814. 'act_number' => $new_act_number,
  2815. 'updated_at' => date('Y-m-d H:i:s')
  2816. ]);
  2817. if (!$update_result) {
  2818. Utils::throwError('20003:更新片段编号失败');
  2819. }
  2820. DB::commit();
  2821. return true;
  2822. } catch (\Exception $e) {
  2823. DB::rollBack();
  2824. Utils::throwError('20003:' . $e->getMessage());
  2825. }
  2826. }
  2827. public function delAct($data) {
  2828. $act_id = getProp($data, 'act_id');
  2829. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2830. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2831. if (!$segment) Utils::throwError('20003:请选择片段');
  2832. $anime_id = getProp($segment, 'anime_id');
  2833. $episode_id = getProp($segment, 'episode_id');
  2834. $act_number = getProp($segment, 'act_number');
  2835. try {
  2836. DB::beginTransaction();
  2837. // 删除该片段记录
  2838. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2839. if (!$deleted) {
  2840. Utils::throwError('20003:删除片段失败');
  2841. }
  2842. // 更新后续act的编号
  2843. DB::table('mp_episode_segments')
  2844. ->where('anime_id', $anime_id)
  2845. ->where('episode_id', $episode_id)
  2846. ->where('act_number', '>', $act_number)
  2847. ->decrement('act_number');
  2848. DB::commit();
  2849. }catch (\Exception $e) {
  2850. DB::rollBack();
  2851. Utils::throwError('20003:'.$e->getMessage());
  2852. }
  2853. return true;
  2854. }
  2855. public function applyAct($data) {
  2856. $act_id = getProp($data, 'act_id');
  2857. $url = getProp($data, 'url');
  2858. if (!$act_id) Utils::throwError('20003:请选择片段');
  2859. if (!$url) Utils::throwError('20003:URL不能为空');
  2860. // 获取URL的文件扩展名
  2861. $urlPath = parse_url($url, PHP_URL_PATH);
  2862. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2863. // 定义图片和视频的扩展名
  2864. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2865. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2866. // 判断是图片还是视频
  2867. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2868. if (in_array($extension, $imageExtensions)) {
  2869. // 图片类型
  2870. $updateData['img_url'] = $url;
  2871. $updateData['current_type'] = 1;
  2872. } elseif (in_array($extension, $videoExtensions)) {
  2873. // 视频类型
  2874. $updateData['video_url'] = $url;
  2875. $updateData['current_type'] = 2;
  2876. } else {
  2877. Utils::throwError('20003:不支持的文件类型');
  2878. }
  2879. // 更新片段记录(全能模式下每个act只有一条记录)
  2880. $result = DB::table('mp_episode_segments')
  2881. ->where('id', $act_id)
  2882. ->update($updateData);
  2883. if (!$result) {
  2884. Utils::throwError('20003:更新片段失败');
  2885. }
  2886. return true;
  2887. }
  2888. public function actChatHistory($data) {
  2889. $act_id = getProp($data, 'act_id');
  2890. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2891. $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');
  2892. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2893. $value = (array)$value;
  2894. $value['created_at'] = transDate($value['created_at']);
  2895. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2896. else $value['reference_images'] = [];
  2897. return $value;
  2898. })->toArray();
  2899. // 获取历史图片
  2900. $url = [];
  2901. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2902. foreach($pic_history as $task) {
  2903. $result_url = getProp($task, 'result_url');
  2904. if (is_json($result_url)) {
  2905. $url = array_merge($url, json_decode($result_url, true));
  2906. }else {
  2907. $url[] = $result_url;
  2908. }
  2909. }
  2910. // 获取历史视频
  2911. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2912. foreach($video_history as $task) {
  2913. $result_url = getProp($task, 'result_url');
  2914. if (is_json($result_url)) {
  2915. $url = array_merge($url, json_decode($result_url, true));
  2916. }else {
  2917. $url[] = $result_url;
  2918. }
  2919. }
  2920. // 获取资产库
  2921. $products = [];
  2922. // 通过act_id查询片段信息获取episode_id
  2923. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2924. if ($segment) {
  2925. $episode_id = getProp($segment, 'episode_id');
  2926. // 查询剧集信息获取roles、scenes和extra_products
  2927. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2928. if ($episode) {
  2929. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2930. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2931. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2932. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2933. // 先合并roles、scenes和props
  2934. // 处理角色数组
  2935. foreach ($roles as $role) {
  2936. $product = $role;
  2937. // 将role字段重命名为product_name
  2938. if (is_array($product) && !empty($product['role'] ?? null)) {
  2939. $product['product_name'] = $product['role'];
  2940. unset($product['role']);
  2941. $product['product'] = 1; // 标记类型为角色
  2942. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2943. }
  2944. }
  2945. // 处理场景数组
  2946. foreach ($scenes as $scene) {
  2947. $product = $scene;
  2948. // 将scene字段重命名为product_name
  2949. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2950. $product['product_name'] = $product['scene'];
  2951. unset($product['scene']);
  2952. $product['product'] = 2; // 标记类型为场景
  2953. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2954. }
  2955. }
  2956. // 处理道具数组
  2957. foreach ($props as $prop) {
  2958. $product = $prop;
  2959. // 将prop字段重命名为product_name
  2960. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2961. $product['product_name'] = $product['prop'];
  2962. unset($product['prop']);
  2963. $product['product'] = 3; // 标记类型为道具
  2964. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2965. }
  2966. }
  2967. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2968. foreach ($extra_products as $extra_product) {
  2969. $product_name = getProp($extra_product, 'product_name');
  2970. if ($product_name) {
  2971. $products[$product_name] = $extra_product; // 覆盖同名数据
  2972. }
  2973. }
  2974. // 重新索引数组(去除key)
  2975. $products = array_values($products);
  2976. }
  2977. }
  2978. // 获取执行中的任务
  2979. $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) {
  2980. $value = (array)$value;
  2981. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2982. else $value['ref_image_url'] = [];
  2983. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2984. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2985. if (!empty($value['prompt'])) {
  2986. $prompt = $value['prompt'];
  2987. // 查找第一个【镜头】的位置
  2988. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2989. // 从【镜头】开始截取
  2990. $prompt = substr($prompt, $matches[0][1]);
  2991. }
  2992. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2993. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2994. $value['prompt'] = $prompt;
  2995. }
  2996. return $value;
  2997. })->toArray();
  2998. return compact('chat', 'url', 'products', 'tasks');
  2999. }
  3000. public function applyAudioData($data) {
  3001. $segment_id = getProp($data, 'segment_id');
  3002. $global_data = getProp($data, 'global_data');
  3003. $segment_data = getProp($data, 'segment_data');
  3004. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3005. $global_data = is_array($global_data) ? $global_data : [];
  3006. $segment_data = is_array($segment_data) ? $segment_data : [];
  3007. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3008. $dialogue_item = null;
  3009. foreach ($global_data as $key => $item) {
  3010. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3011. $dialogue_item = $item;
  3012. unset($global_data[$key]);
  3013. break;
  3014. }
  3015. }
  3016. if ($dialogue_item) {
  3017. $segment_data[] = $dialogue_item;
  3018. }
  3019. // 特殊参数: audio_url,audio_duration,subtitle_info
  3020. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3021. // 如果不是全部存在,则仍需创建音频任务
  3022. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3023. $special_update_data = [];
  3024. $has_all_special_params = false;
  3025. // 从segment_data中提取特殊参数
  3026. $filtered_segment_data = [];
  3027. foreach ($segment_data as $item) {
  3028. $field_name = trim((string)getProp($item, 'name'));
  3029. if (in_array($field_name, $special_fields)) {
  3030. $special_update_data[$field_name] = getProp($item, 'value');
  3031. } else {
  3032. // 非特殊参数保留,继续后续处理
  3033. $filtered_segment_data[] = $item;
  3034. }
  3035. }
  3036. // 检查是否三个特殊参数都存在
  3037. if (count($special_update_data) === 3 &&
  3038. isset($special_update_data['audio_url']) &&
  3039. isset($special_update_data['audio_duration']) &&
  3040. isset($special_update_data['subtitle_info'])) {
  3041. $has_all_special_params = true;
  3042. // 立即更新到当前分镜
  3043. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3044. DB::table('mp_episode_segments')
  3045. ->where('segment_id', $segment_id)
  3046. ->update($special_update_data);
  3047. }
  3048. // 使用过滤后的segment_data继续处理其他参数
  3049. $segment_data = $filtered_segment_data;
  3050. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3051. $global_update_data = [];
  3052. $segment_update_data = [];
  3053. $global_voice_type = '';
  3054. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3055. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3056. $episode_id = getProp($target_segment, 'episode_id');
  3057. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3058. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3059. if (!$episode) Utils::throwError('20003:分集不存在');
  3060. foreach ($global_data as $item) {
  3061. $field_name = trim((string)getProp($item, 'name'));
  3062. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3063. continue;
  3064. }
  3065. $global_update_data[$field_name] = getProp($item, 'value');
  3066. if ($field_name === 'voice_type') {
  3067. $global_voice_type = trim((string)getProp($item, 'value'));
  3068. }
  3069. }
  3070. foreach ($segment_data as $item) {
  3071. $field_name = trim((string)getProp($item, 'name'));
  3072. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3073. continue;
  3074. }
  3075. $segment_update_data[$field_name] = getProp($item, 'value');
  3076. }
  3077. if ($global_voice_type) {
  3078. $timbre_info = DB::table('mp_timbres')
  3079. ->where('timbre_type', $global_voice_type)
  3080. ->select('audio_url', 'timbre_name')
  3081. ->first();
  3082. if ($timbre_info) {
  3083. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3084. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3085. }
  3086. }
  3087. try {
  3088. DB::beginTransaction();
  3089. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3090. $segment_ids_to_create_task = [];
  3091. $segments_data = [];
  3092. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3093. if (!empty($global_update_data)) {
  3094. // 如果角色不存在,则只更新当前分镜
  3095. if (!$target_voice_actor) {
  3096. // 只处理当前分镜
  3097. $affected_segments = DB::table('mp_episode_segments')
  3098. ->where('segment_id', $segment_id)
  3099. ->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')
  3100. ->get();
  3101. } else {
  3102. // 获取该角色的所有分镜
  3103. $affected_segments = DB::table('mp_episode_segments')
  3104. ->where('episode_id', $episode_id)
  3105. ->where('voice_actor', $target_voice_actor)
  3106. ->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')
  3107. ->get();
  3108. }
  3109. foreach ($affected_segments as $seg) {
  3110. $seg = (array)$seg;
  3111. $sid = getProp($seg, 'segment_id');
  3112. // 检查参数是否发生变化
  3113. $has_changed = false;
  3114. foreach ($global_update_data as $field => $new_value) {
  3115. $old_value = getProp($seg, $field);
  3116. if ($old_value != $new_value) {
  3117. $has_changed = true;
  3118. break;
  3119. }
  3120. }
  3121. if ($has_changed) {
  3122. $segment_ids_to_create_task[] = $sid;
  3123. $segments_data[$sid] = $seg;
  3124. }
  3125. }
  3126. // 只有在有变化的分镜时才更新
  3127. if (!empty($segment_ids_to_create_task)) {
  3128. $global_segment_update_data = $global_update_data;
  3129. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3130. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3131. DB::table('mp_episode_segments')
  3132. ->where('episode_id', $episode_id)
  3133. ->where('voice_actor', $target_voice_actor)
  3134. ->whereIn('segment_id', $segment_ids_to_create_task)
  3135. ->update($global_segment_update_data);
  3136. }
  3137. if ($global_voice_type) {
  3138. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3139. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3140. $roles_updated = false;
  3141. foreach ($episode_roles as &$role) {
  3142. // 通过 role 字段匹配角色名,而不是 voice_name
  3143. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3144. continue;
  3145. }
  3146. $role['voice_type'] = $global_voice_type;
  3147. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3148. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3149. $roles_updated = true;
  3150. }
  3151. unset($role);
  3152. if ($roles_updated) {
  3153. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3154. 'roles' => json_encode($episode_roles, 256),
  3155. 'updated_at' => date('Y-m-d H:i:s'),
  3156. ]);
  3157. }
  3158. }
  3159. }
  3160. // 如果有单个分镜更新,检查是否有变化
  3161. if (!empty($segment_update_data)) {
  3162. // 获取当前分镜数据
  3163. $current_segment = DB::table('mp_episode_segments')
  3164. ->where('segment_id', $segment_id)
  3165. ->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')
  3166. ->first();
  3167. if ($current_segment) {
  3168. $current_segment = (array)$current_segment;
  3169. // 检查参数是否发生变化
  3170. $has_changed = false;
  3171. foreach ($segment_update_data as $field => $new_value) {
  3172. $old_value = getProp($current_segment, $field);
  3173. if ($old_value != $new_value) {
  3174. $has_changed = true;
  3175. break;
  3176. }
  3177. }
  3178. if ($has_changed) {
  3179. // 如果该分镜还未在列表中,添加进去
  3180. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3181. $segment_ids_to_create_task[] = $segment_id;
  3182. $segments_data[$segment_id] = $current_segment;
  3183. }
  3184. // 更新分镜数据并清空音频URL
  3185. $segment_update_data['audio_url'] = '';
  3186. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3187. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3188. }
  3189. }
  3190. }
  3191. // 为所有有变化的分镜创建音频合成任务
  3192. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3193. if (!empty($segment_ids_to_create_task)) {
  3194. foreach ($segment_ids_to_create_task as $sid) {
  3195. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3196. if ($sid === $segment_id && $has_all_special_params) {
  3197. continue;
  3198. }
  3199. // 重新获取更新后的分镜数据
  3200. $updated_segment = DB::table('mp_episode_segments')
  3201. ->where('segment_id', $sid)
  3202. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3203. ->first();
  3204. if (!$updated_segment) continue;
  3205. $updated_segment = (array)$updated_segment;
  3206. // 检查dialogue是否为空
  3207. $dialogue = getProp($updated_segment, 'dialogue');
  3208. if (empty($dialogue)) {
  3209. // dialogue为空时,直接写入默认音频信息
  3210. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3211. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3212. 'audio_duration' => 2.0,
  3213. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3214. 'updated_at' => date('Y-m-d H:i:s')
  3215. ]);
  3216. continue;
  3217. }
  3218. $generate_json = [
  3219. 'text' => $dialogue,
  3220. 'role' => getProp($updated_segment, 'voice_actor'),
  3221. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3222. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3223. 'emotion' => getProp($updated_segment, 'emotion'),
  3224. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3225. 'gender' => getProp($updated_segment, 'gender'),
  3226. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3227. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3228. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3229. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3230. ];
  3231. // 插入视频配音合成任务
  3232. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3233. 'alias_segment_id' => $sid,
  3234. 'generate_status' => '执行中',
  3235. 'audio_url' => '',
  3236. 'generate_json' => json_encode($generate_json, 256),
  3237. 'created_at' => date('Y-m-d H:i:s'),
  3238. 'updated_at' => date('Y-m-d H:i:s'),
  3239. ]);
  3240. if (!$dubTaskId) {
  3241. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3242. continue;
  3243. }
  3244. // 将任务ID添加到Redis列表中
  3245. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3246. // 请求远程服务器执行生成
  3247. try {
  3248. sleep(1);
  3249. $client = new Client(['timeout' => 300, 'verify' => false]);
  3250. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3251. $response = $result->getBody()->getContents();
  3252. $response_arr = json_decode($response, true);
  3253. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3254. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3255. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3256. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3257. }
  3258. } catch (\Exception $e) {
  3259. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3260. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3261. }
  3262. }
  3263. }
  3264. DB::commit();
  3265. } catch (\Exception $e) {
  3266. DB::rollBack();
  3267. Utils::throwError('20003:'.$e->getMessage());
  3268. }
  3269. return true;
  3270. }
  3271. public function episodePicsInfo($data) {
  3272. $anime_id = getProp($data, 'anime_id');
  3273. $episode_id = getProp($data, 'episode_id');
  3274. // 参数验证
  3275. if (!$anime_id && !$episode_id) {
  3276. Utils::throwError('20003:请提供动漫ID或分集ID');
  3277. }
  3278. // 根据参数获取数据源
  3279. if ($episode_id) {
  3280. // 从剧集表获取
  3281. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3282. if (!$source) Utils::throwError('20003:该剧集不存在');
  3283. $table_name = 'mp_anime_episodes';
  3284. $id_field = 'id';
  3285. $id_value = $episode_id;
  3286. // 获取剧集的anime_id用于继承全局数据
  3287. $anime_id = getProp($source, 'anime_id');
  3288. } else {
  3289. // 从动漫表获取
  3290. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3291. if (!$source) Utils::throwError('20003:该动漫不存在');
  3292. $table_name = 'mp_animes';
  3293. $id_field = 'id';
  3294. $id_value = $anime_id;
  3295. }
  3296. $source = (array)$source;
  3297. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3298. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3299. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3300. // 如果是分集数据,需要处理继承和任务创建逻辑
  3301. if ($episode_id) {
  3302. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3303. }
  3304. // 返回生成器函数,用于 SSE 流式输出
  3305. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3306. $startTime = time();
  3307. $maxDuration = 600; // 10分钟超时
  3308. $checkInterval = 3; // 每3秒检查一次
  3309. // Redis 缓存键
  3310. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3311. // 生成当前数据的哈希值用于比较
  3312. $generateHash = function($roles, $scenes, $props) {
  3313. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3314. };
  3315. // 发送初始数据
  3316. $currentHash = $generateHash($roles, $scenes, $props);
  3317. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3318. echo "data: " . json_encode([
  3319. 'type' => 'init',
  3320. 'data' => [
  3321. 'roles' => $roles,
  3322. 'scenes' => $scenes,
  3323. 'props' => $props,
  3324. 'start_time' => $startTime
  3325. ]
  3326. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3327. if (ob_get_level() > 0) {
  3328. ob_flush();
  3329. }
  3330. flush();
  3331. // 持续轮询任务状态
  3332. while (time() - $startTime < $maxDuration) {
  3333. $hasProcessing = false;
  3334. $updated = false;
  3335. // 检查角色任务状态
  3336. foreach ($roles as $index => &$role) {
  3337. $task_id = getProp($role, 'task_id');
  3338. $task_status = getProp($role, 'task_status');
  3339. $existing_url = getProp($role, 'url');
  3340. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3341. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3342. $hasProcessing = ($task_status === 'processing');
  3343. // 查询任务状态
  3344. $task = DB::table('mp_generate_pic_tasks')
  3345. ->where('id', $task_id)
  3346. ->select('id', 'status', 'result_url', 'error_message')
  3347. ->first();
  3348. if ($task) {
  3349. $task = (array)$task;
  3350. $status = getProp($task, 'status');
  3351. // 如果任务完成或失败
  3352. if (in_array($status, ['success', 'failed'])) {
  3353. $role['task_status'] = $status;
  3354. if ($status === 'success') {
  3355. $result_url = getProp($task, 'result_url');
  3356. if ($result_url) {
  3357. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3358. if (is_array($result_urls) && !empty($result_urls[0])) {
  3359. $role['url'] = $result_urls[0];
  3360. }
  3361. }
  3362. }
  3363. $updated = true;
  3364. } else if ($status === 'processing') {
  3365. $hasProcessing = true;
  3366. }
  3367. }
  3368. }
  3369. }
  3370. // 检查场景任务状态
  3371. foreach ($scenes as $index => &$scene) {
  3372. $task_id = getProp($scene, 'task_id');
  3373. $task_status = getProp($scene, 'task_status');
  3374. $existing_url = getProp($scene, 'url');
  3375. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3376. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3377. $hasProcessing = ($task_status === 'processing');
  3378. // 查询任务状态
  3379. $task = DB::table('mp_generate_pic_tasks')
  3380. ->where('id', $task_id)
  3381. ->select('id', 'status', 'result_url', 'error_message')
  3382. ->first();
  3383. if ($task) {
  3384. $task = (array)$task;
  3385. $status = getProp($task, 'status');
  3386. // 如果任务完成或失败
  3387. if (in_array($status, ['success', 'failed'])) {
  3388. $scene['task_status'] = $status;
  3389. if ($status === 'success') {
  3390. $result_url = getProp($task, 'result_url');
  3391. if ($result_url) {
  3392. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3393. if (is_array($result_urls) && !empty($result_urls[0])) {
  3394. $scene['url'] = $result_urls[0];
  3395. }
  3396. }
  3397. }
  3398. $updated = true;
  3399. } else if ($status === 'processing') {
  3400. $hasProcessing = true;
  3401. }
  3402. }
  3403. }
  3404. }
  3405. // 检查道具任务状态
  3406. foreach ($props as $index => &$prop) {
  3407. $task_id = getProp($prop, 'task_id');
  3408. $task_status = getProp($prop, 'task_status');
  3409. $existing_url = getProp($prop, 'url');
  3410. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3411. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3412. $hasProcessing = ($task_status === 'processing');
  3413. // 查询任务状态
  3414. $task = DB::table('mp_generate_pic_tasks')
  3415. ->where('id', $task_id)
  3416. ->select('id', 'status', 'result_url', 'error_message')
  3417. ->first();
  3418. if ($task) {
  3419. $task = (array)$task;
  3420. $status = getProp($task, 'status');
  3421. // 如果任务完成或失败
  3422. if (in_array($status, ['success', 'failed'])) {
  3423. $prop['task_status'] = $status;
  3424. if ($status === 'success') {
  3425. $result_url = getProp($task, 'result_url');
  3426. if ($result_url) {
  3427. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3428. if (is_array($result_urls) && !empty($result_urls[0])) {
  3429. $prop['url'] = $result_urls[0];
  3430. }
  3431. }
  3432. }
  3433. $updated = true;
  3434. } else if ($status === 'processing') {
  3435. $hasProcessing = true;
  3436. }
  3437. }
  3438. }
  3439. }
  3440. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3441. if ($updated) {
  3442. $newHash = $generateHash($roles, $scenes, $props);
  3443. $cachedHash = Redis::get($cacheKey);
  3444. // 只有当数据真正变化时才更新数据库和发送事件
  3445. if ($newHash !== $cachedHash) {
  3446. try {
  3447. // 更新数据库
  3448. DB::table($table_name)->where($id_field, $id_value)->update([
  3449. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3450. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3451. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3452. 'updated_at' => date('Y-m-d H:i:s')
  3453. ]);
  3454. // 更新缓存
  3455. Redis::setex($cacheKey, 600, $newHash);
  3456. // 发送更新事件
  3457. echo "data: " . json_encode([
  3458. 'type' => 'update',
  3459. 'data' => [
  3460. 'roles' => $roles,
  3461. 'scenes' => $scenes,
  3462. 'props' => $props,
  3463. 'elapsed_time' => time() - $startTime
  3464. ]
  3465. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3466. if (ob_get_level() > 0) {
  3467. ob_flush();
  3468. }
  3469. flush();
  3470. } catch (\Exception $e) {
  3471. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3472. }
  3473. } else {
  3474. // 即使哈希相同,如果有URL更新也要发送事件
  3475. $hasUrlUpdate = false;
  3476. foreach ($roles as $role) {
  3477. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3478. $hasUrlUpdate = true;
  3479. break;
  3480. }
  3481. }
  3482. if (!$hasUrlUpdate) {
  3483. foreach ($scenes as $scene) {
  3484. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3485. $hasUrlUpdate = true;
  3486. break;
  3487. }
  3488. }
  3489. }
  3490. if (!$hasUrlUpdate) {
  3491. foreach ($props as $prop) {
  3492. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3493. $hasUrlUpdate = true;
  3494. break;
  3495. }
  3496. }
  3497. }
  3498. if ($hasUrlUpdate) {
  3499. // 强制更新数据库和发送事件
  3500. try {
  3501. DB::table($table_name)->where($id_field, $id_value)->update([
  3502. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3503. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3504. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3505. 'updated_at' => date('Y-m-d H:i:s')
  3506. ]);
  3507. // 更新缓存
  3508. Redis::setex($cacheKey, 600, $newHash);
  3509. // 发送更新事件
  3510. echo "data: " . json_encode([
  3511. 'type' => 'update',
  3512. 'data' => [
  3513. 'roles' => $roles,
  3514. 'scenes' => $scenes,
  3515. 'props' => $props,
  3516. 'elapsed_time' => time() - $startTime
  3517. ]
  3518. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3519. if (ob_get_level() > 0) {
  3520. ob_flush();
  3521. }
  3522. flush();
  3523. } catch (\Exception $e) {
  3524. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3525. }
  3526. }
  3527. }
  3528. }
  3529. // 如果所有任务都已完成,发送完成事件并退出
  3530. if (!$hasProcessing) {
  3531. // 查询数据库中的最终数据,确保返回最新的完整数据
  3532. try {
  3533. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3534. if ($finalSource) {
  3535. $finalSource = (array)$finalSource;
  3536. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3537. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3538. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3539. // 使用数据库中的最终数据
  3540. $roles = $finalRoles;
  3541. $scenes = $finalScenes;
  3542. $props = $finalProps;
  3543. }
  3544. } catch (\Exception $e) {
  3545. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3546. // 如果查询失败,继续使用内存中的数据
  3547. }
  3548. // 清理缓存
  3549. Redis::del($cacheKey);
  3550. echo "data: " . json_encode([
  3551. 'type' => 'completed',
  3552. 'data' => [
  3553. 'roles' => $roles,
  3554. 'scenes' => $scenes,
  3555. 'props' => $props,
  3556. 'total_time' => time() - $startTime
  3557. ]
  3558. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3559. if (ob_get_level() > 0) {
  3560. ob_flush();
  3561. }
  3562. flush();
  3563. break;
  3564. }
  3565. // 等待下次检查
  3566. sleep($checkInterval);
  3567. }
  3568. // 超时处理
  3569. if (time() - $startTime >= $maxDuration) {
  3570. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3571. try {
  3572. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3573. if ($finalSource) {
  3574. $finalSource = (array)$finalSource;
  3575. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3576. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3577. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3578. // 使用数据库中的最终数据
  3579. $roles = $finalRoles;
  3580. $scenes = $finalScenes;
  3581. $props = $finalProps;
  3582. }
  3583. } catch (\Exception $e) {
  3584. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3585. // 如果查询失败,继续使用内存中的数据
  3586. }
  3587. // 清理缓存
  3588. Redis::del($cacheKey);
  3589. echo "data: " . json_encode([
  3590. 'type' => 'timeout',
  3591. 'message' => '轮询超时,请刷新页面查看最新状态',
  3592. 'data' => [
  3593. 'roles' => $roles,
  3594. 'scenes' => $scenes,
  3595. 'props' => $props
  3596. ]
  3597. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3598. if (ob_get_level() > 0) {
  3599. ob_flush();
  3600. }
  3601. flush();
  3602. }
  3603. };
  3604. }
  3605. public function clipSegmentVideo($data) {
  3606. $segment_id = getProp($data, 'segment_id');
  3607. $video_time_point_start = getProp($data, 'video_time_point_start');
  3608. $video_time_point_end = getProp($data, 'video_time_point_end');
  3609. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3610. Utils::throwError('20003:参数异常');
  3611. }
  3612. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3613. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3614. }
  3615. $video_duration = $video_time_point_end - $video_time_point_start;
  3616. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3617. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3618. 'video_duration' => $video_duration,
  3619. 'video_time_point_start' => $video_time_point_start,
  3620. 'video_time_point_end' => $video_time_point_end,
  3621. 'updated_at' => date('Y-m-d H:i:s')
  3622. ]);
  3623. }
  3624. // 轮训获取图片任务结果
  3625. private function loopGetPicTaskResult($task_id) {
  3626. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3627. if (!$task) {
  3628. return '';
  3629. }
  3630. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3631. $model = getProp($task, 'model');
  3632. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3633. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3634. $isSyncModel = $isVolcModel || $isGptModel;
  3635. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3636. $start_count = 0;
  3637. $img_url = '';
  3638. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3639. sleep(3);
  3640. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3641. // 如果任务已经完成,直接返回结果
  3642. if ($task->status === 'success' && $task->result_url) {
  3643. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3644. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3645. }
  3646. // 如果任务已失败,返回空
  3647. if ($task->status === 'failed') {
  3648. return '';
  3649. }
  3650. if ($isSyncModel) continue;
  3651. // 查询任务状态
  3652. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3653. if ($statusInfo['status'] === 'success') {
  3654. $task->updateStatus('success', [
  3655. 'result_url' => $statusInfo['result_url'],
  3656. 'result_json' => $statusInfo['result_json'] ?? []
  3657. ]);
  3658. // 同步调整分镜图片状态和结果
  3659. if (getProp($task, 'alias_segment_id')) {
  3660. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3661. 'img_url' => $statusInfo['result_url'][0],
  3662. 'pic_task_status' => '已完成',
  3663. ]);
  3664. }
  3665. $img_url = $statusInfo['result_url'][0];
  3666. break;
  3667. } elseif ($statusInfo['status'] === 'failed') {
  3668. $task->updateStatus('failed', [
  3669. 'error_message' => $statusInfo['error_message'],
  3670. 'result_json' => $statusInfo['result_json'] ?? []
  3671. ]);
  3672. if (getProp($task, 'alias_segment_id')) {
  3673. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3674. 'pic_task_status' => '失败',
  3675. ]);
  3676. }
  3677. break;
  3678. }
  3679. $start_count++;
  3680. }
  3681. return $img_url;
  3682. }
  3683. /**
  3684. * 从分镜内容中提取涉及的角色
  3685. */
  3686. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3687. $found_characters = [];
  3688. foreach ($available_characters as $character) {
  3689. // 检查角色名称是否在分镜内容中出现
  3690. if (strpos($segment_content, $character) !== false) {
  3691. $found_characters[] = $character;
  3692. }
  3693. }
  3694. if (!$found_characters) {
  3695. foreach ($roles as $character) {
  3696. // 检查角色名称是否在分镜内容中出现
  3697. if (strpos($segment_content, $character) !== false) {
  3698. $found_characters[] = $character;
  3699. }
  3700. }
  3701. }
  3702. return array_unique($found_characters);
  3703. }
  3704. // 从分镜剧本中提取关键字段
  3705. private function handleSegmentContent(&$data) {
  3706. $segmentContent = getProp($data, 'segment_content');
  3707. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3708. $segmentData = [
  3709. 'description' => '',
  3710. 'composition' => '',
  3711. 'camera_movement' => '',
  3712. 'voice_actor' => '',
  3713. 'dialogue' => '',
  3714. 'frame_type' => '',
  3715. 'scene' => '', // 场景
  3716. 'characters' => '', // 出镜角色
  3717. 'tail_frame' => '', // 尾帧描述
  3718. 'emotion' => '中性', // 情感
  3719. 'gender' => '0', // 性别(0未知,1男,2女)
  3720. 'speed_ratio' => 0, // 语速
  3721. 'loudness_ratio' => 0, // 音量
  3722. 'emotion_scale' => 4, // 情感强度
  3723. 'pitch' => 0, // 音调
  3724. ];
  3725. // 用于存储需要从 segment_content 中移除的匹配项
  3726. $replaceEmptyArr = [];
  3727. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3728. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3729. $segmentData['description'] = trim($descMatch[1]);
  3730. $data['description'] = trim($descMatch[1]);
  3731. }
  3732. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3733. $segmentData['composition'] = trim($compMatch[1]);
  3734. $data['composition'] = trim($compMatch[1]);
  3735. }
  3736. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3737. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3738. $data['camera_movement'] = trim($cameraMatch[1]);
  3739. }
  3740. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3741. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3742. $data['voice_actor'] = trim($voiceMatch[1]);
  3743. }
  3744. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3745. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3746. $data['dialogue'] = trim($dialogueMatch[1]);
  3747. }
  3748. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3749. $segmentData['frame_type'] = trim($frameMatch[1]);
  3750. $data['frame_type'] = trim($frameMatch[1]);
  3751. }
  3752. // 场景字段
  3753. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3754. $segmentData['scene'] = trim($sceneMatch[1]);
  3755. $data['scene'] = trim($sceneMatch[1]);
  3756. }
  3757. // 出镜角色字段
  3758. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3759. $segmentData['characters'] = trim($charactersMatch[1]);
  3760. $data['characters'] = trim($charactersMatch[1]);
  3761. }
  3762. // 尾帧描述字段
  3763. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3764. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3765. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3766. }
  3767. // 情感字段
  3768. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3769. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3770. $segmentData['emotion'] = trim($emotionMatch[1]);
  3771. $data['emotion'] = trim($emotionMatch[1]);
  3772. }
  3773. // 性别字段
  3774. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3775. $replaceEmptyArr[] = trim($genderMatch[0]);
  3776. $genderStr = trim($genderMatch[1]);
  3777. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3778. $segmentData['gender'] = '1';
  3779. $data['gender'] = '1';
  3780. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3781. $segmentData['gender'] = '2';
  3782. $data['gender'] = '2';
  3783. } else {
  3784. $segmentData['gender'] = '0';
  3785. $data['gender'] = '0';
  3786. }
  3787. }
  3788. // 语速字段
  3789. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3790. $replaceEmptyArr[] = trim($speedMatch[0]);
  3791. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3792. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3793. }
  3794. // 音量字段
  3795. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3796. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3797. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3798. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3799. }
  3800. // 情感强度字段
  3801. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3802. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3803. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3804. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3805. }
  3806. // 音调字段
  3807. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3808. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3809. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3810. $data['pitch'] = (int)trim($pitchMatch[1]);
  3811. }
  3812. // 从 segment_content 中移除已提取的配音参数字段
  3813. if (!empty($replaceEmptyArr)) {
  3814. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3815. }
  3816. // 如果有配音角色,查询音色信息并验证情感
  3817. $voice_actor = $segmentData['voice_actor'];
  3818. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3819. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3820. $anime_id = getProp($data, 'anime_id');
  3821. $episode_id = getProp($data, 'episode_id');
  3822. // 优先从剧集的角色列表中查找
  3823. $roles = [];
  3824. if ($episode_id) {
  3825. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3826. if ($episode && getProp($episode, 'roles')) {
  3827. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3828. }
  3829. }
  3830. // 如果剧集中没有,从动漫的角色列表中查找
  3831. if (empty($roles) && $anime_id) {
  3832. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3833. if ($anime && getProp($anime, 'roles')) {
  3834. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3835. }
  3836. }
  3837. // 查找匹配的角色音色信息
  3838. $timbre_info = null;
  3839. foreach ($roles as $role) {
  3840. if (getProp($role, 'role') === $voice_actor) {
  3841. $timbre_info = $role;
  3842. break;
  3843. }
  3844. }
  3845. // 如果找到音色信息,添加到数据中
  3846. if ($timbre_info) {
  3847. $voice_type = getProp($timbre_info, 'voice_type');
  3848. $voice_name = getProp($timbre_info, 'voice_name');
  3849. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3850. if ($voice_type) {
  3851. $data['voice_type'] = $voice_type;
  3852. $segmentData['voice_type'] = $voice_type;
  3853. }
  3854. if ($voice_name) {
  3855. $data['voice_name'] = $voice_name;
  3856. $segmentData['voice_name'] = $voice_name;
  3857. }
  3858. if ($voice_audio_url) {
  3859. $data['voice_audio_url'] = $voice_audio_url;
  3860. $segmentData['voice_audio_url'] = $voice_audio_url;
  3861. }
  3862. // 验证情感是否在音色支持的情感列表中
  3863. if ($voice_type) {
  3864. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3865. if ($timbre_emotion) {
  3866. $timbre_emotion = explode(',', $timbre_emotion);
  3867. } else {
  3868. $timbre_emotion = [];
  3869. }
  3870. $emotion = getProp($segmentData, 'emotion', '中性');
  3871. if (!in_array($emotion, $timbre_emotion)) {
  3872. $emotion = '中性';
  3873. }
  3874. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3875. $emotion_list = array_flip($emotion_list);
  3876. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3877. $data['emotion_type'] = $emotion_type;
  3878. $segmentData['emotion_type'] = $emotion_type;
  3879. }
  3880. }
  3881. }
  3882. return $segmentData;
  3883. }
  3884. public function createSegmentVideoTask($data) {
  3885. $segment_id = getProp($data, 'segment_id');
  3886. $tail_frame = getProp($data, 'tail_frame');
  3887. $first_frame_url = getProp($data, 'first_frame_url');
  3888. $tail_frame_url = getProp($data, 'tail_frame_url');
  3889. $generate_audio = getProp($data, 'generate_audio', 0);
  3890. if (!$segment_id) {
  3891. Utils::throwError('1002:分镜ID不能为空');
  3892. }
  3893. // 获取分镜信息
  3894. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3895. if (!$segment) {
  3896. Utils::throwError('20003:分镜不存在');
  3897. }
  3898. $segment = (array)$segment;
  3899. $episode_id = getProp($segment, 'episode_id');
  3900. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3901. if (!$ratio) $ratio = '9:16';
  3902. // 获取分镜内容
  3903. $segmentContent = getProp($segment, 'segment_content', '');
  3904. // 检查 $segmentContent 中是否已有尾帧描述
  3905. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3906. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3907. $finalTailFrame = '';
  3908. if ($tail_frame) {
  3909. // 用户输入了尾帧描述,优先使用
  3910. $finalTailFrame = $tail_frame;
  3911. // 如果 segmentContent 中已有尾帧描述,需要替换
  3912. if ($contentHasTailFrame) {
  3913. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3914. }
  3915. } elseif ($contentHasTailFrame) {
  3916. // segmentContent 中有尾帧描述,使用它
  3917. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3918. } else {
  3919. // 两者都没有,使用分镜表中的尾帧描述
  3920. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3921. }
  3922. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3923. $hasDialogue = false;
  3924. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3925. $dialogue = trim($dialogueMatch[1]);
  3926. // 如果台词不为空且不是"无"
  3927. if (!empty($dialogue) && $dialogue !== '无') {
  3928. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3929. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3930. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3931. $hasDialogue = true;
  3932. }
  3933. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3934. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3935. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3936. if (!preg_match('/^[“]/', $dialogue)) {
  3937. $dialogue = '“' . $dialogue;
  3938. }
  3939. if (!preg_match('/[”]$/', $dialogue)) {
  3940. $dialogue .= '”';
  3941. }
  3942. // 将修改后的台词替换回 $segmentContent
  3943. $originalDialogue = $dialogueMatch[1];
  3944. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3945. }
  3946. }
  3947. // 构建完整的提示词
  3948. $fullPrompt = $segmentContent;
  3949. if ($finalTailFrame && !$contentHasTailFrame) {
  3950. // 只有当 segmentContent 中没有尾帧描述时才追加
  3951. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3952. }
  3953. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3954. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3955. $fullPrompt = trim($fullPrompt);
  3956. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3957. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3958. // 智能选择视频时长
  3959. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3960. $videoDuration = -1;
  3961. // 处理视频模型
  3962. $model = getProp($data, 'model');
  3963. if (!$model) {
  3964. // 用户没有输入,从episode表获取
  3965. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3966. $model = getProp($episode, 'video_model');
  3967. if (!$model) {
  3968. // episode表也没有,使用默认值
  3969. $model = 'doubao-seedance-1-5-pro-251215';
  3970. }
  3971. }
  3972. // 验证模型是否在可用模型表中
  3973. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3974. $model = 'doubao-seedance-1-5-pro-251215';
  3975. }
  3976. // 保存到episode表
  3977. $episode_id = getProp($segment, 'episode_id');
  3978. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3979. 'video_model' => $model,
  3980. 'updated_at' => date('Y-m-d H:i:s')
  3981. ]);
  3982. // 构建视频生成参数
  3983. $videoParams = [
  3984. 'model' => $model,
  3985. 'alias_segment_id' => $segment_id,
  3986. 'prompt' => trim($fullPrompt),
  3987. 'video_duration' => $videoDuration,
  3988. 'video_resolution' => '720P',
  3989. 'seed' => -1,
  3990. 'ratio' => $ratio,
  3991. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3992. 'draft' => false,
  3993. 'watermark' => false,
  3994. 'camera_fixed' => false,
  3995. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3996. ];
  3997. // 如果分镜有图片,作为首帧
  3998. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3999. $hasVideo = !empty(getProp($segment, 'video_url'));
  4000. if ($hasImage) {
  4001. if ($first_frame_url) {
  4002. $videoParams['first_frame_url'] = $first_frame_url;
  4003. }else {
  4004. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4005. }
  4006. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4007. }
  4008. // 构建content数组
  4009. $videoParams['content'] = [
  4010. [
  4011. 'type' => 'text',
  4012. 'text' => $videoParams['prompt'],
  4013. ]
  4014. ];
  4015. // 如果有首帧图片,添加到content中
  4016. if ($hasImage) {
  4017. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4018. $videoParams['content'][] = [
  4019. 'type' => 'image_url',
  4020. 'image_url' => [
  4021. 'url' => $videoParams['first_frame_url'],
  4022. ],
  4023. 'role' => 'reference_image',
  4024. ];
  4025. if (isset($videoParams['tail_frame_url'])) {
  4026. $videoParams['content'][] = [
  4027. 'type' => 'image_url',
  4028. 'image_url' => [
  4029. 'url' => $videoParams['tail_frame_url'],
  4030. ],
  4031. 'role' => 'reference_image',
  4032. ];
  4033. }
  4034. }else {
  4035. $videoParams['content'][] = [
  4036. 'type' => 'image_url',
  4037. 'image_url' => [
  4038. 'url' => $videoParams['first_frame_url'],
  4039. ],
  4040. 'role' => 'first_frame',
  4041. ];
  4042. if (isset($videoParams['tail_frame_url'])) {
  4043. $videoParams['content'][] = [
  4044. 'type' => 'image_url',
  4045. 'image_url' => [
  4046. 'url' => $videoParams['tail_frame_url'],
  4047. ],
  4048. 'role' => 'last_frame',
  4049. ];
  4050. }
  4051. }
  4052. }
  4053. // 获取配音音频URL
  4054. $audioUrl = getProp($segment, 'audio_url');
  4055. $audioDuration = getProp($segment, 'audio_duration');
  4056. // 音频传入的前提:必须有至少一张图片或一个视频
  4057. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4058. // 余额预检:按预估时长计算所需积分,不足直接报错
  4059. $chargeDuration = (int)ceil((float)$audioDuration);
  4060. if ($chargeDuration <= 0) {
  4061. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4062. }
  4063. $this->pointsService->checkUserPointsEnough(
  4064. $this->pointsService->getVideoChargePoints([
  4065. 'model' => $model,
  4066. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4067. 'video_duration' => $chargeDuration,
  4068. 'ratio' => $ratio,
  4069. 'generate_audio' => $current_generate_audio,
  4070. ])
  4071. );
  4072. // dd($videoParams);
  4073. // 根据模型选择不同的视频生成方法
  4074. if (strpos($model, 'jimeng') !== false) {
  4075. // 即梦模型参数调整
  4076. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4077. unset($videoParams['content']); // 即梦不使用content格式
  4078. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4079. } elseif (strpos($model, 'kling') !== false) {
  4080. // Keling模型参数调整
  4081. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4082. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4083. unset($videoParams['ratio']);
  4084. unset($videoParams['content']); // Keling不使用content格式
  4085. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4086. } elseif (strpos($model, 'zhizhen') !== false) {
  4087. // 智帧20等新模型使用统一API
  4088. // 构建统一API参数
  4089. $unifiedParams = [
  4090. 'model_code' => $model,
  4091. 'alias_segment_id' => $segment_id,
  4092. 'prompt' => trim($fullPrompt),
  4093. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4094. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4095. 'video_ratio' => $ratio,
  4096. 'seed' => -1,
  4097. ];
  4098. // 构建parameters参数
  4099. $parameters = [
  4100. 'seconds' => $unifiedParams['video_duration'],
  4101. 'resolution' => $unifiedParams['video_resolution'],
  4102. 'ratio' => $ratio,
  4103. // 'video_mode' => 'multi_image',
  4104. // 'mode' => 'multi_image',
  4105. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4106. ];
  4107. $hasImage = false;
  4108. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4109. if ($hasImage) {
  4110. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4111. if (isset($videoParams['tail_frame_url'])) {
  4112. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4113. }
  4114. // 只有在有图片的情况下才能添加参考音频
  4115. if ($audioUrl) {
  4116. // $parameters['reference_audios'] = [$audioUrl];
  4117. }
  4118. } else {
  4119. // 没有图片时,记录错误日志
  4120. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4121. 'segment_id' => $segment_id,
  4122. 'model' => $model
  4123. ]);
  4124. }
  4125. $unifiedParams['parameters'] = $parameters;
  4126. // 调用统一API创建任务
  4127. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4128. } else {
  4129. // Seedance模型(默认)
  4130. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4131. if ($this->isKuaikuaiSeedanceModel($model)) {
  4132. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4133. if ($canUseAudio && $audioUrl) {
  4134. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4135. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4136. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4137. // 优化提示词,增加音频相关描述
  4138. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4139. $videoParams['prompt'] = $audioPrompt;
  4140. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4141. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4142. }
  4143. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4144. } elseif ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4145. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4146. // 添加配音音频到content中
  4147. $videoParams['content'][] = [
  4148. 'type' => 'audio_url',
  4149. 'audio_url' => [
  4150. 'url' => $audioUrl,
  4151. ],
  4152. 'role' => 'reference_audio',
  4153. ];
  4154. // 优化提示词,增加音频相关描述
  4155. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4156. $videoParams['prompt'] = $audioPrompt;
  4157. $videoParams['content'][0]['text'] = $audioPrompt;
  4158. } else {
  4159. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4160. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4161. }
  4162. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4163. }
  4164. }
  4165. // 更新分镜表的视频任务信息
  4166. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4167. 'video_task_id' => $task->id,
  4168. 'video_task_status' => '生成中',
  4169. 'generate_audio' => $generate_audio,
  4170. 'updated_at' => date('Y-m-d H:i:s')
  4171. ]);
  4172. return [
  4173. 'task_id' => $task->id,
  4174. 'status' => $task->status,
  4175. 'segment_id' => $segment_id,
  4176. 'video_duration' => $videoDuration
  4177. ];
  4178. }
  4179. /**
  4180. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4181. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4182. *
  4183. * @param string $model
  4184. * @return bool
  4185. */
  4186. private function isKuaikuaiSeedanceModel(string $model): bool
  4187. {
  4188. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4189. }
  4190. public function createActVideoTask($data) {
  4191. $act_id = getProp($data, 'act_id');
  4192. $first_frame_url = getProp($data, 'first_frame_url');
  4193. $tail_frame_url = getProp($data, 'tail_frame_url');
  4194. $generate_audio = getProp($data, 'generate_audio', 1);
  4195. $video_duration = getProp($data, 'video_duration');
  4196. $video_resolution = getProp($data, 'video_resolution');
  4197. $ratio = getProp($data, 'ratio');
  4198. $products = getProp($data, 'products', []);
  4199. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4200. if (!is_array($reference_images) || !is_array($products)) {
  4201. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4202. }
  4203. if (!$act_id) {
  4204. Utils::throwError('1002:片段ID不能为空');
  4205. }
  4206. // 获取片段信息
  4207. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4208. if (!$act) {
  4209. Utils::throwError('20003:片段不存在');
  4210. }
  4211. $act = (array)$act;
  4212. $anime_id = getProp($act, 'anime_id');
  4213. $episode_id = getProp($act, 'episode_id');
  4214. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4215. $ace_mode = getProp($anime, 'ace_mode');
  4216. $art_style_type = getProp($anime, 'art_style_type');
  4217. $art_style = getProp($anime, 'art_style');
  4218. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4219. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4220. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4221. // 将资产中新出现的资产放到extra_products中
  4222. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4223. if (!empty($products) && $episode) {
  4224. // 获取剧集中的角色、场景和道具列表
  4225. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4226. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4227. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4228. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4229. // 构建角色名称列表
  4230. $role_names = array_column($roles, 'role');
  4231. // 构建场景名称列表
  4232. $scene_names = array_column($scenes, 'scene');
  4233. // 构建道具名称列表
  4234. $prop_names = array_column($props, 'prop');
  4235. // 遍历传入的products
  4236. foreach ($products as $product) {
  4237. $product_name = getProp($product, 'product_name');
  4238. // 如果product_name不在roles、scenes和props中
  4239. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4240. // 查找是否在extra_products中存在同名的
  4241. $found = false;
  4242. foreach ($extra_products as $key => $extra_product) {
  4243. if (getProp($extra_product, 'product_name') === $product_name) {
  4244. // 有同名的则覆盖
  4245. $extra_products[$key] = $product;
  4246. $found = true;
  4247. break;
  4248. }
  4249. }
  4250. // 没有则新增
  4251. if (!$found) {
  4252. $extra_products[] = $product;
  4253. }
  4254. }
  4255. }
  4256. if ($extra_products) {
  4257. // 保存到数据库
  4258. DB::table('mp_anime_episodes')
  4259. ->where('id', $episode_id)
  4260. ->update([
  4261. 'extra_products' => json_encode($extra_products, 256),
  4262. 'updated_at' => date('Y-m-d H:i:s')
  4263. ]);
  4264. }
  4265. }
  4266. // 获取分镜内容
  4267. $actContent = getProp($act, 'act_show_content', '');
  4268. // 音效同出(默认使用)
  4269. $current_generate_audio = $generate_audio ? 1 : 0;
  4270. // 构建完整的提示词
  4271. $processResult = $this->processActContentWithProducts($actContent, $products);
  4272. $fullPrompt = $processResult['content'];
  4273. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4274. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4275. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4276. // 处理视频模型
  4277. $model = getProp($data, 'model');
  4278. if (!$model) {
  4279. $model = getProp($episode, 'video_model');
  4280. if (!$model) {
  4281. // episode表也没有,使用默认值
  4282. $model = 'zhizhen-20';
  4283. }
  4284. }
  4285. // 验证模型是否在可用模型表中
  4286. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4287. $model = 'zhizhen-20';
  4288. }
  4289. // 保存到episode表(仅在专用方法中更新模型)
  4290. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4291. // 'video_model' => $model,
  4292. // 'updated_at' => date('Y-m-d H:i:s')
  4293. // ]);
  4294. // 余额预检:按预估时长计算所需积分,不足直接报错
  4295. $chargeDuration = (int)$videoDuration;
  4296. if ($chargeDuration <= 0) {
  4297. $chargeDuration = 5; // 无时长时按默认5秒预估
  4298. }
  4299. $this->pointsService->checkUserPointsEnough(
  4300. $this->pointsService->getVideoChargePoints([
  4301. 'model' => $model,
  4302. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4303. 'video_duration' => $chargeDuration,
  4304. 'ratio' => $ratio,
  4305. 'generate_audio' => $current_generate_audio,
  4306. ])
  4307. );
  4308. // 构建视频生成参数
  4309. $videoParams = [
  4310. 'model' => $model,
  4311. 'alias_act_id' => $act_id,
  4312. 'prompt' => trim($fullPrompt),
  4313. 'video_duration' => $videoDuration,
  4314. 'video_resolution' => $video_resolution,
  4315. 'seed' => -1,
  4316. 'ratio' => $ratio,
  4317. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4318. 'draft' => false,
  4319. 'watermark' => false,
  4320. 'camera_fixed' => false,
  4321. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4322. ];
  4323. // 如果分镜有图片,作为首帧
  4324. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4325. $hasVideo = !empty(getProp($act, 'video_url'));
  4326. if ($hasImage) {
  4327. if ($first_frame_url) {
  4328. $videoParams['first_frame_url'] = $first_frame_url;
  4329. }else {
  4330. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4331. }
  4332. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4333. }
  4334. // 构建content数组
  4335. $videoParams['content'] = [
  4336. [
  4337. 'type' => 'text',
  4338. 'text' => $videoParams['prompt'],
  4339. ]
  4340. ];
  4341. // 如果有首帧图片,添加到content中
  4342. if ($hasImage) {
  4343. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0'])) {
  4344. $videoParams['content'][] = [
  4345. 'type' => 'image_url',
  4346. 'image_url' => [
  4347. 'url' => $videoParams['first_frame_url'],
  4348. ],
  4349. 'role' => 'reference_image',
  4350. ];
  4351. if (isset($videoParams['tail_frame_url'])) {
  4352. $videoParams['content'][] = [
  4353. 'type' => 'image_url',
  4354. 'image_url' => [
  4355. 'url' => $videoParams['tail_frame_url'],
  4356. ],
  4357. 'role' => 'reference_image',
  4358. ];
  4359. }
  4360. }else {
  4361. $videoParams['content'][] = [
  4362. 'type' => 'image_url',
  4363. 'image_url' => [
  4364. 'url' => $videoParams['first_frame_url'],
  4365. ],
  4366. 'role' => 'first_frame',
  4367. ];
  4368. if (isset($videoParams['tail_frame_url'])) {
  4369. $videoParams['content'][] = [
  4370. 'type' => 'image_url',
  4371. 'image_url' => [
  4372. 'url' => $videoParams['tail_frame_url'],
  4373. ],
  4374. 'role' => 'last_frame',
  4375. ];
  4376. }
  4377. }
  4378. }
  4379. // dd($videoParams);
  4380. // 根据模型选择不同的视频生成方法
  4381. if (strpos($model, 'jimeng') !== false) {
  4382. // 即梦模型参数调整
  4383. unset($videoParams['content']); // 即梦不使用content格式
  4384. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4385. } elseif (strpos($model, 'kling') !== false) {
  4386. // Keling模型参数调整
  4387. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4388. unset($videoParams['ratio']);
  4389. unset($videoParams['content']); // Keling不使用content格式
  4390. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4391. } elseif (strpos($model, 'zhizhen') !== false) {
  4392. // 智帧20等新模型使用统一API
  4393. // 构建统一API参数
  4394. $unifiedParams = [
  4395. 'model_code' => $model,
  4396. 'alias_act_id' => $act_id,
  4397. 'prompt' => trim($fullPrompt),
  4398. 'video_duration' => $videoDuration,
  4399. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4400. 'video_ratio' => $ratio,
  4401. 'seed' => -1,
  4402. ];
  4403. // 构建parameters参数
  4404. $parameters = [
  4405. 'seconds' => $unifiedParams['video_duration'],
  4406. 'resolution' => $unifiedParams['video_resolution'],
  4407. 'ratio' => $ratio,
  4408. // 'video_mode' => 'multi_image',
  4409. // 'mode' => 'multi_image',
  4410. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4411. ];
  4412. $hasImage = false;
  4413. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4414. if ($hasImage) {
  4415. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4416. if (isset($videoParams['tail_frame_url'])) {
  4417. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4418. }
  4419. } else {
  4420. // 没有图片时,记录错误日志
  4421. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4422. 'act_id' => $act_id,
  4423. 'model' => $model
  4424. ]);
  4425. }
  4426. if ($reference_images) {
  4427. // 限制只传入9张参考图
  4428. $reference_images = array_slice($reference_images, 0, 9);
  4429. // 在处理之前先保存原始reference_images到任务参数中
  4430. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4431. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4432. $parameters['reference_images'] = $reference_images;
  4433. $parameters['video_mode'] = 'multi_image';
  4434. $parameters['mode'] = 'multi_image';
  4435. }
  4436. $unifiedParams['parameters'] = $parameters;
  4437. // 调用统一API创建任务
  4438. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4439. } elseif (strpos($model, 'doubao-seedance-2.0') !== false || $this->isKuaikuaiSeedanceModel($model)) {
  4440. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4441. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4442. // 保存原始参考图用于任务记录
  4443. $videoParams['reference_images'] = $reference_images;
  4444. if ($reference_images) {
  4445. // 限制只传入9张参考图
  4446. $reference_images = array_slice($reference_images, 0, 9);
  4447. // 参考图上传为素材(百度网关/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4448. $reference_image_assets = $isKuaikuai
  4449. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4450. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4451. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4452. $videoParams['prompt'] = trim($fullPrompt);
  4453. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4454. $videoParams['reference_image_assets'] = $reference_image_assets;
  4455. }
  4456. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4457. if ($isKuaikuai) {
  4458. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4459. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4460. } else {
  4461. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4462. }
  4463. } else {
  4464. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4465. }
  4466. // 更新分镜表的视频任务信息
  4467. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4468. 'video_task_id' => $task->id,
  4469. 'video_task_status' => '生成中',
  4470. 'generate_audio' => $generate_audio,
  4471. 'updated_at' => date('Y-m-d H:i:s')
  4472. ]);
  4473. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4474. $episode_number = getProp($act, 'episode_number');
  4475. $act_number = getProp($act, 'act_number');
  4476. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4477. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4478. }
  4479. return [
  4480. 'task_id' => $task->id,
  4481. 'status' => $task->status,
  4482. 'act_id' => $act_id,
  4483. 'video_duration' => $videoDuration
  4484. ];
  4485. }
  4486. /**
  4487. * 文生视频通用方法
  4488. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4489. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4490. *
  4491. * @param array $data 请求参数
  4492. * @return array
  4493. */
  4494. public function generateVideo($data) {
  4495. $prompt = getProp($data, 'prompt');
  4496. if (empty($prompt)) {
  4497. Utils::throwError('20003:提示词不能为空');
  4498. }
  4499. $model = getProp($data, 'model');
  4500. if (!$model) {
  4501. $model = 'zhizhen-20';
  4502. }
  4503. // 验证模型是否在可用模型表中
  4504. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4505. Utils::throwError('20003:该模型已不可用,请更换!');
  4506. }
  4507. $video_duration = getProp($data, 'video_duration', 5);
  4508. $video_resolution = getProp($data, 'video_resolution', '480p');
  4509. $ratio = getProp($data, 'ratio', '9:16');
  4510. $generate_audio = getProp($data, 'generate_audio', 1);
  4511. $seed = getProp($data, 'seed', -1);
  4512. $first_frame_url = getProp($data, 'first_frame_url');
  4513. $tail_frame_url = getProp($data, 'tail_frame_url');
  4514. // 参考图(支持数组或JSON字符串,最多9张)
  4515. $reference_images = getProp($data, 'reference_images', []);
  4516. if (is_string($reference_images)) {
  4517. $reference_images = json_decode($reference_images, true) ?: [];
  4518. }
  4519. if (!is_array($reference_images)) {
  4520. Utils::throwError('20003:参考图格式不正确');
  4521. }
  4522. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4523. $reference_images = array_slice($reference_images, 0, 9);
  4524. // 参考视频(支持数组或JSON字符串,最多3个)
  4525. $reference_videos = getProp($data, 'reference_videos', []);
  4526. if (is_string($reference_videos)) {
  4527. $reference_videos = json_decode($reference_videos, true) ?: [];
  4528. }
  4529. if (!is_array($reference_videos)) {
  4530. Utils::throwError('20003:参考视频格式不正确');
  4531. }
  4532. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4533. if (count($reference_videos) > 3) {
  4534. Utils::throwError('20003:参考视频最多选择3个');
  4535. }
  4536. $reference_videos = array_slice($reference_videos, 0, 3);
  4537. // 参考音频(支持数组或JSON字符串,最多3个)
  4538. $reference_audios = getProp($data, 'reference_audios', []);
  4539. if (is_string($reference_audios)) {
  4540. $reference_audios = json_decode($reference_audios, true) ?: [];
  4541. }
  4542. if (!is_array($reference_audios)) {
  4543. Utils::throwError('20003:参考音频格式不正确');
  4544. }
  4545. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4546. if (count($reference_audios) > 3) {
  4547. Utils::throwError('20003:参考音频最多选择3个');
  4548. }
  4549. $reference_audios = array_slice($reference_audios, 0, 3);
  4550. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4551. $videoParams = [
  4552. 'model' => $model,
  4553. 'prompt' => $prompt,
  4554. 'video_duration' => $video_duration,
  4555. 'video_resolution' => $video_resolution,
  4556. 'seed' => $seed,
  4557. 'ratio' => $ratio,
  4558. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4559. 'draft' => getProp($data, 'draft', false),
  4560. 'watermark' => getProp($data, 'watermark', false),
  4561. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4562. ];
  4563. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4564. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4565. // 构建content数组
  4566. $videoParams['content'] = [
  4567. [
  4568. 'type' => 'text',
  4569. 'text' => $prompt,
  4570. ]
  4571. ];
  4572. // 根据模型选择不同的视频生成方法
  4573. if (strpos($model, 'jimeng') !== false) {
  4574. // 即梦模型参数调整
  4575. unset($videoParams['content']); // 即梦不使用content格式
  4576. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4577. } elseif (strpos($model, 'kling') !== false) {
  4578. // 可灵模型参数调整
  4579. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4580. unset($videoParams['ratio']);
  4581. unset($videoParams['content']); // 可灵不使用content格式
  4582. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4583. } elseif (strpos($model, 'zhizhen') !== false) {
  4584. // 智帧等新模型使用统一API
  4585. $unifiedParams = [
  4586. 'model_code' => $model,
  4587. 'prompt' => $prompt,
  4588. 'video_duration' => $video_duration,
  4589. 'video_resolution' => strtolower($video_resolution),
  4590. 'video_ratio' => $ratio,
  4591. 'seed' => $seed,
  4592. ];
  4593. // 构建parameters参数
  4594. $parameters = [
  4595. 'seconds' => $unifiedParams['video_duration'],
  4596. 'resolution' => $unifiedParams['video_resolution'],
  4597. 'ratio' => $ratio,
  4598. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4599. ];
  4600. // 首帧和尾帧
  4601. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4602. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4603. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4604. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4605. if ($refImageUrls) {
  4606. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4607. }
  4608. // 参考图处理
  4609. if ($reference_images) {
  4610. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4611. $parameters['reference_images'] = $reference_images;
  4612. $parameters['video_mode'] = 'multi_image';
  4613. $parameters['mode'] = 'multi_image';
  4614. }
  4615. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4616. if ($reference_videos) {
  4617. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4618. $parameters['reference_videos'] = $reference_videos;
  4619. }
  4620. if ($reference_audios) {
  4621. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4622. $parameters['reference_audios'] = $reference_audios;
  4623. }
  4624. $unifiedParams['parameters'] = $parameters;
  4625. // 调用统一API创建任务
  4626. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4627. } elseif (strpos($model, 'doubao-seedance-2.0') !== false || $this->isKuaikuaiSeedanceModel($model)) {
  4628. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4629. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4630. $videoParams['reference_images'] = $reference_images;
  4631. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4632. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4633. if ($refImageUrls) {
  4634. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4635. }
  4636. if ($reference_images) {
  4637. // 参考图上传为素材(百度网关/快快AI)
  4638. $reference_image_assets = $isKuaikuai
  4639. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4640. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']);
  4641. $videoParams['reference_image_assets'] = $reference_image_assets;
  4642. }
  4643. // 参考视频上传为素材(百度网关/快快AI)
  4644. if ($reference_videos) {
  4645. $reference_video_assets = $isKuaikuai
  4646. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4647. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']);
  4648. $videoParams['reference_video_assets'] = $reference_video_assets;
  4649. }
  4650. // 参考音频上传为素材(百度网关/快快AI)
  4651. if ($reference_audios) {
  4652. $reference_audio_assets = $isKuaikuai
  4653. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4654. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']);
  4655. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4656. }
  4657. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4658. if ($reference_images || $reference_videos || $reference_audios) {
  4659. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4660. }
  4661. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4662. if ($isKuaikuai) {
  4663. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4664. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4665. } else {
  4666. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4667. }
  4668. } else {
  4669. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4670. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4671. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4672. if ($refImageUrls) {
  4673. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4674. }
  4675. if ($reference_videos) {
  4676. foreach ($reference_videos as $videoUrl) {
  4677. $videoParams['content'][] = [
  4678. 'type' => 'video_url',
  4679. 'video_url' => [
  4680. 'url' => $videoUrl,
  4681. ],
  4682. 'role' => 'reference_video',
  4683. ];
  4684. }
  4685. }
  4686. if ($reference_audios) {
  4687. foreach ($reference_audios as $audioUrl) {
  4688. $videoParams['content'][] = [
  4689. 'type' => 'audio_url',
  4690. 'audio_url' => [
  4691. 'url' => $audioUrl,
  4692. ],
  4693. 'role' => 'reference_audio',
  4694. ];
  4695. }
  4696. }
  4697. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4698. }
  4699. return [
  4700. 'task_id' => $task->id,
  4701. 'status' => $task->status,
  4702. 'model' => $model,
  4703. 'video_duration' => $video_duration,
  4704. 'video_resolution' => $video_resolution,
  4705. 'ratio' => $ratio
  4706. ];
  4707. }
  4708. /**
  4709. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4710. *
  4711. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4712. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4713. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4714. *
  4715. * @param array $data
  4716. * @return array
  4717. */
  4718. public function previewCharge(array $data): array
  4719. {
  4720. $mode = (string)getProp($data, 'mode', '');
  4721. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4722. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4723. }
  4724. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4725. $scene = (string)getProp($data, 'scene', 'video_generation');
  4726. $items = [];
  4727. $model = '';
  4728. $resolution = '';
  4729. if ($mode === 'video') {
  4730. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4731. $model = (string)getProp($data, 'model', '');
  4732. if (!$model) {
  4733. Utils::throwError('1002:model参数不能为空');
  4734. }
  4735. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4736. $duration = (int)getProp($data, 'video_duration', 5);
  4737. if ($duration <= 0) {
  4738. $duration = 5;
  4739. }
  4740. $count = max(1, (int)getProp($data, 'count', 1));
  4741. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4742. 'model' => $model,
  4743. 'video_resolution' => $resolution,
  4744. 'video_duration' => $duration,
  4745. 'mode' => $scene,
  4746. ]);
  4747. $points = $pointsPerVideo * $count;
  4748. $items[] = [
  4749. 'type' => 'video',
  4750. 'model' => $model,
  4751. 'video_resolution' => $resolution,
  4752. 'video_duration' => $duration,
  4753. 'count' => $count,
  4754. 'points' => $points,
  4755. ];
  4756. } elseif ($mode === 'image') {
  4757. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4758. $model = (string)getProp($data, 'model', '');
  4759. if (!$model) {
  4760. Utils::throwError('1002:model参数不能为空');
  4761. }
  4762. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4763. if (!$resolution) {
  4764. $width = (int)getProp($data, 'width', 0);
  4765. $height = (int)getProp($data, 'height', 0);
  4766. if ($width <= 0 || $height <= 0) {
  4767. $width = 1600;
  4768. $height = 2848;
  4769. }
  4770. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4771. }
  4772. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4773. $points = $this->pointsService->getImageChargePoints([
  4774. 'model' => $model,
  4775. 'resolution' => $resolution,
  4776. ]) * $imageNum;
  4777. $items[] = [
  4778. 'type' => 'image',
  4779. 'model' => $model,
  4780. 'resolution' => $resolution,
  4781. 'image_num' => $imageNum,
  4782. 'points' => $points,
  4783. ];
  4784. } else {
  4785. // AI对话预估:单次10积分;批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算
  4786. $count = max(1, (int)getProp($data, 'count', 1));
  4787. $animeId = getProp($data, 'anime_id');
  4788. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4789. if ($animeId && $generateEpisodes > 0) {
  4790. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4791. ->where('anime_id', $animeId)
  4792. ->where('is_default', 1)
  4793. ->max('episode_number');
  4794. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4795. $startEpisodeNumber = $currentMaxEpisode + 1;
  4796. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4797. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4798. ->where('anime_id', $animeId)
  4799. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4800. ->whereIn('status', ['pending', 'processing', 'completed'])
  4801. ->count();
  4802. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4803. if ($count < 0) {
  4804. $count = 0;
  4805. }
  4806. }
  4807. $points = $this->pointsService->getChatChargePoints((string)$model) * $count;
  4808. $items[] = [
  4809. 'type' => 'chat',
  4810. 'count' => $count,
  4811. 'points' => $points,
  4812. ];
  4813. }
  4814. $totalPoints = 0;
  4815. foreach ($items as $item) {
  4816. $totalPoints += $item['points'];
  4817. }
  4818. return [
  4819. 'mode' => $mode,
  4820. 'total_points' => $totalPoints,
  4821. 'items' => $items,
  4822. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4823. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4824. ];
  4825. }
  4826. /**
  4827. * 根据提示词内容智能计算最优视频时长
  4828. *
  4829. * @param string $segmentContent 分镜内容
  4830. * @param string $tailFrame 尾帧描述
  4831. * @return int 视频时长(2-12秒)
  4832. */
  4833. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4834. // 合并所有文本内容
  4835. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4836. // 如果没有内容,返回默认时长
  4837. if (empty($fullText)) {
  4838. return 5;
  4839. }
  4840. // 计算文本长度(中文字符按2个字符计算)
  4841. $textLength = mb_strlen($fullText, 'UTF-8');
  4842. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4843. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4844. // 分析内容复杂度
  4845. $complexityScore = $this->analyzeContentComplexity($fullText);
  4846. // 基础时长计算(根据文本长度)
  4847. $baseDuration = 3; // 默认2秒
  4848. // if ($adjustedLength <= 20) {
  4849. // $baseDuration = 3;
  4850. // } elseif ($adjustedLength <= 40) {
  4851. // $baseDuration = 4;
  4852. // } elseif ($adjustedLength <= 60) {
  4853. // $baseDuration = 5;
  4854. // } elseif ($adjustedLength <= 80) {
  4855. // $baseDuration = 6;
  4856. // } elseif ($adjustedLength <= 100) {
  4857. // $baseDuration = 7;
  4858. // } elseif ($adjustedLength <= 120) {
  4859. // $baseDuration = 8;
  4860. // } else {
  4861. // $baseDuration = 9;
  4862. // }
  4863. // 根据内容复杂度调整时长
  4864. $finalDuration = $baseDuration + $complexityScore;
  4865. // 确保时长在2-12秒范围内
  4866. return max(4, min(12, $finalDuration));
  4867. }
  4868. /**
  4869. * 分析内容复杂度,返回时长调整值
  4870. *
  4871. * @param string $text 文本内容
  4872. * @return int 调整值(-2到+3)
  4873. */
  4874. private function analyzeContentComplexity($text) {
  4875. $score = 0;
  4876. // 动作关键词(需要更长时间展现)
  4877. $actionKeywords = [
  4878. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4879. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4880. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4881. ];
  4882. // 静态关键词(可以用较短时间)
  4883. $staticKeywords = [
  4884. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4885. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4886. ];
  4887. // 复杂场景关键词(需要更长时间)
  4888. $complexSceneKeywords = [
  4889. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4890. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4891. ];
  4892. // 情感关键词(需要适中时间表现)
  4893. $emotionKeywords = [
  4894. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4895. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4896. ];
  4897. // 检查动作关键词
  4898. foreach ($actionKeywords as $keyword) {
  4899. if (strpos($text, $keyword) !== false) {
  4900. $score += 1;
  4901. break; // 避免重复加分
  4902. }
  4903. }
  4904. // 检查静态关键词
  4905. foreach ($staticKeywords as $keyword) {
  4906. if (strpos($text, $keyword) !== false) {
  4907. $score -= 1;
  4908. break;
  4909. }
  4910. }
  4911. // 检查复杂场景关键词
  4912. foreach ($complexSceneKeywords as $keyword) {
  4913. if (strpos($text, $keyword) !== false) {
  4914. $score += 1;
  4915. break;
  4916. }
  4917. }
  4918. // 检查情感关键词
  4919. foreach ($emotionKeywords as $keyword) {
  4920. if (strpos($text, $keyword) !== false) {
  4921. $score += 1;
  4922. break;
  4923. }
  4924. }
  4925. // 检查时间相关词汇
  4926. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4927. $score += 1;
  4928. }
  4929. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4930. $score -= 1;
  4931. }
  4932. // 检查转场词汇
  4933. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4934. $score += 1;
  4935. }
  4936. // 检查环境描述(复杂环境需要更多时间)
  4937. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4938. $score += 1;
  4939. }
  4940. // 检查对话内容(对话需要更多时间)
  4941. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4942. $score += 1;
  4943. }
  4944. // 限制调整范围
  4945. return max(-1, min(4, $score));
  4946. }
  4947. /**
  4948. * 创建完整视频合成任务
  4949. *
  4950. * @param array $data
  4951. * @return array
  4952. */
  4953. public function createCompleteVideoTask($data)
  4954. {
  4955. $animeId = getProp($data, 'anime_id');
  4956. $episodeId = getProp($data, 'episode_id');
  4957. // 验证参数
  4958. if (!$animeId || !$episodeId) {
  4959. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4960. }
  4961. // 检查是否已存在处理中的任务
  4962. $existingTask = DB::table('mp_complete_video_tasks')
  4963. ->where('anime_id', $animeId)
  4964. ->where('episode_id', $episodeId)
  4965. ->whereIn('generate_status', ['执行中'])
  4966. ->first();
  4967. if ($existingTask) {
  4968. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4969. }
  4970. // 获取全能模式状态
  4971. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4972. if ((int)$ace_mode === 1) {
  4973. // 获取所有片段的配音视频,按 act_number 排序
  4974. $segments = DB::table('mp_episode_segments')
  4975. ->where('anime_id', $animeId)
  4976. ->where('episode_id', $episodeId)
  4977. ->orderBy('segment_number')
  4978. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4979. ->get();
  4980. // 检查是否所有片段都有视频
  4981. $missingVideos = $segments->filter(function($segment) {
  4982. return empty($segment->video_url);
  4983. });
  4984. if ($missingVideos->isNotEmpty()) {
  4985. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4986. }
  4987. }else {
  4988. // 获取所有分镜的配音视频,按 segment_number 排序
  4989. $segments = DB::table('mp_episode_segments')
  4990. ->where('anime_id', $animeId)
  4991. ->where('episode_id', $episodeId)
  4992. ->orderBy('segment_number')
  4993. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4994. ->get();
  4995. // 检查是否所有分镜都有配音和视频
  4996. $missingVideos = $segments->filter(function($segment) {
  4997. return empty($segment->audio_url) || empty($segment->video_url);
  4998. });
  4999. if ($missingVideos->isNotEmpty()) {
  5000. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5001. }
  5002. }
  5003. if ($segments->isEmpty()) {
  5004. Utils::throwError('20003:未找到该剧集的分镜数据');
  5005. }
  5006. // 获取当前完整视频url
  5007. $completeVideoUrl = DB::table('mp_anime_episodes')
  5008. ->where('anime_id', $animeId)
  5009. ->where('id', $episodeId)
  5010. ->value('complete_video_url');
  5011. // 构建 generate_json
  5012. $generateJson = [];
  5013. $sequence = 1;
  5014. foreach ($segments as $segment) {
  5015. if ((int)$ace_mode === 1) {
  5016. $generateJson[] = [
  5017. 'sequence' => $sequence++,
  5018. 'video_url' => $segment->video_url,
  5019. 'video_time_point_start' => $segment->video_time_point_start,
  5020. 'video_time_point_end' => $segment->video_time_point_end
  5021. ];
  5022. }else {
  5023. $generateJson[] = [
  5024. 'sequence' => $sequence++,
  5025. 'video_url' => $segment->video_url,
  5026. 'audio_url' => $segment->audio_url,
  5027. 'video_time_point_start' => $segment->video_time_point_start,
  5028. 'video_time_point_end' => $segment->video_time_point_end
  5029. ];
  5030. }
  5031. }
  5032. // 创建任务
  5033. $now = date('Y-m-d H:i:s');
  5034. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5035. 'anime_id' => $animeId,
  5036. 'episode_id' => $episodeId,
  5037. 'generate_json' => json_encode($generateJson, 256),
  5038. 'generate_status' => '执行中',
  5039. 'complete_video_url' => '',
  5040. 'created_at' => $now,
  5041. 'updated_at' => $now
  5042. ]);
  5043. if (!$taskId) {
  5044. Utils::throwError('20003:创建任务失败');
  5045. }
  5046. // 更新剧集表的任务ID和状态
  5047. $boolen = DB::table('mp_anime_episodes')
  5048. ->where('anime_id', $animeId)
  5049. ->where('id', $episodeId)
  5050. ->update([
  5051. 'complete_video_task_id' => $taskId,
  5052. 'complete_video_task_status' => '执行中',
  5053. 'updated_at' => $now
  5054. ]);
  5055. if (!$boolen) {
  5056. Utils::throwError('20003:更新剧集表失败');
  5057. }
  5058. dLog('anime')->info('创建完整视频合成任务', [
  5059. 'task_id' => $taskId,
  5060. 'anime_id' => $animeId,
  5061. 'episode_id' => $episodeId,
  5062. 'segment_count' => count($generateJson)
  5063. ]);
  5064. // 请求远程服务器执行生成
  5065. $client = new Client(['timeout' => 600, 'verify' => false]);
  5066. try {
  5067. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5068. $response = $result->getBody()->getContents();
  5069. $response_arr = json_decode($response, true);
  5070. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5071. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5072. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5073. // // 更新任务状态为失败
  5074. // DB::table('mp_complete_video_tasks')
  5075. // ->where('id', $taskId)
  5076. // ->update([
  5077. // 'generate_status' => '执行失败',
  5078. // 'error_message' => $error_msg,
  5079. // 'updated_at' => date('Y-m-d H:i:s')
  5080. // ]);
  5081. // // 同步更新剧集表状态
  5082. // DB::table('mp_anime_episodes')
  5083. // ->where('complete_video_task_id', $taskId)
  5084. // ->update([
  5085. // 'complete_video_task_status' => '执行失败',
  5086. // 'updated_at' => date('Y-m-d H:i:s')
  5087. // ]);
  5088. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5089. }
  5090. } catch (\Exception $e) {
  5091. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5092. // 更新任务状态为失败
  5093. DB::table('mp_complete_video_tasks')
  5094. ->where('id', $taskId)
  5095. ->update([
  5096. 'generate_status' => '执行失败',
  5097. 'error_message' => $e->getMessage(),
  5098. 'updated_at' => date('Y-m-d H:i:s')
  5099. ]);
  5100. // 同步更新剧集表状态
  5101. DB::table('mp_anime_episodes')
  5102. ->where('complete_video_task_id', $taskId)
  5103. ->update([
  5104. 'complete_video_task_status' => '执行失败',
  5105. 'updated_at' => date('Y-m-d H:i:s')
  5106. ]);
  5107. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5108. }
  5109. // 开始轮询任务状态
  5110. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5111. $pollInterval = 5; // 每5秒轮询一次
  5112. $attempt = 0;
  5113. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5114. while ($attempt < $maxAttempts) {
  5115. sleep($pollInterval);
  5116. $attempt++;
  5117. // 查询任务状态
  5118. $task = DB::table('mp_complete_video_tasks')
  5119. ->where('id', $taskId)
  5120. ->first();
  5121. if (!$task) {
  5122. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5123. Utils::throwError('20003:任务不存在');
  5124. }
  5125. dLog('anime')->info('轮询任务状态', [
  5126. 'task_id' => $taskId,
  5127. 'attempt' => $attempt,
  5128. 'status' => $task->generate_status
  5129. ]);
  5130. // 检查任务是否完成
  5131. if ($task->generate_status === '执行成功') {
  5132. // 同步更新剧集表状态
  5133. $boolen3 = DB::table('mp_anime_episodes')
  5134. ->where('anime_id', $animeId)
  5135. ->where('id', $episodeId)
  5136. ->update([
  5137. 'complete_video_url' => $task->complete_video_url,
  5138. 'complete_video_task_status' => '执行成功',
  5139. 'updated_at' => date('Y-m-d H:i:s')
  5140. ]);
  5141. dLog('anime')->info('视频合成任务完成', [
  5142. 'task_id' => $taskId,
  5143. 'video_url' => $task->complete_video_url,
  5144. 'attempts' => $attempt
  5145. ]);
  5146. // 如果更新成功则远程删除之前的文件
  5147. if ($boolen3 && $completeVideoUrl) {
  5148. $encode_url = urlencode($completeVideoUrl);
  5149. $client = new Client(['timeout' => 300, 'verify' => false]);
  5150. // 根据ID通过API通知合成音频
  5151. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5152. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5153. $response = $result->getBody()->getContents();
  5154. $response_arr = json_decode($response, true);
  5155. Log::info('火山删除音频返回: '.$response);
  5156. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5157. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5158. Log::info('火山删除音频失败: '.$error_msg);
  5159. // Utils::throwError('20003:火山删除音频失败');
  5160. }
  5161. }
  5162. return [
  5163. 'task_id' => $taskId,
  5164. 'anime_id' => $animeId,
  5165. 'episode_id' => $episodeId,
  5166. 'segment_count' => count($generateJson),
  5167. 'generate_status' => '执行成功',
  5168. 'complete_video_url' => $task->complete_video_url,
  5169. ];
  5170. }
  5171. // 检查任务是否失败
  5172. if ($task->generate_status === '执行失败') {
  5173. // 同步更新剧集表状态
  5174. DB::table('mp_anime_episodes')
  5175. ->where('anime_id', $animeId)
  5176. ->where('id', $episodeId)
  5177. ->update([
  5178. 'complete_video_task_status' => '执行失败',
  5179. 'updated_at' => date('Y-m-d H:i:s')
  5180. ]);
  5181. $errorMessage = $task->error_message ?? '未知错误';
  5182. dLog('anime')->error('视频合成任务失败', [
  5183. 'task_id' => $taskId,
  5184. 'error' => $errorMessage,
  5185. 'attempts' => $attempt
  5186. ]);
  5187. return [
  5188. 'task_id' => $taskId,
  5189. 'anime_id' => $animeId,
  5190. 'episode_id' => $episodeId,
  5191. 'segment_count' => count($generateJson),
  5192. 'generate_status' => '执行失败',
  5193. 'error_message' => $errorMessage
  5194. ];
  5195. }
  5196. }
  5197. // 超时处理
  5198. dLog('anime')->warning('视频合成任务超时', [
  5199. 'task_id' => $taskId,
  5200. 'max_attempts' => $maxAttempts,
  5201. 'timeout_seconds' => $maxAttempts * $pollInterval
  5202. ]);
  5203. // 更新任务状态为超时
  5204. DB::table('mp_complete_video_tasks')
  5205. ->where('id', $taskId)
  5206. ->update([
  5207. 'generate_status' => '超时',
  5208. 'error_message' => '任务执行超时(5分钟)',
  5209. 'updated_at' => date('Y-m-d H:i:s')
  5210. ]);
  5211. return [
  5212. 'task_id' => $taskId,
  5213. 'anime_id' => $animeId,
  5214. 'episode_id' => $episodeId,
  5215. 'segment_count' => count($generateJson),
  5216. 'generate_status' => '超时',
  5217. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5218. ];
  5219. }
  5220. /**
  5221. * 根据 inner_prompt_type 附加内置提示词
  5222. *
  5223. * @param string $prompt 用户提示词
  5224. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5225. * @return string 合并后的提示词
  5226. */
  5227. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5228. {
  5229. $innerPromptMap = [
  5230. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  5231. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5232. ];
  5233. if (!isset($innerPromptMap[$innerPromptType])) {
  5234. return $prompt;
  5235. }
  5236. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5237. }
  5238. /**
  5239. * 根据 inner_prompt_type 获取生成图片数量
  5240. *
  5241. * @param int $innerPromptType 内置提示词类型
  5242. * @param int $imageNum 传入的图片张数
  5243. * @return int 图片数量
  5244. */
  5245. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5246. {
  5247. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5248. }
  5249. /**
  5250. * 提取图片生成结果URL
  5251. *
  5252. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5253. * @param int $innerPromptType 内置提示词类型
  5254. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5255. */
  5256. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5257. {
  5258. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5259. if (is_array($resultUrls) && !empty($resultUrls)) {
  5260. $resultUrls = array_values($resultUrls);
  5261. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5262. }
  5263. if (!empty($resultUrl)) {
  5264. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5265. }
  5266. return (int)$innerPromptType === 2 ? [] : '';
  5267. }
  5268. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5269. $prompt = getProp($data, 'prompt');
  5270. $episode_id = getProp($data, 'episode_id');
  5271. $ref_img_urls = getProp($data, 'ref_img_urls');
  5272. $ratio = getProp($data, 'ratio', '9:16');
  5273. $resolution = getProp($data, 'resolution', '2k');
  5274. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5275. $imageNum = (int)getProp($data, 'image_num', 1);
  5276. // 定义分辨率和宽高比对应的尺寸映射表
  5277. $sizeMap = [
  5278. '2k' => [
  5279. '1:1' => ['width' => 2048, 'height' => 2048],
  5280. '4:3' => ['width' => 2304, 'height' => 1728],
  5281. '3:4' => ['width' => 1728, 'height' => 2304],
  5282. '16:9' => ['width' => 2848, 'height' => 1600],
  5283. '9:16' => ['width' => 1600, 'height' => 2848],
  5284. '3:2' => ['width' => 2496, 'height' => 1664],
  5285. '2:3' => ['width' => 1664, 'height' => 2496],
  5286. '21:9' => ['width' => 3136, 'height' => 1344],
  5287. ],
  5288. '3k' => [
  5289. '1:1' => ['width' => 3072, 'height' => 3072],
  5290. '4:3' => ['width' => 3456, 'height' => 2592],
  5291. '3:4' => ['width' => 2592, 'height' => 3456],
  5292. '16:9' => ['width' => 4096, 'height' => 2304],
  5293. '9:16' => ['width' => 2304, 'height' => 4096],
  5294. '2:3' => ['width' => 2496, 'height' => 3744],
  5295. '3:2' => ['width' => 3744, 'height' => 2496],
  5296. '21:9' => ['width' => 4704, 'height' => 2016],
  5297. ],
  5298. '4k' => [
  5299. '1:1' => ['width' => 4096, 'height' => 4096],
  5300. '3:4' => ['width' => 3520, 'height' => 4704],
  5301. '4:3' => ['width' => 4704, 'height' => 3520],
  5302. '16:9' => ['width' => 5504, 'height' => 3040],
  5303. '9:16' => ['width' => 3040, 'height' => 5504],
  5304. '2:3' => ['width' => 3328, 'height' => 4992],
  5305. '3:2' => ['width' => 4992, 'height' => 3328],
  5306. '21:9' => ['width' => 6240, 'height' => 2656],
  5307. ],
  5308. ];
  5309. // 参数验证
  5310. $resolution = strtolower($resolution);
  5311. if (!isset($sizeMap[$resolution])) {
  5312. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5313. }
  5314. if (!isset($sizeMap[$resolution][$ratio])) {
  5315. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5316. }
  5317. // 根据 ratio 和 resolution 确定宽高
  5318. $width = $sizeMap[$resolution][$ratio]['width'];
  5319. $height = $sizeMap[$resolution][$ratio]['height'];
  5320. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5321. if (is_json($ref_img_urls)) {
  5322. $ref_img_urls = json_decode($ref_img_urls, true);
  5323. }else {
  5324. $ref_img_urls = explode(',', $ref_img_urls);
  5325. }
  5326. }
  5327. // 处理图片模型
  5328. $model = getProp($data, 'model');
  5329. if (!$model) {
  5330. // 用户没有输入,从episode表获取
  5331. if ($episode_id) {
  5332. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5333. $model = getProp($episode, 'image_model');
  5334. }
  5335. if (!$model) {
  5336. // episode表也没有,使用默认值
  5337. $model = 'doubao-seedream-5-0-lite-260128';
  5338. }
  5339. }
  5340. // 验证模型是否在可用模型表中
  5341. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5342. // $model = 'doubao-seedream-5-0-lite-260128';
  5343. Utils::throwError('20003:该模型已不可用,请更换!');
  5344. }
  5345. // 保存到episode表
  5346. if ($episode_id) {
  5347. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5348. 'image_model' => $model,
  5349. 'updated_at' => date('Y-m-d H:i:s')
  5350. ]);
  5351. }
  5352. // 参数验证
  5353. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5354. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5355. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5356. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5357. try {
  5358. // 创建图片生成任务
  5359. $params = [
  5360. 'prompt' => $prompt,
  5361. 'model' => $model,
  5362. 'ref_img_urls' => '',
  5363. 'width' => $width,
  5364. 'height' => $height,
  5365. 'image_num' => $imageNum
  5366. ];
  5367. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5368. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5369. $task_id = $task->id;
  5370. if (!$task_id) {
  5371. Utils::throwError('20003:创建图片生成任务失败');
  5372. }
  5373. // 创建任务中心记录并关联图片任务ID
  5374. $taskCenter = $this->taskCenterService->createTask('image', [
  5375. 'title' => '文生图',
  5376. 'ref_task_id' => $task_id,
  5377. // 'prompt' => $prompt,
  5378. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5379. ]);
  5380. $taskCenterId = $taskCenter->id;
  5381. // 组装本次任务信息(用于init消息,类似generateVideo)
  5382. $taskInfo = [
  5383. 'task_id' => $task_id,
  5384. 'status' => getProp($task, 'status', 'processing'),
  5385. 'model' => $model,
  5386. 'ratio' => $ratio,
  5387. 'resolution' => $resolution,
  5388. 'image_num' => $imageNum,
  5389. ];
  5390. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5391. if (is_callable($onTaskCreated)) {
  5392. $onTaskCreated($taskCenterId, $taskInfo);
  5393. }
  5394. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5395. $model = getProp($task, 'model');
  5396. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5397. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5398. $isSyncModel = $isVolcModel || $isGptModel;
  5399. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5400. $start_time = time();
  5401. $timeout = 300; // 5分钟
  5402. $img_url = '';
  5403. $img_urls = [];
  5404. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5405. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5406. while (time() - $start_time < $timeout) {
  5407. sleep(3);
  5408. // 每分钟发送一次队列状态消息(仅流式模式)
  5409. if (is_callable($onPoll)) {
  5410. $currentTime = time();
  5411. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5412. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5413. $lastQueueMessageTime = $currentTime;
  5414. }
  5415. }
  5416. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5417. if ($isSyncModel) {
  5418. // 刷新任务状态
  5419. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5420. if ($task->status === 'success' && $task->result_url) {
  5421. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5422. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5423. if (!empty($resultUrls)) {
  5424. $img_urls = $resultUrls;
  5425. $img_url = $resultUrls[0];
  5426. } else {
  5427. $img_url = (string)$task->result_url;
  5428. }
  5429. break;
  5430. } elseif ($task->status === 'failed') {
  5431. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5432. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5433. }
  5434. // // 如果还在处理中,提示用户稍后查看
  5435. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5436. }else {
  5437. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5438. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5439. if ($statusInfo['status'] === 'success') {
  5440. $task->updateStatus('success', [
  5441. 'result_url' => $statusInfo['result_url'],
  5442. 'result_json' => $statusInfo['result_json'] ?? []
  5443. ]);
  5444. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5445. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5446. if (!empty($resultUrls)) {
  5447. $img_urls = $resultUrls;
  5448. $img_url = $resultUrls[0];
  5449. } else {
  5450. $img_url = (string)$statusInfo['result_url'];
  5451. }
  5452. break;
  5453. } elseif ($statusInfo['status'] === 'failed') {
  5454. $task->updateStatus('failed', [
  5455. 'error_message' => $statusInfo['error_message'],
  5456. 'result_json' => $statusInfo['result_json'] ?? []
  5457. ]);
  5458. dLog('anime')->error('图片生成失败,', [
  5459. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5460. ]);
  5461. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5462. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5463. }
  5464. }
  5465. }
  5466. if (empty($img_url)) {
  5467. Utils::throwError('20003:图片生成超时,请稍后重试');
  5468. }
  5469. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5470. if (count($img_urls) > 1) {
  5471. return [
  5472. 'img_url' => $img_url,
  5473. 'image_urls' => $img_urls,
  5474. 'task_id' => $taskCenterId,
  5475. ];
  5476. }
  5477. return [
  5478. 'img_url' => $img_url,
  5479. 'task_id' => $taskCenterId,
  5480. ];
  5481. } catch (\Exception $e) {
  5482. dLog('anime')->error('更新角色或场景失败', [
  5483. 'error' => $e->getMessage()
  5484. ]);
  5485. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5486. Utils::throwError('20003:' . $e->getMessage());
  5487. }
  5488. }
  5489. /**
  5490. * 使用文生文模型解析分镜内容
  5491. */
  5492. private function parseSegmentContentWithAI($segment_content) {
  5493. try {
  5494. // 使用DeepSeek服务的公开方法解析分镜内容
  5495. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5496. } catch (\Exception $e) {
  5497. // 如果AI解析失败,记录日志并返回原内容
  5498. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5499. return $segment_content;
  5500. }
  5501. }
  5502. /**
  5503. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5504. *
  5505. * @param int $episode_id 分集ID
  5506. * @param int $anime_id 动漫ID
  5507. * @param array $roles 分集角色数组(引用传递)
  5508. * @param array $scenes 分集场景数组(引用传递)
  5509. * @param array $episode 分集数据
  5510. */
  5511. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5512. // 获取全局动漫的角色和场景数据
  5513. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5514. if (!$anime) return;
  5515. $art_style_type = getProp($anime, 'art_style_type');
  5516. $character_prefix = '';
  5517. $scene_prefix = '';
  5518. if ($art_style_type) {
  5519. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5520. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5521. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5522. }
  5523. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5524. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5525. $roles_updated = false;
  5526. $scenes_updated = false;
  5527. // 处理角色
  5528. foreach ($roles as &$role) {
  5529. $role_name = getProp($role, 'role');
  5530. $role_description = getProp($role, 'description');
  5531. $role_pic_prompt = getProp($role, 'pic_prompt');
  5532. $role_url = getProp($role, 'url');
  5533. $role_task_id = getProp($role, 'task_id');
  5534. // 如果已有URL或已有任务ID,跳过
  5535. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5536. continue;
  5537. }
  5538. $url_inherited = false;
  5539. // 尝试从全局数据中继承
  5540. foreach ($global_roles as $global_role) {
  5541. $global_role_name = getProp($global_role, 'role');
  5542. $global_role_description = getProp($global_role, 'description');
  5543. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5544. $global_role_url = getProp($global_role, 'url');
  5545. $global_role_task_id = getProp($global_role, 'task_id');
  5546. $global_role_task_status = getProp($global_role, 'task_status');
  5547. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5548. if ($role_name === $global_role_name
  5549. && $role_description === $global_role_description
  5550. && $role_pic_prompt === $global_role_pic_prompt
  5551. && !empty($global_role_url)) {
  5552. // 继承 task_id、task_status 和 url
  5553. $role['task_id'] = $global_role_task_id;
  5554. $role['task_status'] = $global_role_task_status;
  5555. $role['url'] = $global_role_url;
  5556. $roles_updated = true;
  5557. $url_inherited = true;
  5558. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5559. break;
  5560. }
  5561. }
  5562. // 如果无法继承且没有任务ID,创建新任务
  5563. if (!$url_inherited && empty($role_task_id)) {
  5564. try {
  5565. $art_style = getProp($episode, 'art_style');
  5566. // 优先使用 pic_prompt,如果没有则使用 description
  5567. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5568. // if ($art_style) {
  5569. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5570. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5571. // }
  5572. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5573. $params = [
  5574. 'prompt' => $description,
  5575. 'ref_img_urls' => []
  5576. ];
  5577. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5578. $task_id = $task->id;
  5579. if ($task_id) {
  5580. $role['task_id'] = $task_id;
  5581. $role['task_status'] = 'processing';
  5582. $roles_updated = true;
  5583. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5584. }
  5585. } catch (\Exception $e) {
  5586. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5587. }
  5588. }
  5589. }
  5590. // 处理场景
  5591. foreach ($scenes as &$scene) {
  5592. $scene_name = getProp($scene, 'scene');
  5593. $scene_description = getProp($scene, 'description');
  5594. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5595. $scene_url = getProp($scene, 'url');
  5596. $scene_task_id = getProp($scene, 'task_id');
  5597. // 如果已有URL或已有任务ID,跳过
  5598. if (!empty($scene_url) || !empty($scene_task_id)) {
  5599. continue;
  5600. }
  5601. $url_inherited = false;
  5602. // 尝试从全局数据中继承
  5603. foreach ($global_scenes as $global_scene) {
  5604. $global_scene_name = getProp($global_scene, 'scene');
  5605. $global_scene_description = getProp($global_scene, 'description');
  5606. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5607. $global_scene_url = getProp($global_scene, 'url');
  5608. $global_scene_task_id = getProp($global_scene, 'task_id');
  5609. $global_scene_task_status = getProp($global_scene, 'task_status');
  5610. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5611. if ($scene_name === $global_scene_name
  5612. && $scene_description === $global_scene_description
  5613. && $scene_pic_prompt === $global_scene_pic_prompt
  5614. && !empty($global_scene_url)) {
  5615. // 继承 task_id、task_status 和 url
  5616. $scene['task_id'] = $global_scene_task_id;
  5617. $scene['task_status'] = $global_scene_task_status;
  5618. $scene['url'] = $global_scene_url;
  5619. $scenes_updated = true;
  5620. $url_inherited = true;
  5621. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5622. break;
  5623. }
  5624. }
  5625. // 如果无法继承且没有任务ID,创建新任务
  5626. if (!$url_inherited && empty($scene_task_id)) {
  5627. try {
  5628. $art_style = getProp($episode, 'art_style');
  5629. // 优先使用 pic_prompt,如果没有则使用 description
  5630. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5631. // if ($art_style) {
  5632. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5633. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5634. // }
  5635. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5636. $params = [
  5637. 'prompt' => $description,
  5638. 'ref_img_urls' => []
  5639. ];
  5640. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5641. $task_id = $task->id;
  5642. if ($task_id) {
  5643. $scene['task_id'] = $task_id;
  5644. $scene['task_status'] = 'processing';
  5645. $scenes_updated = true;
  5646. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5647. }
  5648. } catch (\Exception $e) {
  5649. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5650. }
  5651. }
  5652. }
  5653. // 如果有更新,保存到数据库
  5654. if ($roles_updated || $scenes_updated) {
  5655. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5656. if ($roles_updated) {
  5657. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5658. }
  5659. if ($scenes_updated) {
  5660. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5661. }
  5662. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5663. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5664. }
  5665. }
  5666. /**
  5667. * 根据图片URL使用AI反推图片提示词
  5668. *
  5669. * @param string $img_url 图片URL
  5670. * @return string 反推的提示词
  5671. */
  5672. private function generateImagePromptFromUrl($img_url) {
  5673. try {
  5674. // 获取默认模型
  5675. $model = 'doubao-seed-2-0-mini-260215';
  5676. // 构建messages参数
  5677. $messages = [
  5678. [
  5679. 'role' => 'user',
  5680. 'content' => [
  5681. [
  5682. 'type' => 'text',
  5683. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5684. ],
  5685. [
  5686. 'type' => 'image_url',
  5687. 'image_url' => [
  5688. 'url' => $img_url
  5689. ]
  5690. ]
  5691. ]
  5692. ]
  5693. ];
  5694. // 构建请求参数
  5695. $params = [
  5696. 'model' => $model,
  5697. 'messages' => $messages,
  5698. 'stream' => false,
  5699. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5700. ];
  5701. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5702. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5703. // 仅记录 token 使用明细(不扣积分)
  5704. $uid = 0;
  5705. try {
  5706. $uid = (int)Site::getUid();
  5707. } catch (\Throwable $e) {
  5708. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5709. }
  5710. $this->pointsService->recordTokenOnlyDetail(
  5711. $uid,
  5712. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5713. [
  5714. 'model' => $model,
  5715. 'img_url' => $img_url,
  5716. 'source' => 'generateImagePromptFromUrl',
  5717. ],
  5718. 'chat',
  5719. $model,
  5720. ''
  5721. );
  5722. // 返回生成的内容
  5723. return getProp($result, 'fullContent', '图片描述生成失败');
  5724. } catch (\Exception $e) {
  5725. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5726. 'img_url' => $img_url
  5727. ]);
  5728. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5729. 'error' => $e->getMessage(),
  5730. 'img_url' => $img_url
  5731. ]);
  5732. return '图片描述生成失败: ' . $e->getMessage();
  5733. }
  5734. }
  5735. /**
  5736. * 音频试听接口
  5737. * 创建音频任务并轮询获取结果
  5738. *
  5739. * @param array $data 参数数组
  5740. * @return array 返回音频URL或错误信息
  5741. */
  5742. public function previewAudio($data) {
  5743. $dialogue = getProp($data, 'dialogue');
  5744. // 必填参数验证
  5745. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5746. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5747. $voice_type = getProp($data, 'voice_type');
  5748. $voice_name = getProp($data, 'voice_name');
  5749. $voice_actor = getProp($data, 'voice_actor');
  5750. $emotion_type = getProp($data, 'emotion_type');
  5751. $gender = getProp($data, 'gender', 0);
  5752. $emotion = getProp($data, 'emotion');
  5753. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5754. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5755. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5756. $pitch = getProp($data, 'pitch', 0);
  5757. try {
  5758. $now = date('Y-m-d H:i:s');
  5759. // 构建生成参数
  5760. $generate_json = json_encode([
  5761. 'text' => $dialogue,
  5762. 'role' => $voice_actor,
  5763. 'voice_type' => $voice_type,
  5764. 'voice_name' => $voice_name,
  5765. 'emotion' => $emotion,
  5766. 'emotion_type' => $emotion_type,
  5767. 'gender' => $gender,
  5768. 'speed_ratio' => $speed_ratio,
  5769. 'loudness_ratio' => $loudness_ratio,
  5770. 'emotion_scale' => $emotion_scale,
  5771. 'pitch' => $pitch,
  5772. ], 256);
  5773. // 请求远程服务器执行生成
  5774. $client = new Client(['timeout' => 600, 'verify' => false]);
  5775. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5776. $response = $result->getBody()->getContents();
  5777. $response_arr = json_decode($response, true);
  5778. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5779. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5780. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5781. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5782. }
  5783. $arr = $response_arr['data'];
  5784. $subtitle_info = $arr['subtitle_info'];
  5785. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5786. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5787. return [
  5788. 'audio_url' => $arr['url'],
  5789. 'subtitle_info' => $subtitle_info,
  5790. 'audio_duration' => round($audio_duration, 2)
  5791. ];
  5792. } catch (\Exception $e) {
  5793. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5794. Utils::throwError('20003:' . $e->getMessage());
  5795. }
  5796. }
  5797. /**
  5798. * 获取角色库列表(支持文件夹递归查询)
  5799. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5800. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5801. */
  5802. public function globalProducts($data) {
  5803. $uid = Site::getUid();
  5804. $cpid = Site::getCpid();
  5805. $role = Site::getRole();
  5806. $id = getProp($data, 'id', 0);
  5807. $parent_id = getProp($data, 'parent_id', 0);
  5808. $product_name = getProp($data, 'product_name');
  5809. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5810. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5811. if (!$product) {
  5812. Utils::throwError('20003:请选择产品类型');
  5813. }
  5814. // 根据角色和is_public参数确定查询范围
  5815. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5816. // user角色:根据is_public参数筛选
  5817. $query_user_ids = [];
  5818. if ($role === 'admin') {
  5819. // admin获取所有个人库和公共库
  5820. $query_user_ids = [$uid, 0];
  5821. } else {
  5822. // user角色根据is_public参数筛选
  5823. if ($is_public == 2) {
  5824. // 个人库+公共库
  5825. $query_user_ids = [$uid, 0];
  5826. } elseif ($is_public == 0) {
  5827. // 仅个人库
  5828. $query_user_ids = [$uid];
  5829. } elseif ($is_public == 1) {
  5830. // 仅公共库
  5831. $query_user_ids = [0];
  5832. }
  5833. }
  5834. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5835. if ($id || $product_name) {
  5836. $query = DB::table('mp_products')
  5837. ->where('cpid', $cpid)
  5838. ->whereIn('user_id', $query_user_ids)
  5839. ->where('is_deleted', 0);
  5840. // 如果指定了 id,按 id 精确查询
  5841. if ($id) {
  5842. $query->where('id', $id);
  5843. }
  5844. // 如果指定了 product_name,按名称模糊查询
  5845. if ($product_name) {
  5846. $query->where('product_name', 'like', "%{$product_name}%");
  5847. }
  5848. // 如果指定了 product,添加筛选条件
  5849. if ($product) {
  5850. $query->where('product', $product);
  5851. }
  5852. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5853. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5854. ->get()
  5855. ->map(function($value) {
  5856. $value = (array)$value;
  5857. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5858. $value['type'] = (int)$value['type'];
  5859. $value['parent_id'] = (int)$value['parent_id'];
  5860. $value['level'] = (int)$value['level'];
  5861. $value['product'] = (int)($value['product'] ?? 1);
  5862. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5863. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5864. unset($value['user_id']);
  5865. return $value;
  5866. })
  5867. ->toArray();
  5868. return $result;
  5869. }
  5870. // 递归获取所有子目录和角色
  5871. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5872. }
  5873. /**
  5874. * 递归获取指定目录下的所有子目录和角色
  5875. * @param int $cpid 公司ID
  5876. * @param int $parent_id 父目录ID
  5877. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5878. * @param array $query_user_ids 用户ID数组(支持多个)
  5879. * @param int $current_uid 当前用户ID(用于排序)
  5880. * @return array
  5881. */
  5882. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5883. // 查询当前层级的所有项(文件夹和角色)
  5884. $query = DB::table('mp_products')
  5885. ->where('cpid', $cpid)
  5886. ->where('is_deleted', 0)
  5887. ->where('parent_id', $parent_id);
  5888. // 添加用户ID验证(支持多个user_id)
  5889. if (!empty($query_user_ids)) {
  5890. $query->whereIn('user_id', $query_user_ids);
  5891. }
  5892. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5893. if ($product) {
  5894. $query->where('product', $product);
  5895. }
  5896. // 排序规则:
  5897. // 1. 文件夹在前(type DESC)
  5898. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5899. // 3. 其他排序规则
  5900. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5901. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5902. ->get();
  5903. $result = [];
  5904. foreach ($items as $item) {
  5905. $itemArray = [
  5906. 'id' => $item->id,
  5907. 'type' => (int)$item->type,
  5908. 'parent_id' => (int)$item->parent_id,
  5909. 'level' => (int)$item->level,
  5910. 'product_name' => $item->product_name,
  5911. 'url' => $item->url,
  5912. 'pic_prompt' => $item->pic_prompt ?? '',
  5913. 'three_view_image_url' => $item->three_view_image_url,
  5914. 'product' => (int)($item->product ?? 1),
  5915. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5916. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5917. ];
  5918. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5919. // 如果是文件夹,递归获取其子项
  5920. if ($item->type == 2) {
  5921. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5922. if (!empty($children)) {
  5923. $itemArray['children'] = $children;
  5924. }
  5925. }
  5926. $result[] = $itemArray;
  5927. }
  5928. return $result;
  5929. }
  5930. /**
  5931. * 创建文件夹
  5932. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5933. * @return int 返回新建文件夹ID
  5934. */
  5935. public function createFolder($data) {
  5936. $uid = Site::getUid();
  5937. $cpid = Site::getCpid();
  5938. $role = Site::getRole();
  5939. $parent_id = getProp($data, 'parent_id', 0);
  5940. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5941. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5942. // 如果是公共库操作,需要admin权限
  5943. if ($is_public && $role !== 'admin') {
  5944. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5945. }
  5946. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5947. $store_uid = $is_public ? 0 : $uid;
  5948. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5949. $product = getProp($data, 'product');
  5950. if (!in_array($product, [1, 2, 3])) {
  5951. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5952. }
  5953. // 验证父文件夹
  5954. $parent_level = 0;
  5955. if ($parent_id > 0) {
  5956. $parent = DB::table('mp_products')
  5957. ->where('id', $parent_id)
  5958. ->where('cpid', $cpid)
  5959. ->where('user_id', $store_uid)
  5960. ->where('type', 2)
  5961. ->where('is_deleted', 0)
  5962. ->first();
  5963. if (!$parent) {
  5964. Utils::throwError('20003:父文件夹不存在');
  5965. }
  5966. // 检查父文件夹的 product 类型是否一致
  5967. if ($parent->product != $product) {
  5968. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5969. }
  5970. $parent_level = $parent->level;
  5971. // 检查层级限制(最多3层)
  5972. if ($parent_level >= 3) {
  5973. Utils::throwError('20003:文件夹层级不能超过3层');
  5974. }
  5975. }
  5976. // 检查当前目录下是否已存在空白文件夹
  5977. $empty_folder_exists = DB::table('mp_products')
  5978. ->where('parent_id', $parent_id)
  5979. ->where('cpid', $cpid)
  5980. ->where('user_id', $store_uid)
  5981. ->where('type', 2)
  5982. ->where('product', $product)
  5983. ->where('product_name', '新建文件夹')
  5984. ->where('is_deleted', 0)
  5985. ->exists();
  5986. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5987. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5988. }
  5989. // 创建文件夹
  5990. $folder_id = DB::table('mp_products')->insertGetId([
  5991. 'user_id' => $store_uid,
  5992. 'cpid' => $cpid,
  5993. 'type' => 2,
  5994. 'parent_id' => $parent_id,
  5995. 'level' => $parent_level + 1,
  5996. 'product_name' => $folder_name,
  5997. 'product' => $product,
  5998. 'sort_order' => time(), // 使用时间戳作为排序权重
  5999. 'is_deleted' => 0,
  6000. 'created_at' => date('Y-m-d H:i:s'),
  6001. 'updated_at' => date('Y-m-d H:i:s')
  6002. ]);
  6003. return [
  6004. 'id' => $folder_id,
  6005. 'type' => 2,
  6006. 'parent_id' => $parent_id,
  6007. 'level' => $parent_level + 1,
  6008. 'product_name' => $folder_name,
  6009. 'product' => $product,
  6010. ];
  6011. }
  6012. /**
  6013. * 重命名文件夹或角色
  6014. * @param array $data 包含 id、product_name(新名称)
  6015. * @return bool
  6016. */
  6017. public function renameFolder($data) {
  6018. $uid = Site::getUid();
  6019. $cpid = Site::getCpid();
  6020. $role = Site::getRole();
  6021. $id = getProp($data, 'id');
  6022. $new_name = getProp($data, 'product_name');
  6023. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6024. if (!$id || !$new_name) {
  6025. Utils::throwError('20003:参数不完整');
  6026. }
  6027. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6028. $query_uid = $is_public ? 0 : $uid;
  6029. // 如果是公共库操作,需要admin权限
  6030. if ($is_public && $role !== 'admin') {
  6031. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6032. }
  6033. // 检查是否存在
  6034. $item = DB::table('mp_products')
  6035. ->where('id', $id)
  6036. ->where('cpid', $cpid)
  6037. ->where('user_id', $query_uid)
  6038. ->where('is_deleted', 0)
  6039. ->first();
  6040. if (!$item) {
  6041. Utils::throwError('20003:项目不存在');
  6042. }
  6043. return DB::table('mp_products')
  6044. ->where('id', $id)
  6045. ->where('cpid', $cpid)
  6046. ->where('user_id', $query_uid)
  6047. ->update([
  6048. 'product_name' => $new_name,
  6049. 'updated_at' => date('Y-m-d H:i:s')
  6050. ]);
  6051. }
  6052. /**
  6053. * 移动角色或文件夹到指定文件夹
  6054. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6055. * @return bool
  6056. */
  6057. public function moveProductOrFolder($data) {
  6058. $uid = Site::getUid();
  6059. $cpid = Site::getCpid();
  6060. $role = Site::getRole();
  6061. $id = getProp($data, 'id');
  6062. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6063. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6064. if (!$id) {
  6065. Utils::throwError('20003:请选择要移动的项目');
  6066. }
  6067. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6068. $query_uid = $is_public ? 0 : $uid;
  6069. // 如果是公共库操作,需要admin权限
  6070. if ($is_public && $role !== 'admin') {
  6071. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6072. }
  6073. // 检查要移动的项目
  6074. $item = DB::table('mp_products')
  6075. ->where('id', $id)
  6076. ->where('cpid', $cpid)
  6077. ->where('user_id', $query_uid)
  6078. ->where('is_deleted', 0)
  6079. ->first();
  6080. if (!$item) {
  6081. Utils::throwError('20003:项目不存在');
  6082. }
  6083. // 验证目标文件夹
  6084. $target_level = 0;
  6085. $target_product = $item->product; // 默认使用当前项目的 product
  6086. if ($target_parent_id > 0) {
  6087. $target_parent = DB::table('mp_products')
  6088. ->where('id', $target_parent_id)
  6089. ->where('cpid', $cpid)
  6090. ->where('user_id', $query_uid)
  6091. ->where('type', 2)
  6092. ->where('is_deleted', 0)
  6093. ->first();
  6094. if (!$target_parent) {
  6095. Utils::throwError('20003:目标文件夹不存在');
  6096. }
  6097. // 检查 product 类型是否一致
  6098. if ($target_parent->product != $item->product) {
  6099. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6100. }
  6101. $target_level = $target_parent->level;
  6102. $target_product = $target_parent->product;
  6103. // 如果移动的是文件夹,需要检查层级
  6104. if ($item->type == 2) {
  6105. // 计算移动后的最大层级
  6106. $max_child_level = $this->getMaxChildLevel($id);
  6107. $depth = $max_child_level - $item->level;
  6108. if ($target_level + 1 + $depth > 3) {
  6109. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6110. }
  6111. // 不能移动到自己或自己的子文件夹下
  6112. if ($this->isDescendant($target_parent_id, $id)) {
  6113. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6114. }
  6115. }
  6116. }
  6117. // 更新父文件夹和层级
  6118. $new_level = $target_level + 1;
  6119. DB::table('mp_products')
  6120. ->where('id', $id)
  6121. ->update([
  6122. 'parent_id' => $target_parent_id,
  6123. 'level' => $new_level,
  6124. 'updated_at' => date('Y-m-d H:i:s')
  6125. ]);
  6126. // 如果是文件夹,需要递归更新所有子项的层级
  6127. if ($item->type == 2) {
  6128. $this->updateChildrenLevel($id, $new_level);
  6129. }
  6130. return true;
  6131. }
  6132. /**
  6133. * 获取文件夹下最大子层级
  6134. * @param int $folder_id
  6135. * @return int
  6136. */
  6137. private function getMaxChildLevel($folder_id) {
  6138. $max_level = DB::table('mp_products')
  6139. ->where('parent_id', $folder_id)
  6140. ->where('is_deleted', 0)
  6141. ->max('level');
  6142. if (!$max_level) {
  6143. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6144. }
  6145. // 递归查找子文件夹
  6146. $children = DB::table('mp_products')
  6147. ->where('parent_id', $folder_id)
  6148. ->where('type', 2)
  6149. ->where('is_deleted', 0)
  6150. ->pluck('id');
  6151. foreach ($children as $child_id) {
  6152. $child_max = $this->getMaxChildLevel($child_id);
  6153. if ($child_max > $max_level) {
  6154. $max_level = $child_max;
  6155. }
  6156. }
  6157. return $max_level;
  6158. }
  6159. /**
  6160. * 检查 target_id 是否是 folder_id 的后代
  6161. * @param int $target_id
  6162. * @param int $folder_id
  6163. * @return bool
  6164. */
  6165. private function isDescendant($target_id, $folder_id) {
  6166. if ($target_id == $folder_id) {
  6167. return true;
  6168. }
  6169. $parent = DB::table('mp_products')
  6170. ->where('id', $target_id)
  6171. ->where('is_deleted', 0)
  6172. ->first();
  6173. if (!$parent || $parent->parent_id == 0) {
  6174. return false;
  6175. }
  6176. return $this->isDescendant($parent->parent_id, $folder_id);
  6177. }
  6178. /**
  6179. * 递归更新子项层级
  6180. * @param int $parent_id
  6181. * @param int $parent_level
  6182. */
  6183. private function updateChildrenLevel($parent_id, $parent_level) {
  6184. $children = DB::table('mp_products')
  6185. ->where('parent_id', $parent_id)
  6186. ->where('is_deleted', 0)
  6187. ->get();
  6188. foreach ($children as $child) {
  6189. $new_level = $parent_level + 1;
  6190. DB::table('mp_products')
  6191. ->where('id', $child->id)
  6192. ->update([
  6193. 'level' => $new_level,
  6194. 'updated_at' => date('Y-m-d H:i:s')
  6195. ]);
  6196. // 如果是文件夹,继续递归
  6197. if ($child->type == 2) {
  6198. $this->updateChildrenLevel($child->id, $new_level);
  6199. }
  6200. }
  6201. }
  6202. /**
  6203. * 获取文件夹路径(面包屑导航)
  6204. * @param array $data 包含 folder_id
  6205. * @return array 返回路径数组
  6206. */
  6207. public function getFolderPath($data) {
  6208. $uid = Site::getUid();
  6209. $cpid = Site::getCpid();
  6210. $folder_id = getProp($data, 'id', 0);
  6211. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6212. if ($folder_id == 0) {
  6213. return [
  6214. ['id' => 0, 'name' => '根目录']
  6215. ];
  6216. }
  6217. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6218. $query_uid = $is_public ? 0 : $uid;
  6219. $path = [];
  6220. $current_id = $folder_id;
  6221. while ($current_id > 0) {
  6222. $folder = DB::table('mp_products')
  6223. ->where('id', $current_id)
  6224. ->where('cpid', $cpid)
  6225. ->where('user_id', $query_uid)
  6226. ->where('type', 2)
  6227. ->where('is_deleted', 0)
  6228. ->first();
  6229. if (!$folder) {
  6230. break;
  6231. }
  6232. array_unshift($path, [
  6233. 'id' => $folder->id,
  6234. 'name' => $folder->product_name
  6235. ]);
  6236. $current_id = $folder->parent_id;
  6237. }
  6238. // 添加根目录
  6239. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6240. return $path;
  6241. }
  6242. public function createProduct($data) {
  6243. $uid = Site::getUid();
  6244. $cpid = Site::getCpid();
  6245. $role = Site::getRole();
  6246. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6247. // 如果是公共库操作,需要admin权限
  6248. if ($is_public && $role !== 'admin') {
  6249. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6250. }
  6251. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6252. $store_uid = $is_public ? 0 : $uid;
  6253. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6254. $script_id = (int)getProp($data, 'script_id', 0);
  6255. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6256. if ($script_id && empty($episode_numbers)) {
  6257. Utils::throwError('20003:剧集序号不能为空');
  6258. }
  6259. if (!$script_id && !empty($episode_numbers)) {
  6260. Utils::throwError('20003:请提供剧本ID');
  6261. }
  6262. $product_name = trim(getProp($data, 'product_name'));
  6263. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6264. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6265. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6266. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6267. $url = trim(getProp($data, 'url'));
  6268. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6269. $versions = getProp($data, 'versions');
  6270. // 检查是否是正确的图片格式
  6271. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6272. $urlPath = parse_url($url, PHP_URL_PATH);
  6273. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6274. if (!in_array($extension, $allowedExtensions)) {
  6275. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6276. }
  6277. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6278. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6279. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6280. $product = getProp($data, 'product');
  6281. if (!in_array($product, [1, 2, 3])) {
  6282. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6283. }
  6284. // 获取父文件夹ID和层级
  6285. $parent_id = getProp($data, 'parent_id', 0);
  6286. $parent_level = 0;
  6287. if ($parent_id > 0) {
  6288. $parent = DB::table('mp_products')
  6289. ->where('id', $parent_id)
  6290. ->where('cpid', $cpid)
  6291. ->where('user_id', $store_uid)
  6292. ->where('type', 2)
  6293. ->where('is_deleted', 0)
  6294. ->first();
  6295. if (!$parent) {
  6296. Utils::throwError('20003:父文件夹不存在');
  6297. }
  6298. $parent_level = $parent->level;
  6299. }
  6300. // 创建资产并保存剧本资产关联关系(同一事务)
  6301. DB::beginTransaction();
  6302. try {
  6303. $id = DB::table('mp_products')->insertGetId([
  6304. 'user_id' => $store_uid,
  6305. 'cpid' => $cpid,
  6306. 'type' => 1, // 1=角色图片
  6307. 'parent_id' => $parent_id,
  6308. 'level' => $parent_level + 1,
  6309. 'product_name' => $product_name,
  6310. 'url' => $url,
  6311. 'pic_prompt' => $pic_prompt,
  6312. 'product' => $product,
  6313. 'versions' => json_encode($versions, 256),
  6314. 'sort_order' => time(), // 使用时间戳作为排序权重
  6315. 'created_at' => date('Y-m-d H:i:s'),
  6316. 'updated_at' => date('Y-m-d H:i:s')
  6317. ]);
  6318. if (!$id) Utils::throwError('20003:创建失败');
  6319. // 保存剧本资产关联关系
  6320. if ($script_id) {
  6321. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6322. }
  6323. DB::commit();
  6324. } catch (\Exception $e) {
  6325. DB::rollback();
  6326. throw $e;
  6327. }
  6328. return [
  6329. 'id' => $id,
  6330. 'type' => 1,
  6331. 'parent_id' => $parent_id,
  6332. 'level' => $parent_level + 1,
  6333. 'product_name' => $product_name,
  6334. 'url' => $url,
  6335. 'pic_prompt' => $pic_prompt,
  6336. 'product' => $product,
  6337. 'versions' => $versions
  6338. ];
  6339. }
  6340. public function editProduct($data) {
  6341. $uid = Site::getUid();
  6342. $cpid = Site::getCpid();
  6343. $role = Site::getRole();
  6344. $id = getProp($data, 'id');
  6345. if (!$id) Utils::throwError('20003:ID不能为空');
  6346. $versions = getProp($data, 'versions');
  6347. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6348. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6349. $script_id = (int)getProp($data, 'script_id', 0);
  6350. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6351. if ($script_id && empty($episode_numbers)) {
  6352. Utils::throwError('20003:剧集序号不能为空');
  6353. }
  6354. if (!$script_id && !empty($episode_numbers)) {
  6355. Utils::throwError('20003:请提供剧本ID');
  6356. }
  6357. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6358. $query_uid = $is_public ? 0 : $uid;
  6359. // 如果是公共库操作,需要admin权限
  6360. if ($is_public && $role !== 'admin') {
  6361. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6362. }
  6363. // 检查是否存在且属于当前用户或公共库
  6364. $role = DB::table('mp_products')
  6365. ->where('id', $id)
  6366. ->where('cpid', $cpid)
  6367. ->where('user_id', $query_uid)
  6368. ->where('type', 1)->first();
  6369. if (!$role) Utils::throwError('20003:记录不存在');
  6370. $updateData = [];
  6371. // $needVersionRecord = false; // 是否需要记录版本
  6372. // 名称
  6373. $product_name = trim(getProp($data, 'product_name'));
  6374. if ($product_name) {
  6375. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6376. $updateData['product_name'] = $product_name;
  6377. }
  6378. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6379. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6380. // 图片地址
  6381. $url = trim(getProp($data, 'url'));
  6382. if ($url) {
  6383. // 检查是否是正确的图片格式
  6384. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6385. $urlPath = parse_url($url, PHP_URL_PATH);
  6386. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6387. if (!in_array($extension, $allowedExtensions)) {
  6388. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6389. }
  6390. // // 如果 url 有变更,记录版本
  6391. // if ($url !== $role->url) {
  6392. // $needVersionRecord = true;
  6393. // }
  6394. $updateData['url'] = $url;
  6395. }
  6396. // 提示词
  6397. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6398. if ($pic_prompt) {
  6399. // // 如果 pic_prompt 有变更,记录版本
  6400. // if ($pic_prompt !== $role->pic_prompt) {
  6401. // $needVersionRecord = true;
  6402. // }
  6403. $updateData['pic_prompt'] = $pic_prompt;
  6404. }
  6405. if (empty($updateData) && !$script_id) {
  6406. Utils::throwError('20003:没有需要更新的数据');
  6407. }
  6408. // // 如果需要记录版本,将数据添加到 versions 数组
  6409. // if ($needVersionRecord) {
  6410. // // 获取现有的 versions 数据
  6411. // $versions = json_decode($role->versions, true) ?: [];
  6412. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6413. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6414. // if ($isFirstVersion) {
  6415. // $oldVersion = [
  6416. // 'url' => $role->url,
  6417. // 'description' => $role->pic_prompt,
  6418. // ];
  6419. // // 旧版本添加到数组末尾
  6420. // $versions[] = $oldVersion;
  6421. // }
  6422. // // 构建新版本(变更后)
  6423. // $newVersion = [
  6424. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6425. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6426. // ];
  6427. // // 检查新版本是否已存在于历史版本中
  6428. // $existingIndex = -1;
  6429. // foreach ($versions as $index => $version) {
  6430. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6431. // $existingIndex = $index;
  6432. // break;
  6433. // }
  6434. // }
  6435. // if ($existingIndex !== -1) {
  6436. // // 如果已存在,移除旧的位置
  6437. // array_splice($versions, $existingIndex, 1);
  6438. // }
  6439. // // 新版本添加到数组开头(最新的在前)
  6440. // array_unshift($versions, $newVersion);
  6441. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6442. // // if (count($versions) > 10) {
  6443. // // $versions = array_slice($versions, 0, 10);
  6444. // // }
  6445. // $updateData['versions'] = json_encode($versions, 256);
  6446. // }
  6447. if ($versions) {
  6448. $updateData['versions'] = json_encode($versions, 256);
  6449. }
  6450. if (!empty($updateData)) {
  6451. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6452. }
  6453. // 更新资产并保存剧本资产关联关系(同一事务)
  6454. DB::beginTransaction();
  6455. try {
  6456. $updated = true;
  6457. if (!empty($updateData)) {
  6458. $updated = DB::table('mp_products')
  6459. ->where('cpid', $cpid)
  6460. ->where('id', $id)
  6461. ->update($updateData);
  6462. }
  6463. // 保存剧本资产关联关系
  6464. if ($script_id) {
  6465. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6466. }
  6467. DB::commit();
  6468. } catch (\Exception $e) {
  6469. DB::rollback();
  6470. throw $e;
  6471. }
  6472. return $updated;
  6473. }
  6474. /**
  6475. * 保存单一资产与剧本剧集的关联关系
  6476. *
  6477. * @param int $product_id 资产ID
  6478. * @param int $script_id 剧本ID
  6479. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6480. * @return int 新增关联数量
  6481. */
  6482. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6483. $uid = Site::getUid();
  6484. // 验证剧本是否存在
  6485. $script = DB::table('mp_scripts')
  6486. ->where('id', $script_id)
  6487. ->where('is_deleted', 0)
  6488. ->first();
  6489. if (!$script) {
  6490. Utils::throwError('20003:剧本不存在');
  6491. }
  6492. // 验证剧本归属:只能关联自己的剧本
  6493. if ((int)$script->user_id !== (int)$uid) {
  6494. Utils::throwError('20003:只能添加到自己的剧本');
  6495. }
  6496. // 使用 splitContent 拆分剧本内容获取总集数
  6497. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6498. // 解析剧集序号(数组)
  6499. $episodes = [];
  6500. foreach ($episode_numbers as $item) {
  6501. if (is_array($item)) {
  6502. continue;
  6503. }
  6504. $item = trim((string)$item);
  6505. if ($item === '' || !is_numeric($item)) {
  6506. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6507. }
  6508. $episodes[] = (int)$item;
  6509. }
  6510. // 去重并校验序号范围(序号从1开始)
  6511. $episodes = array_values(array_unique($episodes));
  6512. if (empty($episodes)) {
  6513. Utils::throwError('20003:剧集序号不能为空');
  6514. }
  6515. foreach ($episodes as $episode) {
  6516. if ($episode < 1 || $episode > $totalEpisodes) {
  6517. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6518. }
  6519. }
  6520. $now = now();
  6521. // 过滤已存在的关联,避免重复
  6522. $existingEpisodes = DB::table('mp_script_product_mappings')
  6523. ->where('script_id', $script_id)
  6524. ->where('product_id', $product_id)
  6525. ->whereIn('episode_number', $episodes)
  6526. ->pluck('episode_number')
  6527. ->all();
  6528. $mappingRecords = [];
  6529. foreach ($episodes as $episode) {
  6530. if (in_array($episode, $existingEpisodes)) {
  6531. continue;
  6532. }
  6533. $mappingRecords[] = [
  6534. 'script_id' => $script_id,
  6535. 'product_id' => $product_id,
  6536. 'episode_number' => $episode,
  6537. 'created_at' => $now,
  6538. 'updated_at' => $now,
  6539. ];
  6540. }
  6541. $insertedCount = 0;
  6542. if (!empty($mappingRecords)) {
  6543. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6544. }
  6545. return $insertedCount;
  6546. }
  6547. /**
  6548. * 规范化剧集序号参数,统一为数组
  6549. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6550. *
  6551. * @param mixed $episode_number 剧集序号参数
  6552. * @return array
  6553. */
  6554. private function normalizeEpisodeNumbers($episode_number) {
  6555. if (!is_array($episode_number)) {
  6556. $episode_number = explode(',', (string)$episode_number);
  6557. }
  6558. $items = [];
  6559. foreach ($episode_number as $item) {
  6560. if (is_array($item)) {
  6561. continue;
  6562. }
  6563. foreach (explode(',', (string)$item) as $part) {
  6564. $part = trim($part);
  6565. if ($part !== '') {
  6566. $items[] = $part;
  6567. }
  6568. }
  6569. }
  6570. return $items;
  6571. }
  6572. /**
  6573. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6574. *
  6575. * @param object $script 剧本记录
  6576. * @return int 总集数
  6577. */
  6578. private function getScriptTotalEpisodeCount($script) {
  6579. if (empty($script->content)) {
  6580. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6581. }
  6582. $totalEpisodes = count(splitContent($script->content));
  6583. if ($totalEpisodes < 1) {
  6584. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6585. }
  6586. return $totalEpisodes;
  6587. }
  6588. /**
  6589. * 获取剧本总集数
  6590. *
  6591. * @param array $data 包含 script_id(剧本ID)
  6592. * @return array
  6593. */
  6594. public function getScriptTotalEpisodes($data) {
  6595. $script_id = (int)getProp($data, 'script_id', 0);
  6596. if (!$script_id) {
  6597. Utils::throwError('20003:请提供剧本ID');
  6598. }
  6599. // 验证剧本是否存在
  6600. $script = DB::table('mp_scripts')
  6601. ->where('id', $script_id)
  6602. ->where('is_deleted', 0)
  6603. ->first();
  6604. if (!$script) {
  6605. Utils::throwError('20003:剧本不存在');
  6606. }
  6607. return [
  6608. 'script_id' => $script_id,
  6609. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6610. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6611. ];
  6612. }
  6613. /**
  6614. * 获取角色版本历史
  6615. * @param array $data 包含 id(角色ID)
  6616. * @return array 返回版本历史列表
  6617. */
  6618. public function getProductVersions($data) {
  6619. $cpid = Site::getCpid();
  6620. $id = getProp($data, 'id');
  6621. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6622. $role = DB::table('mp_products')
  6623. ->where('id', $id)
  6624. ->where('cpid', $cpid)
  6625. ->where('type', 1)
  6626. ->first();
  6627. if (!$role) Utils::throwError('20003:角色不存在');
  6628. // 获取版本历史
  6629. $versions = json_decode($role->versions, true) ?: [];
  6630. // 添加当前版本作为最新版本
  6631. $currentVersion = [
  6632. 'version' => 0, // 0 表示当前版本
  6633. 'url' => $role->url,
  6634. 'pic_prompt' => $role->pic_prompt,
  6635. 'updated_at' => $role->updated_at,
  6636. 'is_current' => true
  6637. ];
  6638. array_unshift($versions, $currentVersion);
  6639. return $versions;
  6640. }
  6641. /**
  6642. * 恢复到指定版本
  6643. * @param array $data 包含 id(角色ID)、version(版本号)
  6644. * @return bool
  6645. */
  6646. public function restoreProductVersion($data) {
  6647. $uid = Site::getUid();
  6648. $cpid = Site::getCpid();
  6649. $id = getProp($data, 'id');
  6650. $version = getProp($data, 'version');
  6651. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6652. if (!$version) Utils::throwError('20003:版本号不能为空');
  6653. $role = DB::table('mp_products')
  6654. ->where('id', $id)
  6655. ->where('cpid', $cpid)
  6656. ->where('type', 1)
  6657. ->first();
  6658. if (!$role) Utils::throwError('20003:角色不存在');
  6659. // 获取版本历史
  6660. $versions = json_decode($role->versions, true) ?: [];
  6661. // 查找指定版本
  6662. $targetVersion = null;
  6663. foreach ($versions as $v) {
  6664. if ($v['version'] == $version) {
  6665. $targetVersion = $v;
  6666. break;
  6667. }
  6668. }
  6669. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6670. // 先将当前版本保存到历史
  6671. $newVersion = [
  6672. 'version' => count($versions) + 1,
  6673. 'url' => $role->url,
  6674. 'pic_prompt' => $role->pic_prompt,
  6675. 'updated_at' => date('Y-m-d H:i:s'),
  6676. 'updated_by' => $uid
  6677. ];
  6678. array_unshift($versions, $newVersion);
  6679. // 限制版本数量
  6680. if (count($versions) > 10) {
  6681. $versions = array_slice($versions, 0, 10);
  6682. }
  6683. // 恢复到指定版本
  6684. return DB::table('mp_products')
  6685. ->where('id', $id)
  6686. ->where('cpid', $cpid)
  6687. ->update([
  6688. 'url' => $targetVersion['url'],
  6689. 'pic_prompt' => $targetVersion['pic_prompt'],
  6690. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6691. 'updated_at' => date('Y-m-d H:i:s')
  6692. ]);
  6693. }
  6694. public function deleteProduct($data) {
  6695. $uid = Site::getUid();
  6696. $cpid = Site::getCpid();
  6697. $role = Site::getRole();
  6698. $id = getProp($data, 'id');
  6699. if (!$id) Utils::throwError('20003:ID不能为空');
  6700. $ids = explode(',', $id);
  6701. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6702. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6703. $query_uid = $is_public ? 0 : $uid;
  6704. // 如果是公共库操作,需要admin权限
  6705. if ($is_public && $role !== 'admin') {
  6706. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6707. }
  6708. // 检查是否存在且属于当前用户或公共库
  6709. $role = DB::table('mp_products')
  6710. ->whereIn('id', $ids)
  6711. ->where('cpid', $cpid)
  6712. ->where('user_id', $query_uid)
  6713. ->get();
  6714. if (!$role) Utils::throwError('20003:记录不存在');
  6715. return DB::table('mp_products')
  6716. ->where('cpid', $cpid)
  6717. ->where('user_id', $query_uid)
  6718. ->whereIn('id', $ids)
  6719. ->update([
  6720. 'is_deleted' => 1,
  6721. 'updated_at' => date('Y-m-d H:i:s')
  6722. ]);
  6723. }
  6724. public function generateThreeView($data) {
  6725. $uid = Site::getUid();
  6726. $cpid = Site::getCpid();
  6727. $role = Site::getRole();
  6728. $id = getProp($data, 'id');
  6729. if (!$id) Utils::throwError('20003:ID不能为空');
  6730. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6731. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6732. $query_uid = $is_public ? 0 : $uid;
  6733. // 如果是公共库操作,需要admin权限
  6734. if ($is_public && $role !== 'admin') {
  6735. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6736. }
  6737. // 检查是否存在且属于当前用户或公共库
  6738. $product = DB::table('mp_products')
  6739. ->where('id', $id)
  6740. ->where('cpid', $cpid)
  6741. ->where('user_id', $query_uid)
  6742. ->where('type', 1)->first();
  6743. if (!$product) Utils::throwError('20003:资产不存在');
  6744. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6745. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6746. if (!$ref_img_url) {
  6747. // 如果没有传入参考图,使用角色表中的图片
  6748. $ref_img_url = $product->url ?? '';
  6749. if (!$ref_img_url) {
  6750. Utils::throwError('20003:参考图不能为空');
  6751. }
  6752. }
  6753. $pic_prompt = getProp($product, 'pic_prompt');
  6754. if ($pic_prompt) {
  6755. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6756. }
  6757. // 检查参考图是否是正确的图片格式
  6758. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6759. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6760. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6761. if (!in_array($extension, $allowedExtensions)) {
  6762. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6763. }
  6764. // 处理图片模型
  6765. $model = getProp($data, 'model');
  6766. if (!$model) {
  6767. // 使用默认模型
  6768. $model = 'doubao-seedream-5-0-lite-260128';
  6769. }
  6770. // 验证模型是否在可用模型表中
  6771. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6772. Utils::throwError('20003:该模型已不可用,请更换!');
  6773. }
  6774. $ratio = getProp($data, 'ratio', '16:9');
  6775. $resolution = getProp($data, 'resolution', '2k');
  6776. // 定义分辨率和宽高比对应的尺寸映射表
  6777. $sizeMap = [
  6778. '2k' => [
  6779. '1:1' => ['width' => 2048, 'height' => 2048],
  6780. '4:3' => ['width' => 2304, 'height' => 1728],
  6781. '3:4' => ['width' => 1728, 'height' => 2304],
  6782. '16:9' => ['width' => 2848, 'height' => 1600],
  6783. '9:16' => ['width' => 1600, 'height' => 2848],
  6784. '3:2' => ['width' => 2496, 'height' => 1664],
  6785. '2:3' => ['width' => 1664, 'height' => 2496],
  6786. '21:9' => ['width' => 3136, 'height' => 1344],
  6787. ],
  6788. '3k' => [
  6789. '1:1' => ['width' => 3072, 'height' => 3072],
  6790. '4:3' => ['width' => 3456, 'height' => 2592],
  6791. '3:4' => ['width' => 2592, 'height' => 3456],
  6792. '16:9' => ['width' => 4096, 'height' => 2304],
  6793. '9:16' => ['width' => 2304, 'height' => 4096],
  6794. '2:3' => ['width' => 2496, 'height' => 3744],
  6795. '3:2' => ['width' => 3744, 'height' => 2496],
  6796. '21:9' => ['width' => 4704, 'height' => 2016],
  6797. ],
  6798. '4k' => [
  6799. '1:1' => ['width' => 4096, 'height' => 4096],
  6800. '3:4' => ['width' => 3520, 'height' => 4704],
  6801. '4:3' => ['width' => 4704, 'height' => 3520],
  6802. '16:9' => ['width' => 5504, 'height' => 3040],
  6803. '9:16' => ['width' => 3040, 'height' => 5504],
  6804. '2:3' => ['width' => 3328, 'height' => 4992],
  6805. '3:2' => ['width' => 4992, 'height' => 3328],
  6806. '21:9' => ['width' => 6240, 'height' => 2656],
  6807. ],
  6808. ];
  6809. // 参数验证
  6810. $resolution = strtolower($resolution);
  6811. if (!isset($sizeMap[$resolution])) {
  6812. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6813. }
  6814. if (!isset($sizeMap[$resolution][$ratio])) {
  6815. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6816. }
  6817. // 根据 ratio 和 resolution 确定宽高
  6818. $width = $sizeMap[$resolution][$ratio]['width'];
  6819. $height = $sizeMap[$resolution][$ratio]['height'];
  6820. try {
  6821. // 创建图片生成任务
  6822. $params = [
  6823. 'prompt' => $prompt,
  6824. 'model' => $model,
  6825. 'ref_img_urls' => [$ref_img_url],
  6826. 'width' => $width,
  6827. 'height' => $height
  6828. ];
  6829. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6830. $task_id = $task->id;
  6831. if (!$task_id) {
  6832. Utils::throwError('20003:创建图片生成任务失败');
  6833. }
  6834. // 轮询获取结果
  6835. // 只查询数据库,不调用API,不更新任务表
  6836. $start_time = time();
  6837. $timeout = 1800;
  6838. $img_url = '';
  6839. while (time() - $start_time < $timeout) {
  6840. sleep(5);
  6841. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6842. $task = DB::table('mp_generate_pic_tasks')
  6843. ->where('id', $task_id)
  6844. ->first();
  6845. if (!$task) {
  6846. Utils::throwError('20003:任务不存在');
  6847. }
  6848. if ($task->status === 'success' && $task->result_url) {
  6849. $result_urls = is_string($task->result_url)
  6850. ? json_decode($task->result_url, true)
  6851. : $task->result_url;
  6852. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6853. break;
  6854. } elseif ($task->status === 'failed') {
  6855. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6856. }
  6857. // 其他状态继续轮询
  6858. }
  6859. if (empty($img_url)) {
  6860. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6861. }
  6862. // 更新 mp_products 表(不是任务表)
  6863. DB::table('mp_products')
  6864. ->where('id', $id)
  6865. ->where('cpid', $cpid)
  6866. ->update([
  6867. 'three_view_image_url' => $img_url,
  6868. 'updated_at' => date('Y-m-d H:i:s')
  6869. ]);
  6870. return ['three_view_image_url' => $img_url];
  6871. } catch (\Exception $e) {
  6872. dLog('anime')->error('生成三视图失败', [
  6873. 'error' => $e->getMessage()
  6874. ]);
  6875. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6876. Utils::throwError('20003:' . $e->getMessage());
  6877. }
  6878. }
  6879. /**
  6880. * 推送(复制)资产或文件夹到目标位置
  6881. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6882. * @return array 返回推送结果
  6883. */
  6884. public function pushProductOrFolder($data) {
  6885. $uid = Site::getUid();
  6886. $cpid = Site::getCpid();
  6887. $role = Site::getRole();
  6888. $product_id = getProp($data, 'product_id');
  6889. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6890. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6891. if (!$product_id) {
  6892. Utils::throwError('20003:请选择要推送的项目');
  6893. }
  6894. // 查询源项目(只通过cpid查询,不限制user_id)
  6895. $sourceItem = DB::table('mp_products')
  6896. ->where('id', $product_id)
  6897. ->where('cpid', $cpid)
  6898. ->where('is_deleted', 0)
  6899. ->first();
  6900. if (!$sourceItem) {
  6901. Utils::throwError('20003:要推送的项目不存在');
  6902. }
  6903. // 通过user_id判断源是公共库还是个人库
  6904. $source_uid = $sourceItem->user_id;
  6905. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6906. // 验证目标文件夹并确定目标是公共库还是个人库
  6907. $target_level = 0;
  6908. $target_uid = $uid; // 默认推送到个人库
  6909. $target_is_public = 0;
  6910. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6911. if ($target_parent_id > 0) {
  6912. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6913. $targetParent = DB::table('mp_products')
  6914. ->where('id', $target_parent_id)
  6915. ->where('cpid', $cpid)
  6916. ->where('type', 2)
  6917. ->where('is_deleted', 0)
  6918. ->first();
  6919. if (!$targetParent) {
  6920. Utils::throwError('20003:目标文件夹不存在');
  6921. }
  6922. // 通过user_id判断目标是公共库还是个人库
  6923. $target_level = $targetParent->level;
  6924. $target_uid = $targetParent->user_id;
  6925. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6926. // 使用目标文件夹的 product 类型
  6927. $final_product_type = $targetParent->product;
  6928. }
  6929. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6930. else {
  6931. $push_to_public = getProp($data, 'push_to_public');
  6932. if ($push_to_public === '') {
  6933. Utils::throwError('20003:请选择是否推送到公共库');
  6934. }
  6935. if ($push_to_public) {
  6936. $target_uid = 0;
  6937. $target_is_public = 1;
  6938. }
  6939. // 推送到根目录时,必须指定 product 类型
  6940. if ($target_product === null || $target_product === '') {
  6941. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6942. }
  6943. $final_product_type = $target_product;
  6944. }
  6945. // 如果目标是公共库,需要admin权限
  6946. if ($target_is_public && $role !== 'admin') {
  6947. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6948. }
  6949. // 权限验证:验证是否符合允许的推送规则
  6950. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6951. try {
  6952. DB::beginTransaction();
  6953. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6954. if ($sourceItem->type == 1) {
  6955. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6956. DB::commit();
  6957. return [
  6958. 'product_id' => $newId,
  6959. ];
  6960. }
  6961. // 如果是文件夹,递归复制(支持跨类型推送)
  6962. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6963. DB::commit();
  6964. return [
  6965. 'product_id' => $newFolderId,
  6966. ];
  6967. } catch (\Exception $e) {
  6968. DB::rollBack();
  6969. dLog('anime')->error('推送失败', [
  6970. 'error' => $e->getMessage(),
  6971. 'product_id' => $product_id
  6972. ]);
  6973. Utils::throwError('20003:' . $e->getMessage());
  6974. }
  6975. }
  6976. /**
  6977. * 验证推送权限
  6978. * 允许的推送规则:
  6979. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6980. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6981. * 3. 公共库推送给公共库(公共库 → 公共库)
  6982. *
  6983. * @param int $source_uid 源的user_id
  6984. * @param int $target_uid 目标的user_id
  6985. * @param int $current_uid 当前用户ID
  6986. * @throws \Exception
  6987. */
  6988. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6989. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6990. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6991. return; // 允许
  6992. }
  6993. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6994. if ($source_uid == 0 && $target_uid == $current_uid) {
  6995. return; // 允许
  6996. }
  6997. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6998. if ($source_uid == 0 && $target_uid == 0) {
  6999. return; // 允许
  7000. }
  7001. // 其他情况都不允许
  7002. if ($source_uid != 0 && $source_uid != $current_uid) {
  7003. // 源是别人的个人库
  7004. Utils::throwError('20003:无权限访问该资产');
  7005. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7006. // 个人库推送给公共库(不允许)
  7007. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7008. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7009. // 不同用户的个人库之间推送(不允许)
  7010. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7011. } else {
  7012. // 其他未知情况
  7013. Utils::throwError('20003:不允许的推送操作');
  7014. }
  7015. }
  7016. /**
  7017. * 复制单个资产
  7018. * @param object $sourceProduct 源资产对象
  7019. * @param int $targetParentId 目标父文件夹ID
  7020. * @param int $targetLevel 目标层级
  7021. * @param int $cpid 公司ID
  7022. * @param int $targetUid 目标用户ID
  7023. * @return int 返回新资产ID
  7024. */
  7025. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7026. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7027. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7028. $newProductData = [
  7029. 'user_id' => $targetUid,
  7030. 'cpid' => $cpid,
  7031. 'type' => 1,
  7032. 'parent_id' => $targetParentId,
  7033. 'level' => $targetLevel,
  7034. 'product_name' => $sourceProduct->product_name,
  7035. 'url' => $sourceProduct->url,
  7036. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7037. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7038. 'product' => $finalProductType,
  7039. 'versions' => $sourceProduct->versions ?? '',
  7040. 'sort_order' => time(),
  7041. 'is_deleted' => 0,
  7042. 'created_at' => date('Y-m-d H:i:s'),
  7043. 'updated_at' => date('Y-m-d H:i:s')
  7044. ];
  7045. return DB::table('mp_products')->insertGetId($newProductData);
  7046. }
  7047. /**
  7048. * 递归复制文件夹及其子项
  7049. * @param object $sourceFolder 源文件夹对象
  7050. * @param int $targetParentId 目标父文件夹ID
  7051. * @param int $targetLevel 目标层级
  7052. * @param int $cpid 公司ID
  7053. * @param int $targetUid 目标用户ID
  7054. * @param int $sourceUid 源用户ID
  7055. * @return int 返回新文件夹ID
  7056. */
  7057. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7058. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7059. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7060. // 创建新文件夹
  7061. $newFolderData = [
  7062. 'user_id' => $targetUid,
  7063. 'cpid' => $cpid,
  7064. 'type' => 2,
  7065. 'parent_id' => $targetParentId,
  7066. 'level' => $targetLevel,
  7067. 'product_name' => $sourceFolder->product_name,
  7068. 'product' => $finalProductType,
  7069. 'sort_order' => time(),
  7070. 'is_deleted' => 0,
  7071. 'created_at' => date('Y-m-d H:i:s'),
  7072. 'updated_at' => date('Y-m-d H:i:s')
  7073. ];
  7074. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7075. // 获取源文件夹下的所有子项
  7076. $children = DB::table('mp_products')
  7077. ->where('parent_id', $sourceFolder->id)
  7078. ->where('cpid', $cpid)
  7079. ->where('user_id', $sourceUid)
  7080. ->where('is_deleted', 0)
  7081. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7082. ->get();
  7083. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7084. foreach ($children as $child) {
  7085. if ($child->type == 1) {
  7086. // 资产
  7087. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7088. } else {
  7089. // 文件夹
  7090. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7091. }
  7092. }
  7093. return $newFolderId;
  7094. }
  7095. /**
  7096. * 保存剧本资产关联关系
  7097. * @param array $data 请求参数
  7098. * @return bool
  7099. */
  7100. public function saveScriptProducts($data) {
  7101. $uid = Site::getUid();
  7102. $cpid = Site::getCpid();
  7103. $script_id = getProp($data, 'script_id');
  7104. $products = getProp($data, 'products', []);
  7105. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  7106. if (!$script_id) {
  7107. Utils::throwError('20003:请提供剧本ID');
  7108. }
  7109. // 验证剧本是否存在
  7110. $script = DB::table('mp_scripts')
  7111. ->where('id', $script_id)
  7112. ->where('is_deleted', 0)
  7113. ->first();
  7114. if (!$script) {
  7115. Utils::throwError('20003:剧本不存在');
  7116. }
  7117. // 处理图片模型
  7118. $model = getProp($data, 'model');
  7119. if (!$model) {
  7120. // 使用默认模型
  7121. $model = 'doubao-seedream-5-0-lite-260128';
  7122. }
  7123. // 验证模型是否在可用模型表中
  7124. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7125. Utils::throwError('20003:该模型已不可用,请更换!');
  7126. }
  7127. $ratio = getProp($data, 'ratio', '9:16');
  7128. $resolution = getProp($data, 'resolution', '2k');
  7129. // 定义分辨率和宽高比对应的尺寸映射表
  7130. $sizeMap = [
  7131. '2k' => [
  7132. '1:1' => ['width' => 2048, 'height' => 2048],
  7133. '4:3' => ['width' => 2304, 'height' => 1728],
  7134. '3:4' => ['width' => 1728, 'height' => 2304],
  7135. '16:9' => ['width' => 2848, 'height' => 1600],
  7136. '9:16' => ['width' => 1600, 'height' => 2848],
  7137. '3:2' => ['width' => 2496, 'height' => 1664],
  7138. '2:3' => ['width' => 1664, 'height' => 2496],
  7139. '21:9' => ['width' => 3136, 'height' => 1344],
  7140. ],
  7141. '3k' => [
  7142. '1:1' => ['width' => 3072, 'height' => 3072],
  7143. '4:3' => ['width' => 3456, 'height' => 2592],
  7144. '3:4' => ['width' => 2592, 'height' => 3456],
  7145. '16:9' => ['width' => 4096, 'height' => 2304],
  7146. '9:16' => ['width' => 2304, 'height' => 4096],
  7147. '2:3' => ['width' => 2496, 'height' => 3744],
  7148. '3:2' => ['width' => 3744, 'height' => 2496],
  7149. '21:9' => ['width' => 4704, 'height' => 2016],
  7150. ],
  7151. '4k' => [
  7152. '1:1' => ['width' => 4096, 'height' => 4096],
  7153. '3:4' => ['width' => 3520, 'height' => 4704],
  7154. '4:3' => ['width' => 4704, 'height' => 3520],
  7155. '16:9' => ['width' => 5504, 'height' => 3040],
  7156. '9:16' => ['width' => 3040, 'height' => 5504],
  7157. '2:3' => ['width' => 3328, 'height' => 4992],
  7158. '3:2' => ['width' => 4992, 'height' => 3328],
  7159. '21:9' => ['width' => 6240, 'height' => 2656],
  7160. ],
  7161. ];
  7162. // 参数验证
  7163. $resolution = strtolower($resolution);
  7164. if (!isset($sizeMap[$resolution])) {
  7165. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7166. }
  7167. if (!isset($sizeMap[$resolution][$ratio])) {
  7168. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7169. }
  7170. // 根据 ratio 和 resolution 确定宽高
  7171. $width = $sizeMap[$resolution][$ratio]['width'];
  7172. $height = $sizeMap[$resolution][$ratio]['height'];
  7173. $script_name = $script->script_name ?? 'script_' . $script_id;
  7174. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  7175. $taskCenterId = $this->createScriptProductTaskCenter(
  7176. $uid,
  7177. $cpid,
  7178. $script_id,
  7179. $products,
  7180. $model,
  7181. $ratio,
  7182. $resolution,
  7183. $auto_generate_images
  7184. );
  7185. // 检查是否已经有该剧本的资产数据
  7186. $existingMappings = DB::table('mp_script_product_mappings')
  7187. ->where('script_id', $script_id)
  7188. ->get();
  7189. if ($existingMappings->isNotEmpty()) {
  7190. // 已存在资产映射,检查是否所有资产都有图片生成任务
  7191. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  7192. // 查询这些资产的图片生成任务状态
  7193. $productsWithTasks = DB::table('mp_products')
  7194. ->whereIn('id', $productIds)
  7195. ->where('is_deleted', 0)
  7196. ->get();
  7197. $productTaskMap = [];
  7198. $typeFolderIds = [];
  7199. $hasAllTasks = true;
  7200. foreach ($productsWithTasks as $product) {
  7201. // 收集类型文件夹ID
  7202. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  7203. $parentFolder = DB::table('mp_products')
  7204. ->where('id', $product->parent_id)
  7205. ->where('type', 2)
  7206. ->first();
  7207. if ($parentFolder) {
  7208. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  7209. }
  7210. }
  7211. // 检查是否有图片生成任务
  7212. if (!empty($product->pic_task_id)) {
  7213. $productTaskMap[$product->id] = $product->pic_task_id;
  7214. } else if($product->url && $product->pic_task_status == '生成成功') {
  7215. continue;
  7216. } else {
  7217. // 有资产没有图片任务
  7218. $hasAllTasks = false;
  7219. }
  7220. }
  7221. // 如果所有资产都有任务ID,直接轮询返回结果
  7222. if ($hasAllTasks && !empty($productTaskMap)) {
  7223. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  7224. 'script_id' => $script_id,
  7225. 'script_name' => $script_name,
  7226. 'product_count' => count($productTaskMap)
  7227. ]);
  7228. // 直接返回 SSE 流轮询结果
  7229. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7230. }
  7231. // 如果部分资产没有任务ID,只为这些资产创建任务
  7232. if (!$hasAllTasks && $auto_generate_images) {
  7233. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  7234. 'script_id' => $script_id,
  7235. 'script_name' => $script_name
  7236. ]);
  7237. // 开启事务
  7238. DB::beginTransaction();
  7239. try {
  7240. foreach ($productsWithTasks as $product) {
  7241. // 跳过已有任务的资产
  7242. if (!empty($product->pic_task_id)) {
  7243. continue;
  7244. }
  7245. // 跳过没有提示词的资产
  7246. if (empty($product->pic_prompt)) {
  7247. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7248. 'product_id' => $product->id,
  7249. 'product_name' => $product->product_name
  7250. ]);
  7251. continue;
  7252. }
  7253. try {
  7254. // 创建图片生成任务
  7255. $params = [
  7256. 'prompt' => $product->pic_prompt,
  7257. 'model' => $model,
  7258. 'ref_img_urls' => [],
  7259. 'width' => $width,
  7260. 'height' => $height
  7261. ];
  7262. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7263. $task_id = $task->id;
  7264. if ($task_id) {
  7265. $productTaskMap[$product->id] = $task_id;
  7266. // 在事务中更新资产表的任务ID和状态
  7267. DB::table('mp_products')
  7268. ->where('id', $product->id)
  7269. ->update([
  7270. 'pic_task_id' => $task_id,
  7271. 'pic_task_status' => '生成中',
  7272. 'updated_at' => now()
  7273. ]);
  7274. dLog('anime')->info('为已存在资产创建图片生成任务', [
  7275. 'product_id' => $product->id,
  7276. 'task_id' => $task_id
  7277. ]);
  7278. }
  7279. } catch (\Exception $e) {
  7280. dLog('anime')->error('创建资产图片生成任务失败', [
  7281. 'product_id' => $product->id,
  7282. 'error' => $e->getMessage()
  7283. ]);
  7284. // 标记为失败(仍在事务中)
  7285. DB::table('mp_products')
  7286. ->where('id', $product->id)
  7287. ->update([
  7288. 'pic_task_status' => '生成失败',
  7289. 'updated_at' => now()
  7290. ]);
  7291. }
  7292. }
  7293. // 提交事务
  7294. DB::commit();
  7295. // 如果有新创建的任务,返回 SSE 流
  7296. if (!empty($productTaskMap)) {
  7297. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7298. }
  7299. } catch (\Exception $e) {
  7300. // 回滚事务
  7301. DB::rollback();
  7302. dLog('anime')->error('为已存在资产创建图片任务失败', [
  7303. 'script_id' => $script_id,
  7304. 'error' => $e->getMessage()
  7305. ]);
  7306. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  7307. }
  7308. }
  7309. // 如果不需要生成图片,返回已存在的信息
  7310. $resultData = [
  7311. 'success' => true,
  7312. 'message' => '剧本资产已存在',
  7313. 'script_id' => $script_id,
  7314. 'script_name' => $script_name,
  7315. 'type_folder_ids' => $typeFolderIds,
  7316. 'existing_products' => count($productIds),
  7317. 'tasks_count' => count($productTaskMap),
  7318. 'task_center_id' => $taskCenterId
  7319. ];
  7320. // 接口已正常完成,更新任务中心状态和结果
  7321. if ($taskCenterId) {
  7322. $this->taskCenterService->updateTask($taskCenterId, [
  7323. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7324. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7325. 'error_message' => null
  7326. ]);
  7327. }
  7328. return $resultData;
  7329. }
  7330. // 解析 products(可能是 JSON 字符串或数组)
  7331. if (is_string($products)) {
  7332. $products = json_decode($products, true);
  7333. if (json_last_error() !== JSON_ERROR_NONE) {
  7334. Utils::throwError('20003:产品数据格式错误');
  7335. }
  7336. }
  7337. if (!is_array($products) || empty($products)) {
  7338. Utils::throwError('20003:产品数据不能为空');
  7339. }
  7340. // 以下是原有的创建逻辑...
  7341. // 开启事务
  7342. DB::beginTransaction();
  7343. try {
  7344. $now = now();
  7345. $mappingRecords = [];
  7346. $createdProductIds = []; // 记录所有创建的资产ID
  7347. // 获取剧本名称
  7348. $script_name = $script->script_name ?? 'script_' . $script_id;
  7349. // 存储每个类型的根文件夹ID
  7350. $typeFolderIds = [];
  7351. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  7352. foreach ($products as $productGroup) {
  7353. $type = getProp($productGroup, 'type');
  7354. $title = getProp($productGroup, 'title', '');
  7355. $content = getProp($productGroup, 'content', []);
  7356. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  7357. continue;
  7358. }
  7359. // 为当前类型创建根文件夹(如果还未创建)
  7360. if (!isset($typeFolderIds[$type])) {
  7361. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7362. 'user_id' => $uid,
  7363. 'cpid' => $cpid,
  7364. 'type' => 2, // 1.资产 2文件夹
  7365. 'product' => $type, // 1.主体 2.场景 3.道具
  7366. 'parent_id' => 0, // 根文件夹,parent_id=0
  7367. 'level' => 1, // 第一层级
  7368. 'product_name' => $script_name,
  7369. 'sort_order' => time() + $type,
  7370. 'is_deleted' => 0,
  7371. 'created_at' => $now,
  7372. 'updated_at' => $now
  7373. ]);
  7374. }
  7375. $folder_id = $typeFolderIds[$type];
  7376. // 获取表头(第一行)并查找关键列的位置
  7377. $headers = $content[0];
  7378. $nameColumnIndex = -1; // 资产名称列索引
  7379. $sequenceColumnIndex = -1; // 使用范围列索引
  7380. $promptColumnIndex = -1; // 参考提示词列索引
  7381. foreach ($headers as $index => $header) {
  7382. // 查找"资产名称"列
  7383. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  7384. $nameColumnIndex = $index;
  7385. }
  7386. // 查找"使用范围"列
  7387. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  7388. $sequenceColumnIndex = $index;
  7389. }
  7390. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  7391. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  7392. $promptColumnIndex = $index;
  7393. }
  7394. }
  7395. // 验证必要的列是否都找到了
  7396. if ($nameColumnIndex === -1) {
  7397. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  7398. continue;
  7399. }
  7400. if ($sequenceColumnIndex === -1) {
  7401. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  7402. continue;
  7403. }
  7404. // 跳过表头,解析每一行数据
  7405. for ($i = 1; $i < count($content); $i++) {
  7406. $row = $content[$i];
  7407. // 确保行数据有效
  7408. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  7409. continue;
  7410. }
  7411. // 根据动态查找的列索引提取数据
  7412. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  7413. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  7414. $pic_prompt = '';
  7415. // 提取参考提示词(如果找到了该列)
  7416. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  7417. $pic_prompt = trim($row[$promptColumnIndex]);
  7418. }
  7419. // 解析使用范围(逗号分隔的序号)
  7420. $sequences = [];
  7421. if (!empty($sequence_str)) {
  7422. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  7423. foreach ($sequenceParts as $part) {
  7424. if (is_numeric($part)) {
  7425. $sequences[] = (int)$part;
  7426. }
  7427. }
  7428. }
  7429. if (empty($product_name)) {
  7430. continue;
  7431. }
  7432. // 处理product_name两边的符号
  7433. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7434. // 如果名称不存在或仅剩占位符号,则跳过
  7435. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  7436. dLog('anime')->warning('资产名称无效,跳过保存', [
  7437. 'script_id' => $script_id,
  7438. 'type' => $type,
  7439. 'product_name' => $product_name
  7440. ]);
  7441. continue;
  7442. }
  7443. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  7444. $product_id = DB::table('mp_products')->insertGetId([
  7445. 'product_name' => $product_name,
  7446. 'type' => 1, // 1=资产 2.文件夹
  7447. 'product' => $type, // 1=角色, 2=场景, 3=道具
  7448. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  7449. 'level' => 2, // 第二层级
  7450. 'pic_prompt' => $pic_prompt,
  7451. 'user_id' => $uid,
  7452. 'cpid' => $cpid,
  7453. 'sort_order' => time(),
  7454. 'is_deleted' => 0,
  7455. 'created_at' => $now,
  7456. 'updated_at' => $now,
  7457. ]);
  7458. // 记录创建的资产ID
  7459. $createdProductIds[] = $product_id;
  7460. // 为每个序号创建映射记录
  7461. if (!empty($sequences)) {
  7462. foreach ($sequences as $sequence) {
  7463. $mappingRecords[] = [
  7464. 'script_id' => $script_id,
  7465. 'product_id' => $product_id,
  7466. 'episode_number' => $sequence,
  7467. 'created_at' => $now,
  7468. 'updated_at' => $now,
  7469. ];
  7470. }
  7471. } else {
  7472. // 如果没有指定序号,创建一个默认映射(序号为0)
  7473. $mappingRecords[] = [
  7474. 'script_id' => $script_id,
  7475. 'product_id' => $product_id,
  7476. 'episode_number' => 0,
  7477. 'created_at' => $now,
  7478. 'updated_at' => $now,
  7479. ];
  7480. }
  7481. }
  7482. }
  7483. if (empty($mappingRecords)) {
  7484. Utils::throwError('20003:没有有效的产品数据');
  7485. }
  7486. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7487. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7488. // 剧本已有资产,同步更新is_products标记
  7489. DB::table('mp_scripts')->where('id', $script_id)->update([
  7490. 'is_products' => 1,
  7491. 'updated_at' => $now
  7492. ]);
  7493. // 如果需要自动生成图片,在事务中创建图片生成任务
  7494. $productTaskMap = [];
  7495. if ($auto_generate_images && !empty($createdProductIds)) {
  7496. // 查询所有创建的资产
  7497. $productsToGenerate = DB::table('mp_products')
  7498. ->whereIn('id', $createdProductIds)
  7499. ->where('is_deleted', 0)
  7500. ->get();
  7501. foreach ($productsToGenerate as $product) {
  7502. if (empty($product->pic_prompt)) {
  7503. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7504. 'product_id' => $product->id,
  7505. 'product_name' => $product->product_name
  7506. ]);
  7507. continue;
  7508. }
  7509. try {
  7510. // 创建图片生成任务
  7511. $params = [
  7512. 'prompt' => $product->pic_prompt,
  7513. 'model' => $model,
  7514. 'ref_img_urls' => [],
  7515. 'width' => $width,
  7516. 'height' => $height
  7517. ];
  7518. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7519. $task_id = $task->id;
  7520. if ($task_id) {
  7521. $productTaskMap[$product->id] = $task_id;
  7522. // 在事务中更新资产表的任务ID和状态
  7523. DB::table('mp_products')
  7524. ->where('id', $product->id)
  7525. ->update([
  7526. 'pic_task_id' => $task_id,
  7527. 'pic_task_status' => '生成中',
  7528. 'updated_at' => now()
  7529. ]);
  7530. dLog('anime')->info('创建资产图片生成任务', [
  7531. 'product_id' => $product->id,
  7532. 'task_id' => $task_id
  7533. ]);
  7534. }
  7535. } catch (\Exception $e) {
  7536. dLog('anime')->error('创建资产图片生成任务失败', [
  7537. 'product_id' => $product->id,
  7538. 'error' => $e->getMessage()
  7539. ]);
  7540. // 标记为失败(仍在事务中)
  7541. DB::table('mp_products')
  7542. ->where('id', $product->id)
  7543. ->update([
  7544. 'pic_task_status' => '生成失败',
  7545. 'updated_at' => now()
  7546. ]);
  7547. }
  7548. }
  7549. }
  7550. // 提交事务
  7551. DB::commit();
  7552. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  7553. if ($auto_generate_images && !empty($productTaskMap)) {
  7554. // 返回 SSE 流(事务外轮询)
  7555. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7556. }
  7557. // 如果不需要生成图片,返回普通结果
  7558. $resultData = [
  7559. 'success' => true,
  7560. 'type_folder_ids' => $typeFolderIds,
  7561. 'inserted_count' => $insertedCount,
  7562. 'total_records' => count($mappingRecords),
  7563. 'created_products' => count($createdProductIds),
  7564. 'image_tasks_created' => count($productTaskMap),
  7565. 'task_center_id' => $taskCenterId
  7566. ];
  7567. // 接口已正常完成,更新任务中心状态和结果
  7568. if ($taskCenterId) {
  7569. $this->taskCenterService->updateTask($taskCenterId, [
  7570. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7571. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7572. 'error_message' => null
  7573. ]);
  7574. }
  7575. return $resultData;
  7576. } catch (\Exception $e) {
  7577. // 回滚事务
  7578. DB::rollback();
  7579. // 更新任务中心状态为失败
  7580. if (!empty($taskCenterId)) {
  7581. $this->taskCenterService->updateTask($taskCenterId, [
  7582. 'status' => MpTaskCenter::STATUS_FAILED,
  7583. 'error_message' => $e->getMessage()
  7584. ]);
  7585. }
  7586. // 记录错误日志
  7587. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  7588. 'script_id' => $script_id,
  7589. 'error' => $e->getMessage(),
  7590. 'trace' => $e->getTraceAsString()
  7591. ]);
  7592. // 统一使用 Utils::throwError 抛出错误
  7593. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  7594. }
  7595. }
  7596. /**
  7597. * 根据入参创建或复用任务中心记录
  7598. *
  7599. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  7600. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  7601. * 避免生成重复任务。
  7602. *
  7603. * @param int|string $uid
  7604. * @param int|string $cpid
  7605. * @param int|string $script_id
  7606. * @param mixed $products
  7607. * @param string $model
  7608. * @param string $ratio
  7609. * @param string $resolution
  7610. * @param mixed $auto_generate_images
  7611. * @return int 任务中心ID
  7612. */
  7613. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  7614. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  7615. if (is_string($products)) {
  7616. $decoded = json_decode($products, true);
  7617. if (json_last_error() === JSON_ERROR_NONE) {
  7618. $products = $decoded;
  7619. }
  7620. }
  7621. $params = [
  7622. 'script_id' => (int)$script_id,
  7623. 'products' => $products,
  7624. 'model' => $model,
  7625. 'ratio' => $ratio,
  7626. 'resolution' => $resolution,
  7627. 'auto_generate_images' => (bool)$auto_generate_images,
  7628. ];
  7629. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  7630. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  7631. $existing = DB::table('mp_task_center')
  7632. ->where('uid', (int)$uid)
  7633. ->where('cpid', (int)$cpid)
  7634. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  7635. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  7636. ->where('params_md5', $paramsMd5)
  7637. ->orderBy('id', 'desc')
  7638. ->first();
  7639. if ($existing) {
  7640. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  7641. 'script_id' => $script_id,
  7642. 'task_center_id' => $existing->id,
  7643. 'params_md5' => $paramsMd5,
  7644. ]);
  7645. return (int)$existing->id;
  7646. }
  7647. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  7648. $now = date('Y-m-d H:i:s');
  7649. DB::table('mp_task_center')->insertOrIgnore([
  7650. 'uid' => (int)$uid,
  7651. 'cpid' => (int)$cpid,
  7652. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  7653. 'title' => '剧本资产图片生成',
  7654. 'ref_task_id' => 0,
  7655. 'status' => MpTaskCenter::STATUS_PROCESSING,
  7656. 'result' => null,
  7657. 'error_message' => null,
  7658. 'prompt' => null,
  7659. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  7660. 'params_md5' => $paramsMd5,
  7661. 'created_at' => $now,
  7662. 'updated_at' => $now,
  7663. ]);
  7664. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  7665. $taskId = (int)DB::table('mp_task_center')
  7666. ->where('uid', (int)$uid)
  7667. ->where('cpid', (int)$cpid)
  7668. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  7669. ->where('params_md5', $paramsMd5)
  7670. ->orderBy('id', 'desc')
  7671. ->value('id');
  7672. dLog('anime')->info('创建任务中心记录', [
  7673. 'script_id' => $script_id,
  7674. 'task_center_id' => $taskId,
  7675. 'params_md5' => $paramsMd5,
  7676. ]);
  7677. return $taskId;
  7678. }
  7679. /**
  7680. * 任务结束时更新任务中心记录的状态和结果
  7681. *
  7682. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  7683. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  7684. *
  7685. * @param int|null $taskCenterId
  7686. * @param array $resultData 接口返回结果数组
  7687. * @param bool $timeout 是否超时未完成
  7688. */
  7689. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  7690. if (!$taskCenterId) {
  7691. return;
  7692. }
  7693. $stats = $resultData['stats'] ?? [];
  7694. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  7695. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  7696. $failedCount = $completedCount - $successCount;
  7697. // 与接口返回给客户端的结果保持一致
  7698. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  7699. if ($timeout) {
  7700. $this->taskCenterService->updateTask((int)$taskCenterId, [
  7701. 'status' => MpTaskCenter::STATUS_FAILED,
  7702. 'result' => $result,
  7703. 'error_message' => '部分任务超时,请稍后查看结果',
  7704. ]);
  7705. return;
  7706. }
  7707. $this->taskCenterService->updateTask((int)$taskCenterId, [
  7708. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  7709. 'result' => $result,
  7710. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  7711. ]);
  7712. }
  7713. /**
  7714. * 批量为剧本资产生成图片
  7715. *
  7716. * @param array $data 请求参数
  7717. * @return \Generator 返回 SSE 流
  7718. */
  7719. public function batchGenerateProductImages($data) {
  7720. $script_id = getProp($data, 'script_id');
  7721. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  7722. if (!$script_id) {
  7723. Utils::throwError('20003:请提供剧本ID');
  7724. }
  7725. // 验证剧本是否存在
  7726. $script = DB::table('mp_scripts')
  7727. ->where('id', $script_id)
  7728. ->where('is_deleted', 0)
  7729. ->first();
  7730. if (!$script) {
  7731. Utils::throwError('20003:剧本不存在');
  7732. }
  7733. $script_name = $script->script_name ?? 'script_' . $script_id;
  7734. // 获取需要生成图片的所有资产
  7735. $products = DB::table('mp_products')
  7736. ->whereIn('parent_id', array_values($type_folder_ids))
  7737. ->where('is_deleted', 0)
  7738. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7739. ->get();
  7740. if ($products->isEmpty()) {
  7741. Utils::throwError('20003:没有找到需要生成图片的资产');
  7742. }
  7743. // 默认参数
  7744. $model = 'doubao-seedream-5-0-lite-260128';
  7745. $width = 1600;
  7746. $height = 2848;
  7747. // 开始为每个资产创建图片生成任务
  7748. $taskIds = [];
  7749. $productTaskMap = []; // 资产ID到任务ID的映射
  7750. foreach ($products as $product) {
  7751. if (empty($product->pic_prompt)) {
  7752. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7753. continue;
  7754. }
  7755. try {
  7756. // 创建图片生成任务
  7757. $params = [
  7758. 'prompt' => $product->pic_prompt,
  7759. 'model' => $model,
  7760. 'ref_img_urls' => [],
  7761. 'width' => $width,
  7762. 'height' => $height
  7763. ];
  7764. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7765. $task_id = $task->id;
  7766. if ($task_id) {
  7767. $taskIds[] = $task_id;
  7768. $productTaskMap[$product->id] = $task_id;
  7769. // 更新资产表的任务ID和状态
  7770. DB::table('mp_products')
  7771. ->where('id', $product->id)
  7772. ->update([
  7773. 'pic_task_id' => $task_id,
  7774. 'pic_task_status' => '生成中',
  7775. 'updated_at' => now()
  7776. ]);
  7777. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7778. }
  7779. } catch (\Exception $e) {
  7780. dLog('anime')->error('创建资产图片生成任务失败', [
  7781. 'product_id' => $product->id,
  7782. 'error' => $e->getMessage()
  7783. ]);
  7784. // 标记为失败
  7785. DB::table('mp_products')
  7786. ->where('id', $product->id)
  7787. ->update([
  7788. 'pic_task_status' => '生成失败',
  7789. 'updated_at' => now()
  7790. ]);
  7791. }
  7792. }
  7793. if (empty($taskIds)) {
  7794. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7795. }
  7796. // 返回 SSE 流
  7797. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7798. }
  7799. /**
  7800. * 轮询资产图片生成任务状态(SSE流式返回)
  7801. * 只通过查询数据库获取任务状态,不主动调用API
  7802. *
  7803. * @param int $script_id 剧本ID
  7804. * @param string $script_name 剧本名称
  7805. * @param array $productTaskMap 资产ID到任务ID的映射
  7806. * @param array $type_folder_ids 类型文件夹ID映射
  7807. * @return \Generator
  7808. */
  7809. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null) {
  7810. $startTime = time();
  7811. $timeout = 1800; // 30分钟超时
  7812. $pollInterval = 10; // 10秒轮询一次
  7813. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7814. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  7815. if ($taskCenterId) {
  7816. $initResponse = [
  7817. 'type' => 'init',
  7818. 'script_id' => $script_id,
  7819. 'script_name' => $script_name,
  7820. 'timestamp' => date('Y-m-d H:i:s'),
  7821. 'task_center_id' => (int)$taskCenterId,
  7822. ];
  7823. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  7824. }
  7825. // 定义类型名称映射
  7826. $typeNames = [
  7827. 1 => 'roles', // 角色
  7828. 2 => 'scenes', // 场景
  7829. 3 => 'props' // 道具
  7830. ];
  7831. while (time() - $startTime < $timeout) {
  7832. sleep($pollInterval);
  7833. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7834. $mappings = DB::table('mp_script_product_mappings')
  7835. ->where('script_id', $script_id)
  7836. ->pluck('product_id')
  7837. ->unique()
  7838. ->toArray();
  7839. if (empty($mappings)) {
  7840. dLog('anime')->warning('该剧本没有关联的资产', [
  7841. 'script_id' => $script_id,
  7842. 'script_name' => $script_name
  7843. ]);
  7844. break;
  7845. }
  7846. // 查询所有资产的当前状态
  7847. $products = DB::table('mp_products')
  7848. ->whereIn('id', $mappings)
  7849. ->where('is_deleted', 0)
  7850. ->get();
  7851. // 统计各类型的状态(使用类型名称作为键名)
  7852. $stats = [
  7853. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7854. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7855. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7856. ];
  7857. $allCompleted = true;
  7858. $hasStatusChange = false;
  7859. foreach ($products as $product) {
  7860. $type = $product->product;
  7861. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7862. // 如果类型名称不在 stats 中,初始化
  7863. if (!isset($stats[$typeName])) {
  7864. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7865. }
  7866. $stats[$typeName]['total']++;
  7867. $task_id = $product->pic_task_id;
  7868. $currentStatus = $product->pic_task_status;
  7869. // 检查状态是否有变化
  7870. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7871. $hasStatusChange = true;
  7872. $lastStatus[$product->id] = $currentStatus;
  7873. }
  7874. // 如果是生成中,查询任务表状态
  7875. if ($currentStatus === '生成中' && $task_id) {
  7876. // 只查询数据库,不调用API
  7877. $task = DB::table('mp_generate_pic_tasks')
  7878. ->where('id', $task_id)
  7879. ->first();
  7880. if ($task) {
  7881. // 检查任务状态
  7882. if ($task->status === 'success' && $task->result_url) {
  7883. // 解析图片URL
  7884. $result_urls = $task->result_url;
  7885. if (is_string($result_urls)) {
  7886. $result_urls = json_decode($result_urls, true);
  7887. }
  7888. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7889. // 更新资产表状态
  7890. DB::table('mp_products')
  7891. ->where('id', $product->id)
  7892. ->update([
  7893. 'pic_task_status' => '生成成功',
  7894. 'url' => $img_url,
  7895. 'updated_at' => now()
  7896. ]);
  7897. $stats[$typeName]['success']++;
  7898. $stats[$typeName]['completed']++;
  7899. $hasStatusChange = true;
  7900. dLog('anime')->info('资产图片生成成功', [
  7901. 'product_id' => $product->id,
  7902. 'task_id' => $task_id,
  7903. 'img_url' => $img_url
  7904. ]);
  7905. } elseif ($task->status === 'failed') {
  7906. // 更新资产表状态
  7907. DB::table('mp_products')
  7908. ->where('id', $product->id)
  7909. ->update([
  7910. 'pic_task_status' => '生成失败',
  7911. 'updated_at' => now()
  7912. ]);
  7913. $stats[$typeName]['completed']++;
  7914. $hasStatusChange = true;
  7915. dLog('anime')->warning('资产图片生成失败', [
  7916. 'product_id' => $product->id,
  7917. 'task_id' => $task_id,
  7918. 'error' => $task->error_message ?? '未知错误'
  7919. ]);
  7920. } else {
  7921. // 任务还在处理中
  7922. $allCompleted = false;
  7923. }
  7924. } else {
  7925. // 任务不存在,标记为失败
  7926. DB::table('mp_products')
  7927. ->where('id', $product->id)
  7928. ->update([
  7929. 'pic_task_status' => '生成失败',
  7930. 'updated_at' => now()
  7931. ]);
  7932. $stats[$type]['completed']++;
  7933. $hasStatusChange = true;
  7934. dLog('anime')->error('图片生成任务不存在', [
  7935. 'product_id' => $product->id,
  7936. 'task_id' => $task_id
  7937. ]);
  7938. }
  7939. } elseif ($currentStatus === '生成成功') {
  7940. $stats[$typeName]['success']++;
  7941. $stats[$typeName]['completed']++;
  7942. } elseif ($currentStatus === '生成失败') {
  7943. $stats[$typeName]['completed']++;
  7944. } else {
  7945. // 其他状态也认为未完成
  7946. $allCompleted = false;
  7947. }
  7948. }
  7949. // 移除没有数据的类型(total=0)
  7950. foreach ($stats as $typeName => $stat) {
  7951. if ($stat['total'] === 0) {
  7952. unset($stats[$typeName]);
  7953. }
  7954. }
  7955. // 如果有状态变化,发送 SSE 更新
  7956. if ($hasStatusChange) {
  7957. $eventType = $allCompleted ? 'complete' : 'update';
  7958. $response = [
  7959. 'type' => $eventType,
  7960. 'script_id' => $script_id,
  7961. 'script_name' => $script_name,
  7962. 'stats' => $stats,
  7963. 'timestamp' => date('Y-m-d H:i:s')
  7964. ];
  7965. if ($taskCenterId) {
  7966. $response['task_center_id'] = $taskCenterId;
  7967. }
  7968. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7969. dLog('anime')->info('SSE更新', [
  7970. 'event_type' => $eventType,
  7971. 'script_id' => $script_id,
  7972. 'script_name' => $script_name,
  7973. 'stats' => $stats
  7974. ]);
  7975. if ($allCompleted) {
  7976. dLog('anime')->info('所有资产图片生成任务已完成', [
  7977. 'script_id' => $script_id,
  7978. 'script_name' => $script_name,
  7979. 'stats' => $stats
  7980. ]);
  7981. // 全部任务完成,更新任务中心状态和结果
  7982. $this->finishScriptProductTask($taskCenterId, $response);
  7983. break;
  7984. }
  7985. }
  7986. }
  7987. // 超时处理
  7988. if (time() - $startTime >= $timeout && !$allCompleted) {
  7989. $response = [
  7990. 'type' => 'timeout',
  7991. 'message' => '部分任务超时,请稍后查看结果',
  7992. 'script_id' => $script_id,
  7993. 'script_name' => $script_name,
  7994. 'timestamp' => date('Y-m-d H:i:s')
  7995. ];
  7996. if ($taskCenterId) {
  7997. $response['task_center_id'] = $taskCenterId;
  7998. }
  7999. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  8000. dLog('anime')->warning('资产图片生成任务超时', [
  8001. 'script_id' => $script_id,
  8002. 'script_name' => $script_name,
  8003. 'timeout' => $timeout
  8004. ]);
  8005. // 超时未完成,更新任务中心状态和结果
  8006. $this->finishScriptProductTask($taskCenterId, $response, true);
  8007. }
  8008. }
  8009. /**
  8010. * 定时任务:检查产品图片生成任务状态并更新产品记录
  8011. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  8012. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  8013. *
  8014. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  8015. */
  8016. public function checkProductPicTasks() {
  8017. // 查询所有生成中的产品图片任务
  8018. $products = DB::table('mp_products')
  8019. ->whereNotNull('pic_task_id')
  8020. ->where('pic_task_status', '生成中')
  8021. ->where('is_deleted', 0)
  8022. ->get();
  8023. $stats = [
  8024. 'total' => $products->count(),
  8025. 'success' => 0,
  8026. 'failed' => 0,
  8027. 'pending' => 0,
  8028. ];
  8029. foreach ($products as $product) {
  8030. try {
  8031. $task_id = $product->pic_task_id;
  8032. // 通过 pic_task_id 查询图片生成任务结果
  8033. $task = DB::table('mp_generate_pic_tasks')
  8034. ->where('id', $task_id)
  8035. ->first();
  8036. if ($task) {
  8037. if ($task->status === 'success' && $task->result_url) {
  8038. // 解析图片URL
  8039. $result_urls = $task->result_url;
  8040. if (is_string($result_urls)) {
  8041. $result_urls = json_decode($result_urls, true);
  8042. }
  8043. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  8044. // 更新资产表状态
  8045. DB::table('mp_products')
  8046. ->where('id', $product->id)
  8047. ->update([
  8048. 'pic_task_status' => '生成成功',
  8049. 'url' => $img_url,
  8050. 'updated_at' => now()
  8051. ]);
  8052. $stats['success']++;
  8053. dLog('anime')->info('资产图片生成成功', [
  8054. 'product_id' => $product->id,
  8055. 'task_id' => $task_id,
  8056. 'img_url' => $img_url
  8057. ]);
  8058. } elseif ($task->status === 'failed') {
  8059. // 更新资产表状态
  8060. DB::table('mp_products')
  8061. ->where('id', $product->id)
  8062. ->update([
  8063. 'pic_task_status' => '生成失败',
  8064. 'updated_at' => now()
  8065. ]);
  8066. $stats['failed']++;
  8067. dLog('anime')->warning('资产图片生成失败', [
  8068. 'product_id' => $product->id,
  8069. 'task_id' => $task_id,
  8070. 'error' => $task->error_message ?? '未知错误'
  8071. ]);
  8072. } else {
  8073. // 任务还在处理中
  8074. $stats['pending']++;
  8075. }
  8076. } else {
  8077. // 任务不存在,标记为失败
  8078. DB::table('mp_products')
  8079. ->where('id', $product->id)
  8080. ->update([
  8081. 'pic_task_status' => '生成失败',
  8082. 'updated_at' => now()
  8083. ]);
  8084. $stats['failed']++;
  8085. dLog('anime')->error('图片生成任务不存在', [
  8086. 'product_id' => $product->id,
  8087. 'task_id' => $task_id
  8088. ]);
  8089. }
  8090. } catch (\Exception $e) {
  8091. dLog('anime')->error('检查产品图片生成任务异常', [
  8092. 'product_id' => $product->id,
  8093. 'task_id' => $product->pic_task_id ?? null,
  8094. 'error' => $e->getMessage()
  8095. ]);
  8096. }
  8097. }
  8098. return $stats;
  8099. }
  8100. /**
  8101. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  8102. *
  8103. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  8104. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  8105. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  8106. *
  8107. * @return int 更新的任务中心记录数
  8108. */
  8109. public function checkSaveScriptProductTaskCenters() {
  8110. $updated = 0;
  8111. // 只扫描尚未结束的 saveScriptProducts 任务
  8112. $tasks = DB::table('mp_task_center')
  8113. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8114. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  8115. ->orderBy('id', 'desc')
  8116. ->limit(500)
  8117. ->get();
  8118. // 与 pollProductImageTasks 保持一致的类型名称映射
  8119. $typeNames = [
  8120. 1 => 'roles', // 角色
  8121. 2 => 'scenes', // 场景
  8122. 3 => 'props', // 道具
  8123. ];
  8124. foreach ($tasks as $task) {
  8125. try {
  8126. $taskParams = json_decode((string)$task->params, true);
  8127. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  8128. if (!$script_id) {
  8129. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  8130. 'task_center_id' => $task->id,
  8131. ]);
  8132. continue;
  8133. }
  8134. // 获取该剧本关联的全部资产ID
  8135. $productIds = DB::table('mp_script_product_mappings')
  8136. ->where('script_id', $script_id)
  8137. ->pluck('product_id')
  8138. ->unique()
  8139. ->toArray();
  8140. if (empty($productIds)) {
  8141. // 剧本没有关联资产,不视为完成,等待下一次检查
  8142. continue;
  8143. }
  8144. $products = DB::table('mp_products')
  8145. ->whereIn('id', $productIds)
  8146. ->where('is_deleted', 0)
  8147. ->get();
  8148. $stats = [];
  8149. $allCompleted = true;
  8150. foreach ($products as $product) {
  8151. $typeName = $typeNames[$product->product] ?? 'unknown';
  8152. if (!isset($stats[$typeName])) {
  8153. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  8154. }
  8155. $stats[$typeName]['total']++;
  8156. if ($product->pic_task_status === '生成成功') {
  8157. $stats[$typeName]['success']++;
  8158. $stats[$typeName]['completed']++;
  8159. } elseif ($product->pic_task_status === '生成失败') {
  8160. $stats[$typeName]['completed']++;
  8161. } else {
  8162. // 仍有资产在生成中或未生成,任务未完成
  8163. $allCompleted = false;
  8164. }
  8165. }
  8166. if (!$allCompleted) {
  8167. continue;
  8168. }
  8169. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  8170. $script = DB::table('mp_scripts')
  8171. ->where('id', $script_id)
  8172. ->where('is_deleted', 0)
  8173. ->first();
  8174. $script_name = $script->script_name ?? 'script_' . $script_id;
  8175. $this->finishScriptProductTask($task->id, [
  8176. 'type' => 'complete',
  8177. 'script_id' => $script_id,
  8178. 'script_name' => $script_name,
  8179. 'stats' => $stats,
  8180. 'timestamp' => date('Y-m-d H:i:s'),
  8181. 'task_center_id' => (int)$task->id,
  8182. ]);
  8183. $updated++;
  8184. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  8185. 'task_center_id' => $task->id,
  8186. 'script_id' => $script_id,
  8187. 'stats' => $stats,
  8188. ]);
  8189. } catch (\Exception $e) {
  8190. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  8191. 'task_center_id' => $task->id,
  8192. 'error' => $e->getMessage(),
  8193. ]);
  8194. }
  8195. }
  8196. return $updated;
  8197. }
  8198. /**
  8199. * 获取剧本关联的资产列表
  8200. * @param array $data 请求参数
  8201. * @return array
  8202. */
  8203. public function getScriptProducts($data) {
  8204. $uid = Site::getUid();
  8205. $cpid = Site::getCpid();
  8206. $script_id = getProp($data, 'script_id');
  8207. $episode_number = getProp($data, 'episode_number');
  8208. if (!$script_id) {
  8209. Utils::throwError('20003:请提供剧本ID');
  8210. }
  8211. // 验证剧本是否存在
  8212. $script = DB::table('mp_scripts')
  8213. ->where('id', $script_id)
  8214. ->where('is_deleted', 0)
  8215. ->first();
  8216. if (!$script) {
  8217. Utils::throwError('20003:剧本不存在');
  8218. }
  8219. // 联表查询资产信息
  8220. $query = DB::table('mp_script_product_mappings as mapping')
  8221. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8222. ->where('mapping.script_id', $script_id)
  8223. ->where('product.cpid', $cpid)
  8224. ->where('product.is_deleted', 0);
  8225. // 如果提供了 episode_number,则过滤指定集数
  8226. if ($episode_number !== null && $episode_number !== '') {
  8227. $query->where('mapping.episode_number', $episode_number);
  8228. }
  8229. $mappings = $query->select(
  8230. 'mapping.script_id',
  8231. 'mapping.product_id',
  8232. 'mapping.episode_number',
  8233. 'product.product_name',
  8234. 'product.type',
  8235. 'product.product',
  8236. 'product.pic_prompt',
  8237. 'product.url',
  8238. 'product.pic_task_id',
  8239. 'product.pic_task_status',
  8240. 'product.three_view_image_url',
  8241. 'mapping.created_at'
  8242. )
  8243. ->orderBy('mapping.product_id', 'asc')
  8244. ->orderBy('mapping.episode_number', 'asc')
  8245. ->get();
  8246. // 按 product_id 分组,合并 episode_number
  8247. $productMap = [];
  8248. foreach ($mappings as $item) {
  8249. $product_id = $item->product_id;
  8250. if (!isset($productMap[$product_id])) {
  8251. $productMap[$product_id] = [
  8252. 'product_id' => $product_id,
  8253. 'product_name' => $item->product_name,
  8254. 'type' => (int)$item->type,
  8255. 'product' => (int)$item->product,
  8256. 'pic_prompt' => $item->pic_prompt,
  8257. 'url' => $item->url,
  8258. 'pic_task_id' => $item->pic_task_id,
  8259. 'pic_task_status' => $item->pic_task_status,
  8260. 'episode_numbers' => [],
  8261. 'created_at' => $item->created_at,
  8262. ];
  8263. }
  8264. // 添加 episode_number(去重)
  8265. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8266. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8267. }
  8268. }
  8269. // 按类型分组
  8270. $roles = []; // type=1 角色/主体
  8271. $scenes = []; // type=2 场景
  8272. $props = []; // type=3 道具
  8273. foreach ($productMap as $product) {
  8274. // 将 episode_numbers 数组转换为逗号分隔的字符串
  8275. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  8276. // 构造返回数据
  8277. $productData = [
  8278. 'product_id' => $product['product_id'],
  8279. 'product_name' => $product['product_name'],
  8280. 'product' => $product['product'],
  8281. 'pic_prompt' => $product['pic_prompt'],
  8282. 'url' => $product['url'],
  8283. 'pic_task_id' => $product['pic_task_id'],
  8284. 'pic_task_status' => $product['pic_task_status'],
  8285. 'episode_numbers' => $episodeNumbersStr,
  8286. 'created_at' => $product['created_at'],
  8287. ];
  8288. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  8289. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  8290. switch ($product['product']) {
  8291. case 1:
  8292. $roles[] = $productData;
  8293. break;
  8294. case 2:
  8295. $scenes[] = $productData;
  8296. break;
  8297. case 3:
  8298. $props[] = $productData;
  8299. break;
  8300. }
  8301. }
  8302. return [
  8303. 'script_id' => $script_id,
  8304. 'script_name' => $script->script_name ?? '',
  8305. 'roles' => $roles, // 主体
  8306. 'scenes' => $scenes, // 场景
  8307. 'props' => $props, // 道具
  8308. ];
  8309. }
  8310. /**
  8311. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  8312. * @param string $actContent 原始内容
  8313. * @param array $products 产品数组(包含product_name和url)
  8314. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  8315. */
  8316. public function processActContentWithProducts($actContent, $products) {
  8317. if (empty($actContent) || empty($products)) {
  8318. return [
  8319. 'content' => $actContent,
  8320. 'reference_images' => []
  8321. ];
  8322. }
  8323. // 构建产品名称到产品信息的映射
  8324. $product_dict = [];
  8325. foreach ($products as $product) {
  8326. $product_name = getProp($product, 'product_name');
  8327. if ($product_name) {
  8328. $product_dict[$product_name] = [
  8329. 'url' => getProp($product, 'url'),
  8330. 'voice_prompt' => getProp($product, 'voice_prompt')
  8331. ];
  8332. }
  8333. }
  8334. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  8335. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  8336. $reference_images = [];
  8337. $product_index_map = []; // 产品名称 => 图片序号的映射
  8338. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  8339. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  8340. $current_index = 1;
  8341. if (!empty($matches[1])) {
  8342. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  8343. $seen_products = []; // 用于去重
  8344. foreach ($matches[1] as $product_name) {
  8345. // 跳过已处理的产品
  8346. if (isset($seen_products[$product_name])) {
  8347. continue;
  8348. }
  8349. $seen_products[$product_name] = true;
  8350. // 检查产品是否在字典中
  8351. if (isset($product_dict[$product_name])) {
  8352. $url = $product_dict[$product_name]['url'];
  8353. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  8354. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  8355. if (!empty($voice_prompt) && $product_name !== '旁白') {
  8356. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  8357. }
  8358. // 只有URL非空才分配序号和添加到参考图片
  8359. if (!empty($url)) {
  8360. // 检查URL是否已经在reference_images中(去重)
  8361. if (!in_array($url, $reference_images)) {
  8362. $reference_images[] = $url;
  8363. $product_index_map[$product_name] = $current_index;
  8364. $current_index++;
  8365. } else {
  8366. // URL重复,找到已有的序号
  8367. $existing_index = array_search($url, $reference_images) + 1;
  8368. $product_index_map[$product_name] = $existing_index;
  8369. }
  8370. } else {
  8371. // URL为空,不分配序号(后续直接去掉{})
  8372. $product_index_map[$product_name] = 0;
  8373. }
  8374. } else {
  8375. // 产品不在字典中,不分配序号
  8376. $product_index_map[$product_name] = 0;
  8377. }
  8378. }
  8379. }
  8380. // 第二步:替换内容中的 {产品名称}
  8381. $processedContent = $actContent;
  8382. foreach ($product_index_map as $product_name => $index) {
  8383. $escaped_name = preg_quote($product_name, '/');
  8384. if ($index > 0) {
  8385. // 有图片,替换为:产品名称(图X)
  8386. $replacement = $product_name . '<图片' . $index . '>';
  8387. } else {
  8388. // 无图片,只保留产品名称
  8389. $replacement = $product_name;
  8390. }
  8391. // 替换所有 {产品名称} 为处理后的格式
  8392. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  8393. }
  8394. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  8395. foreach ($products as $product) {
  8396. $product_name = getProp($product, 'product_name');
  8397. $voice_prompt = getProp($product, 'voice_prompt');
  8398. if ($product_name === '旁白' && !empty($voice_prompt)) {
  8399. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  8400. break; // 找到旁白后退出循环
  8401. }
  8402. }
  8403. // 第四步:将voice_prompt信息添加到内容最前面
  8404. $voice_prompt_prefix = '';
  8405. if (!empty($voice_prompts)) {
  8406. $voice_prompt_prefix .= implode('', $voice_prompts);
  8407. }
  8408. // 旁白的voice_prompt放在最后
  8409. if (!empty($narrator_voice_prompt)) {
  8410. $voice_prompt_prefix .= $narrator_voice_prompt;
  8411. }
  8412. // 如果有voice_prompt信息,添加到内容开头
  8413. if (!empty($voice_prompt_prefix)) {
  8414. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  8415. }
  8416. return [
  8417. 'content' => $processedContent,
  8418. 'reference_images' => $reference_images
  8419. ];
  8420. }
  8421. public function saveActVideoGenerateParams($data) {
  8422. $episode_id = getProp($data, 'episode_id');
  8423. $model = getProp($data, 'video_model');
  8424. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  8425. Utils::throwError('20003:该模型不可用');
  8426. }
  8427. if (!$model) {
  8428. // 使用默认模型
  8429. $model = 'zhizhen-20';
  8430. }
  8431. // 验证模型是否在可用模型表中
  8432. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8433. Utils::throwError('20003:该模型已不可用,请更换!');
  8434. }
  8435. $video_resolution = getProp($data, 'video_resolution', '720p');
  8436. $ratio = getProp($data, 'ratio');
  8437. if (!$ratio) $ratio = '9:16';
  8438. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  8439. if (!$episode) {
  8440. Utils::throwError('20003:分集不存在');
  8441. }
  8442. try {
  8443. DB::beginTransaction();
  8444. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8445. 'video_model' => $model,
  8446. 'video_resolution' => $video_resolution,
  8447. 'ratio' => $ratio,
  8448. 'updated_at' => date('Y-m-d H:i:s')
  8449. ]);
  8450. if ($result === false) {
  8451. Utils::throwError('20003:分集视频参数保存失败');
  8452. }
  8453. // 同步更新mp_animes表
  8454. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  8455. 'video_model' => $model,
  8456. 'video_resolution' => $video_resolution,
  8457. 'video_ratio' => $ratio,
  8458. 'updated_at' => date('Y-m-d H:i:s')
  8459. ]);
  8460. if ($anime_result === false) {
  8461. Utils::throwError('20003:动漫视频参数保存失败');
  8462. }
  8463. } catch (\Exception $e) {
  8464. DB::rollBack();
  8465. Utils::throwError('20003:'.$e->getMessage());
  8466. }
  8467. DB::commit();
  8468. return $result;
  8469. }
  8470. public function confirmActs($data) {
  8471. $episode_id = getProp($data, 'episode_id');
  8472. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  8473. if (!$episode) {
  8474. Utils::throwError('20003:分集不存在');
  8475. }
  8476. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  8477. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  8478. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  8479. // 获取所有片段数据
  8480. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8481. // 收集所有资产名称(角色、场景、道具)
  8482. $product_names = [];
  8483. // 收集角色名称
  8484. foreach ($roles as $role) {
  8485. $role_name = getProp($role, 'role');
  8486. if ($role_name && $role_name != '旁白') {
  8487. $product_names[] = $role_name;
  8488. }
  8489. }
  8490. // 收集场景名称
  8491. foreach ($scenes as $scene) {
  8492. $scene_name = getProp($scene, 'scene');
  8493. if ($scene_name) {
  8494. $product_names[] = $scene_name;
  8495. }
  8496. }
  8497. // 收集道具名称
  8498. foreach ($props as $prop) {
  8499. $prop_name = getProp($prop, 'prop');
  8500. if ($prop_name) {
  8501. $product_names[] = $prop_name;
  8502. }
  8503. }
  8504. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8505. $product_names = array_unique($product_names);
  8506. usort($product_names, function($a, $b) {
  8507. return mb_strlen($b) - mb_strlen($a);
  8508. });
  8509. try {
  8510. DB::beginTransaction();
  8511. // 处理每个片段
  8512. foreach ($acts as $act) {
  8513. $act_content = getProp($act, 'act_content');
  8514. if (!$act_content) continue;
  8515. $processed_content = $act_content;
  8516. // 统一替换所有资产名称为 {资产名} 格式
  8517. // 使用占位符避免嵌套替换问题
  8518. $placeholder_map = [];
  8519. $placeholder_index = 0;
  8520. foreach ($product_names as $product_name) {
  8521. // 转义特殊字符
  8522. $escaped_product = preg_quote($product_name, '/');
  8523. // 检查是否匹配且未被 {} 包裹
  8524. $processed_content = preg_replace_callback(
  8525. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8526. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8527. // 使用唯一占位符
  8528. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8529. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8530. $placeholder_index++;
  8531. return $placeholder;
  8532. },
  8533. $processed_content
  8534. );
  8535. }
  8536. // 将所有占位符替换回实际内容
  8537. foreach ($placeholder_map as $placeholder => $replacement) {
  8538. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8539. }
  8540. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8541. $shot_counter = 0;
  8542. $processed_content = preg_replace_callback(
  8543. '/【(?:镜头|分镜)(\d+)】/u',
  8544. function($matches) use (&$shot_counter) {
  8545. $shot_counter++;
  8546. return '【镜头' . $shot_counter . '】';
  8547. },
  8548. $processed_content
  8549. );
  8550. // 更新数据库
  8551. $boolen = DB::table('mp_episode_segments')
  8552. ->where('id', $act->id)
  8553. ->update([
  8554. 'act_show_content' => $processed_content,
  8555. 'updated_at' => date('Y-m-d H:i:s')
  8556. ]);
  8557. if (!$boolen) {
  8558. Utils::throwError('20003:片段处理失败');
  8559. }
  8560. }
  8561. }catch (\Exception $e) {
  8562. DB::rollBack();
  8563. Utils::throwError('20003:'.$e->getMessage());
  8564. }
  8565. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8566. 'is_generated' => 1,
  8567. 'updated_at' => date('Y-m-d H:i:s')
  8568. ]);
  8569. if (!$boolen1) {
  8570. DB::rollBack();
  8571. Utils::throwError('20003:分集处理失败!');
  8572. }
  8573. DB::commit();
  8574. // 重新查询更新后的片段数据
  8575. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8576. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  8577. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  8578. $products = [];
  8579. // 先处理角色数组
  8580. foreach ($roles as $role) {
  8581. $product = $role;
  8582. // 将role字段重命名为product_name
  8583. if (isset($product['role'])) {
  8584. $product['product_name'] = $product['role'];
  8585. unset($product['role']);
  8586. $product['product'] = 1; // 标记类型为角色
  8587. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8588. }
  8589. }
  8590. // 处理场景数组
  8591. foreach ($scenes as $scene) {
  8592. $product = $scene;
  8593. // 将scene字段重命名为product_name
  8594. if (isset($product['scene'])) {
  8595. $product['product_name'] = $product['scene'];
  8596. unset($product['scene']);
  8597. $product['product'] = 2; // 标记类型为场景
  8598. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8599. }
  8600. }
  8601. // 处理道具数组(逻辑与场景一致)
  8602. foreach ($props as $prop) {
  8603. $product = $prop;
  8604. // 将prop字段重命名为product_name
  8605. if (isset($product['prop'])) {
  8606. $product['product_name'] = $product['prop'];
  8607. unset($product['prop']);
  8608. $product['product'] = 3; // 标记类型为道具
  8609. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8610. }
  8611. }
  8612. // extra_products优先级更高,直接覆盖同名的roles和scenes
  8613. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  8614. foreach ($extra_products as $extra_product) {
  8615. $product_name = getProp($extra_product, 'product_name');
  8616. if ($product_name) {
  8617. $products[$product_name] = $extra_product; // 覆盖同名数据
  8618. }
  8619. }
  8620. // 重新索引数组(去除key)
  8621. $products = array_values($products);
  8622. // 构建返回的acts数组
  8623. $return_acts = [];
  8624. foreach ($acts as $act) {
  8625. $return_acts[] = [
  8626. 'act_id' => getProp($act, 'id'),
  8627. 'act_number' => getProp($act, 'act_number'),
  8628. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  8629. 'act_show_content' => getProp($act, 'act_show_content'),
  8630. 'video_url' => getProp($act, 'video_url'),
  8631. 'video_duration' => getProp($act, 'video_duration'),
  8632. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  8633. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  8634. ];
  8635. }
  8636. return [
  8637. 'anime_id' => getProp($episode, 'anime_id'),
  8638. 'episode_id' => $episode_id,
  8639. 'title' => getProp($episode, 'title'),
  8640. 'episode_number' => getProp($episode, 'episode_number'),
  8641. 'is_generated' => getProp($episode, 'is_generated'),
  8642. 'video_params' => [
  8643. 'video_model' => getProp($episode, 'video_model'),
  8644. 'video_resolution' => getProp($episode, 'video_resolution'),
  8645. 'ratio' => getProp($episode, 'ratio'),
  8646. ],
  8647. 'products' => $products,
  8648. 'acts' => $return_acts
  8649. ];
  8650. }
  8651. /**
  8652. * 导出动漫剧本为PDF(参照示例PDF版式)
  8653. * @param int $animeId 动漫ID
  8654. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  8655. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  8656. * @return string|null
  8657. */
  8658. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  8659. // 图片下载与转换可能占用较多内存
  8660. ini_set('memory_limit', '512M');
  8661. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  8662. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  8663. $anime = (array)$anime;
  8664. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  8665. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  8666. // 获取分集(默认展示版本,按集数升序)
  8667. $episodeQuery = DB::table('mp_anime_episodes')
  8668. ->where('anime_id', $animeId)
  8669. ->where('is_default', 1)
  8670. ->orderBy('episode_number')
  8671. ->orderBy('id');
  8672. if ($episodeCount > 0) {
  8673. $episodeQuery->limit($episodeCount);
  8674. }
  8675. $episodes = $episodeQuery->get()->map(function ($value) {
  8676. return (array)$value;
  8677. })->toArray();
  8678. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  8679. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  8680. $roles = $this->mergeEpisodeItems($episodes, 'role');
  8681. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  8682. $props = $this->mergeEpisodeItems($episodes, 'prop');
  8683. // 组装分集剧本数据
  8684. $episodeScripts = [];
  8685. foreach ($episodes as $episode) {
  8686. $segments = DB::table('mp_episode_segments')
  8687. ->where('anime_id', $animeId)
  8688. ->where('episode_id', $episode['id'])
  8689. ->get();
  8690. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  8691. $acts = [];
  8692. foreach ($segments as $segment) {
  8693. $segment = (array)$segment;
  8694. $actNumber = (int)getProp($segment, 'act_number', 0);
  8695. if ($actNumber <= 0) continue;
  8696. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  8697. $acts[$actNumber] = [
  8698. 'id' => (int)$segment['id'],
  8699. 'act_number' => $actNumber,
  8700. 'duration' => getProp($segment, 'act_duration', ''),
  8701. 'content' => getProp($segment, 'act_content', ''),
  8702. ];
  8703. }
  8704. }
  8705. ksort($acts);
  8706. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  8707. $segmentCounter = 0;
  8708. foreach ($acts as &$act) {
  8709. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  8710. }
  8711. unset($act);
  8712. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  8713. $narratorVoice = '';
  8714. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  8715. foreach ($episodeRoles as $role) {
  8716. if (getProp($role, 'role') === '旁白') {
  8717. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  8718. break;
  8719. }
  8720. }
  8721. if ($narratorVoice === '') {
  8722. foreach ($acts as $act) {
  8723. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  8724. $narratorVoice = trim($match[1]);
  8725. break;
  8726. }
  8727. }
  8728. }
  8729. $episodeScripts[] = [
  8730. 'episode_number' => getProp($episode, 'episode_number'),
  8731. 'title' => getProp($episode, 'title', ''),
  8732. 'act_count' => count($acts),
  8733. 'narrator_voice' => $narratorVoice,
  8734. 'acts' => array_values($acts),
  8735. ];
  8736. }
  8737. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  8738. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  8739. // 构建PDF
  8740. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  8741. // 图片已嵌入PDF,清理临时文件
  8742. foreach ($imageCache as $imgFile) {
  8743. @unlink($imgFile);
  8744. }
  8745. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  8746. if ($savePath) {
  8747. $pdf->Output($savePath, 'F');
  8748. return $savePath;
  8749. }
  8750. // 直接下载输出
  8751. header('Content-Type: application/pdf');
  8752. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  8753. $pdf->Output($filename . '.pdf', 'D');
  8754. exit();
  8755. }
  8756. /**
  8757. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  8758. * @param array $episodes 分集数据
  8759. * @param string $nameKey role|scene|prop
  8760. * @return array
  8761. */
  8762. private function mergeEpisodeItems(array $episodes, $nameKey) {
  8763. $fieldMap = [
  8764. 'role' => 'roles',
  8765. 'scene' => 'scenes',
  8766. 'prop' => 'props',
  8767. ];
  8768. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  8769. $items = [];
  8770. foreach ($episodes as $episode) {
  8771. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  8772. foreach ($list as $item) {
  8773. if (!is_array($item)) continue;
  8774. $name = trim((string)getProp($item, $nameKey, ''));
  8775. if ($name === '') continue;
  8776. // 旁白不进入主体列表(仅作为旁白音色来源)
  8777. if ($nameKey === 'role' && $name === '旁白') continue;
  8778. if (!isset($items[$name])) {
  8779. $items[$name] = $item;
  8780. }
  8781. }
  8782. }
  8783. return array_values($items);
  8784. }
  8785. /**
  8786. * 构建动漫剧本PDF
  8787. * @param array $anime 动漫信息
  8788. * @param array $roles 主体列表
  8789. * @param array $scenes 场景列表
  8790. * @param array $props 道具列表
  8791. * @param array $episodeScripts 分集剧本数据
  8792. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8793. * @return \TCPDF
  8794. */
  8795. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  8796. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  8797. $pdf->SetCreator('动漫剧本导出系统');
  8798. $pdf->SetAuthor('系统');
  8799. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  8800. $pdf->SetSubject('动漫剧本导出');
  8801. $pdf->SetMargins(15, 15, 15);
  8802. $pdf->SetAutoPageBreak(true, 15);
  8803. // 剧本名
  8804. $pdf->AddPage();
  8805. $pdf->SetFont('simsun', 'B', 20);
  8806. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  8807. $pdf->Ln(5);
  8808. // 故事梗概
  8809. $intro = trim((string)getProp($anime, 'intro', ''));
  8810. if ($intro !== '') {
  8811. $this->pdfSectionTitle($pdf, '故事梗概');
  8812. $this->pdfBody($pdf, $intro);
  8813. }
  8814. // 美术风格
  8815. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  8816. if ($artStyle !== '') {
  8817. $this->pdfSectionTitle($pdf, '美术风格');
  8818. $this->pdfBody($pdf, $artStyle);
  8819. }
  8820. // 主体列表(文字+图片)
  8821. $this->pdfSectionTitle($pdf, '主体列表');
  8822. foreach ($roles as $index => $role) {
  8823. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  8824. }
  8825. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  8826. // 场景列表(文字+图片)
  8827. $this->pdfSectionTitle($pdf, '场景列表');
  8828. foreach ($scenes as $index => $scene) {
  8829. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  8830. }
  8831. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  8832. // 道具列表(文字+图片)
  8833. $this->pdfSectionTitle($pdf, '道具列表');
  8834. foreach ($props as $index => $prop) {
  8835. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  8836. }
  8837. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  8838. // 分镜剧本
  8839. $this->pdfSectionTitle($pdf, '分镜剧本');
  8840. foreach ($episodeScripts as $episodeScript) {
  8841. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  8842. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  8843. if ($episodeTitleRaw !== '') {
  8844. // title 字段可能已带"第N集"前缀,避免重复
  8845. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  8846. $episodeTitle = $episodeTitleRaw;
  8847. } else {
  8848. $episodeTitle .= ':' . $episodeTitleRaw;
  8849. }
  8850. }
  8851. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  8852. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  8853. if (getProp($episodeScript, 'narrator_voice') !== '') {
  8854. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  8855. }
  8856. foreach (getProp($episodeScript, 'acts', []) as $act) {
  8857. $actTitle = '片段' . getProp($act, 'act_number');
  8858. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  8859. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  8860. }
  8861. $this->pdfSubTitle($pdf, $actTitle, 12);
  8862. if (getProp($act, 'content') !== '') {
  8863. $this->pdfBody($pdf, getProp($act, 'content'));
  8864. }
  8865. }
  8866. }
  8867. return $pdf;
  8868. }
  8869. /**
  8870. * PDF章节标题(带分隔线)
  8871. */
  8872. private function pdfSectionTitle($pdf, $title) {
  8873. if ($pdf->GetY() > 230) {
  8874. $pdf->AddPage();
  8875. }
  8876. $pdf->SetFont('simsun', 'B', 15);
  8877. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  8878. $y = $pdf->GetY();
  8879. $pdf->SetLineWidth(0.4);
  8880. $pdf->Line(15, $y, 195, $y);
  8881. $pdf->Ln(4);
  8882. }
  8883. /**
  8884. * PDF子标题(集数/片段标题)
  8885. */
  8886. private function pdfSubTitle($pdf, $title, $size = 13) {
  8887. if ($pdf->GetY() > 240) {
  8888. $pdf->AddPage();
  8889. }
  8890. $pdf->SetFont('simsun', 'B', $size);
  8891. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  8892. $pdf->Ln(1);
  8893. }
  8894. /**
  8895. * PDF正文段落
  8896. */
  8897. private function pdfBody($pdf, $text) {
  8898. $pdf->SetFont('simsun', '', 11);
  8899. $pdf->MultiCell(0, 6, $text, 0, 'L');
  8900. $pdf->Ln(2);
  8901. }
  8902. /**
  8903. * 输出列表项图片(每张图单独一页,图下标注名称)
  8904. * @param \TCPDF $pdf
  8905. * @param array $items 列表项
  8906. * @param string $nameKey role|scene|prop
  8907. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8908. */
  8909. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  8910. foreach ($items as $item) {
  8911. $url = trim((string)getProp($item, 'url', ''));
  8912. $name = trim((string)getProp($item, $nameKey, ''));
  8913. if ($url === '' || !isset($imageCache[$url])) continue;
  8914. $imgPath = $imageCache[$url];
  8915. $size = @getimagesize($imgPath);
  8916. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  8917. continue;
  8918. }
  8919. $pdf->AddPage();
  8920. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  8921. $maxW = 160;
  8922. $maxH = 170;
  8923. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  8924. $drawW = $size[0] * $ratio;
  8925. $drawH = $size[1] * $ratio;
  8926. $x = (210 - $drawW) / 2;
  8927. $y = max(15, (297 - $drawH) / 2 - 10);
  8928. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  8929. // 图下标注名称
  8930. $pdf->SetFont('simsun', 'B', 13);
  8931. $pdf->SetY(297 - 28);
  8932. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  8933. }
  8934. }
  8935. /**
  8936. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  8937. * @param array $items 包含url字段的列表项
  8938. * @return array url => 临时文件路径
  8939. */
  8940. private function downloadImagesConcurrently(array $items) {
  8941. // 收集唯一的图片URL
  8942. $urls = [];
  8943. foreach ($items as $item) {
  8944. $url = trim((string)getProp($item, 'url', ''));
  8945. if ($url !== '') $urls[$url] = true;
  8946. }
  8947. if (!$urls) return [];
  8948. $urls = array_keys($urls);
  8949. $tmpDir = sys_get_temp_dir();
  8950. $rawFiles = [];
  8951. foreach ($urls as $url) {
  8952. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  8953. $rawFiles[$url] = $rawFile;
  8954. }
  8955. $client = new Client(['timeout' => 180, 'verify' => false]);
  8956. // 低并发下载,sink写入文件避免大图占用内存
  8957. $generator = (function () use ($urls, $client, $rawFiles) {
  8958. foreach ($urls as $url) {
  8959. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  8960. }
  8961. })();
  8962. $errors = [];
  8963. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  8964. 'concurrency' => 4,
  8965. 'rejected' => function ($reason, $url) use (&$errors) {
  8966. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  8967. },
  8968. ]);
  8969. $each->promise()->wait();
  8970. // 失败的图片串行重试一次(独占带宽,提高成功率)
  8971. foreach ($urls as $url) {
  8972. if (!isset($errors[$url])) continue;
  8973. try {
  8974. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  8975. unset($errors[$url]);
  8976. } catch (\Throwable $e) {
  8977. // 重试仍失败
  8978. }
  8979. }
  8980. $cache = [];
  8981. foreach ($urls as $url) {
  8982. $rawFile = $rawFiles[$url];
  8983. if (isset($errors[$url])) {
  8984. dLog('anime')->error('导出PDF图片下载失败', [
  8985. 'url' => $url,
  8986. 'error' => $errors[$url],
  8987. ]);
  8988. @unlink($rawFile);
  8989. continue;
  8990. }
  8991. $converted = $this->convertImageFile($rawFile, $url);
  8992. if ($converted !== null) {
  8993. $cache[$url] = $converted;
  8994. } else {
  8995. @unlink($rawFile);
  8996. }
  8997. }
  8998. return $cache;
  8999. }
  9000. /**
  9001. * 将已下载的图片文件缩放并转为JPEG
  9002. * @param string $rawFile 原始图片临时文件
  9003. * @param string $url 图片地址(用于命名)
  9004. * @return string|null 转换后的文件路径,转换失败返回null
  9005. */
  9006. private function convertImageFile($rawFile, $url) {
  9007. $content = @file_get_contents($rawFile);
  9008. if ($content === false || $content === '') return null;
  9009. if (!function_exists('imagecreatefromstring')) return null;
  9010. $image = @imagecreatefromstring($content);
  9011. if ($image === false) return null;
  9012. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  9013. imagedestroy($image);
  9014. if ($jpeg !== null) {
  9015. @unlink($rawFile);
  9016. }
  9017. return $jpeg;
  9018. }
  9019. /**
  9020. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  9021. * @param resource $srcImage GD图片资源
  9022. * @param string $rawFile 原始图片临时文件
  9023. * @param string $url 图片地址(用于命名)
  9024. * @return string|null 压缩后的JPEG文件路径
  9025. */
  9026. private function compressImageForPdf($srcImage, $rawFile, $url) {
  9027. $maxBytes = 2 * 1024 * 1024; // 2MB
  9028. $sizes = [2048, 1600, 1280, 1024, 800];
  9029. $qualities = [85, 70, 55, 40];
  9030. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  9031. foreach ($sizes as $size) {
  9032. $resized = $this->copyAndResize($srcImage, $size);
  9033. $flat = $this->flattenToWhite($resized);
  9034. imagedestroy($resized);
  9035. foreach ($qualities as $quality) {
  9036. ob_start();
  9037. $saved = imagejpeg($flat, null, $quality);
  9038. $data = ob_get_clean();
  9039. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  9040. file_put_contents($jpeg, $data);
  9041. imagedestroy($flat);
  9042. dLog('anime')->info('导出PDF图片压缩完成', [
  9043. 'url' => $url,
  9044. 'size' => filesize($jpeg),
  9045. 'edge' => $size,
  9046. 'quality' => $quality,
  9047. ]);
  9048. return $jpeg;
  9049. }
  9050. }
  9051. imagedestroy($flat);
  9052. }
  9053. // 兜底:最小尺寸、最低质量强制输出
  9054. $resized = $this->copyAndResize($srcImage, 800);
  9055. $flat = $this->flattenToWhite($resized);
  9056. imagedestroy($resized);
  9057. $saved = imagejpeg($flat, $jpeg, 30);
  9058. imagedestroy($flat);
  9059. if (!$saved) return null;
  9060. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  9061. 'url' => $url,
  9062. 'size' => filesize($jpeg),
  9063. ]);
  9064. return $jpeg;
  9065. }
  9066. /**
  9067. * 等比缩放图片副本(不销毁原图)
  9068. * @param resource $srcImage GD图片资源
  9069. * @param int $maxEdge 最大边长
  9070. * @return resource
  9071. */
  9072. private function copyAndResize($srcImage, $maxEdge) {
  9073. $width = imagesx($srcImage);
  9074. $height = imagesy($srcImage);
  9075. $max = max($width, $height);
  9076. if ($max <= $maxEdge) {
  9077. $copy = imagecreatetruecolor($width, $height);
  9078. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  9079. return $copy;
  9080. }
  9081. $ratio = $maxEdge / $max;
  9082. $newWidth = max(1, (int)round($width * $ratio));
  9083. $newHeight = max(1, (int)round($height * $ratio));
  9084. $resized = imagecreatetruecolor($newWidth, $newHeight);
  9085. imagealphablending($resized, false);
  9086. imagesavealpha($resized, true);
  9087. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  9088. return $resized;
  9089. }
  9090. /**
  9091. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  9092. * @param resource $image GD图片资源
  9093. * @return resource
  9094. */
  9095. private function flattenToWhite($image) {
  9096. $width = imagesx($image);
  9097. $height = imagesy($image);
  9098. $flat = imagecreatetruecolor($width, $height);
  9099. $white = imagecolorallocate($flat, 255, 255, 255);
  9100. imagefill($flat, 0, 0, $white);
  9101. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  9102. return $flat;
  9103. }
  9104. /**
  9105. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  9106. * @param string $content 片段内容
  9107. * @param int $counter 当前已编号数量(引用传递,整集累计)
  9108. * @return string
  9109. */
  9110. private function renumberSegmentBlocks($content, &$counter) {
  9111. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  9112. $counter++;
  9113. return '【' . $match[1] . $counter . '】';
  9114. }, $content);
  9115. }
  9116. }