AnimeService.php 452 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545
  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. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4448. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4449. // 参考图上传为素材(百度网关/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4450. $reference_image_assets = $isKuaikuai
  4451. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4452. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4453. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4454. $videoParams['prompt'] = trim($fullPrompt);
  4455. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4456. $videoParams['reference_image_assets'] = $reference_image_assets;
  4457. }
  4458. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4459. if ($isKuaikuai) {
  4460. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4461. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4462. } else {
  4463. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4464. }
  4465. } else {
  4466. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4467. }
  4468. // 更新分镜表的视频任务信息
  4469. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4470. 'video_task_id' => $task->id,
  4471. 'video_task_status' => '生成中',
  4472. 'generate_audio' => $generate_audio,
  4473. 'updated_at' => date('Y-m-d H:i:s')
  4474. ]);
  4475. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4476. $episode_number = getProp($act, 'episode_number');
  4477. $act_number = getProp($act, 'act_number');
  4478. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4479. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4480. }
  4481. return [
  4482. 'task_id' => $task->id,
  4483. 'status' => $task->status,
  4484. 'act_id' => $act_id,
  4485. 'video_duration' => $videoDuration
  4486. ];
  4487. }
  4488. /**
  4489. * 文生视频通用方法
  4490. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4491. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4492. *
  4493. * @param array $data 请求参数
  4494. * @return array
  4495. */
  4496. public function generateVideo($data) {
  4497. $prompt = getProp($data, 'prompt');
  4498. if (empty($prompt)) {
  4499. Utils::throwError('20003:提示词不能为空');
  4500. }
  4501. $model = getProp($data, 'model');
  4502. if (!$model) {
  4503. $model = 'zhizhen-20';
  4504. }
  4505. // 验证模型是否在可用模型表中
  4506. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4507. Utils::throwError('20003:该模型已不可用,请更换!');
  4508. }
  4509. $video_duration = getProp($data, 'video_duration', 5);
  4510. $video_resolution = getProp($data, 'video_resolution', '480p');
  4511. $ratio = getProp($data, 'ratio', '9:16');
  4512. $generate_audio = getProp($data, 'generate_audio', 1);
  4513. $seed = getProp($data, 'seed', -1);
  4514. $first_frame_url = getProp($data, 'first_frame_url');
  4515. $tail_frame_url = getProp($data, 'tail_frame_url');
  4516. // 参考图(支持数组或JSON字符串,最多9张)
  4517. $reference_images = getProp($data, 'reference_images', []);
  4518. if (is_string($reference_images)) {
  4519. $reference_images = json_decode($reference_images, true) ?: [];
  4520. }
  4521. if (!is_array($reference_images)) {
  4522. Utils::throwError('20003:参考图格式不正确');
  4523. }
  4524. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4525. $reference_images = array_slice($reference_images, 0, 9);
  4526. // 参考视频(支持数组或JSON字符串,最多3个)
  4527. $reference_videos = getProp($data, 'reference_videos', []);
  4528. if (is_string($reference_videos)) {
  4529. $reference_videos = json_decode($reference_videos, true) ?: [];
  4530. }
  4531. if (!is_array($reference_videos)) {
  4532. Utils::throwError('20003:参考视频格式不正确');
  4533. }
  4534. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4535. if (count($reference_videos) > 3) {
  4536. Utils::throwError('20003:参考视频最多选择3个');
  4537. }
  4538. $reference_videos = array_slice($reference_videos, 0, 3);
  4539. // 参考音频(支持数组或JSON字符串,最多3个)
  4540. $reference_audios = getProp($data, 'reference_audios', []);
  4541. if (is_string($reference_audios)) {
  4542. $reference_audios = json_decode($reference_audios, true) ?: [];
  4543. }
  4544. if (!is_array($reference_audios)) {
  4545. Utils::throwError('20003:参考音频格式不正确');
  4546. }
  4547. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4548. if (count($reference_audios) > 3) {
  4549. Utils::throwError('20003:参考音频最多选择3个');
  4550. }
  4551. $reference_audios = array_slice($reference_audios, 0, 3);
  4552. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4553. $videoParams = [
  4554. 'model' => $model,
  4555. 'prompt' => $prompt,
  4556. 'video_duration' => $video_duration,
  4557. 'video_resolution' => $video_resolution,
  4558. 'seed' => $seed,
  4559. 'ratio' => $ratio,
  4560. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4561. 'draft' => getProp($data, 'draft', false),
  4562. 'watermark' => getProp($data, 'watermark', false),
  4563. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4564. ];
  4565. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4566. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4567. // 构建content数组
  4568. $videoParams['content'] = [
  4569. [
  4570. 'type' => 'text',
  4571. 'text' => $prompt,
  4572. ]
  4573. ];
  4574. // 根据模型选择不同的视频生成方法
  4575. if (strpos($model, 'jimeng') !== false) {
  4576. // 即梦模型参数调整
  4577. unset($videoParams['content']); // 即梦不使用content格式
  4578. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4579. } elseif (strpos($model, 'kling') !== false) {
  4580. // 可灵模型参数调整
  4581. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4582. unset($videoParams['ratio']);
  4583. unset($videoParams['content']); // 可灵不使用content格式
  4584. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4585. } elseif (strpos($model, 'zhizhen') !== false) {
  4586. // 智帧等新模型使用统一API
  4587. $unifiedParams = [
  4588. 'model_code' => $model,
  4589. 'prompt' => $prompt,
  4590. 'video_duration' => $video_duration,
  4591. 'video_resolution' => strtolower($video_resolution),
  4592. 'video_ratio' => $ratio,
  4593. 'seed' => $seed,
  4594. ];
  4595. // 构建parameters参数
  4596. $parameters = [
  4597. 'seconds' => $unifiedParams['video_duration'],
  4598. 'resolution' => $unifiedParams['video_resolution'],
  4599. 'ratio' => $ratio,
  4600. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4601. ];
  4602. // 首帧和尾帧
  4603. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4604. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4605. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4606. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4607. if ($refImageUrls) {
  4608. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4609. }
  4610. // 参考图处理
  4611. if ($reference_images) {
  4612. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4613. $parameters['reference_images'] = $reference_images;
  4614. $parameters['video_mode'] = 'multi_image';
  4615. $parameters['mode'] = 'multi_image';
  4616. }
  4617. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4618. if ($reference_videos) {
  4619. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4620. $parameters['reference_videos'] = $reference_videos;
  4621. }
  4622. if ($reference_audios) {
  4623. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4624. $parameters['reference_audios'] = $reference_audios;
  4625. }
  4626. $unifiedParams['parameters'] = $parameters;
  4627. // 调用统一API创建任务
  4628. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4629. } elseif (strpos($model, 'doubao-seedance-2.0') !== false || $this->isKuaikuaiSeedanceModel($model)) {
  4630. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4631. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4632. $videoParams['reference_images'] = $reference_images;
  4633. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4634. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4635. if ($refImageUrls) {
  4636. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4637. }
  4638. if ($reference_images) {
  4639. // 参考图上传为素材(百度网关/快快AI)
  4640. $reference_image_assets = $isKuaikuai
  4641. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4642. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']);
  4643. $videoParams['reference_image_assets'] = $reference_image_assets;
  4644. }
  4645. // 参考视频上传为素材(百度网关/快快AI)
  4646. if ($reference_videos) {
  4647. $reference_video_assets = $isKuaikuai
  4648. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4649. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']);
  4650. $videoParams['reference_video_assets'] = $reference_video_assets;
  4651. }
  4652. // 参考音频上传为素材(百度网关/快快AI)
  4653. if ($reference_audios) {
  4654. $reference_audio_assets = $isKuaikuai
  4655. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4656. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']);
  4657. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4658. }
  4659. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4660. if ($reference_images || $reference_videos || $reference_audios) {
  4661. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4662. }
  4663. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4664. if ($isKuaikuai) {
  4665. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4666. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4667. } else {
  4668. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4669. }
  4670. } else {
  4671. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4672. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4673. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4674. if ($refImageUrls) {
  4675. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4676. }
  4677. if ($reference_videos) {
  4678. foreach ($reference_videos as $videoUrl) {
  4679. $videoParams['content'][] = [
  4680. 'type' => 'video_url',
  4681. 'video_url' => [
  4682. 'url' => $videoUrl,
  4683. ],
  4684. 'role' => 'reference_video',
  4685. ];
  4686. }
  4687. }
  4688. if ($reference_audios) {
  4689. foreach ($reference_audios as $audioUrl) {
  4690. $videoParams['content'][] = [
  4691. 'type' => 'audio_url',
  4692. 'audio_url' => [
  4693. 'url' => $audioUrl,
  4694. ],
  4695. 'role' => 'reference_audio',
  4696. ];
  4697. }
  4698. }
  4699. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4700. }
  4701. return [
  4702. 'task_id' => $task->id,
  4703. 'status' => $task->status,
  4704. 'model' => $model,
  4705. 'video_duration' => $video_duration,
  4706. 'video_resolution' => $video_resolution,
  4707. 'ratio' => $ratio
  4708. ];
  4709. }
  4710. /**
  4711. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4712. *
  4713. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4714. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4715. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4716. *
  4717. * @param array $data
  4718. * @return array
  4719. */
  4720. public function previewCharge(array $data): array
  4721. {
  4722. $mode = (string)getProp($data, 'mode', '');
  4723. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4724. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4725. }
  4726. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4727. $scene = (string)getProp($data, 'scene', 'video_generation');
  4728. $items = [];
  4729. $model = '';
  4730. $resolution = '';
  4731. if ($mode === 'video') {
  4732. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4733. $model = (string)getProp($data, 'model', '');
  4734. if (!$model) {
  4735. Utils::throwError('1002:model参数不能为空');
  4736. }
  4737. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4738. $duration = (int)getProp($data, 'video_duration', 5);
  4739. if ($duration <= 0) {
  4740. $duration = 5;
  4741. }
  4742. $count = max(1, (int)getProp($data, 'count', 1));
  4743. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4744. 'model' => $model,
  4745. 'video_resolution' => $resolution,
  4746. 'video_duration' => $duration,
  4747. 'mode' => $scene,
  4748. ]);
  4749. $points = $pointsPerVideo * $count;
  4750. $items[] = [
  4751. 'type' => 'video',
  4752. 'model' => $model,
  4753. 'video_resolution' => $resolution,
  4754. 'video_duration' => $duration,
  4755. 'count' => $count,
  4756. 'points' => $points,
  4757. ];
  4758. } elseif ($mode === 'image') {
  4759. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4760. $model = (string)getProp($data, 'model', '');
  4761. if (!$model) {
  4762. Utils::throwError('1002:model参数不能为空');
  4763. }
  4764. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4765. if (!$resolution) {
  4766. $width = (int)getProp($data, 'width', 0);
  4767. $height = (int)getProp($data, 'height', 0);
  4768. if ($width <= 0 || $height <= 0) {
  4769. $width = 1600;
  4770. $height = 2848;
  4771. }
  4772. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4773. }
  4774. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4775. $points = $this->pointsService->getImageChargePoints([
  4776. 'model' => $model,
  4777. 'resolution' => $resolution,
  4778. ]) * $imageNum;
  4779. $items[] = [
  4780. 'type' => 'image',
  4781. 'model' => $model,
  4782. 'resolution' => $resolution,
  4783. 'image_num' => $imageNum,
  4784. 'points' => $points,
  4785. ];
  4786. } else {
  4787. // AI对话预估:单次10积分;批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算
  4788. $count = max(1, (int)getProp($data, 'count', 1));
  4789. $animeId = getProp($data, 'anime_id');
  4790. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4791. if ($animeId && $generateEpisodes > 0) {
  4792. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4793. ->where('anime_id', $animeId)
  4794. ->where('is_default', 1)
  4795. ->max('episode_number');
  4796. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4797. $startEpisodeNumber = $currentMaxEpisode + 1;
  4798. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4799. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4800. ->where('anime_id', $animeId)
  4801. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4802. ->whereIn('status', ['pending', 'processing', 'completed'])
  4803. ->count();
  4804. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4805. if ($count < 0) {
  4806. $count = 0;
  4807. }
  4808. }
  4809. $points = $this->pointsService->getChatChargePoints((string)$model) * $count;
  4810. $items[] = [
  4811. 'type' => 'chat',
  4812. 'count' => $count,
  4813. 'points' => $points,
  4814. ];
  4815. }
  4816. $totalPoints = 0;
  4817. foreach ($items as $item) {
  4818. $totalPoints += $item['points'];
  4819. }
  4820. return [
  4821. 'mode' => $mode,
  4822. 'total_points' => $totalPoints,
  4823. 'items' => $items,
  4824. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4825. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4826. ];
  4827. }
  4828. /**
  4829. * 根据提示词内容智能计算最优视频时长
  4830. *
  4831. * @param string $segmentContent 分镜内容
  4832. * @param string $tailFrame 尾帧描述
  4833. * @return int 视频时长(2-12秒)
  4834. */
  4835. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4836. // 合并所有文本内容
  4837. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4838. // 如果没有内容,返回默认时长
  4839. if (empty($fullText)) {
  4840. return 5;
  4841. }
  4842. // 计算文本长度(中文字符按2个字符计算)
  4843. $textLength = mb_strlen($fullText, 'UTF-8');
  4844. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4845. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4846. // 分析内容复杂度
  4847. $complexityScore = $this->analyzeContentComplexity($fullText);
  4848. // 基础时长计算(根据文本长度)
  4849. $baseDuration = 3; // 默认2秒
  4850. // if ($adjustedLength <= 20) {
  4851. // $baseDuration = 3;
  4852. // } elseif ($adjustedLength <= 40) {
  4853. // $baseDuration = 4;
  4854. // } elseif ($adjustedLength <= 60) {
  4855. // $baseDuration = 5;
  4856. // } elseif ($adjustedLength <= 80) {
  4857. // $baseDuration = 6;
  4858. // } elseif ($adjustedLength <= 100) {
  4859. // $baseDuration = 7;
  4860. // } elseif ($adjustedLength <= 120) {
  4861. // $baseDuration = 8;
  4862. // } else {
  4863. // $baseDuration = 9;
  4864. // }
  4865. // 根据内容复杂度调整时长
  4866. $finalDuration = $baseDuration + $complexityScore;
  4867. // 确保时长在2-12秒范围内
  4868. return max(4, min(12, $finalDuration));
  4869. }
  4870. /**
  4871. * 分析内容复杂度,返回时长调整值
  4872. *
  4873. * @param string $text 文本内容
  4874. * @return int 调整值(-2到+3)
  4875. */
  4876. private function analyzeContentComplexity($text) {
  4877. $score = 0;
  4878. // 动作关键词(需要更长时间展现)
  4879. $actionKeywords = [
  4880. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4881. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4882. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4883. ];
  4884. // 静态关键词(可以用较短时间)
  4885. $staticKeywords = [
  4886. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4887. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4888. ];
  4889. // 复杂场景关键词(需要更长时间)
  4890. $complexSceneKeywords = [
  4891. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4892. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4893. ];
  4894. // 情感关键词(需要适中时间表现)
  4895. $emotionKeywords = [
  4896. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4897. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4898. ];
  4899. // 检查动作关键词
  4900. foreach ($actionKeywords as $keyword) {
  4901. if (strpos($text, $keyword) !== false) {
  4902. $score += 1;
  4903. break; // 避免重复加分
  4904. }
  4905. }
  4906. // 检查静态关键词
  4907. foreach ($staticKeywords as $keyword) {
  4908. if (strpos($text, $keyword) !== false) {
  4909. $score -= 1;
  4910. break;
  4911. }
  4912. }
  4913. // 检查复杂场景关键词
  4914. foreach ($complexSceneKeywords as $keyword) {
  4915. if (strpos($text, $keyword) !== false) {
  4916. $score += 1;
  4917. break;
  4918. }
  4919. }
  4920. // 检查情感关键词
  4921. foreach ($emotionKeywords as $keyword) {
  4922. if (strpos($text, $keyword) !== false) {
  4923. $score += 1;
  4924. break;
  4925. }
  4926. }
  4927. // 检查时间相关词汇
  4928. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4929. $score += 1;
  4930. }
  4931. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4932. $score -= 1;
  4933. }
  4934. // 检查转场词汇
  4935. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4936. $score += 1;
  4937. }
  4938. // 检查环境描述(复杂环境需要更多时间)
  4939. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4940. $score += 1;
  4941. }
  4942. // 检查对话内容(对话需要更多时间)
  4943. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4944. $score += 1;
  4945. }
  4946. // 限制调整范围
  4947. return max(-1, min(4, $score));
  4948. }
  4949. /**
  4950. * 创建完整视频合成任务
  4951. *
  4952. * @param array $data
  4953. * @return array
  4954. */
  4955. public function createCompleteVideoTask($data)
  4956. {
  4957. $animeId = getProp($data, 'anime_id');
  4958. $episodeId = getProp($data, 'episode_id');
  4959. // 验证参数
  4960. if (!$animeId || !$episodeId) {
  4961. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4962. }
  4963. // 检查是否已存在处理中的任务
  4964. $existingTask = DB::table('mp_complete_video_tasks')
  4965. ->where('anime_id', $animeId)
  4966. ->where('episode_id', $episodeId)
  4967. ->whereIn('generate_status', ['执行中'])
  4968. ->first();
  4969. if ($existingTask) {
  4970. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4971. }
  4972. // 获取全能模式状态
  4973. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4974. if ((int)$ace_mode === 1) {
  4975. // 获取所有片段的配音视频,按 act_number 排序
  4976. $segments = DB::table('mp_episode_segments')
  4977. ->where('anime_id', $animeId)
  4978. ->where('episode_id', $episodeId)
  4979. ->orderBy('segment_number')
  4980. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4981. ->get();
  4982. // 检查是否所有片段都有视频
  4983. $missingVideos = $segments->filter(function($segment) {
  4984. return empty($segment->video_url);
  4985. });
  4986. if ($missingVideos->isNotEmpty()) {
  4987. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4988. }
  4989. }else {
  4990. // 获取所有分镜的配音视频,按 segment_number 排序
  4991. $segments = DB::table('mp_episode_segments')
  4992. ->where('anime_id', $animeId)
  4993. ->where('episode_id', $episodeId)
  4994. ->orderBy('segment_number')
  4995. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4996. ->get();
  4997. // 检查是否所有分镜都有配音和视频
  4998. $missingVideos = $segments->filter(function($segment) {
  4999. return empty($segment->audio_url) || empty($segment->video_url);
  5000. });
  5001. if ($missingVideos->isNotEmpty()) {
  5002. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5003. }
  5004. }
  5005. if ($segments->isEmpty()) {
  5006. Utils::throwError('20003:未找到该剧集的分镜数据');
  5007. }
  5008. // 获取当前完整视频url
  5009. $completeVideoUrl = DB::table('mp_anime_episodes')
  5010. ->where('anime_id', $animeId)
  5011. ->where('id', $episodeId)
  5012. ->value('complete_video_url');
  5013. // 构建 generate_json
  5014. $generateJson = [];
  5015. $sequence = 1;
  5016. foreach ($segments as $segment) {
  5017. if ((int)$ace_mode === 1) {
  5018. $generateJson[] = [
  5019. 'sequence' => $sequence++,
  5020. 'video_url' => $segment->video_url,
  5021. 'video_time_point_start' => $segment->video_time_point_start,
  5022. 'video_time_point_end' => $segment->video_time_point_end
  5023. ];
  5024. }else {
  5025. $generateJson[] = [
  5026. 'sequence' => $sequence++,
  5027. 'video_url' => $segment->video_url,
  5028. 'audio_url' => $segment->audio_url,
  5029. 'video_time_point_start' => $segment->video_time_point_start,
  5030. 'video_time_point_end' => $segment->video_time_point_end
  5031. ];
  5032. }
  5033. }
  5034. // 创建任务
  5035. $now = date('Y-m-d H:i:s');
  5036. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5037. 'anime_id' => $animeId,
  5038. 'episode_id' => $episodeId,
  5039. 'generate_json' => json_encode($generateJson, 256),
  5040. 'generate_status' => '执行中',
  5041. 'complete_video_url' => '',
  5042. 'created_at' => $now,
  5043. 'updated_at' => $now
  5044. ]);
  5045. if (!$taskId) {
  5046. Utils::throwError('20003:创建任务失败');
  5047. }
  5048. // 更新剧集表的任务ID和状态
  5049. $boolen = DB::table('mp_anime_episodes')
  5050. ->where('anime_id', $animeId)
  5051. ->where('id', $episodeId)
  5052. ->update([
  5053. 'complete_video_task_id' => $taskId,
  5054. 'complete_video_task_status' => '执行中',
  5055. 'updated_at' => $now
  5056. ]);
  5057. if (!$boolen) {
  5058. Utils::throwError('20003:更新剧集表失败');
  5059. }
  5060. dLog('anime')->info('创建完整视频合成任务', [
  5061. 'task_id' => $taskId,
  5062. 'anime_id' => $animeId,
  5063. 'episode_id' => $episodeId,
  5064. 'segment_count' => count($generateJson)
  5065. ]);
  5066. // 请求远程服务器执行生成
  5067. $client = new Client(['timeout' => 600, 'verify' => false]);
  5068. try {
  5069. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5070. $response = $result->getBody()->getContents();
  5071. $response_arr = json_decode($response, true);
  5072. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5073. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5074. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5075. // // 更新任务状态为失败
  5076. // DB::table('mp_complete_video_tasks')
  5077. // ->where('id', $taskId)
  5078. // ->update([
  5079. // 'generate_status' => '执行失败',
  5080. // 'error_message' => $error_msg,
  5081. // 'updated_at' => date('Y-m-d H:i:s')
  5082. // ]);
  5083. // // 同步更新剧集表状态
  5084. // DB::table('mp_anime_episodes')
  5085. // ->where('complete_video_task_id', $taskId)
  5086. // ->update([
  5087. // 'complete_video_task_status' => '执行失败',
  5088. // 'updated_at' => date('Y-m-d H:i:s')
  5089. // ]);
  5090. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5091. }
  5092. } catch (\Exception $e) {
  5093. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5094. // 更新任务状态为失败
  5095. DB::table('mp_complete_video_tasks')
  5096. ->where('id', $taskId)
  5097. ->update([
  5098. 'generate_status' => '执行失败',
  5099. 'error_message' => $e->getMessage(),
  5100. 'updated_at' => date('Y-m-d H:i:s')
  5101. ]);
  5102. // 同步更新剧集表状态
  5103. DB::table('mp_anime_episodes')
  5104. ->where('complete_video_task_id', $taskId)
  5105. ->update([
  5106. 'complete_video_task_status' => '执行失败',
  5107. 'updated_at' => date('Y-m-d H:i:s')
  5108. ]);
  5109. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5110. }
  5111. // 开始轮询任务状态
  5112. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5113. $pollInterval = 5; // 每5秒轮询一次
  5114. $attempt = 0;
  5115. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5116. while ($attempt < $maxAttempts) {
  5117. sleep($pollInterval);
  5118. $attempt++;
  5119. // 查询任务状态
  5120. $task = DB::table('mp_complete_video_tasks')
  5121. ->where('id', $taskId)
  5122. ->first();
  5123. if (!$task) {
  5124. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5125. Utils::throwError('20003:任务不存在');
  5126. }
  5127. dLog('anime')->info('轮询任务状态', [
  5128. 'task_id' => $taskId,
  5129. 'attempt' => $attempt,
  5130. 'status' => $task->generate_status
  5131. ]);
  5132. // 检查任务是否完成
  5133. if ($task->generate_status === '执行成功') {
  5134. // 同步更新剧集表状态
  5135. $boolen3 = DB::table('mp_anime_episodes')
  5136. ->where('anime_id', $animeId)
  5137. ->where('id', $episodeId)
  5138. ->update([
  5139. 'complete_video_url' => $task->complete_video_url,
  5140. 'complete_video_task_status' => '执行成功',
  5141. 'updated_at' => date('Y-m-d H:i:s')
  5142. ]);
  5143. dLog('anime')->info('视频合成任务完成', [
  5144. 'task_id' => $taskId,
  5145. 'video_url' => $task->complete_video_url,
  5146. 'attempts' => $attempt
  5147. ]);
  5148. // 如果更新成功则远程删除之前的文件
  5149. if ($boolen3 && $completeVideoUrl) {
  5150. $encode_url = urlencode($completeVideoUrl);
  5151. $client = new Client(['timeout' => 300, 'verify' => false]);
  5152. // 根据ID通过API通知合成音频
  5153. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5154. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5155. $response = $result->getBody()->getContents();
  5156. $response_arr = json_decode($response, true);
  5157. Log::info('火山删除音频返回: '.$response);
  5158. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5159. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5160. Log::info('火山删除音频失败: '.$error_msg);
  5161. // Utils::throwError('20003:火山删除音频失败');
  5162. }
  5163. }
  5164. return [
  5165. 'task_id' => $taskId,
  5166. 'anime_id' => $animeId,
  5167. 'episode_id' => $episodeId,
  5168. 'segment_count' => count($generateJson),
  5169. 'generate_status' => '执行成功',
  5170. 'complete_video_url' => $task->complete_video_url,
  5171. ];
  5172. }
  5173. // 检查任务是否失败
  5174. if ($task->generate_status === '执行失败') {
  5175. // 同步更新剧集表状态
  5176. DB::table('mp_anime_episodes')
  5177. ->where('anime_id', $animeId)
  5178. ->where('id', $episodeId)
  5179. ->update([
  5180. 'complete_video_task_status' => '执行失败',
  5181. 'updated_at' => date('Y-m-d H:i:s')
  5182. ]);
  5183. $errorMessage = $task->error_message ?? '未知错误';
  5184. dLog('anime')->error('视频合成任务失败', [
  5185. 'task_id' => $taskId,
  5186. 'error' => $errorMessage,
  5187. 'attempts' => $attempt
  5188. ]);
  5189. return [
  5190. 'task_id' => $taskId,
  5191. 'anime_id' => $animeId,
  5192. 'episode_id' => $episodeId,
  5193. 'segment_count' => count($generateJson),
  5194. 'generate_status' => '执行失败',
  5195. 'error_message' => $errorMessage
  5196. ];
  5197. }
  5198. }
  5199. // 超时处理
  5200. dLog('anime')->warning('视频合成任务超时', [
  5201. 'task_id' => $taskId,
  5202. 'max_attempts' => $maxAttempts,
  5203. 'timeout_seconds' => $maxAttempts * $pollInterval
  5204. ]);
  5205. // 更新任务状态为超时
  5206. DB::table('mp_complete_video_tasks')
  5207. ->where('id', $taskId)
  5208. ->update([
  5209. 'generate_status' => '超时',
  5210. 'error_message' => '任务执行超时(5分钟)',
  5211. 'updated_at' => date('Y-m-d H:i:s')
  5212. ]);
  5213. return [
  5214. 'task_id' => $taskId,
  5215. 'anime_id' => $animeId,
  5216. 'episode_id' => $episodeId,
  5217. 'segment_count' => count($generateJson),
  5218. 'generate_status' => '超时',
  5219. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5220. ];
  5221. }
  5222. /**
  5223. * 根据 inner_prompt_type 附加内置提示词
  5224. *
  5225. * @param string $prompt 用户提示词
  5226. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5227. * @return string 合并后的提示词
  5228. */
  5229. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5230. {
  5231. $innerPromptMap = [
  5232. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  5233. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5234. ];
  5235. if (!isset($innerPromptMap[$innerPromptType])) {
  5236. return $prompt;
  5237. }
  5238. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5239. }
  5240. /**
  5241. * 根据 inner_prompt_type 获取生成图片数量
  5242. *
  5243. * @param int $innerPromptType 内置提示词类型
  5244. * @param int $imageNum 传入的图片张数
  5245. * @return int 图片数量
  5246. */
  5247. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5248. {
  5249. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5250. }
  5251. /**
  5252. * 提取图片生成结果URL
  5253. *
  5254. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5255. * @param int $innerPromptType 内置提示词类型
  5256. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5257. */
  5258. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5259. {
  5260. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5261. if (is_array($resultUrls) && !empty($resultUrls)) {
  5262. $resultUrls = array_values($resultUrls);
  5263. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5264. }
  5265. if (!empty($resultUrl)) {
  5266. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5267. }
  5268. return (int)$innerPromptType === 2 ? [] : '';
  5269. }
  5270. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5271. $prompt = getProp($data, 'prompt');
  5272. $episode_id = getProp($data, 'episode_id');
  5273. $ref_img_urls = getProp($data, 'ref_img_urls');
  5274. $ratio = getProp($data, 'ratio', '9:16');
  5275. $resolution = getProp($data, 'resolution', '2k');
  5276. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5277. $imageNum = (int)getProp($data, 'image_num', 1);
  5278. // 定义分辨率和宽高比对应的尺寸映射表
  5279. $sizeMap = [
  5280. '2k' => [
  5281. '1:1' => ['width' => 2048, 'height' => 2048],
  5282. '4:3' => ['width' => 2304, 'height' => 1728],
  5283. '3:4' => ['width' => 1728, 'height' => 2304],
  5284. '16:9' => ['width' => 2848, 'height' => 1600],
  5285. '9:16' => ['width' => 1600, 'height' => 2848],
  5286. '3:2' => ['width' => 2496, 'height' => 1664],
  5287. '2:3' => ['width' => 1664, 'height' => 2496],
  5288. '21:9' => ['width' => 3136, 'height' => 1344],
  5289. ],
  5290. '3k' => [
  5291. '1:1' => ['width' => 3072, 'height' => 3072],
  5292. '4:3' => ['width' => 3456, 'height' => 2592],
  5293. '3:4' => ['width' => 2592, 'height' => 3456],
  5294. '16:9' => ['width' => 4096, 'height' => 2304],
  5295. '9:16' => ['width' => 2304, 'height' => 4096],
  5296. '2:3' => ['width' => 2496, 'height' => 3744],
  5297. '3:2' => ['width' => 3744, 'height' => 2496],
  5298. '21:9' => ['width' => 4704, 'height' => 2016],
  5299. ],
  5300. '4k' => [
  5301. '1:1' => ['width' => 4096, 'height' => 4096],
  5302. '3:4' => ['width' => 3520, 'height' => 4704],
  5303. '4:3' => ['width' => 4704, 'height' => 3520],
  5304. '16:9' => ['width' => 5504, 'height' => 3040],
  5305. '9:16' => ['width' => 3040, 'height' => 5504],
  5306. '2:3' => ['width' => 3328, 'height' => 4992],
  5307. '3:2' => ['width' => 4992, 'height' => 3328],
  5308. '21:9' => ['width' => 6240, 'height' => 2656],
  5309. ],
  5310. ];
  5311. // 参数验证
  5312. $resolution = strtolower($resolution);
  5313. if (!isset($sizeMap[$resolution])) {
  5314. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5315. }
  5316. if (!isset($sizeMap[$resolution][$ratio])) {
  5317. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5318. }
  5319. // 根据 ratio 和 resolution 确定宽高
  5320. $width = $sizeMap[$resolution][$ratio]['width'];
  5321. $height = $sizeMap[$resolution][$ratio]['height'];
  5322. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5323. if (is_json($ref_img_urls)) {
  5324. $ref_img_urls = json_decode($ref_img_urls, true);
  5325. }else {
  5326. $ref_img_urls = explode(',', $ref_img_urls);
  5327. }
  5328. }
  5329. // 处理图片模型
  5330. $model = getProp($data, 'model');
  5331. if (!$model) {
  5332. // 用户没有输入,从episode表获取
  5333. if ($episode_id) {
  5334. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5335. $model = getProp($episode, 'image_model');
  5336. }
  5337. if (!$model) {
  5338. // episode表也没有,使用默认值
  5339. $model = 'doubao-seedream-5-0-lite-260128';
  5340. }
  5341. }
  5342. // 验证模型是否在可用模型表中
  5343. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5344. // $model = 'doubao-seedream-5-0-lite-260128';
  5345. Utils::throwError('20003:该模型已不可用,请更换!');
  5346. }
  5347. // 保存到episode表
  5348. if ($episode_id) {
  5349. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5350. 'image_model' => $model,
  5351. 'updated_at' => date('Y-m-d H:i:s')
  5352. ]);
  5353. }
  5354. // 参数验证
  5355. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5356. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5357. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5358. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5359. try {
  5360. // 创建图片生成任务
  5361. $params = [
  5362. 'prompt' => $prompt,
  5363. 'model' => $model,
  5364. 'ref_img_urls' => '',
  5365. 'width' => $width,
  5366. 'height' => $height,
  5367. 'image_num' => $imageNum
  5368. ];
  5369. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5370. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5371. $task_id = $task->id;
  5372. if (!$task_id) {
  5373. Utils::throwError('20003:创建图片生成任务失败');
  5374. }
  5375. // 创建任务中心记录并关联图片任务ID
  5376. $taskCenter = $this->taskCenterService->createTask('image', [
  5377. 'title' => '文生图',
  5378. 'ref_task_id' => $task_id,
  5379. // 'prompt' => $prompt,
  5380. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5381. ]);
  5382. $taskCenterId = $taskCenter->id;
  5383. // 组装本次任务信息(用于init消息,类似generateVideo)
  5384. $taskInfo = [
  5385. 'task_id' => $task_id,
  5386. 'status' => getProp($task, 'status', 'processing'),
  5387. 'model' => $model,
  5388. 'ratio' => $ratio,
  5389. 'resolution' => $resolution,
  5390. 'image_num' => $imageNum,
  5391. ];
  5392. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5393. if (is_callable($onTaskCreated)) {
  5394. $onTaskCreated($taskCenterId, $taskInfo);
  5395. }
  5396. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5397. $model = getProp($task, 'model');
  5398. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5399. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5400. $isSyncModel = $isVolcModel || $isGptModel;
  5401. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5402. $start_time = time();
  5403. $timeout = 300; // 5分钟
  5404. $img_url = '';
  5405. $img_urls = [];
  5406. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5407. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5408. while (time() - $start_time < $timeout) {
  5409. sleep(3);
  5410. // 每分钟发送一次队列状态消息(仅流式模式)
  5411. if (is_callable($onPoll)) {
  5412. $currentTime = time();
  5413. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5414. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5415. $lastQueueMessageTime = $currentTime;
  5416. }
  5417. }
  5418. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5419. if ($isSyncModel) {
  5420. // 刷新任务状态
  5421. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5422. if ($task->status === 'success' && $task->result_url) {
  5423. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5424. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5425. if (!empty($resultUrls)) {
  5426. $img_urls = $resultUrls;
  5427. $img_url = $resultUrls[0];
  5428. } else {
  5429. $img_url = (string)$task->result_url;
  5430. }
  5431. break;
  5432. } elseif ($task->status === 'failed') {
  5433. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5434. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5435. }
  5436. // // 如果还在处理中,提示用户稍后查看
  5437. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5438. }else {
  5439. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5440. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5441. if ($statusInfo['status'] === 'success') {
  5442. $task->updateStatus('success', [
  5443. 'result_url' => $statusInfo['result_url'],
  5444. 'result_json' => $statusInfo['result_json'] ?? []
  5445. ]);
  5446. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5447. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5448. if (!empty($resultUrls)) {
  5449. $img_urls = $resultUrls;
  5450. $img_url = $resultUrls[0];
  5451. } else {
  5452. $img_url = (string)$statusInfo['result_url'];
  5453. }
  5454. break;
  5455. } elseif ($statusInfo['status'] === 'failed') {
  5456. $task->updateStatus('failed', [
  5457. 'error_message' => $statusInfo['error_message'],
  5458. 'result_json' => $statusInfo['result_json'] ?? []
  5459. ]);
  5460. dLog('anime')->error('图片生成失败,', [
  5461. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5462. ]);
  5463. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5464. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5465. }
  5466. }
  5467. }
  5468. if (empty($img_url)) {
  5469. Utils::throwError('20003:图片生成超时,请稍后重试');
  5470. }
  5471. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5472. if (count($img_urls) > 1) {
  5473. return [
  5474. 'img_url' => $img_url,
  5475. 'image_urls' => $img_urls,
  5476. 'task_id' => $taskCenterId,
  5477. ];
  5478. }
  5479. return [
  5480. 'img_url' => $img_url,
  5481. 'task_id' => $taskCenterId,
  5482. ];
  5483. } catch (\Exception $e) {
  5484. dLog('anime')->error('更新角色或场景失败', [
  5485. 'error' => $e->getMessage()
  5486. ]);
  5487. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5488. Utils::throwError('20003:' . $e->getMessage());
  5489. }
  5490. }
  5491. /**
  5492. * 使用文生文模型解析分镜内容
  5493. */
  5494. private function parseSegmentContentWithAI($segment_content) {
  5495. try {
  5496. // 使用DeepSeek服务的公开方法解析分镜内容
  5497. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5498. } catch (\Exception $e) {
  5499. // 如果AI解析失败,记录日志并返回原内容
  5500. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5501. return $segment_content;
  5502. }
  5503. }
  5504. /**
  5505. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5506. *
  5507. * @param int $episode_id 分集ID
  5508. * @param int $anime_id 动漫ID
  5509. * @param array $roles 分集角色数组(引用传递)
  5510. * @param array $scenes 分集场景数组(引用传递)
  5511. * @param array $episode 分集数据
  5512. */
  5513. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5514. // 获取全局动漫的角色和场景数据
  5515. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5516. if (!$anime) return;
  5517. $art_style_type = getProp($anime, 'art_style_type');
  5518. $character_prefix = '';
  5519. $scene_prefix = '';
  5520. if ($art_style_type) {
  5521. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5522. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5523. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5524. }
  5525. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5526. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5527. $roles_updated = false;
  5528. $scenes_updated = false;
  5529. // 处理角色
  5530. foreach ($roles as &$role) {
  5531. $role_name = getProp($role, 'role');
  5532. $role_description = getProp($role, 'description');
  5533. $role_pic_prompt = getProp($role, 'pic_prompt');
  5534. $role_url = getProp($role, 'url');
  5535. $role_task_id = getProp($role, 'task_id');
  5536. // 如果已有URL或已有任务ID,跳过
  5537. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5538. continue;
  5539. }
  5540. $url_inherited = false;
  5541. // 尝试从全局数据中继承
  5542. foreach ($global_roles as $global_role) {
  5543. $global_role_name = getProp($global_role, 'role');
  5544. $global_role_description = getProp($global_role, 'description');
  5545. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5546. $global_role_url = getProp($global_role, 'url');
  5547. $global_role_task_id = getProp($global_role, 'task_id');
  5548. $global_role_task_status = getProp($global_role, 'task_status');
  5549. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5550. if ($role_name === $global_role_name
  5551. && $role_description === $global_role_description
  5552. && $role_pic_prompt === $global_role_pic_prompt
  5553. && !empty($global_role_url)) {
  5554. // 继承 task_id、task_status 和 url
  5555. $role['task_id'] = $global_role_task_id;
  5556. $role['task_status'] = $global_role_task_status;
  5557. $role['url'] = $global_role_url;
  5558. $roles_updated = true;
  5559. $url_inherited = true;
  5560. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5561. break;
  5562. }
  5563. }
  5564. // 如果无法继承且没有任务ID,创建新任务
  5565. if (!$url_inherited && empty($role_task_id)) {
  5566. try {
  5567. $art_style = getProp($episode, 'art_style');
  5568. // 优先使用 pic_prompt,如果没有则使用 description
  5569. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5570. // if ($art_style) {
  5571. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5572. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5573. // }
  5574. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5575. $params = [
  5576. 'prompt' => $description,
  5577. 'ref_img_urls' => []
  5578. ];
  5579. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5580. $task_id = $task->id;
  5581. if ($task_id) {
  5582. $role['task_id'] = $task_id;
  5583. $role['task_status'] = 'processing';
  5584. $roles_updated = true;
  5585. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5586. }
  5587. } catch (\Exception $e) {
  5588. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5589. }
  5590. }
  5591. }
  5592. // 处理场景
  5593. foreach ($scenes as &$scene) {
  5594. $scene_name = getProp($scene, 'scene');
  5595. $scene_description = getProp($scene, 'description');
  5596. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5597. $scene_url = getProp($scene, 'url');
  5598. $scene_task_id = getProp($scene, 'task_id');
  5599. // 如果已有URL或已有任务ID,跳过
  5600. if (!empty($scene_url) || !empty($scene_task_id)) {
  5601. continue;
  5602. }
  5603. $url_inherited = false;
  5604. // 尝试从全局数据中继承
  5605. foreach ($global_scenes as $global_scene) {
  5606. $global_scene_name = getProp($global_scene, 'scene');
  5607. $global_scene_description = getProp($global_scene, 'description');
  5608. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5609. $global_scene_url = getProp($global_scene, 'url');
  5610. $global_scene_task_id = getProp($global_scene, 'task_id');
  5611. $global_scene_task_status = getProp($global_scene, 'task_status');
  5612. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5613. if ($scene_name === $global_scene_name
  5614. && $scene_description === $global_scene_description
  5615. && $scene_pic_prompt === $global_scene_pic_prompt
  5616. && !empty($global_scene_url)) {
  5617. // 继承 task_id、task_status 和 url
  5618. $scene['task_id'] = $global_scene_task_id;
  5619. $scene['task_status'] = $global_scene_task_status;
  5620. $scene['url'] = $global_scene_url;
  5621. $scenes_updated = true;
  5622. $url_inherited = true;
  5623. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5624. break;
  5625. }
  5626. }
  5627. // 如果无法继承且没有任务ID,创建新任务
  5628. if (!$url_inherited && empty($scene_task_id)) {
  5629. try {
  5630. $art_style = getProp($episode, 'art_style');
  5631. // 优先使用 pic_prompt,如果没有则使用 description
  5632. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5633. // if ($art_style) {
  5634. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5635. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5636. // }
  5637. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5638. $params = [
  5639. 'prompt' => $description,
  5640. 'ref_img_urls' => []
  5641. ];
  5642. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5643. $task_id = $task->id;
  5644. if ($task_id) {
  5645. $scene['task_id'] = $task_id;
  5646. $scene['task_status'] = 'processing';
  5647. $scenes_updated = true;
  5648. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5649. }
  5650. } catch (\Exception $e) {
  5651. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5652. }
  5653. }
  5654. }
  5655. // 如果有更新,保存到数据库
  5656. if ($roles_updated || $scenes_updated) {
  5657. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5658. if ($roles_updated) {
  5659. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5660. }
  5661. if ($scenes_updated) {
  5662. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5663. }
  5664. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5665. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5666. }
  5667. }
  5668. /**
  5669. * 根据图片URL使用AI反推图片提示词
  5670. *
  5671. * @param string $img_url 图片URL
  5672. * @return string 反推的提示词
  5673. */
  5674. private function generateImagePromptFromUrl($img_url) {
  5675. try {
  5676. // 获取默认模型
  5677. $model = 'doubao-seed-2-0-mini-260215';
  5678. // 构建messages参数
  5679. $messages = [
  5680. [
  5681. 'role' => 'user',
  5682. 'content' => [
  5683. [
  5684. 'type' => 'text',
  5685. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5686. ],
  5687. [
  5688. 'type' => 'image_url',
  5689. 'image_url' => [
  5690. 'url' => $img_url
  5691. ]
  5692. ]
  5693. ]
  5694. ]
  5695. ];
  5696. // 构建请求参数
  5697. $params = [
  5698. 'model' => $model,
  5699. 'messages' => $messages,
  5700. 'stream' => false,
  5701. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5702. ];
  5703. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5704. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5705. // 仅记录 token 使用明细(不扣积分)
  5706. $uid = 0;
  5707. try {
  5708. $uid = (int)Site::getUid();
  5709. } catch (\Throwable $e) {
  5710. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5711. }
  5712. $this->pointsService->recordTokenOnlyDetail(
  5713. $uid,
  5714. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5715. [
  5716. 'model' => $model,
  5717. 'img_url' => $img_url,
  5718. 'source' => 'generateImagePromptFromUrl',
  5719. ],
  5720. 'chat',
  5721. $model,
  5722. ''
  5723. );
  5724. // 返回生成的内容
  5725. return getProp($result, 'fullContent', '图片描述生成失败');
  5726. } catch (\Exception $e) {
  5727. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5728. 'img_url' => $img_url
  5729. ]);
  5730. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5731. 'error' => $e->getMessage(),
  5732. 'img_url' => $img_url
  5733. ]);
  5734. return '图片描述生成失败: ' . $e->getMessage();
  5735. }
  5736. }
  5737. /**
  5738. * 音频试听接口
  5739. * 创建音频任务并轮询获取结果
  5740. *
  5741. * @param array $data 参数数组
  5742. * @return array 返回音频URL或错误信息
  5743. */
  5744. public function previewAudio($data) {
  5745. $dialogue = getProp($data, 'dialogue');
  5746. // 必填参数验证
  5747. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5748. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5749. $voice_type = getProp($data, 'voice_type');
  5750. $voice_name = getProp($data, 'voice_name');
  5751. $voice_actor = getProp($data, 'voice_actor');
  5752. $emotion_type = getProp($data, 'emotion_type');
  5753. $gender = getProp($data, 'gender', 0);
  5754. $emotion = getProp($data, 'emotion');
  5755. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5756. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5757. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5758. $pitch = getProp($data, 'pitch', 0);
  5759. try {
  5760. $now = date('Y-m-d H:i:s');
  5761. // 构建生成参数
  5762. $generate_json = json_encode([
  5763. 'text' => $dialogue,
  5764. 'role' => $voice_actor,
  5765. 'voice_type' => $voice_type,
  5766. 'voice_name' => $voice_name,
  5767. 'emotion' => $emotion,
  5768. 'emotion_type' => $emotion_type,
  5769. 'gender' => $gender,
  5770. 'speed_ratio' => $speed_ratio,
  5771. 'loudness_ratio' => $loudness_ratio,
  5772. 'emotion_scale' => $emotion_scale,
  5773. 'pitch' => $pitch,
  5774. ], 256);
  5775. // 请求远程服务器执行生成
  5776. $client = new Client(['timeout' => 600, 'verify' => false]);
  5777. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5778. $response = $result->getBody()->getContents();
  5779. $response_arr = json_decode($response, true);
  5780. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5781. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5782. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5783. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5784. }
  5785. $arr = $response_arr['data'];
  5786. $subtitle_info = $arr['subtitle_info'];
  5787. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5788. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5789. return [
  5790. 'audio_url' => $arr['url'],
  5791. 'subtitle_info' => $subtitle_info,
  5792. 'audio_duration' => round($audio_duration, 2)
  5793. ];
  5794. } catch (\Exception $e) {
  5795. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5796. Utils::throwError('20003:' . $e->getMessage());
  5797. }
  5798. }
  5799. /**
  5800. * 获取角色库列表(支持文件夹递归查询)
  5801. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5802. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5803. */
  5804. public function globalProducts($data) {
  5805. $uid = Site::getUid();
  5806. $cpid = Site::getCpid();
  5807. $role = Site::getRole();
  5808. $id = getProp($data, 'id', 0);
  5809. $parent_id = getProp($data, 'parent_id', 0);
  5810. $product_name = getProp($data, 'product_name');
  5811. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5812. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5813. if (!$product) {
  5814. Utils::throwError('20003:请选择产品类型');
  5815. }
  5816. // 根据角色和is_public参数确定查询范围
  5817. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5818. // user角色:根据is_public参数筛选
  5819. $query_user_ids = [];
  5820. if ($role === 'admin') {
  5821. // admin获取所有个人库和公共库
  5822. $query_user_ids = [$uid, 0];
  5823. } else {
  5824. // user角色根据is_public参数筛选
  5825. if ($is_public == 2) {
  5826. // 个人库+公共库
  5827. $query_user_ids = [$uid, 0];
  5828. } elseif ($is_public == 0) {
  5829. // 仅个人库
  5830. $query_user_ids = [$uid];
  5831. } elseif ($is_public == 1) {
  5832. // 仅公共库
  5833. $query_user_ids = [0];
  5834. }
  5835. }
  5836. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5837. if ($id || $product_name) {
  5838. $query = DB::table('mp_products')
  5839. ->where('cpid', $cpid)
  5840. ->whereIn('user_id', $query_user_ids)
  5841. ->where('is_deleted', 0);
  5842. // 如果指定了 id,按 id 精确查询
  5843. if ($id) {
  5844. $query->where('id', $id);
  5845. }
  5846. // 如果指定了 product_name,按名称模糊查询
  5847. if ($product_name) {
  5848. $query->where('product_name', 'like', "%{$product_name}%");
  5849. }
  5850. // 如果指定了 product,添加筛选条件
  5851. if ($product) {
  5852. $query->where('product', $product);
  5853. }
  5854. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5855. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5856. ->get()
  5857. ->map(function($value) {
  5858. $value = (array)$value;
  5859. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5860. $value['type'] = (int)$value['type'];
  5861. $value['parent_id'] = (int)$value['parent_id'];
  5862. $value['level'] = (int)$value['level'];
  5863. $value['product'] = (int)($value['product'] ?? 1);
  5864. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5865. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5866. unset($value['user_id']);
  5867. return $value;
  5868. })
  5869. ->toArray();
  5870. return $result;
  5871. }
  5872. // 递归获取所有子目录和角色
  5873. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5874. }
  5875. /**
  5876. * 递归获取指定目录下的所有子目录和角色
  5877. * @param int $cpid 公司ID
  5878. * @param int $parent_id 父目录ID
  5879. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5880. * @param array $query_user_ids 用户ID数组(支持多个)
  5881. * @param int $current_uid 当前用户ID(用于排序)
  5882. * @return array
  5883. */
  5884. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5885. // 查询当前层级的所有项(文件夹和角色)
  5886. $query = DB::table('mp_products')
  5887. ->where('cpid', $cpid)
  5888. ->where('is_deleted', 0)
  5889. ->where('parent_id', $parent_id);
  5890. // 添加用户ID验证(支持多个user_id)
  5891. if (!empty($query_user_ids)) {
  5892. $query->whereIn('user_id', $query_user_ids);
  5893. }
  5894. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5895. if ($product) {
  5896. $query->where('product', $product);
  5897. }
  5898. // 排序规则:
  5899. // 1. 文件夹在前(type DESC)
  5900. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5901. // 3. 其他排序规则
  5902. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5903. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5904. ->get();
  5905. $result = [];
  5906. foreach ($items as $item) {
  5907. $itemArray = [
  5908. 'id' => $item->id,
  5909. 'type' => (int)$item->type,
  5910. 'parent_id' => (int)$item->parent_id,
  5911. 'level' => (int)$item->level,
  5912. 'product_name' => $item->product_name,
  5913. 'url' => $item->url,
  5914. 'pic_prompt' => $item->pic_prompt ?? '',
  5915. 'three_view_image_url' => $item->three_view_image_url,
  5916. 'product' => (int)($item->product ?? 1),
  5917. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5918. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5919. ];
  5920. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5921. // 如果是文件夹,递归获取其子项
  5922. if ($item->type == 2) {
  5923. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5924. if (!empty($children)) {
  5925. $itemArray['children'] = $children;
  5926. }
  5927. }
  5928. $result[] = $itemArray;
  5929. }
  5930. return $result;
  5931. }
  5932. /**
  5933. * 创建文件夹
  5934. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5935. * @return int 返回新建文件夹ID
  5936. */
  5937. public function createFolder($data) {
  5938. $uid = Site::getUid();
  5939. $cpid = Site::getCpid();
  5940. $role = Site::getRole();
  5941. $parent_id = getProp($data, 'parent_id', 0);
  5942. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5943. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5944. // 如果是公共库操作,需要admin权限
  5945. if ($is_public && $role !== 'admin') {
  5946. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5947. }
  5948. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5949. $store_uid = $is_public ? 0 : $uid;
  5950. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5951. $product = getProp($data, 'product');
  5952. if (!in_array($product, [1, 2, 3])) {
  5953. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5954. }
  5955. // 验证父文件夹
  5956. $parent_level = 0;
  5957. if ($parent_id > 0) {
  5958. $parent = DB::table('mp_products')
  5959. ->where('id', $parent_id)
  5960. ->where('cpid', $cpid)
  5961. ->where('user_id', $store_uid)
  5962. ->where('type', 2)
  5963. ->where('is_deleted', 0)
  5964. ->first();
  5965. if (!$parent) {
  5966. Utils::throwError('20003:父文件夹不存在');
  5967. }
  5968. // 检查父文件夹的 product 类型是否一致
  5969. if ($parent->product != $product) {
  5970. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5971. }
  5972. $parent_level = $parent->level;
  5973. // 检查层级限制(最多3层)
  5974. if ($parent_level >= 3) {
  5975. Utils::throwError('20003:文件夹层级不能超过3层');
  5976. }
  5977. }
  5978. // 检查当前目录下是否已存在空白文件夹
  5979. $empty_folder_exists = DB::table('mp_products')
  5980. ->where('parent_id', $parent_id)
  5981. ->where('cpid', $cpid)
  5982. ->where('user_id', $store_uid)
  5983. ->where('type', 2)
  5984. ->where('product', $product)
  5985. ->where('product_name', '新建文件夹')
  5986. ->where('is_deleted', 0)
  5987. ->exists();
  5988. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5989. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5990. }
  5991. // 创建文件夹
  5992. $folder_id = DB::table('mp_products')->insertGetId([
  5993. 'user_id' => $store_uid,
  5994. 'cpid' => $cpid,
  5995. 'type' => 2,
  5996. 'parent_id' => $parent_id,
  5997. 'level' => $parent_level + 1,
  5998. 'product_name' => $folder_name,
  5999. 'product' => $product,
  6000. 'sort_order' => time(), // 使用时间戳作为排序权重
  6001. 'is_deleted' => 0,
  6002. 'created_at' => date('Y-m-d H:i:s'),
  6003. 'updated_at' => date('Y-m-d H:i:s')
  6004. ]);
  6005. return [
  6006. 'id' => $folder_id,
  6007. 'type' => 2,
  6008. 'parent_id' => $parent_id,
  6009. 'level' => $parent_level + 1,
  6010. 'product_name' => $folder_name,
  6011. 'product' => $product,
  6012. ];
  6013. }
  6014. /**
  6015. * 重命名文件夹或角色
  6016. * @param array $data 包含 id、product_name(新名称)
  6017. * @return bool
  6018. */
  6019. public function renameFolder($data) {
  6020. $uid = Site::getUid();
  6021. $cpid = Site::getCpid();
  6022. $role = Site::getRole();
  6023. $id = getProp($data, 'id');
  6024. $new_name = getProp($data, 'product_name');
  6025. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6026. if (!$id || !$new_name) {
  6027. Utils::throwError('20003:参数不完整');
  6028. }
  6029. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6030. $query_uid = $is_public ? 0 : $uid;
  6031. // 如果是公共库操作,需要admin权限
  6032. if ($is_public && $role !== 'admin') {
  6033. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6034. }
  6035. // 检查是否存在
  6036. $item = DB::table('mp_products')
  6037. ->where('id', $id)
  6038. ->where('cpid', $cpid)
  6039. ->where('user_id', $query_uid)
  6040. ->where('is_deleted', 0)
  6041. ->first();
  6042. if (!$item) {
  6043. Utils::throwError('20003:项目不存在');
  6044. }
  6045. return DB::table('mp_products')
  6046. ->where('id', $id)
  6047. ->where('cpid', $cpid)
  6048. ->where('user_id', $query_uid)
  6049. ->update([
  6050. 'product_name' => $new_name,
  6051. 'updated_at' => date('Y-m-d H:i:s')
  6052. ]);
  6053. }
  6054. /**
  6055. * 移动角色或文件夹到指定文件夹
  6056. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6057. * @return bool
  6058. */
  6059. public function moveProductOrFolder($data) {
  6060. $uid = Site::getUid();
  6061. $cpid = Site::getCpid();
  6062. $role = Site::getRole();
  6063. $id = getProp($data, 'id');
  6064. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6065. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6066. if (!$id) {
  6067. Utils::throwError('20003:请选择要移动的项目');
  6068. }
  6069. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6070. $query_uid = $is_public ? 0 : $uid;
  6071. // 如果是公共库操作,需要admin权限
  6072. if ($is_public && $role !== 'admin') {
  6073. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6074. }
  6075. // 检查要移动的项目
  6076. $item = DB::table('mp_products')
  6077. ->where('id', $id)
  6078. ->where('cpid', $cpid)
  6079. ->where('user_id', $query_uid)
  6080. ->where('is_deleted', 0)
  6081. ->first();
  6082. if (!$item) {
  6083. Utils::throwError('20003:项目不存在');
  6084. }
  6085. // 验证目标文件夹
  6086. $target_level = 0;
  6087. $target_product = $item->product; // 默认使用当前项目的 product
  6088. if ($target_parent_id > 0) {
  6089. $target_parent = DB::table('mp_products')
  6090. ->where('id', $target_parent_id)
  6091. ->where('cpid', $cpid)
  6092. ->where('user_id', $query_uid)
  6093. ->where('type', 2)
  6094. ->where('is_deleted', 0)
  6095. ->first();
  6096. if (!$target_parent) {
  6097. Utils::throwError('20003:目标文件夹不存在');
  6098. }
  6099. // 检查 product 类型是否一致
  6100. if ($target_parent->product != $item->product) {
  6101. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6102. }
  6103. $target_level = $target_parent->level;
  6104. $target_product = $target_parent->product;
  6105. // 如果移动的是文件夹,需要检查层级
  6106. if ($item->type == 2) {
  6107. // 计算移动后的最大层级
  6108. $max_child_level = $this->getMaxChildLevel($id);
  6109. $depth = $max_child_level - $item->level;
  6110. if ($target_level + 1 + $depth > 3) {
  6111. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6112. }
  6113. // 不能移动到自己或自己的子文件夹下
  6114. if ($this->isDescendant($target_parent_id, $id)) {
  6115. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6116. }
  6117. }
  6118. }
  6119. // 更新父文件夹和层级
  6120. $new_level = $target_level + 1;
  6121. DB::table('mp_products')
  6122. ->where('id', $id)
  6123. ->update([
  6124. 'parent_id' => $target_parent_id,
  6125. 'level' => $new_level,
  6126. 'updated_at' => date('Y-m-d H:i:s')
  6127. ]);
  6128. // 如果是文件夹,需要递归更新所有子项的层级
  6129. if ($item->type == 2) {
  6130. $this->updateChildrenLevel($id, $new_level);
  6131. }
  6132. return true;
  6133. }
  6134. /**
  6135. * 获取文件夹下最大子层级
  6136. * @param int $folder_id
  6137. * @return int
  6138. */
  6139. private function getMaxChildLevel($folder_id) {
  6140. $max_level = DB::table('mp_products')
  6141. ->where('parent_id', $folder_id)
  6142. ->where('is_deleted', 0)
  6143. ->max('level');
  6144. if (!$max_level) {
  6145. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6146. }
  6147. // 递归查找子文件夹
  6148. $children = DB::table('mp_products')
  6149. ->where('parent_id', $folder_id)
  6150. ->where('type', 2)
  6151. ->where('is_deleted', 0)
  6152. ->pluck('id');
  6153. foreach ($children as $child_id) {
  6154. $child_max = $this->getMaxChildLevel($child_id);
  6155. if ($child_max > $max_level) {
  6156. $max_level = $child_max;
  6157. }
  6158. }
  6159. return $max_level;
  6160. }
  6161. /**
  6162. * 检查 target_id 是否是 folder_id 的后代
  6163. * @param int $target_id
  6164. * @param int $folder_id
  6165. * @return bool
  6166. */
  6167. private function isDescendant($target_id, $folder_id) {
  6168. if ($target_id == $folder_id) {
  6169. return true;
  6170. }
  6171. $parent = DB::table('mp_products')
  6172. ->where('id', $target_id)
  6173. ->where('is_deleted', 0)
  6174. ->first();
  6175. if (!$parent || $parent->parent_id == 0) {
  6176. return false;
  6177. }
  6178. return $this->isDescendant($parent->parent_id, $folder_id);
  6179. }
  6180. /**
  6181. * 递归更新子项层级
  6182. * @param int $parent_id
  6183. * @param int $parent_level
  6184. */
  6185. private function updateChildrenLevel($parent_id, $parent_level) {
  6186. $children = DB::table('mp_products')
  6187. ->where('parent_id', $parent_id)
  6188. ->where('is_deleted', 0)
  6189. ->get();
  6190. foreach ($children as $child) {
  6191. $new_level = $parent_level + 1;
  6192. DB::table('mp_products')
  6193. ->where('id', $child->id)
  6194. ->update([
  6195. 'level' => $new_level,
  6196. 'updated_at' => date('Y-m-d H:i:s')
  6197. ]);
  6198. // 如果是文件夹,继续递归
  6199. if ($child->type == 2) {
  6200. $this->updateChildrenLevel($child->id, $new_level);
  6201. }
  6202. }
  6203. }
  6204. /**
  6205. * 获取文件夹路径(面包屑导航)
  6206. * @param array $data 包含 folder_id
  6207. * @return array 返回路径数组
  6208. */
  6209. public function getFolderPath($data) {
  6210. $uid = Site::getUid();
  6211. $cpid = Site::getCpid();
  6212. $folder_id = getProp($data, 'id', 0);
  6213. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6214. if ($folder_id == 0) {
  6215. return [
  6216. ['id' => 0, 'name' => '根目录']
  6217. ];
  6218. }
  6219. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6220. $query_uid = $is_public ? 0 : $uid;
  6221. $path = [];
  6222. $current_id = $folder_id;
  6223. while ($current_id > 0) {
  6224. $folder = DB::table('mp_products')
  6225. ->where('id', $current_id)
  6226. ->where('cpid', $cpid)
  6227. ->where('user_id', $query_uid)
  6228. ->where('type', 2)
  6229. ->where('is_deleted', 0)
  6230. ->first();
  6231. if (!$folder) {
  6232. break;
  6233. }
  6234. array_unshift($path, [
  6235. 'id' => $folder->id,
  6236. 'name' => $folder->product_name
  6237. ]);
  6238. $current_id = $folder->parent_id;
  6239. }
  6240. // 添加根目录
  6241. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6242. return $path;
  6243. }
  6244. public function createProduct($data) {
  6245. $uid = Site::getUid();
  6246. $cpid = Site::getCpid();
  6247. $role = Site::getRole();
  6248. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6249. // 如果是公共库操作,需要admin权限
  6250. if ($is_public && $role !== 'admin') {
  6251. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6252. }
  6253. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6254. $store_uid = $is_public ? 0 : $uid;
  6255. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6256. $script_id = (int)getProp($data, 'script_id', 0);
  6257. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6258. if ($script_id && empty($episode_numbers)) {
  6259. Utils::throwError('20003:剧集序号不能为空');
  6260. }
  6261. if (!$script_id && !empty($episode_numbers)) {
  6262. Utils::throwError('20003:请提供剧本ID');
  6263. }
  6264. $product_name = trim(getProp($data, 'product_name'));
  6265. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6266. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6267. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6268. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6269. $url = trim(getProp($data, 'url'));
  6270. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6271. $versions = getProp($data, 'versions');
  6272. // 检查是否是正确的图片格式
  6273. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6274. $urlPath = parse_url($url, PHP_URL_PATH);
  6275. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6276. if (!in_array($extension, $allowedExtensions)) {
  6277. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6278. }
  6279. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6280. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6281. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6282. $product = getProp($data, 'product');
  6283. if (!in_array($product, [1, 2, 3])) {
  6284. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6285. }
  6286. // 获取父文件夹ID和层级
  6287. $parent_id = getProp($data, 'parent_id', 0);
  6288. $parent_level = 0;
  6289. if ($parent_id > 0) {
  6290. $parent = DB::table('mp_products')
  6291. ->where('id', $parent_id)
  6292. ->where('cpid', $cpid)
  6293. ->where('user_id', $store_uid)
  6294. ->where('type', 2)
  6295. ->where('is_deleted', 0)
  6296. ->first();
  6297. if (!$parent) {
  6298. Utils::throwError('20003:父文件夹不存在');
  6299. }
  6300. $parent_level = $parent->level;
  6301. }
  6302. // 创建资产并保存剧本资产关联关系(同一事务)
  6303. DB::beginTransaction();
  6304. try {
  6305. $id = DB::table('mp_products')->insertGetId([
  6306. 'user_id' => $store_uid,
  6307. 'cpid' => $cpid,
  6308. 'type' => 1, // 1=角色图片
  6309. 'parent_id' => $parent_id,
  6310. 'level' => $parent_level + 1,
  6311. 'product_name' => $product_name,
  6312. 'url' => $url,
  6313. 'pic_prompt' => $pic_prompt,
  6314. 'product' => $product,
  6315. 'versions' => json_encode($versions, 256),
  6316. 'sort_order' => time(), // 使用时间戳作为排序权重
  6317. 'created_at' => date('Y-m-d H:i:s'),
  6318. 'updated_at' => date('Y-m-d H:i:s')
  6319. ]);
  6320. if (!$id) Utils::throwError('20003:创建失败');
  6321. // 保存剧本资产关联关系
  6322. if ($script_id) {
  6323. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6324. }
  6325. DB::commit();
  6326. } catch (\Exception $e) {
  6327. DB::rollback();
  6328. throw $e;
  6329. }
  6330. return [
  6331. 'id' => $id,
  6332. 'type' => 1,
  6333. 'parent_id' => $parent_id,
  6334. 'level' => $parent_level + 1,
  6335. 'product_name' => $product_name,
  6336. 'url' => $url,
  6337. 'pic_prompt' => $pic_prompt,
  6338. 'product' => $product,
  6339. 'versions' => $versions
  6340. ];
  6341. }
  6342. public function editProduct($data) {
  6343. $uid = Site::getUid();
  6344. $cpid = Site::getCpid();
  6345. $role = Site::getRole();
  6346. $id = getProp($data, 'id');
  6347. if (!$id) Utils::throwError('20003:ID不能为空');
  6348. $versions = getProp($data, 'versions');
  6349. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6350. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6351. $script_id = (int)getProp($data, 'script_id', 0);
  6352. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6353. if ($script_id && empty($episode_numbers)) {
  6354. Utils::throwError('20003:剧集序号不能为空');
  6355. }
  6356. if (!$script_id && !empty($episode_numbers)) {
  6357. Utils::throwError('20003:请提供剧本ID');
  6358. }
  6359. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6360. $query_uid = $is_public ? 0 : $uid;
  6361. // 如果是公共库操作,需要admin权限
  6362. if ($is_public && $role !== 'admin') {
  6363. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6364. }
  6365. // 检查是否存在且属于当前用户或公共库
  6366. $role = DB::table('mp_products')
  6367. ->where('id', $id)
  6368. ->where('cpid', $cpid)
  6369. ->where('user_id', $query_uid)
  6370. ->where('type', 1)->first();
  6371. if (!$role) Utils::throwError('20003:记录不存在');
  6372. $updateData = [];
  6373. // $needVersionRecord = false; // 是否需要记录版本
  6374. // 名称
  6375. $product_name = trim(getProp($data, 'product_name'));
  6376. if ($product_name) {
  6377. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6378. $updateData['product_name'] = $product_name;
  6379. }
  6380. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6381. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6382. // 图片地址
  6383. $url = trim(getProp($data, 'url'));
  6384. if ($url) {
  6385. // 检查是否是正确的图片格式
  6386. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6387. $urlPath = parse_url($url, PHP_URL_PATH);
  6388. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6389. if (!in_array($extension, $allowedExtensions)) {
  6390. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6391. }
  6392. // // 如果 url 有变更,记录版本
  6393. // if ($url !== $role->url) {
  6394. // $needVersionRecord = true;
  6395. // }
  6396. $updateData['url'] = $url;
  6397. }
  6398. // 提示词
  6399. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6400. if ($pic_prompt) {
  6401. // // 如果 pic_prompt 有变更,记录版本
  6402. // if ($pic_prompt !== $role->pic_prompt) {
  6403. // $needVersionRecord = true;
  6404. // }
  6405. $updateData['pic_prompt'] = $pic_prompt;
  6406. }
  6407. if (empty($updateData) && !$script_id) {
  6408. Utils::throwError('20003:没有需要更新的数据');
  6409. }
  6410. // // 如果需要记录版本,将数据添加到 versions 数组
  6411. // if ($needVersionRecord) {
  6412. // // 获取现有的 versions 数据
  6413. // $versions = json_decode($role->versions, true) ?: [];
  6414. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6415. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6416. // if ($isFirstVersion) {
  6417. // $oldVersion = [
  6418. // 'url' => $role->url,
  6419. // 'description' => $role->pic_prompt,
  6420. // ];
  6421. // // 旧版本添加到数组末尾
  6422. // $versions[] = $oldVersion;
  6423. // }
  6424. // // 构建新版本(变更后)
  6425. // $newVersion = [
  6426. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6427. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6428. // ];
  6429. // // 检查新版本是否已存在于历史版本中
  6430. // $existingIndex = -1;
  6431. // foreach ($versions as $index => $version) {
  6432. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6433. // $existingIndex = $index;
  6434. // break;
  6435. // }
  6436. // }
  6437. // if ($existingIndex !== -1) {
  6438. // // 如果已存在,移除旧的位置
  6439. // array_splice($versions, $existingIndex, 1);
  6440. // }
  6441. // // 新版本添加到数组开头(最新的在前)
  6442. // array_unshift($versions, $newVersion);
  6443. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6444. // // if (count($versions) > 10) {
  6445. // // $versions = array_slice($versions, 0, 10);
  6446. // // }
  6447. // $updateData['versions'] = json_encode($versions, 256);
  6448. // }
  6449. if ($versions) {
  6450. $updateData['versions'] = json_encode($versions, 256);
  6451. }
  6452. if (!empty($updateData)) {
  6453. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6454. }
  6455. // 更新资产并保存剧本资产关联关系(同一事务)
  6456. DB::beginTransaction();
  6457. try {
  6458. $updated = true;
  6459. if (!empty($updateData)) {
  6460. $updated = DB::table('mp_products')
  6461. ->where('cpid', $cpid)
  6462. ->where('id', $id)
  6463. ->update($updateData);
  6464. }
  6465. // 保存剧本资产关联关系
  6466. if ($script_id) {
  6467. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6468. }
  6469. DB::commit();
  6470. } catch (\Exception $e) {
  6471. DB::rollback();
  6472. throw $e;
  6473. }
  6474. return $updated;
  6475. }
  6476. /**
  6477. * 保存单一资产与剧本剧集的关联关系
  6478. *
  6479. * @param int $product_id 资产ID
  6480. * @param int $script_id 剧本ID
  6481. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6482. * @return int 新增关联数量
  6483. */
  6484. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6485. $uid = Site::getUid();
  6486. // 验证剧本是否存在
  6487. $script = DB::table('mp_scripts')
  6488. ->where('id', $script_id)
  6489. ->where('is_deleted', 0)
  6490. ->first();
  6491. if (!$script) {
  6492. Utils::throwError('20003:剧本不存在');
  6493. }
  6494. // 验证剧本归属:只能关联自己的剧本
  6495. if ((int)$script->user_id !== (int)$uid) {
  6496. Utils::throwError('20003:只能添加到自己的剧本');
  6497. }
  6498. // 使用 splitContent 拆分剧本内容获取总集数
  6499. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6500. // 解析剧集序号(数组)
  6501. $episodes = [];
  6502. foreach ($episode_numbers as $item) {
  6503. if (is_array($item)) {
  6504. continue;
  6505. }
  6506. $item = trim((string)$item);
  6507. if ($item === '' || !is_numeric($item)) {
  6508. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6509. }
  6510. $episodes[] = (int)$item;
  6511. }
  6512. // 去重并校验序号范围(序号从1开始)
  6513. $episodes = array_values(array_unique($episodes));
  6514. if (empty($episodes)) {
  6515. Utils::throwError('20003:剧集序号不能为空');
  6516. }
  6517. foreach ($episodes as $episode) {
  6518. if ($episode < 1 || $episode > $totalEpisodes) {
  6519. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6520. }
  6521. }
  6522. $now = now();
  6523. // 过滤已存在的关联,避免重复
  6524. $existingEpisodes = DB::table('mp_script_product_mappings')
  6525. ->where('script_id', $script_id)
  6526. ->where('product_id', $product_id)
  6527. ->whereIn('episode_number', $episodes)
  6528. ->pluck('episode_number')
  6529. ->all();
  6530. $mappingRecords = [];
  6531. foreach ($episodes as $episode) {
  6532. if (in_array($episode, $existingEpisodes)) {
  6533. continue;
  6534. }
  6535. $mappingRecords[] = [
  6536. 'script_id' => $script_id,
  6537. 'product_id' => $product_id,
  6538. 'episode_number' => $episode,
  6539. 'created_at' => $now,
  6540. 'updated_at' => $now,
  6541. ];
  6542. }
  6543. $insertedCount = 0;
  6544. if (!empty($mappingRecords)) {
  6545. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6546. }
  6547. return $insertedCount;
  6548. }
  6549. /**
  6550. * 规范化剧集序号参数,统一为数组
  6551. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6552. *
  6553. * @param mixed $episode_number 剧集序号参数
  6554. * @return array
  6555. */
  6556. private function normalizeEpisodeNumbers($episode_number) {
  6557. if (!is_array($episode_number)) {
  6558. $episode_number = explode(',', (string)$episode_number);
  6559. }
  6560. $items = [];
  6561. foreach ($episode_number as $item) {
  6562. if (is_array($item)) {
  6563. continue;
  6564. }
  6565. foreach (explode(',', (string)$item) as $part) {
  6566. $part = trim($part);
  6567. if ($part !== '') {
  6568. $items[] = $part;
  6569. }
  6570. }
  6571. }
  6572. return $items;
  6573. }
  6574. /**
  6575. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6576. *
  6577. * @param object $script 剧本记录
  6578. * @return int 总集数
  6579. */
  6580. private function getScriptTotalEpisodeCount($script) {
  6581. if (empty($script->content)) {
  6582. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6583. }
  6584. $totalEpisodes = count(splitContent($script->content));
  6585. if ($totalEpisodes < 1) {
  6586. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6587. }
  6588. return $totalEpisodes;
  6589. }
  6590. /**
  6591. * 获取剧本总集数
  6592. *
  6593. * @param array $data 包含 script_id(剧本ID)
  6594. * @return array
  6595. */
  6596. public function getScriptTotalEpisodes($data) {
  6597. $script_id = (int)getProp($data, 'script_id', 0);
  6598. if (!$script_id) {
  6599. Utils::throwError('20003:请提供剧本ID');
  6600. }
  6601. // 验证剧本是否存在
  6602. $script = DB::table('mp_scripts')
  6603. ->where('id', $script_id)
  6604. ->where('is_deleted', 0)
  6605. ->first();
  6606. if (!$script) {
  6607. Utils::throwError('20003:剧本不存在');
  6608. }
  6609. return [
  6610. 'script_id' => $script_id,
  6611. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6612. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6613. ];
  6614. }
  6615. /**
  6616. * 获取角色版本历史
  6617. * @param array $data 包含 id(角色ID)
  6618. * @return array 返回版本历史列表
  6619. */
  6620. public function getProductVersions($data) {
  6621. $cpid = Site::getCpid();
  6622. $id = getProp($data, 'id');
  6623. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6624. $role = DB::table('mp_products')
  6625. ->where('id', $id)
  6626. ->where('cpid', $cpid)
  6627. ->where('type', 1)
  6628. ->first();
  6629. if (!$role) Utils::throwError('20003:角色不存在');
  6630. // 获取版本历史
  6631. $versions = json_decode($role->versions, true) ?: [];
  6632. // 添加当前版本作为最新版本
  6633. $currentVersion = [
  6634. 'version' => 0, // 0 表示当前版本
  6635. 'url' => $role->url,
  6636. 'pic_prompt' => $role->pic_prompt,
  6637. 'updated_at' => $role->updated_at,
  6638. 'is_current' => true
  6639. ];
  6640. array_unshift($versions, $currentVersion);
  6641. return $versions;
  6642. }
  6643. /**
  6644. * 恢复到指定版本
  6645. * @param array $data 包含 id(角色ID)、version(版本号)
  6646. * @return bool
  6647. */
  6648. public function restoreProductVersion($data) {
  6649. $uid = Site::getUid();
  6650. $cpid = Site::getCpid();
  6651. $id = getProp($data, 'id');
  6652. $version = getProp($data, 'version');
  6653. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6654. if (!$version) Utils::throwError('20003:版本号不能为空');
  6655. $role = DB::table('mp_products')
  6656. ->where('id', $id)
  6657. ->where('cpid', $cpid)
  6658. ->where('type', 1)
  6659. ->first();
  6660. if (!$role) Utils::throwError('20003:角色不存在');
  6661. // 获取版本历史
  6662. $versions = json_decode($role->versions, true) ?: [];
  6663. // 查找指定版本
  6664. $targetVersion = null;
  6665. foreach ($versions as $v) {
  6666. if ($v['version'] == $version) {
  6667. $targetVersion = $v;
  6668. break;
  6669. }
  6670. }
  6671. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6672. // 先将当前版本保存到历史
  6673. $newVersion = [
  6674. 'version' => count($versions) + 1,
  6675. 'url' => $role->url,
  6676. 'pic_prompt' => $role->pic_prompt,
  6677. 'updated_at' => date('Y-m-d H:i:s'),
  6678. 'updated_by' => $uid
  6679. ];
  6680. array_unshift($versions, $newVersion);
  6681. // 限制版本数量
  6682. if (count($versions) > 10) {
  6683. $versions = array_slice($versions, 0, 10);
  6684. }
  6685. // 恢复到指定版本
  6686. return DB::table('mp_products')
  6687. ->where('id', $id)
  6688. ->where('cpid', $cpid)
  6689. ->update([
  6690. 'url' => $targetVersion['url'],
  6691. 'pic_prompt' => $targetVersion['pic_prompt'],
  6692. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6693. 'updated_at' => date('Y-m-d H:i:s')
  6694. ]);
  6695. }
  6696. public function deleteProduct($data) {
  6697. $uid = Site::getUid();
  6698. $cpid = Site::getCpid();
  6699. $role = Site::getRole();
  6700. $id = getProp($data, 'id');
  6701. if (!$id) Utils::throwError('20003:ID不能为空');
  6702. $ids = explode(',', $id);
  6703. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6704. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6705. $query_uid = $is_public ? 0 : $uid;
  6706. // 如果是公共库操作,需要admin权限
  6707. if ($is_public && $role !== 'admin') {
  6708. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6709. }
  6710. // 检查是否存在且属于当前用户或公共库
  6711. $role = DB::table('mp_products')
  6712. ->whereIn('id', $ids)
  6713. ->where('cpid', $cpid)
  6714. ->where('user_id', $query_uid)
  6715. ->get();
  6716. if (!$role) Utils::throwError('20003:记录不存在');
  6717. return DB::table('mp_products')
  6718. ->where('cpid', $cpid)
  6719. ->where('user_id', $query_uid)
  6720. ->whereIn('id', $ids)
  6721. ->update([
  6722. 'is_deleted' => 1,
  6723. 'updated_at' => date('Y-m-d H:i:s')
  6724. ]);
  6725. }
  6726. public function generateThreeView($data) {
  6727. $uid = Site::getUid();
  6728. $cpid = Site::getCpid();
  6729. $role = Site::getRole();
  6730. $id = getProp($data, 'id');
  6731. if (!$id) Utils::throwError('20003:ID不能为空');
  6732. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6733. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6734. $query_uid = $is_public ? 0 : $uid;
  6735. // 如果是公共库操作,需要admin权限
  6736. if ($is_public && $role !== 'admin') {
  6737. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6738. }
  6739. // 检查是否存在且属于当前用户或公共库
  6740. $product = DB::table('mp_products')
  6741. ->where('id', $id)
  6742. ->where('cpid', $cpid)
  6743. ->where('user_id', $query_uid)
  6744. ->where('type', 1)->first();
  6745. if (!$product) Utils::throwError('20003:资产不存在');
  6746. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6747. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6748. if (!$ref_img_url) {
  6749. // 如果没有传入参考图,使用角色表中的图片
  6750. $ref_img_url = $product->url ?? '';
  6751. if (!$ref_img_url) {
  6752. Utils::throwError('20003:参考图不能为空');
  6753. }
  6754. }
  6755. $pic_prompt = getProp($product, 'pic_prompt');
  6756. if ($pic_prompt) {
  6757. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6758. }
  6759. // 检查参考图是否是正确的图片格式
  6760. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6761. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6762. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6763. if (!in_array($extension, $allowedExtensions)) {
  6764. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6765. }
  6766. // 处理图片模型
  6767. $model = getProp($data, 'model');
  6768. if (!$model) {
  6769. // 使用默认模型
  6770. $model = 'doubao-seedream-5-0-lite-260128';
  6771. }
  6772. // 验证模型是否在可用模型表中
  6773. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6774. Utils::throwError('20003:该模型已不可用,请更换!');
  6775. }
  6776. $ratio = getProp($data, 'ratio', '16:9');
  6777. $resolution = getProp($data, 'resolution', '2k');
  6778. // 定义分辨率和宽高比对应的尺寸映射表
  6779. $sizeMap = [
  6780. '2k' => [
  6781. '1:1' => ['width' => 2048, 'height' => 2048],
  6782. '4:3' => ['width' => 2304, 'height' => 1728],
  6783. '3:4' => ['width' => 1728, 'height' => 2304],
  6784. '16:9' => ['width' => 2848, 'height' => 1600],
  6785. '9:16' => ['width' => 1600, 'height' => 2848],
  6786. '3:2' => ['width' => 2496, 'height' => 1664],
  6787. '2:3' => ['width' => 1664, 'height' => 2496],
  6788. '21:9' => ['width' => 3136, 'height' => 1344],
  6789. ],
  6790. '3k' => [
  6791. '1:1' => ['width' => 3072, 'height' => 3072],
  6792. '4:3' => ['width' => 3456, 'height' => 2592],
  6793. '3:4' => ['width' => 2592, 'height' => 3456],
  6794. '16:9' => ['width' => 4096, 'height' => 2304],
  6795. '9:16' => ['width' => 2304, 'height' => 4096],
  6796. '2:3' => ['width' => 2496, 'height' => 3744],
  6797. '3:2' => ['width' => 3744, 'height' => 2496],
  6798. '21:9' => ['width' => 4704, 'height' => 2016],
  6799. ],
  6800. '4k' => [
  6801. '1:1' => ['width' => 4096, 'height' => 4096],
  6802. '3:4' => ['width' => 3520, 'height' => 4704],
  6803. '4:3' => ['width' => 4704, 'height' => 3520],
  6804. '16:9' => ['width' => 5504, 'height' => 3040],
  6805. '9:16' => ['width' => 3040, 'height' => 5504],
  6806. '2:3' => ['width' => 3328, 'height' => 4992],
  6807. '3:2' => ['width' => 4992, 'height' => 3328],
  6808. '21:9' => ['width' => 6240, 'height' => 2656],
  6809. ],
  6810. ];
  6811. // 参数验证
  6812. $resolution = strtolower($resolution);
  6813. if (!isset($sizeMap[$resolution])) {
  6814. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6815. }
  6816. if (!isset($sizeMap[$resolution][$ratio])) {
  6817. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6818. }
  6819. // 根据 ratio 和 resolution 确定宽高
  6820. $width = $sizeMap[$resolution][$ratio]['width'];
  6821. $height = $sizeMap[$resolution][$ratio]['height'];
  6822. try {
  6823. // 创建图片生成任务
  6824. $params = [
  6825. 'prompt' => $prompt,
  6826. 'model' => $model,
  6827. 'ref_img_urls' => [$ref_img_url],
  6828. 'width' => $width,
  6829. 'height' => $height
  6830. ];
  6831. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6832. $task_id = $task->id;
  6833. if (!$task_id) {
  6834. Utils::throwError('20003:创建图片生成任务失败');
  6835. }
  6836. // 轮询获取结果
  6837. // 只查询数据库,不调用API,不更新任务表
  6838. $start_time = time();
  6839. $timeout = 1800;
  6840. $img_url = '';
  6841. while (time() - $start_time < $timeout) {
  6842. sleep(5);
  6843. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6844. $task = DB::table('mp_generate_pic_tasks')
  6845. ->where('id', $task_id)
  6846. ->first();
  6847. if (!$task) {
  6848. Utils::throwError('20003:任务不存在');
  6849. }
  6850. if ($task->status === 'success' && $task->result_url) {
  6851. $result_urls = is_string($task->result_url)
  6852. ? json_decode($task->result_url, true)
  6853. : $task->result_url;
  6854. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6855. break;
  6856. } elseif ($task->status === 'failed') {
  6857. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6858. }
  6859. // 其他状态继续轮询
  6860. }
  6861. if (empty($img_url)) {
  6862. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6863. }
  6864. // 更新 mp_products 表(不是任务表)
  6865. DB::table('mp_products')
  6866. ->where('id', $id)
  6867. ->where('cpid', $cpid)
  6868. ->update([
  6869. 'three_view_image_url' => $img_url,
  6870. 'updated_at' => date('Y-m-d H:i:s')
  6871. ]);
  6872. return ['three_view_image_url' => $img_url];
  6873. } catch (\Exception $e) {
  6874. dLog('anime')->error('生成三视图失败', [
  6875. 'error' => $e->getMessage()
  6876. ]);
  6877. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6878. Utils::throwError('20003:' . $e->getMessage());
  6879. }
  6880. }
  6881. /**
  6882. * 推送(复制)资产或文件夹到目标位置
  6883. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6884. * @return array 返回推送结果
  6885. */
  6886. public function pushProductOrFolder($data) {
  6887. $uid = Site::getUid();
  6888. $cpid = Site::getCpid();
  6889. $role = Site::getRole();
  6890. $product_id = getProp($data, 'product_id');
  6891. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6892. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6893. if (!$product_id) {
  6894. Utils::throwError('20003:请选择要推送的项目');
  6895. }
  6896. // 查询源项目(只通过cpid查询,不限制user_id)
  6897. $sourceItem = DB::table('mp_products')
  6898. ->where('id', $product_id)
  6899. ->where('cpid', $cpid)
  6900. ->where('is_deleted', 0)
  6901. ->first();
  6902. if (!$sourceItem) {
  6903. Utils::throwError('20003:要推送的项目不存在');
  6904. }
  6905. // 通过user_id判断源是公共库还是个人库
  6906. $source_uid = $sourceItem->user_id;
  6907. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6908. // 验证目标文件夹并确定目标是公共库还是个人库
  6909. $target_level = 0;
  6910. $target_uid = $uid; // 默认推送到个人库
  6911. $target_is_public = 0;
  6912. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6913. if ($target_parent_id > 0) {
  6914. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6915. $targetParent = DB::table('mp_products')
  6916. ->where('id', $target_parent_id)
  6917. ->where('cpid', $cpid)
  6918. ->where('type', 2)
  6919. ->where('is_deleted', 0)
  6920. ->first();
  6921. if (!$targetParent) {
  6922. Utils::throwError('20003:目标文件夹不存在');
  6923. }
  6924. // 通过user_id判断目标是公共库还是个人库
  6925. $target_level = $targetParent->level;
  6926. $target_uid = $targetParent->user_id;
  6927. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6928. // 使用目标文件夹的 product 类型
  6929. $final_product_type = $targetParent->product;
  6930. }
  6931. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6932. else {
  6933. $push_to_public = getProp($data, 'push_to_public');
  6934. if ($push_to_public === '') {
  6935. Utils::throwError('20003:请选择是否推送到公共库');
  6936. }
  6937. if ($push_to_public) {
  6938. $target_uid = 0;
  6939. $target_is_public = 1;
  6940. }
  6941. // 推送到根目录时,必须指定 product 类型
  6942. if ($target_product === null || $target_product === '') {
  6943. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6944. }
  6945. $final_product_type = $target_product;
  6946. }
  6947. // 如果目标是公共库,需要admin权限
  6948. if ($target_is_public && $role !== 'admin') {
  6949. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6950. }
  6951. // 权限验证:验证是否符合允许的推送规则
  6952. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6953. try {
  6954. DB::beginTransaction();
  6955. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6956. if ($sourceItem->type == 1) {
  6957. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6958. DB::commit();
  6959. return [
  6960. 'product_id' => $newId,
  6961. ];
  6962. }
  6963. // 如果是文件夹,递归复制(支持跨类型推送)
  6964. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6965. DB::commit();
  6966. return [
  6967. 'product_id' => $newFolderId,
  6968. ];
  6969. } catch (\Exception $e) {
  6970. DB::rollBack();
  6971. dLog('anime')->error('推送失败', [
  6972. 'error' => $e->getMessage(),
  6973. 'product_id' => $product_id
  6974. ]);
  6975. Utils::throwError('20003:' . $e->getMessage());
  6976. }
  6977. }
  6978. /**
  6979. * 验证推送权限
  6980. * 允许的推送规则:
  6981. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6982. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6983. * 3. 公共库推送给公共库(公共库 → 公共库)
  6984. *
  6985. * @param int $source_uid 源的user_id
  6986. * @param int $target_uid 目标的user_id
  6987. * @param int $current_uid 当前用户ID
  6988. * @throws \Exception
  6989. */
  6990. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6991. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6992. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6993. return; // 允许
  6994. }
  6995. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6996. if ($source_uid == 0 && $target_uid == $current_uid) {
  6997. return; // 允许
  6998. }
  6999. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7000. if ($source_uid == 0 && $target_uid == 0) {
  7001. return; // 允许
  7002. }
  7003. // 其他情况都不允许
  7004. if ($source_uid != 0 && $source_uid != $current_uid) {
  7005. // 源是别人的个人库
  7006. Utils::throwError('20003:无权限访问该资产');
  7007. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7008. // 个人库推送给公共库(不允许)
  7009. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7010. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7011. // 不同用户的个人库之间推送(不允许)
  7012. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7013. } else {
  7014. // 其他未知情况
  7015. Utils::throwError('20003:不允许的推送操作');
  7016. }
  7017. }
  7018. /**
  7019. * 复制单个资产
  7020. * @param object $sourceProduct 源资产对象
  7021. * @param int $targetParentId 目标父文件夹ID
  7022. * @param int $targetLevel 目标层级
  7023. * @param int $cpid 公司ID
  7024. * @param int $targetUid 目标用户ID
  7025. * @return int 返回新资产ID
  7026. */
  7027. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7028. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7029. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7030. $newProductData = [
  7031. 'user_id' => $targetUid,
  7032. 'cpid' => $cpid,
  7033. 'type' => 1,
  7034. 'parent_id' => $targetParentId,
  7035. 'level' => $targetLevel,
  7036. 'product_name' => $sourceProduct->product_name,
  7037. 'url' => $sourceProduct->url,
  7038. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7039. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7040. 'product' => $finalProductType,
  7041. 'versions' => $sourceProduct->versions ?? '',
  7042. 'sort_order' => time(),
  7043. 'is_deleted' => 0,
  7044. 'created_at' => date('Y-m-d H:i:s'),
  7045. 'updated_at' => date('Y-m-d H:i:s')
  7046. ];
  7047. return DB::table('mp_products')->insertGetId($newProductData);
  7048. }
  7049. /**
  7050. * 递归复制文件夹及其子项
  7051. * @param object $sourceFolder 源文件夹对象
  7052. * @param int $targetParentId 目标父文件夹ID
  7053. * @param int $targetLevel 目标层级
  7054. * @param int $cpid 公司ID
  7055. * @param int $targetUid 目标用户ID
  7056. * @param int $sourceUid 源用户ID
  7057. * @return int 返回新文件夹ID
  7058. */
  7059. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7060. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7061. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7062. // 创建新文件夹
  7063. $newFolderData = [
  7064. 'user_id' => $targetUid,
  7065. 'cpid' => $cpid,
  7066. 'type' => 2,
  7067. 'parent_id' => $targetParentId,
  7068. 'level' => $targetLevel,
  7069. 'product_name' => $sourceFolder->product_name,
  7070. 'product' => $finalProductType,
  7071. 'sort_order' => time(),
  7072. 'is_deleted' => 0,
  7073. 'created_at' => date('Y-m-d H:i:s'),
  7074. 'updated_at' => date('Y-m-d H:i:s')
  7075. ];
  7076. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7077. // 获取源文件夹下的所有子项
  7078. $children = DB::table('mp_products')
  7079. ->where('parent_id', $sourceFolder->id)
  7080. ->where('cpid', $cpid)
  7081. ->where('user_id', $sourceUid)
  7082. ->where('is_deleted', 0)
  7083. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7084. ->get();
  7085. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7086. foreach ($children as $child) {
  7087. if ($child->type == 1) {
  7088. // 资产
  7089. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7090. } else {
  7091. // 文件夹
  7092. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7093. }
  7094. }
  7095. return $newFolderId;
  7096. }
  7097. /**
  7098. * 保存剧本资产关联关系
  7099. * @param array $data 请求参数
  7100. * @return bool
  7101. */
  7102. public function saveScriptProducts($data) {
  7103. $uid = Site::getUid();
  7104. $cpid = Site::getCpid();
  7105. $script_id = getProp($data, 'script_id');
  7106. $products = getProp($data, 'products', []);
  7107. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  7108. if (!$script_id) {
  7109. Utils::throwError('20003:请提供剧本ID');
  7110. }
  7111. // 验证剧本是否存在
  7112. $script = DB::table('mp_scripts')
  7113. ->where('id', $script_id)
  7114. ->where('is_deleted', 0)
  7115. ->first();
  7116. if (!$script) {
  7117. Utils::throwError('20003:剧本不存在');
  7118. }
  7119. // 处理图片模型
  7120. $model = getProp($data, 'model');
  7121. if (!$model) {
  7122. // 使用默认模型
  7123. $model = 'doubao-seedream-5-0-lite-260128';
  7124. }
  7125. // 验证模型是否在可用模型表中
  7126. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7127. Utils::throwError('20003:该模型已不可用,请更换!');
  7128. }
  7129. $ratio = getProp($data, 'ratio', '9:16');
  7130. $resolution = getProp($data, 'resolution', '2k');
  7131. // 定义分辨率和宽高比对应的尺寸映射表
  7132. $sizeMap = [
  7133. '2k' => [
  7134. '1:1' => ['width' => 2048, 'height' => 2048],
  7135. '4:3' => ['width' => 2304, 'height' => 1728],
  7136. '3:4' => ['width' => 1728, 'height' => 2304],
  7137. '16:9' => ['width' => 2848, 'height' => 1600],
  7138. '9:16' => ['width' => 1600, 'height' => 2848],
  7139. '3:2' => ['width' => 2496, 'height' => 1664],
  7140. '2:3' => ['width' => 1664, 'height' => 2496],
  7141. '21:9' => ['width' => 3136, 'height' => 1344],
  7142. ],
  7143. '3k' => [
  7144. '1:1' => ['width' => 3072, 'height' => 3072],
  7145. '4:3' => ['width' => 3456, 'height' => 2592],
  7146. '3:4' => ['width' => 2592, 'height' => 3456],
  7147. '16:9' => ['width' => 4096, 'height' => 2304],
  7148. '9:16' => ['width' => 2304, 'height' => 4096],
  7149. '2:3' => ['width' => 2496, 'height' => 3744],
  7150. '3:2' => ['width' => 3744, 'height' => 2496],
  7151. '21:9' => ['width' => 4704, 'height' => 2016],
  7152. ],
  7153. '4k' => [
  7154. '1:1' => ['width' => 4096, 'height' => 4096],
  7155. '3:4' => ['width' => 3520, 'height' => 4704],
  7156. '4:3' => ['width' => 4704, 'height' => 3520],
  7157. '16:9' => ['width' => 5504, 'height' => 3040],
  7158. '9:16' => ['width' => 3040, 'height' => 5504],
  7159. '2:3' => ['width' => 3328, 'height' => 4992],
  7160. '3:2' => ['width' => 4992, 'height' => 3328],
  7161. '21:9' => ['width' => 6240, 'height' => 2656],
  7162. ],
  7163. ];
  7164. // 参数验证
  7165. $resolution = strtolower($resolution);
  7166. if (!isset($sizeMap[$resolution])) {
  7167. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7168. }
  7169. if (!isset($sizeMap[$resolution][$ratio])) {
  7170. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7171. }
  7172. // 根据 ratio 和 resolution 确定宽高
  7173. $width = $sizeMap[$resolution][$ratio]['width'];
  7174. $height = $sizeMap[$resolution][$ratio]['height'];
  7175. $script_name = $script->script_name ?? 'script_' . $script_id;
  7176. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  7177. $taskCenterId = $this->createScriptProductTaskCenter(
  7178. $uid,
  7179. $cpid,
  7180. $script_id,
  7181. $products,
  7182. $model,
  7183. $ratio,
  7184. $resolution,
  7185. $auto_generate_images
  7186. );
  7187. // 检查是否已经有该剧本的资产数据
  7188. $existingMappings = DB::table('mp_script_product_mappings')
  7189. ->where('script_id', $script_id)
  7190. ->get();
  7191. if ($existingMappings->isNotEmpty()) {
  7192. // 已存在资产映射,检查是否所有资产都有图片生成任务
  7193. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  7194. // 查询这些资产的图片生成任务状态
  7195. $productsWithTasks = DB::table('mp_products')
  7196. ->whereIn('id', $productIds)
  7197. ->where('is_deleted', 0)
  7198. ->get();
  7199. $productTaskMap = [];
  7200. $typeFolderIds = [];
  7201. $hasAllTasks = true;
  7202. foreach ($productsWithTasks as $product) {
  7203. // 收集类型文件夹ID
  7204. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  7205. $parentFolder = DB::table('mp_products')
  7206. ->where('id', $product->parent_id)
  7207. ->where('type', 2)
  7208. ->first();
  7209. if ($parentFolder) {
  7210. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  7211. }
  7212. }
  7213. // 检查是否有图片生成任务
  7214. if (!empty($product->pic_task_id)) {
  7215. $productTaskMap[$product->id] = $product->pic_task_id;
  7216. } else if($product->url && $product->pic_task_status == '生成成功') {
  7217. continue;
  7218. } else {
  7219. // 有资产没有图片任务
  7220. $hasAllTasks = false;
  7221. }
  7222. }
  7223. // 如果所有资产都有任务ID,直接轮询返回结果
  7224. if ($hasAllTasks && !empty($productTaskMap)) {
  7225. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  7226. 'script_id' => $script_id,
  7227. 'script_name' => $script_name,
  7228. 'product_count' => count($productTaskMap)
  7229. ]);
  7230. // 直接返回 SSE 流轮询结果
  7231. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7232. }
  7233. // 如果部分资产没有任务ID,只为这些资产创建任务
  7234. if (!$hasAllTasks && $auto_generate_images) {
  7235. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  7236. 'script_id' => $script_id,
  7237. 'script_name' => $script_name
  7238. ]);
  7239. // 开启事务
  7240. DB::beginTransaction();
  7241. try {
  7242. foreach ($productsWithTasks as $product) {
  7243. // 跳过已有任务的资产
  7244. if (!empty($product->pic_task_id)) {
  7245. continue;
  7246. }
  7247. // 跳过没有提示词的资产
  7248. if (empty($product->pic_prompt)) {
  7249. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7250. 'product_id' => $product->id,
  7251. 'product_name' => $product->product_name
  7252. ]);
  7253. continue;
  7254. }
  7255. try {
  7256. // 创建图片生成任务
  7257. $params = [
  7258. 'prompt' => $product->pic_prompt,
  7259. 'model' => $model,
  7260. 'ref_img_urls' => [],
  7261. 'width' => $width,
  7262. 'height' => $height
  7263. ];
  7264. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7265. $task_id = $task->id;
  7266. if ($task_id) {
  7267. $productTaskMap[$product->id] = $task_id;
  7268. // 在事务中更新资产表的任务ID和状态
  7269. DB::table('mp_products')
  7270. ->where('id', $product->id)
  7271. ->update([
  7272. 'pic_task_id' => $task_id,
  7273. 'pic_task_status' => '生成中',
  7274. 'updated_at' => now()
  7275. ]);
  7276. dLog('anime')->info('为已存在资产创建图片生成任务', [
  7277. 'product_id' => $product->id,
  7278. 'task_id' => $task_id
  7279. ]);
  7280. }
  7281. } catch (\Exception $e) {
  7282. dLog('anime')->error('创建资产图片生成任务失败', [
  7283. 'product_id' => $product->id,
  7284. 'error' => $e->getMessage()
  7285. ]);
  7286. // 标记为失败(仍在事务中)
  7287. DB::table('mp_products')
  7288. ->where('id', $product->id)
  7289. ->update([
  7290. 'pic_task_status' => '生成失败',
  7291. 'updated_at' => now()
  7292. ]);
  7293. }
  7294. }
  7295. // 提交事务
  7296. DB::commit();
  7297. // 如果有新创建的任务,返回 SSE 流
  7298. if (!empty($productTaskMap)) {
  7299. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7300. }
  7301. } catch (\Exception $e) {
  7302. // 回滚事务
  7303. DB::rollback();
  7304. dLog('anime')->error('为已存在资产创建图片任务失败', [
  7305. 'script_id' => $script_id,
  7306. 'error' => $e->getMessage()
  7307. ]);
  7308. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  7309. }
  7310. }
  7311. // 如果不需要生成图片,返回已存在的信息
  7312. $resultData = [
  7313. 'success' => true,
  7314. 'message' => '剧本资产已存在',
  7315. 'script_id' => $script_id,
  7316. 'script_name' => $script_name,
  7317. 'type_folder_ids' => $typeFolderIds,
  7318. 'existing_products' => count($productIds),
  7319. 'tasks_count' => count($productTaskMap),
  7320. 'task_center_id' => $taskCenterId
  7321. ];
  7322. // 接口已正常完成,更新任务中心状态和结果
  7323. if ($taskCenterId) {
  7324. $this->taskCenterService->updateTask($taskCenterId, [
  7325. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7326. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7327. 'error_message' => null
  7328. ]);
  7329. }
  7330. return $resultData;
  7331. }
  7332. // 解析 products(可能是 JSON 字符串或数组)
  7333. if (is_string($products)) {
  7334. $products = json_decode($products, true);
  7335. if (json_last_error() !== JSON_ERROR_NONE) {
  7336. Utils::throwError('20003:产品数据格式错误');
  7337. }
  7338. }
  7339. if (!is_array($products) || empty($products)) {
  7340. Utils::throwError('20003:产品数据不能为空');
  7341. }
  7342. // 以下是原有的创建逻辑...
  7343. // 开启事务
  7344. DB::beginTransaction();
  7345. try {
  7346. $now = now();
  7347. $mappingRecords = [];
  7348. $createdProductIds = []; // 记录所有创建的资产ID
  7349. // 获取剧本名称
  7350. $script_name = $script->script_name ?? 'script_' . $script_id;
  7351. // 存储每个类型的根文件夹ID
  7352. $typeFolderIds = [];
  7353. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  7354. foreach ($products as $productGroup) {
  7355. $type = getProp($productGroup, 'type');
  7356. $title = getProp($productGroup, 'title', '');
  7357. $content = getProp($productGroup, 'content', []);
  7358. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  7359. continue;
  7360. }
  7361. // 为当前类型创建根文件夹(如果还未创建)
  7362. if (!isset($typeFolderIds[$type])) {
  7363. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7364. 'user_id' => $uid,
  7365. 'cpid' => $cpid,
  7366. 'type' => 2, // 1.资产 2文件夹
  7367. 'product' => $type, // 1.主体 2.场景 3.道具
  7368. 'parent_id' => 0, // 根文件夹,parent_id=0
  7369. 'level' => 1, // 第一层级
  7370. 'product_name' => $script_name,
  7371. 'sort_order' => time() + $type,
  7372. 'is_deleted' => 0,
  7373. 'created_at' => $now,
  7374. 'updated_at' => $now
  7375. ]);
  7376. }
  7377. $folder_id = $typeFolderIds[$type];
  7378. // 获取表头(第一行)并查找关键列的位置
  7379. $headers = $content[0];
  7380. $nameColumnIndex = -1; // 资产名称列索引
  7381. $sequenceColumnIndex = -1; // 使用范围列索引
  7382. $promptColumnIndex = -1; // 参考提示词列索引
  7383. foreach ($headers as $index => $header) {
  7384. // 查找"资产名称"列
  7385. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  7386. $nameColumnIndex = $index;
  7387. }
  7388. // 查找"使用范围"列
  7389. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  7390. $sequenceColumnIndex = $index;
  7391. }
  7392. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  7393. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  7394. $promptColumnIndex = $index;
  7395. }
  7396. }
  7397. // 验证必要的列是否都找到了
  7398. if ($nameColumnIndex === -1) {
  7399. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  7400. continue;
  7401. }
  7402. if ($sequenceColumnIndex === -1) {
  7403. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  7404. continue;
  7405. }
  7406. // 跳过表头,解析每一行数据
  7407. for ($i = 1; $i < count($content); $i++) {
  7408. $row = $content[$i];
  7409. // 确保行数据有效
  7410. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  7411. continue;
  7412. }
  7413. // 根据动态查找的列索引提取数据
  7414. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  7415. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  7416. $pic_prompt = '';
  7417. // 提取参考提示词(如果找到了该列)
  7418. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  7419. $pic_prompt = trim($row[$promptColumnIndex]);
  7420. }
  7421. // 解析使用范围(逗号分隔的序号)
  7422. $sequences = [];
  7423. if (!empty($sequence_str)) {
  7424. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  7425. foreach ($sequenceParts as $part) {
  7426. if (is_numeric($part)) {
  7427. $sequences[] = (int)$part;
  7428. }
  7429. }
  7430. }
  7431. if (empty($product_name)) {
  7432. continue;
  7433. }
  7434. // 处理product_name两边的符号
  7435. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7436. // 如果名称不存在或仅剩占位符号,则跳过
  7437. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  7438. dLog('anime')->warning('资产名称无效,跳过保存', [
  7439. 'script_id' => $script_id,
  7440. 'type' => $type,
  7441. 'product_name' => $product_name
  7442. ]);
  7443. continue;
  7444. }
  7445. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  7446. $product_id = DB::table('mp_products')->insertGetId([
  7447. 'product_name' => $product_name,
  7448. 'type' => 1, // 1=资产 2.文件夹
  7449. 'product' => $type, // 1=角色, 2=场景, 3=道具
  7450. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  7451. 'level' => 2, // 第二层级
  7452. 'pic_prompt' => $pic_prompt,
  7453. 'user_id' => $uid,
  7454. 'cpid' => $cpid,
  7455. 'sort_order' => time(),
  7456. 'is_deleted' => 0,
  7457. 'created_at' => $now,
  7458. 'updated_at' => $now,
  7459. ]);
  7460. // 记录创建的资产ID
  7461. $createdProductIds[] = $product_id;
  7462. // 为每个序号创建映射记录
  7463. if (!empty($sequences)) {
  7464. foreach ($sequences as $sequence) {
  7465. $mappingRecords[] = [
  7466. 'script_id' => $script_id,
  7467. 'product_id' => $product_id,
  7468. 'episode_number' => $sequence,
  7469. 'created_at' => $now,
  7470. 'updated_at' => $now,
  7471. ];
  7472. }
  7473. } else {
  7474. // 如果没有指定序号,创建一个默认映射(序号为0)
  7475. $mappingRecords[] = [
  7476. 'script_id' => $script_id,
  7477. 'product_id' => $product_id,
  7478. 'episode_number' => 0,
  7479. 'created_at' => $now,
  7480. 'updated_at' => $now,
  7481. ];
  7482. }
  7483. }
  7484. }
  7485. if (empty($mappingRecords)) {
  7486. Utils::throwError('20003:没有有效的产品数据');
  7487. }
  7488. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7489. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7490. // 剧本已有资产,同步更新is_products标记
  7491. DB::table('mp_scripts')->where('id', $script_id)->update([
  7492. 'is_products' => 1,
  7493. 'updated_at' => $now
  7494. ]);
  7495. // 如果需要自动生成图片,在事务中创建图片生成任务
  7496. $productTaskMap = [];
  7497. if ($auto_generate_images && !empty($createdProductIds)) {
  7498. // 查询所有创建的资产
  7499. $productsToGenerate = DB::table('mp_products')
  7500. ->whereIn('id', $createdProductIds)
  7501. ->where('is_deleted', 0)
  7502. ->get();
  7503. foreach ($productsToGenerate as $product) {
  7504. if (empty($product->pic_prompt)) {
  7505. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7506. 'product_id' => $product->id,
  7507. 'product_name' => $product->product_name
  7508. ]);
  7509. continue;
  7510. }
  7511. try {
  7512. // 创建图片生成任务
  7513. $params = [
  7514. 'prompt' => $product->pic_prompt,
  7515. 'model' => $model,
  7516. 'ref_img_urls' => [],
  7517. 'width' => $width,
  7518. 'height' => $height
  7519. ];
  7520. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7521. $task_id = $task->id;
  7522. if ($task_id) {
  7523. $productTaskMap[$product->id] = $task_id;
  7524. // 在事务中更新资产表的任务ID和状态
  7525. DB::table('mp_products')
  7526. ->where('id', $product->id)
  7527. ->update([
  7528. 'pic_task_id' => $task_id,
  7529. 'pic_task_status' => '生成中',
  7530. 'updated_at' => now()
  7531. ]);
  7532. dLog('anime')->info('创建资产图片生成任务', [
  7533. 'product_id' => $product->id,
  7534. 'task_id' => $task_id
  7535. ]);
  7536. }
  7537. } catch (\Exception $e) {
  7538. dLog('anime')->error('创建资产图片生成任务失败', [
  7539. 'product_id' => $product->id,
  7540. 'error' => $e->getMessage()
  7541. ]);
  7542. // 标记为失败(仍在事务中)
  7543. DB::table('mp_products')
  7544. ->where('id', $product->id)
  7545. ->update([
  7546. 'pic_task_status' => '生成失败',
  7547. 'updated_at' => now()
  7548. ]);
  7549. }
  7550. }
  7551. }
  7552. // 提交事务
  7553. DB::commit();
  7554. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  7555. if ($auto_generate_images && !empty($productTaskMap)) {
  7556. // 返回 SSE 流(事务外轮询)
  7557. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7558. }
  7559. // 如果不需要生成图片,返回普通结果
  7560. $resultData = [
  7561. 'success' => true,
  7562. 'type_folder_ids' => $typeFolderIds,
  7563. 'inserted_count' => $insertedCount,
  7564. 'total_records' => count($mappingRecords),
  7565. 'created_products' => count($createdProductIds),
  7566. 'image_tasks_created' => count($productTaskMap),
  7567. 'task_center_id' => $taskCenterId
  7568. ];
  7569. // 接口已正常完成,更新任务中心状态和结果
  7570. if ($taskCenterId) {
  7571. $this->taskCenterService->updateTask($taskCenterId, [
  7572. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7573. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7574. 'error_message' => null
  7575. ]);
  7576. }
  7577. return $resultData;
  7578. } catch (\Exception $e) {
  7579. // 回滚事务
  7580. DB::rollback();
  7581. // 更新任务中心状态为失败
  7582. if (!empty($taskCenterId)) {
  7583. $this->taskCenterService->updateTask($taskCenterId, [
  7584. 'status' => MpTaskCenter::STATUS_FAILED,
  7585. 'error_message' => $e->getMessage()
  7586. ]);
  7587. }
  7588. // 记录错误日志
  7589. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  7590. 'script_id' => $script_id,
  7591. 'error' => $e->getMessage(),
  7592. 'trace' => $e->getTraceAsString()
  7593. ]);
  7594. // 统一使用 Utils::throwError 抛出错误
  7595. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  7596. }
  7597. }
  7598. /**
  7599. * 根据入参创建或复用任务中心记录
  7600. *
  7601. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  7602. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  7603. * 避免生成重复任务。
  7604. *
  7605. * @param int|string $uid
  7606. * @param int|string $cpid
  7607. * @param int|string $script_id
  7608. * @param mixed $products
  7609. * @param string $model
  7610. * @param string $ratio
  7611. * @param string $resolution
  7612. * @param mixed $auto_generate_images
  7613. * @return int 任务中心ID
  7614. */
  7615. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  7616. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  7617. if (is_string($products)) {
  7618. $decoded = json_decode($products, true);
  7619. if (json_last_error() === JSON_ERROR_NONE) {
  7620. $products = $decoded;
  7621. }
  7622. }
  7623. $params = [
  7624. 'script_id' => (int)$script_id,
  7625. 'products' => $products,
  7626. 'model' => $model,
  7627. 'ratio' => $ratio,
  7628. 'resolution' => $resolution,
  7629. 'auto_generate_images' => (bool)$auto_generate_images,
  7630. ];
  7631. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  7632. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  7633. $existing = DB::table('mp_task_center')
  7634. ->where('uid', (int)$uid)
  7635. ->where('cpid', (int)$cpid)
  7636. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  7637. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  7638. ->where('params_md5', $paramsMd5)
  7639. ->orderBy('id', 'desc')
  7640. ->first();
  7641. if ($existing) {
  7642. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  7643. 'script_id' => $script_id,
  7644. 'task_center_id' => $existing->id,
  7645. 'params_md5' => $paramsMd5,
  7646. ]);
  7647. return (int)$existing->id;
  7648. }
  7649. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  7650. $now = date('Y-m-d H:i:s');
  7651. DB::table('mp_task_center')->insertOrIgnore([
  7652. 'uid' => (int)$uid,
  7653. 'cpid' => (int)$cpid,
  7654. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  7655. 'title' => '剧本资产图片生成',
  7656. 'ref_task_id' => 0,
  7657. 'status' => MpTaskCenter::STATUS_PROCESSING,
  7658. 'result' => null,
  7659. 'error_message' => null,
  7660. 'prompt' => null,
  7661. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  7662. 'params_md5' => $paramsMd5,
  7663. 'created_at' => $now,
  7664. 'updated_at' => $now,
  7665. ]);
  7666. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  7667. $taskId = (int)DB::table('mp_task_center')
  7668. ->where('uid', (int)$uid)
  7669. ->where('cpid', (int)$cpid)
  7670. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  7671. ->where('params_md5', $paramsMd5)
  7672. ->orderBy('id', 'desc')
  7673. ->value('id');
  7674. dLog('anime')->info('创建任务中心记录', [
  7675. 'script_id' => $script_id,
  7676. 'task_center_id' => $taskId,
  7677. 'params_md5' => $paramsMd5,
  7678. ]);
  7679. return $taskId;
  7680. }
  7681. /**
  7682. * 任务结束时更新任务中心记录的状态和结果
  7683. *
  7684. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  7685. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  7686. *
  7687. * @param int|null $taskCenterId
  7688. * @param array $resultData 接口返回结果数组
  7689. * @param bool $timeout 是否超时未完成
  7690. */
  7691. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  7692. if (!$taskCenterId) {
  7693. return;
  7694. }
  7695. $stats = $resultData['stats'] ?? [];
  7696. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  7697. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  7698. $failedCount = $completedCount - $successCount;
  7699. // 与接口返回给客户端的结果保持一致
  7700. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  7701. if ($timeout) {
  7702. $this->taskCenterService->updateTask((int)$taskCenterId, [
  7703. 'status' => MpTaskCenter::STATUS_FAILED,
  7704. 'result' => $result,
  7705. 'error_message' => '部分任务超时,请稍后查看结果',
  7706. ]);
  7707. return;
  7708. }
  7709. $this->taskCenterService->updateTask((int)$taskCenterId, [
  7710. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  7711. 'result' => $result,
  7712. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  7713. ]);
  7714. }
  7715. /**
  7716. * 批量为剧本资产生成图片
  7717. *
  7718. * @param array $data 请求参数
  7719. * @return \Generator 返回 SSE 流
  7720. */
  7721. public function batchGenerateProductImages($data) {
  7722. $script_id = getProp($data, 'script_id');
  7723. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  7724. if (!$script_id) {
  7725. Utils::throwError('20003:请提供剧本ID');
  7726. }
  7727. // 验证剧本是否存在
  7728. $script = DB::table('mp_scripts')
  7729. ->where('id', $script_id)
  7730. ->where('is_deleted', 0)
  7731. ->first();
  7732. if (!$script) {
  7733. Utils::throwError('20003:剧本不存在');
  7734. }
  7735. $script_name = $script->script_name ?? 'script_' . $script_id;
  7736. // 获取需要生成图片的所有资产
  7737. $products = DB::table('mp_products')
  7738. ->whereIn('parent_id', array_values($type_folder_ids))
  7739. ->where('is_deleted', 0)
  7740. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7741. ->get();
  7742. if ($products->isEmpty()) {
  7743. Utils::throwError('20003:没有找到需要生成图片的资产');
  7744. }
  7745. // 默认参数
  7746. $model = 'doubao-seedream-5-0-lite-260128';
  7747. $width = 1600;
  7748. $height = 2848;
  7749. // 开始为每个资产创建图片生成任务
  7750. $taskIds = [];
  7751. $productTaskMap = []; // 资产ID到任务ID的映射
  7752. foreach ($products as $product) {
  7753. if (empty($product->pic_prompt)) {
  7754. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7755. continue;
  7756. }
  7757. try {
  7758. // 创建图片生成任务
  7759. $params = [
  7760. 'prompt' => $product->pic_prompt,
  7761. 'model' => $model,
  7762. 'ref_img_urls' => [],
  7763. 'width' => $width,
  7764. 'height' => $height
  7765. ];
  7766. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7767. $task_id = $task->id;
  7768. if ($task_id) {
  7769. $taskIds[] = $task_id;
  7770. $productTaskMap[$product->id] = $task_id;
  7771. // 更新资产表的任务ID和状态
  7772. DB::table('mp_products')
  7773. ->where('id', $product->id)
  7774. ->update([
  7775. 'pic_task_id' => $task_id,
  7776. 'pic_task_status' => '生成中',
  7777. 'updated_at' => now()
  7778. ]);
  7779. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7780. }
  7781. } catch (\Exception $e) {
  7782. dLog('anime')->error('创建资产图片生成任务失败', [
  7783. 'product_id' => $product->id,
  7784. 'error' => $e->getMessage()
  7785. ]);
  7786. // 标记为失败
  7787. DB::table('mp_products')
  7788. ->where('id', $product->id)
  7789. ->update([
  7790. 'pic_task_status' => '生成失败',
  7791. 'updated_at' => now()
  7792. ]);
  7793. }
  7794. }
  7795. if (empty($taskIds)) {
  7796. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7797. }
  7798. // 返回 SSE 流
  7799. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7800. }
  7801. /**
  7802. * 轮询资产图片生成任务状态(SSE流式返回)
  7803. * 只通过查询数据库获取任务状态,不主动调用API
  7804. *
  7805. * @param int $script_id 剧本ID
  7806. * @param string $script_name 剧本名称
  7807. * @param array $productTaskMap 资产ID到任务ID的映射
  7808. * @param array $type_folder_ids 类型文件夹ID映射
  7809. * @return \Generator
  7810. */
  7811. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null) {
  7812. $startTime = time();
  7813. $timeout = 1800; // 30分钟超时
  7814. $pollInterval = 10; // 10秒轮询一次
  7815. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7816. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  7817. if ($taskCenterId) {
  7818. $initResponse = [
  7819. 'type' => 'init',
  7820. 'script_id' => $script_id,
  7821. 'script_name' => $script_name,
  7822. 'timestamp' => date('Y-m-d H:i:s'),
  7823. 'task_center_id' => (int)$taskCenterId,
  7824. ];
  7825. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  7826. }
  7827. // 定义类型名称映射
  7828. $typeNames = [
  7829. 1 => 'roles', // 角色
  7830. 2 => 'scenes', // 场景
  7831. 3 => 'props' // 道具
  7832. ];
  7833. while (time() - $startTime < $timeout) {
  7834. sleep($pollInterval);
  7835. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7836. $mappings = DB::table('mp_script_product_mappings')
  7837. ->where('script_id', $script_id)
  7838. ->pluck('product_id')
  7839. ->unique()
  7840. ->toArray();
  7841. if (empty($mappings)) {
  7842. dLog('anime')->warning('该剧本没有关联的资产', [
  7843. 'script_id' => $script_id,
  7844. 'script_name' => $script_name
  7845. ]);
  7846. break;
  7847. }
  7848. // 查询所有资产的当前状态
  7849. $products = DB::table('mp_products')
  7850. ->whereIn('id', $mappings)
  7851. ->where('is_deleted', 0)
  7852. ->get();
  7853. // 统计各类型的状态(使用类型名称作为键名)
  7854. $stats = [
  7855. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7856. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7857. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7858. ];
  7859. $allCompleted = true;
  7860. $hasStatusChange = false;
  7861. foreach ($products as $product) {
  7862. $type = $product->product;
  7863. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7864. // 如果类型名称不在 stats 中,初始化
  7865. if (!isset($stats[$typeName])) {
  7866. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7867. }
  7868. $stats[$typeName]['total']++;
  7869. $task_id = $product->pic_task_id;
  7870. $currentStatus = $product->pic_task_status;
  7871. // 检查状态是否有变化
  7872. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7873. $hasStatusChange = true;
  7874. $lastStatus[$product->id] = $currentStatus;
  7875. }
  7876. // 如果是生成中,查询任务表状态
  7877. if ($currentStatus === '生成中' && $task_id) {
  7878. // 只查询数据库,不调用API
  7879. $task = DB::table('mp_generate_pic_tasks')
  7880. ->where('id', $task_id)
  7881. ->first();
  7882. if ($task) {
  7883. // 检查任务状态
  7884. if ($task->status === 'success' && $task->result_url) {
  7885. // 解析图片URL
  7886. $result_urls = $task->result_url;
  7887. if (is_string($result_urls)) {
  7888. $result_urls = json_decode($result_urls, true);
  7889. }
  7890. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7891. // 更新资产表状态
  7892. DB::table('mp_products')
  7893. ->where('id', $product->id)
  7894. ->update([
  7895. 'pic_task_status' => '生成成功',
  7896. 'url' => $img_url,
  7897. 'updated_at' => now()
  7898. ]);
  7899. $stats[$typeName]['success']++;
  7900. $stats[$typeName]['completed']++;
  7901. $hasStatusChange = true;
  7902. dLog('anime')->info('资产图片生成成功', [
  7903. 'product_id' => $product->id,
  7904. 'task_id' => $task_id,
  7905. 'img_url' => $img_url
  7906. ]);
  7907. } elseif ($task->status === 'failed') {
  7908. // 更新资产表状态
  7909. DB::table('mp_products')
  7910. ->where('id', $product->id)
  7911. ->update([
  7912. 'pic_task_status' => '生成失败',
  7913. 'updated_at' => now()
  7914. ]);
  7915. $stats[$typeName]['completed']++;
  7916. $hasStatusChange = true;
  7917. dLog('anime')->warning('资产图片生成失败', [
  7918. 'product_id' => $product->id,
  7919. 'task_id' => $task_id,
  7920. 'error' => $task->error_message ?? '未知错误'
  7921. ]);
  7922. } else {
  7923. // 任务还在处理中
  7924. $allCompleted = false;
  7925. }
  7926. } else {
  7927. // 任务不存在,标记为失败
  7928. DB::table('mp_products')
  7929. ->where('id', $product->id)
  7930. ->update([
  7931. 'pic_task_status' => '生成失败',
  7932. 'updated_at' => now()
  7933. ]);
  7934. $stats[$type]['completed']++;
  7935. $hasStatusChange = true;
  7936. dLog('anime')->error('图片生成任务不存在', [
  7937. 'product_id' => $product->id,
  7938. 'task_id' => $task_id
  7939. ]);
  7940. }
  7941. } elseif ($currentStatus === '生成成功') {
  7942. $stats[$typeName]['success']++;
  7943. $stats[$typeName]['completed']++;
  7944. } elseif ($currentStatus === '生成失败') {
  7945. $stats[$typeName]['completed']++;
  7946. } else {
  7947. // 其他状态也认为未完成
  7948. $allCompleted = false;
  7949. }
  7950. }
  7951. // 移除没有数据的类型(total=0)
  7952. foreach ($stats as $typeName => $stat) {
  7953. if ($stat['total'] === 0) {
  7954. unset($stats[$typeName]);
  7955. }
  7956. }
  7957. // 如果有状态变化,发送 SSE 更新
  7958. if ($hasStatusChange) {
  7959. $eventType = $allCompleted ? 'complete' : 'update';
  7960. $response = [
  7961. 'type' => $eventType,
  7962. 'script_id' => $script_id,
  7963. 'script_name' => $script_name,
  7964. 'stats' => $stats,
  7965. 'timestamp' => date('Y-m-d H:i:s')
  7966. ];
  7967. if ($taskCenterId) {
  7968. $response['task_center_id'] = $taskCenterId;
  7969. }
  7970. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7971. dLog('anime')->info('SSE更新', [
  7972. 'event_type' => $eventType,
  7973. 'script_id' => $script_id,
  7974. 'script_name' => $script_name,
  7975. 'stats' => $stats
  7976. ]);
  7977. if ($allCompleted) {
  7978. dLog('anime')->info('所有资产图片生成任务已完成', [
  7979. 'script_id' => $script_id,
  7980. 'script_name' => $script_name,
  7981. 'stats' => $stats
  7982. ]);
  7983. // 全部任务完成,更新任务中心状态和结果
  7984. $this->finishScriptProductTask($taskCenterId, $response);
  7985. break;
  7986. }
  7987. }
  7988. }
  7989. // 超时处理
  7990. if (time() - $startTime >= $timeout && !$allCompleted) {
  7991. $response = [
  7992. 'type' => 'timeout',
  7993. 'message' => '部分任务超时,请稍后查看结果',
  7994. 'script_id' => $script_id,
  7995. 'script_name' => $script_name,
  7996. 'timestamp' => date('Y-m-d H:i:s')
  7997. ];
  7998. if ($taskCenterId) {
  7999. $response['task_center_id'] = $taskCenterId;
  8000. }
  8001. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  8002. dLog('anime')->warning('资产图片生成任务超时', [
  8003. 'script_id' => $script_id,
  8004. 'script_name' => $script_name,
  8005. 'timeout' => $timeout
  8006. ]);
  8007. // 超时未完成,更新任务中心状态和结果
  8008. $this->finishScriptProductTask($taskCenterId, $response, true);
  8009. }
  8010. }
  8011. /**
  8012. * 定时任务:检查产品图片生成任务状态并更新产品记录
  8013. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  8014. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  8015. *
  8016. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  8017. */
  8018. public function checkProductPicTasks() {
  8019. // 查询所有生成中的产品图片任务
  8020. $products = DB::table('mp_products')
  8021. ->whereNotNull('pic_task_id')
  8022. ->where('pic_task_status', '生成中')
  8023. ->where('is_deleted', 0)
  8024. ->get();
  8025. $stats = [
  8026. 'total' => $products->count(),
  8027. 'success' => 0,
  8028. 'failed' => 0,
  8029. 'pending' => 0,
  8030. ];
  8031. foreach ($products as $product) {
  8032. try {
  8033. $task_id = $product->pic_task_id;
  8034. // 通过 pic_task_id 查询图片生成任务结果
  8035. $task = DB::table('mp_generate_pic_tasks')
  8036. ->where('id', $task_id)
  8037. ->first();
  8038. if ($task) {
  8039. if ($task->status === 'success' && $task->result_url) {
  8040. // 解析图片URL
  8041. $result_urls = $task->result_url;
  8042. if (is_string($result_urls)) {
  8043. $result_urls = json_decode($result_urls, true);
  8044. }
  8045. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  8046. // 更新资产表状态
  8047. DB::table('mp_products')
  8048. ->where('id', $product->id)
  8049. ->update([
  8050. 'pic_task_status' => '生成成功',
  8051. 'url' => $img_url,
  8052. 'updated_at' => now()
  8053. ]);
  8054. $stats['success']++;
  8055. dLog('anime')->info('资产图片生成成功', [
  8056. 'product_id' => $product->id,
  8057. 'task_id' => $task_id,
  8058. 'img_url' => $img_url
  8059. ]);
  8060. } elseif ($task->status === 'failed') {
  8061. // 更新资产表状态
  8062. DB::table('mp_products')
  8063. ->where('id', $product->id)
  8064. ->update([
  8065. 'pic_task_status' => '生成失败',
  8066. 'updated_at' => now()
  8067. ]);
  8068. $stats['failed']++;
  8069. dLog('anime')->warning('资产图片生成失败', [
  8070. 'product_id' => $product->id,
  8071. 'task_id' => $task_id,
  8072. 'error' => $task->error_message ?? '未知错误'
  8073. ]);
  8074. } else {
  8075. // 任务还在处理中
  8076. $stats['pending']++;
  8077. }
  8078. } else {
  8079. // 任务不存在,标记为失败
  8080. DB::table('mp_products')
  8081. ->where('id', $product->id)
  8082. ->update([
  8083. 'pic_task_status' => '生成失败',
  8084. 'updated_at' => now()
  8085. ]);
  8086. $stats['failed']++;
  8087. dLog('anime')->error('图片生成任务不存在', [
  8088. 'product_id' => $product->id,
  8089. 'task_id' => $task_id
  8090. ]);
  8091. }
  8092. } catch (\Exception $e) {
  8093. dLog('anime')->error('检查产品图片生成任务异常', [
  8094. 'product_id' => $product->id,
  8095. 'task_id' => $product->pic_task_id ?? null,
  8096. 'error' => $e->getMessage()
  8097. ]);
  8098. }
  8099. }
  8100. return $stats;
  8101. }
  8102. /**
  8103. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  8104. *
  8105. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  8106. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  8107. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  8108. *
  8109. * @return int 更新的任务中心记录数
  8110. */
  8111. public function checkSaveScriptProductTaskCenters() {
  8112. $updated = 0;
  8113. // 只扫描尚未结束的 saveScriptProducts 任务
  8114. $tasks = DB::table('mp_task_center')
  8115. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8116. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  8117. ->orderBy('id', 'desc')
  8118. ->limit(500)
  8119. ->get();
  8120. // 与 pollProductImageTasks 保持一致的类型名称映射
  8121. $typeNames = [
  8122. 1 => 'roles', // 角色
  8123. 2 => 'scenes', // 场景
  8124. 3 => 'props', // 道具
  8125. ];
  8126. foreach ($tasks as $task) {
  8127. try {
  8128. $taskParams = json_decode((string)$task->params, true);
  8129. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  8130. if (!$script_id) {
  8131. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  8132. 'task_center_id' => $task->id,
  8133. ]);
  8134. continue;
  8135. }
  8136. // 获取该剧本关联的全部资产ID
  8137. $productIds = DB::table('mp_script_product_mappings')
  8138. ->where('script_id', $script_id)
  8139. ->pluck('product_id')
  8140. ->unique()
  8141. ->toArray();
  8142. if (empty($productIds)) {
  8143. // 剧本没有关联资产,不视为完成,等待下一次检查
  8144. continue;
  8145. }
  8146. $products = DB::table('mp_products')
  8147. ->whereIn('id', $productIds)
  8148. ->where('is_deleted', 0)
  8149. ->get();
  8150. $stats = [];
  8151. $allCompleted = true;
  8152. foreach ($products as $product) {
  8153. $typeName = $typeNames[$product->product] ?? 'unknown';
  8154. if (!isset($stats[$typeName])) {
  8155. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  8156. }
  8157. $stats[$typeName]['total']++;
  8158. if ($product->pic_task_status === '生成成功') {
  8159. $stats[$typeName]['success']++;
  8160. $stats[$typeName]['completed']++;
  8161. } elseif ($product->pic_task_status === '生成失败') {
  8162. $stats[$typeName]['completed']++;
  8163. } else {
  8164. // 仍有资产在生成中或未生成,任务未完成
  8165. $allCompleted = false;
  8166. }
  8167. }
  8168. if (!$allCompleted) {
  8169. continue;
  8170. }
  8171. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  8172. $script = DB::table('mp_scripts')
  8173. ->where('id', $script_id)
  8174. ->where('is_deleted', 0)
  8175. ->first();
  8176. $script_name = $script->script_name ?? 'script_' . $script_id;
  8177. $this->finishScriptProductTask($task->id, [
  8178. 'type' => 'complete',
  8179. 'script_id' => $script_id,
  8180. 'script_name' => $script_name,
  8181. 'stats' => $stats,
  8182. 'timestamp' => date('Y-m-d H:i:s'),
  8183. 'task_center_id' => (int)$task->id,
  8184. ]);
  8185. $updated++;
  8186. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  8187. 'task_center_id' => $task->id,
  8188. 'script_id' => $script_id,
  8189. 'stats' => $stats,
  8190. ]);
  8191. } catch (\Exception $e) {
  8192. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  8193. 'task_center_id' => $task->id,
  8194. 'error' => $e->getMessage(),
  8195. ]);
  8196. }
  8197. }
  8198. return $updated;
  8199. }
  8200. /**
  8201. * 获取剧本关联的资产列表
  8202. * @param array $data 请求参数
  8203. * @return array
  8204. */
  8205. public function getScriptProducts($data) {
  8206. $uid = Site::getUid();
  8207. $cpid = Site::getCpid();
  8208. $script_id = getProp($data, 'script_id');
  8209. $episode_number = getProp($data, 'episode_number');
  8210. if (!$script_id) {
  8211. Utils::throwError('20003:请提供剧本ID');
  8212. }
  8213. // 验证剧本是否存在
  8214. $script = DB::table('mp_scripts')
  8215. ->where('id', $script_id)
  8216. ->where('is_deleted', 0)
  8217. ->first();
  8218. if (!$script) {
  8219. Utils::throwError('20003:剧本不存在');
  8220. }
  8221. // 联表查询资产信息
  8222. $query = DB::table('mp_script_product_mappings as mapping')
  8223. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8224. ->where('mapping.script_id', $script_id)
  8225. ->where('product.cpid', $cpid)
  8226. ->where('product.is_deleted', 0);
  8227. // 如果提供了 episode_number,则过滤指定集数
  8228. if ($episode_number !== null && $episode_number !== '') {
  8229. $query->where('mapping.episode_number', $episode_number);
  8230. }
  8231. $mappings = $query->select(
  8232. 'mapping.script_id',
  8233. 'mapping.product_id',
  8234. 'mapping.episode_number',
  8235. 'product.product_name',
  8236. 'product.type',
  8237. 'product.product',
  8238. 'product.pic_prompt',
  8239. 'product.url',
  8240. 'product.pic_task_id',
  8241. 'product.pic_task_status',
  8242. 'product.three_view_image_url',
  8243. 'mapping.created_at'
  8244. )
  8245. ->orderBy('mapping.product_id', 'asc')
  8246. ->orderBy('mapping.episode_number', 'asc')
  8247. ->get();
  8248. // 按 product_id 分组,合并 episode_number
  8249. $productMap = [];
  8250. foreach ($mappings as $item) {
  8251. $product_id = $item->product_id;
  8252. if (!isset($productMap[$product_id])) {
  8253. $productMap[$product_id] = [
  8254. 'product_id' => $product_id,
  8255. 'product_name' => $item->product_name,
  8256. 'type' => (int)$item->type,
  8257. 'product' => (int)$item->product,
  8258. 'pic_prompt' => $item->pic_prompt,
  8259. 'url' => $item->url,
  8260. 'pic_task_id' => $item->pic_task_id,
  8261. 'pic_task_status' => $item->pic_task_status,
  8262. 'episode_numbers' => [],
  8263. 'created_at' => $item->created_at,
  8264. ];
  8265. }
  8266. // 添加 episode_number(去重)
  8267. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8268. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8269. }
  8270. }
  8271. // 按类型分组
  8272. $roles = []; // type=1 角色/主体
  8273. $scenes = []; // type=2 场景
  8274. $props = []; // type=3 道具
  8275. foreach ($productMap as $product) {
  8276. // 将 episode_numbers 数组转换为逗号分隔的字符串
  8277. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  8278. // 构造返回数据
  8279. $productData = [
  8280. 'product_id' => $product['product_id'],
  8281. 'product_name' => $product['product_name'],
  8282. 'product' => $product['product'],
  8283. 'pic_prompt' => $product['pic_prompt'],
  8284. 'url' => $product['url'],
  8285. 'pic_task_id' => $product['pic_task_id'],
  8286. 'pic_task_status' => $product['pic_task_status'],
  8287. 'episode_numbers' => $episodeNumbersStr,
  8288. 'created_at' => $product['created_at'],
  8289. ];
  8290. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  8291. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  8292. switch ($product['product']) {
  8293. case 1:
  8294. $roles[] = $productData;
  8295. break;
  8296. case 2:
  8297. $scenes[] = $productData;
  8298. break;
  8299. case 3:
  8300. $props[] = $productData;
  8301. break;
  8302. }
  8303. }
  8304. return [
  8305. 'script_id' => $script_id,
  8306. 'script_name' => $script->script_name ?? '',
  8307. 'roles' => $roles, // 主体
  8308. 'scenes' => $scenes, // 场景
  8309. 'props' => $props, // 道具
  8310. ];
  8311. }
  8312. /**
  8313. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  8314. * @param string $actContent 原始内容
  8315. * @param array $products 产品数组(包含product_name和url)
  8316. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  8317. */
  8318. public function processActContentWithProducts($actContent, $products) {
  8319. if (empty($actContent) || empty($products)) {
  8320. return [
  8321. 'content' => $actContent,
  8322. 'reference_images' => []
  8323. ];
  8324. }
  8325. // 构建产品名称到产品信息的映射
  8326. $product_dict = [];
  8327. foreach ($products as $product) {
  8328. $product_name = getProp($product, 'product_name');
  8329. if ($product_name) {
  8330. $product_dict[$product_name] = [
  8331. 'url' => getProp($product, 'url'),
  8332. 'voice_prompt' => getProp($product, 'voice_prompt')
  8333. ];
  8334. }
  8335. }
  8336. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  8337. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  8338. $reference_images = [];
  8339. $product_index_map = []; // 产品名称 => 图片序号的映射
  8340. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  8341. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  8342. $current_index = 1;
  8343. if (!empty($matches[1])) {
  8344. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  8345. $seen_products = []; // 用于去重
  8346. foreach ($matches[1] as $product_name) {
  8347. // 跳过已处理的产品
  8348. if (isset($seen_products[$product_name])) {
  8349. continue;
  8350. }
  8351. $seen_products[$product_name] = true;
  8352. // 检查产品是否在字典中
  8353. if (isset($product_dict[$product_name])) {
  8354. $url = $product_dict[$product_name]['url'];
  8355. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  8356. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  8357. if (!empty($voice_prompt) && $product_name !== '旁白') {
  8358. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  8359. }
  8360. // 只有URL非空才分配序号和添加到参考图片
  8361. if (!empty($url)) {
  8362. // 检查URL是否已经在reference_images中(去重)
  8363. if (!in_array($url, $reference_images)) {
  8364. $reference_images[] = $url;
  8365. $product_index_map[$product_name] = $current_index;
  8366. $current_index++;
  8367. } else {
  8368. // URL重复,找到已有的序号
  8369. $existing_index = array_search($url, $reference_images) + 1;
  8370. $product_index_map[$product_name] = $existing_index;
  8371. }
  8372. } else {
  8373. // URL为空,不分配序号(后续直接去掉{})
  8374. $product_index_map[$product_name] = 0;
  8375. }
  8376. } else {
  8377. // 产品不在字典中,不分配序号
  8378. $product_index_map[$product_name] = 0;
  8379. }
  8380. }
  8381. }
  8382. // 第二步:替换内容中的 {产品名称}
  8383. $processedContent = $actContent;
  8384. foreach ($product_index_map as $product_name => $index) {
  8385. $escaped_name = preg_quote($product_name, '/');
  8386. if ($index > 0) {
  8387. // 有图片,替换为:产品名称(图X)
  8388. $replacement = $product_name . '<图片' . $index . '>';
  8389. } else {
  8390. // 无图片,只保留产品名称
  8391. $replacement = $product_name;
  8392. }
  8393. // 替换所有 {产品名称} 为处理后的格式
  8394. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  8395. }
  8396. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  8397. foreach ($products as $product) {
  8398. $product_name = getProp($product, 'product_name');
  8399. $voice_prompt = getProp($product, 'voice_prompt');
  8400. if ($product_name === '旁白' && !empty($voice_prompt)) {
  8401. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  8402. break; // 找到旁白后退出循环
  8403. }
  8404. }
  8405. // 第四步:将voice_prompt信息添加到内容最前面
  8406. $voice_prompt_prefix = '';
  8407. if (!empty($voice_prompts)) {
  8408. $voice_prompt_prefix .= implode('', $voice_prompts);
  8409. }
  8410. // 旁白的voice_prompt放在最后
  8411. if (!empty($narrator_voice_prompt)) {
  8412. $voice_prompt_prefix .= $narrator_voice_prompt;
  8413. }
  8414. // 如果有voice_prompt信息,添加到内容开头
  8415. if (!empty($voice_prompt_prefix)) {
  8416. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  8417. }
  8418. return [
  8419. 'content' => $processedContent,
  8420. 'reference_images' => $reference_images
  8421. ];
  8422. }
  8423. public function saveActVideoGenerateParams($data) {
  8424. $episode_id = getProp($data, 'episode_id');
  8425. $model = getProp($data, 'video_model');
  8426. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  8427. Utils::throwError('20003:该模型不可用');
  8428. }
  8429. if (!$model) {
  8430. // 使用默认模型
  8431. $model = 'zhizhen-20';
  8432. }
  8433. // 验证模型是否在可用模型表中
  8434. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8435. Utils::throwError('20003:该模型已不可用,请更换!');
  8436. }
  8437. $video_resolution = getProp($data, 'video_resolution', '720p');
  8438. $ratio = getProp($data, 'ratio');
  8439. if (!$ratio) $ratio = '9:16';
  8440. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  8441. if (!$episode) {
  8442. Utils::throwError('20003:分集不存在');
  8443. }
  8444. try {
  8445. DB::beginTransaction();
  8446. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8447. 'video_model' => $model,
  8448. 'video_resolution' => $video_resolution,
  8449. 'ratio' => $ratio,
  8450. 'updated_at' => date('Y-m-d H:i:s')
  8451. ]);
  8452. if ($result === false) {
  8453. Utils::throwError('20003:分集视频参数保存失败');
  8454. }
  8455. // 同步更新mp_animes表
  8456. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  8457. 'video_model' => $model,
  8458. 'video_resolution' => $video_resolution,
  8459. 'video_ratio' => $ratio,
  8460. 'updated_at' => date('Y-m-d H:i:s')
  8461. ]);
  8462. if ($anime_result === false) {
  8463. Utils::throwError('20003:动漫视频参数保存失败');
  8464. }
  8465. } catch (\Exception $e) {
  8466. DB::rollBack();
  8467. Utils::throwError('20003:'.$e->getMessage());
  8468. }
  8469. DB::commit();
  8470. return $result;
  8471. }
  8472. public function confirmActs($data) {
  8473. $episode_id = getProp($data, 'episode_id');
  8474. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  8475. if (!$episode) {
  8476. Utils::throwError('20003:分集不存在');
  8477. }
  8478. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  8479. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  8480. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  8481. // 获取所有片段数据
  8482. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8483. // 收集所有资产名称(角色、场景、道具)
  8484. $product_names = [];
  8485. // 收集角色名称
  8486. foreach ($roles as $role) {
  8487. $role_name = getProp($role, 'role');
  8488. if ($role_name && $role_name != '旁白') {
  8489. $product_names[] = $role_name;
  8490. }
  8491. }
  8492. // 收集场景名称
  8493. foreach ($scenes as $scene) {
  8494. $scene_name = getProp($scene, 'scene');
  8495. if ($scene_name) {
  8496. $product_names[] = $scene_name;
  8497. }
  8498. }
  8499. // 收集道具名称
  8500. foreach ($props as $prop) {
  8501. $prop_name = getProp($prop, 'prop');
  8502. if ($prop_name) {
  8503. $product_names[] = $prop_name;
  8504. }
  8505. }
  8506. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8507. $product_names = array_unique($product_names);
  8508. usort($product_names, function($a, $b) {
  8509. return mb_strlen($b) - mb_strlen($a);
  8510. });
  8511. try {
  8512. DB::beginTransaction();
  8513. // 处理每个片段
  8514. foreach ($acts as $act) {
  8515. $act_content = getProp($act, 'act_content');
  8516. if (!$act_content) continue;
  8517. $processed_content = $act_content;
  8518. // 统一替换所有资产名称为 {资产名} 格式
  8519. // 使用占位符避免嵌套替换问题
  8520. $placeholder_map = [];
  8521. $placeholder_index = 0;
  8522. foreach ($product_names as $product_name) {
  8523. // 转义特殊字符
  8524. $escaped_product = preg_quote($product_name, '/');
  8525. // 检查是否匹配且未被 {} 包裹
  8526. $processed_content = preg_replace_callback(
  8527. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8528. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8529. // 使用唯一占位符
  8530. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8531. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8532. $placeholder_index++;
  8533. return $placeholder;
  8534. },
  8535. $processed_content
  8536. );
  8537. }
  8538. // 将所有占位符替换回实际内容
  8539. foreach ($placeholder_map as $placeholder => $replacement) {
  8540. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8541. }
  8542. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8543. $shot_counter = 0;
  8544. $processed_content = preg_replace_callback(
  8545. '/【(?:镜头|分镜)(\d+)】/u',
  8546. function($matches) use (&$shot_counter) {
  8547. $shot_counter++;
  8548. return '【镜头' . $shot_counter . '】';
  8549. },
  8550. $processed_content
  8551. );
  8552. // 更新数据库
  8553. $boolen = DB::table('mp_episode_segments')
  8554. ->where('id', $act->id)
  8555. ->update([
  8556. 'act_show_content' => $processed_content,
  8557. 'updated_at' => date('Y-m-d H:i:s')
  8558. ]);
  8559. if (!$boolen) {
  8560. Utils::throwError('20003:片段处理失败');
  8561. }
  8562. }
  8563. }catch (\Exception $e) {
  8564. DB::rollBack();
  8565. Utils::throwError('20003:'.$e->getMessage());
  8566. }
  8567. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8568. 'is_generated' => 1,
  8569. 'updated_at' => date('Y-m-d H:i:s')
  8570. ]);
  8571. if (!$boolen1) {
  8572. DB::rollBack();
  8573. Utils::throwError('20003:分集处理失败!');
  8574. }
  8575. DB::commit();
  8576. // 重新查询更新后的片段数据
  8577. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8578. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  8579. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  8580. $products = [];
  8581. // 先处理角色数组
  8582. foreach ($roles as $role) {
  8583. $product = $role;
  8584. // 将role字段重命名为product_name
  8585. if (isset($product['role'])) {
  8586. $product['product_name'] = $product['role'];
  8587. unset($product['role']);
  8588. $product['product'] = 1; // 标记类型为角色
  8589. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8590. }
  8591. }
  8592. // 处理场景数组
  8593. foreach ($scenes as $scene) {
  8594. $product = $scene;
  8595. // 将scene字段重命名为product_name
  8596. if (isset($product['scene'])) {
  8597. $product['product_name'] = $product['scene'];
  8598. unset($product['scene']);
  8599. $product['product'] = 2; // 标记类型为场景
  8600. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8601. }
  8602. }
  8603. // 处理道具数组(逻辑与场景一致)
  8604. foreach ($props as $prop) {
  8605. $product = $prop;
  8606. // 将prop字段重命名为product_name
  8607. if (isset($product['prop'])) {
  8608. $product['product_name'] = $product['prop'];
  8609. unset($product['prop']);
  8610. $product['product'] = 3; // 标记类型为道具
  8611. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8612. }
  8613. }
  8614. // extra_products优先级更高,直接覆盖同名的roles和scenes
  8615. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  8616. foreach ($extra_products as $extra_product) {
  8617. $product_name = getProp($extra_product, 'product_name');
  8618. if ($product_name) {
  8619. $products[$product_name] = $extra_product; // 覆盖同名数据
  8620. }
  8621. }
  8622. // 重新索引数组(去除key)
  8623. $products = array_values($products);
  8624. // 构建返回的acts数组
  8625. $return_acts = [];
  8626. foreach ($acts as $act) {
  8627. $return_acts[] = [
  8628. 'act_id' => getProp($act, 'id'),
  8629. 'act_number' => getProp($act, 'act_number'),
  8630. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  8631. 'act_show_content' => getProp($act, 'act_show_content'),
  8632. 'video_url' => getProp($act, 'video_url'),
  8633. 'video_duration' => getProp($act, 'video_duration'),
  8634. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  8635. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  8636. ];
  8637. }
  8638. return [
  8639. 'anime_id' => getProp($episode, 'anime_id'),
  8640. 'episode_id' => $episode_id,
  8641. 'title' => getProp($episode, 'title'),
  8642. 'episode_number' => getProp($episode, 'episode_number'),
  8643. 'is_generated' => getProp($episode, 'is_generated'),
  8644. 'video_params' => [
  8645. 'video_model' => getProp($episode, 'video_model'),
  8646. 'video_resolution' => getProp($episode, 'video_resolution'),
  8647. 'ratio' => getProp($episode, 'ratio'),
  8648. ],
  8649. 'products' => $products,
  8650. 'acts' => $return_acts
  8651. ];
  8652. }
  8653. /**
  8654. * 导出动漫剧本为PDF(参照示例PDF版式)
  8655. * @param int $animeId 动漫ID
  8656. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  8657. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  8658. * @return string|null
  8659. */
  8660. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  8661. // 图片下载与转换可能占用较多内存
  8662. ini_set('memory_limit', '512M');
  8663. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  8664. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  8665. $anime = (array)$anime;
  8666. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  8667. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  8668. // 获取分集(默认展示版本,按集数升序)
  8669. $episodeQuery = DB::table('mp_anime_episodes')
  8670. ->where('anime_id', $animeId)
  8671. ->where('is_default', 1)
  8672. ->orderBy('episode_number')
  8673. ->orderBy('id');
  8674. if ($episodeCount > 0) {
  8675. $episodeQuery->limit($episodeCount);
  8676. }
  8677. $episodes = $episodeQuery->get()->map(function ($value) {
  8678. return (array)$value;
  8679. })->toArray();
  8680. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  8681. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  8682. $roles = $this->mergeEpisodeItems($episodes, 'role');
  8683. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  8684. $props = $this->mergeEpisodeItems($episodes, 'prop');
  8685. // 组装分集剧本数据
  8686. $episodeScripts = [];
  8687. foreach ($episodes as $episode) {
  8688. $segments = DB::table('mp_episode_segments')
  8689. ->where('anime_id', $animeId)
  8690. ->where('episode_id', $episode['id'])
  8691. ->get();
  8692. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  8693. $acts = [];
  8694. foreach ($segments as $segment) {
  8695. $segment = (array)$segment;
  8696. $actNumber = (int)getProp($segment, 'act_number', 0);
  8697. if ($actNumber <= 0) continue;
  8698. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  8699. $acts[$actNumber] = [
  8700. 'id' => (int)$segment['id'],
  8701. 'act_number' => $actNumber,
  8702. 'duration' => getProp($segment, 'act_duration', ''),
  8703. 'content' => getProp($segment, 'act_content', ''),
  8704. ];
  8705. }
  8706. }
  8707. ksort($acts);
  8708. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  8709. $segmentCounter = 0;
  8710. foreach ($acts as &$act) {
  8711. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  8712. }
  8713. unset($act);
  8714. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  8715. $narratorVoice = '';
  8716. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  8717. foreach ($episodeRoles as $role) {
  8718. if (getProp($role, 'role') === '旁白') {
  8719. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  8720. break;
  8721. }
  8722. }
  8723. if ($narratorVoice === '') {
  8724. foreach ($acts as $act) {
  8725. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  8726. $narratorVoice = trim($match[1]);
  8727. break;
  8728. }
  8729. }
  8730. }
  8731. $episodeScripts[] = [
  8732. 'episode_number' => getProp($episode, 'episode_number'),
  8733. 'title' => getProp($episode, 'title', ''),
  8734. 'act_count' => count($acts),
  8735. 'narrator_voice' => $narratorVoice,
  8736. 'acts' => array_values($acts),
  8737. ];
  8738. }
  8739. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  8740. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  8741. // 构建PDF
  8742. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  8743. // 图片已嵌入PDF,清理临时文件
  8744. foreach ($imageCache as $imgFile) {
  8745. @unlink($imgFile);
  8746. }
  8747. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  8748. if ($savePath) {
  8749. $pdf->Output($savePath, 'F');
  8750. return $savePath;
  8751. }
  8752. // 直接下载输出
  8753. header('Content-Type: application/pdf');
  8754. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  8755. $pdf->Output($filename . '.pdf', 'D');
  8756. exit();
  8757. }
  8758. /**
  8759. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  8760. * @param array $episodes 分集数据
  8761. * @param string $nameKey role|scene|prop
  8762. * @return array
  8763. */
  8764. private function mergeEpisodeItems(array $episodes, $nameKey) {
  8765. $fieldMap = [
  8766. 'role' => 'roles',
  8767. 'scene' => 'scenes',
  8768. 'prop' => 'props',
  8769. ];
  8770. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  8771. $items = [];
  8772. foreach ($episodes as $episode) {
  8773. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  8774. foreach ($list as $item) {
  8775. if (!is_array($item)) continue;
  8776. $name = trim((string)getProp($item, $nameKey, ''));
  8777. if ($name === '') continue;
  8778. // 旁白不进入主体列表(仅作为旁白音色来源)
  8779. if ($nameKey === 'role' && $name === '旁白') continue;
  8780. if (!isset($items[$name])) {
  8781. $items[$name] = $item;
  8782. }
  8783. }
  8784. }
  8785. return array_values($items);
  8786. }
  8787. /**
  8788. * 构建动漫剧本PDF
  8789. * @param array $anime 动漫信息
  8790. * @param array $roles 主体列表
  8791. * @param array $scenes 场景列表
  8792. * @param array $props 道具列表
  8793. * @param array $episodeScripts 分集剧本数据
  8794. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8795. * @return \TCPDF
  8796. */
  8797. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  8798. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  8799. $pdf->SetCreator('动漫剧本导出系统');
  8800. $pdf->SetAuthor('系统');
  8801. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  8802. $pdf->SetSubject('动漫剧本导出');
  8803. $pdf->SetMargins(15, 15, 15);
  8804. $pdf->SetAutoPageBreak(true, 15);
  8805. // 剧本名
  8806. $pdf->AddPage();
  8807. $pdf->SetFont('simsun', 'B', 20);
  8808. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  8809. $pdf->Ln(5);
  8810. // 故事梗概
  8811. $intro = trim((string)getProp($anime, 'intro', ''));
  8812. if ($intro !== '') {
  8813. $this->pdfSectionTitle($pdf, '故事梗概');
  8814. $this->pdfBody($pdf, $intro);
  8815. }
  8816. // 美术风格
  8817. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  8818. if ($artStyle !== '') {
  8819. $this->pdfSectionTitle($pdf, '美术风格');
  8820. $this->pdfBody($pdf, $artStyle);
  8821. }
  8822. // 主体列表(文字+图片)
  8823. $this->pdfSectionTitle($pdf, '主体列表');
  8824. foreach ($roles as $index => $role) {
  8825. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  8826. }
  8827. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  8828. // 场景列表(文字+图片)
  8829. $this->pdfSectionTitle($pdf, '场景列表');
  8830. foreach ($scenes as $index => $scene) {
  8831. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  8832. }
  8833. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  8834. // 道具列表(文字+图片)
  8835. $this->pdfSectionTitle($pdf, '道具列表');
  8836. foreach ($props as $index => $prop) {
  8837. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  8838. }
  8839. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  8840. // 分镜剧本
  8841. $this->pdfSectionTitle($pdf, '分镜剧本');
  8842. foreach ($episodeScripts as $episodeScript) {
  8843. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  8844. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  8845. if ($episodeTitleRaw !== '') {
  8846. // title 字段可能已带"第N集"前缀,避免重复
  8847. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  8848. $episodeTitle = $episodeTitleRaw;
  8849. } else {
  8850. $episodeTitle .= ':' . $episodeTitleRaw;
  8851. }
  8852. }
  8853. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  8854. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  8855. if (getProp($episodeScript, 'narrator_voice') !== '') {
  8856. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  8857. }
  8858. foreach (getProp($episodeScript, 'acts', []) as $act) {
  8859. $actTitle = '片段' . getProp($act, 'act_number');
  8860. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  8861. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  8862. }
  8863. $this->pdfSubTitle($pdf, $actTitle, 12);
  8864. if (getProp($act, 'content') !== '') {
  8865. $this->pdfBody($pdf, getProp($act, 'content'));
  8866. }
  8867. }
  8868. }
  8869. return $pdf;
  8870. }
  8871. /**
  8872. * PDF章节标题(带分隔线)
  8873. */
  8874. private function pdfSectionTitle($pdf, $title) {
  8875. if ($pdf->GetY() > 230) {
  8876. $pdf->AddPage();
  8877. }
  8878. $pdf->SetFont('simsun', 'B', 15);
  8879. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  8880. $y = $pdf->GetY();
  8881. $pdf->SetLineWidth(0.4);
  8882. $pdf->Line(15, $y, 195, $y);
  8883. $pdf->Ln(4);
  8884. }
  8885. /**
  8886. * PDF子标题(集数/片段标题)
  8887. */
  8888. private function pdfSubTitle($pdf, $title, $size = 13) {
  8889. if ($pdf->GetY() > 240) {
  8890. $pdf->AddPage();
  8891. }
  8892. $pdf->SetFont('simsun', 'B', $size);
  8893. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  8894. $pdf->Ln(1);
  8895. }
  8896. /**
  8897. * PDF正文段落
  8898. */
  8899. private function pdfBody($pdf, $text) {
  8900. $pdf->SetFont('simsun', '', 11);
  8901. $pdf->MultiCell(0, 6, $text, 0, 'L');
  8902. $pdf->Ln(2);
  8903. }
  8904. /**
  8905. * 输出列表项图片(每张图单独一页,图下标注名称)
  8906. * @param \TCPDF $pdf
  8907. * @param array $items 列表项
  8908. * @param string $nameKey role|scene|prop
  8909. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8910. */
  8911. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  8912. foreach ($items as $item) {
  8913. $url = trim((string)getProp($item, 'url', ''));
  8914. $name = trim((string)getProp($item, $nameKey, ''));
  8915. if ($url === '' || !isset($imageCache[$url])) continue;
  8916. $imgPath = $imageCache[$url];
  8917. $size = @getimagesize($imgPath);
  8918. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  8919. continue;
  8920. }
  8921. $pdf->AddPage();
  8922. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  8923. $maxW = 160;
  8924. $maxH = 170;
  8925. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  8926. $drawW = $size[0] * $ratio;
  8927. $drawH = $size[1] * $ratio;
  8928. $x = (210 - $drawW) / 2;
  8929. $y = max(15, (297 - $drawH) / 2 - 10);
  8930. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  8931. // 图下标注名称
  8932. $pdf->SetFont('simsun', 'B', 13);
  8933. $pdf->SetY(297 - 28);
  8934. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  8935. }
  8936. }
  8937. /**
  8938. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  8939. * @param array $items 包含url字段的列表项
  8940. * @return array url => 临时文件路径
  8941. */
  8942. private function downloadImagesConcurrently(array $items) {
  8943. // 收集唯一的图片URL
  8944. $urls = [];
  8945. foreach ($items as $item) {
  8946. $url = trim((string)getProp($item, 'url', ''));
  8947. if ($url !== '') $urls[$url] = true;
  8948. }
  8949. if (!$urls) return [];
  8950. $urls = array_keys($urls);
  8951. $tmpDir = sys_get_temp_dir();
  8952. $rawFiles = [];
  8953. foreach ($urls as $url) {
  8954. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  8955. $rawFiles[$url] = $rawFile;
  8956. }
  8957. $client = new Client(['timeout' => 180, 'verify' => false]);
  8958. // 低并发下载,sink写入文件避免大图占用内存
  8959. $generator = (function () use ($urls, $client, $rawFiles) {
  8960. foreach ($urls as $url) {
  8961. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  8962. }
  8963. })();
  8964. $errors = [];
  8965. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  8966. 'concurrency' => 4,
  8967. 'rejected' => function ($reason, $url) use (&$errors) {
  8968. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  8969. },
  8970. ]);
  8971. $each->promise()->wait();
  8972. // 失败的图片串行重试一次(独占带宽,提高成功率)
  8973. foreach ($urls as $url) {
  8974. if (!isset($errors[$url])) continue;
  8975. try {
  8976. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  8977. unset($errors[$url]);
  8978. } catch (\Throwable $e) {
  8979. // 重试仍失败
  8980. }
  8981. }
  8982. $cache = [];
  8983. foreach ($urls as $url) {
  8984. $rawFile = $rawFiles[$url];
  8985. if (isset($errors[$url])) {
  8986. dLog('anime')->error('导出PDF图片下载失败', [
  8987. 'url' => $url,
  8988. 'error' => $errors[$url],
  8989. ]);
  8990. @unlink($rawFile);
  8991. continue;
  8992. }
  8993. $converted = $this->convertImageFile($rawFile, $url);
  8994. if ($converted !== null) {
  8995. $cache[$url] = $converted;
  8996. } else {
  8997. @unlink($rawFile);
  8998. }
  8999. }
  9000. return $cache;
  9001. }
  9002. /**
  9003. * 将已下载的图片文件缩放并转为JPEG
  9004. * @param string $rawFile 原始图片临时文件
  9005. * @param string $url 图片地址(用于命名)
  9006. * @return string|null 转换后的文件路径,转换失败返回null
  9007. */
  9008. private function convertImageFile($rawFile, $url) {
  9009. $content = @file_get_contents($rawFile);
  9010. if ($content === false || $content === '') return null;
  9011. if (!function_exists('imagecreatefromstring')) return null;
  9012. $image = @imagecreatefromstring($content);
  9013. if ($image === false) return null;
  9014. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  9015. imagedestroy($image);
  9016. if ($jpeg !== null) {
  9017. @unlink($rawFile);
  9018. }
  9019. return $jpeg;
  9020. }
  9021. /**
  9022. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  9023. * @param resource $srcImage GD图片资源
  9024. * @param string $rawFile 原始图片临时文件
  9025. * @param string $url 图片地址(用于命名)
  9026. * @return string|null 压缩后的JPEG文件路径
  9027. */
  9028. private function compressImageForPdf($srcImage, $rawFile, $url) {
  9029. $maxBytes = 2 * 1024 * 1024; // 2MB
  9030. $sizes = [2048, 1600, 1280, 1024, 800];
  9031. $qualities = [85, 70, 55, 40];
  9032. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  9033. foreach ($sizes as $size) {
  9034. $resized = $this->copyAndResize($srcImage, $size);
  9035. $flat = $this->flattenToWhite($resized);
  9036. imagedestroy($resized);
  9037. foreach ($qualities as $quality) {
  9038. ob_start();
  9039. $saved = imagejpeg($flat, null, $quality);
  9040. $data = ob_get_clean();
  9041. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  9042. file_put_contents($jpeg, $data);
  9043. imagedestroy($flat);
  9044. dLog('anime')->info('导出PDF图片压缩完成', [
  9045. 'url' => $url,
  9046. 'size' => filesize($jpeg),
  9047. 'edge' => $size,
  9048. 'quality' => $quality,
  9049. ]);
  9050. return $jpeg;
  9051. }
  9052. }
  9053. imagedestroy($flat);
  9054. }
  9055. // 兜底:最小尺寸、最低质量强制输出
  9056. $resized = $this->copyAndResize($srcImage, 800);
  9057. $flat = $this->flattenToWhite($resized);
  9058. imagedestroy($resized);
  9059. $saved = imagejpeg($flat, $jpeg, 30);
  9060. imagedestroy($flat);
  9061. if (!$saved) return null;
  9062. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  9063. 'url' => $url,
  9064. 'size' => filesize($jpeg),
  9065. ]);
  9066. return $jpeg;
  9067. }
  9068. /**
  9069. * 等比缩放图片副本(不销毁原图)
  9070. * @param resource $srcImage GD图片资源
  9071. * @param int $maxEdge 最大边长
  9072. * @return resource
  9073. */
  9074. private function copyAndResize($srcImage, $maxEdge) {
  9075. $width = imagesx($srcImage);
  9076. $height = imagesy($srcImage);
  9077. $max = max($width, $height);
  9078. if ($max <= $maxEdge) {
  9079. $copy = imagecreatetruecolor($width, $height);
  9080. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  9081. return $copy;
  9082. }
  9083. $ratio = $maxEdge / $max;
  9084. $newWidth = max(1, (int)round($width * $ratio));
  9085. $newHeight = max(1, (int)round($height * $ratio));
  9086. $resized = imagecreatetruecolor($newWidth, $newHeight);
  9087. imagealphablending($resized, false);
  9088. imagesavealpha($resized, true);
  9089. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  9090. return $resized;
  9091. }
  9092. /**
  9093. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  9094. * @param resource $image GD图片资源
  9095. * @return resource
  9096. */
  9097. private function flattenToWhite($image) {
  9098. $width = imagesx($image);
  9099. $height = imagesy($image);
  9100. $flat = imagecreatetruecolor($width, $height);
  9101. $white = imagecolorallocate($flat, 255, 255, 255);
  9102. imagefill($flat, 0, 0, $white);
  9103. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  9104. return $flat;
  9105. }
  9106. /**
  9107. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  9108. * @param string $content 片段内容
  9109. * @param int $counter 当前已编号数量(引用传递,整集累计)
  9110. * @return string
  9111. */
  9112. private function renumberSegmentBlocks($content, &$counter) {
  9113. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  9114. $counter++;
  9115. return '【' . $match[1] . $counter . '】';
  9116. }, $content);
  9117. }
  9118. }