AnimeService.php 387 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963
  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\Services\AIGeneration\AIImageGenerationService;
  9. use App\Services\AIGeneration\AIVideoGenerationService;
  10. use App\Services\DeepSeek\DeepSeekService;
  11. use Dflydev\DotAccessData\Util;
  12. use GuzzleHttp\Client;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. use OSS\Core\OssException;
  17. use OSS\OssClient;
  18. class AnimeService
  19. {
  20. protected $aiImageGenerationService;
  21. protected $aiVideoGenerationService;
  22. protected $DeepSeekService;
  23. private $url;
  24. private $api_key;
  25. private $headers;
  26. public function __construct(
  27. AIImageGenerationService $aiImageGenerationService,
  28. AIVideoGenerationService $aiVideoGenerationService,
  29. DeepSeekService $DeepSeekService
  30. ) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->aiVideoGenerationService = $aiVideoGenerationService;
  33. $this->DeepSeekService = $DeepSeekService;
  34. $this->url = 'https://api.deepseek.com/chat/completions';
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. }
  41. /**
  42. * 构建统一的分镜数据结构(episodeInfo格式)
  43. * @param array $segments 分镜数据数组
  44. * @return array 返回包含acts和total_duration的数组
  45. */
  46. public function buildEpisodeSegmentsStructure($segments) {
  47. $acts = [];
  48. $totalDuration = 0; // 初始化总时长
  49. foreach($segments as $segment) {
  50. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  51. $videoDuration = getProp($segment, 'video_duration');
  52. $audioDuration = getProp($segment, 'audio_duration');
  53. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  54. $totalDuration += floatval($videoDuration);
  55. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  56. $totalDuration += floatval($audioDuration);
  57. } else {
  58. $totalDuration += 5; // 默认5秒
  59. }
  60. $segment_content = getProp($segment, 'segment_content');
  61. // 判断是否有尾帧描述,如果有则去掉这部分内容
  62. if (strpos($segment_content, '尾帧') !== false) {
  63. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  64. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  65. }
  66. // 构建分镜信息
  67. $segmentInfo = [
  68. 'segment_id' => getProp($segment, 'segment_id'),
  69. 'segment_number' => getProp($segment, 'segment_number'),
  70. 'segment_content' => $segment_content,
  71. 'description' => getProp($segment, 'description'),
  72. 'composition' => getProp($segment, 'composition'),
  73. 'camera_movement' => getProp($segment, 'camera_movement'),
  74. 'voice_actor' => getProp($segment, 'voice_actor'),
  75. 'dialogue' => getProp($segment, 'dialogue'),
  76. 'frame_type' => getProp($segment, 'frame_type'),
  77. 'scene' => getProp($segment, 'scene'),
  78. 'characters' => getProp($segment, 'characters'),
  79. 'tail_frame' => getProp($segment, 'tail_frame'),
  80. 'emotion' => getProp($segment, 'emotion'),
  81. 'emotion_type' => getProp($segment, 'emotion_type'),
  82. 'gender' => getProp($segment, 'gender'),
  83. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  84. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  85. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  86. 'pitch' => getProp($segment, 'pitch'),
  87. 'voice_name' => getProp($segment, 'voice_name'),
  88. 'voice_type' => getProp($segment, 'voice_type'),
  89. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  90. 'img_url' => getProp($segment, 'img_url'),
  91. 'audio_url' => getProp($segment, 'audio_url'),
  92. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  93. 'video_url' => getProp($segment, 'video_url'),
  94. 'video_duration' => getProp($segment, 'video_duration', 0),
  95. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  96. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  97. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  98. 'current_type' => getProp($segment, 'current_type'),
  99. ];
  100. $actNumber = getProp($segment, 'act_number');
  101. if (isset($acts[$actNumber])) {
  102. $acts[$actNumber]['segments'][] = $segmentInfo;
  103. } else {
  104. $acts[$actNumber] = [
  105. 'act_number' => $actNumber,
  106. 'act_title' => getProp($segment, 'act_title'),
  107. 'act_duration' => getProp($segment, 'act_duration'),
  108. 'segments' => [$segmentInfo]
  109. ];
  110. }
  111. }
  112. return [
  113. 'acts' => array_values($acts),
  114. 'total_duration' => intval(round($totalDuration))
  115. ];
  116. }
  117. /**
  118. * 构建统一的分段数据结构(episodeInfoForAce格式)
  119. * @param array $segments 分段数据数组
  120. * @return array 返回包含acts和total_duration的数组
  121. */
  122. public function buildEpisodeActsStructureForAce($segments) {
  123. $acts = [];
  124. $totalDuration = 0; // 初始化总时长
  125. foreach($segments as $segment) {
  126. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  127. $videoDuration = getProp($segment, 'video_duration');
  128. $actDuration = getProp($segment, 'act_duration');
  129. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  130. $totalDuration += floatval($videoDuration);
  131. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  132. $totalDuration += floatval($actDuration);
  133. } else {
  134. $totalDuration += 5; // 默认5秒
  135. }
  136. // 构建分镜信息
  137. $segmentInfo = [
  138. 'act_id' => getProp($segment, 'id'),
  139. 'act_number' => getProp($segment, 'act_number'),
  140. 'act_title' => getProp($segment, 'act_title'),
  141. 'act_duration' => getProp($segment, 'act_duration'),
  142. 'act_content' => getProp($segment, 'act_content'),
  143. 'video_url' => getProp($segment, 'video_url'),
  144. 'video_duration' => getProp($segment, 'video_duration', 0),
  145. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  146. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  147. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  148. 'current_type' => getProp($segment, 'current_type'),
  149. ];
  150. $acts[] = $segmentInfo;
  151. }
  152. return [
  153. 'acts' => array_values($acts),
  154. 'total_duration' => intval(round($totalDuration))
  155. ];
  156. }
  157. /**
  158. * 验证画面比例是否有效
  159. * @param string $ratio 画面比例
  160. * @return bool
  161. */
  162. public function validateRatio($ratio) {
  163. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  164. }
  165. /**
  166. * 获取画面比例对应的宽高
  167. * @param string $ratio 画面比例
  168. * @return array ['width' => int, 'height' => int]
  169. * @throws \Exception
  170. */
  171. private function getRatioDimensions($ratio) {
  172. if ($ratio && !$this->validateRatio($ratio)) {
  173. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  174. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  175. }
  176. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  177. }
  178. public function createAnime($data) {
  179. $uid = Site::getUid();
  180. $cpid = Site::getCpid();
  181. $input_art_style = getProp($data, 'art_style');
  182. $file = getProp($data, 'file');
  183. $content = getProp($data, 'content', '');
  184. $bid = getProp($data, 'bid', 0);
  185. $script_id = getProp($data, 'script_id', 0);
  186. $ace_mode = getProp($data, 'ace_mode', 0);
  187. $extra_products = getProp($data, 'products', []);
  188. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  189. if (!is_array($extra_products)) {
  190. Utils::throwError('20003:传入的资产格式不正确');
  191. }
  192. // 替换美术风格
  193. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  194. // 提取文件内容
  195. if ($file) {
  196. $content = $this->DeepSeekService->extractFileContent($file);
  197. if (!$content) {
  198. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  199. }
  200. } elseif ($script_id) {
  201. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  202. if (!$content) {
  203. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  204. }
  205. } elseif ($bid) {
  206. $content = $this->DeepSeekService->getContentByBid($bid);
  207. if (!$content) {
  208. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  209. }
  210. } elseif ($content) {
  211. $content = filterContent($content);
  212. }else {
  213. $content = '';
  214. }
  215. $anime_data = [
  216. 'user_id' => $uid,
  217. 'cpid' => $cpid,
  218. 'anime_name' => '新剧本策划',
  219. 'is_multi' => getProp($data, 'is_multi', 1),
  220. 'content' => $content,
  221. 'art_style_type' => $input_art_style,
  222. 'ace_mode' => $ace_mode,
  223. 'script_id' => $script_id,
  224. 'extra_products' => json_encode($extra_products, 256),
  225. 'created_at' => date('Y-m-d H:i:s'),
  226. 'updated_at' => date('Y-m-d H:i:s'),
  227. ];
  228. // 处理文本模型
  229. $model = getProp($data, 'model');
  230. if (!$model) {
  231. // 用户没有输入,使用默认值
  232. $model = 'deepseek-v4-pro';
  233. }
  234. // 验证模型是否在可用模型表中
  235. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  236. $model = 'deepseek-v4-pro';
  237. }
  238. $anime_data['model'] = $model;
  239. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  240. return DB::table('mp_animes')->insertGetId($anime_data);
  241. }
  242. public function chatList($data) {
  243. $uid = Site::getUid();
  244. $anime_name = getProp($data, 'anime_name');
  245. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  246. if ($anime_name) {
  247. $query->where('anime_name', 'like', "%$anime_name%");
  248. }
  249. return $query->orderBy('id', 'desc')->paginate();
  250. }
  251. public function chatHistory($data) {
  252. $anime_id = getProp($data, 'anime_id');
  253. $sequence = getProp($data, 'sequence', 0);
  254. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  255. $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)
  256. ->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');
  257. return $query->orderBy('ar.id')->get()->map(function ($value) {
  258. $value = (array)$value;
  259. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  260. $value['created_at'] = transDate($value['created_at']);
  261. $value['episode_created_at'] = transDate($value['episode_created_at']);
  262. return $value;
  263. })->toArray();
  264. }
  265. public function batchSetRoleImg($data) {
  266. $episode_id = getProp($data, 'episode_id');
  267. if (!$episode_id) Utils::throwError('1002:请选择分集');
  268. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  269. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  270. $art_style = getProp($episode, 'art_style');
  271. $anime_id = getProp($episode, 'anime_id');
  272. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  273. $art_style_type = getProp($anime, 'art_style_type');
  274. $character_prefix = '';
  275. $scene_prefix = '';
  276. if ($art_style_type) {
  277. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  278. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  279. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  280. }
  281. foreach ($roles as &$role) {
  282. $role_name = getProp($role, 'role');
  283. if ($role_name == '旁白') continue;
  284. // 优先使用 pic_prompt,如果没有则使用 description
  285. $pic_prompt = getProp($role, 'pic_prompt');
  286. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  287. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  288. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  289. // 参考图地址
  290. $ref_img_url = getProp($role, 'url');
  291. if ($ref_img_url) continue; // 已有图片则跳过
  292. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  293. try {
  294. $params = [
  295. 'prompt' => $description,
  296. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  297. ];
  298. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  299. $task_id = $task->id;
  300. if (!$task_id) {
  301. Utils::throwError("20003:角色({$role_name})生成图片失败");
  302. }
  303. $role['task_id'] = $task_id;
  304. $role['task_status'] = 'processing';
  305. } catch (\Exception $e) {
  306. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  307. Utils::throwError("20003:" . $e->getMessage());
  308. }
  309. }
  310. // 保存角色信息
  311. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  312. 'roles' => json_encode($roles, 256),
  313. 'generate_status' => '执行中',
  314. 'generate_at' => date('Y-m-d H:i:s'),
  315. 'updated_at' => date('Y-m-d H:i:s')
  316. ]);
  317. if (!$boolen) {
  318. Utils::throwError('20003:保存角色信息失败');
  319. }
  320. return $boolen;
  321. }
  322. public function batchSetSceneImg($data) {
  323. $episode_id = getProp($data, 'episode_id');
  324. if (!$episode_id) Utils::throwError('1002:请选择分集');
  325. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  326. $scenes = json_decode(getProp($episode, 'scenes'), true);
  327. $art_style = getProp($episode, 'art_style');
  328. $target_scene = getProp($data, 'target_scene');
  329. $anime_id = getProp($episode, 'anime_id');
  330. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  331. $art_style_type = getProp($anime, 'art_style_type');
  332. $character_prefix = '';
  333. $scene_prefix = '';
  334. if ($art_style_type) {
  335. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  336. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  337. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  338. }
  339. foreach ($scenes as &$scene) {
  340. $scene_name = getProp($scene, 'scene');
  341. if ($scene_name != $target_scene) continue;
  342. // 优先使用 pic_prompt,如果没有则使用 description
  343. $pic_prompt = getProp($scene, 'pic_prompt');
  344. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  345. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  346. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  347. // 参考图地址
  348. $ref_img_url = getProp($scene, 'url');
  349. if ($ref_img_url) continue; // 已有图片则跳过
  350. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  351. try {
  352. $params = [
  353. 'prompt' => $description,
  354. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  355. ];
  356. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  357. $task_id = $task->id;
  358. if (!$task_id) {
  359. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  360. }
  361. $scene['task_id'] = $task_id;
  362. $scene['task_status'] = 'processing';
  363. } catch (\Exception $e) {
  364. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  365. Utils::throwError("20003:" . $e->getMessage());
  366. }
  367. }
  368. // 保存场景信息
  369. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  370. 'scenes' => json_encode($scenes, 256),
  371. 'generate_status' => '执行中',
  372. 'generate_at' => date('Y-m-d H:i:s'),
  373. 'updated_at' => date('Y-m-d H:i:s')
  374. ]);
  375. if (!$boolen) {
  376. Utils::throwError('20003:保存角色信息失败');
  377. }
  378. return $boolen;
  379. }
  380. public function editAnime($data) {
  381. $anime_id = getProp($data, 'anime_id');
  382. $anime_name = trim(getProp($data, 'anime_name'));
  383. // 确认对话名称唯一性
  384. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  385. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  386. }
  387. if (!$anime_id || !$anime_name) {
  388. Utils::throwError('20003:参数异常');
  389. }
  390. return DB::table('mp_animes')->where('id', $anime_id)->update([
  391. 'anime_name' => $anime_name,
  392. 'updated_at' => date('Y-m-d H:i:s')
  393. ]);
  394. // $script_arr =getProp($data, 'script', []);
  395. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  396. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  397. // $anime_id = getProp($data, 'anime_id');
  398. // try {
  399. // DB::beginTransaction();
  400. // $table_data = [
  401. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  402. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  403. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  404. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  405. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  406. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  407. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  408. // 'status' => 3,
  409. // 'start_episode_sequence' => $start_episode_sequence,
  410. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  411. // 'episode_num' => count($script_arr['episodes']),
  412. // 'updated_at' => date('Y-m-d H:i:s')
  413. // ];
  414. // // 保存剧本内容
  415. // if (!empty($anime_id)) {
  416. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  417. // if (!$boolen) {
  418. // dLog('anime')->info('对话保存失败', $table_data);
  419. // Utils::throwError('20003:对话保存失败');
  420. // }
  421. // }else {
  422. // $table['created_at'] = $table_data['updated_at'];
  423. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  424. // if (!$anime_id) {
  425. // dLog('anime')->info('对话保存失败', $table_data);
  426. // Utils::throwError('20003:对话保存失败');
  427. // }
  428. // }
  429. // // 保存分集内容
  430. // // 删除历史分集内容
  431. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  432. // $episodes = [];
  433. // $sequence = 1;
  434. // foreach ($script_arr['episodes'] as $episode) {
  435. // $segment_number = 1;
  436. // foreach($episode['segments'] as $segment) {
  437. // $episodes[] = [
  438. // 'anime_id' => $anime_id,
  439. // 'episode_number' => $episode['episode_number'],
  440. // 'title' => $episode['title'],
  441. // // 'content' => $episode['content'],
  442. // 'content' => '',
  443. // 'segment_number' => $segment_number,
  444. // 'segment_content' => $segment['segment_content'],
  445. // 'sequence' => $sequence,
  446. // 'created_at' => date('Y-m-d H:i:s'),
  447. // 'updated_at' => date('Y-m-d H:i:s')
  448. // ];
  449. // $sequence++;
  450. // $segment_number++;
  451. // }
  452. // }
  453. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  454. // if (!$boolen2) {
  455. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  456. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  457. // Utils::throwError('20003:分集内容保存失败');
  458. // }
  459. // } catch (\Exception $e) {
  460. // DB::rollBack();
  461. // Utils::throwError('20003:'.$e->getMessage());
  462. // }
  463. // DB::commit();
  464. // return true;
  465. }
  466. public function delAnime($data) {
  467. $anime_id = getProp($data, 'anime_id');
  468. if (!$anime_id) {
  469. Utils::throwError('20003:请选择剧本');
  470. }
  471. return DB::table('mp_animes')->where('id', $anime_id)->update([
  472. 'is_deleted' => 1,
  473. 'updated_at' => date('Y-m-d H:i:s')
  474. ]);
  475. }
  476. public function animeDetail($data) {
  477. $uid = Site::getUid();
  478. $anime_id = getProp($data, 'anime_id');
  479. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  480. ->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();
  481. if (!$anime) Utils::throwError('20003:权限不足');
  482. $anime = (array)$anime;
  483. $anime['roles'] = json_decode($anime['roles']);
  484. $anime['scenes'] = json_decode($anime['scenes']);
  485. // 获取分集信息
  486. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  487. ->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"))
  488. ->orderBy('episode_number')->get()->map(function ($value) {
  489. return (array)$value;
  490. })->toArray();
  491. $anime['episodes'] = $episodes;
  492. return $anime;
  493. }
  494. public function episodeInfo($data) {
  495. $uid = Site::getUid();
  496. $anime_id = getProp($data, 'anime_id');
  497. $episode_id = getProp($data, 'episode_id');
  498. if (!$anime_id || !$episode_id) {
  499. Utils::throwError('1002:请选择剧集');
  500. }
  501. // 验证用户权限
  502. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  503. if (!$anime) Utils::throwError('20003:权限不足');
  504. $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();
  505. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  506. $episode = (array)$episode;
  507. $episode['roles'] = json_decode($episode['roles'], true);
  508. // foreach($episode['roles'] as &$item) {
  509. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  510. // }
  511. $episode['scenes'] = json_decode($episode['scenes'], true);
  512. // foreach($episode['scenes'] as &$item) {
  513. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  514. // }
  515. // 获取分镜信息
  516. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  517. ->select('*')->get()->map(function ($value) {
  518. return (array)$value;
  519. })->toArray();
  520. // 使用公共方法构建分镜结构
  521. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  522. $episode['acts'] = $segmentsStructure['acts'];
  523. $episode['total_duration'] = $segmentsStructure['total_duration'];
  524. return $episode;
  525. }
  526. public function episodeInfoForAce($data) {
  527. $anime_id = getProp($data, 'anime_id');
  528. $episode_id = getProp($data, 'episode_id');
  529. if (!$anime_id || !$episode_id) {
  530. Utils::throwError('1002:请选择剧集');
  531. }
  532. $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();
  533. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  534. $episode = (array)$episode;
  535. $episode['roles'] = json_decode($episode['roles'], true);
  536. // foreach($episode['roles'] as &$item) {
  537. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  538. // }
  539. $episode['scenes'] = json_decode($episode['scenes'], true);
  540. // foreach($episode['scenes'] as &$item) {
  541. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  542. // }
  543. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  544. // 获取分镜信息
  545. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  546. ->select('*')->get()->map(function ($value) {
  547. return (array)$value;
  548. })->toArray();
  549. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  550. $episode['acts'] = $segmentsStructure['acts'];
  551. $episode['total_duration'] = $segmentsStructure['total_duration'];
  552. // 获取mp_animes表中的视频参数
  553. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  554. $episode['video_params'] = [
  555. 'video_model' => getProp($anime, 'video_model'),
  556. 'video_resolution' => getProp($anime, 'video_resolution'),
  557. 'ratio' => getProp($anime, 'video_ratio'),
  558. ];
  559. return $episode;
  560. }
  561. public function segmentInfo($data) {
  562. $uid = Site::getUid();
  563. $segment_id = getProp($data, 'segment_id');
  564. if (!$segment_id) {
  565. Utils::throwError('1002:请选择分镜');
  566. }
  567. // 获取分镜信息
  568. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  569. // 验证用户权限
  570. if ($segment) {
  571. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  572. if (!$anime) Utils::throwError('20003:权限不足');
  573. }
  574. $result = [
  575. 'segment_id' => getProp($segment, 'segment_id'),
  576. 'segment_number' => getProp($segment, 'segment_number'),
  577. 'segment_content' => getProp($segment, 'segment_content'),
  578. 'description' => getProp($segment, 'description'),
  579. 'composition' => getProp($segment, 'composition'),
  580. 'camera_movement' => getProp($segment, 'camera_movement'),
  581. 'voice_actor' => getProp($segment, 'voice_actor'),
  582. 'dialogue' => getProp($segment, 'dialogue'),
  583. 'frame_type' => getProp($segment, 'frame_type'),
  584. 'scene' => getProp($segment, 'scene'),
  585. 'characters' => getProp($segment, 'characters'),
  586. 'tail_frame' => getProp($segment, 'tail_frame'),
  587. 'emotion' => getProp($segment, 'emotion'),
  588. 'emotion_type' => getProp($segment, 'emotion_type'),
  589. 'gender' => getProp($segment, 'gender'),
  590. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  591. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  592. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  593. 'pitch' => getProp($segment, 'pitch'),
  594. 'voice_name' => getProp($segment, 'voice_name'),
  595. 'voice_type' => getProp($segment, 'voice_type'),
  596. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  597. 'img_url' => getProp($segment, 'img_url'),
  598. 'video_url' => getProp($segment, 'video_url'),
  599. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  600. ];
  601. return $result;
  602. }
  603. public function copyEpisodeVersion($data) {
  604. $episode_id = getProp($data, 'episode_id');
  605. $uid = Site::getUid();
  606. $cpid = Site::getCpid();
  607. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  608. if (!$episode) Utils::throwError('20003:该剧集不存在');
  609. $episode = (array)$episode;
  610. $anime_id = $episode['anime_id'];
  611. $episode_number = $episode['episode_number'];
  612. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  613. $sequence = $count + 1;
  614. unset($episode['id']);
  615. $now = date('Y-m-d H:i:s');
  616. $episode['created_at'] = $now;
  617. $episode['updated_at'] = $now;
  618. $episode['is_default'] = 1;
  619. // 获取版本中含有"(副本"字样的个数
  620. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  621. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  622. $episode['sequence'] = $sequence;
  623. $episode['is_generated'] = 0;
  624. $episode['cpid'] = $cpid;
  625. // 获取ace_mode
  626. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  627. try {
  628. DB::beginTransaction();
  629. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  630. // 新增副本
  631. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  632. if (!$new_episode_id) {
  633. Utils::throwError('20003:创建副本失败!');
  634. }
  635. // 获取分镜数据并准备插入
  636. $segments_for_insert = DB::table('mp_episode_segments')
  637. ->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')
  638. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  639. $item = (array)$item;
  640. $item['episode_id'] = $new_episode_id;
  641. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  642. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  643. return $item;
  644. })->toArray();
  645. // 写入分镜数据
  646. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  647. if (!$boolen2) {
  648. Utils::throwError('20003:写入分镜数据失败!');
  649. }
  650. // 写入对话历史
  651. $records = [
  652. [
  653. 'uid' => $uid,
  654. 'anime_id' => $anime_id,
  655. 'role' => 'user',
  656. 'content' => '创建副本',
  657. 'sequence' => $episode_number,
  658. 'episode_id' => $new_episode_id,
  659. 'created_at' => $now,
  660. 'updated_at' => $now
  661. ],
  662. [
  663. 'uid' => $uid,
  664. 'anime_id' => $anime_id,
  665. 'role' => 'assistant',
  666. 'content' => '好的,已为您创建副本',
  667. 'sequence' => $episode_number,
  668. 'episode_id' => $new_episode_id,
  669. 'created_at' => $now,
  670. 'updated_at' => $now
  671. ]
  672. ];
  673. $boolen3 = DB::table('mp_anime_records')->insert($records);
  674. if (!$boolen3) {
  675. Utils::throwError('20003:对话记录保存失败');
  676. }
  677. }catch (\Exception $e) {
  678. DB::rollBack();
  679. Utils::throwError('20003:'.$e->getMessage());
  680. }
  681. DB::commit();
  682. // 构建与 episodeInfo 方法一致的返回数据结构
  683. $result = [
  684. 'episode_id' => $new_episode_id,
  685. 'anime_id' => $anime_id,
  686. 'episode_number' => $episode_number,
  687. 'title' => $episode['title'],
  688. 'intro' => $episode['intro'],
  689. 'art_style' => $episode['art_style'],
  690. 'roles' => json_decode($episode['roles'], true),
  691. 'scenes' => json_decode($episode['scenes'], true),
  692. 'is_generated' => (int)$episode['is_generated']
  693. ];
  694. if ((int)$ace_mode === 1) {
  695. // 获取分镜信息
  696. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  697. ->select('*')->get()->map(function ($value) {
  698. return (array)$value;
  699. })->toArray();
  700. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  701. }else {
  702. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  703. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  704. }
  705. $result['acts'] = $segmentsStructure['acts'];
  706. $result['total_duration'] = $segmentsStructure['total_duration'];
  707. return $result;
  708. }
  709. public function episodeVersions($data) {
  710. $anime_id = getProp($data, 'anime_id');
  711. $episode_id = getProp($data, 'episode_id');
  712. if (!$anime_id || !$episode_id) {
  713. Utils::throwError('1002:请选择剧集');
  714. }
  715. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  716. $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) {
  717. return (array)$value;
  718. })->toArray();
  719. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  720. foreach($episodes as &$episode) {
  721. $episode['version'] = 'V'.$episode['sequence'];
  722. $episode['roles'] = json_decode($episode['roles'], true);
  723. $episode['scenes'] = json_decode($episode['scenes'], true);
  724. // 获取分镜信息
  725. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  726. ->select('*')->get()->map(function ($value) {
  727. return (array)$value;
  728. })->toArray();
  729. // 使用公共方法构建分镜结构
  730. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  731. $episode['acts'] = $segmentsStructure['acts'];
  732. $episode['total_duration'] = $segmentsStructure['total_duration'];
  733. }
  734. return $episodes;
  735. }
  736. public function bindEpisodeVersion($data) {
  737. $episode_id = getProp($data, 'episode_id');
  738. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  739. if (!$episode) Utils::throwError('20003:该剧集不存在');
  740. $episode = (array)$episode;
  741. if ((int)$episode['is_default'] === 1) return true;
  742. try {
  743. DB::beginTransaction();
  744. // 移除is_default标志
  745. $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')]);
  746. if (!$boolen) {
  747. Utils::throwError('20003:更新失败!');
  748. }
  749. // 绑定副本
  750. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  751. if (!$boolen2) {
  752. Utils::throwError('20003:绑定失败!');
  753. }
  754. }catch (\Exception $e) {
  755. DB::rollBack();
  756. Utils::throwError('20003:'.$e->getMessage());
  757. }
  758. DB::commit();
  759. return true;
  760. }
  761. public function chatChangeImg($data) {
  762. $segment_id = getProp($data, 'segment_id');
  763. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  764. $prompt = getProp($data, 'prompt');
  765. if (!$prompt || !$segment_id) {
  766. Utils::throwError('1002:请输入提示词,并且选择分镜');
  767. }
  768. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  769. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  770. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  771. else $ref_img_url = '';
  772. // $ref_img_url = '';
  773. if (empty($prompt)) {
  774. if (empty($ref_img_url)) {
  775. $prompt = getProp($segment, 'segment_content');
  776. }else {
  777. $prompt = '请根据图片生成';
  778. }
  779. }
  780. $anime_id = getProp($segment, 'anime_id');
  781. $episode_id = getProp($segment, 'episode_id');
  782. $episode_number = getProp($segment, 'episode_number');
  783. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  784. $ratio = getProp($data, 'ratio');
  785. if (!$ratio) {
  786. $ratio = getProp($episode, 'ratio');
  787. if (!$ratio) $ratio = '9:16';
  788. }
  789. $art_style = getProp($episode, 'art_style');
  790. if ($art_style) {
  791. $prompt = "美术风格:{$art_style}\n{$prompt}";
  792. }
  793. $dimensions = $this->getRatioDimensions($ratio);
  794. $width = $dimensions['width'];
  795. $height = $dimensions['height'];
  796. try {
  797. $params = [
  798. 'alias_segment_id' => $segment_id,
  799. 'prompt' => $prompt,
  800. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  801. 'width' => $width,
  802. 'height' => $height
  803. ];
  804. // 优化提示词(不要生成字幕)
  805. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  806. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  807. $task_id = $task->id;
  808. if (!$task_id) {
  809. Utils::throwError("20003:生成图片失败");
  810. }
  811. // 更新任务ID
  812. $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')]);
  813. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  814. } catch (\Exception $e) {
  815. Utils::throwError("20003:" . $e->getMessage());
  816. }
  817. // 创建任务之后先暂停10s等待异步任务完成
  818. sleep(10);
  819. $img_url = $this->loopGetPicTaskResult($task_id);
  820. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  821. // 图片生成后新增对话记录
  822. try {
  823. $uid = Site::getUid();
  824. $now = date('Y-m-d H:i:s');
  825. // 使用AI反推图片提示词
  826. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  827. // 保存对话记录
  828. $records = [
  829. [
  830. 'uid' => $uid,
  831. 'anime_id' => $anime_id,
  832. 'sequence' => $episode_number,
  833. 'role' => 'user',
  834. 'content' => $prompt,
  835. 'segment_id' => $segment_id,
  836. 'image_url' => '',
  837. 'created_at' => $now,
  838. 'updated_at' => $now
  839. ],
  840. [
  841. 'uid' => $uid,
  842. 'anime_id' => $anime_id,
  843. 'sequence' => $episode_number,
  844. 'role' => 'assistant',
  845. 'content' => $pic_prompt,
  846. 'segment_id' => $segment_id,
  847. 'image_url' => $img_url,
  848. 'created_at' => $now,
  849. 'updated_at' => $now
  850. ]
  851. ];
  852. DB::table('mp_anime_records')->insert($records);
  853. } catch (\Exception $e) {
  854. // 记录日志但不影响主流程
  855. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  856. 'segment_id' => $segment_id,
  857. 'img_url' => $img_url
  858. ]);
  859. logDB('anime', 'error', '保存对话记录失败', [
  860. 'segment_id' => $segment_id,
  861. 'img_url' => $img_url,
  862. 'error' => $e->getMessage()
  863. ]);
  864. }
  865. return $img_url;
  866. }
  867. public function segmentChatHistory($data) {
  868. $segment_id = getProp($data, 'segment_id');
  869. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  870. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
  871. $chat = $query->orderBy('id')->get()->map(function ($value) {
  872. $value = (array)$value;
  873. $value['created_at'] = transDate($value['created_at']);
  874. return $value;
  875. })->toArray();
  876. // 获取历史图片
  877. $url = [];
  878. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  879. foreach($pic_history as $task) {
  880. $result_url = getProp($task, 'result_url');
  881. if (is_json($result_url)) {
  882. $url = array_merge($url, json_decode($result_url, true));
  883. }else {
  884. $url[] = $result_url;
  885. }
  886. }
  887. // 获取历史视频
  888. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  889. foreach($video_history as $task) {
  890. $result_url = getProp($task, 'compressed_url');
  891. if (is_json($result_url)) {
  892. $url = array_merge($url, json_decode($result_url, true));
  893. }else {
  894. $url[] = $result_url;
  895. }
  896. }
  897. return compact('chat', 'url');
  898. }
  899. public function changeEpisodeRoles($data) {
  900. $anime_id = getProp($data, 'anime_id');
  901. $episode_id = getProp($data, 'episode_id');
  902. $target_roles = getProp($data, 'roles');
  903. $is_deleted = getProp($data, 'is_deleted', 0);
  904. // 参数验证
  905. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  906. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  907. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  908. // 验证剧集是否存在
  909. $episode = DB::table('mp_anime_episodes')
  910. ->where('anime_id', $anime_id)
  911. ->where('id', $episode_id)
  912. ->first();
  913. if (!$episode) Utils::throwError('20003:该剧集不存在');
  914. $roles = json_decode(getProp($episode, 'roles'), true);
  915. // 获取anime信息,检查是否有关联的script_id
  916. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  917. if (!$anime) Utils::throwError('20003:动漫不存在');
  918. $script_id = getProp($anime, 'script_id');
  919. $episode_number = getProp($episode, 'episode_number', 1);
  920. $uid = Site::getUid();
  921. $cpid = Site::getCpid();
  922. try {
  923. $target_role_name = getProp($target_roles, 'role');
  924. if (empty($target_role_name)) {
  925. Utils::throwError('20003:角色名称不能为空');
  926. }
  927. // 如果是删除操作
  928. if ($is_deleted == 1) {
  929. // 从角色列表中移除该角色
  930. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  931. return getProp($role, 'role') !== $target_role_name;
  932. }));
  933. // 更新角色列表
  934. $result = DB::table('mp_anime_episodes')
  935. ->where('anime_id', $anime_id)
  936. ->where('id', $episode_id)
  937. ->update([
  938. 'roles' => json_encode($roles, 256),
  939. 'updated_at' => date('Y-m-d H:i:s')
  940. ]);
  941. if ($result === false) {
  942. Utils::throwError('20003:删除角色失败');
  943. }
  944. } else {
  945. // 新增或更新操作
  946. $role_found = false;
  947. $is_new_role = false;
  948. // 查找并更新已存在的角色
  949. foreach($roles as &$role) {
  950. if (getProp($role, 'role') === $target_role_name) {
  951. $role = $target_roles;
  952. $role_found = true;
  953. break;
  954. }
  955. }
  956. // 如果角色不存在,则新增
  957. if (!$role_found) {
  958. $roles[] = $target_roles;
  959. $is_new_role = true;
  960. }
  961. // 更新角色列表
  962. $result = DB::table('mp_anime_episodes')
  963. ->where('anime_id', $anime_id)
  964. ->where('id', $episode_id)
  965. ->update([
  966. 'roles' => json_encode($roles, 256),
  967. 'updated_at' => date('Y-m-d H:i:s')
  968. ]);
  969. if ($result === false) {
  970. Utils::throwError('20003:更新角色列表失败');
  971. }
  972. // 同步更新分镜表中对应主体的音色信息
  973. $voice_name = getProp($target_roles, 'voice_name');
  974. $voice_type = getProp($target_roles, 'voice_type');
  975. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  976. DB::table('mp_episode_segments')
  977. ->where('anime_id', $anime_id)
  978. ->where('episode_id', $episode_id)
  979. ->where('voice_actor', $target_role_name)
  980. ->update([
  981. 'voice_name' => $voice_name,
  982. 'voice_type' => $voice_type,
  983. 'voice_audio_url' => $voice_audio_url,
  984. 'updated_at' => date('Y-m-d H:i:s')
  985. ]);
  986. // 如果有关联的script_id,则同步到mp_products表
  987. if ($script_id) {
  988. // 查询剧本信息
  989. $script = DB::table('mp_scripts')
  990. ->where('id', $script_id)
  991. ->where('is_deleted', 0)
  992. ->first();
  993. if ($script) {
  994. $script_name = $script->script_name ?? 'script_' . $script_id;
  995. $product_name = getProp($target_roles, 'role');
  996. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  997. $url = getProp($target_roles, 'url', '');
  998. $product_type = 1; // 1=角色
  999. // 查找或创建以script_name命名的文件夹
  1000. $folder = DB::table('mp_products')
  1001. ->where('cpid', $cpid)
  1002. ->where('type', 2) // 文件夹类型
  1003. ->where('product', $product_type) // 角色类型
  1004. ->where('product_name', $script_name)
  1005. ->where('parent_id', 0)
  1006. ->where('is_deleted', 0)
  1007. ->first();
  1008. if (!$folder) {
  1009. // 创建文件夹
  1010. $folder_id = DB::table('mp_products')->insertGetId([
  1011. 'user_id' => $uid,
  1012. 'cpid' => $cpid,
  1013. 'type' => 2, // 文件夹
  1014. 'product' => $product_type, // 角色类型
  1015. 'parent_id' => 0,
  1016. 'level' => 1,
  1017. 'product_name' => $script_name,
  1018. 'sort_order' => time(),
  1019. 'is_deleted' => 0,
  1020. 'created_at' => date('Y-m-d H:i:s'),
  1021. 'updated_at' => date('Y-m-d H:i:s')
  1022. ]);
  1023. } else {
  1024. $folder_id = $folder->id;
  1025. }
  1026. // 查找该文件夹下是否已存在同名资产
  1027. $existing_product = DB::table('mp_products')
  1028. ->where('cpid', $cpid)
  1029. ->where('type', 1) // 资产类型
  1030. ->where('product', $product_type)
  1031. ->where('parent_id', $folder_id)
  1032. ->where('product_name', $product_name)
  1033. ->where('is_deleted', 0)
  1034. ->first();
  1035. if ($existing_product) {
  1036. // 更新已存在的资产
  1037. $updateData = [
  1038. 'pic_task_status' => '生成成功',
  1039. ];
  1040. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1041. if ($url) $updateData['url'] = $url;
  1042. // 处理versions字段
  1043. $versions = getProp($target_roles, 'versions', []);
  1044. if ($versions && is_array($versions)) {
  1045. $updateData['versions'] = json_encode($versions, 256);
  1046. }
  1047. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1048. DB::table('mp_products')
  1049. ->where('id', $existing_product->id)
  1050. ->update($updateData);
  1051. $product_id = $existing_product->id;
  1052. } else {
  1053. // 创建新资产
  1054. $versions = getProp($target_roles, 'versions', []);
  1055. $product_id = DB::table('mp_products')->insertGetId([
  1056. 'user_id' => $uid,
  1057. 'cpid' => $cpid,
  1058. 'type' => 1, // 资产
  1059. 'product' => $product_type, // 角色
  1060. 'parent_id' => $folder_id,
  1061. 'level' => 2,
  1062. 'product_name' => $product_name,
  1063. 'url' => $url,
  1064. 'pic_prompt' => $pic_prompt,
  1065. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1066. 'sort_order' => time(),
  1067. 'is_deleted' => 0,
  1068. 'pic_task_status' => '生成成功',
  1069. 'created_at' => date('Y-m-d H:i:s'),
  1070. 'updated_at' => date('Y-m-d H:i:s')
  1071. ]);
  1072. }
  1073. // 建立或更新绑定关系
  1074. $existing_mapping = DB::table('mp_script_product_mappings')
  1075. ->where('script_id', $script_id)
  1076. ->where('product_id', $product_id)
  1077. ->where('episode_number', $episode_number)
  1078. ->first();
  1079. if (!$existing_mapping) {
  1080. // 创建绑定关系
  1081. DB::table('mp_script_product_mappings')->insert([
  1082. 'script_id' => $script_id,
  1083. 'product_id' => $product_id,
  1084. 'episode_number' => $episode_number,
  1085. 'created_at' => date('Y-m-d H:i:s'),
  1086. 'updated_at' => date('Y-m-d H:i:s')
  1087. ]);
  1088. }
  1089. }
  1090. }
  1091. }
  1092. } catch (\Exception $e) {
  1093. dLog('anime')->error('更新剧集角色失败', [
  1094. 'anime_id' => $anime_id,
  1095. 'episode_id' => $episode_id,
  1096. 'error' => $e->getMessage()
  1097. ]);
  1098. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1099. }
  1100. return true;
  1101. }
  1102. public function changeEpisodeScenes($data) {
  1103. $anime_id = getProp($data, 'anime_id');
  1104. $episode_id = getProp($data, 'episode_id');
  1105. $target_scenes = getProp($data, 'scenes');
  1106. $is_deleted = getProp($data, 'is_deleted', 0);
  1107. // 参数验证
  1108. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1109. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1110. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1111. // 验证剧集是否存在
  1112. $episode = DB::table('mp_anime_episodes')
  1113. ->where('anime_id', $anime_id)
  1114. ->where('id', $episode_id)
  1115. ->first();
  1116. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1117. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1118. // 获取anime信息,检查是否有关联的script_id
  1119. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1120. if (!$anime) Utils::throwError('20003:动漫不存在');
  1121. $script_id = getProp($anime, 'script_id');
  1122. $episode_number = getProp($episode, 'episode_number', 1);
  1123. $uid = Site::getUid();
  1124. $cpid = Site::getCpid();
  1125. try {
  1126. $target_scene_name = getProp($target_scenes, 'scene');
  1127. if (empty($target_scene_name)) {
  1128. Utils::throwError('20003:场景名称不能为空');
  1129. }
  1130. // 如果是删除操作
  1131. if ($is_deleted == 1) {
  1132. // 从场景列表中移除该场景
  1133. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1134. return getProp($scene, 'scene') !== $target_scene_name;
  1135. }));
  1136. // 更新场景列表
  1137. $result = DB::table('mp_anime_episodes')
  1138. ->where('anime_id', $anime_id)
  1139. ->where('id', $episode_id)
  1140. ->update([
  1141. 'scenes' => json_encode($scenes, 256),
  1142. 'updated_at' => date('Y-m-d H:i:s')
  1143. ]);
  1144. if ($result === false) {
  1145. Utils::throwError('20003:删除场景失败');
  1146. }
  1147. } else {
  1148. // 新增或更新操作
  1149. $scene_found = false;
  1150. $is_new_scene = false;
  1151. // 查找并更新已存在的场景
  1152. foreach($scenes as &$scene) {
  1153. if (getProp($scene, 'scene') === $target_scene_name) {
  1154. $scene = $target_scenes;
  1155. $scene_found = true;
  1156. break;
  1157. }
  1158. }
  1159. // 如果场景不存在,则新增
  1160. if (!$scene_found) {
  1161. $scenes[] = $target_scenes;
  1162. $is_new_scene = true;
  1163. }
  1164. // 更新场景列表
  1165. $result = DB::table('mp_anime_episodes')
  1166. ->where('anime_id', $anime_id)
  1167. ->where('id', $episode_id)
  1168. ->update([
  1169. 'scenes' => json_encode($scenes, 256),
  1170. 'updated_at' => date('Y-m-d H:i:s')
  1171. ]);
  1172. if ($result === false) {
  1173. Utils::throwError('20003:更新场景列表失败');
  1174. }
  1175. // 如果有关联的script_id,则同步到mp_products表
  1176. if ($script_id) {
  1177. // 查询剧本信息
  1178. $script = DB::table('mp_scripts')
  1179. ->where('id', $script_id)
  1180. ->where('is_deleted', 0)
  1181. ->first();
  1182. if ($script) {
  1183. $script_name = $script->script_name ?? 'script_' . $script_id;
  1184. $product_name = getProp($target_scenes, 'scene');
  1185. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1186. $url = getProp($target_scenes, 'url', '');
  1187. $product_type = 2; // 2=场景
  1188. // 查找或创建以script_name命名的文件夹
  1189. $folder = DB::table('mp_products')
  1190. ->where('cpid', $cpid)
  1191. ->where('type', 2) // 文件夹类型
  1192. ->where('product', $product_type) // 场景类型
  1193. ->where('product_name', $script_name)
  1194. ->where('parent_id', 0)
  1195. ->where('is_deleted', 0)
  1196. ->first();
  1197. if (!$folder) {
  1198. // 创建文件夹
  1199. $folder_id = DB::table('mp_products')->insertGetId([
  1200. 'user_id' => $uid,
  1201. 'cpid' => $cpid,
  1202. 'type' => 2, // 文件夹
  1203. 'product' => $product_type, // 场景类型
  1204. 'parent_id' => 0,
  1205. 'level' => 1,
  1206. 'product_name' => $script_name,
  1207. 'sort_order' => time(),
  1208. 'is_deleted' => 0,
  1209. 'created_at' => date('Y-m-d H:i:s'),
  1210. 'updated_at' => date('Y-m-d H:i:s')
  1211. ]);
  1212. } else {
  1213. $folder_id = $folder->id;
  1214. }
  1215. // 查找该文件夹下是否已存在同名资产
  1216. $existing_product = DB::table('mp_products')
  1217. ->where('cpid', $cpid)
  1218. ->where('type', 1) // 资产类型
  1219. ->where('product', $product_type)
  1220. ->where('parent_id', $folder_id)
  1221. ->where('product_name', $product_name)
  1222. ->where('is_deleted', 0)
  1223. ->first();
  1224. if ($existing_product) {
  1225. // 更新已存在的资产
  1226. $updateData = [
  1227. 'pic_task_status' => '生成成功'
  1228. ];
  1229. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1230. if ($url) $updateData['url'] = $url;
  1231. // 处理versions字段
  1232. $versions = getProp($target_scenes, 'versions', []);
  1233. if ($versions && is_array($versions)) {
  1234. $updateData['versions'] = json_encode($versions, 256);
  1235. }
  1236. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1237. DB::table('mp_products')
  1238. ->where('id', $existing_product->id)
  1239. ->update($updateData);
  1240. $product_id = $existing_product->id;
  1241. } else {
  1242. // 创建新资产
  1243. $versions = getProp($target_scenes, 'versions', []);
  1244. $product_id = DB::table('mp_products')->insertGetId([
  1245. 'user_id' => $uid,
  1246. 'cpid' => $cpid,
  1247. 'type' => 1, // 资产
  1248. 'product' => $product_type, // 场景
  1249. 'parent_id' => $folder_id,
  1250. 'level' => 2,
  1251. 'product_name' => $product_name,
  1252. 'url' => $url,
  1253. 'pic_prompt' => $pic_prompt,
  1254. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1255. 'sort_order' => time(),
  1256. 'is_deleted' => 0,
  1257. 'pic_task_status' => '生成成功',
  1258. 'created_at' => date('Y-m-d H:i:s'),
  1259. 'updated_at' => date('Y-m-d H:i:s')
  1260. ]);
  1261. }
  1262. // 建立或更新绑定关系
  1263. $existing_mapping = DB::table('mp_script_product_mappings')
  1264. ->where('script_id', $script_id)
  1265. ->where('product_id', $product_id)
  1266. ->where('episode_number', $episode_number)
  1267. ->first();
  1268. if (!$existing_mapping) {
  1269. // 创建绑定关系
  1270. DB::table('mp_script_product_mappings')->insert([
  1271. 'script_id' => $script_id,
  1272. 'product_id' => $product_id,
  1273. 'episode_number' => $episode_number,
  1274. 'created_at' => date('Y-m-d H:i:s'),
  1275. 'updated_at' => date('Y-m-d H:i:s')
  1276. ]);
  1277. }
  1278. }
  1279. }
  1280. }
  1281. } catch (\Exception $e) {
  1282. dLog('anime')->error('更新剧集场景失败', [
  1283. 'anime_id' => $anime_id,
  1284. 'episode_id' => $episode_id,
  1285. 'error' => $e->getMessage()
  1286. ]);
  1287. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1288. }
  1289. return true;
  1290. }
  1291. public function changeEpisodeProps($data) {
  1292. $anime_id = getProp($data, 'anime_id');
  1293. $episode_id = getProp($data, 'episode_id');
  1294. $target_props = getProp($data, 'props');
  1295. $is_deleted = getProp($data, 'is_deleted', 0);
  1296. // 参数验证
  1297. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1298. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1299. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1300. // 验证剧集是否存在
  1301. $episode = DB::table('mp_anime_episodes')
  1302. ->where('anime_id', $anime_id)
  1303. ->where('id', $episode_id)
  1304. ->first();
  1305. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1306. $props = json_decode(getProp($episode, 'props'), true);
  1307. // 获取anime信息,检查是否有关联的script_id
  1308. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1309. if (!$anime) Utils::throwError('20003:动漫不存在');
  1310. $script_id = getProp($anime, 'script_id');
  1311. $episode_number = getProp($episode, 'episode_number', 1);
  1312. $uid = Site::getUid();
  1313. $cpid = Site::getCpid();
  1314. try {
  1315. $target_prop_name = getProp($target_props, 'prop');
  1316. if (empty($target_prop_name)) {
  1317. Utils::throwError('20003:道具名称不能为空');
  1318. }
  1319. // 如果是删除操作
  1320. if ($is_deleted == 1) {
  1321. // 从道具列表中移除该道具
  1322. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1323. return getProp($prop, 'prop') !== $target_prop_name;
  1324. }));
  1325. // 更新道具列表
  1326. $result = DB::table('mp_anime_episodes')
  1327. ->where('anime_id', $anime_id)
  1328. ->where('id', $episode_id)
  1329. ->update([
  1330. 'props' => json_encode($props, 256),
  1331. 'updated_at' => date('Y-m-d H:i:s')
  1332. ]);
  1333. if ($result === false) {
  1334. Utils::throwError('20003:删除道具失败');
  1335. }
  1336. } else {
  1337. // 新增或更新操作
  1338. $prop_found = false;
  1339. $is_new_prop = false;
  1340. // 查找并更新已存在的道具
  1341. foreach($props as &$prop) {
  1342. if (getProp($prop, 'prop') === $target_prop_name) {
  1343. $prop = $target_props;
  1344. $prop_found = true;
  1345. break;
  1346. }
  1347. }
  1348. // 如果道具不存在,则新增
  1349. if (!$prop_found) {
  1350. $props[] = $target_props;
  1351. $is_new_prop = true;
  1352. }
  1353. // 更新道具列表
  1354. $result = DB::table('mp_anime_episodes')
  1355. ->where('anime_id', $anime_id)
  1356. ->where('id', $episode_id)
  1357. ->update([
  1358. 'props' => json_encode($props, 256),
  1359. 'updated_at' => date('Y-m-d H:i:s')
  1360. ]);
  1361. if ($result === false) {
  1362. Utils::throwError('20003:更新道具列表失败');
  1363. }
  1364. // 如果有关联的script_id,则同步到mp_products表
  1365. if ($script_id) {
  1366. // 查询剧本信息
  1367. $script = DB::table('mp_scripts')
  1368. ->where('id', $script_id)
  1369. ->where('is_deleted', 0)
  1370. ->first();
  1371. if ($script) {
  1372. $script_name = $script->script_name ?? 'script_' . $script_id;
  1373. $product_name = getProp($target_props, 'prop');
  1374. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1375. $url = getProp($target_props, 'url', '');
  1376. $product_type = 3; // 3=道具
  1377. // 查找或创建以script_name命名的文件夹
  1378. $folder = DB::table('mp_products')
  1379. ->where('cpid', $cpid)
  1380. ->where('type', 2) // 文件夹类型
  1381. ->where('product', $product_type) // 道具类型
  1382. ->where('product_name', $script_name)
  1383. ->where('parent_id', 0)
  1384. ->where('is_deleted', 0)
  1385. ->first();
  1386. if (!$folder) {
  1387. // 创建文件夹
  1388. $folder_id = DB::table('mp_products')->insertGetId([
  1389. 'user_id' => $uid,
  1390. 'cpid' => $cpid,
  1391. 'type' => 2, // 文件夹
  1392. 'product' => $product_type, // 道具类型
  1393. 'parent_id' => 0,
  1394. 'level' => 1,
  1395. 'product_name' => $script_name,
  1396. 'sort_order' => time(),
  1397. 'is_deleted' => 0,
  1398. 'created_at' => date('Y-m-d H:i:s'),
  1399. 'updated_at' => date('Y-m-d H:i:s')
  1400. ]);
  1401. } else {
  1402. $folder_id = $folder->id;
  1403. }
  1404. // 查找该文件夹下是否已存在同名资产
  1405. $existing_product = DB::table('mp_products')
  1406. ->where('cpid', $cpid)
  1407. ->where('type', 1) // 资产类型
  1408. ->where('product', $product_type)
  1409. ->where('parent_id', $folder_id)
  1410. ->where('product_name', $product_name)
  1411. ->where('is_deleted', 0)
  1412. ->first();
  1413. if ($existing_product) {
  1414. // 更新已存在的资产
  1415. $updateData = [
  1416. 'pic_task_status' => '生成成功'
  1417. ];
  1418. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1419. if ($url) $updateData['url'] = $url;
  1420. // 处理versions字段
  1421. $versions = getProp($target_props, 'versions', []);
  1422. if ($versions && is_array($versions)) {
  1423. $updateData['versions'] = json_encode($versions, 256);
  1424. }
  1425. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1426. DB::table('mp_products')
  1427. ->where('id', $existing_product->id)
  1428. ->update($updateData);
  1429. $product_id = $existing_product->id;
  1430. } else {
  1431. // 创建新资产
  1432. $versions = getProp($target_props, 'versions', []);
  1433. $product_id = DB::table('mp_products')->insertGetId([
  1434. 'user_id' => $uid,
  1435. 'cpid' => $cpid,
  1436. 'type' => 1, // 资产
  1437. 'product' => $product_type, // 道具
  1438. 'parent_id' => $folder_id,
  1439. 'level' => 2,
  1440. 'product_name' => $product_name,
  1441. 'url' => $url,
  1442. 'pic_prompt' => $pic_prompt,
  1443. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1444. 'sort_order' => time(),
  1445. 'is_deleted' => 0,
  1446. 'pic_task_status' => '生成成功',
  1447. 'created_at' => date('Y-m-d H:i:s'),
  1448. 'updated_at' => date('Y-m-d H:i:s')
  1449. ]);
  1450. }
  1451. // 建立或更新绑定关系
  1452. $existing_mapping = DB::table('mp_script_product_mappings')
  1453. ->where('script_id', $script_id)
  1454. ->where('product_id', $product_id)
  1455. ->where('episode_number', $episode_number)
  1456. ->first();
  1457. if (!$existing_mapping) {
  1458. // 创建绑定关系
  1459. DB::table('mp_script_product_mappings')->insert([
  1460. 'script_id' => $script_id,
  1461. 'product_id' => $product_id,
  1462. 'episode_number' => $episode_number,
  1463. 'created_at' => date('Y-m-d H:i:s'),
  1464. 'updated_at' => date('Y-m-d H:i:s')
  1465. ]);
  1466. }
  1467. }
  1468. }
  1469. }
  1470. } catch (\Exception $e) {
  1471. dLog('anime')->error('更新剧集道具失败', [
  1472. 'anime_id' => $anime_id,
  1473. 'episode_id' => $episode_id,
  1474. 'error' => $e->getMessage()
  1475. ]);
  1476. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1477. }
  1478. return true;
  1479. }
  1480. public function editSegment($data) {
  1481. $segment_id = getProp($data, 'segment_id');
  1482. $segment_content = getProp($data, 'segment_content');
  1483. $image_url = getProp($data, 'image_url');
  1484. $video_url = getProp($data, 'video_url');
  1485. // 参数验证
  1486. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1487. // 验证分镜是否存在
  1488. $segment = DB::table('mp_episode_segments')
  1489. ->where('segment_id', $segment_id)
  1490. ->first();
  1491. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1492. $dubTaskId = 0;
  1493. try {
  1494. DB::beginTransaction();
  1495. // 准备更新数据
  1496. $update_data = [
  1497. 'updated_at' => date('Y-m-d H:i:s')
  1498. ];
  1499. if ($segment_content) {
  1500. // 先将segment_content赋值到update_data
  1501. $update_data['segment_content'] = $segment_content;
  1502. // 使用现有方法分析segment_content,提取各个字段
  1503. $this->handleSegmentContent($update_data);
  1504. // 如果有对话内容,创建视频配音合成任务
  1505. $dialogue = getProp($update_data, 'dialogue');
  1506. if (!empty($dialogue)) {
  1507. $now = date('Y-m-d H:i:s');
  1508. $generate_json = [
  1509. 'text' => $dialogue,
  1510. 'role' => getProp($update_data, 'voice_actor'),
  1511. 'voice_type' => getProp($update_data, 'voice_type'),
  1512. 'voice_name' => getProp($update_data, 'voice_name'),
  1513. 'emotion' => getProp($update_data, 'emotion'),
  1514. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1515. 'gender' => getProp($update_data, 'gender'),
  1516. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1517. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1518. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1519. 'pitch' => getProp($update_data, 'pitch', 0),
  1520. ];
  1521. // 插入视频配音合成任务
  1522. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1523. 'alias_segment_id' => $segment_id,
  1524. 'generate_status' => '执行中',
  1525. 'audio_url' => '',
  1526. 'generate_json' => json_encode($generate_json, 256),
  1527. 'created_at' => $now,
  1528. 'updated_at' => $now,
  1529. ]);
  1530. if (!$dubTaskId) {
  1531. Utils::throwError('20003:创建配音任务失败!');
  1532. }
  1533. $update_data['audio_url'] = '';
  1534. } else {
  1535. // dialogue为空时,直接写入默认音频信息
  1536. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1537. $update_data['audio_duration'] = 2.0;
  1538. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1539. }
  1540. }
  1541. if ($image_url) {
  1542. $update_data['img_url'] = $image_url;
  1543. // 同时写入一个简单的图片生成任务
  1544. $pic_task = [
  1545. 'alias_segment_id' => $segment_id,
  1546. 'ref_img_url' => json_encode([]),
  1547. 'status' => 'success',
  1548. 'result_url' => json_encode([$image_url], 256),
  1549. 'model' => '',
  1550. 'created_at' => date('Y-m-d H:i:s'),
  1551. 'updated_at' => date('Y-m-d H:i:s'),
  1552. ];
  1553. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1554. }
  1555. if ($video_url) {
  1556. $update_data['origin_video_url'] = $video_url;
  1557. $compressed_video_url = compressVideo($video_url);
  1558. $update_data['current_type'] = 2;
  1559. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1560. // 同时写入一个简单的视频生成任务
  1561. $video_task = [
  1562. 'alias_segment_id' => $segment_id,
  1563. 'status' => 'success',
  1564. 'result_url' => $update_data['origin_video_url'],
  1565. 'compressed_url' => $update_data['video_url'],
  1566. 'created_at' => date('Y-m-d H:i:s'),
  1567. 'updated_at' => date('Y-m-d H:i:s'),
  1568. ];
  1569. DB::table('mp_generate_video_tasks')->insert($video_task);
  1570. }
  1571. // 更新分镜信息
  1572. $result = DB::table('mp_episode_segments')
  1573. ->where('segment_id', $segment_id)
  1574. ->update($update_data);
  1575. if ($result === false) {
  1576. Utils::throwError('20003:更新分镜剧本失败');
  1577. }
  1578. DB::commit();
  1579. // 如果有创建音频生成任务则调用API
  1580. if ($dubTaskId) {
  1581. // 请求远程服务器执行生成
  1582. $client = new Client(['timeout' => 300, 'verify' => false]);
  1583. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1584. $response = $result->getBody()->getContents();
  1585. $response_arr = json_decode($response, true);
  1586. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1587. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1588. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1589. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1590. Utils::throwError('20003:火山生成音频失败');
  1591. }
  1592. }
  1593. return true;
  1594. } catch (\Exception $e) {
  1595. DB::rollBack();
  1596. dLog('anime')->error('更新分镜剧本失败', [
  1597. 'segment_id' => $segment_id,
  1598. 'error' => $e->getMessage()
  1599. ]);
  1600. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1601. }
  1602. }
  1603. public function batchSetSegmentPics($data) {
  1604. $anime_id = getProp($data, 'anime_id');
  1605. $episode_id = getProp($data, 'episode_id');
  1606. $ratio = getProp($data, 'ratio');
  1607. $dimensions = $this->getRatioDimensions($ratio);
  1608. $width = $dimensions['width'];
  1609. $height = $dimensions['height'];
  1610. if (!$anime_id || !$episode_id) {
  1611. Utils::throwError('1002:请选择剧集');
  1612. }
  1613. // 获取剧集信息
  1614. $episode = DB::table('mp_anime_episodes')
  1615. ->where('anime_id', $anime_id)
  1616. ->where('id', $episode_id)
  1617. ->where('is_default', 1)
  1618. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1619. ->first();
  1620. if (!$episode) {
  1621. Utils::throwError('20003:该剧集不存在');
  1622. }
  1623. $model = getProp($data, 'model');
  1624. if (!$model) {
  1625. $model = getProp($episode, 'image_model');
  1626. if (!$model) {
  1627. // episode表也没有,使用默认值
  1628. $model = 'doubao-seedream-5-0-lite-260128';
  1629. }
  1630. }
  1631. // 验证模型是否在可用模型表中
  1632. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1633. $model = 'doubao-seedream-5-0-lite-260128';
  1634. }
  1635. $roles = json_decode(getProp($episode, 'roles'), true);
  1636. if (!$roles) {
  1637. Utils::throwError('20003:角色信息格式错误');
  1638. }
  1639. // 构建角色名称到参考图的映射
  1640. $role_map = [];
  1641. foreach ($roles as $role) {
  1642. $role_name = getProp($role, 'role');
  1643. $role_url = getProp($role, 'url');
  1644. if (!empty($role_name) && !empty($role_url)) {
  1645. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1646. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1647. // $role_map[$base_name] = $role_url;
  1648. // 同时保存完整名称的映射
  1649. $role_map[$role_name] = $role_url;
  1650. }
  1651. }
  1652. $scenes = json_decode(getProp($episode, 'roles'), true);
  1653. if (!$scenes) {
  1654. Utils::throwError('20003:场景信息格式错误');
  1655. }
  1656. // 构建角色名称到参考图的映射
  1657. $scene_map = [];
  1658. foreach ($scenes as $scene) {
  1659. $scene_name = getProp($scene, 'scene');
  1660. $scene_url = getProp($scene, 'url');
  1661. if (!empty($scene_name) && !empty($scene_url)) {
  1662. $scene_map[$scene_name] = $scene_url;
  1663. }
  1664. }
  1665. // 获取所有分镜信息
  1666. $segments = DB::table('mp_episode_segments')
  1667. ->where('anime_id', $anime_id)
  1668. ->where('episode_id', $episode_id)
  1669. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1670. ->orderBy('segment_number')
  1671. ->get()
  1672. ->toArray();
  1673. if (empty($segments)) {
  1674. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1675. }
  1676. // 保存图片比例
  1677. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1678. $updated_segments = [];
  1679. $failed_segments = [];
  1680. // 批量为每个分镜生成图片任务
  1681. foreach ($segments as $segment) {
  1682. $segment_id = $segment->segment_id;
  1683. $segment_content = $segment->segment_content;
  1684. if (empty($segment_content)) {
  1685. $failed_segments[] = [
  1686. 'segment_id' => $segment_id,
  1687. 'error' => '分镜内容为空'
  1688. ];
  1689. continue;
  1690. }
  1691. try {
  1692. $dubTaskId = 0;
  1693. // 解析分镜内容,提取画面描述作为主要提示词
  1694. $prompt = $segment_content;
  1695. $ref_img_urls = [];
  1696. // 分镜场景
  1697. $scene = getProp($segment, 'scene');
  1698. $matched_scene = '';
  1699. if (isset($scene_map[$scene])) {
  1700. $img_index = count($ref_img_urls) + 1;
  1701. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1702. $ref_img_urls[] = $scene_map[$scene];
  1703. $matched_scene = $scene;
  1704. }
  1705. // 分镜角色
  1706. $characters = getProp($segment, 'characters');
  1707. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1708. $roles = explode(',', $characters);
  1709. // 从分镜内容中提取涉及的角色
  1710. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1711. // 获取匹配角色的参考图
  1712. foreach ($segment_characters as $character) {
  1713. if (isset($role_map[$character])) {
  1714. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1715. $img_index = count($ref_img_urls) + 1;
  1716. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1717. $ref_img_urls[] = $role_map[$character];
  1718. }
  1719. }
  1720. // 如果没有找到匹配的角色参考图,不使用参考图
  1721. if (empty($ref_img_urls)) {
  1722. $ref_img_urls = [];
  1723. }
  1724. // 准备生成任务参数
  1725. $params = [
  1726. 'model' => $model,
  1727. 'alias_segment_id' => $segment_id,
  1728. 'prompt' => $prompt,
  1729. 'ref_img_urls' => $ref_img_urls,
  1730. 'width' => $width,
  1731. 'height' => $height,
  1732. ];
  1733. // 优化提示词(不要生成字幕)
  1734. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1735. // $task_id = mt_rand(100000, 999999);
  1736. // 调用AI图片生成服务
  1737. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1738. $task_id = $task->id;
  1739. if (!$task_id) {
  1740. $failed_segments[] = [
  1741. 'segment_id' => $segment_id,
  1742. 'error' => '创建生成任务失败'
  1743. ];
  1744. continue;
  1745. }
  1746. $update_data = [
  1747. 'pic_task_id' => $task_id,
  1748. 'pic_task_status' => '生成中',
  1749. 'audio_url' => '',
  1750. 'updated_at' => date('Y-m-d H:i:s')
  1751. ];
  1752. // 如果有对话内容,创建视频配音合成任务
  1753. $dialogue = getProp($segment, 'dialogue');
  1754. if (!empty($dialogue)) {
  1755. $now = date('Y-m-d H:i:s');
  1756. $generate_json = [
  1757. 'text' => $dialogue,
  1758. 'role' => getProp($segment, 'voice_actor'),
  1759. 'voice_type' => getProp($segment, 'voice_type'),
  1760. 'voice_name' => getProp($segment, 'voice_name'),
  1761. 'emotion' => getProp($segment, 'emotion'),
  1762. 'emotion_type' => getProp($segment, 'emotion_type'),
  1763. 'gender' => getProp($segment, 'gender'),
  1764. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1765. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1766. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1767. 'pitch' => getProp($segment, 'pitch', 0),
  1768. ];
  1769. // 插入视频配音合成任务
  1770. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1771. 'alias_segment_id' => $segment_id,
  1772. 'generate_status' => '执行中',
  1773. 'audio_url' => '',
  1774. 'generate_json' => json_encode($generate_json, 256),
  1775. 'created_at' => $now,
  1776. 'updated_at' => $now,
  1777. ]);
  1778. if (!$dubTaskId) {
  1779. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1780. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1781. // Utils::throwError('20003:创建配音任务失败!');
  1782. }
  1783. } else {
  1784. // dialogue为空时,直接写入默认音频信息到分镜表
  1785. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1786. $update_data['audio_duration'] = 2.0;
  1787. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1788. }
  1789. // 更新分镜的任务信息
  1790. $update_result = DB::table('mp_episode_segments')
  1791. ->where('segment_id', $segment_id)
  1792. ->update($update_data);
  1793. // 如果是第一集的首帧图片,则存入待更新数组
  1794. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1795. Redis::sadd('anime_first_frame_urls', $segment_id);
  1796. }
  1797. if ($update_result) {
  1798. $updated_segments[] = [
  1799. 'segment_id' => $segment_id,
  1800. 'task_id' => $task_id,
  1801. 'status' => '生成中',
  1802. 'matched_scenes' => $matched_scene,
  1803. 'matched_roles' => $segment_characters,
  1804. 'ref_urls_count' => count($ref_img_urls)
  1805. ];
  1806. } else {
  1807. $failed_segments[] = [
  1808. 'segment_id' => $segment_id,
  1809. 'error' => '更新分镜任务状态失败'
  1810. ];
  1811. }
  1812. if ($dubTaskId) {
  1813. sleep(1);
  1814. // 请求远程服务器执行生成
  1815. $client = new Client(['timeout' => 300, 'verify' => false]);
  1816. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1817. $response = $result->getBody()->getContents();
  1818. $response_arr = json_decode($response, true);
  1819. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1820. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1821. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1822. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1823. }
  1824. }
  1825. } catch (\Exception $e) {
  1826. $failed_segments[] = [
  1827. 'segment_id' => $segment_id,
  1828. 'error' => $e->getMessage()
  1829. ];
  1830. }
  1831. }
  1832. // 更新剧集生成状态
  1833. if (!empty($updated_segments)) {
  1834. DB::table('mp_anime_episodes')
  1835. ->where('id', $episode_id)
  1836. ->update([
  1837. 'is_generated' => 1,
  1838. 'updated_at' => date('Y-m-d H:i:s')
  1839. ]);
  1840. }
  1841. return [
  1842. 'success_count' => count($updated_segments),
  1843. 'failed_count' => count($failed_segments),
  1844. 'success_segments' => $updated_segments,
  1845. 'failed_segments' => $failed_segments,
  1846. 'total_segments' => count($segments)
  1847. ];
  1848. }
  1849. public function reGenerateSegment($data) {
  1850. $segment_id = getProp($data, 'segment_id');
  1851. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1852. $anime_id = getProp($segment, 'anime_id');
  1853. $episode_id = getProp($segment, 'episode_id');
  1854. $episode_number = getProp($segment, 'episode_number');
  1855. $segment_content = getProp($data, 'segment_content');
  1856. $ratio = getProp($data, 'ratio');
  1857. if (!$ratio) {
  1858. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1859. if (!$ratio) $ratio = '9:16';
  1860. }
  1861. $dimensions = $this->getRatioDimensions($ratio);
  1862. $width = $dimensions['width'];
  1863. $height = $dimensions['height'];
  1864. if (!$anime_id || !$episode_id) {
  1865. Utils::throwError('1002:请选择分镜');
  1866. }
  1867. // 使用文生文模型重新解析segment_content
  1868. if (!empty($segment_content)) {
  1869. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1870. }
  1871. // 获取动漫的角色信息(包含参考图)
  1872. $anime = DB::table('mp_animes')
  1873. ->where('id', $anime_id)
  1874. ->select('roles', 'scenes')
  1875. ->first();
  1876. if (!$anime || !$anime->roles) {
  1877. Utils::throwError('20003:未找到角色信息');
  1878. }
  1879. $roles = json_decode($anime->roles, true);
  1880. if (!$roles) {
  1881. Utils::throwError('20003:角色信息格式错误');
  1882. }
  1883. // 构建角色名称到参考图的映射
  1884. $role_map = [];
  1885. foreach ($roles as $role) {
  1886. $role_name = getProp($role, 'role');
  1887. $role_url = getProp($role, 'url');
  1888. if (!empty($role_name) && !empty($role_url)) {
  1889. $role_map[$role_name] = $role_url;
  1890. }
  1891. }
  1892. $scenes = json_decode($anime->scenes, true);
  1893. if (!$scenes) {
  1894. Utils::throwError('20003:角色信息格式错误');
  1895. }
  1896. // 构建角色名称到参考图的映射
  1897. $scene_map = [];
  1898. foreach ($scenes as $scene) {
  1899. $scene_name = getProp($scene, 'scene');
  1900. $scene_url = getProp($scene, 'url');
  1901. if (!empty($scene_name) && !empty($scene_url)) {
  1902. $scene_map[$scene_name] = $scene_url;
  1903. }
  1904. }
  1905. $segment_id = $segment->segment_id;
  1906. $original_segment_content = $segment->segment_content;
  1907. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1908. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1909. if (empty($final_segment_content)) {
  1910. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1911. }
  1912. try {
  1913. $dubTaskId = 0;
  1914. // 分镜剧本数组
  1915. $update_data = [
  1916. 'segment_content' => $final_segment_content,
  1917. 'pic_task_status' => '生成中',
  1918. 'updated_at' => date('Y-m-d H:i:s')
  1919. ];
  1920. // 解析分镜内容,提取画面描述作为主要提示词
  1921. $prompt = $final_segment_content;
  1922. $ref_img_urls = [];
  1923. // 分镜场景
  1924. $scene = getProp($data, 'scene');
  1925. if ($scene) {
  1926. $matched_scene = '';
  1927. if (isset($scene_map[$scene])) {
  1928. $img_index = count($ref_img_urls) + 1;
  1929. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1930. $ref_img_urls[] = $scene_map[$scene];
  1931. $matched_scene = $scene;
  1932. }
  1933. $update_data['scene'] = $scene;
  1934. }
  1935. // 分镜角色
  1936. $characters = getProp($data, 'characters');
  1937. if ($characters) {
  1938. $update_data['characters'] = $characters;
  1939. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1940. $characters = explode(',', $characters);
  1941. // 从分镜内容中提取涉及的角色
  1942. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1943. // 获取匹配角色的参考图
  1944. foreach ($segment_characters as $character) {
  1945. if (isset($role_map[$character])) {
  1946. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1947. $img_index = count($ref_img_urls) + 1;
  1948. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1949. $ref_img_urls[] = $role_map[$character];
  1950. }
  1951. }
  1952. }
  1953. // 如果没有找到匹配的角色参考图,不使用参考图
  1954. if (empty($ref_img_urls)) {
  1955. $ref_img_urls = [];
  1956. }
  1957. // 准备生成任务参数
  1958. $params = [
  1959. 'alias_segment_id' => $segment_id,
  1960. 'prompt' => $prompt,
  1961. 'ref_img_urls' => $ref_img_urls,
  1962. 'width' => $width,
  1963. 'height' => $height,
  1964. ];
  1965. // 优化提示词(不要生成字幕)
  1966. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1967. // 调用AI图片生成服务
  1968. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1969. $task_id = $task->id;
  1970. if (!$task_id) {
  1971. Utils::throwError('20003:创建生成任务失败!');
  1972. }
  1973. $update_data['pic_task_id'] = $task_id;
  1974. // 更新分镜剧本信息
  1975. $this->handleSegmentContent($update_data);
  1976. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1977. if ($segment_content) {
  1978. $dialogue = getProp($update_data, 'dialogue');
  1979. if (!empty($dialogue)) {
  1980. $now = date('Y-m-d H:i:s');
  1981. $generate_json = [
  1982. 'text' => $dialogue,
  1983. 'role' => getProp($update_data, 'voice_actor'),
  1984. 'voice_type' => getProp($update_data, 'voice_type'),
  1985. 'voice_name' => getProp($update_data, 'voice_name'),
  1986. 'emotion' => getProp($update_data, 'emotion'),
  1987. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1988. 'gender' => getProp($update_data, 'gender'),
  1989. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1990. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1991. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1992. 'pitch' => getProp($update_data, 'pitch', 0),
  1993. ];
  1994. // 插入视频配音合成任务
  1995. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1996. 'alias_segment_id' => $segment_id,
  1997. 'generate_status' => '执行中',
  1998. 'audio_url' => '',
  1999. 'generate_json' => json_encode($generate_json, 256),
  2000. 'created_at' => date('Y-m-d H:i:s'),
  2001. 'updated_at' => date('Y-m-d H:i:s'),
  2002. ]);
  2003. if (!$dubTaskId) {
  2004. Utils::throwError('20003:创建配音任务失败!');
  2005. }
  2006. $update_data['audio_url'] = '';
  2007. } else {
  2008. // dialogue为空时,直接写入默认音频信息
  2009. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2010. $update_data['audio_duration'] = 2.0;
  2011. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2012. }
  2013. }
  2014. $boolen = DB::table('mp_episode_segments')
  2015. ->where('segment_id', $segment_id)
  2016. ->update($update_data);
  2017. // 如果是第一集的首帧图片,则存入待更新数组
  2018. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2019. Redis::sadd('anime_first_frame_urls', $segment_id);
  2020. }
  2021. if ($dubTaskId) {
  2022. // 请求远程服务器执行生成
  2023. $client = new Client(['timeout' => 300, 'verify' => false]);
  2024. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2025. $response = $result->getBody()->getContents();
  2026. $response_arr = json_decode($response, true);
  2027. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2028. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2029. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2030. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2031. Utils::throwError('20003:火山生成音频失败');
  2032. }
  2033. }
  2034. } catch (\Exception $e) {
  2035. $failed_segments[] = [
  2036. 'segment_id' => $segment_id,
  2037. 'error' => $e->getMessage()
  2038. ];
  2039. }
  2040. // 创建任务之后先暂停10s等待异步任务完成
  2041. sleep(10);
  2042. $img_url = $this->loopGetPicTaskResult($task_id);
  2043. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2044. // 图片生成后新增对话记录
  2045. try {
  2046. $uid = Site::getUid();
  2047. $now = date('Y-m-d H:i:s');
  2048. // 使用AI反推图片提示词
  2049. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2050. // 保存对话记录
  2051. $records = [
  2052. [
  2053. 'uid' => $uid,
  2054. 'anime_id' => $anime_id,
  2055. 'sequence' => $episode_number,
  2056. 'role' => 'user',
  2057. 'content' => '重新生成',
  2058. 'segment_id' => $segment_id,
  2059. 'image_url' => '',
  2060. 'created_at' => $now,
  2061. 'updated_at' => $now
  2062. ],
  2063. [
  2064. 'uid' => $uid,
  2065. 'anime_id' => $anime_id,
  2066. 'sequence' => $episode_number,
  2067. 'role' => 'assistant',
  2068. 'content' => $pic_prompt,
  2069. 'segment_id' => $segment_id,
  2070. 'image_url' => $img_url,
  2071. 'created_at' => $now,
  2072. 'updated_at' => $now
  2073. ]
  2074. ];
  2075. DB::table('mp_anime_records')->insert($records);
  2076. } catch (\Exception $e) {
  2077. // 记录日志但不影响主流程
  2078. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2079. 'segment_id' => $segment_id,
  2080. 'img_url' => $img_url
  2081. ]);
  2082. }
  2083. return $img_url;
  2084. }
  2085. public function addSegment($data) {
  2086. $prev_segment_id = getProp($data, 'prev_segment_id');
  2087. $img_url = getProp($data, 'img_url');
  2088. $video_url = getProp($data, 'video_url');
  2089. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2090. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2091. $anime_id = getProp($segment, 'anime_id');
  2092. $episode_id = getProp($segment, 'episode_id');
  2093. $episode_number = getProp($segment, 'episode_number');
  2094. $segment_number = getProp($segment, 'segment_number');
  2095. $new_segment_number = $segment_number + 1;
  2096. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2097. // 分镜剧本数组
  2098. $insert_data = [
  2099. 'anime_id' => $anime_id,
  2100. 'episode_id' => $episode_id,
  2101. 'episode_number' => $episode_number,
  2102. 'act_number' => getProp($segment, 'act_number'),
  2103. 'act_title' => getProp($segment, 'act_title'),
  2104. 'segment_id' => $segment_id,
  2105. 'segment_number' => $new_segment_number,
  2106. 'segment_content' => '',
  2107. 'img_url' => '',
  2108. 'video_url' => '',
  2109. 'created_at' => date('Y-m-d H:i:s'),
  2110. 'updated_at' => date('Y-m-d H:i:s')
  2111. ];
  2112. if ($img_url) $insert_data['img_url'] = $img_url;
  2113. if ($video_url) {
  2114. $insert_data['origin_video_url'] = $video_url;
  2115. $insert_data['current_type'] = 2;
  2116. $compressed_video_url = compressVideo($video_url);
  2117. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2118. }
  2119. try {
  2120. DB::beginTransaction();
  2121. // 先更新序号
  2122. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2123. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2124. if (!$id) {
  2125. Utils::throwError('20003:新增分镜失败!');
  2126. }
  2127. }catch (\Exception $e) {
  2128. DB::rollBack();
  2129. Utils::throwError('20003:'.$e->getMessage());
  2130. }
  2131. DB::commit();
  2132. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2133. $segment = $segment ? (array)$segment : [];
  2134. return $segment;
  2135. // 以下代码暂弃用
  2136. $anime_id = getProp($segment, 'anime_id');
  2137. $episode_id = getProp($segment, 'episode_id');
  2138. $episode_number = getProp($segment, 'episode_number');
  2139. $segment_number = getProp($segment, 'segment_number');
  2140. $segment_content = getProp($data, 'segment_content');
  2141. $img_url = getProp($data, 'img_url');
  2142. $video_url = getProp($data, 'video_url');
  2143. $ratio = getProp($data, 'ratio');
  2144. $dimensions = $this->getRatioDimensions($ratio);
  2145. $width = $dimensions['width'];
  2146. $height = $dimensions['height'];
  2147. if (!$anime_id || !$episode_id) {
  2148. Utils::throwError('1002:请选择分镜');
  2149. }
  2150. // 使用文生文模型重新解析segment_content
  2151. if (!empty($segment_content)) {
  2152. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2153. }
  2154. // 获取动漫的角色信息(包含参考图)
  2155. $anime = DB::table('mp_animes')
  2156. ->where('id', $anime_id)
  2157. ->select('roles', 'scenes')
  2158. ->first();
  2159. if (!$anime || !$anime->roles) {
  2160. Utils::throwError('20003:未找到角色信息');
  2161. }
  2162. $roles = json_decode($anime->roles, true);
  2163. if (!$roles) {
  2164. Utils::throwError('20003:角色信息格式错误');
  2165. }
  2166. // 构建角色名称到参考图的映射
  2167. $role_map = [];
  2168. foreach ($roles as $role) {
  2169. $role_name = getProp($role, 'role');
  2170. $role_url = getProp($role, 'url');
  2171. if (!empty($role_name) && !empty($role_url)) {
  2172. $role_map[$role_name] = $role_url;
  2173. }
  2174. }
  2175. $scenes = json_decode($anime->scenes, true);
  2176. if (!$scenes) {
  2177. Utils::throwError('20003:角色信息格式错误');
  2178. }
  2179. // 构建角色名称到参考图的映射
  2180. $scene_map = [];
  2181. foreach ($scenes as $scene) {
  2182. $scene_name = getProp($scene, 'scene');
  2183. $scene_url = getProp($scene, 'url');
  2184. if (!empty($scene_name) && !empty($scene_url)) {
  2185. $scene_map[$scene_name] = $scene_url;
  2186. }
  2187. }
  2188. $segment_id = $segment->segment_id;
  2189. $original_segment_content = $segment->segment_content;
  2190. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2191. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2192. if (empty($final_segment_content)) {
  2193. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2194. }
  2195. try {
  2196. $dubTaskId = 0;
  2197. DB::beginTransaction();
  2198. $new_segment_number = $segment_number + 1;
  2199. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2200. // 分镜剧本数组
  2201. $insert_data = [
  2202. 'anime_id' => $anime_id,
  2203. 'episode_id' => $episode_id,
  2204. 'episode_number' => $episode_number,
  2205. 'act_number' => getProp($segment, 'act_number'),
  2206. 'act_title' => getProp($segment, 'act_title'),
  2207. 'segment_id' => $segment_id,
  2208. 'segment_number' => $new_segment_number,
  2209. 'segment_content' => $final_segment_content,
  2210. 'img_url' => $img_url,
  2211. 'video_url' => $video_url,
  2212. 'created_at' => date('Y-m-d H:i:s'),
  2213. 'updated_at' => date('Y-m-d H:i:s')
  2214. ];
  2215. // 更新分镜剧本信息
  2216. $this->handleSegmentContent($insert_data);
  2217. // 如果有对话内容,创建视频配音合成任务
  2218. $dialogue = getProp($insert_data, 'dialogue');
  2219. if (!empty($dialogue)) {
  2220. $now = date('Y-m-d H:i:s');
  2221. $generate_json = [
  2222. 'text' => $dialogue,
  2223. 'role' => getProp($insert_data, 'voice_actor'),
  2224. 'voice_type' => getProp($insert_data, 'voice_type'),
  2225. 'voice_name' => getProp($insert_data, 'voice_name'),
  2226. 'emotion' => getProp($insert_data, 'emotion'),
  2227. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2228. 'gender' => getProp($insert_data, 'gender'),
  2229. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2230. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2231. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2232. 'pitch' => getProp($insert_data, 'pitch', 0),
  2233. ];
  2234. // 插入视频配音合成任务
  2235. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2236. 'alias_segment_id' => $segment_id,
  2237. 'generate_status' => '执行中',
  2238. 'audio_url' => '',
  2239. 'generate_json' => json_encode($generate_json, 256),
  2240. 'created_at' => $now,
  2241. 'updated_at' => $now,
  2242. ]);
  2243. if (!$dubTaskId) {
  2244. Utils::throwError('20003:创建配音任务失败!');
  2245. }
  2246. $insert_data['audio_url'] = '';
  2247. } else {
  2248. // dialogue为空时,直接写入默认音频信息
  2249. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2250. $insert_data['audio_duration'] = 2.0;
  2251. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2252. }
  2253. // 如果没有上传图片则使用当前描述进行生成
  2254. if (!$img_url) {
  2255. // 解析分镜内容,提取画面描述作为主要提示词
  2256. $prompt = $final_segment_content;
  2257. $ref_img_urls = [];
  2258. // 分镜场景
  2259. $scene = getProp($insert_data, 'scene');
  2260. if ($scene) {
  2261. $matched_scene = '';
  2262. if (isset($scene_map[$scene])) {
  2263. $img_index = count($ref_img_urls) + 1;
  2264. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2265. $ref_img_urls[] = $scene_map[$scene];
  2266. $matched_scene = $scene;
  2267. }
  2268. $update_data['scene'] = $scene;
  2269. }
  2270. // 分镜角色
  2271. $characters = getProp($insert_data, 'characters');
  2272. if ($characters) {
  2273. $update_data['characters'] = $characters;
  2274. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2275. $characters = explode(',', $characters);
  2276. // 从分镜内容中提取涉及的角色
  2277. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2278. // 获取匹配角色的参考图
  2279. foreach ($segment_characters as $character) {
  2280. if (isset($role_map[$character])) {
  2281. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2282. $img_index = count($ref_img_urls) + 1;
  2283. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2284. $ref_img_urls[] = $role_map[$character];
  2285. }
  2286. }
  2287. }
  2288. // 如果没有找到匹配的角色参考图,不使用参考图
  2289. if (empty($ref_img_urls)) {
  2290. $ref_img_urls = [];
  2291. }
  2292. // 准备生成任务参数
  2293. $params = [
  2294. 'alias_segment_id' => $segment_id,
  2295. 'prompt' => $prompt,
  2296. 'ref_img_urls' => $ref_img_urls,
  2297. 'width' => $width,
  2298. 'height' => $height,
  2299. ];
  2300. // 调用AI图片生成服务
  2301. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2302. $task_id = $task->id;
  2303. // $task_id = 'whatever';
  2304. if (!$task_id) {
  2305. Utils::throwError('20003:创建生成任务失败!');
  2306. }
  2307. $insert_data['pic_task_status'] = '生成中';
  2308. $insert_data['pic_task_id'] = $task_id;
  2309. }
  2310. // 先更新序号
  2311. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2312. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2313. if (!$boolen) {
  2314. Utils::throwError('20003:新增分镜失败!');
  2315. }
  2316. // 如果是第一集的首帧图片,则存入待更新数组
  2317. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2318. Redis::sadd('anime_first_frame_urls', $segment_id);
  2319. }
  2320. if ($dubTaskId) {
  2321. // 请求远程服务器执行生成
  2322. $client = new Client(['timeout' => 300, 'verify' => false]);
  2323. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2324. $response = $result->getBody()->getContents();
  2325. $response_arr = json_decode($response, true);
  2326. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2327. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2328. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2329. Utils::throwError('20003:火山生成音频失败');
  2330. }
  2331. }
  2332. } catch (\Exception $e) {
  2333. DB::rollBack();
  2334. Utils::throwError('20003:'.$e->getMessage());
  2335. }
  2336. DB::commit();
  2337. // 创建任务之后先暂停10s等待异步任务完成
  2338. sleep(10);
  2339. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2340. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2341. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2342. $segment = $segment ? (array)$segment : [];
  2343. return $segment;
  2344. }
  2345. public function copySegment($data) {
  2346. $segment_id = getProp($data, 'segment_id');
  2347. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2348. if (!$segment) Utils::throwError('20003:请选择分镜');
  2349. $anime_id = getProp($segment, 'anime_id');
  2350. $episode_id = getProp($segment, 'episode_id');
  2351. $episode_number = getProp($segment, 'episode_number');
  2352. $segment_number = getProp($segment, 'segment_number');
  2353. $new_segment_id = 0;
  2354. try {
  2355. DB::beginTransaction();
  2356. $segment = (array)$segment;
  2357. unset($segment['id']);
  2358. $segment['segment_number'] += 1;
  2359. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2360. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2361. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2362. // 更新其他分镜序号
  2363. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2364. // 复制分镜
  2365. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2366. if (!$id) {
  2367. Utils::throwError('20003:复制分镜失败');
  2368. }
  2369. }catch (\Exception $e) {
  2370. DB::rollBack();
  2371. Utils::throwError('20003:'.$e->getMessage());
  2372. }
  2373. DB::commit();
  2374. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2375. $segment = $segment ? (array)$segment : [];
  2376. return $segment;
  2377. }
  2378. public function moveSegment($data) {
  2379. $segment_id = getProp($data, 'segment_id');
  2380. $target_segment_id = getProp($data, 'target_segment_id');
  2381. // 获取源分镜信息
  2382. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2383. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2384. // 获取目标分镜信息
  2385. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2386. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2387. $anime_id = getProp($source_segment, 'anime_id');
  2388. $episode_id = getProp($source_segment, 'episode_id');
  2389. $episode_number = getProp($source_segment, 'episode_number');
  2390. $source_segment_number = getProp($source_segment, 'segment_number');
  2391. $target_segment_number = getProp($target_segment, 'segment_number');
  2392. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2393. $target_anime_id = getProp($target_segment, 'anime_id');
  2394. $target_episode_number = getProp($target_segment, 'episode_number');
  2395. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2396. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2397. }
  2398. // 如果源分镜和目标分镜相同,无需移动
  2399. if ($source_segment_number == $target_segment_number) {
  2400. return true;
  2401. }
  2402. try {
  2403. DB::beginTransaction();
  2404. if ($source_segment_number < $target_segment_number) {
  2405. // 向后移动:源分镜移动到目标分镜之后
  2406. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2407. DB::table('mp_episode_segments')
  2408. ->where('anime_id', $anime_id)
  2409. ->where('episode_id', $episode_id)
  2410. ->where('segment_number', '>', $source_segment_number)
  2411. ->where('segment_number', '<=', $target_segment_number)
  2412. ->decrement('segment_number');
  2413. // 2. 将源分镜移动到目标分镜之后
  2414. $new_segment_number = $target_segment_number;
  2415. } else {
  2416. // 向前移动:源分镜移动到目标分镜之后
  2417. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2418. DB::table('mp_episode_segments')
  2419. ->where('anime_id', $anime_id)
  2420. ->where('episode_id', $episode_id)
  2421. ->where('segment_number', '>', $target_segment_number)
  2422. ->where('segment_number', '<', $source_segment_number)
  2423. ->increment('segment_number');
  2424. // 2. 将源分镜移动到目标分镜之后
  2425. $new_segment_number = $target_segment_number + 1;
  2426. }
  2427. // 3. 更新源分镜的序号
  2428. $update_result = DB::table('mp_episode_segments')
  2429. ->where('segment_id', $segment_id)
  2430. ->update([
  2431. 'segment_number' => $new_segment_number,
  2432. 'updated_at' => date('Y-m-d H:i:s')
  2433. ]);
  2434. if (!$update_result) {
  2435. Utils::throwError('20003:更新分镜序号失败');
  2436. }
  2437. DB::commit();
  2438. return true;
  2439. } catch (\Exception $e) {
  2440. DB::rollBack();
  2441. Utils::throwError('20003:' . $e->getMessage());
  2442. }
  2443. }
  2444. public function delSegment($data) {
  2445. $segment_id = getProp($data, 'segment_id');
  2446. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2447. if (!$segment) Utils::throwError('20003:请选择分镜');
  2448. $anime_id = getProp($segment, 'anime_id');
  2449. $episode_id = getProp($segment, 'episode_id');
  2450. $episode_number = getProp($segment, 'episode_number');
  2451. $segment_number = getProp($segment, 'segment_number');
  2452. try {
  2453. DB::beginTransaction();
  2454. // 删除分镜
  2455. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2456. if (!$boolen) {
  2457. Utils::throwError('20003:删除分镜失败');
  2458. }
  2459. // 更新其他分镜序号
  2460. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2461. }catch (\Exception $e) {
  2462. DB::rollBack();
  2463. Utils::throwError('20003:'.$e->getMessage());
  2464. }
  2465. DB::commit();
  2466. return true;
  2467. }
  2468. public function applySegment($data) {
  2469. $segment_id = getProp($data, 'segment_id');
  2470. $url = getProp($data, 'url');
  2471. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2472. if (!$url) Utils::throwError('20003:URL不能为空');
  2473. // 获取URL的文件扩展名
  2474. $urlPath = parse_url($url, PHP_URL_PATH);
  2475. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2476. // 定义图片和视频的扩展名
  2477. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2478. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2479. // 判断是图片还是视频
  2480. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2481. if (in_array($extension, $imageExtensions)) {
  2482. // 图片类型
  2483. $updateData['img_url'] = $url;
  2484. $updateData['current_type'] = 1;
  2485. } elseif (in_array($extension, $videoExtensions)) {
  2486. // 视频类型
  2487. $updateData['video_url'] = $url;
  2488. $updateData['current_type'] = 2;
  2489. } else {
  2490. Utils::throwError('20003:不支持的文件类型');
  2491. }
  2492. // 更新分镜表
  2493. $result = DB::table('mp_episode_segments')
  2494. ->where('segment_id', $segment_id)
  2495. ->update($updateData);
  2496. if (!$result) {
  2497. Utils::throwError('20003:更新分镜失败');
  2498. }
  2499. return true;
  2500. }
  2501. public function segmentHistory($data) {
  2502. $segment_id = getProp($data, 'segment_id');
  2503. // 获取历史图片
  2504. $pics = [];
  2505. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2506. foreach($pic_history as $task) {
  2507. $result_url = getProp($task, 'result_url');
  2508. if (is_json($result_url)) {
  2509. $pics = array_merge($pics, json_decode($result_url, true));
  2510. }else {
  2511. $pics[] = $result_url;
  2512. }
  2513. }
  2514. // 获取历史视频
  2515. $videos = [];
  2516. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2517. foreach($video_history as $task) {
  2518. $result_url = getProp($task, 'result_url');
  2519. if (is_json($result_url)) {
  2520. $videos = array_merge($videos, json_decode($result_url, true));
  2521. }else {
  2522. $videos[] = $result_url;
  2523. }
  2524. }
  2525. return compact('pics', 'videos');
  2526. }
  2527. public function addAct($data) {
  2528. $prev_act_id = getProp($data, 'prev_act_id');
  2529. $act_title = getProp($data, 'act_title', '');
  2530. $act_content = getProp($data, 'act_content', '');
  2531. $act_duration = getProp($data, 'act_duration', 5);
  2532. $video_url = getProp($data, 'video_url');
  2533. // 根据prev_act_id获取记录
  2534. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2535. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2536. $anime_id = getProp($prev_segment, 'anime_id');
  2537. $episode_id = getProp($prev_segment, 'episode_id');
  2538. $episode_number = getProp($prev_segment, 'episode_number');
  2539. $prev_act_number = getProp($prev_segment, 'act_number');
  2540. // 获取新的act_number
  2541. $new_act_number = $prev_act_number + 1;
  2542. try {
  2543. DB::beginTransaction();
  2544. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2545. DB::table('mp_episode_segments')
  2546. ->where('anime_id', $anime_id)
  2547. ->where('episode_id', $episode_id)
  2548. ->where('act_number', '>', $prev_act_number)
  2549. ->increment('act_number');
  2550. // 插入新片段记录
  2551. $insert_data = [
  2552. 'anime_id' => $anime_id,
  2553. 'episode_id' => $episode_id,
  2554. 'episode_number' => $episode_number,
  2555. 'act_number' => $new_act_number,
  2556. 'created_at' => date('Y-m-d H:i:s'),
  2557. 'updated_at' => date('Y-m-d H:i:s')
  2558. ];
  2559. if ($act_title) {
  2560. $insert_data['act_title'] = $act_title;
  2561. }
  2562. if ($act_content) {
  2563. $insert_data['act_content'] = $act_content;
  2564. }
  2565. if ($act_duration) {
  2566. $insert_data['act_duration'] = $act_duration;
  2567. }
  2568. if ($video_url) {
  2569. $insert_data['origin_video_url'] = $video_url;
  2570. $insert_data['current_type'] = 2;
  2571. $compressed_video_url = compressVideo($video_url);
  2572. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2573. }
  2574. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2575. if (!$id) {
  2576. Utils::throwError('20003:新增片段失败!');
  2577. }
  2578. DB::commit();
  2579. }catch (\Exception $e) {
  2580. DB::rollBack();
  2581. Utils::throwError('20003:'.$e->getMessage());
  2582. }
  2583. $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();
  2584. $segment = $segment ? (array)$segment : [];
  2585. return $segment;
  2586. }
  2587. public function editAct($data) {
  2588. $act_id = getProp($data, 'act_id');
  2589. $act_content = getProp($data, 'act_content');
  2590. $act_duration = getProp($data, 'act_duration');
  2591. $act_title = getProp($data, 'act_title');
  2592. $image_url = getProp($data, 'image_url');
  2593. $video_url = getProp($data, 'video_url');
  2594. // 参数验证
  2595. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2596. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2597. $segment = DB::table('mp_episode_segments')
  2598. ->where('id', $act_id)
  2599. ->first();
  2600. if (!$segment) Utils::throwError('20003:该片段不存在');
  2601. try {
  2602. DB::beginTransaction();
  2603. // 准备更新数据
  2604. $update_data = [
  2605. 'updated_at' => date('Y-m-d H:i:s')
  2606. ];
  2607. // 更新act相关字段
  2608. if (!empty($act_content)) {
  2609. $update_data['act_show_content'] = $act_content;
  2610. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2611. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2612. $shot_counter = 0;
  2613. $update_data['act_show_content'] = preg_replace_callback(
  2614. '/【(?:镜头|分镜)(\d+)】/u',
  2615. function($matches) use (&$shot_counter) {
  2616. $shot_counter++;
  2617. return '【镜头' . $shot_counter . '】';
  2618. },
  2619. $update_data['act_show_content']
  2620. );
  2621. }
  2622. if (!empty($act_duration)) {
  2623. $update_data['act_duration'] = $act_duration;
  2624. }
  2625. if (!empty($act_title)) {
  2626. $update_data['act_title'] = $act_title;
  2627. }
  2628. // 处理图片上传
  2629. if ($image_url) {
  2630. $update_data['img_url'] = $image_url;
  2631. $update_data['current_type'] = 1;
  2632. // 同时写入一个图片生成任务记录
  2633. if ($act_id) {
  2634. $pic_task = [
  2635. 'alias_act_id' => $act_id,
  2636. 'ref_img_url' => json_encode([]),
  2637. 'status' => 'success',
  2638. 'result_url' => json_encode([$image_url], 256),
  2639. 'model' => '',
  2640. 'created_at' => date('Y-m-d H:i:s'),
  2641. 'updated_at' => date('Y-m-d H:i:s'),
  2642. ];
  2643. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2644. }
  2645. }
  2646. // 处理视频上传
  2647. if ($video_url) {
  2648. $update_data['origin_video_url'] = $video_url;
  2649. $compressed_video_url = compressVideo($video_url);
  2650. $update_data['current_type'] = 2;
  2651. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2652. // 同时写入一个视频生成任务记录
  2653. if ($act_id) {
  2654. $video_task = [
  2655. 'alias_act_id' => $act_id,
  2656. 'status' => 'success',
  2657. 'result_url' => $update_data['origin_video_url'],
  2658. 'compressed_url' => $update_data['video_url'],
  2659. 'created_at' => date('Y-m-d H:i:s'),
  2660. 'updated_at' => date('Y-m-d H:i:s'),
  2661. ];
  2662. DB::table('mp_generate_video_tasks')->insert($video_task);
  2663. }
  2664. }
  2665. // 更新片段信息
  2666. $result = DB::table('mp_episode_segments')
  2667. ->where('id', $act_id)
  2668. ->update($update_data);
  2669. if ($result === false) {
  2670. Utils::throwError('20003:更新片段失败');
  2671. }
  2672. DB::commit();
  2673. // 返回新复制的记录
  2674. $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();
  2675. $new_segment = (array)$new_segment;
  2676. return $new_segment;
  2677. } catch (\Exception $e) {
  2678. DB::rollBack();
  2679. dLog('anime')->error('更新片段失败', [
  2680. 'act_id' => $act_id,
  2681. 'error' => $e->getMessage()
  2682. ]);
  2683. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2684. }
  2685. }
  2686. public function copyAct($data) {
  2687. $act_id = getProp($data, 'act_id');
  2688. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2689. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2690. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2691. $anime_id = getProp($source_segment, 'anime_id');
  2692. $episode_id = getProp($source_segment, 'episode_id');
  2693. $episode_number = getProp($source_segment, 'episode_number');
  2694. $act_number = getProp($source_segment, 'act_number');
  2695. try {
  2696. DB::beginTransaction();
  2697. // 新act的编号
  2698. $new_act_number = $act_number + 1;
  2699. // 更新后续所有act的act_number
  2700. DB::table('mp_episode_segments')
  2701. ->where('anime_id', $anime_id)
  2702. ->where('episode_id', $episode_id)
  2703. ->where('act_number', '>', $act_number)
  2704. ->increment('act_number');
  2705. // 复制该片段记录
  2706. $segment_data = (array)$source_segment;
  2707. unset($segment_data['id']);
  2708. $segment_data['video_url'] = '';
  2709. $segment_data['video_task_id'] = '';
  2710. $segment_data['video_task_status'] = '';
  2711. $segment_data['act_number'] = $new_act_number;
  2712. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2713. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2714. if (!$id) {
  2715. Utils::throwError('20003:复制片段失败');
  2716. }
  2717. DB::commit();
  2718. }catch (\Exception $e) {
  2719. DB::rollBack();
  2720. Utils::throwError('20003:'.$e->getMessage());
  2721. }
  2722. // 返回新复制的记录
  2723. $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();
  2724. $new_segment = $new_segment ? (array)$new_segment : [];
  2725. $new_segment['act_id'] = $id;
  2726. return $new_segment;
  2727. }
  2728. public function moveAct($data) {
  2729. $act_id = getProp($data, 'act_id');
  2730. $target_act_id = getProp($data, 'target_act_id');
  2731. // 获取源片段信息
  2732. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2733. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2734. // 获取目标片段信息
  2735. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2736. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2737. $anime_id = getProp($source_segment, 'anime_id');
  2738. $episode_id = getProp($source_segment, 'episode_id');
  2739. $source_act_number = getProp($source_segment, 'act_number');
  2740. $target_act_number = getProp($target_segment, 'act_number');
  2741. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2742. $target_anime_id = getProp($target_segment, 'anime_id');
  2743. $target_episode_id = getProp($target_segment, 'episode_id');
  2744. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2745. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2746. }
  2747. // 如果源片段和目标片段相同,无需移动
  2748. if ($source_act_number == $target_act_number) {
  2749. return true;
  2750. }
  2751. try {
  2752. DB::beginTransaction();
  2753. if ($source_act_number < $target_act_number) {
  2754. // 向后移动:源片段移动到目标片段之后
  2755. // 1. 将源片段和目标片段之间的所有片段编号减1
  2756. DB::table('mp_episode_segments')
  2757. ->where('anime_id', $anime_id)
  2758. ->where('episode_id', $episode_id)
  2759. ->where('act_number', '>', $source_act_number)
  2760. ->where('act_number', '<=', $target_act_number)
  2761. ->decrement('act_number');
  2762. // 2. 将源片段移动到目标片段之后
  2763. $new_act_number = $target_act_number;
  2764. } else {
  2765. // 向前移动:源片段移动到目标片段之后
  2766. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2767. DB::table('mp_episode_segments')
  2768. ->where('anime_id', $anime_id)
  2769. ->where('episode_id', $episode_id)
  2770. ->where('act_number', '>', $target_act_number)
  2771. ->where('act_number', '<', $source_act_number)
  2772. ->increment('act_number');
  2773. // 2. 将源片段移动到目标片段之后
  2774. $new_act_number = $target_act_number + 1;
  2775. }
  2776. // 3. 更新源片段的编号
  2777. $update_result = DB::table('mp_episode_segments')
  2778. ->where('id', $act_id)
  2779. ->update([
  2780. 'act_number' => $new_act_number,
  2781. 'updated_at' => date('Y-m-d H:i:s')
  2782. ]);
  2783. if (!$update_result) {
  2784. Utils::throwError('20003:更新片段编号失败');
  2785. }
  2786. DB::commit();
  2787. return true;
  2788. } catch (\Exception $e) {
  2789. DB::rollBack();
  2790. Utils::throwError('20003:' . $e->getMessage());
  2791. }
  2792. }
  2793. public function delAct($data) {
  2794. $act_id = getProp($data, 'act_id');
  2795. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2796. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2797. if (!$segment) Utils::throwError('20003:请选择片段');
  2798. $anime_id = getProp($segment, 'anime_id');
  2799. $episode_id = getProp($segment, 'episode_id');
  2800. $act_number = getProp($segment, 'act_number');
  2801. try {
  2802. DB::beginTransaction();
  2803. // 删除该片段记录
  2804. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2805. if (!$deleted) {
  2806. Utils::throwError('20003:删除片段失败');
  2807. }
  2808. // 更新后续act的编号
  2809. DB::table('mp_episode_segments')
  2810. ->where('anime_id', $anime_id)
  2811. ->where('episode_id', $episode_id)
  2812. ->where('act_number', '>', $act_number)
  2813. ->decrement('act_number');
  2814. DB::commit();
  2815. }catch (\Exception $e) {
  2816. DB::rollBack();
  2817. Utils::throwError('20003:'.$e->getMessage());
  2818. }
  2819. return true;
  2820. }
  2821. public function applyAct($data) {
  2822. $act_id = getProp($data, 'act_id');
  2823. $url = getProp($data, 'url');
  2824. if (!$act_id) Utils::throwError('20003:请选择片段');
  2825. if (!$url) Utils::throwError('20003:URL不能为空');
  2826. // 获取URL的文件扩展名
  2827. $urlPath = parse_url($url, PHP_URL_PATH);
  2828. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2829. // 定义图片和视频的扩展名
  2830. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2831. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2832. // 判断是图片还是视频
  2833. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2834. if (in_array($extension, $imageExtensions)) {
  2835. // 图片类型
  2836. $updateData['img_url'] = $url;
  2837. $updateData['current_type'] = 1;
  2838. } elseif (in_array($extension, $videoExtensions)) {
  2839. // 视频类型
  2840. $updateData['video_url'] = $url;
  2841. $updateData['current_type'] = 2;
  2842. } else {
  2843. Utils::throwError('20003:不支持的文件类型');
  2844. }
  2845. // 更新片段记录(全能模式下每个act只有一条记录)
  2846. $result = DB::table('mp_episode_segments')
  2847. ->where('id', $act_id)
  2848. ->update($updateData);
  2849. if (!$result) {
  2850. Utils::throwError('20003:更新片段失败');
  2851. }
  2852. return true;
  2853. }
  2854. public function actChatHistory($data) {
  2855. $act_id = getProp($data, 'act_id');
  2856. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2857. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2858. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2859. $value = (array)$value;
  2860. $value['created_at'] = transDate($value['created_at']);
  2861. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2862. else $value['reference_images'] = [];
  2863. return $value;
  2864. })->toArray();
  2865. // 获取历史图片
  2866. $url = [];
  2867. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2868. foreach($pic_history as $task) {
  2869. $result_url = getProp($task, 'result_url');
  2870. if (is_json($result_url)) {
  2871. $url = array_merge($url, json_decode($result_url, true));
  2872. }else {
  2873. $url[] = $result_url;
  2874. }
  2875. }
  2876. // 获取历史视频
  2877. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2878. foreach($video_history as $task) {
  2879. $result_url = getProp($task, 'result_url');
  2880. if (is_json($result_url)) {
  2881. $url = array_merge($url, json_decode($result_url, true));
  2882. }else {
  2883. $url[] = $result_url;
  2884. }
  2885. }
  2886. // 获取资产库
  2887. $products = [];
  2888. // 通过act_id查询片段信息获取episode_id
  2889. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2890. if ($segment) {
  2891. $episode_id = getProp($segment, 'episode_id');
  2892. // 查询剧集信息获取roles、scenes和extra_products
  2893. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2894. if ($episode) {
  2895. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2896. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2897. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2898. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2899. // 先合并roles、scenes和props
  2900. // 处理角色数组
  2901. foreach ($roles as $role) {
  2902. $product = $role;
  2903. // 将role字段重命名为product_name
  2904. if (is_array($product) && !empty($product['role'] ?? null)) {
  2905. $product['product_name'] = $product['role'];
  2906. unset($product['role']);
  2907. $product['product'] = 1; // 标记类型为角色
  2908. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2909. }
  2910. }
  2911. // 处理场景数组
  2912. foreach ($scenes as $scene) {
  2913. $product = $scene;
  2914. // 将scene字段重命名为product_name
  2915. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2916. $product['product_name'] = $product['scene'];
  2917. unset($product['scene']);
  2918. $product['product'] = 2; // 标记类型为场景
  2919. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2920. }
  2921. }
  2922. // 处理道具数组
  2923. foreach ($props as $prop) {
  2924. $product = $prop;
  2925. // 将prop字段重命名为product_name
  2926. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2927. $product['product_name'] = $product['prop'];
  2928. unset($product['prop']);
  2929. $product['product'] = 3; // 标记类型为道具
  2930. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2931. }
  2932. }
  2933. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2934. foreach ($extra_products as $extra_product) {
  2935. $product_name = getProp($extra_product, 'product_name');
  2936. if ($product_name) {
  2937. $products[$product_name] = $extra_product; // 覆盖同名数据
  2938. }
  2939. }
  2940. // 重新索引数组(去除key)
  2941. $products = array_values($products);
  2942. }
  2943. }
  2944. // 获取执行中的任务
  2945. $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) {
  2946. $value = (array)$value;
  2947. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2948. else $value['ref_image_url'] = [];
  2949. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2950. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2951. if (!empty($value['prompt'])) {
  2952. $prompt = $value['prompt'];
  2953. // 查找第一个【镜头】的位置
  2954. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2955. // 从【镜头】开始截取
  2956. $prompt = substr($prompt, $matches[0][1]);
  2957. }
  2958. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2959. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2960. $value['prompt'] = $prompt;
  2961. }
  2962. return $value;
  2963. })->toArray();
  2964. return compact('chat', 'url', 'products', 'tasks');
  2965. }
  2966. public function applyAudioData($data) {
  2967. $segment_id = getProp($data, 'segment_id');
  2968. $global_data = getProp($data, 'global_data');
  2969. $segment_data = getProp($data, 'segment_data');
  2970. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2971. $global_data = is_array($global_data) ? $global_data : [];
  2972. $segment_data = is_array($segment_data) ? $segment_data : [];
  2973. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2974. $dialogue_item = null;
  2975. foreach ($global_data as $key => $item) {
  2976. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2977. $dialogue_item = $item;
  2978. unset($global_data[$key]);
  2979. break;
  2980. }
  2981. }
  2982. if ($dialogue_item) {
  2983. $segment_data[] = $dialogue_item;
  2984. }
  2985. // 特殊参数: audio_url,audio_duration,subtitle_info
  2986. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2987. // 如果不是全部存在,则仍需创建音频任务
  2988. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2989. $special_update_data = [];
  2990. $has_all_special_params = false;
  2991. // 从segment_data中提取特殊参数
  2992. $filtered_segment_data = [];
  2993. foreach ($segment_data as $item) {
  2994. $field_name = trim((string)getProp($item, 'name'));
  2995. if (in_array($field_name, $special_fields)) {
  2996. $special_update_data[$field_name] = getProp($item, 'value');
  2997. } else {
  2998. // 非特殊参数保留,继续后续处理
  2999. $filtered_segment_data[] = $item;
  3000. }
  3001. }
  3002. // 检查是否三个特殊参数都存在
  3003. if (count($special_update_data) === 3 &&
  3004. isset($special_update_data['audio_url']) &&
  3005. isset($special_update_data['audio_duration']) &&
  3006. isset($special_update_data['subtitle_info'])) {
  3007. $has_all_special_params = true;
  3008. // 立即更新到当前分镜
  3009. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3010. DB::table('mp_episode_segments')
  3011. ->where('segment_id', $segment_id)
  3012. ->update($special_update_data);
  3013. }
  3014. // 使用过滤后的segment_data继续处理其他参数
  3015. $segment_data = $filtered_segment_data;
  3016. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3017. $global_update_data = [];
  3018. $segment_update_data = [];
  3019. $global_voice_type = '';
  3020. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3021. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3022. $episode_id = getProp($target_segment, 'episode_id');
  3023. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3024. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3025. if (!$episode) Utils::throwError('20003:分集不存在');
  3026. foreach ($global_data as $item) {
  3027. $field_name = trim((string)getProp($item, 'name'));
  3028. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3029. continue;
  3030. }
  3031. $global_update_data[$field_name] = getProp($item, 'value');
  3032. if ($field_name === 'voice_type') {
  3033. $global_voice_type = trim((string)getProp($item, 'value'));
  3034. }
  3035. }
  3036. foreach ($segment_data as $item) {
  3037. $field_name = trim((string)getProp($item, 'name'));
  3038. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3039. continue;
  3040. }
  3041. $segment_update_data[$field_name] = getProp($item, 'value');
  3042. }
  3043. if ($global_voice_type) {
  3044. $timbre_info = DB::table('mp_timbres')
  3045. ->where('timbre_type', $global_voice_type)
  3046. ->select('audio_url', 'timbre_name')
  3047. ->first();
  3048. if ($timbre_info) {
  3049. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3050. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3051. }
  3052. }
  3053. try {
  3054. DB::beginTransaction();
  3055. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3056. $segment_ids_to_create_task = [];
  3057. $segments_data = [];
  3058. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3059. if (!empty($global_update_data)) {
  3060. // 如果角色不存在,则只更新当前分镜
  3061. if (!$target_voice_actor) {
  3062. // 只处理当前分镜
  3063. $affected_segments = DB::table('mp_episode_segments')
  3064. ->where('segment_id', $segment_id)
  3065. ->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')
  3066. ->get();
  3067. } else {
  3068. // 获取该角色的所有分镜
  3069. $affected_segments = DB::table('mp_episode_segments')
  3070. ->where('episode_id', $episode_id)
  3071. ->where('voice_actor', $target_voice_actor)
  3072. ->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')
  3073. ->get();
  3074. }
  3075. foreach ($affected_segments as $seg) {
  3076. $seg = (array)$seg;
  3077. $sid = getProp($seg, 'segment_id');
  3078. // 检查参数是否发生变化
  3079. $has_changed = false;
  3080. foreach ($global_update_data as $field => $new_value) {
  3081. $old_value = getProp($seg, $field);
  3082. if ($old_value != $new_value) {
  3083. $has_changed = true;
  3084. break;
  3085. }
  3086. }
  3087. if ($has_changed) {
  3088. $segment_ids_to_create_task[] = $sid;
  3089. $segments_data[$sid] = $seg;
  3090. }
  3091. }
  3092. // 只有在有变化的分镜时才更新
  3093. if (!empty($segment_ids_to_create_task)) {
  3094. $global_segment_update_data = $global_update_data;
  3095. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3096. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3097. DB::table('mp_episode_segments')
  3098. ->where('episode_id', $episode_id)
  3099. ->where('voice_actor', $target_voice_actor)
  3100. ->whereIn('segment_id', $segment_ids_to_create_task)
  3101. ->update($global_segment_update_data);
  3102. }
  3103. if ($global_voice_type) {
  3104. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3105. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3106. $roles_updated = false;
  3107. foreach ($episode_roles as &$role) {
  3108. // 通过 role 字段匹配角色名,而不是 voice_name
  3109. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3110. continue;
  3111. }
  3112. $role['voice_type'] = $global_voice_type;
  3113. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3114. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3115. $roles_updated = true;
  3116. }
  3117. unset($role);
  3118. if ($roles_updated) {
  3119. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3120. 'roles' => json_encode($episode_roles, 256),
  3121. 'updated_at' => date('Y-m-d H:i:s'),
  3122. ]);
  3123. }
  3124. }
  3125. }
  3126. // 如果有单个分镜更新,检查是否有变化
  3127. if (!empty($segment_update_data)) {
  3128. // 获取当前分镜数据
  3129. $current_segment = DB::table('mp_episode_segments')
  3130. ->where('segment_id', $segment_id)
  3131. ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3132. ->first();
  3133. if ($current_segment) {
  3134. $current_segment = (array)$current_segment;
  3135. // 检查参数是否发生变化
  3136. $has_changed = false;
  3137. foreach ($segment_update_data as $field => $new_value) {
  3138. $old_value = getProp($current_segment, $field);
  3139. if ($old_value != $new_value) {
  3140. $has_changed = true;
  3141. break;
  3142. }
  3143. }
  3144. if ($has_changed) {
  3145. // 如果该分镜还未在列表中,添加进去
  3146. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3147. $segment_ids_to_create_task[] = $segment_id;
  3148. $segments_data[$segment_id] = $current_segment;
  3149. }
  3150. // 更新分镜数据并清空音频URL
  3151. $segment_update_data['audio_url'] = '';
  3152. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3153. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3154. }
  3155. }
  3156. }
  3157. // 为所有有变化的分镜创建音频合成任务
  3158. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3159. if (!empty($segment_ids_to_create_task)) {
  3160. foreach ($segment_ids_to_create_task as $sid) {
  3161. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3162. if ($sid === $segment_id && $has_all_special_params) {
  3163. continue;
  3164. }
  3165. // 重新获取更新后的分镜数据
  3166. $updated_segment = DB::table('mp_episode_segments')
  3167. ->where('segment_id', $sid)
  3168. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3169. ->first();
  3170. if (!$updated_segment) continue;
  3171. $updated_segment = (array)$updated_segment;
  3172. // 检查dialogue是否为空
  3173. $dialogue = getProp($updated_segment, 'dialogue');
  3174. if (empty($dialogue)) {
  3175. // dialogue为空时,直接写入默认音频信息
  3176. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3177. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3178. 'audio_duration' => 2.0,
  3179. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3180. 'updated_at' => date('Y-m-d H:i:s')
  3181. ]);
  3182. continue;
  3183. }
  3184. $generate_json = [
  3185. 'text' => $dialogue,
  3186. 'role' => getProp($updated_segment, 'voice_actor'),
  3187. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3188. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3189. 'emotion' => getProp($updated_segment, 'emotion'),
  3190. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3191. 'gender' => getProp($updated_segment, 'gender'),
  3192. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3193. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3194. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3195. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3196. ];
  3197. // 插入视频配音合成任务
  3198. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3199. 'alias_segment_id' => $sid,
  3200. 'generate_status' => '执行中',
  3201. 'audio_url' => '',
  3202. 'generate_json' => json_encode($generate_json, 256),
  3203. 'created_at' => date('Y-m-d H:i:s'),
  3204. 'updated_at' => date('Y-m-d H:i:s'),
  3205. ]);
  3206. if (!$dubTaskId) {
  3207. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3208. continue;
  3209. }
  3210. // 将任务ID添加到Redis列表中
  3211. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3212. // 请求远程服务器执行生成
  3213. try {
  3214. sleep(1);
  3215. $client = new Client(['timeout' => 300, 'verify' => false]);
  3216. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3217. $response = $result->getBody()->getContents();
  3218. $response_arr = json_decode($response, true);
  3219. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3220. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3221. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3222. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3223. }
  3224. } catch (\Exception $e) {
  3225. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3226. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3227. }
  3228. }
  3229. }
  3230. DB::commit();
  3231. } catch (\Exception $e) {
  3232. DB::rollBack();
  3233. Utils::throwError('20003:'.$e->getMessage());
  3234. }
  3235. return true;
  3236. }
  3237. public function episodePicsInfo($data) {
  3238. $anime_id = getProp($data, 'anime_id');
  3239. $episode_id = getProp($data, 'episode_id');
  3240. // 参数验证
  3241. if (!$anime_id && !$episode_id) {
  3242. Utils::throwError('20003:请提供动漫ID或分集ID');
  3243. }
  3244. // 根据参数获取数据源
  3245. if ($episode_id) {
  3246. // 从剧集表获取
  3247. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3248. if (!$source) Utils::throwError('20003:该剧集不存在');
  3249. $table_name = 'mp_anime_episodes';
  3250. $id_field = 'id';
  3251. $id_value = $episode_id;
  3252. // 获取剧集的anime_id用于继承全局数据
  3253. $anime_id = getProp($source, 'anime_id');
  3254. } else {
  3255. // 从动漫表获取
  3256. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3257. if (!$source) Utils::throwError('20003:该动漫不存在');
  3258. $table_name = 'mp_animes';
  3259. $id_field = 'id';
  3260. $id_value = $anime_id;
  3261. }
  3262. $source = (array)$source;
  3263. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3264. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3265. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3266. // 如果是分集数据,需要处理继承和任务创建逻辑
  3267. if ($episode_id) {
  3268. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3269. }
  3270. // 返回生成器函数,用于 SSE 流式输出
  3271. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3272. $startTime = time();
  3273. $maxDuration = 600; // 10分钟超时
  3274. $checkInterval = 3; // 每3秒检查一次
  3275. // Redis 缓存键
  3276. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3277. // 生成当前数据的哈希值用于比较
  3278. $generateHash = function($roles, $scenes, $props) {
  3279. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3280. };
  3281. // 发送初始数据
  3282. $currentHash = $generateHash($roles, $scenes, $props);
  3283. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3284. echo "data: " . json_encode([
  3285. 'type' => 'init',
  3286. 'data' => [
  3287. 'roles' => $roles,
  3288. 'scenes' => $scenes,
  3289. 'props' => $props,
  3290. 'start_time' => $startTime
  3291. ]
  3292. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3293. if (ob_get_level() > 0) {
  3294. ob_flush();
  3295. }
  3296. flush();
  3297. // 持续轮询任务状态
  3298. while (time() - $startTime < $maxDuration) {
  3299. $hasProcessing = false;
  3300. $updated = false;
  3301. // 检查角色任务状态
  3302. foreach ($roles as $index => &$role) {
  3303. $task_id = getProp($role, 'task_id');
  3304. $task_status = getProp($role, 'task_status');
  3305. $existing_url = getProp($role, 'url');
  3306. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3307. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3308. $hasProcessing = ($task_status === 'processing');
  3309. // 查询任务状态
  3310. $task = DB::table('mp_generate_pic_tasks')
  3311. ->where('id', $task_id)
  3312. ->select('id', 'status', 'result_url', 'error_message')
  3313. ->first();
  3314. if ($task) {
  3315. $task = (array)$task;
  3316. $status = getProp($task, 'status');
  3317. // 如果任务完成或失败
  3318. if (in_array($status, ['success', 'failed'])) {
  3319. $role['task_status'] = $status;
  3320. if ($status === 'success') {
  3321. $result_url = getProp($task, 'result_url');
  3322. if ($result_url) {
  3323. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3324. if (is_array($result_urls) && !empty($result_urls[0])) {
  3325. $role['url'] = $result_urls[0];
  3326. }
  3327. }
  3328. }
  3329. $updated = true;
  3330. } else if ($status === 'processing') {
  3331. $hasProcessing = true;
  3332. }
  3333. }
  3334. }
  3335. }
  3336. // 检查场景任务状态
  3337. foreach ($scenes as $index => &$scene) {
  3338. $task_id = getProp($scene, 'task_id');
  3339. $task_status = getProp($scene, 'task_status');
  3340. $existing_url = getProp($scene, 'url');
  3341. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3342. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3343. $hasProcessing = ($task_status === 'processing');
  3344. // 查询任务状态
  3345. $task = DB::table('mp_generate_pic_tasks')
  3346. ->where('id', $task_id)
  3347. ->select('id', 'status', 'result_url', 'error_message')
  3348. ->first();
  3349. if ($task) {
  3350. $task = (array)$task;
  3351. $status = getProp($task, 'status');
  3352. // 如果任务完成或失败
  3353. if (in_array($status, ['success', 'failed'])) {
  3354. $scene['task_status'] = $status;
  3355. if ($status === 'success') {
  3356. $result_url = getProp($task, 'result_url');
  3357. if ($result_url) {
  3358. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3359. if (is_array($result_urls) && !empty($result_urls[0])) {
  3360. $scene['url'] = $result_urls[0];
  3361. }
  3362. }
  3363. }
  3364. $updated = true;
  3365. } else if ($status === 'processing') {
  3366. $hasProcessing = true;
  3367. }
  3368. }
  3369. }
  3370. }
  3371. // 检查道具任务状态
  3372. foreach ($props as $index => &$prop) {
  3373. $task_id = getProp($prop, 'task_id');
  3374. $task_status = getProp($prop, 'task_status');
  3375. $existing_url = getProp($prop, 'url');
  3376. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3377. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3378. $hasProcessing = ($task_status === 'processing');
  3379. // 查询任务状态
  3380. $task = DB::table('mp_generate_pic_tasks')
  3381. ->where('id', $task_id)
  3382. ->select('id', 'status', 'result_url', 'error_message')
  3383. ->first();
  3384. if ($task) {
  3385. $task = (array)$task;
  3386. $status = getProp($task, 'status');
  3387. // 如果任务完成或失败
  3388. if (in_array($status, ['success', 'failed'])) {
  3389. $prop['task_status'] = $status;
  3390. if ($status === 'success') {
  3391. $result_url = getProp($task, 'result_url');
  3392. if ($result_url) {
  3393. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3394. if (is_array($result_urls) && !empty($result_urls[0])) {
  3395. $prop['url'] = $result_urls[0];
  3396. }
  3397. }
  3398. }
  3399. $updated = true;
  3400. } else if ($status === 'processing') {
  3401. $hasProcessing = true;
  3402. }
  3403. }
  3404. }
  3405. }
  3406. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3407. if ($updated) {
  3408. $newHash = $generateHash($roles, $scenes, $props);
  3409. $cachedHash = Redis::get($cacheKey);
  3410. // 只有当数据真正变化时才更新数据库和发送事件
  3411. if ($newHash !== $cachedHash) {
  3412. try {
  3413. // 更新数据库
  3414. DB::table($table_name)->where($id_field, $id_value)->update([
  3415. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3416. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3417. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3418. 'updated_at' => date('Y-m-d H:i:s')
  3419. ]);
  3420. // 更新缓存
  3421. Redis::setex($cacheKey, 600, $newHash);
  3422. // 发送更新事件
  3423. echo "data: " . json_encode([
  3424. 'type' => 'update',
  3425. 'data' => [
  3426. 'roles' => $roles,
  3427. 'scenes' => $scenes,
  3428. 'props' => $props,
  3429. 'elapsed_time' => time() - $startTime
  3430. ]
  3431. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3432. if (ob_get_level() > 0) {
  3433. ob_flush();
  3434. }
  3435. flush();
  3436. } catch (\Exception $e) {
  3437. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3438. }
  3439. } else {
  3440. // 即使哈希相同,如果有URL更新也要发送事件
  3441. $hasUrlUpdate = false;
  3442. foreach ($roles as $role) {
  3443. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3444. $hasUrlUpdate = true;
  3445. break;
  3446. }
  3447. }
  3448. if (!$hasUrlUpdate) {
  3449. foreach ($scenes as $scene) {
  3450. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3451. $hasUrlUpdate = true;
  3452. break;
  3453. }
  3454. }
  3455. }
  3456. if (!$hasUrlUpdate) {
  3457. foreach ($props as $prop) {
  3458. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3459. $hasUrlUpdate = true;
  3460. break;
  3461. }
  3462. }
  3463. }
  3464. if ($hasUrlUpdate) {
  3465. // 强制更新数据库和发送事件
  3466. try {
  3467. DB::table($table_name)->where($id_field, $id_value)->update([
  3468. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3469. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3470. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3471. 'updated_at' => date('Y-m-d H:i:s')
  3472. ]);
  3473. // 更新缓存
  3474. Redis::setex($cacheKey, 600, $newHash);
  3475. // 发送更新事件
  3476. echo "data: " . json_encode([
  3477. 'type' => 'update',
  3478. 'data' => [
  3479. 'roles' => $roles,
  3480. 'scenes' => $scenes,
  3481. 'props' => $props,
  3482. 'elapsed_time' => time() - $startTime
  3483. ]
  3484. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3485. if (ob_get_level() > 0) {
  3486. ob_flush();
  3487. }
  3488. flush();
  3489. } catch (\Exception $e) {
  3490. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3491. }
  3492. }
  3493. }
  3494. }
  3495. // 如果所有任务都已完成,发送完成事件并退出
  3496. if (!$hasProcessing) {
  3497. // 查询数据库中的最终数据,确保返回最新的完整数据
  3498. try {
  3499. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3500. if ($finalSource) {
  3501. $finalSource = (array)$finalSource;
  3502. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3503. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3504. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3505. // 使用数据库中的最终数据
  3506. $roles = $finalRoles;
  3507. $scenes = $finalScenes;
  3508. $props = $finalProps;
  3509. }
  3510. } catch (\Exception $e) {
  3511. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3512. // 如果查询失败,继续使用内存中的数据
  3513. }
  3514. // 清理缓存
  3515. Redis::del($cacheKey);
  3516. echo "data: " . json_encode([
  3517. 'type' => 'completed',
  3518. 'data' => [
  3519. 'roles' => $roles,
  3520. 'scenes' => $scenes,
  3521. 'props' => $props,
  3522. 'total_time' => time() - $startTime
  3523. ]
  3524. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3525. if (ob_get_level() > 0) {
  3526. ob_flush();
  3527. }
  3528. flush();
  3529. break;
  3530. }
  3531. // 等待下次检查
  3532. sleep($checkInterval);
  3533. }
  3534. // 超时处理
  3535. if (time() - $startTime >= $maxDuration) {
  3536. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3537. try {
  3538. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3539. if ($finalSource) {
  3540. $finalSource = (array)$finalSource;
  3541. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3542. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3543. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3544. // 使用数据库中的最终数据
  3545. $roles = $finalRoles;
  3546. $scenes = $finalScenes;
  3547. $props = $finalProps;
  3548. }
  3549. } catch (\Exception $e) {
  3550. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3551. // 如果查询失败,继续使用内存中的数据
  3552. }
  3553. // 清理缓存
  3554. Redis::del($cacheKey);
  3555. echo "data: " . json_encode([
  3556. 'type' => 'timeout',
  3557. 'message' => '轮询超时,请刷新页面查看最新状态',
  3558. 'data' => [
  3559. 'roles' => $roles,
  3560. 'scenes' => $scenes,
  3561. 'props' => $props
  3562. ]
  3563. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3564. if (ob_get_level() > 0) {
  3565. ob_flush();
  3566. }
  3567. flush();
  3568. }
  3569. };
  3570. }
  3571. public function clipSegmentVideo($data) {
  3572. $segment_id = getProp($data, 'segment_id');
  3573. $video_time_point_start = getProp($data, 'video_time_point_start');
  3574. $video_time_point_end = getProp($data, 'video_time_point_end');
  3575. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3576. Utils::throwError('20003:参数异常');
  3577. }
  3578. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3579. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3580. }
  3581. $video_duration = $video_time_point_end - $video_time_point_start;
  3582. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3583. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3584. 'video_duration' => $video_duration,
  3585. 'video_time_point_start' => $video_time_point_start,
  3586. 'video_time_point_end' => $video_time_point_end,
  3587. 'updated_at' => date('Y-m-d H:i:s')
  3588. ]);
  3589. }
  3590. // 轮训获取图片任务结果
  3591. private function loopGetPicTaskResult($task_id) {
  3592. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3593. if (!$task) {
  3594. return '';
  3595. }
  3596. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3597. $model = getProp($task, 'model');
  3598. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3599. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3600. $isSyncModel = $isVolcModel || $isGptModel;
  3601. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3602. $start_count = 0;
  3603. $img_url = '';
  3604. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3605. sleep(3);
  3606. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3607. // 如果任务已经完成,直接返回结果
  3608. if ($task->status === 'success' && $task->result_url) {
  3609. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3610. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3611. }
  3612. // 如果任务已失败,返回空
  3613. if ($task->status === 'failed') {
  3614. return '';
  3615. }
  3616. if ($isSyncModel) continue;
  3617. // 查询任务状态
  3618. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3619. if ($statusInfo['status'] === 'success') {
  3620. $task->updateStatus('success', [
  3621. 'result_url' => $statusInfo['result_url'],
  3622. 'result_json' => $statusInfo['result_json'] ?? []
  3623. ]);
  3624. // 同步调整分镜图片状态和结果
  3625. if (getProp($task, 'alias_segment_id')) {
  3626. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3627. 'img_url' => $statusInfo['result_url'][0],
  3628. 'pic_task_status' => '已完成',
  3629. ]);
  3630. }
  3631. $img_url = $statusInfo['result_url'][0];
  3632. break;
  3633. } elseif ($statusInfo['status'] === 'failed') {
  3634. $task->updateStatus('failed', [
  3635. 'error_message' => $statusInfo['error_message'],
  3636. 'result_json' => $statusInfo['result_json'] ?? []
  3637. ]);
  3638. if (getProp($task, 'alias_segment_id')) {
  3639. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3640. 'pic_task_status' => '失败',
  3641. ]);
  3642. }
  3643. break;
  3644. }
  3645. $start_count++;
  3646. }
  3647. return $img_url;
  3648. }
  3649. /**
  3650. * 从分镜内容中提取涉及的角色
  3651. */
  3652. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3653. $found_characters = [];
  3654. foreach ($available_characters as $character) {
  3655. // 检查角色名称是否在分镜内容中出现
  3656. if (strpos($segment_content, $character) !== false) {
  3657. $found_characters[] = $character;
  3658. }
  3659. }
  3660. if (!$found_characters) {
  3661. foreach ($roles as $character) {
  3662. // 检查角色名称是否在分镜内容中出现
  3663. if (strpos($segment_content, $character) !== false) {
  3664. $found_characters[] = $character;
  3665. }
  3666. }
  3667. }
  3668. return array_unique($found_characters);
  3669. }
  3670. // 从分镜剧本中提取关键字段
  3671. private function handleSegmentContent(&$data) {
  3672. $segmentContent = getProp($data, 'segment_content');
  3673. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3674. $segmentData = [
  3675. 'description' => '',
  3676. 'composition' => '',
  3677. 'camera_movement' => '',
  3678. 'voice_actor' => '',
  3679. 'dialogue' => '',
  3680. 'frame_type' => '',
  3681. 'scene' => '', // 场景
  3682. 'characters' => '', // 出镜角色
  3683. 'tail_frame' => '', // 尾帧描述
  3684. 'emotion' => '中性', // 情感
  3685. 'gender' => '0', // 性别(0未知,1男,2女)
  3686. 'speed_ratio' => 0, // 语速
  3687. 'loudness_ratio' => 0, // 音量
  3688. 'emotion_scale' => 4, // 情感强度
  3689. 'pitch' => 0, // 音调
  3690. ];
  3691. // 用于存储需要从 segment_content 中移除的匹配项
  3692. $replaceEmptyArr = [];
  3693. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3694. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3695. $segmentData['description'] = trim($descMatch[1]);
  3696. $data['description'] = trim($descMatch[1]);
  3697. }
  3698. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3699. $segmentData['composition'] = trim($compMatch[1]);
  3700. $data['composition'] = trim($compMatch[1]);
  3701. }
  3702. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3703. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3704. $data['camera_movement'] = trim($cameraMatch[1]);
  3705. }
  3706. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3707. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3708. $data['voice_actor'] = trim($voiceMatch[1]);
  3709. }
  3710. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3711. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3712. $data['dialogue'] = trim($dialogueMatch[1]);
  3713. }
  3714. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3715. $segmentData['frame_type'] = trim($frameMatch[1]);
  3716. $data['frame_type'] = trim($frameMatch[1]);
  3717. }
  3718. // 场景字段
  3719. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3720. $segmentData['scene'] = trim($sceneMatch[1]);
  3721. $data['scene'] = trim($sceneMatch[1]);
  3722. }
  3723. // 出镜角色字段
  3724. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3725. $segmentData['characters'] = trim($charactersMatch[1]);
  3726. $data['characters'] = trim($charactersMatch[1]);
  3727. }
  3728. // 尾帧描述字段
  3729. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3730. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3731. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3732. }
  3733. // 情感字段
  3734. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3735. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3736. $segmentData['emotion'] = trim($emotionMatch[1]);
  3737. $data['emotion'] = trim($emotionMatch[1]);
  3738. }
  3739. // 性别字段
  3740. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3741. $replaceEmptyArr[] = trim($genderMatch[0]);
  3742. $genderStr = trim($genderMatch[1]);
  3743. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3744. $segmentData['gender'] = '1';
  3745. $data['gender'] = '1';
  3746. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3747. $segmentData['gender'] = '2';
  3748. $data['gender'] = '2';
  3749. } else {
  3750. $segmentData['gender'] = '0';
  3751. $data['gender'] = '0';
  3752. }
  3753. }
  3754. // 语速字段
  3755. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3756. $replaceEmptyArr[] = trim($speedMatch[0]);
  3757. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3758. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3759. }
  3760. // 音量字段
  3761. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3762. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3763. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3764. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3765. }
  3766. // 情感强度字段
  3767. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3768. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3769. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3770. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3771. }
  3772. // 音调字段
  3773. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3774. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3775. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3776. $data['pitch'] = (int)trim($pitchMatch[1]);
  3777. }
  3778. // 从 segment_content 中移除已提取的配音参数字段
  3779. if (!empty($replaceEmptyArr)) {
  3780. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3781. }
  3782. // 如果有配音角色,查询音色信息并验证情感
  3783. $voice_actor = $segmentData['voice_actor'];
  3784. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3785. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3786. $anime_id = getProp($data, 'anime_id');
  3787. $episode_id = getProp($data, 'episode_id');
  3788. // 优先从剧集的角色列表中查找
  3789. $roles = [];
  3790. if ($episode_id) {
  3791. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3792. if ($episode && getProp($episode, 'roles')) {
  3793. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3794. }
  3795. }
  3796. // 如果剧集中没有,从动漫的角色列表中查找
  3797. if (empty($roles) && $anime_id) {
  3798. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3799. if ($anime && getProp($anime, 'roles')) {
  3800. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3801. }
  3802. }
  3803. // 查找匹配的角色音色信息
  3804. $timbre_info = null;
  3805. foreach ($roles as $role) {
  3806. if (getProp($role, 'role') === $voice_actor) {
  3807. $timbre_info = $role;
  3808. break;
  3809. }
  3810. }
  3811. // 如果找到音色信息,添加到数据中
  3812. if ($timbre_info) {
  3813. $voice_type = getProp($timbre_info, 'voice_type');
  3814. $voice_name = getProp($timbre_info, 'voice_name');
  3815. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3816. if ($voice_type) {
  3817. $data['voice_type'] = $voice_type;
  3818. $segmentData['voice_type'] = $voice_type;
  3819. }
  3820. if ($voice_name) {
  3821. $data['voice_name'] = $voice_name;
  3822. $segmentData['voice_name'] = $voice_name;
  3823. }
  3824. if ($voice_audio_url) {
  3825. $data['voice_audio_url'] = $voice_audio_url;
  3826. $segmentData['voice_audio_url'] = $voice_audio_url;
  3827. }
  3828. // 验证情感是否在音色支持的情感列表中
  3829. if ($voice_type) {
  3830. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3831. if ($timbre_emotion) {
  3832. $timbre_emotion = explode(',', $timbre_emotion);
  3833. } else {
  3834. $timbre_emotion = [];
  3835. }
  3836. $emotion = getProp($segmentData, 'emotion', '中性');
  3837. if (!in_array($emotion, $timbre_emotion)) {
  3838. $emotion = '中性';
  3839. }
  3840. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3841. $emotion_list = array_flip($emotion_list);
  3842. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3843. $data['emotion_type'] = $emotion_type;
  3844. $segmentData['emotion_type'] = $emotion_type;
  3845. }
  3846. }
  3847. }
  3848. return $segmentData;
  3849. }
  3850. public function createSegmentVideoTask($data) {
  3851. $segment_id = getProp($data, 'segment_id');
  3852. $tail_frame = getProp($data, 'tail_frame');
  3853. $first_frame_url = getProp($data, 'first_frame_url');
  3854. $tail_frame_url = getProp($data, 'tail_frame_url');
  3855. $generate_audio = getProp($data, 'generate_audio', 0);
  3856. if (!$segment_id) {
  3857. Utils::throwError('1002:分镜ID不能为空');
  3858. }
  3859. // 获取分镜信息
  3860. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3861. if (!$segment) {
  3862. Utils::throwError('20003:分镜不存在');
  3863. }
  3864. $segment = (array)$segment;
  3865. $episode_id = getProp($segment, 'episode_id');
  3866. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3867. if (!$ratio) $ratio = '9:16';
  3868. // 获取分镜内容
  3869. $segmentContent = getProp($segment, 'segment_content', '');
  3870. // 检查 $segmentContent 中是否已有尾帧描述
  3871. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3872. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3873. $finalTailFrame = '';
  3874. if ($tail_frame) {
  3875. // 用户输入了尾帧描述,优先使用
  3876. $finalTailFrame = $tail_frame;
  3877. // 如果 segmentContent 中已有尾帧描述,需要替换
  3878. if ($contentHasTailFrame) {
  3879. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3880. }
  3881. } elseif ($contentHasTailFrame) {
  3882. // segmentContent 中有尾帧描述,使用它
  3883. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3884. } else {
  3885. // 两者都没有,使用分镜表中的尾帧描述
  3886. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3887. }
  3888. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3889. $hasDialogue = false;
  3890. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3891. $dialogue = trim($dialogueMatch[1]);
  3892. // 如果台词不为空且不是"无"
  3893. if (!empty($dialogue) && $dialogue !== '无') {
  3894. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3895. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3896. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3897. $hasDialogue = true;
  3898. }
  3899. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3900. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3901. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3902. if (!preg_match('/^[“]/', $dialogue)) {
  3903. $dialogue = '“' . $dialogue;
  3904. }
  3905. if (!preg_match('/[”]$/', $dialogue)) {
  3906. $dialogue .= '”';
  3907. }
  3908. // 将修改后的台词替换回 $segmentContent
  3909. $originalDialogue = $dialogueMatch[1];
  3910. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3911. }
  3912. }
  3913. // 构建完整的提示词
  3914. $fullPrompt = $segmentContent;
  3915. if ($finalTailFrame && !$contentHasTailFrame) {
  3916. // 只有当 segmentContent 中没有尾帧描述时才追加
  3917. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3918. }
  3919. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3920. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3921. $fullPrompt = trim($fullPrompt);
  3922. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3923. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3924. // 智能选择视频时长
  3925. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3926. $videoDuration = -1;
  3927. // 处理视频模型
  3928. $model = getProp($data, 'model');
  3929. if (!$model) {
  3930. // 用户没有输入,从episode表获取
  3931. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3932. $model = getProp($episode, 'video_model');
  3933. if (!$model) {
  3934. // episode表也没有,使用默认值
  3935. $model = 'doubao-seedance-1-5-pro-251215';
  3936. }
  3937. }
  3938. // 验证模型是否在可用模型表中
  3939. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3940. $model = 'doubao-seedance-1-5-pro-251215';
  3941. }
  3942. // 保存到episode表
  3943. $episode_id = getProp($segment, 'episode_id');
  3944. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3945. 'video_model' => $model,
  3946. 'updated_at' => date('Y-m-d H:i:s')
  3947. ]);
  3948. // 构建视频生成参数
  3949. $videoParams = [
  3950. 'model' => $model,
  3951. 'alias_segment_id' => $segment_id,
  3952. 'prompt' => trim($fullPrompt),
  3953. 'video_duration' => $videoDuration,
  3954. 'video_resolution' => '720P',
  3955. 'seed' => -1,
  3956. 'ratio' => $ratio,
  3957. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3958. 'draft' => false,
  3959. 'watermark' => false,
  3960. 'camera_fixed' => false,
  3961. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3962. ];
  3963. // 如果分镜有图片,作为首帧
  3964. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3965. $hasVideo = !empty(getProp($segment, 'video_url'));
  3966. if ($hasImage) {
  3967. if ($first_frame_url) {
  3968. $videoParams['first_frame_url'] = $first_frame_url;
  3969. }else {
  3970. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3971. }
  3972. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3973. }
  3974. // 构建content数组
  3975. $videoParams['content'] = [
  3976. [
  3977. 'type' => 'text',
  3978. 'text' => $videoParams['prompt'],
  3979. ]
  3980. ];
  3981. // 如果有首帧图片,添加到content中
  3982. if ($hasImage) {
  3983. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3984. $videoParams['content'][] = [
  3985. 'type' => 'image_url',
  3986. 'image_url' => [
  3987. 'url' => $videoParams['first_frame_url'],
  3988. ],
  3989. 'role' => 'reference_image',
  3990. ];
  3991. if (isset($videoParams['tail_frame_url'])) {
  3992. $videoParams['content'][] = [
  3993. 'type' => 'image_url',
  3994. 'image_url' => [
  3995. 'url' => $videoParams['tail_frame_url'],
  3996. ],
  3997. 'role' => 'reference_image',
  3998. ];
  3999. }
  4000. }else {
  4001. $videoParams['content'][] = [
  4002. 'type' => 'image_url',
  4003. 'image_url' => [
  4004. 'url' => $videoParams['first_frame_url'],
  4005. ],
  4006. 'role' => 'first_frame',
  4007. ];
  4008. if (isset($videoParams['tail_frame_url'])) {
  4009. $videoParams['content'][] = [
  4010. 'type' => 'image_url',
  4011. 'image_url' => [
  4012. 'url' => $videoParams['tail_frame_url'],
  4013. ],
  4014. 'role' => 'last_frame',
  4015. ];
  4016. }
  4017. }
  4018. }
  4019. // 获取配音音频URL
  4020. $audioUrl = getProp($segment, 'audio_url');
  4021. $audioDuration = getProp($segment, 'audio_duration');
  4022. // 音频传入的前提:必须有至少一张图片或一个视频
  4023. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4024. // dd($videoParams);
  4025. // 根据模型选择不同的视频生成方法
  4026. if (strpos($model, 'jimeng') !== false) {
  4027. // 即梦模型参数调整
  4028. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4029. unset($videoParams['content']); // 即梦不使用content格式
  4030. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4031. } elseif (strpos($model, 'kling') !== false) {
  4032. // Keling模型参数调整
  4033. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4034. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4035. unset($videoParams['ratio']);
  4036. unset($videoParams['content']); // Keling不使用content格式
  4037. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4038. } elseif (strpos($model, 'zhizhen') !== false) {
  4039. // 智帧20等新模型使用统一API
  4040. // 构建统一API参数
  4041. $unifiedParams = [
  4042. 'model_code' => $model,
  4043. 'alias_segment_id' => $segment_id,
  4044. 'prompt' => trim($fullPrompt),
  4045. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4046. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4047. 'video_ratio' => $ratio,
  4048. 'seed' => -1,
  4049. ];
  4050. // 构建parameters参数
  4051. $parameters = [
  4052. 'seconds' => $unifiedParams['video_duration'],
  4053. 'resolution' => $unifiedParams['video_resolution'],
  4054. 'ratio' => $ratio,
  4055. // 'video_mode' => 'multi_image',
  4056. // 'mode' => 'multi_image',
  4057. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4058. ];
  4059. $hasImage = false;
  4060. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4061. if ($hasImage) {
  4062. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4063. if (isset($videoParams['tail_frame_url'])) {
  4064. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4065. }
  4066. // 只有在有图片的情况下才能添加参考音频
  4067. if ($audioUrl) {
  4068. // $parameters['reference_audios'] = [$audioUrl];
  4069. }
  4070. } else {
  4071. // 没有图片时,记录错误日志
  4072. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4073. 'segment_id' => $segment_id,
  4074. 'model' => $model
  4075. ]);
  4076. }
  4077. $unifiedParams['parameters'] = $parameters;
  4078. // 调用统一API创建任务
  4079. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4080. } else {
  4081. // Seedance模型(默认)
  4082. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4083. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4084. // 添加配音音频到content中
  4085. $videoParams['content'][] = [
  4086. 'type' => 'audio_url',
  4087. 'audio_url' => [
  4088. 'url' => $audioUrl,
  4089. ],
  4090. 'role' => 'reference_audio',
  4091. ];
  4092. // 优化提示词,增加音频相关描述
  4093. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4094. $videoParams['prompt'] = $audioPrompt;
  4095. $videoParams['content'][0]['text'] = $audioPrompt;
  4096. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4097. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4098. }
  4099. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4100. }
  4101. // 更新分镜表的视频任务信息
  4102. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4103. 'video_task_id' => $task->id,
  4104. 'video_task_status' => '生成中',
  4105. 'generate_audio' => $generate_audio,
  4106. 'updated_at' => date('Y-m-d H:i:s')
  4107. ]);
  4108. return [
  4109. 'task_id' => $task->id,
  4110. 'status' => $task->status,
  4111. 'segment_id' => $segment_id,
  4112. 'video_duration' => $videoDuration
  4113. ];
  4114. }
  4115. public function createActVideoTask($data) {
  4116. $act_id = getProp($data, 'act_id');
  4117. $first_frame_url = getProp($data, 'first_frame_url');
  4118. $tail_frame_url = getProp($data, 'tail_frame_url');
  4119. $generate_audio = getProp($data, 'generate_audio', 1);
  4120. $video_duration = getProp($data, 'video_duration');
  4121. $video_resolution = getProp($data, 'video_resolution');
  4122. $ratio = getProp($data, 'ratio');
  4123. $products = getProp($data, 'products', []);
  4124. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4125. if (!is_array($reference_images) || !is_array($products)) {
  4126. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4127. }
  4128. if (!$act_id) {
  4129. Utils::throwError('1002:片段ID不能为空');
  4130. }
  4131. // 获取片段信息
  4132. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4133. if (!$act) {
  4134. Utils::throwError('20003:片段不存在');
  4135. }
  4136. $act = (array)$act;
  4137. $anime_id = getProp($act, 'anime_id');
  4138. $episode_id = getProp($act, 'episode_id');
  4139. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4140. $ace_mode = getProp($anime, 'ace_mode');
  4141. $art_style_type = getProp($anime, 'art_style_type');
  4142. $art_style = getProp($anime, 'art_style');
  4143. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4144. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4145. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4146. // 将资产中新出现的资产放到extra_products中
  4147. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4148. if (!empty($products) && $episode) {
  4149. // 获取剧集中的角色、场景和道具列表
  4150. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4151. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4152. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4153. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4154. // 构建角色名称列表
  4155. $role_names = array_column($roles, 'role');
  4156. // 构建场景名称列表
  4157. $scene_names = array_column($scenes, 'scene');
  4158. // 构建道具名称列表
  4159. $prop_names = array_column($props, 'prop');
  4160. // 遍历传入的products
  4161. foreach ($products as $product) {
  4162. $product_name = getProp($product, 'product_name');
  4163. // 如果product_name不在roles、scenes和props中
  4164. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4165. // 查找是否在extra_products中存在同名的
  4166. $found = false;
  4167. foreach ($extra_products as $key => $extra_product) {
  4168. if (getProp($extra_product, 'product_name') === $product_name) {
  4169. // 有同名的则覆盖
  4170. $extra_products[$key] = $product;
  4171. $found = true;
  4172. break;
  4173. }
  4174. }
  4175. // 没有则新增
  4176. if (!$found) {
  4177. $extra_products[] = $product;
  4178. }
  4179. }
  4180. }
  4181. if ($extra_products) {
  4182. // 保存到数据库
  4183. DB::table('mp_anime_episodes')
  4184. ->where('id', $episode_id)
  4185. ->update([
  4186. 'extra_products' => json_encode($extra_products, 256),
  4187. 'updated_at' => date('Y-m-d H:i:s')
  4188. ]);
  4189. }
  4190. }
  4191. // 获取分镜内容
  4192. $actContent = getProp($act, 'act_show_content', '');
  4193. // 音效同出(默认使用)
  4194. $current_generate_audio = $generate_audio ? 1 : 0;
  4195. // 构建完整的提示词
  4196. $processResult = $this->processActContentWithProducts($actContent, $products);
  4197. $fullPrompt = $processResult['content'];
  4198. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4199. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4200. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4201. // 处理视频模型
  4202. $model = getProp($data, 'model');
  4203. if (!$model) {
  4204. $model = getProp($episode, 'video_model');
  4205. if (!$model) {
  4206. // episode表也没有,使用默认值
  4207. $model = 'zhizhen-20';
  4208. }
  4209. }
  4210. // 验证模型是否在可用模型表中
  4211. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4212. $model = 'zhizhen-20';
  4213. }
  4214. // 保存到episode表
  4215. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4216. 'video_model' => $model,
  4217. 'updated_at' => date('Y-m-d H:i:s')
  4218. ]);
  4219. // 构建视频生成参数
  4220. $videoParams = [
  4221. 'model' => $model,
  4222. 'alias_act_id' => $act_id,
  4223. 'prompt' => trim($fullPrompt),
  4224. 'video_duration' => $videoDuration,
  4225. 'video_resolution' => $video_resolution,
  4226. 'seed' => -1,
  4227. 'ratio' => $ratio,
  4228. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4229. 'draft' => false,
  4230. 'watermark' => false,
  4231. 'camera_fixed' => false,
  4232. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4233. ];
  4234. // 如果分镜有图片,作为首帧
  4235. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4236. $hasVideo = !empty(getProp($act, 'video_url'));
  4237. if ($hasImage) {
  4238. if ($first_frame_url) {
  4239. $videoParams['first_frame_url'] = $first_frame_url;
  4240. }else {
  4241. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4242. }
  4243. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4244. }
  4245. // 构建content数组
  4246. $videoParams['content'] = [
  4247. [
  4248. 'type' => 'text',
  4249. 'text' => $videoParams['prompt'],
  4250. ]
  4251. ];
  4252. // 如果有首帧图片,添加到content中
  4253. if ($hasImage) {
  4254. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0'])) {
  4255. $videoParams['content'][] = [
  4256. 'type' => 'image_url',
  4257. 'image_url' => [
  4258. 'url' => $videoParams['first_frame_url'],
  4259. ],
  4260. 'role' => 'reference_image',
  4261. ];
  4262. if (isset($videoParams['tail_frame_url'])) {
  4263. $videoParams['content'][] = [
  4264. 'type' => 'image_url',
  4265. 'image_url' => [
  4266. 'url' => $videoParams['tail_frame_url'],
  4267. ],
  4268. 'role' => 'reference_image',
  4269. ];
  4270. }
  4271. }else {
  4272. $videoParams['content'][] = [
  4273. 'type' => 'image_url',
  4274. 'image_url' => [
  4275. 'url' => $videoParams['first_frame_url'],
  4276. ],
  4277. 'role' => 'first_frame',
  4278. ];
  4279. if (isset($videoParams['tail_frame_url'])) {
  4280. $videoParams['content'][] = [
  4281. 'type' => 'image_url',
  4282. 'image_url' => [
  4283. 'url' => $videoParams['tail_frame_url'],
  4284. ],
  4285. 'role' => 'last_frame',
  4286. ];
  4287. }
  4288. }
  4289. }
  4290. // dd($videoParams);
  4291. // 根据模型选择不同的视频生成方法
  4292. if (strpos($model, 'jimeng') !== false) {
  4293. // 即梦模型参数调整
  4294. unset($videoParams['content']); // 即梦不使用content格式
  4295. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4296. } elseif (strpos($model, 'kling') !== false) {
  4297. // Keling模型参数调整
  4298. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4299. unset($videoParams['ratio']);
  4300. unset($videoParams['content']); // Keling不使用content格式
  4301. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4302. } elseif (strpos($model, 'zhizhen') !== false) {
  4303. // 智帧20等新模型使用统一API
  4304. // 构建统一API参数
  4305. $unifiedParams = [
  4306. 'model_code' => $model,
  4307. 'alias_act_id' => $act_id,
  4308. 'prompt' => trim($fullPrompt),
  4309. 'video_duration' => $videoDuration,
  4310. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4311. 'video_ratio' => $ratio,
  4312. 'seed' => -1,
  4313. ];
  4314. // 构建parameters参数
  4315. $parameters = [
  4316. 'seconds' => $unifiedParams['video_duration'],
  4317. 'resolution' => $unifiedParams['video_resolution'],
  4318. 'ratio' => $ratio,
  4319. // 'video_mode' => 'multi_image',
  4320. // 'mode' => 'multi_image',
  4321. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4322. ];
  4323. $hasImage = false;
  4324. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4325. if ($hasImage) {
  4326. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4327. if (isset($videoParams['tail_frame_url'])) {
  4328. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4329. }
  4330. } else {
  4331. // 没有图片时,记录错误日志
  4332. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4333. 'act_id' => $act_id,
  4334. 'model' => $model
  4335. ]);
  4336. }
  4337. if ($reference_images) {
  4338. // 限制只传入9张参考图
  4339. $reference_images = array_slice($reference_images, 0, 9);
  4340. // 在处理之前先保存原始reference_images到任务参数中
  4341. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4342. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4343. $parameters['reference_images'] = $reference_images;
  4344. $parameters['video_mode'] = 'multi_image';
  4345. $parameters['mode'] = 'multi_image';
  4346. }
  4347. $unifiedParams['parameters'] = $parameters;
  4348. // 调用统一API创建任务
  4349. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4350. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4351. // 豆包Seedance 2.0(百度AI网关):图片需要先上传为素材
  4352. // 保存原始参考图用于任务记录
  4353. $videoParams['reference_images'] = $reference_images;
  4354. if ($reference_images) {
  4355. // 限制只传入9张参考图
  4356. $reference_images = array_slice($reference_images, 0, 9);
  4357. // 参考图上传为百度网关素材,上传失败时同步清理提示词中的<图片N>标记
  4358. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4359. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4360. $videoParams['prompt'] = trim($fullPrompt);
  4361. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4362. $videoParams['reference_image_assets'] = $reference_image_assets;
  4363. }
  4364. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4365. } else {
  4366. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4367. }
  4368. // 更新分镜表的视频任务信息
  4369. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4370. 'video_task_id' => $task->id,
  4371. 'video_task_status' => '生成中',
  4372. 'generate_audio' => $generate_audio,
  4373. 'updated_at' => date('Y-m-d H:i:s')
  4374. ]);
  4375. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4376. $episode_number = getProp($act, 'episode_number');
  4377. $act_number = getProp($act, 'act_number');
  4378. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4379. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4380. }
  4381. return [
  4382. 'task_id' => $task->id,
  4383. 'status' => $task->status,
  4384. 'act_id' => $act_id,
  4385. 'video_duration' => $videoDuration
  4386. ];
  4387. }
  4388. /**
  4389. * 文生视频通用方法
  4390. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4391. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4392. *
  4393. * @param array $data 请求参数
  4394. * @return array
  4395. */
  4396. public function generateVideo($data) {
  4397. $prompt = getProp($data, 'prompt');
  4398. if (empty($prompt)) {
  4399. Utils::throwError('20003:提示词不能为空');
  4400. }
  4401. $model = getProp($data, 'model');
  4402. if (!$model) {
  4403. $model = 'zhizhen-20';
  4404. }
  4405. // 验证模型是否在可用模型表中
  4406. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4407. Utils::throwError('20003:该模型已不可用,请更换!');
  4408. }
  4409. $video_duration = getProp($data, 'video_duration', 5);
  4410. $video_resolution = getProp($data, 'video_resolution', '480p');
  4411. $ratio = getProp($data, 'ratio', '9:16');
  4412. $generate_audio = getProp($data, 'generate_audio', 1);
  4413. $seed = getProp($data, 'seed', -1);
  4414. $first_frame_url = getProp($data, 'first_frame_url');
  4415. $tail_frame_url = getProp($data, 'tail_frame_url');
  4416. // 参考图(支持数组或JSON字符串,最多9张)
  4417. $reference_images = getProp($data, 'reference_images', []);
  4418. if (is_string($reference_images)) {
  4419. $reference_images = json_decode($reference_images, true) ?: [];
  4420. }
  4421. if (!is_array($reference_images)) {
  4422. Utils::throwError('20003:参考图格式不正确');
  4423. }
  4424. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4425. $reference_images = array_slice($reference_images, 0, 9);
  4426. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4427. $videoParams = [
  4428. 'model' => $model,
  4429. 'prompt' => $prompt,
  4430. 'video_duration' => $video_duration,
  4431. 'video_resolution' => $video_resolution,
  4432. 'seed' => $seed,
  4433. 'ratio' => $ratio,
  4434. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4435. 'draft' => getProp($data, 'draft', false),
  4436. 'watermark' => getProp($data, 'watermark', false),
  4437. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4438. ];
  4439. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4440. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4441. // 构建content数组
  4442. $videoParams['content'] = [
  4443. [
  4444. 'type' => 'text',
  4445. 'text' => $prompt,
  4446. ]
  4447. ];
  4448. // 根据模型选择不同的视频生成方法
  4449. if (strpos($model, 'jimeng') !== false) {
  4450. // 即梦模型参数调整
  4451. unset($videoParams['content']); // 即梦不使用content格式
  4452. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4453. } elseif (strpos($model, 'kling') !== false) {
  4454. // 可灵模型参数调整
  4455. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4456. unset($videoParams['ratio']);
  4457. unset($videoParams['content']); // 可灵不使用content格式
  4458. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4459. } elseif (strpos($model, 'zhizhen') !== false) {
  4460. // 智帧等新模型使用统一API
  4461. $unifiedParams = [
  4462. 'model_code' => $model,
  4463. 'prompt' => $prompt,
  4464. 'video_duration' => $video_duration,
  4465. 'video_resolution' => strtolower($video_resolution),
  4466. 'video_ratio' => $ratio,
  4467. 'seed' => $seed,
  4468. ];
  4469. // 构建parameters参数
  4470. $parameters = [
  4471. 'seconds' => $unifiedParams['video_duration'],
  4472. 'resolution' => $unifiedParams['video_resolution'],
  4473. 'ratio' => $ratio,
  4474. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4475. ];
  4476. // 首帧和尾帧
  4477. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4478. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4479. // 参考图处理
  4480. if ($reference_images) {
  4481. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4482. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4483. $parameters['reference_images'] = $reference_images;
  4484. $parameters['video_mode'] = 'multi_image';
  4485. $parameters['mode'] = 'multi_image';
  4486. }
  4487. $unifiedParams['parameters'] = $parameters;
  4488. // 调用统一API创建任务
  4489. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4490. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4491. // 豆包Seedance 2.0(百度AI网关):图片需要先上传为素材
  4492. $videoParams['reference_images'] = $reference_images;
  4493. if ($reference_images) {
  4494. // 参考图上传为百度网关素材
  4495. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']);
  4496. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4497. $videoParams['reference_image_assets'] = $reference_image_assets;
  4498. }
  4499. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4500. } else {
  4501. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4502. }
  4503. return [
  4504. 'task_id' => $task->id,
  4505. 'status' => $task->status,
  4506. 'model' => $model,
  4507. 'video_duration' => $video_duration,
  4508. 'video_resolution' => $video_resolution,
  4509. 'ratio' => $ratio
  4510. ];
  4511. }
  4512. /**
  4513. * 根据提示词内容智能计算最优视频时长
  4514. *
  4515. * @param string $segmentContent 分镜内容
  4516. * @param string $tailFrame 尾帧描述
  4517. * @return int 视频时长(2-12秒)
  4518. */
  4519. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4520. // 合并所有文本内容
  4521. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4522. // 如果没有内容,返回默认时长
  4523. if (empty($fullText)) {
  4524. return 5;
  4525. }
  4526. // 计算文本长度(中文字符按2个字符计算)
  4527. $textLength = mb_strlen($fullText, 'UTF-8');
  4528. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4529. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4530. // 分析内容复杂度
  4531. $complexityScore = $this->analyzeContentComplexity($fullText);
  4532. // 基础时长计算(根据文本长度)
  4533. $baseDuration = 3; // 默认2秒
  4534. // if ($adjustedLength <= 20) {
  4535. // $baseDuration = 3;
  4536. // } elseif ($adjustedLength <= 40) {
  4537. // $baseDuration = 4;
  4538. // } elseif ($adjustedLength <= 60) {
  4539. // $baseDuration = 5;
  4540. // } elseif ($adjustedLength <= 80) {
  4541. // $baseDuration = 6;
  4542. // } elseif ($adjustedLength <= 100) {
  4543. // $baseDuration = 7;
  4544. // } elseif ($adjustedLength <= 120) {
  4545. // $baseDuration = 8;
  4546. // } else {
  4547. // $baseDuration = 9;
  4548. // }
  4549. // 根据内容复杂度调整时长
  4550. $finalDuration = $baseDuration + $complexityScore;
  4551. // 确保时长在2-12秒范围内
  4552. return max(4, min(12, $finalDuration));
  4553. }
  4554. /**
  4555. * 分析内容复杂度,返回时长调整值
  4556. *
  4557. * @param string $text 文本内容
  4558. * @return int 调整值(-2到+3)
  4559. */
  4560. private function analyzeContentComplexity($text) {
  4561. $score = 0;
  4562. // 动作关键词(需要更长时间展现)
  4563. $actionKeywords = [
  4564. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4565. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4566. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4567. ];
  4568. // 静态关键词(可以用较短时间)
  4569. $staticKeywords = [
  4570. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4571. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4572. ];
  4573. // 复杂场景关键词(需要更长时间)
  4574. $complexSceneKeywords = [
  4575. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4576. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4577. ];
  4578. // 情感关键词(需要适中时间表现)
  4579. $emotionKeywords = [
  4580. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4581. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4582. ];
  4583. // 检查动作关键词
  4584. foreach ($actionKeywords as $keyword) {
  4585. if (strpos($text, $keyword) !== false) {
  4586. $score += 1;
  4587. break; // 避免重复加分
  4588. }
  4589. }
  4590. // 检查静态关键词
  4591. foreach ($staticKeywords as $keyword) {
  4592. if (strpos($text, $keyword) !== false) {
  4593. $score -= 1;
  4594. break;
  4595. }
  4596. }
  4597. // 检查复杂场景关键词
  4598. foreach ($complexSceneKeywords as $keyword) {
  4599. if (strpos($text, $keyword) !== false) {
  4600. $score += 1;
  4601. break;
  4602. }
  4603. }
  4604. // 检查情感关键词
  4605. foreach ($emotionKeywords as $keyword) {
  4606. if (strpos($text, $keyword) !== false) {
  4607. $score += 1;
  4608. break;
  4609. }
  4610. }
  4611. // 检查时间相关词汇
  4612. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4613. $score += 1;
  4614. }
  4615. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4616. $score -= 1;
  4617. }
  4618. // 检查转场词汇
  4619. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4620. $score += 1;
  4621. }
  4622. // 检查环境描述(复杂环境需要更多时间)
  4623. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4624. $score += 1;
  4625. }
  4626. // 检查对话内容(对话需要更多时间)
  4627. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4628. $score += 1;
  4629. }
  4630. // 限制调整范围
  4631. return max(-1, min(4, $score));
  4632. }
  4633. /**
  4634. * 创建完整视频合成任务
  4635. *
  4636. * @param array $data
  4637. * @return array
  4638. */
  4639. public function createCompleteVideoTask($data)
  4640. {
  4641. $animeId = getProp($data, 'anime_id');
  4642. $episodeId = getProp($data, 'episode_id');
  4643. // 验证参数
  4644. if (!$animeId || !$episodeId) {
  4645. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4646. }
  4647. // 检查是否已存在处理中的任务
  4648. $existingTask = DB::table('mp_complete_video_tasks')
  4649. ->where('anime_id', $animeId)
  4650. ->where('episode_id', $episodeId)
  4651. ->whereIn('generate_status', ['执行中'])
  4652. ->first();
  4653. if ($existingTask) {
  4654. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4655. }
  4656. // 获取全能模式状态
  4657. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4658. if ((int)$ace_mode === 1) {
  4659. // 获取所有片段的配音视频,按 act_number 排序
  4660. $segments = DB::table('mp_episode_segments')
  4661. ->where('anime_id', $animeId)
  4662. ->where('episode_id', $episodeId)
  4663. ->orderBy('segment_number')
  4664. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4665. ->get();
  4666. // 检查是否所有片段都有视频
  4667. $missingVideos = $segments->filter(function($segment) {
  4668. return empty($segment->video_url);
  4669. });
  4670. if ($missingVideos->isNotEmpty()) {
  4671. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4672. }
  4673. }else {
  4674. // 获取所有分镜的配音视频,按 segment_number 排序
  4675. $segments = DB::table('mp_episode_segments')
  4676. ->where('anime_id', $animeId)
  4677. ->where('episode_id', $episodeId)
  4678. ->orderBy('segment_number')
  4679. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4680. ->get();
  4681. // 检查是否所有分镜都有配音和视频
  4682. $missingVideos = $segments->filter(function($segment) {
  4683. return empty($segment->audio_url) || empty($segment->video_url);
  4684. });
  4685. if ($missingVideos->isNotEmpty()) {
  4686. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4687. }
  4688. }
  4689. if ($segments->isEmpty()) {
  4690. Utils::throwError('20003:未找到该剧集的分镜数据');
  4691. }
  4692. // 获取当前完整视频url
  4693. $completeVideoUrl = DB::table('mp_anime_episodes')
  4694. ->where('anime_id', $animeId)
  4695. ->where('id', $episodeId)
  4696. ->value('complete_video_url');
  4697. // 构建 generate_json
  4698. $generateJson = [];
  4699. $sequence = 1;
  4700. foreach ($segments as $segment) {
  4701. if ((int)$ace_mode === 1) {
  4702. $generateJson[] = [
  4703. 'sequence' => $sequence++,
  4704. 'video_url' => $segment->video_url,
  4705. 'video_time_point_start' => $segment->video_time_point_start,
  4706. 'video_time_point_end' => $segment->video_time_point_end
  4707. ];
  4708. }else {
  4709. $generateJson[] = [
  4710. 'sequence' => $sequence++,
  4711. 'video_url' => $segment->video_url,
  4712. 'audio_url' => $segment->audio_url,
  4713. 'video_time_point_start' => $segment->video_time_point_start,
  4714. 'video_time_point_end' => $segment->video_time_point_end
  4715. ];
  4716. }
  4717. }
  4718. // 创建任务
  4719. $now = date('Y-m-d H:i:s');
  4720. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4721. 'anime_id' => $animeId,
  4722. 'episode_id' => $episodeId,
  4723. 'generate_json' => json_encode($generateJson, 256),
  4724. 'generate_status' => '执行中',
  4725. 'complete_video_url' => '',
  4726. 'created_at' => $now,
  4727. 'updated_at' => $now
  4728. ]);
  4729. if (!$taskId) {
  4730. Utils::throwError('20003:创建任务失败');
  4731. }
  4732. // 更新剧集表的任务ID和状态
  4733. $boolen = DB::table('mp_anime_episodes')
  4734. ->where('anime_id', $animeId)
  4735. ->where('id', $episodeId)
  4736. ->update([
  4737. 'complete_video_task_id' => $taskId,
  4738. 'complete_video_task_status' => '执行中',
  4739. 'updated_at' => $now
  4740. ]);
  4741. if (!$boolen) {
  4742. Utils::throwError('20003:更新剧集表失败');
  4743. }
  4744. dLog('anime')->info('创建完整视频合成任务', [
  4745. 'task_id' => $taskId,
  4746. 'anime_id' => $animeId,
  4747. 'episode_id' => $episodeId,
  4748. 'segment_count' => count($generateJson)
  4749. ]);
  4750. // 请求远程服务器执行生成
  4751. $client = new Client(['timeout' => 600, 'verify' => false]);
  4752. try {
  4753. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4754. $response = $result->getBody()->getContents();
  4755. $response_arr = json_decode($response, true);
  4756. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4757. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4758. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4759. // // 更新任务状态为失败
  4760. // DB::table('mp_complete_video_tasks')
  4761. // ->where('id', $taskId)
  4762. // ->update([
  4763. // 'generate_status' => '执行失败',
  4764. // 'error_message' => $error_msg,
  4765. // 'updated_at' => date('Y-m-d H:i:s')
  4766. // ]);
  4767. // // 同步更新剧集表状态
  4768. // DB::table('mp_anime_episodes')
  4769. // ->where('complete_video_task_id', $taskId)
  4770. // ->update([
  4771. // 'complete_video_task_status' => '执行失败',
  4772. // 'updated_at' => date('Y-m-d H:i:s')
  4773. // ]);
  4774. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4775. }
  4776. } catch (\Exception $e) {
  4777. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4778. // 更新任务状态为失败
  4779. DB::table('mp_complete_video_tasks')
  4780. ->where('id', $taskId)
  4781. ->update([
  4782. 'generate_status' => '执行失败',
  4783. 'error_message' => $e->getMessage(),
  4784. 'updated_at' => date('Y-m-d H:i:s')
  4785. ]);
  4786. // 同步更新剧集表状态
  4787. DB::table('mp_anime_episodes')
  4788. ->where('complete_video_task_id', $taskId)
  4789. ->update([
  4790. 'complete_video_task_status' => '执行失败',
  4791. 'updated_at' => date('Y-m-d H:i:s')
  4792. ]);
  4793. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4794. }
  4795. // 开始轮询任务状态
  4796. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4797. $pollInterval = 5; // 每5秒轮询一次
  4798. $attempt = 0;
  4799. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4800. while ($attempt < $maxAttempts) {
  4801. sleep($pollInterval);
  4802. $attempt++;
  4803. // 查询任务状态
  4804. $task = DB::table('mp_complete_video_tasks')
  4805. ->where('id', $taskId)
  4806. ->first();
  4807. if (!$task) {
  4808. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4809. Utils::throwError('20003:任务不存在');
  4810. }
  4811. dLog('anime')->info('轮询任务状态', [
  4812. 'task_id' => $taskId,
  4813. 'attempt' => $attempt,
  4814. 'status' => $task->generate_status
  4815. ]);
  4816. // 检查任务是否完成
  4817. if ($task->generate_status === '执行成功') {
  4818. // 同步更新剧集表状态
  4819. $boolen3 = DB::table('mp_anime_episodes')
  4820. ->where('anime_id', $animeId)
  4821. ->where('id', $episodeId)
  4822. ->update([
  4823. 'complete_video_url' => $task->complete_video_url,
  4824. 'complete_video_task_status' => '执行成功',
  4825. 'updated_at' => date('Y-m-d H:i:s')
  4826. ]);
  4827. dLog('anime')->info('视频合成任务完成', [
  4828. 'task_id' => $taskId,
  4829. 'video_url' => $task->complete_video_url,
  4830. 'attempts' => $attempt
  4831. ]);
  4832. // 如果更新成功则远程删除之前的文件
  4833. if ($boolen3 && $completeVideoUrl) {
  4834. $encode_url = urlencode($completeVideoUrl);
  4835. $client = new Client(['timeout' => 300, 'verify' => false]);
  4836. // 根据ID通过API通知合成音频
  4837. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4838. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4839. $response = $result->getBody()->getContents();
  4840. $response_arr = json_decode($response, true);
  4841. Log::info('火山删除音频返回: '.$response);
  4842. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4843. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4844. Log::info('火山删除音频失败: '.$error_msg);
  4845. // Utils::throwError('20003:火山删除音频失败');
  4846. }
  4847. }
  4848. return [
  4849. 'task_id' => $taskId,
  4850. 'anime_id' => $animeId,
  4851. 'episode_id' => $episodeId,
  4852. 'segment_count' => count($generateJson),
  4853. 'generate_status' => '执行成功',
  4854. 'complete_video_url' => $task->complete_video_url,
  4855. ];
  4856. }
  4857. // 检查任务是否失败
  4858. if ($task->generate_status === '执行失败') {
  4859. // 同步更新剧集表状态
  4860. DB::table('mp_anime_episodes')
  4861. ->where('anime_id', $animeId)
  4862. ->where('id', $episodeId)
  4863. ->update([
  4864. 'complete_video_task_status' => '执行失败',
  4865. 'updated_at' => date('Y-m-d H:i:s')
  4866. ]);
  4867. $errorMessage = $task->error_message ?? '未知错误';
  4868. dLog('anime')->error('视频合成任务失败', [
  4869. 'task_id' => $taskId,
  4870. 'error' => $errorMessage,
  4871. 'attempts' => $attempt
  4872. ]);
  4873. return [
  4874. 'task_id' => $taskId,
  4875. 'anime_id' => $animeId,
  4876. 'episode_id' => $episodeId,
  4877. 'segment_count' => count($generateJson),
  4878. 'generate_status' => '执行失败',
  4879. 'error_message' => $errorMessage
  4880. ];
  4881. }
  4882. }
  4883. // 超时处理
  4884. dLog('anime')->warning('视频合成任务超时', [
  4885. 'task_id' => $taskId,
  4886. 'max_attempts' => $maxAttempts,
  4887. 'timeout_seconds' => $maxAttempts * $pollInterval
  4888. ]);
  4889. // 更新任务状态为超时
  4890. DB::table('mp_complete_video_tasks')
  4891. ->where('id', $taskId)
  4892. ->update([
  4893. 'generate_status' => '超时',
  4894. 'error_message' => '任务执行超时(5分钟)',
  4895. 'updated_at' => date('Y-m-d H:i:s')
  4896. ]);
  4897. return [
  4898. 'task_id' => $taskId,
  4899. 'anime_id' => $animeId,
  4900. 'episode_id' => $episodeId,
  4901. 'segment_count' => count($generateJson),
  4902. 'generate_status' => '超时',
  4903. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4904. ];
  4905. }
  4906. /**
  4907. * 根据 inner_prompt_type 附加内置提示词
  4908. *
  4909. * @param string $prompt 用户提示词
  4910. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  4911. * @return string 合并后的提示词
  4912. */
  4913. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  4914. {
  4915. $innerPromptMap = [
  4916. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  4917. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  4918. ];
  4919. if (!isset($innerPromptMap[$innerPromptType])) {
  4920. return $prompt;
  4921. }
  4922. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  4923. }
  4924. /**
  4925. * 根据 inner_prompt_type 获取生成图片数量
  4926. *
  4927. * @param int $innerPromptType 内置提示词类型
  4928. * @return int 图片数量
  4929. */
  4930. public static function getInnerImageNum($innerPromptType = 0)
  4931. {
  4932. return (int)$innerPromptType === 2 ? 9 : 1;
  4933. }
  4934. /**
  4935. * 提取图片生成结果URL
  4936. *
  4937. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  4938. * @param int $innerPromptType 内置提示词类型
  4939. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  4940. */
  4941. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  4942. {
  4943. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  4944. if (is_array($resultUrls) && !empty($resultUrls)) {
  4945. $resultUrls = array_values($resultUrls);
  4946. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  4947. }
  4948. if (!empty($resultUrl)) {
  4949. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  4950. }
  4951. return (int)$innerPromptType === 2 ? [] : '';
  4952. }
  4953. public function generateImg($data) {
  4954. $prompt = getProp($data, 'prompt');
  4955. $episode_id = getProp($data, 'episode_id');
  4956. $ref_img_urls = getProp($data, 'ref_img_urls');
  4957. $ratio = getProp($data, 'ratio', '9:16');
  4958. $resolution = getProp($data, 'resolution', '2k');
  4959. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  4960. // 定义分辨率和宽高比对应的尺寸映射表
  4961. $sizeMap = [
  4962. '2k' => [
  4963. '1:1' => ['width' => 2048, 'height' => 2048],
  4964. '4:3' => ['width' => 2304, 'height' => 1728],
  4965. '3:4' => ['width' => 1728, 'height' => 2304],
  4966. '16:9' => ['width' => 2848, 'height' => 1600],
  4967. '9:16' => ['width' => 1600, 'height' => 2848],
  4968. '3:2' => ['width' => 2496, 'height' => 1664],
  4969. '2:3' => ['width' => 1664, 'height' => 2496],
  4970. '21:9' => ['width' => 3136, 'height' => 1344],
  4971. ],
  4972. '3k' => [
  4973. '1:1' => ['width' => 3072, 'height' => 3072],
  4974. '4:3' => ['width' => 3456, 'height' => 2592],
  4975. '3:4' => ['width' => 2592, 'height' => 3456],
  4976. '16:9' => ['width' => 4096, 'height' => 2304],
  4977. '9:16' => ['width' => 2304, 'height' => 4096],
  4978. '2:3' => ['width' => 2496, 'height' => 3744],
  4979. '3:2' => ['width' => 3744, 'height' => 2496],
  4980. '21:9' => ['width' => 4704, 'height' => 2016],
  4981. ],
  4982. '4k' => [
  4983. '1:1' => ['width' => 4096, 'height' => 4096],
  4984. '3:4' => ['width' => 3520, 'height' => 4704],
  4985. '4:3' => ['width' => 4704, 'height' => 3520],
  4986. '16:9' => ['width' => 5504, 'height' => 3040],
  4987. '9:16' => ['width' => 3040, 'height' => 5504],
  4988. '2:3' => ['width' => 3328, 'height' => 4992],
  4989. '3:2' => ['width' => 4992, 'height' => 3328],
  4990. '21:9' => ['width' => 6240, 'height' => 2656],
  4991. ],
  4992. ];
  4993. // 参数验证
  4994. $resolution = strtolower($resolution);
  4995. if (!isset($sizeMap[$resolution])) {
  4996. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  4997. }
  4998. if (!isset($sizeMap[$resolution][$ratio])) {
  4999. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5000. }
  5001. // 根据 ratio 和 resolution 确定宽高
  5002. $width = $sizeMap[$resolution][$ratio]['width'];
  5003. $height = $sizeMap[$resolution][$ratio]['height'];
  5004. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5005. if (is_json($ref_img_urls)) {
  5006. $ref_img_urls = json_decode($ref_img_urls, true);
  5007. }else {
  5008. $ref_img_urls = explode(',', $ref_img_urls);
  5009. }
  5010. }
  5011. // 处理图片模型
  5012. $model = getProp($data, 'model');
  5013. if (!$model) {
  5014. // 用户没有输入,从episode表获取
  5015. if ($episode_id) {
  5016. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5017. $model = getProp($episode, 'image_model');
  5018. }
  5019. if (!$model) {
  5020. // episode表也没有,使用默认值
  5021. $model = 'doubao-seedream-5-0-lite-260128';
  5022. }
  5023. }
  5024. // 验证模型是否在可用模型表中
  5025. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5026. // $model = 'doubao-seedream-5-0-lite-260128';
  5027. Utils::throwError('20003:该模型已不可用,请更换!');
  5028. }
  5029. // 保存到episode表
  5030. if ($episode_id) {
  5031. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5032. 'image_model' => $model,
  5033. 'updated_at' => date('Y-m-d H:i:s')
  5034. ]);
  5035. }
  5036. // 参数验证
  5037. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5038. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5039. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5040. $imageNum = self::getInnerImageNum($inner_prompt_type);
  5041. try {
  5042. // 创建图片生成任务
  5043. $params = [
  5044. 'prompt' => $prompt,
  5045. 'model' => $model,
  5046. 'ref_img_urls' => '',
  5047. 'width' => $width,
  5048. 'height' => $height,
  5049. 'image_num' => $imageNum
  5050. ];
  5051. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5052. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5053. $task_id = $task->id;
  5054. if (!$task_id) {
  5055. Utils::throwError('20003:创建图片生成任务失败');
  5056. }
  5057. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5058. $model = getProp($task, 'model');
  5059. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5060. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5061. $isSyncModel = $isVolcModel || $isGptModel;
  5062. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5063. $start_time = time();
  5064. $timeout = 300; // 5分钟
  5065. $img_url = '';
  5066. while (time() - $start_time < $timeout) {
  5067. sleep(3);
  5068. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5069. if ($isSyncModel) {
  5070. // 刷新任务状态
  5071. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5072. if ($task->status === 'success' && $task->result_url) {
  5073. $img_url = self::extractResultUrls($task->result_url, $inner_prompt_type);
  5074. break;
  5075. } elseif ($task->status === 'failed') {
  5076. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5077. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5078. }
  5079. // // 如果还在处理中,提示用户稍后查看
  5080. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5081. }else {
  5082. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5083. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5084. if ($statusInfo['status'] === 'success') {
  5085. $task->updateStatus('success', [
  5086. 'result_url' => $statusInfo['result_url'],
  5087. 'result_json' => $statusInfo['result_json'] ?? []
  5088. ]);
  5089. $img_url = self::extractResultUrls($statusInfo['result_url'], $inner_prompt_type);
  5090. break;
  5091. } elseif ($statusInfo['status'] === 'failed') {
  5092. $task->updateStatus('failed', [
  5093. 'error_message' => $statusInfo['error_message'],
  5094. 'result_json' => $statusInfo['result_json'] ?? []
  5095. ]);
  5096. dLog('anime')->error('图片生成失败,', [
  5097. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5098. ]);
  5099. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5100. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5101. }
  5102. }
  5103. }
  5104. if (empty($img_url)) {
  5105. Utils::throwError('20003:图片生成超时,请稍后重试');
  5106. }
  5107. return $img_url;
  5108. } catch (\Exception $e) {
  5109. dLog('anime')->error('更新角色或场景失败', [
  5110. 'error' => $e->getMessage()
  5111. ]);
  5112. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5113. Utils::throwError('20003:' . $e->getMessage());
  5114. }
  5115. }
  5116. /**
  5117. * 使用文生文模型解析分镜内容
  5118. */
  5119. private function parseSegmentContentWithAI($segment_content) {
  5120. try {
  5121. // 使用DeepSeek服务的公开方法解析分镜内容
  5122. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5123. } catch (\Exception $e) {
  5124. // 如果AI解析失败,记录日志并返回原内容
  5125. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5126. return $segment_content;
  5127. }
  5128. }
  5129. /**
  5130. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5131. *
  5132. * @param int $episode_id 分集ID
  5133. * @param int $anime_id 动漫ID
  5134. * @param array $roles 分集角色数组(引用传递)
  5135. * @param array $scenes 分集场景数组(引用传递)
  5136. * @param array $episode 分集数据
  5137. */
  5138. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5139. // 获取全局动漫的角色和场景数据
  5140. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5141. if (!$anime) return;
  5142. $art_style_type = getProp($anime, 'art_style_type');
  5143. $character_prefix = '';
  5144. $scene_prefix = '';
  5145. if ($art_style_type) {
  5146. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5147. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5148. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5149. }
  5150. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5151. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5152. $roles_updated = false;
  5153. $scenes_updated = false;
  5154. // 处理角色
  5155. foreach ($roles as &$role) {
  5156. $role_name = getProp($role, 'role');
  5157. $role_description = getProp($role, 'description');
  5158. $role_pic_prompt = getProp($role, 'pic_prompt');
  5159. $role_url = getProp($role, 'url');
  5160. $role_task_id = getProp($role, 'task_id');
  5161. // 如果已有URL或已有任务ID,跳过
  5162. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5163. continue;
  5164. }
  5165. $url_inherited = false;
  5166. // 尝试从全局数据中继承
  5167. foreach ($global_roles as $global_role) {
  5168. $global_role_name = getProp($global_role, 'role');
  5169. $global_role_description = getProp($global_role, 'description');
  5170. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5171. $global_role_url = getProp($global_role, 'url');
  5172. $global_role_task_id = getProp($global_role, 'task_id');
  5173. $global_role_task_status = getProp($global_role, 'task_status');
  5174. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5175. if ($role_name === $global_role_name
  5176. && $role_description === $global_role_description
  5177. && $role_pic_prompt === $global_role_pic_prompt
  5178. && !empty($global_role_url)) {
  5179. // 继承 task_id、task_status 和 url
  5180. $role['task_id'] = $global_role_task_id;
  5181. $role['task_status'] = $global_role_task_status;
  5182. $role['url'] = $global_role_url;
  5183. $roles_updated = true;
  5184. $url_inherited = true;
  5185. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5186. break;
  5187. }
  5188. }
  5189. // 如果无法继承且没有任务ID,创建新任务
  5190. if (!$url_inherited && empty($role_task_id)) {
  5191. try {
  5192. $art_style = getProp($episode, 'art_style');
  5193. // 优先使用 pic_prompt,如果没有则使用 description
  5194. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5195. // if ($art_style) {
  5196. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5197. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5198. // }
  5199. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5200. $params = [
  5201. 'prompt' => $description,
  5202. 'ref_img_urls' => []
  5203. ];
  5204. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5205. $task_id = $task->id;
  5206. if ($task_id) {
  5207. $role['task_id'] = $task_id;
  5208. $role['task_status'] = 'processing';
  5209. $roles_updated = true;
  5210. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5211. }
  5212. } catch (\Exception $e) {
  5213. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5214. }
  5215. }
  5216. }
  5217. // 处理场景
  5218. foreach ($scenes as &$scene) {
  5219. $scene_name = getProp($scene, 'scene');
  5220. $scene_description = getProp($scene, 'description');
  5221. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5222. $scene_url = getProp($scene, 'url');
  5223. $scene_task_id = getProp($scene, 'task_id');
  5224. // 如果已有URL或已有任务ID,跳过
  5225. if (!empty($scene_url) || !empty($scene_task_id)) {
  5226. continue;
  5227. }
  5228. $url_inherited = false;
  5229. // 尝试从全局数据中继承
  5230. foreach ($global_scenes as $global_scene) {
  5231. $global_scene_name = getProp($global_scene, 'scene');
  5232. $global_scene_description = getProp($global_scene, 'description');
  5233. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5234. $global_scene_url = getProp($global_scene, 'url');
  5235. $global_scene_task_id = getProp($global_scene, 'task_id');
  5236. $global_scene_task_status = getProp($global_scene, 'task_status');
  5237. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5238. if ($scene_name === $global_scene_name
  5239. && $scene_description === $global_scene_description
  5240. && $scene_pic_prompt === $global_scene_pic_prompt
  5241. && !empty($global_scene_url)) {
  5242. // 继承 task_id、task_status 和 url
  5243. $scene['task_id'] = $global_scene_task_id;
  5244. $scene['task_status'] = $global_scene_task_status;
  5245. $scene['url'] = $global_scene_url;
  5246. $scenes_updated = true;
  5247. $url_inherited = true;
  5248. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5249. break;
  5250. }
  5251. }
  5252. // 如果无法继承且没有任务ID,创建新任务
  5253. if (!$url_inherited && empty($scene_task_id)) {
  5254. try {
  5255. $art_style = getProp($episode, 'art_style');
  5256. // 优先使用 pic_prompt,如果没有则使用 description
  5257. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5258. // if ($art_style) {
  5259. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5260. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5261. // }
  5262. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5263. $params = [
  5264. 'prompt' => $description,
  5265. 'ref_img_urls' => []
  5266. ];
  5267. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5268. $task_id = $task->id;
  5269. if ($task_id) {
  5270. $scene['task_id'] = $task_id;
  5271. $scene['task_status'] = 'processing';
  5272. $scenes_updated = true;
  5273. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5274. }
  5275. } catch (\Exception $e) {
  5276. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5277. }
  5278. }
  5279. }
  5280. // 如果有更新,保存到数据库
  5281. if ($roles_updated || $scenes_updated) {
  5282. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5283. if ($roles_updated) {
  5284. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5285. }
  5286. if ($scenes_updated) {
  5287. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5288. }
  5289. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5290. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5291. }
  5292. }
  5293. /**
  5294. * 根据图片URL使用AI反推图片提示词
  5295. *
  5296. * @param string $img_url 图片URL
  5297. * @return string 反推的提示词
  5298. */
  5299. private function generateImagePromptFromUrl($img_url) {
  5300. try {
  5301. // 获取默认模型
  5302. $model = 'doubao-seed-2-0-mini-260215';
  5303. // 构建messages参数
  5304. $messages = [
  5305. [
  5306. 'role' => 'user',
  5307. 'content' => [
  5308. [
  5309. 'type' => 'text',
  5310. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5311. ],
  5312. [
  5313. 'type' => 'image_url',
  5314. 'image_url' => [
  5315. 'url' => $img_url
  5316. ]
  5317. ]
  5318. ]
  5319. ]
  5320. ];
  5321. // 构建请求参数
  5322. $params = [
  5323. 'model' => $model,
  5324. 'messages' => $messages,
  5325. 'stream' => false,
  5326. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5327. ];
  5328. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5329. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5330. // 返回生成的内容
  5331. return getProp($result, 'fullContent', '图片描述生成失败');
  5332. } catch (\Exception $e) {
  5333. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5334. 'img_url' => $img_url
  5335. ]);
  5336. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5337. 'error' => $e->getMessage(),
  5338. 'img_url' => $img_url
  5339. ]);
  5340. return '图片描述生成失败: ' . $e->getMessage();
  5341. }
  5342. }
  5343. /**
  5344. * 音频试听接口
  5345. * 创建音频任务并轮询获取结果
  5346. *
  5347. * @param array $data 参数数组
  5348. * @return array 返回音频URL或错误信息
  5349. */
  5350. public function previewAudio($data) {
  5351. $dialogue = getProp($data, 'dialogue');
  5352. // 必填参数验证
  5353. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5354. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5355. $voice_type = getProp($data, 'voice_type');
  5356. $voice_name = getProp($data, 'voice_name');
  5357. $voice_actor = getProp($data, 'voice_actor');
  5358. $emotion_type = getProp($data, 'emotion_type');
  5359. $gender = getProp($data, 'gender', 0);
  5360. $emotion = getProp($data, 'emotion');
  5361. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5362. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5363. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5364. $pitch = getProp($data, 'pitch', 0);
  5365. try {
  5366. $now = date('Y-m-d H:i:s');
  5367. // 构建生成参数
  5368. $generate_json = json_encode([
  5369. 'text' => $dialogue,
  5370. 'role' => $voice_actor,
  5371. 'voice_type' => $voice_type,
  5372. 'voice_name' => $voice_name,
  5373. 'emotion' => $emotion,
  5374. 'emotion_type' => $emotion_type,
  5375. 'gender' => $gender,
  5376. 'speed_ratio' => $speed_ratio,
  5377. 'loudness_ratio' => $loudness_ratio,
  5378. 'emotion_scale' => $emotion_scale,
  5379. 'pitch' => $pitch,
  5380. ], 256);
  5381. // 请求远程服务器执行生成
  5382. $client = new Client(['timeout' => 600, 'verify' => false]);
  5383. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5384. $response = $result->getBody()->getContents();
  5385. $response_arr = json_decode($response, true);
  5386. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5387. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5388. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5389. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5390. }
  5391. $arr = $response_arr['data'];
  5392. $subtitle_info = $arr['subtitle_info'];
  5393. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5394. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5395. return [
  5396. 'audio_url' => $arr['url'],
  5397. 'subtitle_info' => $subtitle_info,
  5398. 'audio_duration' => round($audio_duration, 2)
  5399. ];
  5400. } catch (\Exception $e) {
  5401. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5402. Utils::throwError('20003:' . $e->getMessage());
  5403. }
  5404. }
  5405. /**
  5406. * 获取角色库列表(支持文件夹递归查询)
  5407. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5408. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5409. */
  5410. public function globalProducts($data) {
  5411. $uid = Site::getUid();
  5412. $cpid = Site::getCpid();
  5413. $role = Site::getRole();
  5414. $id = getProp($data, 'id', 0);
  5415. $parent_id = getProp($data, 'parent_id', 0);
  5416. $product_name = getProp($data, 'product_name');
  5417. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5418. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5419. if (!$product) {
  5420. Utils::throwError('20003:请选择产品类型');
  5421. }
  5422. // 根据角色和is_public参数确定查询范围
  5423. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5424. // user角色:根据is_public参数筛选
  5425. $query_user_ids = [];
  5426. if ($role === 'admin') {
  5427. // admin获取所有个人库和公共库
  5428. $query_user_ids = [$uid, 0];
  5429. } else {
  5430. // user角色根据is_public参数筛选
  5431. if ($is_public == 2) {
  5432. // 个人库+公共库
  5433. $query_user_ids = [$uid, 0];
  5434. } elseif ($is_public == 0) {
  5435. // 仅个人库
  5436. $query_user_ids = [$uid];
  5437. } elseif ($is_public == 1) {
  5438. // 仅公共库
  5439. $query_user_ids = [0];
  5440. }
  5441. }
  5442. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5443. if ($id || $product_name) {
  5444. $query = DB::table('mp_products')
  5445. ->where('cpid', $cpid)
  5446. ->whereIn('user_id', $query_user_ids)
  5447. ->where('is_deleted', 0);
  5448. // 如果指定了 id,按 id 精确查询
  5449. if ($id) {
  5450. $query->where('id', $id);
  5451. }
  5452. // 如果指定了 product_name,按名称模糊查询
  5453. if ($product_name) {
  5454. $query->where('product_name', 'like', "%{$product_name}%");
  5455. }
  5456. // 如果指定了 product,添加筛选条件
  5457. if ($product) {
  5458. $query->where('product', $product);
  5459. }
  5460. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5461. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5462. ->get()
  5463. ->map(function($value) {
  5464. $value = (array)$value;
  5465. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5466. $value['type'] = (int)$value['type'];
  5467. $value['parent_id'] = (int)$value['parent_id'];
  5468. $value['level'] = (int)$value['level'];
  5469. $value['product'] = (int)($value['product'] ?? 1);
  5470. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5471. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5472. unset($value['user_id']);
  5473. return $value;
  5474. })
  5475. ->toArray();
  5476. return $result;
  5477. }
  5478. // 递归获取所有子目录和角色
  5479. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5480. }
  5481. /**
  5482. * 递归获取指定目录下的所有子目录和角色
  5483. * @param int $cpid 公司ID
  5484. * @param int $parent_id 父目录ID
  5485. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5486. * @param array $query_user_ids 用户ID数组(支持多个)
  5487. * @param int $current_uid 当前用户ID(用于排序)
  5488. * @return array
  5489. */
  5490. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5491. // 查询当前层级的所有项(文件夹和角色)
  5492. $query = DB::table('mp_products')
  5493. ->where('cpid', $cpid)
  5494. ->where('is_deleted', 0)
  5495. ->where('parent_id', $parent_id);
  5496. // 添加用户ID验证(支持多个user_id)
  5497. if (!empty($query_user_ids)) {
  5498. $query->whereIn('user_id', $query_user_ids);
  5499. }
  5500. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5501. if ($product) {
  5502. $query->where('product', $product);
  5503. }
  5504. // 排序规则:
  5505. // 1. 文件夹在前(type DESC)
  5506. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5507. // 3. 其他排序规则
  5508. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5509. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5510. ->get();
  5511. $result = [];
  5512. foreach ($items as $item) {
  5513. $itemArray = [
  5514. 'id' => $item->id,
  5515. 'type' => (int)$item->type,
  5516. 'parent_id' => (int)$item->parent_id,
  5517. 'level' => (int)$item->level,
  5518. 'product_name' => $item->product_name,
  5519. 'url' => $item->url,
  5520. 'pic_prompt' => $item->pic_prompt ?? '',
  5521. 'three_view_image_url' => $item->three_view_image_url,
  5522. 'product' => (int)($item->product ?? 1),
  5523. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5524. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5525. ];
  5526. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5527. // 如果是文件夹,递归获取其子项
  5528. if ($item->type == 2) {
  5529. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5530. if (!empty($children)) {
  5531. $itemArray['children'] = $children;
  5532. }
  5533. }
  5534. $result[] = $itemArray;
  5535. }
  5536. return $result;
  5537. }
  5538. /**
  5539. * 创建文件夹
  5540. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5541. * @return int 返回新建文件夹ID
  5542. */
  5543. public function createFolder($data) {
  5544. $uid = Site::getUid();
  5545. $cpid = Site::getCpid();
  5546. $role = Site::getRole();
  5547. $parent_id = getProp($data, 'parent_id', 0);
  5548. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5549. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5550. // 如果是公共库操作,需要admin权限
  5551. if ($is_public && $role !== 'admin') {
  5552. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5553. }
  5554. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5555. $store_uid = $is_public ? 0 : $uid;
  5556. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5557. $product = getProp($data, 'product');
  5558. if (!in_array($product, [1, 2, 3])) {
  5559. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5560. }
  5561. // 验证父文件夹
  5562. $parent_level = 0;
  5563. if ($parent_id > 0) {
  5564. $parent = DB::table('mp_products')
  5565. ->where('id', $parent_id)
  5566. ->where('cpid', $cpid)
  5567. ->where('user_id', $store_uid)
  5568. ->where('type', 2)
  5569. ->where('is_deleted', 0)
  5570. ->first();
  5571. if (!$parent) {
  5572. Utils::throwError('20003:父文件夹不存在');
  5573. }
  5574. // 检查父文件夹的 product 类型是否一致
  5575. if ($parent->product != $product) {
  5576. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5577. }
  5578. $parent_level = $parent->level;
  5579. // 检查层级限制(最多3层)
  5580. if ($parent_level >= 3) {
  5581. Utils::throwError('20003:文件夹层级不能超过3层');
  5582. }
  5583. }
  5584. // 检查当前目录下是否已存在空白文件夹
  5585. $empty_folder_exists = DB::table('mp_products')
  5586. ->where('parent_id', $parent_id)
  5587. ->where('cpid', $cpid)
  5588. ->where('user_id', $store_uid)
  5589. ->where('type', 2)
  5590. ->where('product', $product)
  5591. ->where('product_name', '新建文件夹')
  5592. ->where('is_deleted', 0)
  5593. ->exists();
  5594. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5595. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5596. }
  5597. // 创建文件夹
  5598. $folder_id = DB::table('mp_products')->insertGetId([
  5599. 'user_id' => $store_uid,
  5600. 'cpid' => $cpid,
  5601. 'type' => 2,
  5602. 'parent_id' => $parent_id,
  5603. 'level' => $parent_level + 1,
  5604. 'product_name' => $folder_name,
  5605. 'product' => $product,
  5606. 'sort_order' => time(), // 使用时间戳作为排序权重
  5607. 'is_deleted' => 0,
  5608. 'created_at' => date('Y-m-d H:i:s'),
  5609. 'updated_at' => date('Y-m-d H:i:s')
  5610. ]);
  5611. return [
  5612. 'id' => $folder_id,
  5613. 'type' => 2,
  5614. 'parent_id' => $parent_id,
  5615. 'level' => $parent_level + 1,
  5616. 'product_name' => $folder_name,
  5617. 'product' => $product,
  5618. ];
  5619. }
  5620. /**
  5621. * 重命名文件夹或角色
  5622. * @param array $data 包含 id、product_name(新名称)
  5623. * @return bool
  5624. */
  5625. public function renameFolder($data) {
  5626. $uid = Site::getUid();
  5627. $cpid = Site::getCpid();
  5628. $role = Site::getRole();
  5629. $id = getProp($data, 'id');
  5630. $new_name = getProp($data, 'product_name');
  5631. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5632. if (!$id || !$new_name) {
  5633. Utils::throwError('20003:参数不完整');
  5634. }
  5635. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5636. $query_uid = $is_public ? 0 : $uid;
  5637. // 如果是公共库操作,需要admin权限
  5638. if ($is_public && $role !== 'admin') {
  5639. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5640. }
  5641. // 检查是否存在
  5642. $item = DB::table('mp_products')
  5643. ->where('id', $id)
  5644. ->where('cpid', $cpid)
  5645. ->where('user_id', $query_uid)
  5646. ->where('is_deleted', 0)
  5647. ->first();
  5648. if (!$item) {
  5649. Utils::throwError('20003:项目不存在');
  5650. }
  5651. return DB::table('mp_products')
  5652. ->where('id', $id)
  5653. ->where('cpid', $cpid)
  5654. ->where('user_id', $query_uid)
  5655. ->update([
  5656. 'product_name' => $new_name,
  5657. 'updated_at' => date('Y-m-d H:i:s')
  5658. ]);
  5659. }
  5660. /**
  5661. * 移动角色或文件夹到指定文件夹
  5662. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5663. * @return bool
  5664. */
  5665. public function moveProductOrFolder($data) {
  5666. $uid = Site::getUid();
  5667. $cpid = Site::getCpid();
  5668. $role = Site::getRole();
  5669. $id = getProp($data, 'id');
  5670. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5671. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5672. if (!$id) {
  5673. Utils::throwError('20003:请选择要移动的项目');
  5674. }
  5675. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5676. $query_uid = $is_public ? 0 : $uid;
  5677. // 如果是公共库操作,需要admin权限
  5678. if ($is_public && $role !== 'admin') {
  5679. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5680. }
  5681. // 检查要移动的项目
  5682. $item = DB::table('mp_products')
  5683. ->where('id', $id)
  5684. ->where('cpid', $cpid)
  5685. ->where('user_id', $query_uid)
  5686. ->where('is_deleted', 0)
  5687. ->first();
  5688. if (!$item) {
  5689. Utils::throwError('20003:项目不存在');
  5690. }
  5691. // 验证目标文件夹
  5692. $target_level = 0;
  5693. $target_product = $item->product; // 默认使用当前项目的 product
  5694. if ($target_parent_id > 0) {
  5695. $target_parent = DB::table('mp_products')
  5696. ->where('id', $target_parent_id)
  5697. ->where('cpid', $cpid)
  5698. ->where('user_id', $query_uid)
  5699. ->where('type', 2)
  5700. ->where('is_deleted', 0)
  5701. ->first();
  5702. if (!$target_parent) {
  5703. Utils::throwError('20003:目标文件夹不存在');
  5704. }
  5705. // 检查 product 类型是否一致
  5706. if ($target_parent->product != $item->product) {
  5707. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5708. }
  5709. $target_level = $target_parent->level;
  5710. $target_product = $target_parent->product;
  5711. // 如果移动的是文件夹,需要检查层级
  5712. if ($item->type == 2) {
  5713. // 计算移动后的最大层级
  5714. $max_child_level = $this->getMaxChildLevel($id);
  5715. $depth = $max_child_level - $item->level;
  5716. if ($target_level + 1 + $depth > 3) {
  5717. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5718. }
  5719. // 不能移动到自己或自己的子文件夹下
  5720. if ($this->isDescendant($target_parent_id, $id)) {
  5721. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5722. }
  5723. }
  5724. }
  5725. // 更新父文件夹和层级
  5726. $new_level = $target_level + 1;
  5727. DB::table('mp_products')
  5728. ->where('id', $id)
  5729. ->update([
  5730. 'parent_id' => $target_parent_id,
  5731. 'level' => $new_level,
  5732. 'updated_at' => date('Y-m-d H:i:s')
  5733. ]);
  5734. // 如果是文件夹,需要递归更新所有子项的层级
  5735. if ($item->type == 2) {
  5736. $this->updateChildrenLevel($id, $new_level);
  5737. }
  5738. return true;
  5739. }
  5740. /**
  5741. * 获取文件夹下最大子层级
  5742. * @param int $folder_id
  5743. * @return int
  5744. */
  5745. private function getMaxChildLevel($folder_id) {
  5746. $max_level = DB::table('mp_products')
  5747. ->where('parent_id', $folder_id)
  5748. ->where('is_deleted', 0)
  5749. ->max('level');
  5750. if (!$max_level) {
  5751. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5752. }
  5753. // 递归查找子文件夹
  5754. $children = DB::table('mp_products')
  5755. ->where('parent_id', $folder_id)
  5756. ->where('type', 2)
  5757. ->where('is_deleted', 0)
  5758. ->pluck('id');
  5759. foreach ($children as $child_id) {
  5760. $child_max = $this->getMaxChildLevel($child_id);
  5761. if ($child_max > $max_level) {
  5762. $max_level = $child_max;
  5763. }
  5764. }
  5765. return $max_level;
  5766. }
  5767. /**
  5768. * 检查 target_id 是否是 folder_id 的后代
  5769. * @param int $target_id
  5770. * @param int $folder_id
  5771. * @return bool
  5772. */
  5773. private function isDescendant($target_id, $folder_id) {
  5774. if ($target_id == $folder_id) {
  5775. return true;
  5776. }
  5777. $parent = DB::table('mp_products')
  5778. ->where('id', $target_id)
  5779. ->where('is_deleted', 0)
  5780. ->first();
  5781. if (!$parent || $parent->parent_id == 0) {
  5782. return false;
  5783. }
  5784. return $this->isDescendant($parent->parent_id, $folder_id);
  5785. }
  5786. /**
  5787. * 递归更新子项层级
  5788. * @param int $parent_id
  5789. * @param int $parent_level
  5790. */
  5791. private function updateChildrenLevel($parent_id, $parent_level) {
  5792. $children = DB::table('mp_products')
  5793. ->where('parent_id', $parent_id)
  5794. ->where('is_deleted', 0)
  5795. ->get();
  5796. foreach ($children as $child) {
  5797. $new_level = $parent_level + 1;
  5798. DB::table('mp_products')
  5799. ->where('id', $child->id)
  5800. ->update([
  5801. 'level' => $new_level,
  5802. 'updated_at' => date('Y-m-d H:i:s')
  5803. ]);
  5804. // 如果是文件夹,继续递归
  5805. if ($child->type == 2) {
  5806. $this->updateChildrenLevel($child->id, $new_level);
  5807. }
  5808. }
  5809. }
  5810. /**
  5811. * 获取文件夹路径(面包屑导航)
  5812. * @param array $data 包含 folder_id
  5813. * @return array 返回路径数组
  5814. */
  5815. public function getFolderPath($data) {
  5816. $uid = Site::getUid();
  5817. $cpid = Site::getCpid();
  5818. $folder_id = getProp($data, 'id', 0);
  5819. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5820. if ($folder_id == 0) {
  5821. return [
  5822. ['id' => 0, 'name' => '根目录']
  5823. ];
  5824. }
  5825. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5826. $query_uid = $is_public ? 0 : $uid;
  5827. $path = [];
  5828. $current_id = $folder_id;
  5829. while ($current_id > 0) {
  5830. $folder = DB::table('mp_products')
  5831. ->where('id', $current_id)
  5832. ->where('cpid', $cpid)
  5833. ->where('user_id', $query_uid)
  5834. ->where('type', 2)
  5835. ->where('is_deleted', 0)
  5836. ->first();
  5837. if (!$folder) {
  5838. break;
  5839. }
  5840. array_unshift($path, [
  5841. 'id' => $folder->id,
  5842. 'name' => $folder->product_name
  5843. ]);
  5844. $current_id = $folder->parent_id;
  5845. }
  5846. // 添加根目录
  5847. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5848. return $path;
  5849. }
  5850. public function createProduct($data) {
  5851. $uid = Site::getUid();
  5852. $cpid = Site::getCpid();
  5853. $role = Site::getRole();
  5854. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5855. // 如果是公共库操作,需要admin权限
  5856. if ($is_public && $role !== 'admin') {
  5857. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5858. }
  5859. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5860. $store_uid = $is_public ? 0 : $uid;
  5861. $product_name = trim(getProp($data, 'product_name'));
  5862. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5863. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5864. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5865. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5866. $url = trim(getProp($data, 'url'));
  5867. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5868. $versions = getProp($data, 'versions');
  5869. // 检查是否是正确的图片格式
  5870. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5871. $urlPath = parse_url($url, PHP_URL_PATH);
  5872. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5873. if (!in_array($extension, $allowedExtensions)) {
  5874. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5875. }
  5876. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5877. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5878. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5879. $product = getProp($data, 'product');
  5880. if (!in_array($product, [1, 2, 3])) {
  5881. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5882. }
  5883. // 获取父文件夹ID和层级
  5884. $parent_id = getProp($data, 'parent_id', 0);
  5885. $parent_level = 0;
  5886. if ($parent_id > 0) {
  5887. $parent = DB::table('mp_products')
  5888. ->where('id', $parent_id)
  5889. ->where('cpid', $cpid)
  5890. ->where('user_id', $store_uid)
  5891. ->where('type', 2)
  5892. ->where('is_deleted', 0)
  5893. ->first();
  5894. if (!$parent) {
  5895. Utils::throwError('20003:父文件夹不存在');
  5896. }
  5897. $parent_level = $parent->level;
  5898. }
  5899. $id = DB::table('mp_products')->insertGetId([
  5900. 'user_id' => $store_uid,
  5901. 'cpid' => $cpid,
  5902. 'type' => 1, // 1=角色图片
  5903. 'parent_id' => $parent_id,
  5904. 'level' => $parent_level + 1,
  5905. 'product_name' => $product_name,
  5906. 'url' => $url,
  5907. 'pic_prompt' => $pic_prompt,
  5908. 'product' => $product,
  5909. 'versions' => json_encode($versions, 256),
  5910. 'sort_order' => time(), // 使用时间戳作为排序权重
  5911. 'created_at' => date('Y-m-d H:i:s'),
  5912. 'updated_at' => date('Y-m-d H:i:s')
  5913. ]);
  5914. if (!$id) Utils::throwError('20003:创建失败');
  5915. return [
  5916. 'id' => $id,
  5917. 'type' => 1,
  5918. 'parent_id' => $parent_id,
  5919. 'level' => $parent_level + 1,
  5920. 'product_name' => $product_name,
  5921. 'url' => $url,
  5922. 'pic_prompt' => $pic_prompt,
  5923. 'product' => $product,
  5924. 'versions' => $versions
  5925. ];
  5926. }
  5927. public function editProduct($data) {
  5928. $uid = Site::getUid();
  5929. $cpid = Site::getCpid();
  5930. $role = Site::getRole();
  5931. $id = getProp($data, 'id');
  5932. if (!$id) Utils::throwError('20003:ID不能为空');
  5933. $versions = getProp($data, 'versions');
  5934. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5935. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5936. $query_uid = $is_public ? 0 : $uid;
  5937. // 如果是公共库操作,需要admin权限
  5938. if ($is_public && $role !== 'admin') {
  5939. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5940. }
  5941. // 检查是否存在且属于当前用户或公共库
  5942. $role = DB::table('mp_products')
  5943. ->where('id', $id)
  5944. ->where('cpid', $cpid)
  5945. ->where('user_id', $query_uid)
  5946. ->where('type', 1)->first();
  5947. if (!$role) Utils::throwError('20003:记录不存在');
  5948. $updateData = [];
  5949. // $needVersionRecord = false; // 是否需要记录版本
  5950. // 名称
  5951. $product_name = trim(getProp($data, 'product_name'));
  5952. if ($product_name) {
  5953. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5954. $updateData['product_name'] = $product_name;
  5955. }
  5956. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5957. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5958. // 图片地址
  5959. $url = trim(getProp($data, 'url'));
  5960. if ($url) {
  5961. // 检查是否是正确的图片格式
  5962. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5963. $urlPath = parse_url($url, PHP_URL_PATH);
  5964. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5965. if (!in_array($extension, $allowedExtensions)) {
  5966. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5967. }
  5968. // // 如果 url 有变更,记录版本
  5969. // if ($url !== $role->url) {
  5970. // $needVersionRecord = true;
  5971. // }
  5972. $updateData['url'] = $url;
  5973. }
  5974. // 提示词
  5975. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5976. if ($pic_prompt) {
  5977. // // 如果 pic_prompt 有变更,记录版本
  5978. // if ($pic_prompt !== $role->pic_prompt) {
  5979. // $needVersionRecord = true;
  5980. // }
  5981. $updateData['pic_prompt'] = $pic_prompt;
  5982. }
  5983. if (empty($updateData)) {
  5984. Utils::throwError('20003:没有需要更新的数据');
  5985. }
  5986. // // 如果需要记录版本,将数据添加到 versions 数组
  5987. // if ($needVersionRecord) {
  5988. // // 获取现有的 versions 数据
  5989. // $versions = json_decode($role->versions, true) ?: [];
  5990. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  5991. // // 如果是第一次记录版本,先添加旧版本(变更前)
  5992. // if ($isFirstVersion) {
  5993. // $oldVersion = [
  5994. // 'url' => $role->url,
  5995. // 'description' => $role->pic_prompt,
  5996. // ];
  5997. // // 旧版本添加到数组末尾
  5998. // $versions[] = $oldVersion;
  5999. // }
  6000. // // 构建新版本(变更后)
  6001. // $newVersion = [
  6002. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6003. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6004. // ];
  6005. // // 检查新版本是否已存在于历史版本中
  6006. // $existingIndex = -1;
  6007. // foreach ($versions as $index => $version) {
  6008. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6009. // $existingIndex = $index;
  6010. // break;
  6011. // }
  6012. // }
  6013. // if ($existingIndex !== -1) {
  6014. // // 如果已存在,移除旧的位置
  6015. // array_splice($versions, $existingIndex, 1);
  6016. // }
  6017. // // 新版本添加到数组开头(最新的在前)
  6018. // array_unshift($versions, $newVersion);
  6019. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6020. // // if (count($versions) > 10) {
  6021. // // $versions = array_slice($versions, 0, 10);
  6022. // // }
  6023. // $updateData['versions'] = json_encode($versions, 256);
  6024. // }
  6025. if ($versions) {
  6026. $updateData['versions'] = json_encode($versions, 256);
  6027. }
  6028. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6029. return DB::table('mp_products')
  6030. ->where('cpid', $cpid)
  6031. ->where('id', $id)->update($updateData);
  6032. }
  6033. /**
  6034. * 获取角色版本历史
  6035. * @param array $data 包含 id(角色ID)
  6036. * @return array 返回版本历史列表
  6037. */
  6038. public function getProductVersions($data) {
  6039. $cpid = Site::getCpid();
  6040. $id = getProp($data, 'id');
  6041. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6042. $role = DB::table('mp_products')
  6043. ->where('id', $id)
  6044. ->where('cpid', $cpid)
  6045. ->where('type', 1)
  6046. ->first();
  6047. if (!$role) Utils::throwError('20003:角色不存在');
  6048. // 获取版本历史
  6049. $versions = json_decode($role->versions, true) ?: [];
  6050. // 添加当前版本作为最新版本
  6051. $currentVersion = [
  6052. 'version' => 0, // 0 表示当前版本
  6053. 'url' => $role->url,
  6054. 'pic_prompt' => $role->pic_prompt,
  6055. 'updated_at' => $role->updated_at,
  6056. 'is_current' => true
  6057. ];
  6058. array_unshift($versions, $currentVersion);
  6059. return $versions;
  6060. }
  6061. /**
  6062. * 恢复到指定版本
  6063. * @param array $data 包含 id(角色ID)、version(版本号)
  6064. * @return bool
  6065. */
  6066. public function restoreProductVersion($data) {
  6067. $uid = Site::getUid();
  6068. $cpid = Site::getCpid();
  6069. $id = getProp($data, 'id');
  6070. $version = getProp($data, 'version');
  6071. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6072. if (!$version) Utils::throwError('20003:版本号不能为空');
  6073. $role = DB::table('mp_products')
  6074. ->where('id', $id)
  6075. ->where('cpid', $cpid)
  6076. ->where('type', 1)
  6077. ->first();
  6078. if (!$role) Utils::throwError('20003:角色不存在');
  6079. // 获取版本历史
  6080. $versions = json_decode($role->versions, true) ?: [];
  6081. // 查找指定版本
  6082. $targetVersion = null;
  6083. foreach ($versions as $v) {
  6084. if ($v['version'] == $version) {
  6085. $targetVersion = $v;
  6086. break;
  6087. }
  6088. }
  6089. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6090. // 先将当前版本保存到历史
  6091. $newVersion = [
  6092. 'version' => count($versions) + 1,
  6093. 'url' => $role->url,
  6094. 'pic_prompt' => $role->pic_prompt,
  6095. 'updated_at' => date('Y-m-d H:i:s'),
  6096. 'updated_by' => $uid
  6097. ];
  6098. array_unshift($versions, $newVersion);
  6099. // 限制版本数量
  6100. if (count($versions) > 10) {
  6101. $versions = array_slice($versions, 0, 10);
  6102. }
  6103. // 恢复到指定版本
  6104. return DB::table('mp_products')
  6105. ->where('id', $id)
  6106. ->where('cpid', $cpid)
  6107. ->update([
  6108. 'url' => $targetVersion['url'],
  6109. 'pic_prompt' => $targetVersion['pic_prompt'],
  6110. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6111. 'updated_at' => date('Y-m-d H:i:s')
  6112. ]);
  6113. }
  6114. public function deleteProduct($data) {
  6115. $uid = Site::getUid();
  6116. $cpid = Site::getCpid();
  6117. $role = Site::getRole();
  6118. $id = getProp($data, 'id');
  6119. if (!$id) Utils::throwError('20003:ID不能为空');
  6120. $ids = explode(',', $id);
  6121. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6122. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6123. $query_uid = $is_public ? 0 : $uid;
  6124. // 如果是公共库操作,需要admin权限
  6125. if ($is_public && $role !== 'admin') {
  6126. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6127. }
  6128. // 检查是否存在且属于当前用户或公共库
  6129. $role = DB::table('mp_products')
  6130. ->whereIn('id', $ids)
  6131. ->where('cpid', $cpid)
  6132. ->where('user_id', $query_uid)
  6133. ->get();
  6134. if (!$role) Utils::throwError('20003:记录不存在');
  6135. return DB::table('mp_products')
  6136. ->where('cpid', $cpid)
  6137. ->where('user_id', $query_uid)
  6138. ->whereIn('id', $ids)
  6139. ->update([
  6140. 'is_deleted' => 1,
  6141. 'updated_at' => date('Y-m-d H:i:s')
  6142. ]);
  6143. }
  6144. public function generateThreeView($data) {
  6145. $uid = Site::getUid();
  6146. $cpid = Site::getCpid();
  6147. $role = Site::getRole();
  6148. $id = getProp($data, 'id');
  6149. if (!$id) Utils::throwError('20003:ID不能为空');
  6150. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6151. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6152. $query_uid = $is_public ? 0 : $uid;
  6153. // 如果是公共库操作,需要admin权限
  6154. if ($is_public && $role !== 'admin') {
  6155. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6156. }
  6157. // 检查是否存在且属于当前用户或公共库
  6158. $product = DB::table('mp_products')
  6159. ->where('id', $id)
  6160. ->where('cpid', $cpid)
  6161. ->where('user_id', $query_uid)
  6162. ->where('type', 1)->first();
  6163. if (!$product) Utils::throwError('20003:资产不存在');
  6164. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6165. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6166. if (!$ref_img_url) {
  6167. // 如果没有传入参考图,使用角色表中的图片
  6168. $ref_img_url = $product->url ?? '';
  6169. if (!$ref_img_url) {
  6170. Utils::throwError('20003:参考图不能为空');
  6171. }
  6172. }
  6173. $pic_prompt = getProp($product, 'pic_prompt');
  6174. if ($pic_prompt) {
  6175. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6176. }
  6177. // 检查参考图是否是正确的图片格式
  6178. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6179. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6180. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6181. if (!in_array($extension, $allowedExtensions)) {
  6182. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6183. }
  6184. // 处理图片模型
  6185. $model = getProp($data, 'model');
  6186. if (!$model) {
  6187. // 使用默认模型
  6188. $model = 'doubao-seedream-5-0-lite-260128';
  6189. }
  6190. // 验证模型是否在可用模型表中
  6191. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6192. Utils::throwError('20003:该模型已不可用,请更换!');
  6193. }
  6194. $ratio = getProp($data, 'ratio', '16:9');
  6195. $resolution = getProp($data, 'resolution', '2k');
  6196. // 定义分辨率和宽高比对应的尺寸映射表
  6197. $sizeMap = [
  6198. '2k' => [
  6199. '1:1' => ['width' => 2048, 'height' => 2048],
  6200. '4:3' => ['width' => 2304, 'height' => 1728],
  6201. '3:4' => ['width' => 1728, 'height' => 2304],
  6202. '16:9' => ['width' => 2848, 'height' => 1600],
  6203. '9:16' => ['width' => 1600, 'height' => 2848],
  6204. '3:2' => ['width' => 2496, 'height' => 1664],
  6205. '2:3' => ['width' => 1664, 'height' => 2496],
  6206. '21:9' => ['width' => 3136, 'height' => 1344],
  6207. ],
  6208. '3k' => [
  6209. '1:1' => ['width' => 3072, 'height' => 3072],
  6210. '4:3' => ['width' => 3456, 'height' => 2592],
  6211. '3:4' => ['width' => 2592, 'height' => 3456],
  6212. '16:9' => ['width' => 4096, 'height' => 2304],
  6213. '9:16' => ['width' => 2304, 'height' => 4096],
  6214. '2:3' => ['width' => 2496, 'height' => 3744],
  6215. '3:2' => ['width' => 3744, 'height' => 2496],
  6216. '21:9' => ['width' => 4704, 'height' => 2016],
  6217. ],
  6218. '4k' => [
  6219. '1:1' => ['width' => 4096, 'height' => 4096],
  6220. '3:4' => ['width' => 3520, 'height' => 4704],
  6221. '4:3' => ['width' => 4704, 'height' => 3520],
  6222. '16:9' => ['width' => 5504, 'height' => 3040],
  6223. '9:16' => ['width' => 3040, 'height' => 5504],
  6224. '2:3' => ['width' => 3328, 'height' => 4992],
  6225. '3:2' => ['width' => 4992, 'height' => 3328],
  6226. '21:9' => ['width' => 6240, 'height' => 2656],
  6227. ],
  6228. ];
  6229. // 参数验证
  6230. $resolution = strtolower($resolution);
  6231. if (!isset($sizeMap[$resolution])) {
  6232. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6233. }
  6234. if (!isset($sizeMap[$resolution][$ratio])) {
  6235. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6236. }
  6237. // 根据 ratio 和 resolution 确定宽高
  6238. $width = $sizeMap[$resolution][$ratio]['width'];
  6239. $height = $sizeMap[$resolution][$ratio]['height'];
  6240. try {
  6241. // 创建图片生成任务
  6242. $params = [
  6243. 'prompt' => $prompt,
  6244. 'model' => $model,
  6245. 'ref_img_urls' => [$ref_img_url],
  6246. 'width' => $width,
  6247. 'height' => $height
  6248. ];
  6249. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6250. $task_id = $task->id;
  6251. if (!$task_id) {
  6252. Utils::throwError('20003:创建图片生成任务失败');
  6253. }
  6254. // 轮询获取结果
  6255. // 只查询数据库,不调用API,不更新任务表
  6256. $start_time = time();
  6257. $timeout = 1800;
  6258. $img_url = '';
  6259. while (time() - $start_time < $timeout) {
  6260. sleep(5);
  6261. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6262. $task = DB::table('mp_generate_pic_tasks')
  6263. ->where('id', $task_id)
  6264. ->first();
  6265. if (!$task) {
  6266. Utils::throwError('20003:任务不存在');
  6267. }
  6268. if ($task->status === 'success' && $task->result_url) {
  6269. $result_urls = is_string($task->result_url)
  6270. ? json_decode($task->result_url, true)
  6271. : $task->result_url;
  6272. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6273. break;
  6274. } elseif ($task->status === 'failed') {
  6275. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6276. }
  6277. // 其他状态继续轮询
  6278. }
  6279. if (empty($img_url)) {
  6280. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6281. }
  6282. // 更新 mp_products 表(不是任务表)
  6283. DB::table('mp_products')
  6284. ->where('id', $id)
  6285. ->where('cpid', $cpid)
  6286. ->update([
  6287. 'three_view_image_url' => $img_url,
  6288. 'updated_at' => date('Y-m-d H:i:s')
  6289. ]);
  6290. return ['three_view_image_url' => $img_url];
  6291. } catch (\Exception $e) {
  6292. dLog('anime')->error('生成三视图失败', [
  6293. 'error' => $e->getMessage()
  6294. ]);
  6295. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6296. Utils::throwError('20003:' . $e->getMessage());
  6297. }
  6298. }
  6299. /**
  6300. * 推送(复制)资产或文件夹到目标位置
  6301. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6302. * @return array 返回推送结果
  6303. */
  6304. public function pushProductOrFolder($data) {
  6305. $uid = Site::getUid();
  6306. $cpid = Site::getCpid();
  6307. $role = Site::getRole();
  6308. $product_id = getProp($data, 'product_id');
  6309. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6310. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6311. if (!$product_id) {
  6312. Utils::throwError('20003:请选择要推送的项目');
  6313. }
  6314. // 查询源项目(只通过cpid查询,不限制user_id)
  6315. $sourceItem = DB::table('mp_products')
  6316. ->where('id', $product_id)
  6317. ->where('cpid', $cpid)
  6318. ->where('is_deleted', 0)
  6319. ->first();
  6320. if (!$sourceItem) {
  6321. Utils::throwError('20003:要推送的项目不存在');
  6322. }
  6323. // 通过user_id判断源是公共库还是个人库
  6324. $source_uid = $sourceItem->user_id;
  6325. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6326. // 验证目标文件夹并确定目标是公共库还是个人库
  6327. $target_level = 0;
  6328. $target_uid = $uid; // 默认推送到个人库
  6329. $target_is_public = 0;
  6330. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6331. if ($target_parent_id > 0) {
  6332. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6333. $targetParent = DB::table('mp_products')
  6334. ->where('id', $target_parent_id)
  6335. ->where('cpid', $cpid)
  6336. ->where('type', 2)
  6337. ->where('is_deleted', 0)
  6338. ->first();
  6339. if (!$targetParent) {
  6340. Utils::throwError('20003:目标文件夹不存在');
  6341. }
  6342. // 通过user_id判断目标是公共库还是个人库
  6343. $target_level = $targetParent->level;
  6344. $target_uid = $targetParent->user_id;
  6345. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6346. // 使用目标文件夹的 product 类型
  6347. $final_product_type = $targetParent->product;
  6348. }
  6349. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6350. else {
  6351. $push_to_public = getProp($data, 'push_to_public');
  6352. if ($push_to_public === '') {
  6353. Utils::throwError('20003:请选择是否推送到公共库');
  6354. }
  6355. if ($push_to_public) {
  6356. $target_uid = 0;
  6357. $target_is_public = 1;
  6358. }
  6359. // 推送到根目录时,必须指定 product 类型
  6360. if ($target_product === null || $target_product === '') {
  6361. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6362. }
  6363. $final_product_type = $target_product;
  6364. }
  6365. // 如果目标是公共库,需要admin权限
  6366. if ($target_is_public && $role !== 'admin') {
  6367. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6368. }
  6369. // 权限验证:验证是否符合允许的推送规则
  6370. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6371. try {
  6372. DB::beginTransaction();
  6373. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6374. if ($sourceItem->type == 1) {
  6375. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6376. DB::commit();
  6377. return [
  6378. 'product_id' => $newId,
  6379. ];
  6380. }
  6381. // 如果是文件夹,递归复制(支持跨类型推送)
  6382. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6383. DB::commit();
  6384. return [
  6385. 'product_id' => $newFolderId,
  6386. ];
  6387. } catch (\Exception $e) {
  6388. DB::rollBack();
  6389. dLog('anime')->error('推送失败', [
  6390. 'error' => $e->getMessage(),
  6391. 'product_id' => $product_id
  6392. ]);
  6393. Utils::throwError('20003:' . $e->getMessage());
  6394. }
  6395. }
  6396. /**
  6397. * 验证推送权限
  6398. * 允许的推送规则:
  6399. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6400. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6401. * 3. 公共库推送给公共库(公共库 → 公共库)
  6402. *
  6403. * @param int $source_uid 源的user_id
  6404. * @param int $target_uid 目标的user_id
  6405. * @param int $current_uid 当前用户ID
  6406. * @throws \Exception
  6407. */
  6408. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6409. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6410. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6411. return; // 允许
  6412. }
  6413. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6414. if ($source_uid == 0 && $target_uid == $current_uid) {
  6415. return; // 允许
  6416. }
  6417. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6418. if ($source_uid == 0 && $target_uid == 0) {
  6419. return; // 允许
  6420. }
  6421. // 其他情况都不允许
  6422. if ($source_uid != 0 && $source_uid != $current_uid) {
  6423. // 源是别人的个人库
  6424. Utils::throwError('20003:无权限访问该资产');
  6425. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6426. // 个人库推送给公共库(不允许)
  6427. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6428. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6429. // 不同用户的个人库之间推送(不允许)
  6430. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6431. } else {
  6432. // 其他未知情况
  6433. Utils::throwError('20003:不允许的推送操作');
  6434. }
  6435. }
  6436. /**
  6437. * 复制单个资产
  6438. * @param object $sourceProduct 源资产对象
  6439. * @param int $targetParentId 目标父文件夹ID
  6440. * @param int $targetLevel 目标层级
  6441. * @param int $cpid 公司ID
  6442. * @param int $targetUid 目标用户ID
  6443. * @return int 返回新资产ID
  6444. */
  6445. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6446. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6447. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6448. $newProductData = [
  6449. 'user_id' => $targetUid,
  6450. 'cpid' => $cpid,
  6451. 'type' => 1,
  6452. 'parent_id' => $targetParentId,
  6453. 'level' => $targetLevel,
  6454. 'product_name' => $sourceProduct->product_name,
  6455. 'url' => $sourceProduct->url,
  6456. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6457. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6458. 'product' => $finalProductType,
  6459. 'versions' => $sourceProduct->versions ?? '',
  6460. 'sort_order' => time(),
  6461. 'is_deleted' => 0,
  6462. 'created_at' => date('Y-m-d H:i:s'),
  6463. 'updated_at' => date('Y-m-d H:i:s')
  6464. ];
  6465. return DB::table('mp_products')->insertGetId($newProductData);
  6466. }
  6467. /**
  6468. * 递归复制文件夹及其子项
  6469. * @param object $sourceFolder 源文件夹对象
  6470. * @param int $targetParentId 目标父文件夹ID
  6471. * @param int $targetLevel 目标层级
  6472. * @param int $cpid 公司ID
  6473. * @param int $targetUid 目标用户ID
  6474. * @param int $sourceUid 源用户ID
  6475. * @return int 返回新文件夹ID
  6476. */
  6477. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6478. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6479. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6480. // 创建新文件夹
  6481. $newFolderData = [
  6482. 'user_id' => $targetUid,
  6483. 'cpid' => $cpid,
  6484. 'type' => 2,
  6485. 'parent_id' => $targetParentId,
  6486. 'level' => $targetLevel,
  6487. 'product_name' => $sourceFolder->product_name,
  6488. 'product' => $finalProductType,
  6489. 'sort_order' => time(),
  6490. 'is_deleted' => 0,
  6491. 'created_at' => date('Y-m-d H:i:s'),
  6492. 'updated_at' => date('Y-m-d H:i:s')
  6493. ];
  6494. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6495. // 获取源文件夹下的所有子项
  6496. $children = DB::table('mp_products')
  6497. ->where('parent_id', $sourceFolder->id)
  6498. ->where('cpid', $cpid)
  6499. ->where('user_id', $sourceUid)
  6500. ->where('is_deleted', 0)
  6501. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6502. ->get();
  6503. // 递归复制子项(子项继承目标文件夹的 product 类型)
  6504. foreach ($children as $child) {
  6505. if ($child->type == 1) {
  6506. // 资产
  6507. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  6508. } else {
  6509. // 文件夹
  6510. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  6511. }
  6512. }
  6513. return $newFolderId;
  6514. }
  6515. /**
  6516. * 保存剧本资产关联关系
  6517. * @param array $data 请求参数
  6518. * @return bool
  6519. */
  6520. public function saveScriptProducts($data) {
  6521. $uid = Site::getUid();
  6522. $cpid = Site::getCpid();
  6523. $script_id = getProp($data, 'script_id');
  6524. $products = getProp($data, 'products', []);
  6525. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6526. if (!$script_id) {
  6527. Utils::throwError('20003:请提供剧本ID');
  6528. }
  6529. // 验证剧本是否存在
  6530. $script = DB::table('mp_scripts')
  6531. ->where('id', $script_id)
  6532. ->where('is_deleted', 0)
  6533. ->first();
  6534. if (!$script) {
  6535. Utils::throwError('20003:剧本不存在');
  6536. }
  6537. // 处理图片模型
  6538. $model = getProp($data, 'model');
  6539. if (!$model) {
  6540. // 使用默认模型
  6541. $model = 'doubao-seedream-5-0-lite-260128';
  6542. }
  6543. // 验证模型是否在可用模型表中
  6544. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6545. Utils::throwError('20003:该模型已不可用,请更换!');
  6546. }
  6547. $ratio = getProp($data, 'ratio', '9:16');
  6548. $resolution = getProp($data, 'resolution', '2k');
  6549. // 定义分辨率和宽高比对应的尺寸映射表
  6550. $sizeMap = [
  6551. '2k' => [
  6552. '1:1' => ['width' => 2048, 'height' => 2048],
  6553. '4:3' => ['width' => 2304, 'height' => 1728],
  6554. '3:4' => ['width' => 1728, 'height' => 2304],
  6555. '16:9' => ['width' => 2848, 'height' => 1600],
  6556. '9:16' => ['width' => 1600, 'height' => 2848],
  6557. '3:2' => ['width' => 2496, 'height' => 1664],
  6558. '2:3' => ['width' => 1664, 'height' => 2496],
  6559. '21:9' => ['width' => 3136, 'height' => 1344],
  6560. ],
  6561. '3k' => [
  6562. '1:1' => ['width' => 3072, 'height' => 3072],
  6563. '4:3' => ['width' => 3456, 'height' => 2592],
  6564. '3:4' => ['width' => 2592, 'height' => 3456],
  6565. '16:9' => ['width' => 4096, 'height' => 2304],
  6566. '9:16' => ['width' => 2304, 'height' => 4096],
  6567. '2:3' => ['width' => 2496, 'height' => 3744],
  6568. '3:2' => ['width' => 3744, 'height' => 2496],
  6569. '21:9' => ['width' => 4704, 'height' => 2016],
  6570. ],
  6571. '4k' => [
  6572. '1:1' => ['width' => 4096, 'height' => 4096],
  6573. '3:4' => ['width' => 3520, 'height' => 4704],
  6574. '4:3' => ['width' => 4704, 'height' => 3520],
  6575. '16:9' => ['width' => 5504, 'height' => 3040],
  6576. '9:16' => ['width' => 3040, 'height' => 5504],
  6577. '2:3' => ['width' => 3328, 'height' => 4992],
  6578. '3:2' => ['width' => 4992, 'height' => 3328],
  6579. '21:9' => ['width' => 6240, 'height' => 2656],
  6580. ],
  6581. ];
  6582. // 参数验证
  6583. $resolution = strtolower($resolution);
  6584. if (!isset($sizeMap[$resolution])) {
  6585. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6586. }
  6587. if (!isset($sizeMap[$resolution][$ratio])) {
  6588. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6589. }
  6590. // 根据 ratio 和 resolution 确定宽高
  6591. $width = $sizeMap[$resolution][$ratio]['width'];
  6592. $height = $sizeMap[$resolution][$ratio]['height'];
  6593. $script_name = $script->script_name ?? 'script_' . $script_id;
  6594. // 检查是否已经有该剧本的资产数据
  6595. $existingMappings = DB::table('mp_script_product_mappings')
  6596. ->where('script_id', $script_id)
  6597. ->get();
  6598. if ($existingMappings->isNotEmpty()) {
  6599. // 已存在资产映射,检查是否所有资产都有图片生成任务
  6600. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  6601. // 查询这些资产的图片生成任务状态
  6602. $productsWithTasks = DB::table('mp_products')
  6603. ->whereIn('id', $productIds)
  6604. ->where('is_deleted', 0)
  6605. ->get();
  6606. $productTaskMap = [];
  6607. $typeFolderIds = [];
  6608. $hasAllTasks = true;
  6609. foreach ($productsWithTasks as $product) {
  6610. // 收集类型文件夹ID
  6611. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  6612. $parentFolder = DB::table('mp_products')
  6613. ->where('id', $product->parent_id)
  6614. ->where('type', 2)
  6615. ->first();
  6616. if ($parentFolder) {
  6617. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  6618. }
  6619. }
  6620. // 检查是否有图片生成任务
  6621. if (!empty($product->pic_task_id)) {
  6622. $productTaskMap[$product->id] = $product->pic_task_id;
  6623. } else if($product->url && $product->pic_task_status == '生成成功') {
  6624. continue;
  6625. } else {
  6626. // 有资产没有图片任务
  6627. $hasAllTasks = false;
  6628. }
  6629. }
  6630. // 如果所有资产都有任务ID,直接轮询返回结果
  6631. if ($hasAllTasks && !empty($productTaskMap)) {
  6632. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  6633. 'script_id' => $script_id,
  6634. 'script_name' => $script_name,
  6635. 'product_count' => count($productTaskMap)
  6636. ]);
  6637. // 直接返回 SSE 流轮询结果
  6638. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6639. }
  6640. // 如果部分资产没有任务ID,只为这些资产创建任务
  6641. if (!$hasAllTasks && $auto_generate_images) {
  6642. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  6643. 'script_id' => $script_id,
  6644. 'script_name' => $script_name
  6645. ]);
  6646. // 开启事务
  6647. DB::beginTransaction();
  6648. try {
  6649. foreach ($productsWithTasks as $product) {
  6650. // 跳过已有任务的资产
  6651. if (!empty($product->pic_task_id)) {
  6652. continue;
  6653. }
  6654. // 跳过没有提示词的资产
  6655. if (empty($product->pic_prompt)) {
  6656. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6657. 'product_id' => $product->id,
  6658. 'product_name' => $product->product_name
  6659. ]);
  6660. continue;
  6661. }
  6662. try {
  6663. // 创建图片生成任务
  6664. $params = [
  6665. 'prompt' => $product->pic_prompt,
  6666. 'model' => $model,
  6667. 'ref_img_urls' => [],
  6668. 'width' => $width,
  6669. 'height' => $height
  6670. ];
  6671. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6672. $task_id = $task->id;
  6673. if ($task_id) {
  6674. $productTaskMap[$product->id] = $task_id;
  6675. // 在事务中更新资产表的任务ID和状态
  6676. DB::table('mp_products')
  6677. ->where('id', $product->id)
  6678. ->update([
  6679. 'pic_task_id' => $task_id,
  6680. 'pic_task_status' => '生成中',
  6681. 'updated_at' => now()
  6682. ]);
  6683. dLog('anime')->info('为已存在资产创建图片生成任务', [
  6684. 'product_id' => $product->id,
  6685. 'task_id' => $task_id
  6686. ]);
  6687. }
  6688. } catch (\Exception $e) {
  6689. dLog('anime')->error('创建资产图片生成任务失败', [
  6690. 'product_id' => $product->id,
  6691. 'error' => $e->getMessage()
  6692. ]);
  6693. // 标记为失败(仍在事务中)
  6694. DB::table('mp_products')
  6695. ->where('id', $product->id)
  6696. ->update([
  6697. 'pic_task_status' => '生成失败',
  6698. 'updated_at' => now()
  6699. ]);
  6700. }
  6701. }
  6702. // 提交事务
  6703. DB::commit();
  6704. // 如果有新创建的任务,返回 SSE 流
  6705. if (!empty($productTaskMap)) {
  6706. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6707. }
  6708. } catch (\Exception $e) {
  6709. // 回滚事务
  6710. DB::rollback();
  6711. dLog('anime')->error('为已存在资产创建图片任务失败', [
  6712. 'script_id' => $script_id,
  6713. 'error' => $e->getMessage()
  6714. ]);
  6715. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  6716. }
  6717. }
  6718. // 如果不需要生成图片,返回已存在的信息
  6719. return [
  6720. 'success' => true,
  6721. 'message' => '剧本资产已存在',
  6722. 'script_id' => $script_id,
  6723. 'script_name' => $script_name,
  6724. 'type_folder_ids' => $typeFolderIds,
  6725. 'existing_products' => count($productIds),
  6726. 'tasks_count' => count($productTaskMap)
  6727. ];
  6728. }
  6729. // 解析 products(可能是 JSON 字符串或数组)
  6730. if (is_string($products)) {
  6731. $products = json_decode($products, true);
  6732. if (json_last_error() !== JSON_ERROR_NONE) {
  6733. Utils::throwError('20003:产品数据格式错误');
  6734. }
  6735. }
  6736. if (!is_array($products) || empty($products)) {
  6737. Utils::throwError('20003:产品数据不能为空');
  6738. }
  6739. // 以下是原有的创建逻辑...
  6740. // 开启事务
  6741. DB::beginTransaction();
  6742. try {
  6743. $now = now();
  6744. $mappingRecords = [];
  6745. $createdProductIds = []; // 记录所有创建的资产ID
  6746. // 获取剧本名称
  6747. $script_name = $script->script_name ?? 'script_' . $script_id;
  6748. // 存储每个类型的根文件夹ID
  6749. $typeFolderIds = [];
  6750. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  6751. foreach ($products as $productGroup) {
  6752. $type = getProp($productGroup, 'type');
  6753. $title = getProp($productGroup, 'title', '');
  6754. $content = getProp($productGroup, 'content', []);
  6755. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  6756. continue;
  6757. }
  6758. // 为当前类型创建根文件夹(如果还未创建)
  6759. if (!isset($typeFolderIds[$type])) {
  6760. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  6761. 'user_id' => $uid,
  6762. 'cpid' => $cpid,
  6763. 'type' => 2, // 1.资产 2文件夹
  6764. 'product' => $type, // 1.主体 2.场景 3.道具
  6765. 'parent_id' => 0, // 根文件夹,parent_id=0
  6766. 'level' => 1, // 第一层级
  6767. 'product_name' => $script_name,
  6768. 'sort_order' => time() + $type,
  6769. 'is_deleted' => 0,
  6770. 'created_at' => $now,
  6771. 'updated_at' => $now
  6772. ]);
  6773. }
  6774. $folder_id = $typeFolderIds[$type];
  6775. // 获取表头(第一行)并查找关键列的位置
  6776. $headers = $content[0];
  6777. $nameColumnIndex = -1; // 资产名称列索引
  6778. $sequenceColumnIndex = -1; // 使用范围列索引
  6779. $promptColumnIndex = -1; // 参考提示词列索引
  6780. foreach ($headers as $index => $header) {
  6781. // 查找"资产名称"列
  6782. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  6783. $nameColumnIndex = $index;
  6784. }
  6785. // 查找"使用范围"列
  6786. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  6787. $sequenceColumnIndex = $index;
  6788. }
  6789. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  6790. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  6791. $promptColumnIndex = $index;
  6792. }
  6793. }
  6794. // 验证必要的列是否都找到了
  6795. if ($nameColumnIndex === -1) {
  6796. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  6797. continue;
  6798. }
  6799. if ($sequenceColumnIndex === -1) {
  6800. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  6801. continue;
  6802. }
  6803. // 跳过表头,解析每一行数据
  6804. for ($i = 1; $i < count($content); $i++) {
  6805. $row = $content[$i];
  6806. // 确保行数据有效
  6807. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  6808. continue;
  6809. }
  6810. // 根据动态查找的列索引提取数据
  6811. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  6812. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6813. $pic_prompt = '';
  6814. // 提取参考提示词(如果找到了该列)
  6815. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6816. $pic_prompt = trim($row[$promptColumnIndex]);
  6817. }
  6818. // 解析使用范围(逗号分隔的序号)
  6819. $sequences = [];
  6820. if (!empty($sequence_str)) {
  6821. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  6822. foreach ($sequenceParts as $part) {
  6823. if (is_numeric($part)) {
  6824. $sequences[] = (int)$part;
  6825. }
  6826. }
  6827. }
  6828. if (empty($product_name)) {
  6829. continue;
  6830. }
  6831. // 处理product_name两边的符号
  6832. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6833. // 如果名称不存在或仅剩占位符号,则跳过
  6834. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  6835. dLog('anime')->warning('资产名称无效,跳过保存', [
  6836. 'script_id' => $script_id,
  6837. 'type' => $type,
  6838. 'product_name' => $product_name
  6839. ]);
  6840. continue;
  6841. }
  6842. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  6843. $product_id = DB::table('mp_products')->insertGetId([
  6844. 'product_name' => $product_name,
  6845. 'type' => 1, // 1=资产 2.文件夹
  6846. 'product' => $type, // 1=角色, 2=场景, 3=道具
  6847. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  6848. 'level' => 2, // 第二层级
  6849. 'pic_prompt' => $pic_prompt,
  6850. 'user_id' => $uid,
  6851. 'cpid' => $cpid,
  6852. 'sort_order' => time(),
  6853. 'is_deleted' => 0,
  6854. 'created_at' => $now,
  6855. 'updated_at' => $now,
  6856. ]);
  6857. // 记录创建的资产ID
  6858. $createdProductIds[] = $product_id;
  6859. // 为每个序号创建映射记录
  6860. if (!empty($sequences)) {
  6861. foreach ($sequences as $sequence) {
  6862. $mappingRecords[] = [
  6863. 'script_id' => $script_id,
  6864. 'product_id' => $product_id,
  6865. 'episode_number' => $sequence,
  6866. 'created_at' => $now,
  6867. 'updated_at' => $now,
  6868. ];
  6869. }
  6870. } else {
  6871. // 如果没有指定序号,创建一个默认映射(序号为0)
  6872. $mappingRecords[] = [
  6873. 'script_id' => $script_id,
  6874. 'product_id' => $product_id,
  6875. 'episode_number' => 0,
  6876. 'created_at' => $now,
  6877. 'updated_at' => $now,
  6878. ];
  6879. }
  6880. }
  6881. }
  6882. if (empty($mappingRecords)) {
  6883. Utils::throwError('20003:没有有效的产品数据');
  6884. }
  6885. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  6886. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  6887. // 剧本已有资产,同步更新is_products标记
  6888. DB::table('mp_scripts')->where('id', $script_id)->update([
  6889. 'is_products' => 1,
  6890. 'updated_at' => $now
  6891. ]);
  6892. // 如果需要自动生成图片,在事务中创建图片生成任务
  6893. $productTaskMap = [];
  6894. if ($auto_generate_images && !empty($createdProductIds)) {
  6895. // 查询所有创建的资产
  6896. $productsToGenerate = DB::table('mp_products')
  6897. ->whereIn('id', $createdProductIds)
  6898. ->where('is_deleted', 0)
  6899. ->get();
  6900. foreach ($productsToGenerate as $product) {
  6901. if (empty($product->pic_prompt)) {
  6902. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6903. 'product_id' => $product->id,
  6904. 'product_name' => $product->product_name
  6905. ]);
  6906. continue;
  6907. }
  6908. try {
  6909. // 创建图片生成任务
  6910. $params = [
  6911. 'prompt' => $product->pic_prompt,
  6912. 'model' => $model,
  6913. 'ref_img_urls' => [],
  6914. 'width' => $width,
  6915. 'height' => $height
  6916. ];
  6917. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6918. $task_id = $task->id;
  6919. if ($task_id) {
  6920. $productTaskMap[$product->id] = $task_id;
  6921. // 在事务中更新资产表的任务ID和状态
  6922. DB::table('mp_products')
  6923. ->where('id', $product->id)
  6924. ->update([
  6925. 'pic_task_id' => $task_id,
  6926. 'pic_task_status' => '生成中',
  6927. 'updated_at' => now()
  6928. ]);
  6929. dLog('anime')->info('创建资产图片生成任务', [
  6930. 'product_id' => $product->id,
  6931. 'task_id' => $task_id
  6932. ]);
  6933. }
  6934. } catch (\Exception $e) {
  6935. dLog('anime')->error('创建资产图片生成任务失败', [
  6936. 'product_id' => $product->id,
  6937. 'error' => $e->getMessage()
  6938. ]);
  6939. // 标记为失败(仍在事务中)
  6940. DB::table('mp_products')
  6941. ->where('id', $product->id)
  6942. ->update([
  6943. 'pic_task_status' => '生成失败',
  6944. 'updated_at' => now()
  6945. ]);
  6946. }
  6947. }
  6948. }
  6949. // 提交事务
  6950. DB::commit();
  6951. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6952. if ($auto_generate_images && !empty($productTaskMap)) {
  6953. // 返回 SSE 流(事务外轮询)
  6954. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6955. }
  6956. // 如果不需要生成图片,返回普通结果
  6957. return [
  6958. 'success' => true,
  6959. 'type_folder_ids' => $typeFolderIds,
  6960. 'inserted_count' => $insertedCount,
  6961. 'total_records' => count($mappingRecords),
  6962. 'created_products' => count($createdProductIds),
  6963. 'image_tasks_created' => count($productTaskMap)
  6964. ];
  6965. } catch (\Exception $e) {
  6966. // 回滚事务
  6967. DB::rollback();
  6968. // 记录错误日志
  6969. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6970. 'script_id' => $script_id,
  6971. 'error' => $e->getMessage(),
  6972. 'trace' => $e->getTraceAsString()
  6973. ]);
  6974. // 统一使用 Utils::throwError 抛出错误
  6975. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6976. }
  6977. }
  6978. /**
  6979. * 批量为剧本资产生成图片
  6980. *
  6981. * @param array $data 请求参数
  6982. * @return \Generator 返回 SSE 流
  6983. */
  6984. public function batchGenerateProductImages($data) {
  6985. $script_id = getProp($data, 'script_id');
  6986. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  6987. if (!$script_id) {
  6988. Utils::throwError('20003:请提供剧本ID');
  6989. }
  6990. // 验证剧本是否存在
  6991. $script = DB::table('mp_scripts')
  6992. ->where('id', $script_id)
  6993. ->where('is_deleted', 0)
  6994. ->first();
  6995. if (!$script) {
  6996. Utils::throwError('20003:剧本不存在');
  6997. }
  6998. $script_name = $script->script_name ?? 'script_' . $script_id;
  6999. // 获取需要生成图片的所有资产
  7000. $products = DB::table('mp_products')
  7001. ->whereIn('parent_id', array_values($type_folder_ids))
  7002. ->where('is_deleted', 0)
  7003. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7004. ->get();
  7005. if ($products->isEmpty()) {
  7006. Utils::throwError('20003:没有找到需要生成图片的资产');
  7007. }
  7008. // 默认参数
  7009. $model = 'doubao-seedream-5-0-lite-260128';
  7010. $width = 1600;
  7011. $height = 2848;
  7012. // 开始为每个资产创建图片生成任务
  7013. $taskIds = [];
  7014. $productTaskMap = []; // 资产ID到任务ID的映射
  7015. foreach ($products as $product) {
  7016. if (empty($product->pic_prompt)) {
  7017. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7018. continue;
  7019. }
  7020. try {
  7021. // 创建图片生成任务
  7022. $params = [
  7023. 'prompt' => $product->pic_prompt,
  7024. 'model' => $model,
  7025. 'ref_img_urls' => [],
  7026. 'width' => $width,
  7027. 'height' => $height
  7028. ];
  7029. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7030. $task_id = $task->id;
  7031. if ($task_id) {
  7032. $taskIds[] = $task_id;
  7033. $productTaskMap[$product->id] = $task_id;
  7034. // 更新资产表的任务ID和状态
  7035. DB::table('mp_products')
  7036. ->where('id', $product->id)
  7037. ->update([
  7038. 'pic_task_id' => $task_id,
  7039. 'pic_task_status' => '生成中',
  7040. 'updated_at' => now()
  7041. ]);
  7042. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7043. }
  7044. } catch (\Exception $e) {
  7045. dLog('anime')->error('创建资产图片生成任务失败', [
  7046. 'product_id' => $product->id,
  7047. 'error' => $e->getMessage()
  7048. ]);
  7049. // 标记为失败
  7050. DB::table('mp_products')
  7051. ->where('id', $product->id)
  7052. ->update([
  7053. 'pic_task_status' => '生成失败',
  7054. 'updated_at' => now()
  7055. ]);
  7056. }
  7057. }
  7058. if (empty($taskIds)) {
  7059. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7060. }
  7061. // 返回 SSE 流
  7062. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7063. }
  7064. /**
  7065. * 轮询资产图片生成任务状态(SSE流式返回)
  7066. * 只通过查询数据库获取任务状态,不主动调用API
  7067. *
  7068. * @param int $script_id 剧本ID
  7069. * @param string $script_name 剧本名称
  7070. * @param array $productTaskMap 资产ID到任务ID的映射
  7071. * @param array $type_folder_ids 类型文件夹ID映射
  7072. * @return \Generator
  7073. */
  7074. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  7075. $startTime = time();
  7076. $timeout = 1800; // 30分钟超时
  7077. $pollInterval = 10; // 10秒轮询一次
  7078. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7079. // 定义类型名称映射
  7080. $typeNames = [
  7081. 1 => 'roles', // 角色
  7082. 2 => 'scenes', // 场景
  7083. 3 => 'props' // 道具
  7084. ];
  7085. while (time() - $startTime < $timeout) {
  7086. sleep($pollInterval);
  7087. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7088. $mappings = DB::table('mp_script_product_mappings')
  7089. ->where('script_id', $script_id)
  7090. ->pluck('product_id')
  7091. ->unique()
  7092. ->toArray();
  7093. if (empty($mappings)) {
  7094. dLog('anime')->warning('该剧本没有关联的资产', [
  7095. 'script_id' => $script_id,
  7096. 'script_name' => $script_name
  7097. ]);
  7098. break;
  7099. }
  7100. // 查询所有资产的当前状态
  7101. $products = DB::table('mp_products')
  7102. ->whereIn('id', $mappings)
  7103. ->where('is_deleted', 0)
  7104. ->get();
  7105. // 统计各类型的状态(使用类型名称作为键名)
  7106. $stats = [
  7107. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7108. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7109. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7110. ];
  7111. $allCompleted = true;
  7112. $hasStatusChange = false;
  7113. foreach ($products as $product) {
  7114. $type = $product->product;
  7115. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7116. // 如果类型名称不在 stats 中,初始化
  7117. if (!isset($stats[$typeName])) {
  7118. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7119. }
  7120. $stats[$typeName]['total']++;
  7121. $task_id = $product->pic_task_id;
  7122. $currentStatus = $product->pic_task_status;
  7123. // 检查状态是否有变化
  7124. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7125. $hasStatusChange = true;
  7126. $lastStatus[$product->id] = $currentStatus;
  7127. }
  7128. // 如果是生成中,查询任务表状态
  7129. if ($currentStatus === '生成中' && $task_id) {
  7130. // 只查询数据库,不调用API
  7131. $task = DB::table('mp_generate_pic_tasks')
  7132. ->where('id', $task_id)
  7133. ->first();
  7134. if ($task) {
  7135. // 检查任务状态
  7136. if ($task->status === 'success' && $task->result_url) {
  7137. // 解析图片URL
  7138. $result_urls = $task->result_url;
  7139. if (is_string($result_urls)) {
  7140. $result_urls = json_decode($result_urls, true);
  7141. }
  7142. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7143. // 更新资产表状态
  7144. DB::table('mp_products')
  7145. ->where('id', $product->id)
  7146. ->update([
  7147. 'pic_task_status' => '生成成功',
  7148. 'url' => $img_url,
  7149. 'updated_at' => now()
  7150. ]);
  7151. $stats[$typeName]['success']++;
  7152. $stats[$typeName]['completed']++;
  7153. $hasStatusChange = true;
  7154. dLog('anime')->info('资产图片生成成功', [
  7155. 'product_id' => $product->id,
  7156. 'task_id' => $task_id,
  7157. 'img_url' => $img_url
  7158. ]);
  7159. } elseif ($task->status === 'failed') {
  7160. // 更新资产表状态
  7161. DB::table('mp_products')
  7162. ->where('id', $product->id)
  7163. ->update([
  7164. 'pic_task_status' => '生成失败',
  7165. 'updated_at' => now()
  7166. ]);
  7167. $stats[$typeName]['completed']++;
  7168. $hasStatusChange = true;
  7169. dLog('anime')->warning('资产图片生成失败', [
  7170. 'product_id' => $product->id,
  7171. 'task_id' => $task_id,
  7172. 'error' => $task->error_message ?? '未知错误'
  7173. ]);
  7174. } else {
  7175. // 任务还在处理中
  7176. $allCompleted = false;
  7177. }
  7178. } else {
  7179. // 任务不存在,标记为失败
  7180. DB::table('mp_products')
  7181. ->where('id', $product->id)
  7182. ->update([
  7183. 'pic_task_status' => '生成失败',
  7184. 'updated_at' => now()
  7185. ]);
  7186. $stats[$type]['completed']++;
  7187. $hasStatusChange = true;
  7188. dLog('anime')->error('图片生成任务不存在', [
  7189. 'product_id' => $product->id,
  7190. 'task_id' => $task_id
  7191. ]);
  7192. }
  7193. } elseif ($currentStatus === '生成成功') {
  7194. $stats[$typeName]['success']++;
  7195. $stats[$typeName]['completed']++;
  7196. } elseif ($currentStatus === '生成失败') {
  7197. $stats[$typeName]['completed']++;
  7198. } else {
  7199. // 其他状态也认为未完成
  7200. $allCompleted = false;
  7201. }
  7202. }
  7203. // 移除没有数据的类型(total=0)
  7204. foreach ($stats as $typeName => $stat) {
  7205. if ($stat['total'] === 0) {
  7206. unset($stats[$typeName]);
  7207. }
  7208. }
  7209. // 如果有状态变化,发送 SSE 更新
  7210. if ($hasStatusChange) {
  7211. $eventType = $allCompleted ? 'complete' : 'update';
  7212. $response = [
  7213. 'type' => $eventType,
  7214. 'script_id' => $script_id,
  7215. 'script_name' => $script_name,
  7216. 'stats' => $stats,
  7217. 'timestamp' => date('Y-m-d H:i:s')
  7218. ];
  7219. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7220. dLog('anime')->info('SSE更新', [
  7221. 'event_type' => $eventType,
  7222. 'script_id' => $script_id,
  7223. 'script_name' => $script_name,
  7224. 'stats' => $stats
  7225. ]);
  7226. if ($allCompleted) {
  7227. dLog('anime')->info('所有资产图片生成任务已完成', [
  7228. 'script_id' => $script_id,
  7229. 'script_name' => $script_name,
  7230. 'stats' => $stats
  7231. ]);
  7232. break;
  7233. }
  7234. }
  7235. }
  7236. // 超时处理
  7237. if (time() - $startTime >= $timeout && !$allCompleted) {
  7238. $response = [
  7239. 'type' => 'timeout',
  7240. 'message' => '部分任务超时,请稍后查看结果',
  7241. 'script_id' => $script_id,
  7242. 'script_name' => $script_name,
  7243. 'timestamp' => date('Y-m-d H:i:s')
  7244. ];
  7245. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7246. dLog('anime')->warning('资产图片生成任务超时', [
  7247. 'script_id' => $script_id,
  7248. 'script_name' => $script_name,
  7249. 'timeout' => $timeout
  7250. ]);
  7251. }
  7252. }
  7253. /**
  7254. * 获取剧本关联的资产列表
  7255. * @param array $data 请求参数
  7256. * @return array
  7257. */
  7258. public function getScriptProducts($data) {
  7259. $uid = Site::getUid();
  7260. $cpid = Site::getCpid();
  7261. $script_id = getProp($data, 'script_id');
  7262. $episode_number = getProp($data, 'episode_number');
  7263. if (!$script_id) {
  7264. Utils::throwError('20003:请提供剧本ID');
  7265. }
  7266. // 验证剧本是否存在
  7267. $script = DB::table('mp_scripts')
  7268. ->where('id', $script_id)
  7269. ->where('is_deleted', 0)
  7270. ->first();
  7271. if (!$script) {
  7272. Utils::throwError('20003:剧本不存在');
  7273. }
  7274. // 联表查询资产信息
  7275. $query = DB::table('mp_script_product_mappings as mapping')
  7276. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7277. ->where('mapping.script_id', $script_id)
  7278. ->where('product.cpid', $cpid)
  7279. ->where('product.is_deleted', 0);
  7280. // 如果提供了 episode_number,则过滤指定集数
  7281. if ($episode_number !== null && $episode_number !== '') {
  7282. $query->where('mapping.episode_number', $episode_number);
  7283. }
  7284. $mappings = $query->select(
  7285. 'mapping.script_id',
  7286. 'mapping.product_id',
  7287. 'mapping.episode_number',
  7288. 'product.product_name',
  7289. 'product.type',
  7290. 'product.product',
  7291. 'product.pic_prompt',
  7292. 'product.url',
  7293. 'product.pic_task_id',
  7294. 'product.pic_task_status',
  7295. 'product.three_view_image_url',
  7296. 'mapping.created_at'
  7297. )
  7298. ->orderBy('mapping.product_id', 'asc')
  7299. ->orderBy('mapping.episode_number', 'asc')
  7300. ->get();
  7301. // 按 product_id 分组,合并 episode_number
  7302. $productMap = [];
  7303. foreach ($mappings as $item) {
  7304. $product_id = $item->product_id;
  7305. if (!isset($productMap[$product_id])) {
  7306. $productMap[$product_id] = [
  7307. 'product_id' => $product_id,
  7308. 'product_name' => $item->product_name,
  7309. 'type' => (int)$item->type,
  7310. 'product' => (int)$item->product,
  7311. 'pic_prompt' => $item->pic_prompt,
  7312. 'url' => $item->url,
  7313. 'pic_task_id' => $item->pic_task_id,
  7314. 'pic_task_status' => $item->pic_task_status,
  7315. 'episode_numbers' => [],
  7316. 'created_at' => $item->created_at,
  7317. ];
  7318. }
  7319. // 添加 episode_number(去重)
  7320. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7321. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7322. }
  7323. }
  7324. // 按类型分组
  7325. $roles = []; // type=1 角色/主体
  7326. $scenes = []; // type=2 场景
  7327. $props = []; // type=3 道具
  7328. foreach ($productMap as $product) {
  7329. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7330. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7331. // 构造返回数据
  7332. $productData = [
  7333. 'product_id' => $product['product_id'],
  7334. 'product_name' => $product['product_name'],
  7335. 'product' => $product['product'],
  7336. 'pic_prompt' => $product['pic_prompt'],
  7337. 'url' => $product['url'],
  7338. 'pic_task_id' => $product['pic_task_id'],
  7339. 'pic_task_status' => $product['pic_task_status'],
  7340. 'episode_numbers' => $episodeNumbersStr,
  7341. 'created_at' => $product['created_at'],
  7342. ];
  7343. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7344. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7345. switch ($product['product']) {
  7346. case 1:
  7347. $roles[] = $productData;
  7348. break;
  7349. case 2:
  7350. $scenes[] = $productData;
  7351. break;
  7352. case 3:
  7353. $props[] = $productData;
  7354. break;
  7355. }
  7356. }
  7357. return [
  7358. 'script_id' => $script_id,
  7359. 'script_name' => $script->script_name ?? '',
  7360. 'roles' => $roles, // 主体
  7361. 'scenes' => $scenes, // 场景
  7362. 'props' => $props, // 道具
  7363. ];
  7364. }
  7365. /**
  7366. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7367. * @param string $actContent 原始内容
  7368. * @param array $products 产品数组(包含product_name和url)
  7369. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7370. */
  7371. public function processActContentWithProducts($actContent, $products) {
  7372. if (empty($actContent) || empty($products)) {
  7373. return [
  7374. 'content' => $actContent,
  7375. 'reference_images' => []
  7376. ];
  7377. }
  7378. // 构建产品名称到产品信息的映射
  7379. $product_dict = [];
  7380. foreach ($products as $product) {
  7381. $product_name = getProp($product, 'product_name');
  7382. if ($product_name) {
  7383. $product_dict[$product_name] = [
  7384. 'url' => getProp($product, 'url'),
  7385. 'voice_prompt' => getProp($product, 'voice_prompt')
  7386. ];
  7387. }
  7388. }
  7389. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7390. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7391. $reference_images = [];
  7392. $product_index_map = []; // 产品名称 => 图片序号的映射
  7393. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7394. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7395. $current_index = 1;
  7396. if (!empty($matches[1])) {
  7397. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7398. $seen_products = []; // 用于去重
  7399. foreach ($matches[1] as $product_name) {
  7400. // 跳过已处理的产品
  7401. if (isset($seen_products[$product_name])) {
  7402. continue;
  7403. }
  7404. $seen_products[$product_name] = true;
  7405. // 检查产品是否在字典中
  7406. if (isset($product_dict[$product_name])) {
  7407. $url = $product_dict[$product_name]['url'];
  7408. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7409. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7410. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7411. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7412. }
  7413. // 只有URL非空才分配序号和添加到参考图片
  7414. if (!empty($url)) {
  7415. // 检查URL是否已经在reference_images中(去重)
  7416. if (!in_array($url, $reference_images)) {
  7417. $reference_images[] = $url;
  7418. $product_index_map[$product_name] = $current_index;
  7419. $current_index++;
  7420. } else {
  7421. // URL重复,找到已有的序号
  7422. $existing_index = array_search($url, $reference_images) + 1;
  7423. $product_index_map[$product_name] = $existing_index;
  7424. }
  7425. } else {
  7426. // URL为空,不分配序号(后续直接去掉{})
  7427. $product_index_map[$product_name] = 0;
  7428. }
  7429. } else {
  7430. // 产品不在字典中,不分配序号
  7431. $product_index_map[$product_name] = 0;
  7432. }
  7433. }
  7434. }
  7435. // 第二步:替换内容中的 {产品名称}
  7436. $processedContent = $actContent;
  7437. foreach ($product_index_map as $product_name => $index) {
  7438. $escaped_name = preg_quote($product_name, '/');
  7439. if ($index > 0) {
  7440. // 有图片,替换为:产品名称(图X)
  7441. $replacement = $product_name . '<图片' . $index . '>';
  7442. } else {
  7443. // 无图片,只保留产品名称
  7444. $replacement = $product_name;
  7445. }
  7446. // 替换所有 {产品名称} 为处理后的格式
  7447. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7448. }
  7449. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7450. foreach ($products as $product) {
  7451. $product_name = getProp($product, 'product_name');
  7452. $voice_prompt = getProp($product, 'voice_prompt');
  7453. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7454. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7455. break; // 找到旁白后退出循环
  7456. }
  7457. }
  7458. // 第四步:将voice_prompt信息添加到内容最前面
  7459. $voice_prompt_prefix = '';
  7460. if (!empty($voice_prompts)) {
  7461. $voice_prompt_prefix .= implode('', $voice_prompts);
  7462. }
  7463. // 旁白的voice_prompt放在最后
  7464. if (!empty($narrator_voice_prompt)) {
  7465. $voice_prompt_prefix .= $narrator_voice_prompt;
  7466. }
  7467. // 如果有voice_prompt信息,添加到内容开头
  7468. if (!empty($voice_prompt_prefix)) {
  7469. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7470. }
  7471. return [
  7472. 'content' => $processedContent,
  7473. 'reference_images' => $reference_images
  7474. ];
  7475. }
  7476. public function saveActVideoGenerateParams($data) {
  7477. $episode_id = getProp($data, 'episode_id');
  7478. $model = getProp($data, 'video_model');
  7479. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7480. Utils::throwError('20003:该模型不可用');
  7481. }
  7482. if (!$model) {
  7483. // 使用默认模型
  7484. $model = 'zhizhen-20';
  7485. }
  7486. // 验证模型是否在可用模型表中
  7487. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7488. Utils::throwError('20003:该模型已不可用,请更换!');
  7489. }
  7490. $video_resolution = getProp($data, 'video_resolution', '720p');
  7491. $ratio = getProp($data, 'ratio');
  7492. if (!$ratio) $ratio = '9:16';
  7493. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  7494. if (!$episode) {
  7495. Utils::throwError('20003:分集不存在');
  7496. }
  7497. try {
  7498. DB::beginTransaction();
  7499. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7500. 'video_model' => $model,
  7501. 'video_resolution' => $video_resolution,
  7502. 'ratio' => $ratio,
  7503. 'updated_at' => date('Y-m-d H:i:s')
  7504. ]);
  7505. if ($result === false) {
  7506. Utils::throwError('20003:分集视频参数保存失败');
  7507. }
  7508. // 同步更新mp_animes表
  7509. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  7510. 'video_model' => $model,
  7511. 'video_resolution' => $video_resolution,
  7512. 'video_ratio' => $ratio,
  7513. 'updated_at' => date('Y-m-d H:i:s')
  7514. ]);
  7515. if ($anime_result === false) {
  7516. Utils::throwError('20003:动漫视频参数保存失败');
  7517. }
  7518. } catch (\Exception $e) {
  7519. DB::rollBack();
  7520. Utils::throwError('20003:'.$e->getMessage());
  7521. }
  7522. DB::commit();
  7523. return $result;
  7524. }
  7525. public function confirmActs($data) {
  7526. $episode_id = getProp($data, 'episode_id');
  7527. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7528. if (!$episode) {
  7529. Utils::throwError('20003:分集不存在');
  7530. }
  7531. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7532. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7533. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  7534. // 获取所有片段数据
  7535. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7536. // 收集所有资产名称(角色、场景、道具)
  7537. $product_names = [];
  7538. // 收集角色名称
  7539. foreach ($roles as $role) {
  7540. $role_name = getProp($role, 'role');
  7541. if ($role_name && $role_name != '旁白') {
  7542. $product_names[] = $role_name;
  7543. }
  7544. }
  7545. // 收集场景名称
  7546. foreach ($scenes as $scene) {
  7547. $scene_name = getProp($scene, 'scene');
  7548. if ($scene_name) {
  7549. $product_names[] = $scene_name;
  7550. }
  7551. }
  7552. // 收集道具名称
  7553. foreach ($props as $prop) {
  7554. $prop_name = getProp($prop, 'prop');
  7555. if ($prop_name) {
  7556. $product_names[] = $prop_name;
  7557. }
  7558. }
  7559. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  7560. $product_names = array_unique($product_names);
  7561. usort($product_names, function($a, $b) {
  7562. return mb_strlen($b) - mb_strlen($a);
  7563. });
  7564. try {
  7565. DB::beginTransaction();
  7566. // 处理每个片段
  7567. foreach ($acts as $act) {
  7568. $act_content = getProp($act, 'act_content');
  7569. if (!$act_content) continue;
  7570. $processed_content = $act_content;
  7571. // 统一替换所有资产名称为 {资产名} 格式
  7572. // 使用占位符避免嵌套替换问题
  7573. $placeholder_map = [];
  7574. $placeholder_index = 0;
  7575. foreach ($product_names as $product_name) {
  7576. // 转义特殊字符
  7577. $escaped_product = preg_quote($product_name, '/');
  7578. // 检查是否匹配且未被 {} 包裹
  7579. $processed_content = preg_replace_callback(
  7580. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  7581. function($matches) use (&$placeholder_map, &$placeholder_index) {
  7582. // 使用唯一占位符
  7583. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  7584. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  7585. $placeholder_index++;
  7586. return $placeholder;
  7587. },
  7588. $processed_content
  7589. );
  7590. }
  7591. // 将所有占位符替换回实际内容
  7592. foreach ($placeholder_map as $placeholder => $replacement) {
  7593. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  7594. }
  7595. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7596. $shot_counter = 0;
  7597. $processed_content = preg_replace_callback(
  7598. '/【(?:镜头|分镜)(\d+)】/u',
  7599. function($matches) use (&$shot_counter) {
  7600. $shot_counter++;
  7601. return '【镜头' . $shot_counter . '】';
  7602. },
  7603. $processed_content
  7604. );
  7605. // 更新数据库
  7606. $boolen = DB::table('mp_episode_segments')
  7607. ->where('id', $act->id)
  7608. ->update([
  7609. 'act_show_content' => $processed_content,
  7610. 'updated_at' => date('Y-m-d H:i:s')
  7611. ]);
  7612. if (!$boolen) {
  7613. Utils::throwError('20003:片段处理失败');
  7614. }
  7615. }
  7616. }catch (\Exception $e) {
  7617. DB::rollBack();
  7618. Utils::throwError('20003:'.$e->getMessage());
  7619. }
  7620. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7621. 'is_generated' => 1,
  7622. 'updated_at' => date('Y-m-d H:i:s')
  7623. ]);
  7624. if (!$boolen1) {
  7625. DB::rollBack();
  7626. Utils::throwError('20003:分集处理失败!');
  7627. }
  7628. DB::commit();
  7629. // 重新查询更新后的片段数据
  7630. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7631. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  7632. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  7633. $products = [];
  7634. // 先处理角色数组
  7635. foreach ($roles as $role) {
  7636. $product = $role;
  7637. // 将role字段重命名为product_name
  7638. if (isset($product['role'])) {
  7639. $product['product_name'] = $product['role'];
  7640. unset($product['role']);
  7641. $product['product'] = 1; // 标记类型为角色
  7642. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7643. }
  7644. }
  7645. // 处理场景数组
  7646. foreach ($scenes as $scene) {
  7647. $product = $scene;
  7648. // 将scene字段重命名为product_name
  7649. if (isset($product['scene'])) {
  7650. $product['product_name'] = $product['scene'];
  7651. unset($product['scene']);
  7652. $product['product'] = 2; // 标记类型为场景
  7653. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7654. }
  7655. }
  7656. // 处理道具数组(逻辑与场景一致)
  7657. foreach ($props as $prop) {
  7658. $product = $prop;
  7659. // 将prop字段重命名为product_name
  7660. if (isset($product['prop'])) {
  7661. $product['product_name'] = $product['prop'];
  7662. unset($product['prop']);
  7663. $product['product'] = 3; // 标记类型为道具
  7664. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7665. }
  7666. }
  7667. // extra_products优先级更高,直接覆盖同名的roles和scenes
  7668. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  7669. foreach ($extra_products as $extra_product) {
  7670. $product_name = getProp($extra_product, 'product_name');
  7671. if ($product_name) {
  7672. $products[$product_name] = $extra_product; // 覆盖同名数据
  7673. }
  7674. }
  7675. // 重新索引数组(去除key)
  7676. $products = array_values($products);
  7677. // 构建返回的acts数组
  7678. $return_acts = [];
  7679. foreach ($acts as $act) {
  7680. $return_acts[] = [
  7681. 'act_id' => getProp($act, 'id'),
  7682. 'act_number' => getProp($act, 'act_number'),
  7683. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  7684. 'act_show_content' => getProp($act, 'act_show_content'),
  7685. 'video_url' => getProp($act, 'video_url'),
  7686. 'video_duration' => getProp($act, 'video_duration'),
  7687. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  7688. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  7689. ];
  7690. }
  7691. return [
  7692. 'anime_id' => getProp($episode, 'anime_id'),
  7693. 'episode_id' => $episode_id,
  7694. 'title' => getProp($episode, 'title'),
  7695. 'episode_number' => getProp($episode, 'episode_number'),
  7696. 'is_generated' => getProp($episode, 'is_generated'),
  7697. 'video_params' => [
  7698. 'video_model' => getProp($episode, 'video_model'),
  7699. 'video_resolution' => getProp($episode, 'video_resolution'),
  7700. 'ratio' => getProp($episode, 'ratio'),
  7701. ],
  7702. 'products' => $products,
  7703. 'acts' => $return_acts
  7704. ];
  7705. }
  7706. }