AnimeService.php 347 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045
  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. $input_art_style = getProp($data, 'art_style');
  181. $file = getProp($data, 'file');
  182. $content = getProp($data, 'content', '');
  183. $bid = getProp($data, 'bid', 0);
  184. $script_id = getProp($data, 'script_id', 0);
  185. $ace_mode = getProp($data, 'ace_mode', 0);
  186. $extra_products = getProp($data, 'products', []);
  187. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  188. if (!is_array($extra_products)) {
  189. Utils::throwError('20003:传入的资产格式不正确');
  190. }
  191. // 替换美术风格
  192. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  193. // 提取文件内容
  194. if ($file) {
  195. $content = $this->DeepSeekService->extractFileContent($file);
  196. if (!$content) {
  197. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  198. }
  199. } elseif ($script_id) {
  200. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  201. if (!$content) {
  202. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  203. }
  204. } elseif ($bid) {
  205. $content = $this->DeepSeekService->getContentByBid($bid);
  206. if (!$content) {
  207. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  208. }
  209. } elseif ($content) {
  210. $content = filterContent($content);
  211. }else {
  212. $content = '';
  213. }
  214. $anime_data = [
  215. 'user_id' => $uid,
  216. 'anime_name' => '新剧本策划',
  217. 'is_multi' => getProp($data, 'is_multi', 1),
  218. 'content' => $content,
  219. 'art_style_type' => $input_art_style,
  220. 'ace_mode' => $ace_mode,
  221. 'script_id' => $script_id,
  222. 'extra_products' => json_encode($extra_products, 256),
  223. 'created_at' => date('Y-m-d H:i:s'),
  224. 'updated_at' => date('Y-m-d H:i:s'),
  225. ];
  226. // 处理文本模型
  227. $model = getProp($data, 'model');
  228. if (!$model) {
  229. // 用户没有输入,使用默认值
  230. $model = 'doubao-seed-2-0-mini-260215';
  231. }
  232. // 验证模型是否在可用模型表中
  233. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  234. $model = 'doubao-seed-2-0-mini-260215';
  235. }
  236. $anime_data['model'] = $model;
  237. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  238. return DB::table('mp_animes')->insertGetId($anime_data);
  239. }
  240. public function chatList($data) {
  241. $uid = Site::getUid();
  242. $anime_name = getProp($data, 'anime_name');
  243. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  244. if ($anime_name) {
  245. $query->where('anime_name', 'like', "%$anime_name%");
  246. }
  247. return $query->orderBy('id', 'desc')->paginate();
  248. }
  249. public function chatHistory($data) {
  250. $anime_id = getProp($data, 'anime_id');
  251. $sequence = getProp($data, 'sequence', 0);
  252. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  253. $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)
  254. ->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');
  255. return $query->orderBy('ar.id')->get()->map(function ($value) {
  256. $value = (array)$value;
  257. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  258. $value['created_at'] = transDate($value['created_at']);
  259. $value['episode_created_at'] = transDate($value['episode_created_at']);
  260. return $value;
  261. })->toArray();
  262. }
  263. public function batchSetRoleImg($data) {
  264. $episode_id = getProp($data, 'episode_id');
  265. if (!$episode_id) Utils::throwError('1002:请选择分集');
  266. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  267. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  268. $art_style = getProp($episode, 'art_style');
  269. $anime_id = getProp($episode, 'anime_id');
  270. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  271. $art_style_type = getProp($anime, 'art_style_type');
  272. $character_prefix = '';
  273. $scene_prefix = '';
  274. if ($art_style_type) {
  275. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  276. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  277. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  278. }
  279. foreach ($roles as &$role) {
  280. $role_name = getProp($role, 'role');
  281. if ($role_name == '旁白') continue;
  282. // 优先使用 pic_prompt,如果没有则使用 description
  283. $pic_prompt = getProp($role, 'pic_prompt');
  284. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  285. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  286. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  287. // 参考图地址
  288. $ref_img_url = getProp($role, 'url');
  289. if ($ref_img_url) continue; // 已有图片则跳过
  290. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  291. try {
  292. $params = [
  293. 'prompt' => $description,
  294. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  295. ];
  296. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  297. $task_id = $task->id;
  298. if (!$task_id) {
  299. Utils::throwError("20003:角色({$role_name})生成图片失败");
  300. }
  301. $role['task_id'] = $task_id;
  302. $role['task_status'] = 'processing';
  303. } catch (\Exception $e) {
  304. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  305. Utils::throwError("20003:" . $e->getMessage());
  306. }
  307. }
  308. // 保存角色信息
  309. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  310. 'roles' => json_encode($roles, 256),
  311. 'generate_status' => '执行中',
  312. 'generate_at' => date('Y-m-d H:i:s'),
  313. 'updated_at' => date('Y-m-d H:i:s')
  314. ]);
  315. if (!$boolen) {
  316. Utils::throwError('20003:保存角色信息失败');
  317. }
  318. return $boolen;
  319. }
  320. public function batchSetSceneImg($data) {
  321. $episode_id = getProp($data, 'episode_id');
  322. if (!$episode_id) Utils::throwError('1002:请选择分集');
  323. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  324. $scenes = json_decode(getProp($episode, 'scenes'), true);
  325. $art_style = getProp($episode, 'art_style');
  326. $target_scene = getProp($data, 'target_scene');
  327. $anime_id = getProp($episode, 'anime_id');
  328. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  329. $art_style_type = getProp($anime, 'art_style_type');
  330. $character_prefix = '';
  331. $scene_prefix = '';
  332. if ($art_style_type) {
  333. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  334. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  335. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  336. }
  337. foreach ($scenes as &$scene) {
  338. $scene_name = getProp($scene, 'scene');
  339. if ($scene_name != $target_scene) continue;
  340. // 优先使用 pic_prompt,如果没有则使用 description
  341. $pic_prompt = getProp($scene, 'pic_prompt');
  342. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  343. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  344. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  345. // 参考图地址
  346. $ref_img_url = getProp($scene, 'url');
  347. if ($ref_img_url) continue; // 已有图片则跳过
  348. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  349. try {
  350. $params = [
  351. 'prompt' => $description,
  352. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  353. ];
  354. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  355. $task_id = $task->id;
  356. if (!$task_id) {
  357. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  358. }
  359. $scene['task_id'] = $task_id;
  360. $scene['task_status'] = 'processing';
  361. } catch (\Exception $e) {
  362. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  363. Utils::throwError("20003:" . $e->getMessage());
  364. }
  365. }
  366. // 保存场景信息
  367. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  368. 'scenes' => json_encode($scenes, 256),
  369. 'generate_status' => '执行中',
  370. 'generate_at' => date('Y-m-d H:i:s'),
  371. 'updated_at' => date('Y-m-d H:i:s')
  372. ]);
  373. if (!$boolen) {
  374. Utils::throwError('20003:保存角色信息失败');
  375. }
  376. return $boolen;
  377. }
  378. public function editAnime($data) {
  379. $anime_id = getProp($data, 'anime_id');
  380. $anime_name = trim(getProp($data, 'anime_name'));
  381. // 确认对话名称唯一性
  382. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  383. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  384. }
  385. if (!$anime_id || !$anime_name) {
  386. Utils::throwError('20003:参数异常');
  387. }
  388. return DB::table('mp_animes')->where('id', $anime_id)->update([
  389. 'anime_name' => $anime_name,
  390. 'updated_at' => date('Y-m-d H:i:s')
  391. ]);
  392. // $script_arr =getProp($data, 'script', []);
  393. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  394. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  395. // $anime_id = getProp($data, 'anime_id');
  396. // try {
  397. // DB::beginTransaction();
  398. // $table_data = [
  399. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  400. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  401. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  402. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  403. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  404. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  405. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  406. // 'status' => 3,
  407. // 'start_episode_sequence' => $start_episode_sequence,
  408. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  409. // 'episode_num' => count($script_arr['episodes']),
  410. // 'updated_at' => date('Y-m-d H:i:s')
  411. // ];
  412. // // 保存剧本内容
  413. // if (!empty($anime_id)) {
  414. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  415. // if (!$boolen) {
  416. // dLog('anime')->info('对话保存失败', $table_data);
  417. // Utils::throwError('20003:对话保存失败');
  418. // }
  419. // }else {
  420. // $table['created_at'] = $table_data['updated_at'];
  421. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  422. // if (!$anime_id) {
  423. // dLog('anime')->info('对话保存失败', $table_data);
  424. // Utils::throwError('20003:对话保存失败');
  425. // }
  426. // }
  427. // // 保存分集内容
  428. // // 删除历史分集内容
  429. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  430. // $episodes = [];
  431. // $sequence = 1;
  432. // foreach ($script_arr['episodes'] as $episode) {
  433. // $segment_number = 1;
  434. // foreach($episode['segments'] as $segment) {
  435. // $episodes[] = [
  436. // 'anime_id' => $anime_id,
  437. // 'episode_number' => $episode['episode_number'],
  438. // 'title' => $episode['title'],
  439. // // 'content' => $episode['content'],
  440. // 'content' => '',
  441. // 'segment_number' => $segment_number,
  442. // 'segment_content' => $segment['segment_content'],
  443. // 'sequence' => $sequence,
  444. // 'created_at' => date('Y-m-d H:i:s'),
  445. // 'updated_at' => date('Y-m-d H:i:s')
  446. // ];
  447. // $sequence++;
  448. // $segment_number++;
  449. // }
  450. // }
  451. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  452. // if (!$boolen2) {
  453. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  454. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  455. // Utils::throwError('20003:分集内容保存失败');
  456. // }
  457. // } catch (\Exception $e) {
  458. // DB::rollBack();
  459. // Utils::throwError('20003:'.$e->getMessage());
  460. // }
  461. // DB::commit();
  462. // return true;
  463. }
  464. public function delAnime($data) {
  465. $anime_id = getProp($data, 'anime_id');
  466. if (!$anime_id) {
  467. Utils::throwError('20003:请选择剧本');
  468. }
  469. return DB::table('mp_animes')->where('id', $anime_id)->update([
  470. 'is_deleted' => 1,
  471. 'updated_at' => date('Y-m-d H:i:s')
  472. ]);
  473. }
  474. public function animeDetail($data) {
  475. $uid = Site::getUid();
  476. $anime_id = getProp($data, 'anime_id');
  477. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  478. ->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')->first();
  479. if (!$anime) Utils::throwError('20003:权限不足');
  480. $anime = (array)$anime;
  481. $anime['roles'] = json_decode($anime['roles']);
  482. $anime['scenes'] = json_decode($anime['scenes']);
  483. // 获取分集信息
  484. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  485. ->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"))
  486. ->orderBy('episode_number')->get()->map(function ($value) {
  487. return (array)$value;
  488. })->toArray();
  489. $anime['episodes'] = $episodes;
  490. return $anime;
  491. }
  492. public function episodeInfo($data) {
  493. $uid = Site::getUid();
  494. $anime_id = getProp($data, 'anime_id');
  495. $episode_id = getProp($data, 'episode_id');
  496. if (!$anime_id || !$episode_id) {
  497. Utils::throwError('1002:请选择剧集');
  498. }
  499. // 验证用户权限
  500. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  501. if (!$anime) Utils::throwError('20003:权限不足');
  502. $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();
  503. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  504. $episode = (array)$episode;
  505. $episode['roles'] = json_decode($episode['roles'], true);
  506. // foreach($episode['roles'] as &$item) {
  507. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  508. // }
  509. $episode['scenes'] = json_decode($episode['scenes'], true);
  510. // foreach($episode['scenes'] as &$item) {
  511. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  512. // }
  513. // 获取分镜信息
  514. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  515. ->select('*')->get()->map(function ($value) {
  516. return (array)$value;
  517. })->toArray();
  518. // 使用公共方法构建分镜结构
  519. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  520. $episode['acts'] = $segmentsStructure['acts'];
  521. $episode['total_duration'] = $segmentsStructure['total_duration'];
  522. return $episode;
  523. }
  524. public function episodeInfoForAce($data) {
  525. $anime_id = getProp($data, 'anime_id');
  526. $episode_id = getProp($data, 'episode_id');
  527. if (!$anime_id || !$episode_id) {
  528. Utils::throwError('1002:请选择剧集');
  529. }
  530. $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();
  531. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  532. $episode = (array)$episode;
  533. $episode['roles'] = json_decode($episode['roles'], true);
  534. // foreach($episode['roles'] as &$item) {
  535. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  536. // }
  537. $episode['scenes'] = json_decode($episode['scenes'], true);
  538. // foreach($episode['scenes'] as &$item) {
  539. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  540. // }
  541. // 获取分镜信息
  542. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  543. ->select('*')->get()->map(function ($value) {
  544. return (array)$value;
  545. })->toArray();
  546. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  547. $episode['acts'] = $segmentsStructure['acts'];
  548. $episode['total_duration'] = $segmentsStructure['total_duration'];
  549. return $episode;
  550. }
  551. public function segmentInfo($data) {
  552. $uid = Site::getUid();
  553. $segment_id = getProp($data, 'segment_id');
  554. if (!$segment_id) {
  555. Utils::throwError('1002:请选择分镜');
  556. }
  557. // 获取分镜信息
  558. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  559. // 验证用户权限
  560. if ($segment) {
  561. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  562. if (!$anime) Utils::throwError('20003:权限不足');
  563. }
  564. $result = [
  565. 'segment_id' => getProp($segment, 'segment_id'),
  566. 'segment_number' => getProp($segment, 'segment_number'),
  567. 'segment_content' => getProp($segment, 'segment_content'),
  568. 'description' => getProp($segment, 'description'),
  569. 'composition' => getProp($segment, 'composition'),
  570. 'camera_movement' => getProp($segment, 'camera_movement'),
  571. 'voice_actor' => getProp($segment, 'voice_actor'),
  572. 'dialogue' => getProp($segment, 'dialogue'),
  573. 'frame_type' => getProp($segment, 'frame_type'),
  574. 'scene' => getProp($segment, 'scene'),
  575. 'characters' => getProp($segment, 'characters'),
  576. 'tail_frame' => getProp($segment, 'tail_frame'),
  577. 'emotion' => getProp($segment, 'emotion'),
  578. 'emotion_type' => getProp($segment, 'emotion_type'),
  579. 'gender' => getProp($segment, 'gender'),
  580. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  581. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  582. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  583. 'pitch' => getProp($segment, 'pitch'),
  584. 'voice_name' => getProp($segment, 'voice_name'),
  585. 'voice_type' => getProp($segment, 'voice_type'),
  586. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  587. 'img_url' => getProp($segment, 'img_url'),
  588. 'video_url' => getProp($segment, 'video_url'),
  589. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  590. ];
  591. return $result;
  592. }
  593. public function copyEpisodeVersion($data) {
  594. $episode_id = getProp($data, 'episode_id');
  595. $uid = Site::getUid();
  596. $cpid = Site::getCpid();
  597. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  598. if (!$episode) Utils::throwError('20003:该剧集不存在');
  599. $episode = (array)$episode;
  600. $anime_id = $episode['anime_id'];
  601. $episode_number = $episode['episode_number'];
  602. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  603. $sequence = $count + 1;
  604. unset($episode['id']);
  605. $now = date('Y-m-d H:i:s');
  606. $episode['created_at'] = $now;
  607. $episode['updated_at'] = $now;
  608. $episode['is_default'] = 1;
  609. // 获取版本中含有"(副本"字样的个数
  610. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  611. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  612. $episode['sequence'] = $sequence;
  613. $episode['is_generated'] = 0;
  614. $episode['cpid'] = $cpid;
  615. // 获取ace_mode
  616. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  617. try {
  618. DB::beginTransaction();
  619. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  620. // 新增副本
  621. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  622. if (!$new_episode_id) {
  623. Utils::throwError('20003:创建副本失败!');
  624. }
  625. // 获取分镜数据并准备插入
  626. $segments_for_insert = DB::table('mp_episode_segments')
  627. ->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')
  628. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  629. $item = (array)$item;
  630. $item['episode_id'] = $new_episode_id;
  631. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  632. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  633. return $item;
  634. })->toArray();
  635. // 写入分镜数据
  636. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  637. if (!$boolen2) {
  638. Utils::throwError('20003:写入分镜数据失败!');
  639. }
  640. // 写入对话历史
  641. $records = [
  642. [
  643. 'uid' => $uid,
  644. 'anime_id' => $anime_id,
  645. 'role' => 'user',
  646. 'content' => '创建副本',
  647. 'sequence' => $episode_number,
  648. 'episode_id' => $new_episode_id,
  649. 'created_at' => $now,
  650. 'updated_at' => $now
  651. ],
  652. [
  653. 'uid' => $uid,
  654. 'anime_id' => $anime_id,
  655. 'role' => 'assistant',
  656. 'content' => '好的,已为您创建副本',
  657. 'sequence' => $episode_number,
  658. 'episode_id' => $new_episode_id,
  659. 'created_at' => $now,
  660. 'updated_at' => $now
  661. ]
  662. ];
  663. $boolen3 = DB::table('mp_anime_records')->insert($records);
  664. if (!$boolen3) {
  665. Utils::throwError('20003:对话记录保存失败');
  666. }
  667. }catch (\Exception $e) {
  668. DB::rollBack();
  669. Utils::throwError('20003:'.$e->getMessage());
  670. }
  671. DB::commit();
  672. // 构建与 episodeInfo 方法一致的返回数据结构
  673. $result = [
  674. 'episode_id' => $new_episode_id,
  675. 'anime_id' => $anime_id,
  676. 'episode_number' => $episode_number,
  677. 'title' => $episode['title'],
  678. 'intro' => $episode['intro'],
  679. 'art_style' => $episode['art_style'],
  680. 'roles' => json_decode($episode['roles'], true),
  681. 'scenes' => json_decode($episode['scenes'], true),
  682. 'is_generated' => (int)$episode['is_generated']
  683. ];
  684. if ((int)$ace_mode === 1) {
  685. // 获取分镜信息
  686. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  687. ->select('*')->get()->map(function ($value) {
  688. return (array)$value;
  689. })->toArray();
  690. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  691. }else {
  692. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  693. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  694. }
  695. $result['acts'] = $segmentsStructure['acts'];
  696. $result['total_duration'] = $segmentsStructure['total_duration'];
  697. return $result;
  698. }
  699. public function episodeVersions($data) {
  700. $anime_id = getProp($data, 'anime_id');
  701. $episode_id = getProp($data, 'episode_id');
  702. if (!$anime_id || !$episode_id) {
  703. Utils::throwError('1002:请选择剧集');
  704. }
  705. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  706. $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) {
  707. return (array)$value;
  708. })->toArray();
  709. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  710. foreach($episodes as &$episode) {
  711. $episode['version'] = 'V'.$episode['sequence'];
  712. $episode['roles'] = json_decode($episode['roles'], true);
  713. $episode['scenes'] = json_decode($episode['scenes'], true);
  714. // 获取分镜信息
  715. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  716. ->select('*')->get()->map(function ($value) {
  717. return (array)$value;
  718. })->toArray();
  719. // 使用公共方法构建分镜结构
  720. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  721. $episode['acts'] = $segmentsStructure['acts'];
  722. $episode['total_duration'] = $segmentsStructure['total_duration'];
  723. }
  724. return $episodes;
  725. }
  726. public function bindEpisodeVersion($data) {
  727. $episode_id = getProp($data, 'episode_id');
  728. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  729. if (!$episode) Utils::throwError('20003:该剧集不存在');
  730. $episode = (array)$episode;
  731. if ((int)$episode['is_default'] === 1) return true;
  732. try {
  733. DB::beginTransaction();
  734. // 移除is_default标志
  735. $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')]);
  736. if (!$boolen) {
  737. Utils::throwError('20003:更新失败!');
  738. }
  739. // 绑定副本
  740. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  741. if (!$boolen2) {
  742. Utils::throwError('20003:绑定失败!');
  743. }
  744. }catch (\Exception $e) {
  745. DB::rollBack();
  746. Utils::throwError('20003:'.$e->getMessage());
  747. }
  748. DB::commit();
  749. return true;
  750. }
  751. public function chatChangeImg($data) {
  752. $segment_id = getProp($data, 'segment_id');
  753. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  754. $prompt = getProp($data, 'prompt');
  755. if (!$prompt || !$segment_id) {
  756. Utils::throwError('1002:请输入提示词,并且选择分镜');
  757. }
  758. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  759. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  760. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  761. else $ref_img_url = '';
  762. // $ref_img_url = '';
  763. if (empty($prompt)) {
  764. if (empty($ref_img_url)) {
  765. $prompt = getProp($segment, 'segment_content');
  766. }else {
  767. $prompt = '请根据图片生成';
  768. }
  769. }
  770. $anime_id = getProp($segment, 'anime_id');
  771. $episode_id = getProp($segment, 'episode_id');
  772. $episode_number = getProp($segment, 'episode_number');
  773. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  774. $ratio = getProp($data, 'ratio');
  775. if (!$ratio) {
  776. $ratio = getProp($episode, 'ratio');
  777. if (!$ratio) $ratio = '9:16';
  778. }
  779. $art_style = getProp($episode, 'art_style');
  780. if ($art_style) {
  781. $prompt = "美术风格:{$art_style}\n{$prompt}";
  782. }
  783. $dimensions = $this->getRatioDimensions($ratio);
  784. $width = $dimensions['width'];
  785. $height = $dimensions['height'];
  786. try {
  787. $params = [
  788. 'alias_segment_id' => $segment_id,
  789. 'prompt' => $prompt,
  790. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  791. 'width' => $width,
  792. 'height' => $height
  793. ];
  794. // 优化提示词(不要生成字幕)
  795. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  796. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  797. $task_id = $task->id;
  798. if (!$task_id) {
  799. Utils::throwError("20003:生成图片失败");
  800. }
  801. // 更新任务ID
  802. $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')]);
  803. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  804. } catch (\Exception $e) {
  805. Utils::throwError("20003:" . $e->getMessage());
  806. }
  807. // 创建任务之后先暂停10s等待异步任务完成
  808. sleep(10);
  809. $img_url = $this->loopGetPicTaskResult($task_id);
  810. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  811. // 图片生成后新增对话记录
  812. try {
  813. $uid = Site::getUid();
  814. $now = date('Y-m-d H:i:s');
  815. // 使用AI反推图片提示词
  816. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  817. // 保存对话记录
  818. $records = [
  819. [
  820. 'uid' => $uid,
  821. 'anime_id' => $anime_id,
  822. 'sequence' => $episode_number,
  823. 'role' => 'user',
  824. 'content' => $prompt,
  825. 'segment_id' => $segment_id,
  826. 'image_url' => '',
  827. 'created_at' => $now,
  828. 'updated_at' => $now
  829. ],
  830. [
  831. 'uid' => $uid,
  832. 'anime_id' => $anime_id,
  833. 'sequence' => $episode_number,
  834. 'role' => 'assistant',
  835. 'content' => $pic_prompt,
  836. 'segment_id' => $segment_id,
  837. 'image_url' => $img_url,
  838. 'created_at' => $now,
  839. 'updated_at' => $now
  840. ]
  841. ];
  842. DB::table('mp_anime_records')->insert($records);
  843. } catch (\Exception $e) {
  844. // 记录日志但不影响主流程
  845. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  846. 'segment_id' => $segment_id,
  847. 'img_url' => $img_url
  848. ]);
  849. logDB('anime', 'error', '保存对话记录失败', [
  850. 'segment_id' => $segment_id,
  851. 'img_url' => $img_url,
  852. 'error' => $e->getMessage()
  853. ]);
  854. }
  855. return $img_url;
  856. }
  857. public function segmentChatHistory($data) {
  858. $segment_id = getProp($data, 'segment_id');
  859. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  860. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
  861. $chat = $query->orderBy('id')->get()->map(function ($value) {
  862. $value = (array)$value;
  863. $value['created_at'] = transDate($value['created_at']);
  864. return $value;
  865. })->toArray();
  866. // 获取历史图片
  867. $url = [];
  868. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  869. foreach($pic_history as $task) {
  870. $result_url = getProp($task, 'result_url');
  871. if (is_json($result_url)) {
  872. $url = array_merge($url, json_decode($result_url, true));
  873. }else {
  874. $url[] = $result_url;
  875. }
  876. }
  877. // 获取历史视频
  878. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  879. foreach($video_history as $task) {
  880. $result_url = getProp($task, 'compressed_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. return compact('chat', 'url');
  888. }
  889. public function changeEpisodeRoles($data) {
  890. $anime_id = getProp($data, 'anime_id');
  891. $episode_id = getProp($data, 'episode_id');
  892. $target_roles = getProp($data, 'roles');
  893. $is_deleted = getProp($data, 'is_deleted', 0);
  894. // 参数验证
  895. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  896. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  897. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  898. // 验证剧集是否存在
  899. $episode = DB::table('mp_anime_episodes')
  900. ->where('anime_id', $anime_id)
  901. ->where('id', $episode_id)
  902. ->first();
  903. if (!$episode) Utils::throwError('20003:该剧集不存在');
  904. $roles = json_decode(getProp($episode, 'roles'), true);
  905. // 获取anime信息,检查是否有关联的script_id
  906. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  907. if (!$anime) Utils::throwError('20003:动漫不存在');
  908. $script_id = getProp($anime, 'script_id');
  909. $episode_number = getProp($episode, 'episode_number', 1);
  910. $uid = Site::getUid();
  911. $cpid = Site::getCpid();
  912. try {
  913. $target_role_name = getProp($target_roles, 'role');
  914. // 如果是删除操作
  915. if ($is_deleted == 1) {
  916. // 从角色列表中移除该角色
  917. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  918. return getProp($role, 'role') !== $target_role_name;
  919. }));
  920. // 更新角色列表
  921. $result = DB::table('mp_anime_episodes')
  922. ->where('anime_id', $anime_id)
  923. ->where('id', $episode_id)
  924. ->update([
  925. 'roles' => json_encode($roles, 256),
  926. 'updated_at' => date('Y-m-d H:i:s')
  927. ]);
  928. if ($result === false) {
  929. Utils::throwError('20003:删除角色失败');
  930. }
  931. } else {
  932. // 新增或更新操作
  933. $role_found = false;
  934. $is_new_role = false;
  935. // 查找并更新已存在的角色
  936. foreach($roles as &$role) {
  937. if (getProp($role, 'role') === $target_role_name) {
  938. $role = $target_roles;
  939. $role_found = true;
  940. break;
  941. }
  942. }
  943. // 如果角色不存在,则新增
  944. if (!$role_found) {
  945. $roles[] = $target_roles;
  946. $is_new_role = true;
  947. }
  948. // 更新角色列表
  949. $result = DB::table('mp_anime_episodes')
  950. ->where('anime_id', $anime_id)
  951. ->where('id', $episode_id)
  952. ->update([
  953. 'roles' => json_encode($roles, 256),
  954. 'updated_at' => date('Y-m-d H:i:s')
  955. ]);
  956. if ($result === false) {
  957. Utils::throwError('20003:更新角色列表失败');
  958. }
  959. // 同步更新分镜表中对应主体的音色信息
  960. $voice_name = getProp($target_roles, 'voice_name');
  961. $voice_type = getProp($target_roles, 'voice_type');
  962. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  963. DB::table('mp_episode_segments')
  964. ->where('anime_id', $anime_id)
  965. ->where('episode_id', $episode_id)
  966. ->where('voice_actor', $target_role_name)
  967. ->update([
  968. 'voice_name' => $voice_name,
  969. 'voice_type' => $voice_type,
  970. 'voice_audio_url' => $voice_audio_url,
  971. 'updated_at' => date('Y-m-d H:i:s')
  972. ]);
  973. // 如果有关联的script_id,则同步到mp_products表
  974. if ($script_id) {
  975. // 查询剧本信息
  976. $script = DB::table('mp_scripts')
  977. ->where('id', $script_id)
  978. ->where('is_deleted', 0)
  979. ->first();
  980. if ($script) {
  981. $script_name = $script->script_name ?? 'script_' . $script_id;
  982. $product_name = getProp($target_roles, 'role');
  983. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  984. $url = getProp($target_roles, 'url', '');
  985. $product_type = 1; // 1=角色
  986. // 查找或创建以script_name命名的文件夹
  987. $folder = DB::table('mp_products')
  988. ->where('cpid', $cpid)
  989. ->where('type', 2) // 文件夹类型
  990. ->where('product', $product_type) // 角色类型
  991. ->where('product_name', $script_name)
  992. ->where('parent_id', 0)
  993. ->where('is_deleted', 0)
  994. ->first();
  995. if (!$folder) {
  996. // 创建文件夹
  997. $folder_id = DB::table('mp_products')->insertGetId([
  998. 'user_id' => $uid,
  999. 'cpid' => $cpid,
  1000. 'type' => 2, // 文件夹
  1001. 'product' => $product_type, // 角色类型
  1002. 'parent_id' => 0,
  1003. 'level' => 1,
  1004. 'product_name' => $script_name,
  1005. 'sort_order' => time(),
  1006. 'is_deleted' => 0,
  1007. 'created_at' => date('Y-m-d H:i:s'),
  1008. 'updated_at' => date('Y-m-d H:i:s')
  1009. ]);
  1010. } else {
  1011. $folder_id = $folder->id;
  1012. }
  1013. // 查找该文件夹下是否已存在同名资产
  1014. $existing_product = DB::table('mp_products')
  1015. ->where('cpid', $cpid)
  1016. ->where('type', 1) // 资产类型
  1017. ->where('product', $product_type)
  1018. ->where('parent_id', $folder_id)
  1019. ->where('product_name', $product_name)
  1020. ->where('is_deleted', 0)
  1021. ->first();
  1022. if ($existing_product) {
  1023. // 更新已存在的资产
  1024. $updateData = [
  1025. 'pic_task_status' => '生成成功',
  1026. ];
  1027. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1028. if ($url) $updateData['url'] = $url;
  1029. // 处理versions字段
  1030. $versions = getProp($target_roles, 'versions', []);
  1031. if ($versions && is_array($versions)) {
  1032. $updateData['versions'] = json_encode($versions, 256);
  1033. }
  1034. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1035. DB::table('mp_products')
  1036. ->where('id', $existing_product->id)
  1037. ->update($updateData);
  1038. $product_id = $existing_product->id;
  1039. } else {
  1040. // 创建新资产
  1041. $versions = getProp($target_roles, 'versions', []);
  1042. $product_id = DB::table('mp_products')->insertGetId([
  1043. 'user_id' => $uid,
  1044. 'cpid' => $cpid,
  1045. 'type' => 1, // 资产
  1046. 'product' => $product_type, // 角色
  1047. 'parent_id' => $folder_id,
  1048. 'level' => 2,
  1049. 'product_name' => $product_name,
  1050. 'url' => $url,
  1051. 'pic_prompt' => $pic_prompt,
  1052. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1053. 'sort_order' => time(),
  1054. 'is_deleted' => 0,
  1055. 'pic_task_status' => '生成成功',
  1056. 'created_at' => date('Y-m-d H:i:s'),
  1057. 'updated_at' => date('Y-m-d H:i:s')
  1058. ]);
  1059. }
  1060. // 建立或更新绑定关系
  1061. $existing_mapping = DB::table('mp_script_product_mappings')
  1062. ->where('script_id', $script_id)
  1063. ->where('product_id', $product_id)
  1064. ->where('episode_number', $episode_number)
  1065. ->first();
  1066. if (!$existing_mapping) {
  1067. // 创建绑定关系
  1068. DB::table('mp_script_product_mappings')->insert([
  1069. 'script_id' => $script_id,
  1070. 'product_id' => $product_id,
  1071. 'episode_number' => $episode_number,
  1072. 'created_at' => date('Y-m-d H:i:s'),
  1073. 'updated_at' => date('Y-m-d H:i:s')
  1074. ]);
  1075. }
  1076. }
  1077. }
  1078. }
  1079. } catch (\Exception $e) {
  1080. dLog('anime')->error('更新剧集角色失败', [
  1081. 'anime_id' => $anime_id,
  1082. 'episode_id' => $episode_id,
  1083. 'error' => $e->getMessage()
  1084. ]);
  1085. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1086. }
  1087. return true;
  1088. }
  1089. public function changeEpisodeScenes($data) {
  1090. $anime_id = getProp($data, 'anime_id');
  1091. $episode_id = getProp($data, 'episode_id');
  1092. $target_scenes = getProp($data, 'scenes');
  1093. $is_deleted = getProp($data, 'is_deleted', 0);
  1094. // 参数验证
  1095. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1096. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1097. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1098. // 验证剧集是否存在
  1099. $episode = DB::table('mp_anime_episodes')
  1100. ->where('anime_id', $anime_id)
  1101. ->where('id', $episode_id)
  1102. ->first();
  1103. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1104. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1105. // 获取anime信息,检查是否有关联的script_id
  1106. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1107. if (!$anime) Utils::throwError('20003:动漫不存在');
  1108. $script_id = getProp($anime, 'script_id');
  1109. $episode_number = getProp($episode, 'episode_number', 1);
  1110. $uid = Site::getUid();
  1111. $cpid = Site::getCpid();
  1112. try {
  1113. $target_scene_name = getProp($target_scenes, 'scene');
  1114. // 如果是删除操作
  1115. if ($is_deleted == 1) {
  1116. // 从场景列表中移除该场景
  1117. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1118. return getProp($scene, 'scene') !== $target_scene_name;
  1119. }));
  1120. // 更新场景列表
  1121. $result = DB::table('mp_anime_episodes')
  1122. ->where('anime_id', $anime_id)
  1123. ->where('id', $episode_id)
  1124. ->update([
  1125. 'scenes' => json_encode($scenes, 256),
  1126. 'updated_at' => date('Y-m-d H:i:s')
  1127. ]);
  1128. if ($result === false) {
  1129. Utils::throwError('20003:删除场景失败');
  1130. }
  1131. } else {
  1132. // 新增或更新操作
  1133. $scene_found = false;
  1134. $is_new_scene = false;
  1135. // 查找并更新已存在的场景
  1136. foreach($scenes as &$scene) {
  1137. if (getProp($scene, 'scene') === $target_scene_name) {
  1138. $scene = $target_scenes;
  1139. $scene_found = true;
  1140. break;
  1141. }
  1142. }
  1143. // 如果场景不存在,则新增
  1144. if (!$scene_found) {
  1145. $scenes[] = $target_scenes;
  1146. $is_new_scene = true;
  1147. }
  1148. // 更新场景列表
  1149. $result = DB::table('mp_anime_episodes')
  1150. ->where('anime_id', $anime_id)
  1151. ->where('id', $episode_id)
  1152. ->update([
  1153. 'scenes' => json_encode($scenes, 256),
  1154. 'updated_at' => date('Y-m-d H:i:s')
  1155. ]);
  1156. if ($result === false) {
  1157. Utils::throwError('20003:更新场景列表失败');
  1158. }
  1159. // 如果有关联的script_id,则同步到mp_products表
  1160. if ($script_id) {
  1161. // 查询剧本信息
  1162. $script = DB::table('mp_scripts')
  1163. ->where('id', $script_id)
  1164. ->where('is_deleted', 0)
  1165. ->first();
  1166. if ($script) {
  1167. $script_name = $script->script_name ?? 'script_' . $script_id;
  1168. $product_name = getProp($target_scenes, 'scene');
  1169. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1170. $url = getProp($target_scenes, 'url', '');
  1171. $product_type = 2; // 2=场景
  1172. // 查找或创建以script_name命名的文件夹
  1173. $folder = DB::table('mp_products')
  1174. ->where('cpid', $cpid)
  1175. ->where('type', 2) // 文件夹类型
  1176. ->where('product', $product_type) // 场景类型
  1177. ->where('product_name', $script_name)
  1178. ->where('parent_id', 0)
  1179. ->where('is_deleted', 0)
  1180. ->first();
  1181. if (!$folder) {
  1182. // 创建文件夹
  1183. $folder_id = DB::table('mp_products')->insertGetId([
  1184. 'user_id' => $uid,
  1185. 'cpid' => $cpid,
  1186. 'type' => 2, // 文件夹
  1187. 'product' => $product_type, // 场景类型
  1188. 'parent_id' => 0,
  1189. 'level' => 1,
  1190. 'product_name' => $script_name,
  1191. 'sort_order' => time(),
  1192. 'is_deleted' => 0,
  1193. 'created_at' => date('Y-m-d H:i:s'),
  1194. 'updated_at' => date('Y-m-d H:i:s')
  1195. ]);
  1196. } else {
  1197. $folder_id = $folder->id;
  1198. }
  1199. // 查找该文件夹下是否已存在同名资产
  1200. $existing_product = DB::table('mp_products')
  1201. ->where('cpid', $cpid)
  1202. ->where('type', 1) // 资产类型
  1203. ->where('product', $product_type)
  1204. ->where('parent_id', $folder_id)
  1205. ->where('product_name', $product_name)
  1206. ->where('is_deleted', 0)
  1207. ->first();
  1208. if ($existing_product) {
  1209. // 更新已存在的资产
  1210. $updateData = [
  1211. 'pic_task_status' => '生成成功'
  1212. ];
  1213. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1214. if ($url) $updateData['url'] = $url;
  1215. // 处理versions字段
  1216. $versions = getProp($target_scenes, 'versions', []);
  1217. if ($versions && is_array($versions)) {
  1218. $updateData['versions'] = json_encode($versions, 256);
  1219. }
  1220. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1221. DB::table('mp_products')
  1222. ->where('id', $existing_product->id)
  1223. ->update($updateData);
  1224. $product_id = $existing_product->id;
  1225. } else {
  1226. // 创建新资产
  1227. $versions = getProp($target_scenes, 'versions', []);
  1228. $product_id = DB::table('mp_products')->insertGetId([
  1229. 'user_id' => $uid,
  1230. 'cpid' => $cpid,
  1231. 'type' => 1, // 资产
  1232. 'product' => $product_type, // 场景
  1233. 'parent_id' => $folder_id,
  1234. 'level' => 2,
  1235. 'product_name' => $product_name,
  1236. 'url' => $url,
  1237. 'pic_prompt' => $pic_prompt,
  1238. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1239. 'sort_order' => time(),
  1240. 'is_deleted' => 0,
  1241. 'pic_task_status' => '生成成功',
  1242. 'created_at' => date('Y-m-d H:i:s'),
  1243. 'updated_at' => date('Y-m-d H:i:s')
  1244. ]);
  1245. }
  1246. // 建立或更新绑定关系
  1247. $existing_mapping = DB::table('mp_script_product_mappings')
  1248. ->where('script_id', $script_id)
  1249. ->where('product_id', $product_id)
  1250. ->where('episode_number', $episode_number)
  1251. ->first();
  1252. if (!$existing_mapping) {
  1253. // 创建绑定关系
  1254. DB::table('mp_script_product_mappings')->insert([
  1255. 'script_id' => $script_id,
  1256. 'product_id' => $product_id,
  1257. 'episode_number' => $episode_number,
  1258. 'created_at' => date('Y-m-d H:i:s'),
  1259. 'updated_at' => date('Y-m-d H:i:s')
  1260. ]);
  1261. }
  1262. }
  1263. }
  1264. }
  1265. } catch (\Exception $e) {
  1266. dLog('anime')->error('更新剧集场景失败', [
  1267. 'anime_id' => $anime_id,
  1268. 'episode_id' => $episode_id,
  1269. 'error' => $e->getMessage()
  1270. ]);
  1271. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1272. }
  1273. return true;
  1274. }
  1275. public function editSegment($data) {
  1276. $segment_id = getProp($data, 'segment_id');
  1277. $segment_content = getProp($data, 'segment_content');
  1278. $image_url = getProp($data, 'image_url');
  1279. $video_url = getProp($data, 'video_url');
  1280. // 参数验证
  1281. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1282. // 验证分镜是否存在
  1283. $segment = DB::table('mp_episode_segments')
  1284. ->where('segment_id', $segment_id)
  1285. ->first();
  1286. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1287. $dubTaskId = 0;
  1288. try {
  1289. DB::beginTransaction();
  1290. // 准备更新数据
  1291. $update_data = [
  1292. 'updated_at' => date('Y-m-d H:i:s')
  1293. ];
  1294. if ($segment_content) {
  1295. // 先将segment_content赋值到update_data
  1296. $update_data['segment_content'] = $segment_content;
  1297. // 使用现有方法分析segment_content,提取各个字段
  1298. $this->handleSegmentContent($update_data);
  1299. // 如果有对话内容,创建视频配音合成任务
  1300. $dialogue = getProp($update_data, 'dialogue');
  1301. if (!empty($dialogue)) {
  1302. $now = date('Y-m-d H:i:s');
  1303. $generate_json = [
  1304. 'text' => $dialogue,
  1305. 'role' => getProp($update_data, 'voice_actor'),
  1306. 'voice_type' => getProp($update_data, 'voice_type'),
  1307. 'voice_name' => getProp($update_data, 'voice_name'),
  1308. 'emotion' => getProp($update_data, 'emotion'),
  1309. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1310. 'gender' => getProp($update_data, 'gender'),
  1311. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1312. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1313. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1314. 'pitch' => getProp($update_data, 'pitch', 0),
  1315. ];
  1316. // 插入视频配音合成任务
  1317. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1318. 'alias_segment_id' => $segment_id,
  1319. 'generate_status' => '执行中',
  1320. 'audio_url' => '',
  1321. 'generate_json' => json_encode($generate_json, 256),
  1322. 'created_at' => $now,
  1323. 'updated_at' => $now,
  1324. ]);
  1325. if (!$dubTaskId) {
  1326. Utils::throwError('20003:创建配音任务失败!');
  1327. }
  1328. $update_data['audio_url'] = '';
  1329. } else {
  1330. // dialogue为空时,直接写入默认音频信息
  1331. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1332. $update_data['audio_duration'] = 2.0;
  1333. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1334. }
  1335. }
  1336. if ($image_url) {
  1337. $update_data['img_url'] = $image_url;
  1338. // 同时写入一个简单的图片生成任务
  1339. $pic_task = [
  1340. 'alias_segment_id' => $segment_id,
  1341. 'ref_img_url' => json_encode([]),
  1342. 'status' => 'success',
  1343. 'result_url' => json_encode([$image_url], 256),
  1344. 'model' => '',
  1345. 'created_at' => date('Y-m-d H:i:s'),
  1346. 'updated_at' => date('Y-m-d H:i:s'),
  1347. ];
  1348. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1349. }
  1350. if ($video_url) {
  1351. $update_data['origin_video_url'] = $video_url;
  1352. $compressed_video_url = compressVideo($video_url);
  1353. $update_data['current_type'] = 2;
  1354. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1355. // 同时写入一个简单的视频生成任务
  1356. $video_task = [
  1357. 'alias_segment_id' => $segment_id,
  1358. 'status' => 'success',
  1359. 'result_url' => $update_data['origin_video_url'],
  1360. 'compressed_url' => $update_data['video_url'],
  1361. 'created_at' => date('Y-m-d H:i:s'),
  1362. 'updated_at' => date('Y-m-d H:i:s'),
  1363. ];
  1364. DB::table('mp_generate_video_tasks')->insert($video_task);
  1365. }
  1366. // 更新分镜信息
  1367. $result = DB::table('mp_episode_segments')
  1368. ->where('segment_id', $segment_id)
  1369. ->update($update_data);
  1370. if ($result === false) {
  1371. Utils::throwError('20003:更新分镜剧本失败');
  1372. }
  1373. DB::commit();
  1374. // 如果有创建音频生成任务则调用API
  1375. if ($dubTaskId) {
  1376. // 请求远程服务器执行生成
  1377. $client = new Client(['timeout' => 300, 'verify' => false]);
  1378. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1379. $response = $result->getBody()->getContents();
  1380. $response_arr = json_decode($response, true);
  1381. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1382. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1383. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1384. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1385. Utils::throwError('20003:火山生成音频失败');
  1386. }
  1387. }
  1388. return true;
  1389. } catch (\Exception $e) {
  1390. DB::rollBack();
  1391. dLog('anime')->error('更新分镜剧本失败', [
  1392. 'segment_id' => $segment_id,
  1393. 'error' => $e->getMessage()
  1394. ]);
  1395. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1396. }
  1397. }
  1398. public function batchSetSegmentPics($data) {
  1399. $anime_id = getProp($data, 'anime_id');
  1400. $episode_id = getProp($data, 'episode_id');
  1401. $ratio = getProp($data, 'ratio');
  1402. $dimensions = $this->getRatioDimensions($ratio);
  1403. $width = $dimensions['width'];
  1404. $height = $dimensions['height'];
  1405. if (!$anime_id || !$episode_id) {
  1406. Utils::throwError('1002:请选择剧集');
  1407. }
  1408. // 获取剧集信息
  1409. $episode = DB::table('mp_anime_episodes')
  1410. ->where('anime_id', $anime_id)
  1411. ->where('id', $episode_id)
  1412. ->where('is_default', 1)
  1413. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1414. ->first();
  1415. if (!$episode) {
  1416. Utils::throwError('20003:该剧集不存在');
  1417. }
  1418. $model = getProp($data, 'model');
  1419. if (!$model) {
  1420. $model = getProp($episode, 'image_model');
  1421. if (!$model) {
  1422. // episode表也没有,使用默认值
  1423. $model = 'doubao-seedream-5-0-lite-260128';
  1424. }
  1425. }
  1426. // 验证模型是否在可用模型表中
  1427. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1428. $model = 'doubao-seedream-5-0-lite-260128';
  1429. }
  1430. $roles = json_decode(getProp($episode, 'roles'), true);
  1431. if (!$roles) {
  1432. Utils::throwError('20003:角色信息格式错误');
  1433. }
  1434. // 构建角色名称到参考图的映射
  1435. $role_map = [];
  1436. foreach ($roles as $role) {
  1437. $role_name = getProp($role, 'role');
  1438. $role_url = getProp($role, 'url');
  1439. if (!empty($role_name) && !empty($role_url)) {
  1440. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1441. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1442. // $role_map[$base_name] = $role_url;
  1443. // 同时保存完整名称的映射
  1444. $role_map[$role_name] = $role_url;
  1445. }
  1446. }
  1447. $scenes = json_decode(getProp($episode, 'roles'), true);
  1448. if (!$scenes) {
  1449. Utils::throwError('20003:场景信息格式错误');
  1450. }
  1451. // 构建角色名称到参考图的映射
  1452. $scene_map = [];
  1453. foreach ($scenes as $scene) {
  1454. $scene_name = getProp($scene, 'scene');
  1455. $scene_url = getProp($scene, 'url');
  1456. if (!empty($scene_name) && !empty($scene_url)) {
  1457. $scene_map[$scene_name] = $scene_url;
  1458. }
  1459. }
  1460. // 获取所有分镜信息
  1461. $segments = DB::table('mp_episode_segments')
  1462. ->where('anime_id', $anime_id)
  1463. ->where('episode_id', $episode_id)
  1464. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1465. ->orderBy('segment_number')
  1466. ->get()
  1467. ->toArray();
  1468. if (empty($segments)) {
  1469. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1470. }
  1471. // 保存图片比例
  1472. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1473. $updated_segments = [];
  1474. $failed_segments = [];
  1475. // 批量为每个分镜生成图片任务
  1476. foreach ($segments as $segment) {
  1477. $segment_id = $segment->segment_id;
  1478. $segment_content = $segment->segment_content;
  1479. if (empty($segment_content)) {
  1480. $failed_segments[] = [
  1481. 'segment_id' => $segment_id,
  1482. 'error' => '分镜内容为空'
  1483. ];
  1484. continue;
  1485. }
  1486. try {
  1487. $dubTaskId = 0;
  1488. // 解析分镜内容,提取画面描述作为主要提示词
  1489. $prompt = $segment_content;
  1490. $ref_img_urls = [];
  1491. // 分镜场景
  1492. $scene = getProp($segment, 'scene');
  1493. $matched_scene = '';
  1494. if (isset($scene_map[$scene])) {
  1495. $img_index = count($ref_img_urls) + 1;
  1496. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1497. $ref_img_urls[] = $scene_map[$scene];
  1498. $matched_scene = $scene;
  1499. }
  1500. // 分镜角色
  1501. $characters = getProp($segment, 'characters');
  1502. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1503. $roles = explode(',', $characters);
  1504. // 从分镜内容中提取涉及的角色
  1505. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1506. // 获取匹配角色的参考图
  1507. foreach ($segment_characters as $character) {
  1508. if (isset($role_map[$character])) {
  1509. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1510. $img_index = count($ref_img_urls) + 1;
  1511. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1512. $ref_img_urls[] = $role_map[$character];
  1513. }
  1514. }
  1515. // 如果没有找到匹配的角色参考图,不使用参考图
  1516. if (empty($ref_img_urls)) {
  1517. $ref_img_urls = [];
  1518. }
  1519. // 准备生成任务参数
  1520. $params = [
  1521. 'model' => $model,
  1522. 'alias_segment_id' => $segment_id,
  1523. 'prompt' => $prompt,
  1524. 'ref_img_urls' => $ref_img_urls,
  1525. 'width' => $width,
  1526. 'height' => $height,
  1527. ];
  1528. // 优化提示词(不要生成字幕)
  1529. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1530. // $task_id = mt_rand(100000, 999999);
  1531. // 调用AI图片生成服务
  1532. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1533. $task_id = $task->id;
  1534. if (!$task_id) {
  1535. $failed_segments[] = [
  1536. 'segment_id' => $segment_id,
  1537. 'error' => '创建生成任务失败'
  1538. ];
  1539. continue;
  1540. }
  1541. $update_data = [
  1542. 'pic_task_id' => $task_id,
  1543. 'pic_task_status' => '生成中',
  1544. 'audio_url' => '',
  1545. 'updated_at' => date('Y-m-d H:i:s')
  1546. ];
  1547. // 如果有对话内容,创建视频配音合成任务
  1548. $dialogue = getProp($segment, 'dialogue');
  1549. if (!empty($dialogue)) {
  1550. $now = date('Y-m-d H:i:s');
  1551. $generate_json = [
  1552. 'text' => $dialogue,
  1553. 'role' => getProp($segment, 'voice_actor'),
  1554. 'voice_type' => getProp($segment, 'voice_type'),
  1555. 'voice_name' => getProp($segment, 'voice_name'),
  1556. 'emotion' => getProp($segment, 'emotion'),
  1557. 'emotion_type' => getProp($segment, 'emotion_type'),
  1558. 'gender' => getProp($segment, 'gender'),
  1559. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1560. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1561. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1562. 'pitch' => getProp($segment, 'pitch', 0),
  1563. ];
  1564. // 插入视频配音合成任务
  1565. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1566. 'alias_segment_id' => $segment_id,
  1567. 'generate_status' => '执行中',
  1568. 'audio_url' => '',
  1569. 'generate_json' => json_encode($generate_json, 256),
  1570. 'created_at' => $now,
  1571. 'updated_at' => $now,
  1572. ]);
  1573. if (!$dubTaskId) {
  1574. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1575. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1576. // Utils::throwError('20003:创建配音任务失败!');
  1577. }
  1578. } else {
  1579. // dialogue为空时,直接写入默认音频信息到分镜表
  1580. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1581. $update_data['audio_duration'] = 2.0;
  1582. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1583. }
  1584. // 更新分镜的任务信息
  1585. $update_result = DB::table('mp_episode_segments')
  1586. ->where('segment_id', $segment_id)
  1587. ->update($update_data);
  1588. // 如果是第一集的首帧图片,则存入待更新数组
  1589. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1590. Redis::sadd('anime_first_frame_urls', $segment_id);
  1591. }
  1592. if ($update_result) {
  1593. $updated_segments[] = [
  1594. 'segment_id' => $segment_id,
  1595. 'task_id' => $task_id,
  1596. 'status' => '生成中',
  1597. 'matched_scenes' => $matched_scene,
  1598. 'matched_roles' => $segment_characters,
  1599. 'ref_urls_count' => count($ref_img_urls)
  1600. ];
  1601. } else {
  1602. $failed_segments[] = [
  1603. 'segment_id' => $segment_id,
  1604. 'error' => '更新分镜任务状态失败'
  1605. ];
  1606. }
  1607. if ($dubTaskId) {
  1608. sleep(1);
  1609. // 请求远程服务器执行生成
  1610. $client = new Client(['timeout' => 300, 'verify' => false]);
  1611. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1612. $response = $result->getBody()->getContents();
  1613. $response_arr = json_decode($response, true);
  1614. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1615. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1616. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1617. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1618. }
  1619. }
  1620. } catch (\Exception $e) {
  1621. $failed_segments[] = [
  1622. 'segment_id' => $segment_id,
  1623. 'error' => $e->getMessage()
  1624. ];
  1625. }
  1626. }
  1627. // 更新剧集生成状态
  1628. if (!empty($updated_segments)) {
  1629. DB::table('mp_anime_episodes')
  1630. ->where('id', $episode_id)
  1631. ->update([
  1632. 'is_generated' => 1,
  1633. 'updated_at' => date('Y-m-d H:i:s')
  1634. ]);
  1635. }
  1636. return [
  1637. 'success_count' => count($updated_segments),
  1638. 'failed_count' => count($failed_segments),
  1639. 'success_segments' => $updated_segments,
  1640. 'failed_segments' => $failed_segments,
  1641. 'total_segments' => count($segments)
  1642. ];
  1643. }
  1644. public function reGenerateSegment($data) {
  1645. $segment_id = getProp($data, 'segment_id');
  1646. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1647. $anime_id = getProp($segment, 'anime_id');
  1648. $episode_id = getProp($segment, 'episode_id');
  1649. $episode_number = getProp($segment, 'episode_number');
  1650. $segment_content = getProp($data, 'segment_content');
  1651. $ratio = getProp($data, 'ratio');
  1652. if (!$ratio) {
  1653. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1654. if (!$ratio) $ratio = '9:16';
  1655. }
  1656. $dimensions = $this->getRatioDimensions($ratio);
  1657. $width = $dimensions['width'];
  1658. $height = $dimensions['height'];
  1659. if (!$anime_id || !$episode_id) {
  1660. Utils::throwError('1002:请选择分镜');
  1661. }
  1662. // 使用文生文模型重新解析segment_content
  1663. if (!empty($segment_content)) {
  1664. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1665. }
  1666. // 获取动漫的角色信息(包含参考图)
  1667. $anime = DB::table('mp_animes')
  1668. ->where('id', $anime_id)
  1669. ->select('roles', 'scenes')
  1670. ->first();
  1671. if (!$anime || !$anime->roles) {
  1672. Utils::throwError('20003:未找到角色信息');
  1673. }
  1674. $roles = json_decode($anime->roles, true);
  1675. if (!$roles) {
  1676. Utils::throwError('20003:角色信息格式错误');
  1677. }
  1678. // 构建角色名称到参考图的映射
  1679. $role_map = [];
  1680. foreach ($roles as $role) {
  1681. $role_name = getProp($role, 'role');
  1682. $role_url = getProp($role, 'url');
  1683. if (!empty($role_name) && !empty($role_url)) {
  1684. $role_map[$role_name] = $role_url;
  1685. }
  1686. }
  1687. $scenes = json_decode($anime->scenes, true);
  1688. if (!$scenes) {
  1689. Utils::throwError('20003:角色信息格式错误');
  1690. }
  1691. // 构建角色名称到参考图的映射
  1692. $scene_map = [];
  1693. foreach ($scenes as $scene) {
  1694. $scene_name = getProp($scene, 'scene');
  1695. $scene_url = getProp($scene, 'url');
  1696. if (!empty($scene_name) && !empty($scene_url)) {
  1697. $scene_map[$scene_name] = $scene_url;
  1698. }
  1699. }
  1700. $segment_id = $segment->segment_id;
  1701. $original_segment_content = $segment->segment_content;
  1702. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1703. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1704. if (empty($final_segment_content)) {
  1705. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1706. }
  1707. try {
  1708. $dubTaskId = 0;
  1709. // 分镜剧本数组
  1710. $update_data = [
  1711. 'segment_content' => $final_segment_content,
  1712. 'pic_task_status' => '生成中',
  1713. 'updated_at' => date('Y-m-d H:i:s')
  1714. ];
  1715. // 解析分镜内容,提取画面描述作为主要提示词
  1716. $prompt = $final_segment_content;
  1717. $ref_img_urls = [];
  1718. // 分镜场景
  1719. $scene = getProp($data, 'scene');
  1720. if ($scene) {
  1721. $matched_scene = '';
  1722. if (isset($scene_map[$scene])) {
  1723. $img_index = count($ref_img_urls) + 1;
  1724. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1725. $ref_img_urls[] = $scene_map[$scene];
  1726. $matched_scene = $scene;
  1727. }
  1728. $update_data['scene'] = $scene;
  1729. }
  1730. // 分镜角色
  1731. $characters = getProp($data, 'characters');
  1732. if ($characters) {
  1733. $update_data['characters'] = $characters;
  1734. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1735. $characters = explode(',', $characters);
  1736. // 从分镜内容中提取涉及的角色
  1737. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1738. // 获取匹配角色的参考图
  1739. foreach ($segment_characters as $character) {
  1740. if (isset($role_map[$character])) {
  1741. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1742. $img_index = count($ref_img_urls) + 1;
  1743. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1744. $ref_img_urls[] = $role_map[$character];
  1745. }
  1746. }
  1747. }
  1748. // 如果没有找到匹配的角色参考图,不使用参考图
  1749. if (empty($ref_img_urls)) {
  1750. $ref_img_urls = [];
  1751. }
  1752. // 准备生成任务参数
  1753. $params = [
  1754. 'alias_segment_id' => $segment_id,
  1755. 'prompt' => $prompt,
  1756. 'ref_img_urls' => $ref_img_urls,
  1757. 'width' => $width,
  1758. 'height' => $height,
  1759. ];
  1760. // 优化提示词(不要生成字幕)
  1761. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1762. // 调用AI图片生成服务
  1763. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1764. $task_id = $task->id;
  1765. if (!$task_id) {
  1766. Utils::throwError('20003:创建生成任务失败!');
  1767. }
  1768. $update_data['pic_task_id'] = $task_id;
  1769. // 更新分镜剧本信息
  1770. $this->handleSegmentContent($update_data);
  1771. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1772. if ($segment_content) {
  1773. $dialogue = getProp($update_data, 'dialogue');
  1774. if (!empty($dialogue)) {
  1775. $now = date('Y-m-d H:i:s');
  1776. $generate_json = [
  1777. 'text' => $dialogue,
  1778. 'role' => getProp($update_data, 'voice_actor'),
  1779. 'voice_type' => getProp($update_data, 'voice_type'),
  1780. 'voice_name' => getProp($update_data, 'voice_name'),
  1781. 'emotion' => getProp($update_data, 'emotion'),
  1782. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1783. 'gender' => getProp($update_data, 'gender'),
  1784. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1785. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1786. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1787. 'pitch' => getProp($update_data, 'pitch', 0),
  1788. ];
  1789. // 插入视频配音合成任务
  1790. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1791. 'alias_segment_id' => $segment_id,
  1792. 'generate_status' => '执行中',
  1793. 'audio_url' => '',
  1794. 'generate_json' => json_encode($generate_json, 256),
  1795. 'created_at' => date('Y-m-d H:i:s'),
  1796. 'updated_at' => date('Y-m-d H:i:s'),
  1797. ]);
  1798. if (!$dubTaskId) {
  1799. Utils::throwError('20003:创建配音任务失败!');
  1800. }
  1801. $update_data['audio_url'] = '';
  1802. } else {
  1803. // dialogue为空时,直接写入默认音频信息
  1804. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1805. $update_data['audio_duration'] = 2.0;
  1806. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1807. }
  1808. }
  1809. $boolen = DB::table('mp_episode_segments')
  1810. ->where('segment_id', $segment_id)
  1811. ->update($update_data);
  1812. // 如果是第一集的首帧图片,则存入待更新数组
  1813. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1814. Redis::sadd('anime_first_frame_urls', $segment_id);
  1815. }
  1816. if ($dubTaskId) {
  1817. // 请求远程服务器执行生成
  1818. $client = new Client(['timeout' => 300, 'verify' => false]);
  1819. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1820. $response = $result->getBody()->getContents();
  1821. $response_arr = json_decode($response, true);
  1822. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1823. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1824. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  1825. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  1826. Utils::throwError('20003:火山生成音频失败');
  1827. }
  1828. }
  1829. } catch (\Exception $e) {
  1830. $failed_segments[] = [
  1831. 'segment_id' => $segment_id,
  1832. 'error' => $e->getMessage()
  1833. ];
  1834. }
  1835. // 创建任务之后先暂停10s等待异步任务完成
  1836. sleep(10);
  1837. $img_url = $this->loopGetPicTaskResult($task_id);
  1838. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  1839. // 图片生成后新增对话记录
  1840. try {
  1841. $uid = Site::getUid();
  1842. $now = date('Y-m-d H:i:s');
  1843. // 使用AI反推图片提示词
  1844. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  1845. // 保存对话记录
  1846. $records = [
  1847. [
  1848. 'uid' => $uid,
  1849. 'anime_id' => $anime_id,
  1850. 'sequence' => $episode_number,
  1851. 'role' => 'user',
  1852. 'content' => '重新生成',
  1853. 'segment_id' => $segment_id,
  1854. 'image_url' => '',
  1855. 'created_at' => $now,
  1856. 'updated_at' => $now
  1857. ],
  1858. [
  1859. 'uid' => $uid,
  1860. 'anime_id' => $anime_id,
  1861. 'sequence' => $episode_number,
  1862. 'role' => 'assistant',
  1863. 'content' => $pic_prompt,
  1864. 'segment_id' => $segment_id,
  1865. 'image_url' => $img_url,
  1866. 'created_at' => $now,
  1867. 'updated_at' => $now
  1868. ]
  1869. ];
  1870. DB::table('mp_anime_records')->insert($records);
  1871. } catch (\Exception $e) {
  1872. // 记录日志但不影响主流程
  1873. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  1874. 'segment_id' => $segment_id,
  1875. 'img_url' => $img_url
  1876. ]);
  1877. }
  1878. return $img_url;
  1879. }
  1880. public function addSegment($data) {
  1881. $prev_segment_id = getProp($data, 'prev_segment_id');
  1882. $img_url = getProp($data, 'img_url');
  1883. $video_url = getProp($data, 'video_url');
  1884. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  1885. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1886. $anime_id = getProp($segment, 'anime_id');
  1887. $episode_id = getProp($segment, 'episode_id');
  1888. $episode_number = getProp($segment, 'episode_number');
  1889. $segment_number = getProp($segment, 'segment_number');
  1890. $new_segment_number = $segment_number + 1;
  1891. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  1892. // 分镜剧本数组
  1893. $insert_data = [
  1894. 'anime_id' => $anime_id,
  1895. 'episode_id' => $episode_id,
  1896. 'episode_number' => $episode_number,
  1897. 'act_number' => getProp($segment, 'act_number'),
  1898. 'act_title' => getProp($segment, 'act_title'),
  1899. 'segment_id' => $segment_id,
  1900. 'segment_number' => $new_segment_number,
  1901. 'segment_content' => '',
  1902. 'img_url' => '',
  1903. 'video_url' => '',
  1904. 'created_at' => date('Y-m-d H:i:s'),
  1905. 'updated_at' => date('Y-m-d H:i:s')
  1906. ];
  1907. if ($img_url) $insert_data['img_url'] = $img_url;
  1908. if ($video_url) {
  1909. $insert_data['origin_video_url'] = $video_url;
  1910. $insert_data['current_type'] = 2;
  1911. $compressed_video_url = compressVideo($video_url);
  1912. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  1913. }
  1914. try {
  1915. DB::beginTransaction();
  1916. // 先更新序号
  1917. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  1918. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  1919. if (!$id) {
  1920. Utils::throwError('20003:新增分镜失败!');
  1921. }
  1922. }catch (\Exception $e) {
  1923. DB::rollBack();
  1924. Utils::throwError('20003:'.$e->getMessage());
  1925. }
  1926. DB::commit();
  1927. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  1928. $segment = $segment ? (array)$segment : [];
  1929. return $segment;
  1930. // 以下代码暂弃用
  1931. $anime_id = getProp($segment, 'anime_id');
  1932. $episode_id = getProp($segment, 'episode_id');
  1933. $episode_number = getProp($segment, 'episode_number');
  1934. $segment_number = getProp($segment, 'segment_number');
  1935. $segment_content = getProp($data, 'segment_content');
  1936. $img_url = getProp($data, 'img_url');
  1937. $video_url = getProp($data, 'video_url');
  1938. $ratio = getProp($data, 'ratio');
  1939. $dimensions = $this->getRatioDimensions($ratio);
  1940. $width = $dimensions['width'];
  1941. $height = $dimensions['height'];
  1942. if (!$anime_id || !$episode_id) {
  1943. Utils::throwError('1002:请选择分镜');
  1944. }
  1945. // 使用文生文模型重新解析segment_content
  1946. if (!empty($segment_content)) {
  1947. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1948. }
  1949. // 获取动漫的角色信息(包含参考图)
  1950. $anime = DB::table('mp_animes')
  1951. ->where('id', $anime_id)
  1952. ->select('roles', 'scenes')
  1953. ->first();
  1954. if (!$anime || !$anime->roles) {
  1955. Utils::throwError('20003:未找到角色信息');
  1956. }
  1957. $roles = json_decode($anime->roles, true);
  1958. if (!$roles) {
  1959. Utils::throwError('20003:角色信息格式错误');
  1960. }
  1961. // 构建角色名称到参考图的映射
  1962. $role_map = [];
  1963. foreach ($roles as $role) {
  1964. $role_name = getProp($role, 'role');
  1965. $role_url = getProp($role, 'url');
  1966. if (!empty($role_name) && !empty($role_url)) {
  1967. $role_map[$role_name] = $role_url;
  1968. }
  1969. }
  1970. $scenes = json_decode($anime->scenes, true);
  1971. if (!$scenes) {
  1972. Utils::throwError('20003:角色信息格式错误');
  1973. }
  1974. // 构建角色名称到参考图的映射
  1975. $scene_map = [];
  1976. foreach ($scenes as $scene) {
  1977. $scene_name = getProp($scene, 'scene');
  1978. $scene_url = getProp($scene, 'url');
  1979. if (!empty($scene_name) && !empty($scene_url)) {
  1980. $scene_map[$scene_name] = $scene_url;
  1981. }
  1982. }
  1983. $segment_id = $segment->segment_id;
  1984. $original_segment_content = $segment->segment_content;
  1985. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1986. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1987. if (empty($final_segment_content)) {
  1988. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1989. }
  1990. try {
  1991. $dubTaskId = 0;
  1992. DB::beginTransaction();
  1993. $new_segment_number = $segment_number + 1;
  1994. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  1995. // 分镜剧本数组
  1996. $insert_data = [
  1997. 'anime_id' => $anime_id,
  1998. 'episode_id' => $episode_id,
  1999. 'episode_number' => $episode_number,
  2000. 'act_number' => getProp($segment, 'act_number'),
  2001. 'act_title' => getProp($segment, 'act_title'),
  2002. 'segment_id' => $segment_id,
  2003. 'segment_number' => $new_segment_number,
  2004. 'segment_content' => $final_segment_content,
  2005. 'img_url' => $img_url,
  2006. 'video_url' => $video_url,
  2007. 'created_at' => date('Y-m-d H:i:s'),
  2008. 'updated_at' => date('Y-m-d H:i:s')
  2009. ];
  2010. // 更新分镜剧本信息
  2011. $this->handleSegmentContent($insert_data);
  2012. // 如果有对话内容,创建视频配音合成任务
  2013. $dialogue = getProp($insert_data, 'dialogue');
  2014. if (!empty($dialogue)) {
  2015. $now = date('Y-m-d H:i:s');
  2016. $generate_json = [
  2017. 'text' => $dialogue,
  2018. 'role' => getProp($insert_data, 'voice_actor'),
  2019. 'voice_type' => getProp($insert_data, 'voice_type'),
  2020. 'voice_name' => getProp($insert_data, 'voice_name'),
  2021. 'emotion' => getProp($insert_data, 'emotion'),
  2022. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2023. 'gender' => getProp($insert_data, 'gender'),
  2024. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2025. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2026. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2027. 'pitch' => getProp($insert_data, 'pitch', 0),
  2028. ];
  2029. // 插入视频配音合成任务
  2030. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2031. 'alias_segment_id' => $segment_id,
  2032. 'generate_status' => '执行中',
  2033. 'audio_url' => '',
  2034. 'generate_json' => json_encode($generate_json, 256),
  2035. 'created_at' => $now,
  2036. 'updated_at' => $now,
  2037. ]);
  2038. if (!$dubTaskId) {
  2039. Utils::throwError('20003:创建配音任务失败!');
  2040. }
  2041. $insert_data['audio_url'] = '';
  2042. } else {
  2043. // dialogue为空时,直接写入默认音频信息
  2044. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2045. $insert_data['audio_duration'] = 2.0;
  2046. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2047. }
  2048. // 如果没有上传图片则使用当前描述进行生成
  2049. if (!$img_url) {
  2050. // 解析分镜内容,提取画面描述作为主要提示词
  2051. $prompt = $final_segment_content;
  2052. $ref_img_urls = [];
  2053. // 分镜场景
  2054. $scene = getProp($insert_data, 'scene');
  2055. if ($scene) {
  2056. $matched_scene = '';
  2057. if (isset($scene_map[$scene])) {
  2058. $img_index = count($ref_img_urls) + 1;
  2059. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2060. $ref_img_urls[] = $scene_map[$scene];
  2061. $matched_scene = $scene;
  2062. }
  2063. $update_data['scene'] = $scene;
  2064. }
  2065. // 分镜角色
  2066. $characters = getProp($insert_data, 'characters');
  2067. if ($characters) {
  2068. $update_data['characters'] = $characters;
  2069. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2070. $characters = explode(',', $characters);
  2071. // 从分镜内容中提取涉及的角色
  2072. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2073. // 获取匹配角色的参考图
  2074. foreach ($segment_characters as $character) {
  2075. if (isset($role_map[$character])) {
  2076. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2077. $img_index = count($ref_img_urls) + 1;
  2078. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2079. $ref_img_urls[] = $role_map[$character];
  2080. }
  2081. }
  2082. }
  2083. // 如果没有找到匹配的角色参考图,不使用参考图
  2084. if (empty($ref_img_urls)) {
  2085. $ref_img_urls = [];
  2086. }
  2087. // 准备生成任务参数
  2088. $params = [
  2089. 'alias_segment_id' => $segment_id,
  2090. 'prompt' => $prompt,
  2091. 'ref_img_urls' => $ref_img_urls,
  2092. 'width' => $width,
  2093. 'height' => $height,
  2094. ];
  2095. // 调用AI图片生成服务
  2096. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2097. $task_id = $task->id;
  2098. // $task_id = 'whatever';
  2099. if (!$task_id) {
  2100. Utils::throwError('20003:创建生成任务失败!');
  2101. }
  2102. $insert_data['pic_task_status'] = '生成中';
  2103. $insert_data['pic_task_id'] = $task_id;
  2104. }
  2105. // 先更新序号
  2106. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2107. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2108. if (!$boolen) {
  2109. Utils::throwError('20003:新增分镜失败!');
  2110. }
  2111. // 如果是第一集的首帧图片,则存入待更新数组
  2112. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2113. Redis::sadd('anime_first_frame_urls', $segment_id);
  2114. }
  2115. if ($dubTaskId) {
  2116. // 请求远程服务器执行生成
  2117. $client = new Client(['timeout' => 300, 'verify' => false]);
  2118. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2119. $response = $result->getBody()->getContents();
  2120. $response_arr = json_decode($response, true);
  2121. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2122. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2123. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2124. Utils::throwError('20003:火山生成音频失败');
  2125. }
  2126. }
  2127. } catch (\Exception $e) {
  2128. DB::rollBack();
  2129. Utils::throwError('20003:'.$e->getMessage());
  2130. }
  2131. DB::commit();
  2132. // 创建任务之后先暂停10s等待异步任务完成
  2133. sleep(10);
  2134. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2135. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2136. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2137. $segment = $segment ? (array)$segment : [];
  2138. return $segment;
  2139. }
  2140. public function copySegment($data) {
  2141. $segment_id = getProp($data, 'segment_id');
  2142. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2143. if (!$segment) Utils::throwError('20003:请选择分镜');
  2144. $anime_id = getProp($segment, 'anime_id');
  2145. $episode_id = getProp($segment, 'episode_id');
  2146. $episode_number = getProp($segment, 'episode_number');
  2147. $segment_number = getProp($segment, 'segment_number');
  2148. $new_segment_id = 0;
  2149. try {
  2150. DB::beginTransaction();
  2151. $segment = (array)$segment;
  2152. unset($segment['id']);
  2153. $segment['segment_number'] += 1;
  2154. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2155. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2156. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2157. // 更新其他分镜序号
  2158. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2159. // 复制分镜
  2160. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2161. if (!$id) {
  2162. Utils::throwError('20003:复制分镜失败');
  2163. }
  2164. }catch (\Exception $e) {
  2165. DB::rollBack();
  2166. Utils::throwError('20003:'.$e->getMessage());
  2167. }
  2168. DB::commit();
  2169. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2170. $segment = $segment ? (array)$segment : [];
  2171. return $segment;
  2172. }
  2173. public function moveSegment($data) {
  2174. $segment_id = getProp($data, 'segment_id');
  2175. $target_segment_id = getProp($data, 'target_segment_id');
  2176. // 获取源分镜信息
  2177. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2178. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2179. // 获取目标分镜信息
  2180. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2181. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2182. $anime_id = getProp($source_segment, 'anime_id');
  2183. $episode_id = getProp($source_segment, 'episode_id');
  2184. $episode_number = getProp($source_segment, 'episode_number');
  2185. $source_segment_number = getProp($source_segment, 'segment_number');
  2186. $target_segment_number = getProp($target_segment, 'segment_number');
  2187. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2188. $target_anime_id = getProp($target_segment, 'anime_id');
  2189. $target_episode_number = getProp($target_segment, 'episode_number');
  2190. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2191. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2192. }
  2193. // 如果源分镜和目标分镜相同,无需移动
  2194. if ($source_segment_number == $target_segment_number) {
  2195. return true;
  2196. }
  2197. try {
  2198. DB::beginTransaction();
  2199. if ($source_segment_number < $target_segment_number) {
  2200. // 向后移动:源分镜移动到目标分镜之后
  2201. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2202. DB::table('mp_episode_segments')
  2203. ->where('anime_id', $anime_id)
  2204. ->where('episode_id', $episode_id)
  2205. ->where('segment_number', '>', $source_segment_number)
  2206. ->where('segment_number', '<=', $target_segment_number)
  2207. ->decrement('segment_number');
  2208. // 2. 将源分镜移动到目标分镜之后
  2209. $new_segment_number = $target_segment_number;
  2210. } else {
  2211. // 向前移动:源分镜移动到目标分镜之后
  2212. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2213. DB::table('mp_episode_segments')
  2214. ->where('anime_id', $anime_id)
  2215. ->where('episode_id', $episode_id)
  2216. ->where('segment_number', '>', $target_segment_number)
  2217. ->where('segment_number', '<', $source_segment_number)
  2218. ->increment('segment_number');
  2219. // 2. 将源分镜移动到目标分镜之后
  2220. $new_segment_number = $target_segment_number + 1;
  2221. }
  2222. // 3. 更新源分镜的序号
  2223. $update_result = DB::table('mp_episode_segments')
  2224. ->where('segment_id', $segment_id)
  2225. ->update([
  2226. 'segment_number' => $new_segment_number,
  2227. 'updated_at' => date('Y-m-d H:i:s')
  2228. ]);
  2229. if (!$update_result) {
  2230. Utils::throwError('20003:更新分镜序号失败');
  2231. }
  2232. DB::commit();
  2233. return true;
  2234. } catch (\Exception $e) {
  2235. DB::rollBack();
  2236. Utils::throwError('20003:' . $e->getMessage());
  2237. }
  2238. }
  2239. public function delSegment($data) {
  2240. $segment_id = getProp($data, 'segment_id');
  2241. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2242. if (!$segment) Utils::throwError('20003:请选择分镜');
  2243. $anime_id = getProp($segment, 'anime_id');
  2244. $episode_id = getProp($segment, 'episode_id');
  2245. $episode_number = getProp($segment, 'episode_number');
  2246. $segment_number = getProp($segment, 'segment_number');
  2247. try {
  2248. DB::beginTransaction();
  2249. // 删除分镜
  2250. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2251. if (!$boolen) {
  2252. Utils::throwError('20003:删除分镜失败');
  2253. }
  2254. // 更新其他分镜序号
  2255. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2256. }catch (\Exception $e) {
  2257. DB::rollBack();
  2258. Utils::throwError('20003:'.$e->getMessage());
  2259. }
  2260. DB::commit();
  2261. return true;
  2262. }
  2263. public function applySegment($data) {
  2264. $segment_id = getProp($data, 'segment_id');
  2265. $url = getProp($data, 'url');
  2266. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2267. if (!$url) Utils::throwError('20003:URL不能为空');
  2268. // 获取URL的文件扩展名
  2269. $urlPath = parse_url($url, PHP_URL_PATH);
  2270. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2271. // 定义图片和视频的扩展名
  2272. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2273. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2274. // 判断是图片还是视频
  2275. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2276. if (in_array($extension, $imageExtensions)) {
  2277. // 图片类型
  2278. $updateData['img_url'] = $url;
  2279. $updateData['current_type'] = 1;
  2280. } elseif (in_array($extension, $videoExtensions)) {
  2281. // 视频类型
  2282. $updateData['video_url'] = $url;
  2283. $updateData['current_type'] = 2;
  2284. } else {
  2285. Utils::throwError('20003:不支持的文件类型');
  2286. }
  2287. // 更新分镜表
  2288. $result = DB::table('mp_episode_segments')
  2289. ->where('segment_id', $segment_id)
  2290. ->update($updateData);
  2291. if (!$result) {
  2292. Utils::throwError('20003:更新分镜失败');
  2293. }
  2294. return true;
  2295. }
  2296. public function segmentHistory($data) {
  2297. $segment_id = getProp($data, 'segment_id');
  2298. // 获取历史图片
  2299. $pics = [];
  2300. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2301. foreach($pic_history as $task) {
  2302. $result_url = getProp($task, 'result_url');
  2303. if (is_json($result_url)) {
  2304. $pics = array_merge($pics, json_decode($result_url, true));
  2305. }else {
  2306. $pics[] = $result_url;
  2307. }
  2308. }
  2309. // 获取历史视频
  2310. $videos = [];
  2311. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2312. foreach($video_history as $task) {
  2313. $result_url = getProp($task, 'result_url');
  2314. if (is_json($result_url)) {
  2315. $videos = array_merge($videos, json_decode($result_url, true));
  2316. }else {
  2317. $videos[] = $result_url;
  2318. }
  2319. }
  2320. return compact('pics', 'videos');
  2321. }
  2322. public function addAct($data) {
  2323. $prev_act_id = getProp($data, 'prev_act_id');
  2324. $act_title = getProp($data, 'act_title', '');
  2325. $act_content = getProp($data, 'act_content', '');
  2326. $act_duration = getProp($data, 'act_duration', 5);
  2327. $video_url = getProp($data, 'video_url');
  2328. // 根据prev_act_id获取记录
  2329. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2330. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2331. $anime_id = getProp($prev_segment, 'anime_id');
  2332. $episode_id = getProp($prev_segment, 'episode_id');
  2333. $episode_number = getProp($prev_segment, 'episode_number');
  2334. $prev_act_number = getProp($prev_segment, 'act_number');
  2335. // 获取新的act_number
  2336. $new_act_number = $prev_act_number + 1;
  2337. try {
  2338. DB::beginTransaction();
  2339. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2340. DB::table('mp_episode_segments')
  2341. ->where('anime_id', $anime_id)
  2342. ->where('episode_id', $episode_id)
  2343. ->where('act_number', '>', $prev_act_number)
  2344. ->increment('act_number');
  2345. // 插入新片段记录
  2346. $insert_data = [
  2347. 'anime_id' => $anime_id,
  2348. 'episode_id' => $episode_id,
  2349. 'episode_number' => $episode_number,
  2350. 'act_number' => $new_act_number,
  2351. 'created_at' => date('Y-m-d H:i:s'),
  2352. 'updated_at' => date('Y-m-d H:i:s')
  2353. ];
  2354. if ($act_title) {
  2355. $insert_data['act_title'] = $act_title;
  2356. }
  2357. if ($act_content) {
  2358. $insert_data['act_content'] = $act_content;
  2359. }
  2360. if ($act_duration) {
  2361. $insert_data['act_duration'] = $act_duration;
  2362. }
  2363. if ($video_url) {
  2364. $insert_data['origin_video_url'] = $video_url;
  2365. $insert_data['current_type'] = 2;
  2366. $compressed_video_url = compressVideo($video_url);
  2367. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2368. }
  2369. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2370. if (!$id) {
  2371. Utils::throwError('20003:新增片段失败!');
  2372. }
  2373. DB::commit();
  2374. }catch (\Exception $e) {
  2375. DB::rollBack();
  2376. Utils::throwError('20003:'.$e->getMessage());
  2377. }
  2378. $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();
  2379. $segment = $segment ? (array)$segment : [];
  2380. return $segment;
  2381. }
  2382. public function editAct($data) {
  2383. $act_id = getProp($data, 'act_id');
  2384. $act_content = getProp($data, 'act_content');
  2385. $act_duration = getProp($data, 'act_duration');
  2386. $act_title = getProp($data, 'act_title');
  2387. $image_url = getProp($data, 'image_url');
  2388. $video_url = getProp($data, 'video_url');
  2389. // 参数验证
  2390. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2391. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2392. $segment = DB::table('mp_episode_segments')
  2393. ->where('id', $act_id)
  2394. ->first();
  2395. if (!$segment) Utils::throwError('20003:该片段不存在');
  2396. try {
  2397. DB::beginTransaction();
  2398. // 准备更新数据
  2399. $update_data = [
  2400. 'updated_at' => date('Y-m-d H:i:s')
  2401. ];
  2402. // 更新act相关字段
  2403. if (!empty($act_content)) {
  2404. $update_data['act_show_content'] = $act_content;
  2405. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2406. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2407. $shot_counter = 0;
  2408. $update_data['act_show_content'] = preg_replace_callback(
  2409. '/【(?:镜头|分镜)(\d+)】/u',
  2410. function($matches) use (&$shot_counter) {
  2411. $shot_counter++;
  2412. return '【镜头' . $shot_counter . '】';
  2413. },
  2414. $update_data['act_show_content']
  2415. );
  2416. }
  2417. if (!empty($act_duration)) {
  2418. $update_data['act_duration'] = $act_duration;
  2419. }
  2420. if (!empty($act_title)) {
  2421. $update_data['act_title'] = $act_title;
  2422. }
  2423. // 处理图片上传
  2424. if ($image_url) {
  2425. $update_data['img_url'] = $image_url;
  2426. $update_data['current_type'] = 1;
  2427. // 同时写入一个图片生成任务记录
  2428. if ($act_id) {
  2429. $pic_task = [
  2430. 'alias_act_id' => $act_id,
  2431. 'ref_img_url' => json_encode([]),
  2432. 'status' => 'success',
  2433. 'result_url' => json_encode([$image_url], 256),
  2434. 'model' => '',
  2435. 'created_at' => date('Y-m-d H:i:s'),
  2436. 'updated_at' => date('Y-m-d H:i:s'),
  2437. ];
  2438. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2439. }
  2440. }
  2441. // 处理视频上传
  2442. if ($video_url) {
  2443. $update_data['origin_video_url'] = $video_url;
  2444. $compressed_video_url = compressVideo($video_url);
  2445. $update_data['current_type'] = 2;
  2446. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2447. // 同时写入一个视频生成任务记录
  2448. if ($act_id) {
  2449. $video_task = [
  2450. 'alias_act_id' => $act_id,
  2451. 'status' => 'success',
  2452. 'result_url' => $update_data['origin_video_url'],
  2453. 'compressed_url' => $update_data['video_url'],
  2454. 'created_at' => date('Y-m-d H:i:s'),
  2455. 'updated_at' => date('Y-m-d H:i:s'),
  2456. ];
  2457. DB::table('mp_generate_video_tasks')->insert($video_task);
  2458. }
  2459. }
  2460. // 更新片段信息
  2461. $result = DB::table('mp_episode_segments')
  2462. ->where('id', $act_id)
  2463. ->update($update_data);
  2464. if ($result === false) {
  2465. Utils::throwError('20003:更新片段失败');
  2466. }
  2467. DB::commit();
  2468. // 返回新复制的记录
  2469. $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();
  2470. $new_segment = (array)$new_segment;
  2471. return $new_segment;
  2472. } catch (\Exception $e) {
  2473. DB::rollBack();
  2474. dLog('anime')->error('更新片段失败', [
  2475. 'act_id' => $act_id,
  2476. 'error' => $e->getMessage()
  2477. ]);
  2478. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2479. }
  2480. }
  2481. public function copyAct($data) {
  2482. $act_id = getProp($data, 'act_id');
  2483. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2484. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2485. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2486. $anime_id = getProp($source_segment, 'anime_id');
  2487. $episode_id = getProp($source_segment, 'episode_id');
  2488. $episode_number = getProp($source_segment, 'episode_number');
  2489. $act_number = getProp($source_segment, 'act_number');
  2490. try {
  2491. DB::beginTransaction();
  2492. // 新act的编号
  2493. $new_act_number = $act_number + 1;
  2494. // 更新后续所有act的act_number
  2495. DB::table('mp_episode_segments')
  2496. ->where('anime_id', $anime_id)
  2497. ->where('episode_id', $episode_id)
  2498. ->where('act_number', '>', $act_number)
  2499. ->increment('act_number');
  2500. // 复制该片段记录
  2501. $segment_data = (array)$source_segment;
  2502. unset($segment_data['id']);
  2503. $segment_data['video_url'] = '';
  2504. $segment_data['video_task_id'] = '';
  2505. $segment_data['video_task_status'] = '';
  2506. $segment_data['act_number'] = $new_act_number;
  2507. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2508. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2509. if (!$id) {
  2510. Utils::throwError('20003:复制片段失败');
  2511. }
  2512. DB::commit();
  2513. }catch (\Exception $e) {
  2514. DB::rollBack();
  2515. Utils::throwError('20003:'.$e->getMessage());
  2516. }
  2517. // 返回新复制的记录
  2518. $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();
  2519. $new_segment = $new_segment ? (array)$new_segment : [];
  2520. $new_segment['act_id'] = $id;
  2521. return $new_segment;
  2522. }
  2523. public function moveAct($data) {
  2524. $act_id = getProp($data, 'act_id');
  2525. $target_act_id = getProp($data, 'target_act_id');
  2526. // 获取源片段信息
  2527. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2528. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2529. // 获取目标片段信息
  2530. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2531. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2532. $anime_id = getProp($source_segment, 'anime_id');
  2533. $episode_id = getProp($source_segment, 'episode_id');
  2534. $source_act_number = getProp($source_segment, 'act_number');
  2535. $target_act_number = getProp($target_segment, 'act_number');
  2536. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2537. $target_anime_id = getProp($target_segment, 'anime_id');
  2538. $target_episode_id = getProp($target_segment, 'episode_id');
  2539. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2540. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2541. }
  2542. // 如果源片段和目标片段相同,无需移动
  2543. if ($source_act_number == $target_act_number) {
  2544. return true;
  2545. }
  2546. try {
  2547. DB::beginTransaction();
  2548. if ($source_act_number < $target_act_number) {
  2549. // 向后移动:源片段移动到目标片段之后
  2550. // 1. 将源片段和目标片段之间的所有片段编号减1
  2551. DB::table('mp_episode_segments')
  2552. ->where('anime_id', $anime_id)
  2553. ->where('episode_id', $episode_id)
  2554. ->where('act_number', '>', $source_act_number)
  2555. ->where('act_number', '<=', $target_act_number)
  2556. ->decrement('act_number');
  2557. // 2. 将源片段移动到目标片段之后
  2558. $new_act_number = $target_act_number;
  2559. } else {
  2560. // 向前移动:源片段移动到目标片段之后
  2561. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2562. DB::table('mp_episode_segments')
  2563. ->where('anime_id', $anime_id)
  2564. ->where('episode_id', $episode_id)
  2565. ->where('act_number', '>', $target_act_number)
  2566. ->where('act_number', '<', $source_act_number)
  2567. ->increment('act_number');
  2568. // 2. 将源片段移动到目标片段之后
  2569. $new_act_number = $target_act_number + 1;
  2570. }
  2571. // 3. 更新源片段的编号
  2572. $update_result = DB::table('mp_episode_segments')
  2573. ->where('id', $act_id)
  2574. ->update([
  2575. 'act_number' => $new_act_number,
  2576. 'updated_at' => date('Y-m-d H:i:s')
  2577. ]);
  2578. if (!$update_result) {
  2579. Utils::throwError('20003:更新片段编号失败');
  2580. }
  2581. DB::commit();
  2582. return true;
  2583. } catch (\Exception $e) {
  2584. DB::rollBack();
  2585. Utils::throwError('20003:' . $e->getMessage());
  2586. }
  2587. }
  2588. public function delAct($data) {
  2589. $act_id = getProp($data, 'act_id');
  2590. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2591. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2592. if (!$segment) Utils::throwError('20003:请选择片段');
  2593. $anime_id = getProp($segment, 'anime_id');
  2594. $episode_id = getProp($segment, 'episode_id');
  2595. $act_number = getProp($segment, 'act_number');
  2596. try {
  2597. DB::beginTransaction();
  2598. // 删除该片段记录
  2599. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2600. if (!$deleted) {
  2601. Utils::throwError('20003:删除片段失败');
  2602. }
  2603. // 更新后续act的编号
  2604. DB::table('mp_episode_segments')
  2605. ->where('anime_id', $anime_id)
  2606. ->where('episode_id', $episode_id)
  2607. ->where('act_number', '>', $act_number)
  2608. ->decrement('act_number');
  2609. DB::commit();
  2610. }catch (\Exception $e) {
  2611. DB::rollBack();
  2612. Utils::throwError('20003:'.$e->getMessage());
  2613. }
  2614. return true;
  2615. }
  2616. public function applyAct($data) {
  2617. $act_id = getProp($data, 'act_id');
  2618. $url = getProp($data, 'url');
  2619. if (!$act_id) Utils::throwError('20003:请选择片段');
  2620. if (!$url) Utils::throwError('20003:URL不能为空');
  2621. // 获取URL的文件扩展名
  2622. $urlPath = parse_url($url, PHP_URL_PATH);
  2623. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2624. // 定义图片和视频的扩展名
  2625. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2626. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2627. // 判断是图片还是视频
  2628. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2629. if (in_array($extension, $imageExtensions)) {
  2630. // 图片类型
  2631. $updateData['img_url'] = $url;
  2632. $updateData['current_type'] = 1;
  2633. } elseif (in_array($extension, $videoExtensions)) {
  2634. // 视频类型
  2635. $updateData['video_url'] = $url;
  2636. $updateData['current_type'] = 2;
  2637. } else {
  2638. Utils::throwError('20003:不支持的文件类型');
  2639. }
  2640. // 更新片段记录(全能模式下每个act只有一条记录)
  2641. $result = DB::table('mp_episode_segments')
  2642. ->where('id', $act_id)
  2643. ->update($updateData);
  2644. if (!$result) {
  2645. Utils::throwError('20003:更新片段失败');
  2646. }
  2647. return true;
  2648. }
  2649. public function actChatHistory($data) {
  2650. $act_id = getProp($data, 'act_id');
  2651. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2652. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2653. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2654. $value = (array)$value;
  2655. $value['created_at'] = transDate($value['created_at']);
  2656. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2657. else $value['reference_images'] = [];
  2658. return $value;
  2659. })->toArray();
  2660. // 获取历史图片
  2661. $url = [];
  2662. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2663. foreach($pic_history as $task) {
  2664. $result_url = getProp($task, 'result_url');
  2665. if (is_json($result_url)) {
  2666. $url = array_merge($url, json_decode($result_url, true));
  2667. }else {
  2668. $url[] = $result_url;
  2669. }
  2670. }
  2671. // 获取历史视频
  2672. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2673. foreach($video_history as $task) {
  2674. $result_url = getProp($task, 'result_url');
  2675. if (is_json($result_url)) {
  2676. $url = array_merge($url, json_decode($result_url, true));
  2677. }else {
  2678. $url[] = $result_url;
  2679. }
  2680. }
  2681. // 获取资产库
  2682. $products = [];
  2683. // 通过act_id查询片段信息获取episode_id
  2684. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2685. if ($segment) {
  2686. $episode_id = getProp($segment, 'episode_id');
  2687. // 查询剧集信息获取roles、scenes和extra_products
  2688. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2689. if ($episode) {
  2690. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2691. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2692. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2693. // 先合并roles和scenes
  2694. // 处理角色数组
  2695. foreach ($roles as $role) {
  2696. $product = $role;
  2697. // 将role字段重命名为product_name
  2698. if (isset($product['role'])) {
  2699. $product['product_name'] = $product['role'];
  2700. unset($product['role']);
  2701. }
  2702. $product['product'] = 1; // 标记类型为角色
  2703. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2704. }
  2705. // 处理场景数组
  2706. foreach ($scenes as $scene) {
  2707. $product = $scene;
  2708. // 将scene字段重命名为product_name
  2709. if (isset($product['scene'])) {
  2710. $product['product_name'] = $product['scene'];
  2711. unset($product['scene']);
  2712. }
  2713. $product['product'] = 2; // 标记类型为场景
  2714. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2715. }
  2716. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2717. foreach ($extra_products as $extra_product) {
  2718. $product_name = getProp($extra_product, 'product_name');
  2719. if ($product_name) {
  2720. $products[$product_name] = $extra_product; // 覆盖同名数据
  2721. }
  2722. }
  2723. // 重新索引数组(去除key)
  2724. $products = array_values($products);
  2725. }
  2726. }
  2727. // 获取执行中的任务
  2728. $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) {
  2729. $value = (array)$value;
  2730. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2731. else $value['ref_image_url'] = [];
  2732. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2733. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2734. if (!empty($value['prompt'])) {
  2735. $prompt = $value['prompt'];
  2736. // 查找第一个【镜头】的位置
  2737. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2738. // 从【镜头】开始截取
  2739. $prompt = substr($prompt, $matches[0][1]);
  2740. }
  2741. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2742. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2743. $value['prompt'] = $prompt;
  2744. }
  2745. return $value;
  2746. })->toArray();
  2747. return compact('chat', 'url', 'products', 'tasks');
  2748. }
  2749. public function applyAudioData($data) {
  2750. $segment_id = getProp($data, 'segment_id');
  2751. $global_data = getProp($data, 'global_data');
  2752. $segment_data = getProp($data, 'segment_data');
  2753. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2754. $global_data = is_array($global_data) ? $global_data : [];
  2755. $segment_data = is_array($segment_data) ? $segment_data : [];
  2756. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2757. $dialogue_item = null;
  2758. foreach ($global_data as $key => $item) {
  2759. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2760. $dialogue_item = $item;
  2761. unset($global_data[$key]);
  2762. break;
  2763. }
  2764. }
  2765. if ($dialogue_item) {
  2766. $segment_data[] = $dialogue_item;
  2767. }
  2768. // 特殊参数: audio_url,audio_duration,subtitle_info
  2769. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2770. // 如果不是全部存在,则仍需创建音频任务
  2771. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2772. $special_update_data = [];
  2773. $has_all_special_params = false;
  2774. // 从segment_data中提取特殊参数
  2775. $filtered_segment_data = [];
  2776. foreach ($segment_data as $item) {
  2777. $field_name = trim((string)getProp($item, 'name'));
  2778. if (in_array($field_name, $special_fields)) {
  2779. $special_update_data[$field_name] = getProp($item, 'value');
  2780. } else {
  2781. // 非特殊参数保留,继续后续处理
  2782. $filtered_segment_data[] = $item;
  2783. }
  2784. }
  2785. // 检查是否三个特殊参数都存在
  2786. if (count($special_update_data) === 3 &&
  2787. isset($special_update_data['audio_url']) &&
  2788. isset($special_update_data['audio_duration']) &&
  2789. isset($special_update_data['subtitle_info'])) {
  2790. $has_all_special_params = true;
  2791. // 立即更新到当前分镜
  2792. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  2793. DB::table('mp_episode_segments')
  2794. ->where('segment_id', $segment_id)
  2795. ->update($special_update_data);
  2796. }
  2797. // 使用过滤后的segment_data继续处理其他参数
  2798. $segment_data = $filtered_segment_data;
  2799. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  2800. $global_update_data = [];
  2801. $segment_update_data = [];
  2802. $global_voice_type = '';
  2803. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2804. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  2805. $episode_id = getProp($target_segment, 'episode_id');
  2806. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  2807. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2808. if (!$episode) Utils::throwError('20003:分集不存在');
  2809. foreach ($global_data as $item) {
  2810. $field_name = trim((string)getProp($item, 'name'));
  2811. if (!$field_name || !in_array($field_name, $allow_fields)) {
  2812. continue;
  2813. }
  2814. $global_update_data[$field_name] = getProp($item, 'value');
  2815. if ($field_name === 'voice_type') {
  2816. $global_voice_type = trim((string)getProp($item, 'value'));
  2817. }
  2818. }
  2819. foreach ($segment_data as $item) {
  2820. $field_name = trim((string)getProp($item, 'name'));
  2821. if (!$field_name || !in_array($field_name, $allow_fields)) {
  2822. continue;
  2823. }
  2824. $segment_update_data[$field_name] = getProp($item, 'value');
  2825. }
  2826. if ($global_voice_type) {
  2827. $timbre_info = DB::table('mp_timbres')
  2828. ->where('timbre_type', $global_voice_type)
  2829. ->select('audio_url', 'timbre_name')
  2830. ->first();
  2831. if ($timbre_info) {
  2832. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  2833. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  2834. }
  2835. }
  2836. try {
  2837. DB::beginTransaction();
  2838. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  2839. $segment_ids_to_create_task = [];
  2840. $segments_data = [];
  2841. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  2842. if (!empty($global_update_data)) {
  2843. // 如果角色不存在,则只更新当前分镜
  2844. if (!$target_voice_actor) {
  2845. // 只处理当前分镜
  2846. $affected_segments = DB::table('mp_episode_segments')
  2847. ->where('segment_id', $segment_id)
  2848. ->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')
  2849. ->get();
  2850. } else {
  2851. // 获取该角色的所有分镜
  2852. $affected_segments = DB::table('mp_episode_segments')
  2853. ->where('episode_id', $episode_id)
  2854. ->where('voice_actor', $target_voice_actor)
  2855. ->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')
  2856. ->get();
  2857. }
  2858. foreach ($affected_segments as $seg) {
  2859. $seg = (array)$seg;
  2860. $sid = getProp($seg, 'segment_id');
  2861. // 检查参数是否发生变化
  2862. $has_changed = false;
  2863. foreach ($global_update_data as $field => $new_value) {
  2864. $old_value = getProp($seg, $field);
  2865. if ($old_value != $new_value) {
  2866. $has_changed = true;
  2867. break;
  2868. }
  2869. }
  2870. if ($has_changed) {
  2871. $segment_ids_to_create_task[] = $sid;
  2872. $segments_data[$sid] = $seg;
  2873. }
  2874. }
  2875. // 只有在有变化的分镜时才更新
  2876. if (!empty($segment_ids_to_create_task)) {
  2877. $global_segment_update_data = $global_update_data;
  2878. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  2879. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  2880. DB::table('mp_episode_segments')
  2881. ->where('episode_id', $episode_id)
  2882. ->where('voice_actor', $target_voice_actor)
  2883. ->whereIn('segment_id', $segment_ids_to_create_task)
  2884. ->update($global_segment_update_data);
  2885. }
  2886. if ($global_voice_type) {
  2887. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  2888. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  2889. $roles_updated = false;
  2890. foreach ($episode_roles as &$role) {
  2891. // 通过 role 字段匹配角色名,而不是 voice_name
  2892. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  2893. continue;
  2894. }
  2895. $role['voice_type'] = $global_voice_type;
  2896. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  2897. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  2898. $roles_updated = true;
  2899. }
  2900. unset($role);
  2901. if ($roles_updated) {
  2902. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  2903. 'roles' => json_encode($episode_roles, 256),
  2904. 'updated_at' => date('Y-m-d H:i:s'),
  2905. ]);
  2906. }
  2907. }
  2908. }
  2909. // 如果有单个分镜更新,检查是否有变化
  2910. if (!empty($segment_update_data)) {
  2911. // 获取当前分镜数据
  2912. $current_segment = DB::table('mp_episode_segments')
  2913. ->where('segment_id', $segment_id)
  2914. ->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')
  2915. ->first();
  2916. if ($current_segment) {
  2917. $current_segment = (array)$current_segment;
  2918. // 检查参数是否发生变化
  2919. $has_changed = false;
  2920. foreach ($segment_update_data as $field => $new_value) {
  2921. $old_value = getProp($current_segment, $field);
  2922. if ($old_value != $new_value) {
  2923. $has_changed = true;
  2924. break;
  2925. }
  2926. }
  2927. if ($has_changed) {
  2928. // 如果该分镜还未在列表中,添加进去
  2929. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  2930. $segment_ids_to_create_task[] = $segment_id;
  2931. $segments_data[$segment_id] = $current_segment;
  2932. }
  2933. // 更新分镜数据并清空音频URL
  2934. $segment_update_data['audio_url'] = '';
  2935. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  2936. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  2937. }
  2938. }
  2939. }
  2940. // 为所有有变化的分镜创建音频合成任务
  2941. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  2942. if (!empty($segment_ids_to_create_task)) {
  2943. foreach ($segment_ids_to_create_task as $sid) {
  2944. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  2945. if ($sid === $segment_id && $has_all_special_params) {
  2946. continue;
  2947. }
  2948. // 重新获取更新后的分镜数据
  2949. $updated_segment = DB::table('mp_episode_segments')
  2950. ->where('segment_id', $sid)
  2951. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  2952. ->first();
  2953. if (!$updated_segment) continue;
  2954. $updated_segment = (array)$updated_segment;
  2955. // 检查dialogue是否为空
  2956. $dialogue = getProp($updated_segment, 'dialogue');
  2957. if (empty($dialogue)) {
  2958. // dialogue为空时,直接写入默认音频信息
  2959. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  2960. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  2961. 'audio_duration' => 2.0,
  2962. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  2963. 'updated_at' => date('Y-m-d H:i:s')
  2964. ]);
  2965. continue;
  2966. }
  2967. $generate_json = [
  2968. 'text' => $dialogue,
  2969. 'role' => getProp($updated_segment, 'voice_actor'),
  2970. 'voice_type' => getProp($updated_segment, 'voice_type'),
  2971. 'voice_name' => getProp($updated_segment, 'voice_name'),
  2972. 'emotion' => getProp($updated_segment, 'emotion'),
  2973. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  2974. 'gender' => getProp($updated_segment, 'gender'),
  2975. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  2976. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  2977. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  2978. 'pitch' => getProp($updated_segment, 'pitch', 0),
  2979. ];
  2980. // 插入视频配音合成任务
  2981. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2982. 'alias_segment_id' => $sid,
  2983. 'generate_status' => '执行中',
  2984. 'audio_url' => '',
  2985. 'generate_json' => json_encode($generate_json, 256),
  2986. 'created_at' => date('Y-m-d H:i:s'),
  2987. 'updated_at' => date('Y-m-d H:i:s'),
  2988. ]);
  2989. if (!$dubTaskId) {
  2990. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  2991. continue;
  2992. }
  2993. // 将任务ID添加到Redis列表中
  2994. Redis::lpush('dub_video_task_queue', $dubTaskId);
  2995. // 请求远程服务器执行生成
  2996. try {
  2997. sleep(1);
  2998. $client = new Client(['timeout' => 300, 'verify' => false]);
  2999. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3000. $response = $result->getBody()->getContents();
  3001. $response_arr = json_decode($response, true);
  3002. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3003. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3004. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3005. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3006. }
  3007. } catch (\Exception $e) {
  3008. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3009. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3010. }
  3011. }
  3012. }
  3013. DB::commit();
  3014. } catch (\Exception $e) {
  3015. DB::rollBack();
  3016. Utils::throwError('20003:'.$e->getMessage());
  3017. }
  3018. return true;
  3019. }
  3020. public function episodePicsInfo($data) {
  3021. $anime_id = getProp($data, 'anime_id');
  3022. $episode_id = getProp($data, 'episode_id');
  3023. // 参数验证
  3024. if (!$anime_id && !$episode_id) {
  3025. Utils::throwError('20003:请提供动漫ID或分集ID');
  3026. }
  3027. // 根据参数获取数据源
  3028. if ($episode_id) {
  3029. // 从剧集表获取
  3030. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3031. if (!$source) Utils::throwError('20003:该剧集不存在');
  3032. $table_name = 'mp_anime_episodes';
  3033. $id_field = 'id';
  3034. $id_value = $episode_id;
  3035. // 获取剧集的anime_id用于继承全局数据
  3036. $anime_id = getProp($source, 'anime_id');
  3037. } else {
  3038. // 从动漫表获取
  3039. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3040. if (!$source) Utils::throwError('20003:该动漫不存在');
  3041. $table_name = 'mp_animes';
  3042. $id_field = 'id';
  3043. $id_value = $anime_id;
  3044. }
  3045. $source = (array)$source;
  3046. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3047. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3048. // 如果是分集数据,需要处理继承和任务创建逻辑
  3049. if ($episode_id) {
  3050. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3051. }
  3052. // 返回生成器函数,用于 SSE 流式输出
  3053. return function() use ($roles, $scenes, $table_name, $id_field, $id_value) {
  3054. $startTime = time();
  3055. $maxDuration = 600; // 10分钟超时
  3056. $checkInterval = 3; // 每3秒检查一次
  3057. // Redis 缓存键
  3058. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3059. // 生成当前数据的哈希值用于比较
  3060. $generateHash = function($roles, $scenes) {
  3061. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes], JSON_UNESCAPED_UNICODE));
  3062. };
  3063. // 发送初始数据
  3064. $currentHash = $generateHash($roles, $scenes);
  3065. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3066. echo "data: " . json_encode([
  3067. 'type' => 'init',
  3068. 'data' => [
  3069. 'roles' => $roles,
  3070. 'scenes' => $scenes,
  3071. 'start_time' => $startTime
  3072. ]
  3073. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3074. ob_flush();
  3075. flush();
  3076. // 持续轮询任务状态
  3077. while (time() - $startTime < $maxDuration) {
  3078. $hasProcessing = false;
  3079. $updated = false;
  3080. // 检查角色任务状态
  3081. foreach ($roles as $index => &$role) {
  3082. $task_id = getProp($role, 'task_id');
  3083. $task_status = getProp($role, 'task_status');
  3084. $existing_url = getProp($role, 'url');
  3085. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3086. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3087. $hasProcessing = ($task_status === 'processing');
  3088. // 查询任务状态
  3089. $task = DB::table('mp_generate_pic_tasks')
  3090. ->where('id', $task_id)
  3091. ->select('id', 'status', 'result_url', 'error_message')
  3092. ->first();
  3093. if ($task) {
  3094. $task = (array)$task;
  3095. $status = getProp($task, 'status');
  3096. // 如果任务完成或失败
  3097. if (in_array($status, ['success', 'failed'])) {
  3098. $role['task_status'] = $status;
  3099. if ($status === 'success') {
  3100. $result_url = getProp($task, 'result_url');
  3101. if ($result_url) {
  3102. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3103. if (is_array($result_urls) && !empty($result_urls[0])) {
  3104. $role['url'] = $result_urls[0];
  3105. }
  3106. }
  3107. }
  3108. $updated = true;
  3109. } else if ($status === 'processing') {
  3110. $hasProcessing = true;
  3111. }
  3112. }
  3113. }
  3114. }
  3115. // 检查场景任务状态
  3116. foreach ($scenes as $index => &$scene) {
  3117. $task_id = getProp($scene, 'task_id');
  3118. $task_status = getProp($scene, 'task_status');
  3119. $existing_url = getProp($scene, 'url');
  3120. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3121. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3122. $hasProcessing = ($task_status === 'processing');
  3123. // 查询任务状态
  3124. $task = DB::table('mp_generate_pic_tasks')
  3125. ->where('id', $task_id)
  3126. ->select('id', 'status', 'result_url', 'error_message')
  3127. ->first();
  3128. if ($task) {
  3129. $task = (array)$task;
  3130. $status = getProp($task, 'status');
  3131. // 如果任务完成或失败
  3132. if (in_array($status, ['success', 'failed'])) {
  3133. $scene['task_status'] = $status;
  3134. if ($status === 'success') {
  3135. $result_url = getProp($task, 'result_url');
  3136. if ($result_url) {
  3137. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3138. if (is_array($result_urls) && !empty($result_urls[0])) {
  3139. $scene['url'] = $result_urls[0];
  3140. }
  3141. }
  3142. }
  3143. $updated = true;
  3144. } else if ($status === 'processing') {
  3145. $hasProcessing = true;
  3146. }
  3147. }
  3148. }
  3149. }
  3150. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3151. if ($updated) {
  3152. $newHash = $generateHash($roles, $scenes);
  3153. $cachedHash = Redis::get($cacheKey);
  3154. // 只有当数据真正变化时才更新数据库和发送事件
  3155. if ($newHash !== $cachedHash) {
  3156. try {
  3157. // 更新数据库
  3158. DB::table($table_name)->where($id_field, $id_value)->update([
  3159. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3160. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3161. 'updated_at' => date('Y-m-d H:i:s')
  3162. ]);
  3163. // 更新缓存
  3164. Redis::setex($cacheKey, 600, $newHash);
  3165. // 发送更新事件
  3166. echo "data: " . json_encode([
  3167. 'type' => 'update',
  3168. 'data' => [
  3169. 'roles' => $roles,
  3170. 'scenes' => $scenes,
  3171. 'elapsed_time' => time() - $startTime
  3172. ]
  3173. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3174. ob_flush();
  3175. flush();
  3176. } catch (\Exception $e) {
  3177. dLog('anime')->error('更新角色/场景信息失败: ' . $e->getMessage());
  3178. }
  3179. } else {
  3180. // 即使哈希相同,如果有URL更新也要发送事件
  3181. $hasUrlUpdate = false;
  3182. foreach ($roles as $role) {
  3183. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3184. $hasUrlUpdate = true;
  3185. break;
  3186. }
  3187. }
  3188. if (!$hasUrlUpdate) {
  3189. foreach ($scenes as $scene) {
  3190. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3191. $hasUrlUpdate = true;
  3192. break;
  3193. }
  3194. }
  3195. }
  3196. if ($hasUrlUpdate) {
  3197. // 强制更新数据库和发送事件
  3198. try {
  3199. DB::table($table_name)->where($id_field, $id_value)->update([
  3200. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3201. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3202. 'updated_at' => date('Y-m-d H:i:s')
  3203. ]);
  3204. // 更新缓存
  3205. Redis::setex($cacheKey, 600, $newHash);
  3206. // 发送更新事件
  3207. echo "data: " . json_encode([
  3208. 'type' => 'update',
  3209. 'data' => [
  3210. 'roles' => $roles,
  3211. 'scenes' => $scenes,
  3212. 'elapsed_time' => time() - $startTime
  3213. ]
  3214. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3215. ob_flush();
  3216. flush();
  3217. } catch (\Exception $e) {
  3218. dLog('anime')->error('强制更新角色/场景信息失败: ' . $e->getMessage());
  3219. }
  3220. }
  3221. }
  3222. }
  3223. // 如果所有任务都已完成,发送完成事件并退出
  3224. if (!$hasProcessing) {
  3225. // 查询数据库中的最终数据,确保返回最新的完整数据
  3226. try {
  3227. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3228. if ($finalSource) {
  3229. $finalSource = (array)$finalSource;
  3230. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3231. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3232. // 使用数据库中的最终数据
  3233. $roles = $finalRoles;
  3234. $scenes = $finalScenes;
  3235. }
  3236. } catch (\Exception $e) {
  3237. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3238. // 如果查询失败,继续使用内存中的数据
  3239. }
  3240. // 清理缓存
  3241. Redis::del($cacheKey);
  3242. echo "data: " . json_encode([
  3243. 'type' => 'completed',
  3244. 'data' => [
  3245. 'roles' => $roles,
  3246. 'scenes' => $scenes,
  3247. 'total_time' => time() - $startTime
  3248. ]
  3249. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3250. ob_flush();
  3251. flush();
  3252. break;
  3253. }
  3254. // 等待下次检查
  3255. sleep($checkInterval);
  3256. }
  3257. // 超时处理
  3258. if (time() - $startTime >= $maxDuration) {
  3259. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3260. try {
  3261. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3262. if ($finalSource) {
  3263. $finalSource = (array)$finalSource;
  3264. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3265. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3266. // 使用数据库中的最终数据
  3267. $roles = $finalRoles;
  3268. $scenes = $finalScenes;
  3269. }
  3270. } catch (\Exception $e) {
  3271. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3272. // 如果查询失败,继续使用内存中的数据
  3273. }
  3274. // 清理缓存
  3275. Redis::del($cacheKey);
  3276. echo "data: " . json_encode([
  3277. 'type' => 'timeout',
  3278. 'message' => '轮询超时,请刷新页面查看最新状态',
  3279. 'data' => [
  3280. 'roles' => $roles,
  3281. 'scenes' => $scenes
  3282. ]
  3283. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3284. ob_flush();
  3285. flush();
  3286. }
  3287. };
  3288. }
  3289. public function clipSegmentVideo($data) {
  3290. $segment_id = getProp($data, 'segment_id');
  3291. $video_time_point_start = getProp($data, 'video_time_point_start');
  3292. $video_time_point_end = getProp($data, 'video_time_point_end');
  3293. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3294. Utils::throwError('20003:参数异常');
  3295. }
  3296. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3297. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3298. }
  3299. $video_duration = $video_time_point_end - $video_time_point_start;
  3300. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3301. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3302. 'video_duration' => $video_duration,
  3303. 'video_time_point_start' => $video_time_point_start,
  3304. 'video_time_point_end' => $video_time_point_end,
  3305. 'updated_at' => date('Y-m-d H:i:s')
  3306. ]);
  3307. }
  3308. // 轮训获取图片任务结果
  3309. private function loopGetPicTaskResult($task_id) {
  3310. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3311. if (!$task) {
  3312. return '';
  3313. }
  3314. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3315. $model = getProp($task, 'model');
  3316. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3317. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3318. $isSyncModel = $isVolcModel || $isGptModel;
  3319. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3320. $start_count = 0;
  3321. $img_url = '';
  3322. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3323. sleep(3);
  3324. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3325. // 如果任务已经完成,直接返回结果
  3326. if ($task->status === 'success' && $task->result_url) {
  3327. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3328. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3329. }
  3330. // 如果任务已失败,返回空
  3331. if ($task->status === 'failed') {
  3332. return '';
  3333. }
  3334. if ($isSyncModel) continue;
  3335. // 查询任务状态
  3336. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3337. if ($statusInfo['status'] === 'success') {
  3338. $task->updateStatus('success', [
  3339. 'result_url' => $statusInfo['result_url'],
  3340. 'result_json' => $statusInfo['result_json'] ?? []
  3341. ]);
  3342. // 同步调整分镜图片状态和结果
  3343. if (getProp($task, 'alias_segment_id')) {
  3344. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3345. 'img_url' => $statusInfo['result_url'][0],
  3346. 'pic_task_status' => '已完成',
  3347. ]);
  3348. }
  3349. $img_url = $statusInfo['result_url'][0];
  3350. break;
  3351. } elseif ($statusInfo['status'] === 'failed') {
  3352. $task->updateStatus('failed', [
  3353. 'error_message' => $statusInfo['error_message'],
  3354. 'result_json' => $statusInfo['result_json'] ?? []
  3355. ]);
  3356. if (getProp($task, 'alias_segment_id')) {
  3357. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3358. 'pic_task_status' => '失败',
  3359. ]);
  3360. }
  3361. break;
  3362. }
  3363. $start_count++;
  3364. }
  3365. return $img_url;
  3366. }
  3367. /**
  3368. * 从分镜内容中提取涉及的角色
  3369. */
  3370. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3371. $found_characters = [];
  3372. foreach ($available_characters as $character) {
  3373. // 检查角色名称是否在分镜内容中出现
  3374. if (strpos($segment_content, $character) !== false) {
  3375. $found_characters[] = $character;
  3376. }
  3377. }
  3378. if (!$found_characters) {
  3379. foreach ($roles as $character) {
  3380. // 检查角色名称是否在分镜内容中出现
  3381. if (strpos($segment_content, $character) !== false) {
  3382. $found_characters[] = $character;
  3383. }
  3384. }
  3385. }
  3386. return array_unique($found_characters);
  3387. }
  3388. // 从分镜剧本中提取关键字段
  3389. private function handleSegmentContent(&$data) {
  3390. $segmentContent = getProp($data, 'segment_content');
  3391. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3392. $segmentData = [
  3393. 'description' => '',
  3394. 'composition' => '',
  3395. 'camera_movement' => '',
  3396. 'voice_actor' => '',
  3397. 'dialogue' => '',
  3398. 'frame_type' => '',
  3399. 'scene' => '', // 场景
  3400. 'characters' => '', // 出镜角色
  3401. 'tail_frame' => '', // 尾帧描述
  3402. 'emotion' => '中性', // 情感
  3403. 'gender' => '0', // 性别(0未知,1男,2女)
  3404. 'speed_ratio' => 0, // 语速
  3405. 'loudness_ratio' => 0, // 音量
  3406. 'emotion_scale' => 4, // 情感强度
  3407. 'pitch' => 0, // 音调
  3408. ];
  3409. // 用于存储需要从 segment_content 中移除的匹配项
  3410. $replaceEmptyArr = [];
  3411. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3412. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3413. $segmentData['description'] = trim($descMatch[1]);
  3414. $data['description'] = trim($descMatch[1]);
  3415. }
  3416. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3417. $segmentData['composition'] = trim($compMatch[1]);
  3418. $data['composition'] = trim($compMatch[1]);
  3419. }
  3420. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3421. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3422. $data['camera_movement'] = trim($cameraMatch[1]);
  3423. }
  3424. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3425. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3426. $data['voice_actor'] = trim($voiceMatch[1]);
  3427. }
  3428. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3429. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3430. $data['dialogue'] = trim($dialogueMatch[1]);
  3431. }
  3432. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3433. $segmentData['frame_type'] = trim($frameMatch[1]);
  3434. $data['frame_type'] = trim($frameMatch[1]);
  3435. }
  3436. // 场景字段
  3437. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3438. $segmentData['scene'] = trim($sceneMatch[1]);
  3439. $data['scene'] = trim($sceneMatch[1]);
  3440. }
  3441. // 出镜角色字段
  3442. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3443. $segmentData['characters'] = trim($charactersMatch[1]);
  3444. $data['characters'] = trim($charactersMatch[1]);
  3445. }
  3446. // 尾帧描述字段
  3447. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3448. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3449. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3450. }
  3451. // 情感字段
  3452. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3453. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3454. $segmentData['emotion'] = trim($emotionMatch[1]);
  3455. $data['emotion'] = trim($emotionMatch[1]);
  3456. }
  3457. // 性别字段
  3458. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3459. $replaceEmptyArr[] = trim($genderMatch[0]);
  3460. $genderStr = trim($genderMatch[1]);
  3461. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3462. $segmentData['gender'] = '1';
  3463. $data['gender'] = '1';
  3464. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3465. $segmentData['gender'] = '2';
  3466. $data['gender'] = '2';
  3467. } else {
  3468. $segmentData['gender'] = '0';
  3469. $data['gender'] = '0';
  3470. }
  3471. }
  3472. // 语速字段
  3473. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3474. $replaceEmptyArr[] = trim($speedMatch[0]);
  3475. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3476. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3477. }
  3478. // 音量字段
  3479. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3480. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3481. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3482. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3483. }
  3484. // 情感强度字段
  3485. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3486. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3487. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3488. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3489. }
  3490. // 音调字段
  3491. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3492. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3493. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3494. $data['pitch'] = (int)trim($pitchMatch[1]);
  3495. }
  3496. // 从 segment_content 中移除已提取的配音参数字段
  3497. if (!empty($replaceEmptyArr)) {
  3498. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3499. }
  3500. // 如果有配音角色,查询音色信息并验证情感
  3501. $voice_actor = $segmentData['voice_actor'];
  3502. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3503. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3504. $anime_id = getProp($data, 'anime_id');
  3505. $episode_id = getProp($data, 'episode_id');
  3506. // 优先从剧集的角色列表中查找
  3507. $roles = [];
  3508. if ($episode_id) {
  3509. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3510. if ($episode && getProp($episode, 'roles')) {
  3511. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3512. }
  3513. }
  3514. // 如果剧集中没有,从动漫的角色列表中查找
  3515. if (empty($roles) && $anime_id) {
  3516. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3517. if ($anime && getProp($anime, 'roles')) {
  3518. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3519. }
  3520. }
  3521. // 查找匹配的角色音色信息
  3522. $timbre_info = null;
  3523. foreach ($roles as $role) {
  3524. if (getProp($role, 'role') === $voice_actor) {
  3525. $timbre_info = $role;
  3526. break;
  3527. }
  3528. }
  3529. // 如果找到音色信息,添加到数据中
  3530. if ($timbre_info) {
  3531. $voice_type = getProp($timbre_info, 'voice_type');
  3532. $voice_name = getProp($timbre_info, 'voice_name');
  3533. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3534. if ($voice_type) {
  3535. $data['voice_type'] = $voice_type;
  3536. $segmentData['voice_type'] = $voice_type;
  3537. }
  3538. if ($voice_name) {
  3539. $data['voice_name'] = $voice_name;
  3540. $segmentData['voice_name'] = $voice_name;
  3541. }
  3542. if ($voice_audio_url) {
  3543. $data['voice_audio_url'] = $voice_audio_url;
  3544. $segmentData['voice_audio_url'] = $voice_audio_url;
  3545. }
  3546. // 验证情感是否在音色支持的情感列表中
  3547. if ($voice_type) {
  3548. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3549. if ($timbre_emotion) {
  3550. $timbre_emotion = explode(',', $timbre_emotion);
  3551. } else {
  3552. $timbre_emotion = [];
  3553. }
  3554. $emotion = getProp($segmentData, 'emotion', '中性');
  3555. if (!in_array($emotion, $timbre_emotion)) {
  3556. $emotion = '中性';
  3557. }
  3558. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3559. $emotion_list = array_flip($emotion_list);
  3560. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3561. $data['emotion_type'] = $emotion_type;
  3562. $segmentData['emotion_type'] = $emotion_type;
  3563. }
  3564. }
  3565. }
  3566. return $segmentData;
  3567. }
  3568. public function createSegmentVideoTask($data) {
  3569. $segment_id = getProp($data, 'segment_id');
  3570. $tail_frame = getProp($data, 'tail_frame');
  3571. $first_frame_url = getProp($data, 'first_frame_url');
  3572. $tail_frame_url = getProp($data, 'tail_frame_url');
  3573. $generate_audio = getProp($data, 'generate_audio', 0);
  3574. if (!$segment_id) {
  3575. Utils::throwError('1002:分镜ID不能为空');
  3576. }
  3577. // 获取分镜信息
  3578. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3579. if (!$segment) {
  3580. Utils::throwError('20003:分镜不存在');
  3581. }
  3582. $segment = (array)$segment;
  3583. $episode_id = getProp($segment, 'episode_id');
  3584. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3585. if (!$ratio) $ratio = '9:16';
  3586. // 获取分镜内容
  3587. $segmentContent = getProp($segment, 'segment_content', '');
  3588. // 检查 $segmentContent 中是否已有尾帧描述
  3589. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3590. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3591. $finalTailFrame = '';
  3592. if ($tail_frame) {
  3593. // 用户输入了尾帧描述,优先使用
  3594. $finalTailFrame = $tail_frame;
  3595. // 如果 segmentContent 中已有尾帧描述,需要替换
  3596. if ($contentHasTailFrame) {
  3597. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3598. }
  3599. } elseif ($contentHasTailFrame) {
  3600. // segmentContent 中有尾帧描述,使用它
  3601. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3602. } else {
  3603. // 两者都没有,使用分镜表中的尾帧描述
  3604. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3605. }
  3606. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3607. $hasDialogue = false;
  3608. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3609. $dialogue = trim($dialogueMatch[1]);
  3610. // 如果台词不为空且不是"无"
  3611. if (!empty($dialogue) && $dialogue !== '无') {
  3612. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3613. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3614. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3615. $hasDialogue = true;
  3616. }
  3617. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3618. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3619. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3620. if (!preg_match('/^[“]/', $dialogue)) {
  3621. $dialogue = '“' . $dialogue;
  3622. }
  3623. if (!preg_match('/[”]$/', $dialogue)) {
  3624. $dialogue .= '”';
  3625. }
  3626. // 将修改后的台词替换回 $segmentContent
  3627. $originalDialogue = $dialogueMatch[1];
  3628. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3629. }
  3630. }
  3631. // 构建完整的提示词
  3632. $fullPrompt = $segmentContent;
  3633. if ($finalTailFrame && !$contentHasTailFrame) {
  3634. // 只有当 segmentContent 中没有尾帧描述时才追加
  3635. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3636. }
  3637. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3638. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3639. $fullPrompt = trim($fullPrompt);
  3640. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3641. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3642. // 智能选择视频时长
  3643. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3644. $videoDuration = -1;
  3645. // 处理视频模型
  3646. $model = getProp($data, 'model');
  3647. if (!$model) {
  3648. // 用户没有输入,从episode表获取
  3649. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3650. $model = getProp($episode, 'video_model');
  3651. if (!$model) {
  3652. // episode表也没有,使用默认值
  3653. $model = 'doubao-seedance-1-5-pro-251215';
  3654. }
  3655. }
  3656. // 验证模型是否在可用模型表中
  3657. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3658. $model = 'doubao-seedance-1-5-pro-251215';
  3659. }
  3660. // 保存到episode表
  3661. $episode_id = getProp($segment, 'episode_id');
  3662. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3663. 'video_model' => $model,
  3664. 'updated_at' => date('Y-m-d H:i:s')
  3665. ]);
  3666. // 构建视频生成参数
  3667. $videoParams = [
  3668. 'model' => $model,
  3669. 'alias_segment_id' => $segment_id,
  3670. 'prompt' => trim($fullPrompt),
  3671. 'video_duration' => $videoDuration,
  3672. 'video_resolution' => '720P',
  3673. 'seed' => -1,
  3674. 'ratio' => $ratio,
  3675. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3676. 'draft' => false,
  3677. 'watermark' => false,
  3678. 'camera_fixed' => false,
  3679. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3680. ];
  3681. // 如果分镜有图片,作为首帧
  3682. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3683. $hasVideo = !empty(getProp($segment, 'video_url'));
  3684. if ($hasImage) {
  3685. if ($first_frame_url) {
  3686. $videoParams['first_frame_url'] = $first_frame_url;
  3687. }else {
  3688. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3689. }
  3690. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3691. }
  3692. // 构建content数组
  3693. $videoParams['content'] = [
  3694. [
  3695. 'type' => 'text',
  3696. 'text' => $videoParams['prompt'],
  3697. ]
  3698. ];
  3699. // 如果有首帧图片,添加到content中
  3700. if ($hasImage) {
  3701. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3702. $videoParams['content'][] = [
  3703. 'type' => 'image_url',
  3704. 'image_url' => [
  3705. 'url' => $videoParams['first_frame_url'],
  3706. ],
  3707. 'role' => 'reference_image',
  3708. ];
  3709. if (isset($videoParams['tail_frame_url'])) {
  3710. $videoParams['content'][] = [
  3711. 'type' => 'image_url',
  3712. 'image_url' => [
  3713. 'url' => $videoParams['tail_frame_url'],
  3714. ],
  3715. 'role' => 'reference_image',
  3716. ];
  3717. }
  3718. }else {
  3719. $videoParams['content'][] = [
  3720. 'type' => 'image_url',
  3721. 'image_url' => [
  3722. 'url' => $videoParams['first_frame_url'],
  3723. ],
  3724. 'role' => 'first_frame',
  3725. ];
  3726. if (isset($videoParams['tail_frame_url'])) {
  3727. $videoParams['content'][] = [
  3728. 'type' => 'image_url',
  3729. 'image_url' => [
  3730. 'url' => $videoParams['tail_frame_url'],
  3731. ],
  3732. 'role' => 'last_frame',
  3733. ];
  3734. }
  3735. }
  3736. }
  3737. // 获取配音音频URL
  3738. $audioUrl = getProp($segment, 'audio_url');
  3739. $audioDuration = getProp($segment, 'audio_duration');
  3740. // 音频传入的前提:必须有至少一张图片或一个视频
  3741. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  3742. // dd($videoParams);
  3743. // 根据模型选择不同的视频生成方法
  3744. if (strpos($model, 'jimeng') !== false) {
  3745. // 即梦模型参数调整
  3746. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  3747. unset($videoParams['content']); // 即梦不使用content格式
  3748. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  3749. } elseif (strpos($model, 'kling') !== false) {
  3750. // Keling模型参数调整
  3751. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  3752. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  3753. unset($videoParams['ratio']);
  3754. unset($videoParams['content']); // Keling不使用content格式
  3755. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  3756. } elseif (strpos($model, 'zhizhen') !== false) {
  3757. // 智帧20等新模型使用统一API
  3758. // 构建统一API参数
  3759. $unifiedParams = [
  3760. 'model_code' => $model,
  3761. 'alias_segment_id' => $segment_id,
  3762. 'prompt' => trim($fullPrompt),
  3763. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  3764. 'video_resolution' => strtolower($videoParams['video_resolution']),
  3765. 'video_ratio' => $ratio,
  3766. 'seed' => -1,
  3767. ];
  3768. // 构建parameters参数
  3769. $parameters = [
  3770. 'seconds' => $unifiedParams['video_duration'],
  3771. 'resolution' => $unifiedParams['video_resolution'],
  3772. 'ratio' => $ratio,
  3773. // 'video_mode' => 'multi_image',
  3774. // 'mode' => 'multi_image',
  3775. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  3776. ];
  3777. $hasImage = false;
  3778. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  3779. if ($hasImage) {
  3780. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  3781. if (isset($videoParams['tail_frame_url'])) {
  3782. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  3783. }
  3784. // 只有在有图片的情况下才能添加参考音频
  3785. if ($audioUrl) {
  3786. // $parameters['reference_audios'] = [$audioUrl];
  3787. }
  3788. } else {
  3789. // 没有图片时,记录错误日志
  3790. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  3791. 'segment_id' => $segment_id,
  3792. 'model' => $model
  3793. ]);
  3794. }
  3795. $unifiedParams['parameters'] = $parameters;
  3796. // 调用统一API创建任务
  3797. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  3798. } else {
  3799. // Seedance模型(默认)
  3800. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  3801. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3802. // 添加配音音频到content中
  3803. $videoParams['content'][] = [
  3804. 'type' => 'audio_url',
  3805. 'audio_url' => [
  3806. 'url' => $audioUrl,
  3807. ],
  3808. 'role' => 'reference_audio',
  3809. ];
  3810. // 优化提示词,增加音频相关描述
  3811. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  3812. $videoParams['prompt'] = $audioPrompt;
  3813. $videoParams['content'][0]['text'] = $audioPrompt;
  3814. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  3815. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  3816. }
  3817. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  3818. }
  3819. // 更新分镜表的视频任务信息
  3820. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3821. 'video_task_id' => $task->id,
  3822. 'video_task_status' => '生成中',
  3823. 'generate_audio' => $generate_audio,
  3824. 'updated_at' => date('Y-m-d H:i:s')
  3825. ]);
  3826. return [
  3827. 'task_id' => $task->id,
  3828. 'status' => $task->status,
  3829. 'segment_id' => $segment_id,
  3830. 'video_duration' => $videoDuration
  3831. ];
  3832. }
  3833. public function createActVideoTask($data) {
  3834. $act_id = getProp($data, 'act_id');
  3835. $first_frame_url = getProp($data, 'first_frame_url');
  3836. $tail_frame_url = getProp($data, 'tail_frame_url');
  3837. $generate_audio = getProp($data, 'generate_audio', 1);
  3838. $video_duration = getProp($data, 'video_duration');
  3839. $video_resolution = getProp($data, 'video_resolution');
  3840. $ratio = getProp($data, 'ratio');
  3841. $products = getProp($data, 'products', []);
  3842. $reference_images = array_unique(getProp($data, 'reference_images', []));
  3843. if (!is_array($reference_images) || !is_array($products)) {
  3844. Utils::throwError('20003:传入的参考图或资产格式不正确');
  3845. }
  3846. if (!$act_id) {
  3847. Utils::throwError('1002:片段ID不能为空');
  3848. }
  3849. // 获取片段信息
  3850. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  3851. if (!$act) {
  3852. Utils::throwError('20003:片段不存在');
  3853. }
  3854. $act = (array)$act;
  3855. $anime_id = getProp($act, 'anime_id');
  3856. $episode_id = getProp($act, 'episode_id');
  3857. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3858. $ace_mode = getProp($anime, 'ace_mode');
  3859. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3860. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  3861. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  3862. // 将资产中新出现的资产放到extra_products中
  3863. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles和scenes做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  3864. if (!empty($products) && $episode) {
  3865. // 获取剧集中的角色和场景列表
  3866. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  3867. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  3868. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  3869. // 构建角色名称列表
  3870. $role_names = array_column($roles, 'role');
  3871. // 构建场景名称列表
  3872. $scene_names = array_column($scenes, 'scene');
  3873. // 遍历传入的products
  3874. foreach ($products as $product) {
  3875. $product_name = getProp($product, 'product_name');
  3876. // 如果product_name不在roles和scenes中
  3877. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names)) {
  3878. // 查找是否在extra_products中存在同名的
  3879. $found = false;
  3880. foreach ($extra_products as $key => $extra_product) {
  3881. if (getProp($extra_product, 'product_name') === $product_name) {
  3882. // 有同名的则覆盖
  3883. $extra_products[$key] = $product;
  3884. $found = true;
  3885. break;
  3886. }
  3887. }
  3888. // 没有则新增
  3889. if (!$found) {
  3890. $extra_products[] = $product;
  3891. }
  3892. }
  3893. }
  3894. if ($extra_products) {
  3895. // 保存到数据库
  3896. DB::table('mp_anime_episodes')
  3897. ->where('id', $episode_id)
  3898. ->update([
  3899. 'extra_products' => json_encode($extra_products, 256),
  3900. 'updated_at' => date('Y-m-d H:i:s')
  3901. ]);
  3902. }
  3903. }
  3904. // 获取分镜内容
  3905. $actContent = getProp($act, 'act_show_content', '');
  3906. // 音效同出(默认使用)
  3907. $current_generate_audio = $generate_audio ? 1 : 0;
  3908. // 构建完整的提示词
  3909. $processResult = $this->processActContentWithProducts($actContent, $products);
  3910. $fullPrompt = $processResult['content'];
  3911. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  3912. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  3913. // 处理视频模型
  3914. $model = getProp($data, 'model');
  3915. if (!$model) {
  3916. $model = getProp($episode, 'video_model');
  3917. if (!$model) {
  3918. // episode表也没有,使用默认值
  3919. $model = 'zhizhen-20-mini';
  3920. }
  3921. }
  3922. // 验证模型是否在可用模型表中
  3923. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3924. $model = 'zhizhen-20-mini';
  3925. }
  3926. // 保存到episode表
  3927. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3928. 'video_model' => $model,
  3929. 'updated_at' => date('Y-m-d H:i:s')
  3930. ]);
  3931. // 构建视频生成参数
  3932. $videoParams = [
  3933. 'model' => $model,
  3934. 'alias_act_id' => $act_id,
  3935. 'prompt' => trim($fullPrompt),
  3936. 'video_duration' => $videoDuration,
  3937. 'video_resolution' => $video_resolution,
  3938. 'seed' => -1,
  3939. 'ratio' => $ratio,
  3940. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3941. 'draft' => false,
  3942. 'watermark' => false,
  3943. 'camera_fixed' => false,
  3944. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3945. ];
  3946. // 如果分镜有图片,作为首帧
  3947. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  3948. $hasVideo = !empty(getProp($act, 'video_url'));
  3949. if ($hasImage) {
  3950. if ($first_frame_url) {
  3951. $videoParams['first_frame_url'] = $first_frame_url;
  3952. }else {
  3953. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  3954. }
  3955. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3956. }
  3957. // 构建content数组
  3958. $videoParams['content'] = [
  3959. [
  3960. 'type' => 'text',
  3961. 'text' => $videoParams['prompt'],
  3962. ]
  3963. ];
  3964. // 如果有首帧图片,添加到content中
  3965. if ($hasImage) {
  3966. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3967. $videoParams['content'][] = [
  3968. 'type' => 'image_url',
  3969. 'image_url' => [
  3970. 'url' => $videoParams['first_frame_url'],
  3971. ],
  3972. 'role' => 'reference_image',
  3973. ];
  3974. if (isset($videoParams['tail_frame_url'])) {
  3975. $videoParams['content'][] = [
  3976. 'type' => 'image_url',
  3977. 'image_url' => [
  3978. 'url' => $videoParams['tail_frame_url'],
  3979. ],
  3980. 'role' => 'reference_image',
  3981. ];
  3982. }
  3983. }else {
  3984. $videoParams['content'][] = [
  3985. 'type' => 'image_url',
  3986. 'image_url' => [
  3987. 'url' => $videoParams['first_frame_url'],
  3988. ],
  3989. 'role' => 'first_frame',
  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' => 'last_frame',
  3998. ];
  3999. }
  4000. }
  4001. }
  4002. // dd($videoParams);
  4003. // 根据模型选择不同的视频生成方法
  4004. if (strpos($model, 'jimeng') !== false) {
  4005. // 即梦模型参数调整
  4006. unset($videoParams['content']); // 即梦不使用content格式
  4007. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4008. } elseif (strpos($model, 'kling') !== false) {
  4009. // Keling模型参数调整
  4010. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4011. unset($videoParams['ratio']);
  4012. unset($videoParams['content']); // Keling不使用content格式
  4013. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4014. } elseif (strpos($model, 'zhizhen') !== false) {
  4015. // 智帧20等新模型使用统一API
  4016. // 构建统一API参数
  4017. $unifiedParams = [
  4018. 'model_code' => $model,
  4019. 'alias_act_id' => $act_id,
  4020. 'prompt' => trim($fullPrompt),
  4021. 'video_duration' => $videoDuration,
  4022. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4023. 'video_ratio' => $ratio,
  4024. 'seed' => -1,
  4025. ];
  4026. // 构建parameters参数
  4027. $parameters = [
  4028. 'seconds' => $unifiedParams['video_duration'],
  4029. 'resolution' => $unifiedParams['video_resolution'],
  4030. 'ratio' => $ratio,
  4031. // 'video_mode' => 'multi_image',
  4032. // 'mode' => 'multi_image',
  4033. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4034. ];
  4035. $hasImage = false;
  4036. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4037. if ($hasImage) {
  4038. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4039. if (isset($videoParams['tail_frame_url'])) {
  4040. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4041. }
  4042. } else {
  4043. // 没有图片时,记录错误日志
  4044. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4045. 'act_id' => $act_id,
  4046. 'model' => $model
  4047. ]);
  4048. }
  4049. if ($reference_images) {
  4050. // 限制只传入9张参考图
  4051. $reference_images = array_slice($reference_images, 0, 9);
  4052. // 在处理之前先保存原始reference_images到任务参数中
  4053. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4054. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4055. $parameters['reference_images'] = $reference_images;
  4056. $parameters['video_mode'] = 'multi_image';
  4057. $parameters['mode'] = 'multi_image';
  4058. }
  4059. $unifiedParams['parameters'] = $parameters;
  4060. // 调用统一API创建任务
  4061. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4062. } else {
  4063. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4064. }
  4065. // 更新分镜表的视频任务信息
  4066. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4067. 'video_task_id' => $task->id,
  4068. 'video_task_status' => '生成中',
  4069. 'generate_audio' => $generate_audio,
  4070. 'updated_at' => date('Y-m-d H:i:s')
  4071. ]);
  4072. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4073. $episode_number = getProp($act, 'episode_number');
  4074. $act_number = getProp($act, 'act_number');
  4075. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4076. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4077. }
  4078. return [
  4079. 'task_id' => $task->id,
  4080. 'status' => $task->status,
  4081. 'act_id' => $act_id,
  4082. 'video_duration' => $videoDuration
  4083. ];
  4084. }
  4085. /**
  4086. * 根据提示词内容智能计算最优视频时长
  4087. *
  4088. * @param string $segmentContent 分镜内容
  4089. * @param string $tailFrame 尾帧描述
  4090. * @return int 视频时长(2-12秒)
  4091. */
  4092. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4093. // 合并所有文本内容
  4094. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4095. // 如果没有内容,返回默认时长
  4096. if (empty($fullText)) {
  4097. return 5;
  4098. }
  4099. // 计算文本长度(中文字符按2个字符计算)
  4100. $textLength = mb_strlen($fullText, 'UTF-8');
  4101. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4102. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4103. // 分析内容复杂度
  4104. $complexityScore = $this->analyzeContentComplexity($fullText);
  4105. // 基础时长计算(根据文本长度)
  4106. $baseDuration = 3; // 默认2秒
  4107. // if ($adjustedLength <= 20) {
  4108. // $baseDuration = 3;
  4109. // } elseif ($adjustedLength <= 40) {
  4110. // $baseDuration = 4;
  4111. // } elseif ($adjustedLength <= 60) {
  4112. // $baseDuration = 5;
  4113. // } elseif ($adjustedLength <= 80) {
  4114. // $baseDuration = 6;
  4115. // } elseif ($adjustedLength <= 100) {
  4116. // $baseDuration = 7;
  4117. // } elseif ($adjustedLength <= 120) {
  4118. // $baseDuration = 8;
  4119. // } else {
  4120. // $baseDuration = 9;
  4121. // }
  4122. // 根据内容复杂度调整时长
  4123. $finalDuration = $baseDuration + $complexityScore;
  4124. // 确保时长在2-12秒范围内
  4125. return max(4, min(12, $finalDuration));
  4126. }
  4127. /**
  4128. * 分析内容复杂度,返回时长调整值
  4129. *
  4130. * @param string $text 文本内容
  4131. * @return int 调整值(-2到+3)
  4132. */
  4133. private function analyzeContentComplexity($text) {
  4134. $score = 0;
  4135. // 动作关键词(需要更长时间展现)
  4136. $actionKeywords = [
  4137. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4138. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4139. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4140. ];
  4141. // 静态关键词(可以用较短时间)
  4142. $staticKeywords = [
  4143. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4144. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4145. ];
  4146. // 复杂场景关键词(需要更长时间)
  4147. $complexSceneKeywords = [
  4148. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4149. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4150. ];
  4151. // 情感关键词(需要适中时间表现)
  4152. $emotionKeywords = [
  4153. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4154. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4155. ];
  4156. // 检查动作关键词
  4157. foreach ($actionKeywords as $keyword) {
  4158. if (strpos($text, $keyword) !== false) {
  4159. $score += 1;
  4160. break; // 避免重复加分
  4161. }
  4162. }
  4163. // 检查静态关键词
  4164. foreach ($staticKeywords as $keyword) {
  4165. if (strpos($text, $keyword) !== false) {
  4166. $score -= 1;
  4167. break;
  4168. }
  4169. }
  4170. // 检查复杂场景关键词
  4171. foreach ($complexSceneKeywords as $keyword) {
  4172. if (strpos($text, $keyword) !== false) {
  4173. $score += 1;
  4174. break;
  4175. }
  4176. }
  4177. // 检查情感关键词
  4178. foreach ($emotionKeywords as $keyword) {
  4179. if (strpos($text, $keyword) !== false) {
  4180. $score += 1;
  4181. break;
  4182. }
  4183. }
  4184. // 检查时间相关词汇
  4185. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4186. $score += 1;
  4187. }
  4188. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4189. $score -= 1;
  4190. }
  4191. // 检查转场词汇
  4192. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4193. $score += 1;
  4194. }
  4195. // 检查环境描述(复杂环境需要更多时间)
  4196. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4197. $score += 1;
  4198. }
  4199. // 检查对话内容(对话需要更多时间)
  4200. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4201. $score += 1;
  4202. }
  4203. // 限制调整范围
  4204. return max(-1, min(4, $score));
  4205. }
  4206. /**
  4207. * 创建完整视频合成任务
  4208. *
  4209. * @param array $data
  4210. * @return array
  4211. */
  4212. public function createCompleteVideoTask($data)
  4213. {
  4214. $animeId = getProp($data, 'anime_id');
  4215. $episodeId = getProp($data, 'episode_id');
  4216. // 验证参数
  4217. if (!$animeId || !$episodeId) {
  4218. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4219. }
  4220. // 检查是否已存在处理中的任务
  4221. $existingTask = DB::table('mp_complete_video_tasks')
  4222. ->where('anime_id', $animeId)
  4223. ->where('episode_id', $episodeId)
  4224. ->whereIn('generate_status', ['执行中'])
  4225. ->first();
  4226. if ($existingTask) {
  4227. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4228. }
  4229. // 获取全能模式状态
  4230. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4231. if ((int)$ace_mode === 1) {
  4232. // 获取所有片段的配音视频,按 act_number 排序
  4233. $segments = DB::table('mp_episode_segments')
  4234. ->where('anime_id', $animeId)
  4235. ->where('episode_id', $episodeId)
  4236. ->orderBy('segment_number')
  4237. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4238. ->get();
  4239. // 检查是否所有片段都有视频
  4240. $missingVideos = $segments->filter(function($segment) {
  4241. return empty($segment->video_url);
  4242. });
  4243. if ($missingVideos->isNotEmpty()) {
  4244. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4245. }
  4246. }else {
  4247. // 获取所有分镜的配音视频,按 segment_number 排序
  4248. $segments = DB::table('mp_episode_segments')
  4249. ->where('anime_id', $animeId)
  4250. ->where('episode_id', $episodeId)
  4251. ->orderBy('segment_number')
  4252. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4253. ->get();
  4254. // 检查是否所有分镜都有配音和视频
  4255. $missingVideos = $segments->filter(function($segment) {
  4256. return empty($segment->audio_url) || empty($segment->video_url);
  4257. });
  4258. if ($missingVideos->isNotEmpty()) {
  4259. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4260. }
  4261. }
  4262. if ($segments->isEmpty()) {
  4263. Utils::throwError('20003:未找到该剧集的分镜数据');
  4264. }
  4265. // 获取当前完整视频url
  4266. $completeVideoUrl = DB::table('mp_anime_episodes')
  4267. ->where('anime_id', $animeId)
  4268. ->where('id', $episodeId)
  4269. ->value('complete_video_url');
  4270. // 构建 generate_json
  4271. $generateJson = [];
  4272. $sequence = 1;
  4273. foreach ($segments as $segment) {
  4274. if ((int)$ace_mode === 1) {
  4275. $generateJson[] = [
  4276. 'sequence' => $sequence++,
  4277. 'video_url' => $segment->video_url,
  4278. 'video_time_point_start' => $segment->video_time_point_start,
  4279. 'video_time_point_end' => $segment->video_time_point_end
  4280. ];
  4281. }else {
  4282. $generateJson[] = [
  4283. 'sequence' => $sequence++,
  4284. 'video_url' => $segment->video_url,
  4285. 'audio_url' => $segment->audio_url,
  4286. 'video_time_point_start' => $segment->video_time_point_start,
  4287. 'video_time_point_end' => $segment->video_time_point_end
  4288. ];
  4289. }
  4290. }
  4291. // 创建任务
  4292. $now = date('Y-m-d H:i:s');
  4293. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4294. 'anime_id' => $animeId,
  4295. 'episode_id' => $episodeId,
  4296. 'generate_json' => json_encode($generateJson, 256),
  4297. 'generate_status' => '执行中',
  4298. 'complete_video_url' => '',
  4299. 'created_at' => $now,
  4300. 'updated_at' => $now
  4301. ]);
  4302. if (!$taskId) {
  4303. Utils::throwError('20003:创建任务失败');
  4304. }
  4305. // 更新剧集表的任务ID和状态
  4306. $boolen = DB::table('mp_anime_episodes')
  4307. ->where('anime_id', $animeId)
  4308. ->where('id', $episodeId)
  4309. ->update([
  4310. 'complete_video_task_id' => $taskId,
  4311. 'complete_video_task_status' => '执行中',
  4312. 'updated_at' => $now
  4313. ]);
  4314. if (!$boolen) {
  4315. Utils::throwError('20003:更新剧集表失败');
  4316. }
  4317. dLog('anime')->info('创建完整视频合成任务', [
  4318. 'task_id' => $taskId,
  4319. 'anime_id' => $animeId,
  4320. 'episode_id' => $episodeId,
  4321. 'segment_count' => count($generateJson)
  4322. ]);
  4323. // 请求远程服务器执行生成
  4324. $client = new Client(['timeout' => 600, 'verify' => false]);
  4325. try {
  4326. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4327. $response = $result->getBody()->getContents();
  4328. $response_arr = json_decode($response, true);
  4329. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4330. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4331. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4332. // // 更新任务状态为失败
  4333. // DB::table('mp_complete_video_tasks')
  4334. // ->where('id', $taskId)
  4335. // ->update([
  4336. // 'generate_status' => '执行失败',
  4337. // 'error_message' => $error_msg,
  4338. // 'updated_at' => date('Y-m-d H:i:s')
  4339. // ]);
  4340. // // 同步更新剧集表状态
  4341. // DB::table('mp_anime_episodes')
  4342. // ->where('complete_video_task_id', $taskId)
  4343. // ->update([
  4344. // 'complete_video_task_status' => '执行失败',
  4345. // 'updated_at' => date('Y-m-d H:i:s')
  4346. // ]);
  4347. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4348. }
  4349. } catch (\Exception $e) {
  4350. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4351. // 更新任务状态为失败
  4352. DB::table('mp_complete_video_tasks')
  4353. ->where('id', $taskId)
  4354. ->update([
  4355. 'generate_status' => '执行失败',
  4356. 'error_message' => $e->getMessage(),
  4357. 'updated_at' => date('Y-m-d H:i:s')
  4358. ]);
  4359. // 同步更新剧集表状态
  4360. DB::table('mp_anime_episodes')
  4361. ->where('complete_video_task_id', $taskId)
  4362. ->update([
  4363. 'complete_video_task_status' => '执行失败',
  4364. 'updated_at' => date('Y-m-d H:i:s')
  4365. ]);
  4366. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4367. }
  4368. // 开始轮询任务状态
  4369. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4370. $pollInterval = 5; // 每5秒轮询一次
  4371. $attempt = 0;
  4372. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4373. while ($attempt < $maxAttempts) {
  4374. sleep($pollInterval);
  4375. $attempt++;
  4376. // 查询任务状态
  4377. $task = DB::table('mp_complete_video_tasks')
  4378. ->where('id', $taskId)
  4379. ->first();
  4380. if (!$task) {
  4381. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4382. Utils::throwError('20003:任务不存在');
  4383. }
  4384. dLog('anime')->info('轮询任务状态', [
  4385. 'task_id' => $taskId,
  4386. 'attempt' => $attempt,
  4387. 'status' => $task->generate_status
  4388. ]);
  4389. // 检查任务是否完成
  4390. if ($task->generate_status === '执行成功') {
  4391. // 同步更新剧集表状态
  4392. $boolen3 = DB::table('mp_anime_episodes')
  4393. ->where('anime_id', $animeId)
  4394. ->where('id', $episodeId)
  4395. ->update([
  4396. 'complete_video_url' => $task->complete_video_url,
  4397. 'complete_video_task_status' => '执行成功',
  4398. 'updated_at' => date('Y-m-d H:i:s')
  4399. ]);
  4400. dLog('anime')->info('视频合成任务完成', [
  4401. 'task_id' => $taskId,
  4402. 'video_url' => $task->complete_video_url,
  4403. 'attempts' => $attempt
  4404. ]);
  4405. // 如果更新成功则远程删除之前的文件
  4406. if ($boolen3 && $completeVideoUrl) {
  4407. $encode_url = urlencode($completeVideoUrl);
  4408. $client = new Client(['timeout' => 300, 'verify' => false]);
  4409. // 根据ID通过API通知合成音频
  4410. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4411. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4412. $response = $result->getBody()->getContents();
  4413. $response_arr = json_decode($response, true);
  4414. Log::info('火山删除音频返回: '.$response);
  4415. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4416. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4417. Log::info('火山删除音频失败: '.$error_msg);
  4418. // Utils::throwError('20003:火山删除音频失败');
  4419. }
  4420. }
  4421. return [
  4422. 'task_id' => $taskId,
  4423. 'anime_id' => $animeId,
  4424. 'episode_id' => $episodeId,
  4425. 'segment_count' => count($generateJson),
  4426. 'generate_status' => '执行成功',
  4427. 'complete_video_url' => $task->complete_video_url,
  4428. ];
  4429. }
  4430. // 检查任务是否失败
  4431. if ($task->generate_status === '执行失败') {
  4432. // 同步更新剧集表状态
  4433. DB::table('mp_anime_episodes')
  4434. ->where('anime_id', $animeId)
  4435. ->where('id', $episodeId)
  4436. ->update([
  4437. 'complete_video_task_status' => '执行失败',
  4438. 'updated_at' => date('Y-m-d H:i:s')
  4439. ]);
  4440. $errorMessage = $task->error_message ?? '未知错误';
  4441. dLog('anime')->error('视频合成任务失败', [
  4442. 'task_id' => $taskId,
  4443. 'error' => $errorMessage,
  4444. 'attempts' => $attempt
  4445. ]);
  4446. return [
  4447. 'task_id' => $taskId,
  4448. 'anime_id' => $animeId,
  4449. 'episode_id' => $episodeId,
  4450. 'segment_count' => count($generateJson),
  4451. 'generate_status' => '执行失败',
  4452. 'error_message' => $errorMessage
  4453. ];
  4454. }
  4455. }
  4456. // 超时处理
  4457. dLog('anime')->warning('视频合成任务超时', [
  4458. 'task_id' => $taskId,
  4459. 'max_attempts' => $maxAttempts,
  4460. 'timeout_seconds' => $maxAttempts * $pollInterval
  4461. ]);
  4462. // 更新任务状态为超时
  4463. DB::table('mp_complete_video_tasks')
  4464. ->where('id', $taskId)
  4465. ->update([
  4466. 'generate_status' => '超时',
  4467. 'error_message' => '任务执行超时(5分钟)',
  4468. 'updated_at' => date('Y-m-d H:i:s')
  4469. ]);
  4470. return [
  4471. 'task_id' => $taskId,
  4472. 'anime_id' => $animeId,
  4473. 'episode_id' => $episodeId,
  4474. 'segment_count' => count($generateJson),
  4475. 'generate_status' => '超时',
  4476. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4477. ];
  4478. }
  4479. public function generateImg($data) {
  4480. $prompt = getProp($data, 'prompt');
  4481. $episode_id = getProp($data, 'episode_id');
  4482. $ref_img_urls = getProp($data, 'ref_img_urls');
  4483. $ratio = getProp($data, 'ratio', '9:16');
  4484. $resolution = getProp($data, 'resolution', '2k');
  4485. // 定义分辨率和宽高比对应的尺寸映射表
  4486. $sizeMap = [
  4487. '2k' => [
  4488. '1:1' => ['width' => 2048, 'height' => 2048],
  4489. '4:3' => ['width' => 2304, 'height' => 1728],
  4490. '3:4' => ['width' => 1728, 'height' => 2304],
  4491. '16:9' => ['width' => 2848, 'height' => 1600],
  4492. '9:16' => ['width' => 1600, 'height' => 2848],
  4493. '3:2' => ['width' => 2496, 'height' => 1664],
  4494. '2:3' => ['width' => 1664, 'height' => 2496],
  4495. '21:9' => ['width' => 3136, 'height' => 1344],
  4496. ],
  4497. '3k' => [
  4498. '1:1' => ['width' => 3072, 'height' => 3072],
  4499. '4:3' => ['width' => 3456, 'height' => 2592],
  4500. '3:4' => ['width' => 2592, 'height' => 3456],
  4501. '16:9' => ['width' => 4096, 'height' => 2304],
  4502. '9:16' => ['width' => 2304, 'height' => 4096],
  4503. '2:3' => ['width' => 2496, 'height' => 3744],
  4504. '3:2' => ['width' => 3744, 'height' => 2496],
  4505. '21:9' => ['width' => 4704, 'height' => 2016],
  4506. ],
  4507. '4k' => [
  4508. '1:1' => ['width' => 4096, 'height' => 4096],
  4509. '3:4' => ['width' => 3520, 'height' => 4704],
  4510. '4:3' => ['width' => 4704, 'height' => 3520],
  4511. '16:9' => ['width' => 5504, 'height' => 3040],
  4512. '9:16' => ['width' => 3040, 'height' => 5504],
  4513. '2:3' => ['width' => 3328, 'height' => 4992],
  4514. '3:2' => ['width' => 4992, 'height' => 3328],
  4515. '21:9' => ['width' => 6240, 'height' => 2656],
  4516. ],
  4517. ];
  4518. // 参数验证
  4519. $resolution = strtolower($resolution);
  4520. if (!isset($sizeMap[$resolution])) {
  4521. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  4522. }
  4523. if (!isset($sizeMap[$resolution][$ratio])) {
  4524. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  4525. }
  4526. // 根据 ratio 和 resolution 确定宽高
  4527. $width = $sizeMap[$resolution][$ratio]['width'];
  4528. $height = $sizeMap[$resolution][$ratio]['height'];
  4529. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  4530. if (is_json($ref_img_urls)) {
  4531. $ref_img_urls = json_decode($ref_img_urls, true);
  4532. }else {
  4533. $ref_img_urls = explode(',', $ref_img_urls);
  4534. }
  4535. }
  4536. // 处理图片模型
  4537. $model = getProp($data, 'model');
  4538. if (!$model) {
  4539. // 用户没有输入,从episode表获取
  4540. if ($episode_id) {
  4541. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4542. $model = getProp($episode, 'image_model');
  4543. }
  4544. if (!$model) {
  4545. // episode表也没有,使用默认值
  4546. $model = 'doubao-seedream-5-0-lite-260128';
  4547. }
  4548. }
  4549. // 验证模型是否在可用模型表中
  4550. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4551. // $model = 'doubao-seedream-5-0-lite-260128';
  4552. Utils::throwError('20003:该模型已不可用,请更换!');
  4553. }
  4554. // 保存到episode表
  4555. if ($episode_id) {
  4556. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4557. 'image_model' => $model,
  4558. 'updated_at' => date('Y-m-d H:i:s')
  4559. ]);
  4560. }
  4561. // 参数验证
  4562. if (!$prompt) Utils::throwError('20003:请提供提示词');
  4563. try {
  4564. // 创建图片生成任务
  4565. $params = [
  4566. 'prompt' => $prompt,
  4567. 'model' => $model,
  4568. 'ref_img_urls' => '',
  4569. 'width' => $width,
  4570. 'height' => $height
  4571. ];
  4572. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  4573. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4574. $task_id = $task->id;
  4575. if (!$task_id) {
  4576. Utils::throwError('20003:创建图片生成任务失败');
  4577. }
  4578. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  4579. $model = getProp($task, 'model');
  4580. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  4581. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  4582. $isSyncModel = $isVolcModel || $isGptModel;
  4583. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  4584. $start_time = time();
  4585. $timeout = 300; // 5分钟
  4586. $img_url = '';
  4587. while (time() - $start_time < $timeout) {
  4588. sleep(3);
  4589. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  4590. if ($isSyncModel) {
  4591. // 刷新任务状态
  4592. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4593. if ($task->status === 'success' && $task->result_url) {
  4594. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  4595. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  4596. break;
  4597. } elseif ($task->status === 'failed') {
  4598. $errorMsg = mapErrorMessage($task->error_message ?? '');
  4599. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4600. }
  4601. // // 如果还在处理中,提示用户稍后查看
  4602. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  4603. }else {
  4604. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4605. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  4606. if ($statusInfo['status'] === 'success') {
  4607. $task->updateStatus('success', [
  4608. 'result_url' => $statusInfo['result_url'],
  4609. 'result_json' => $statusInfo['result_json'] ?? []
  4610. ]);
  4611. $img_url = $statusInfo['result_url'][0];
  4612. break;
  4613. } elseif ($statusInfo['status'] === 'failed') {
  4614. $task->updateStatus('failed', [
  4615. 'error_message' => $statusInfo['error_message'],
  4616. 'result_json' => $statusInfo['result_json'] ?? []
  4617. ]);
  4618. dLog('anime')->error('图片生成失败,', [
  4619. 'error' => $statusInfo['error_message'] ?? '未知错误'
  4620. ]);
  4621. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  4622. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4623. }
  4624. }
  4625. }
  4626. if (empty($img_url)) {
  4627. Utils::throwError('20003:图片生成超时,请稍后重试');
  4628. }
  4629. return $img_url;
  4630. } catch (\Exception $e) {
  4631. dLog('anime')->error('更新角色或场景失败', [
  4632. 'error' => $e->getMessage()
  4633. ]);
  4634. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  4635. Utils::throwError('20003:' . $e->getMessage());
  4636. }
  4637. }
  4638. /**
  4639. * 使用文生文模型解析分镜内容
  4640. */
  4641. private function parseSegmentContentWithAI($segment_content) {
  4642. try {
  4643. // 使用DeepSeek服务的公开方法解析分镜内容
  4644. return $this->DeepSeekService->parseSegmentContent($segment_content);
  4645. } catch (\Exception $e) {
  4646. // 如果AI解析失败,记录日志并返回原内容
  4647. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  4648. return $segment_content;
  4649. }
  4650. }
  4651. /**
  4652. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  4653. *
  4654. * @param int $episode_id 分集ID
  4655. * @param int $anime_id 动漫ID
  4656. * @param array $roles 分集角色数组(引用传递)
  4657. * @param array $scenes 分集场景数组(引用传递)
  4658. * @param array $episode 分集数据
  4659. */
  4660. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  4661. // 获取全局动漫的角色和场景数据
  4662. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4663. if (!$anime) return;
  4664. $art_style_type = getProp($anime, 'art_style_type');
  4665. $character_prefix = '';
  4666. $scene_prefix = '';
  4667. if ($art_style_type) {
  4668. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  4669. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  4670. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  4671. }
  4672. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  4673. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  4674. $roles_updated = false;
  4675. $scenes_updated = false;
  4676. // 处理角色
  4677. foreach ($roles as &$role) {
  4678. $role_name = getProp($role, 'role');
  4679. $role_description = getProp($role, 'description');
  4680. $role_pic_prompt = getProp($role, 'pic_prompt');
  4681. $role_url = getProp($role, 'url');
  4682. $role_task_id = getProp($role, 'task_id');
  4683. // 如果已有URL或已有任务ID,跳过
  4684. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  4685. continue;
  4686. }
  4687. $url_inherited = false;
  4688. // 尝试从全局数据中继承
  4689. foreach ($global_roles as $global_role) {
  4690. $global_role_name = getProp($global_role, 'role');
  4691. $global_role_description = getProp($global_role, 'description');
  4692. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  4693. $global_role_url = getProp($global_role, 'url');
  4694. $global_role_task_id = getProp($global_role, 'task_id');
  4695. $global_role_task_status = getProp($global_role, 'task_status');
  4696. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  4697. if ($role_name === $global_role_name
  4698. && $role_description === $global_role_description
  4699. && $role_pic_prompt === $global_role_pic_prompt
  4700. && !empty($global_role_url)) {
  4701. // 继承 task_id、task_status 和 url
  4702. $role['task_id'] = $global_role_task_id;
  4703. $role['task_status'] = $global_role_task_status;
  4704. $role['url'] = $global_role_url;
  4705. $roles_updated = true;
  4706. $url_inherited = true;
  4707. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  4708. break;
  4709. }
  4710. }
  4711. // 如果无法继承且没有任务ID,创建新任务
  4712. if (!$url_inherited && empty($role_task_id)) {
  4713. try {
  4714. $art_style = getProp($episode, 'art_style');
  4715. // 优先使用 pic_prompt,如果没有则使用 description
  4716. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  4717. // if ($art_style) {
  4718. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4719. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4720. // }
  4721. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  4722. $params = [
  4723. 'prompt' => $description,
  4724. 'ref_img_urls' => []
  4725. ];
  4726. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4727. $task_id = $task->id;
  4728. if ($task_id) {
  4729. $role['task_id'] = $task_id;
  4730. $role['task_status'] = 'processing';
  4731. $roles_updated = true;
  4732. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  4733. }
  4734. } catch (\Exception $e) {
  4735. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  4736. }
  4737. }
  4738. }
  4739. // 处理场景
  4740. foreach ($scenes as &$scene) {
  4741. $scene_name = getProp($scene, 'scene');
  4742. $scene_description = getProp($scene, 'description');
  4743. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  4744. $scene_url = getProp($scene, 'url');
  4745. $scene_task_id = getProp($scene, 'task_id');
  4746. // 如果已有URL或已有任务ID,跳过
  4747. if (!empty($scene_url) || !empty($scene_task_id)) {
  4748. continue;
  4749. }
  4750. $url_inherited = false;
  4751. // 尝试从全局数据中继承
  4752. foreach ($global_scenes as $global_scene) {
  4753. $global_scene_name = getProp($global_scene, 'scene');
  4754. $global_scene_description = getProp($global_scene, 'description');
  4755. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  4756. $global_scene_url = getProp($global_scene, 'url');
  4757. $global_scene_task_id = getProp($global_scene, 'task_id');
  4758. $global_scene_task_status = getProp($global_scene, 'task_status');
  4759. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  4760. if ($scene_name === $global_scene_name
  4761. && $scene_description === $global_scene_description
  4762. && $scene_pic_prompt === $global_scene_pic_prompt
  4763. && !empty($global_scene_url)) {
  4764. // 继承 task_id、task_status 和 url
  4765. $scene['task_id'] = $global_scene_task_id;
  4766. $scene['task_status'] = $global_scene_task_status;
  4767. $scene['url'] = $global_scene_url;
  4768. $scenes_updated = true;
  4769. $url_inherited = true;
  4770. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  4771. break;
  4772. }
  4773. }
  4774. // 如果无法继承且没有任务ID,创建新任务
  4775. if (!$url_inherited && empty($scene_task_id)) {
  4776. try {
  4777. $art_style = getProp($episode, 'art_style');
  4778. // 优先使用 pic_prompt,如果没有则使用 description
  4779. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  4780. // if ($art_style) {
  4781. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  4782. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  4783. // }
  4784. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  4785. $params = [
  4786. 'prompt' => $description,
  4787. 'ref_img_urls' => []
  4788. ];
  4789. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4790. $task_id = $task->id;
  4791. if ($task_id) {
  4792. $scene['task_id'] = $task_id;
  4793. $scene['task_status'] = 'processing';
  4794. $scenes_updated = true;
  4795. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  4796. }
  4797. } catch (\Exception $e) {
  4798. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  4799. }
  4800. }
  4801. }
  4802. // 如果有更新,保存到数据库
  4803. if ($roles_updated || $scenes_updated) {
  4804. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  4805. if ($roles_updated) {
  4806. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  4807. }
  4808. if ($scenes_updated) {
  4809. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  4810. }
  4811. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  4812. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  4813. }
  4814. }
  4815. /**
  4816. * 根据图片URL使用AI反推图片提示词
  4817. *
  4818. * @param string $img_url 图片URL
  4819. * @return string 反推的提示词
  4820. */
  4821. private function generateImagePromptFromUrl($img_url) {
  4822. try {
  4823. // 获取默认模型
  4824. $model = 'doubao-seed-2-0-mini-260215';
  4825. // 构建messages参数
  4826. $messages = [
  4827. [
  4828. 'role' => 'user',
  4829. 'content' => [
  4830. [
  4831. 'type' => 'text',
  4832. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  4833. ],
  4834. [
  4835. 'type' => 'image_url',
  4836. 'image_url' => [
  4837. 'url' => $img_url
  4838. ]
  4839. ]
  4840. ]
  4841. ]
  4842. ];
  4843. // 构建请求参数
  4844. $params = [
  4845. 'model' => $model,
  4846. 'messages' => $messages,
  4847. 'stream' => false,
  4848. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  4849. ];
  4850. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  4851. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  4852. // 返回生成的内容
  4853. return getProp($result, 'fullContent', '图片描述生成失败');
  4854. } catch (\Exception $e) {
  4855. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  4856. 'img_url' => $img_url
  4857. ]);
  4858. logDB('anime', 'error', 'AI反推图片提示词失败', [
  4859. 'error' => $e->getMessage(),
  4860. 'img_url' => $img_url
  4861. ]);
  4862. return '图片描述生成失败: ' . $e->getMessage();
  4863. }
  4864. }
  4865. /**
  4866. * 音频试听接口
  4867. * 创建音频任务并轮询获取结果
  4868. *
  4869. * @param array $data 参数数组
  4870. * @return array 返回音频URL或错误信息
  4871. */
  4872. public function previewAudio($data) {
  4873. $dialogue = getProp($data, 'dialogue');
  4874. // 必填参数验证
  4875. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  4876. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  4877. $voice_type = getProp($data, 'voice_type');
  4878. $voice_name = getProp($data, 'voice_name');
  4879. $voice_actor = getProp($data, 'voice_actor');
  4880. $emotion_type = getProp($data, 'emotion_type');
  4881. $gender = getProp($data, 'gender', 0);
  4882. $emotion = getProp($data, 'emotion');
  4883. $speed_ratio = getProp($data, 'speed_ratio', 0);
  4884. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  4885. $emotion_scale = getProp($data, 'emotion_scale', 0);
  4886. $pitch = getProp($data, 'pitch', 0);
  4887. try {
  4888. $now = date('Y-m-d H:i:s');
  4889. // 构建生成参数
  4890. $generate_json = json_encode([
  4891. 'text' => $dialogue,
  4892. 'role' => $voice_actor,
  4893. 'voice_type' => $voice_type,
  4894. 'voice_name' => $voice_name,
  4895. 'emotion' => $emotion,
  4896. 'emotion_type' => $emotion_type,
  4897. 'gender' => $gender,
  4898. 'speed_ratio' => $speed_ratio,
  4899. 'loudness_ratio' => $loudness_ratio,
  4900. 'emotion_scale' => $emotion_scale,
  4901. 'pitch' => $pitch,
  4902. ], 256);
  4903. // 请求远程服务器执行生成
  4904. $client = new Client(['timeout' => 600, 'verify' => false]);
  4905. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  4906. $response = $result->getBody()->getContents();
  4907. $response_arr = json_decode($response, true);
  4908. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4909. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4910. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  4911. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  4912. }
  4913. $arr = $response_arr['data'];
  4914. $subtitle_info = $arr['subtitle_info'];
  4915. $audio_duration = json_decode($subtitle_info, true)['duration'];
  4916. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  4917. return [
  4918. 'audio_url' => $arr['url'],
  4919. 'subtitle_info' => $subtitle_info,
  4920. 'audio_duration' => round($audio_duration, 2)
  4921. ];
  4922. } catch (\Exception $e) {
  4923. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  4924. Utils::throwError('20003:' . $e->getMessage());
  4925. }
  4926. }
  4927. /**
  4928. * 获取角色库列表(支持文件夹递归查询)
  4929. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)
  4930. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  4931. */
  4932. public function globalProducts($data) {
  4933. $uid = Site::getUid();
  4934. $cpid = Site::getCpid();
  4935. $id = getProp($data, 'id', 0);
  4936. $parent_id = getProp($data, 'parent_id', 0);
  4937. $product_name = getProp($data, 'product_name');
  4938. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  4939. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  4940. if (!$product) {
  4941. Utils::throwError('20003:请选择产品类型');
  4942. }
  4943. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  4944. $query_uid = $is_public ? 0 : $uid;
  4945. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  4946. if ($id || $product_name) {
  4947. $query = DB::table('mp_products')
  4948. ->where('cpid', $cpid)
  4949. ->where('user_id', $query_uid)
  4950. ->where('is_deleted', 0);
  4951. // 如果指定了 id,按 id 精确查询
  4952. if ($id) {
  4953. $query->where('id', $id);
  4954. }
  4955. // 如果指定了 product_name,按名称模糊查询
  4956. if ($product_name) {
  4957. $query->where('product_name', 'like', "%{$product_name}%");
  4958. }
  4959. // 如果指定了 product,添加筛选条件
  4960. if ($product) {
  4961. $query->where('product', $product);
  4962. }
  4963. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'created_at')
  4964. ->orderByRaw('sort_order DESC, created_at DESC')
  4965. ->get()
  4966. ->map(function($value) {
  4967. $value = (array)$value;
  4968. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  4969. $value['type'] = (int)$value['type'];
  4970. $value['parent_id'] = (int)$value['parent_id'];
  4971. $value['level'] = (int)$value['level'];
  4972. $value['product'] = (int)($value['product'] ?? 1);
  4973. $value['versions'] = json_decode($value['versions'], true) ?: [];
  4974. return $value;
  4975. })
  4976. ->toArray();
  4977. return $result;
  4978. }
  4979. // 递归获取所有子目录和角色
  4980. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_uid);
  4981. }
  4982. /**
  4983. * 递归获取指定目录下的所有子目录和角色
  4984. * @param int $cpid 公司ID
  4985. * @param int $parent_id 父目录ID
  4986. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  4987. * @param int $uid 用户ID
  4988. * @return array
  4989. */
  4990. private function getChildrenRecursive($cpid, $parent_id, $product = null, $uid = null) {
  4991. // 查询当前层级的所有项(文件夹和角色)
  4992. $query = DB::table('mp_products')
  4993. ->where('cpid', $cpid)
  4994. ->where('is_deleted', 0)
  4995. ->where('parent_id', $parent_id);
  4996. // 添加用户ID验证
  4997. if ($uid !== '') {
  4998. $query->where('user_id', $uid);
  4999. }
  5000. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5001. if ($product) {
  5002. $query->where('product', $product);
  5003. }
  5004. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'created_at')
  5005. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  5006. ->get();
  5007. $result = [];
  5008. foreach ($items as $item) {
  5009. $itemArray = [
  5010. 'id' => $item->id,
  5011. 'type' => (int)$item->type,
  5012. 'parent_id' => (int)$item->parent_id,
  5013. 'level' => (int)$item->level,
  5014. 'product_name' => $item->product_name,
  5015. 'url' => $item->url,
  5016. 'pic_prompt' => $item->pic_prompt ?? '',
  5017. 'three_view_image_url' => $item->three_view_image_url,
  5018. 'product' => (int)($item->product ?? 1),
  5019. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5020. ];
  5021. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5022. // 如果是文件夹,递归获取其子项
  5023. if ($item->type == 2) {
  5024. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $uid);
  5025. if (!empty($children)) {
  5026. $itemArray['children'] = $children;
  5027. }
  5028. }
  5029. $result[] = $itemArray;
  5030. }
  5031. return $result;
  5032. }
  5033. /**
  5034. * 创建文件夹
  5035. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5036. * @return int 返回新建文件夹ID
  5037. */
  5038. public function createFolder($data) {
  5039. $uid = Site::getUid();
  5040. $cpid = Site::getCpid();
  5041. $parent_id = getProp($data, 'parent_id', 0);
  5042. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5043. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5044. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5045. $store_uid = $is_public ? 0 : $uid;
  5046. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5047. $product = getProp($data, 'product');
  5048. if (!in_array($product, [1, 2, 3])) {
  5049. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5050. }
  5051. // 验证父文件夹
  5052. $parent_level = 0;
  5053. if ($parent_id > 0) {
  5054. $parent = DB::table('mp_products')
  5055. ->where('id', $parent_id)
  5056. ->where('cpid', $cpid)
  5057. ->where('user_id', $store_uid)
  5058. ->where('type', 2)
  5059. ->where('is_deleted', 0)
  5060. ->first();
  5061. if (!$parent) {
  5062. Utils::throwError('20003:父文件夹不存在');
  5063. }
  5064. // 检查父文件夹的 product 类型是否一致
  5065. if ($parent->product != $product) {
  5066. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5067. }
  5068. $parent_level = $parent->level;
  5069. // 检查层级限制(最多3层)
  5070. if ($parent_level >= 3) {
  5071. Utils::throwError('20003:文件夹层级不能超过3层');
  5072. }
  5073. }
  5074. // 检查当前目录下是否已存在空白文件夹
  5075. $empty_folder_exists = DB::table('mp_products')
  5076. ->where('parent_id', $parent_id)
  5077. ->where('cpid', $cpid)
  5078. ->where('user_id', $store_uid)
  5079. ->where('type', 2)
  5080. ->where('product', $product)
  5081. ->where('product_name', '新建文件夹')
  5082. ->where('is_deleted', 0)
  5083. ->exists();
  5084. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5085. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5086. }
  5087. // 创建文件夹
  5088. $folder_id = DB::table('mp_products')->insertGetId([
  5089. 'user_id' => $store_uid,
  5090. 'cpid' => $cpid,
  5091. 'type' => 2,
  5092. 'parent_id' => $parent_id,
  5093. 'level' => $parent_level + 1,
  5094. 'product_name' => $folder_name,
  5095. 'product' => $product,
  5096. 'sort_order' => time(), // 使用时间戳作为排序权重
  5097. 'is_deleted' => 0,
  5098. 'created_at' => date('Y-m-d H:i:s'),
  5099. 'updated_at' => date('Y-m-d H:i:s')
  5100. ]);
  5101. return [
  5102. 'id' => $folder_id,
  5103. 'type' => 2,
  5104. 'parent_id' => $parent_id,
  5105. 'level' => $parent_level + 1,
  5106. 'product_name' => $folder_name,
  5107. 'product' => $product,
  5108. ];
  5109. }
  5110. /**
  5111. * 重命名文件夹或角色
  5112. * @param array $data 包含 id、product_name(新名称)
  5113. * @return bool
  5114. */
  5115. public function renameFolder($data) {
  5116. $uid = Site::getUid();
  5117. $cpid = Site::getCpid();
  5118. $id = getProp($data, 'id');
  5119. $new_name = getProp($data, 'product_name');
  5120. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5121. if (!$id || !$new_name) {
  5122. Utils::throwError('20003:参数不完整');
  5123. }
  5124. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5125. $query_uid = $is_public ? 0 : $uid;
  5126. // 检查是否存在
  5127. $item = DB::table('mp_products')
  5128. ->where('id', $id)
  5129. ->where('cpid', $cpid)
  5130. ->where('user_id', $query_uid)
  5131. ->where('is_deleted', 0)
  5132. ->first();
  5133. if (!$item) {
  5134. Utils::throwError('20003:项目不存在');
  5135. }
  5136. return DB::table('mp_products')
  5137. ->where('id', $id)
  5138. ->where('cpid', $cpid)
  5139. ->where('user_id', $query_uid)
  5140. ->update([
  5141. 'product_name' => $new_name,
  5142. 'updated_at' => date('Y-m-d H:i:s')
  5143. ]);
  5144. }
  5145. /**
  5146. * 移动角色或文件夹到指定文件夹
  5147. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5148. * @return bool
  5149. */
  5150. public function moveProductOrFolder($data) {
  5151. $uid = Site::getUid();
  5152. $cpid = Site::getCpid();
  5153. $id = getProp($data, 'id');
  5154. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5155. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5156. if (!$id) {
  5157. Utils::throwError('20003:请选择要移动的项目');
  5158. }
  5159. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5160. $query_uid = $is_public ? 0 : $uid;
  5161. // 检查要移动的项目
  5162. $item = DB::table('mp_products')
  5163. ->where('id', $id)
  5164. ->where('cpid', $cpid)
  5165. ->where('user_id', $query_uid)
  5166. ->where('is_deleted', 0)
  5167. ->first();
  5168. if (!$item) {
  5169. Utils::throwError('20003:项目不存在');
  5170. }
  5171. // 验证目标文件夹
  5172. $target_level = 0;
  5173. $target_product = $item->product; // 默认使用当前项目的 product
  5174. if ($target_parent_id > 0) {
  5175. $target_parent = DB::table('mp_products')
  5176. ->where('id', $target_parent_id)
  5177. ->where('cpid', $cpid)
  5178. ->where('user_id', $query_uid)
  5179. ->where('type', 2)
  5180. ->where('is_deleted', 0)
  5181. ->first();
  5182. if (!$target_parent) {
  5183. Utils::throwError('20003:目标文件夹不存在');
  5184. }
  5185. // 检查 product 类型是否一致
  5186. if ($target_parent->product != $item->product) {
  5187. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5188. }
  5189. $target_level = $target_parent->level;
  5190. $target_product = $target_parent->product;
  5191. // 如果移动的是文件夹,需要检查层级
  5192. if ($item->type == 2) {
  5193. // 计算移动后的最大层级
  5194. $max_child_level = $this->getMaxChildLevel($id);
  5195. $depth = $max_child_level - $item->level;
  5196. if ($target_level + 1 + $depth > 3) {
  5197. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5198. }
  5199. // 不能移动到自己或自己的子文件夹下
  5200. if ($this->isDescendant($target_parent_id, $id)) {
  5201. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5202. }
  5203. }
  5204. }
  5205. // 更新父文件夹和层级
  5206. $new_level = $target_level + 1;
  5207. DB::table('mp_products')
  5208. ->where('id', $id)
  5209. ->update([
  5210. 'parent_id' => $target_parent_id,
  5211. 'level' => $new_level,
  5212. 'updated_at' => date('Y-m-d H:i:s')
  5213. ]);
  5214. // 如果是文件夹,需要递归更新所有子项的层级
  5215. if ($item->type == 2) {
  5216. $this->updateChildrenLevel($id, $new_level);
  5217. }
  5218. return true;
  5219. }
  5220. /**
  5221. * 获取文件夹下最大子层级
  5222. * @param int $folder_id
  5223. * @return int
  5224. */
  5225. private function getMaxChildLevel($folder_id) {
  5226. $max_level = DB::table('mp_products')
  5227. ->where('parent_id', $folder_id)
  5228. ->where('is_deleted', 0)
  5229. ->max('level');
  5230. if (!$max_level) {
  5231. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5232. }
  5233. // 递归查找子文件夹
  5234. $children = DB::table('mp_products')
  5235. ->where('parent_id', $folder_id)
  5236. ->where('type', 2)
  5237. ->where('is_deleted', 0)
  5238. ->pluck('id');
  5239. foreach ($children as $child_id) {
  5240. $child_max = $this->getMaxChildLevel($child_id);
  5241. if ($child_max > $max_level) {
  5242. $max_level = $child_max;
  5243. }
  5244. }
  5245. return $max_level;
  5246. }
  5247. /**
  5248. * 检查 target_id 是否是 folder_id 的后代
  5249. * @param int $target_id
  5250. * @param int $folder_id
  5251. * @return bool
  5252. */
  5253. private function isDescendant($target_id, $folder_id) {
  5254. if ($target_id == $folder_id) {
  5255. return true;
  5256. }
  5257. $parent = DB::table('mp_products')
  5258. ->where('id', $target_id)
  5259. ->where('is_deleted', 0)
  5260. ->first();
  5261. if (!$parent || $parent->parent_id == 0) {
  5262. return false;
  5263. }
  5264. return $this->isDescendant($parent->parent_id, $folder_id);
  5265. }
  5266. /**
  5267. * 递归更新子项层级
  5268. * @param int $parent_id
  5269. * @param int $parent_level
  5270. */
  5271. private function updateChildrenLevel($parent_id, $parent_level) {
  5272. $children = DB::table('mp_products')
  5273. ->where('parent_id', $parent_id)
  5274. ->where('is_deleted', 0)
  5275. ->get();
  5276. foreach ($children as $child) {
  5277. $new_level = $parent_level + 1;
  5278. DB::table('mp_products')
  5279. ->where('id', $child->id)
  5280. ->update([
  5281. 'level' => $new_level,
  5282. 'updated_at' => date('Y-m-d H:i:s')
  5283. ]);
  5284. // 如果是文件夹,继续递归
  5285. if ($child->type == 2) {
  5286. $this->updateChildrenLevel($child->id, $new_level);
  5287. }
  5288. }
  5289. }
  5290. /**
  5291. * 获取文件夹路径(面包屑导航)
  5292. * @param array $data 包含 folder_id
  5293. * @return array 返回路径数组
  5294. */
  5295. public function getFolderPath($data) {
  5296. $uid = Site::getUid();
  5297. $cpid = Site::getCpid();
  5298. $folder_id = getProp($data, 'id', 0);
  5299. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5300. if ($folder_id == 0) {
  5301. return [
  5302. ['id' => 0, 'name' => '根目录']
  5303. ];
  5304. }
  5305. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5306. $query_uid = $is_public ? 0 : $uid;
  5307. $path = [];
  5308. $current_id = $folder_id;
  5309. while ($current_id > 0) {
  5310. $folder = DB::table('mp_products')
  5311. ->where('id', $current_id)
  5312. ->where('cpid', $cpid)
  5313. ->where('user_id', $query_uid)
  5314. ->where('type', 2)
  5315. ->where('is_deleted', 0)
  5316. ->first();
  5317. if (!$folder) {
  5318. break;
  5319. }
  5320. array_unshift($path, [
  5321. 'id' => $folder->id,
  5322. 'name' => $folder->product_name
  5323. ]);
  5324. $current_id = $folder->parent_id;
  5325. }
  5326. // 添加根目录
  5327. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5328. return $path;
  5329. }
  5330. public function createProduct($data) {
  5331. $uid = Site::getUid();
  5332. $cpid = Site::getCpid();
  5333. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5334. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5335. $store_uid = $is_public ? 0 : $uid;
  5336. $product_name = trim(getProp($data, 'product_name'));
  5337. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5338. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5339. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5340. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5341. $url = trim(getProp($data, 'url'));
  5342. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5343. $versions = getProp($data, 'versions');
  5344. // 检查是否是正确的图片格式
  5345. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5346. $urlPath = parse_url($url, PHP_URL_PATH);
  5347. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5348. if (!in_array($extension, $allowedExtensions)) {
  5349. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5350. }
  5351. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5352. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5353. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5354. $product = getProp($data, 'product');
  5355. if (!in_array($product, [1, 2, 3])) {
  5356. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5357. }
  5358. // 获取父文件夹ID和层级
  5359. $parent_id = getProp($data, 'parent_id', 0);
  5360. $parent_level = 0;
  5361. if ($parent_id > 0) {
  5362. $parent = DB::table('mp_products')
  5363. ->where('id', $parent_id)
  5364. ->where('cpid', $cpid)
  5365. ->where('user_id', $store_uid)
  5366. ->where('type', 2)
  5367. ->where('is_deleted', 0)
  5368. ->first();
  5369. if (!$parent) {
  5370. Utils::throwError('20003:父文件夹不存在');
  5371. }
  5372. $parent_level = $parent->level;
  5373. }
  5374. $id = DB::table('mp_products')->insertGetId([
  5375. 'user_id' => $store_uid,
  5376. 'cpid' => $cpid,
  5377. 'type' => 1, // 1=角色图片
  5378. 'parent_id' => $parent_id,
  5379. 'level' => $parent_level + 1,
  5380. 'product_name' => $product_name,
  5381. 'url' => $url,
  5382. 'pic_prompt' => $pic_prompt,
  5383. 'product' => $product,
  5384. 'versions' => json_encode($versions, 256),
  5385. 'sort_order' => time(), // 使用时间戳作为排序权重
  5386. 'created_at' => date('Y-m-d H:i:s'),
  5387. 'updated_at' => date('Y-m-d H:i:s')
  5388. ]);
  5389. if (!$id) Utils::throwError('20003:创建失败');
  5390. return [
  5391. 'id' => $id,
  5392. 'type' => 1,
  5393. 'parent_id' => $parent_id,
  5394. 'level' => $parent_level + 1,
  5395. 'product_name' => $product_name,
  5396. 'url' => $url,
  5397. 'pic_prompt' => $pic_prompt,
  5398. 'product' => $product,
  5399. 'versions' => $versions
  5400. ];
  5401. }
  5402. public function editProduct($data) {
  5403. $uid = Site::getUid();
  5404. $cpid = Site::getCpid();
  5405. $id = getProp($data, 'id');
  5406. if (!$id) Utils::throwError('20003:ID不能为空');
  5407. $versions = getProp($data, 'versions');
  5408. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5409. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5410. $query_uid = $is_public ? 0 : $uid;
  5411. // 检查是否存在且属于当前用户或公共库
  5412. $role = DB::table('mp_products')
  5413. ->where('id', $id)
  5414. ->where('cpid', $cpid)
  5415. ->where('user_id', $query_uid)
  5416. ->where('type', 1)->first();
  5417. if (!$role) Utils::throwError('20003:记录不存在');
  5418. $updateData = [];
  5419. // $needVersionRecord = false; // 是否需要记录版本
  5420. // 名称
  5421. $product_name = trim(getProp($data, 'product_name'));
  5422. if ($product_name) {
  5423. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5424. $updateData['product_name'] = $product_name;
  5425. }
  5426. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5427. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5428. // 图片地址
  5429. $url = trim(getProp($data, 'url'));
  5430. if ($url) {
  5431. // 检查是否是正确的图片格式
  5432. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5433. $urlPath = parse_url($url, PHP_URL_PATH);
  5434. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5435. if (!in_array($extension, $allowedExtensions)) {
  5436. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5437. }
  5438. // // 如果 url 有变更,记录版本
  5439. // if ($url !== $role->url) {
  5440. // $needVersionRecord = true;
  5441. // }
  5442. $updateData['url'] = $url;
  5443. }
  5444. // 提示词
  5445. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5446. if ($pic_prompt) {
  5447. // // 如果 pic_prompt 有变更,记录版本
  5448. // if ($pic_prompt !== $role->pic_prompt) {
  5449. // $needVersionRecord = true;
  5450. // }
  5451. $updateData['pic_prompt'] = $pic_prompt;
  5452. }
  5453. if (empty($updateData)) {
  5454. Utils::throwError('20003:没有需要更新的数据');
  5455. }
  5456. // // 如果需要记录版本,将数据添加到 versions 数组
  5457. // if ($needVersionRecord) {
  5458. // // 获取现有的 versions 数据
  5459. // $versions = json_decode($role->versions, true) ?: [];
  5460. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  5461. // // 如果是第一次记录版本,先添加旧版本(变更前)
  5462. // if ($isFirstVersion) {
  5463. // $oldVersion = [
  5464. // 'url' => $role->url,
  5465. // 'description' => $role->pic_prompt,
  5466. // ];
  5467. // // 旧版本添加到数组末尾
  5468. // $versions[] = $oldVersion;
  5469. // }
  5470. // // 构建新版本(变更后)
  5471. // $newVersion = [
  5472. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  5473. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  5474. // ];
  5475. // // 检查新版本是否已存在于历史版本中
  5476. // $existingIndex = -1;
  5477. // foreach ($versions as $index => $version) {
  5478. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  5479. // $existingIndex = $index;
  5480. // break;
  5481. // }
  5482. // }
  5483. // if ($existingIndex !== -1) {
  5484. // // 如果已存在,移除旧的位置
  5485. // array_splice($versions, $existingIndex, 1);
  5486. // }
  5487. // // 新版本添加到数组开头(最新的在前)
  5488. // array_unshift($versions, $newVersion);
  5489. // // // 限制版本数量(可选,例如只保留最近10个版本)
  5490. // // if (count($versions) > 10) {
  5491. // // $versions = array_slice($versions, 0, 10);
  5492. // // }
  5493. // $updateData['versions'] = json_encode($versions, 256);
  5494. // }
  5495. if ($versions) {
  5496. $updateData['versions'] = json_encode($versions, 256);
  5497. }
  5498. $updateData['updated_at'] = date('Y-m-d H:i:s');
  5499. return DB::table('mp_products')
  5500. ->where('cpid', $cpid)
  5501. ->where('id', $id)->update($updateData);
  5502. }
  5503. /**
  5504. * 获取角色版本历史
  5505. * @param array $data 包含 id(角色ID)
  5506. * @return array 返回版本历史列表
  5507. */
  5508. public function getProductVersions($data) {
  5509. $cpid = Site::getCpid();
  5510. $id = getProp($data, 'id');
  5511. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5512. $role = DB::table('mp_products')
  5513. ->where('id', $id)
  5514. ->where('cpid', $cpid)
  5515. ->where('type', 1)
  5516. ->first();
  5517. if (!$role) Utils::throwError('20003:角色不存在');
  5518. // 获取版本历史
  5519. $versions = json_decode($role->versions, true) ?: [];
  5520. // 添加当前版本作为最新版本
  5521. $currentVersion = [
  5522. 'version' => 0, // 0 表示当前版本
  5523. 'url' => $role->url,
  5524. 'pic_prompt' => $role->pic_prompt,
  5525. 'updated_at' => $role->updated_at,
  5526. 'is_current' => true
  5527. ];
  5528. array_unshift($versions, $currentVersion);
  5529. return $versions;
  5530. }
  5531. /**
  5532. * 恢复到指定版本
  5533. * @param array $data 包含 id(角色ID)、version(版本号)
  5534. * @return bool
  5535. */
  5536. public function restoreProductVersion($data) {
  5537. $uid = Site::getUid();
  5538. $cpid = Site::getCpid();
  5539. $id = getProp($data, 'id');
  5540. $version = getProp($data, 'version');
  5541. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5542. if (!$version) Utils::throwError('20003:版本号不能为空');
  5543. $role = DB::table('mp_products')
  5544. ->where('id', $id)
  5545. ->where('cpid', $cpid)
  5546. ->where('type', 1)
  5547. ->first();
  5548. if (!$role) Utils::throwError('20003:角色不存在');
  5549. // 获取版本历史
  5550. $versions = json_decode($role->versions, true) ?: [];
  5551. // 查找指定版本
  5552. $targetVersion = null;
  5553. foreach ($versions as $v) {
  5554. if ($v['version'] == $version) {
  5555. $targetVersion = $v;
  5556. break;
  5557. }
  5558. }
  5559. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  5560. // 先将当前版本保存到历史
  5561. $newVersion = [
  5562. 'version' => count($versions) + 1,
  5563. 'url' => $role->url,
  5564. 'pic_prompt' => $role->pic_prompt,
  5565. 'updated_at' => date('Y-m-d H:i:s'),
  5566. 'updated_by' => $uid
  5567. ];
  5568. array_unshift($versions, $newVersion);
  5569. // 限制版本数量
  5570. if (count($versions) > 10) {
  5571. $versions = array_slice($versions, 0, 10);
  5572. }
  5573. // 恢复到指定版本
  5574. return DB::table('mp_products')
  5575. ->where('id', $id)
  5576. ->where('cpid', $cpid)
  5577. ->update([
  5578. 'url' => $targetVersion['url'],
  5579. 'pic_prompt' => $targetVersion['pic_prompt'],
  5580. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  5581. 'updated_at' => date('Y-m-d H:i:s')
  5582. ]);
  5583. }
  5584. public function deleteProduct($data) {
  5585. $uid = Site::getUid();
  5586. $cpid = Site::getCpid();
  5587. $id = getProp($data, 'id');
  5588. if (!$id) Utils::throwError('20003:ID不能为空');
  5589. $ids = explode(',', $id);
  5590. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5591. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5592. $query_uid = $is_public ? 0 : $uid;
  5593. // 检查是否存在且属于当前用户或公共库
  5594. $role = DB::table('mp_products')
  5595. ->whereIn('id', $ids)
  5596. ->where('cpid', $cpid)
  5597. ->where('user_id', $query_uid)
  5598. ->get();
  5599. if (!$role) Utils::throwError('20003:记录不存在');
  5600. return DB::table('mp_products')
  5601. ->where('cpid', $cpid)
  5602. ->where('user_id', $query_uid)
  5603. ->whereIn('id', $ids)
  5604. ->update([
  5605. 'is_deleted' => 1,
  5606. 'updated_at' => date('Y-m-d H:i:s')
  5607. ]);
  5608. }
  5609. public function generateThreeView($data) {
  5610. $uid = Site::getUid();
  5611. $cpid = Site::getCpid();
  5612. $id = getProp($data, 'id');
  5613. if (!$id) Utils::throwError('20003:ID不能为空');
  5614. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5615. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5616. $query_uid = $is_public ? 0 : $uid;
  5617. // 检查是否存在且属于当前用户或公共库
  5618. $product = DB::table('mp_products')
  5619. ->where('id', $id)
  5620. ->where('cpid', $cpid)
  5621. ->where('user_id', $query_uid)
  5622. ->where('type', 1)->first();
  5623. if (!$product) Utils::throwError('20003:资产不存在');
  5624. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  5625. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  5626. if (!$ref_img_url) {
  5627. // 如果没有传入参考图,使用角色表中的图片
  5628. $ref_img_url = $product->url ?? '';
  5629. if (!$ref_img_url) {
  5630. Utils::throwError('20003:参考图不能为空');
  5631. }
  5632. }
  5633. $pic_prompt = getProp($product, 'pic_prompt');
  5634. if ($pic_prompt) {
  5635. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  5636. }
  5637. // 检查参考图是否是正确的图片格式
  5638. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5639. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  5640. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5641. if (!in_array($extension, $allowedExtensions)) {
  5642. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5643. }
  5644. // 处理图片模型
  5645. $model = getProp($data, 'model');
  5646. if (!$model) {
  5647. // 使用默认模型
  5648. $model = 'doubao-seedream-5-0-lite-260128';
  5649. }
  5650. // 验证模型是否在可用模型表中
  5651. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5652. Utils::throwError('20003:该模型已不可用,请更换!');
  5653. }
  5654. $ratio = getProp($data, 'ratio', '16:9');
  5655. $resolution = getProp($data, 'resolution', '2k');
  5656. // 定义分辨率和宽高比对应的尺寸映射表
  5657. $sizeMap = [
  5658. '2k' => [
  5659. '1:1' => ['width' => 2048, 'height' => 2048],
  5660. '4:3' => ['width' => 2304, 'height' => 1728],
  5661. '3:4' => ['width' => 1728, 'height' => 2304],
  5662. '16:9' => ['width' => 2848, 'height' => 1600],
  5663. '9:16' => ['width' => 1600, 'height' => 2848],
  5664. '3:2' => ['width' => 2496, 'height' => 1664],
  5665. '2:3' => ['width' => 1664, 'height' => 2496],
  5666. '21:9' => ['width' => 3136, 'height' => 1344],
  5667. ],
  5668. '3k' => [
  5669. '1:1' => ['width' => 3072, 'height' => 3072],
  5670. '4:3' => ['width' => 3456, 'height' => 2592],
  5671. '3:4' => ['width' => 2592, 'height' => 3456],
  5672. '16:9' => ['width' => 4096, 'height' => 2304],
  5673. '9:16' => ['width' => 2304, 'height' => 4096],
  5674. '2:3' => ['width' => 2496, 'height' => 3744],
  5675. '3:2' => ['width' => 3744, 'height' => 2496],
  5676. '21:9' => ['width' => 4704, 'height' => 2016],
  5677. ],
  5678. '4k' => [
  5679. '1:1' => ['width' => 4096, 'height' => 4096],
  5680. '3:4' => ['width' => 3520, 'height' => 4704],
  5681. '4:3' => ['width' => 4704, 'height' => 3520],
  5682. '16:9' => ['width' => 5504, 'height' => 3040],
  5683. '9:16' => ['width' => 3040, 'height' => 5504],
  5684. '2:3' => ['width' => 3328, 'height' => 4992],
  5685. '3:2' => ['width' => 4992, 'height' => 3328],
  5686. '21:9' => ['width' => 6240, 'height' => 2656],
  5687. ],
  5688. ];
  5689. // 参数验证
  5690. $resolution = strtolower($resolution);
  5691. if (!isset($sizeMap[$resolution])) {
  5692. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5693. }
  5694. if (!isset($sizeMap[$resolution][$ratio])) {
  5695. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5696. }
  5697. // 根据 ratio 和 resolution 确定宽高
  5698. $width = $sizeMap[$resolution][$ratio]['width'];
  5699. $height = $sizeMap[$resolution][$ratio]['height'];
  5700. try {
  5701. // 创建图片生成任务
  5702. $params = [
  5703. 'prompt' => $prompt,
  5704. 'model' => $model,
  5705. 'ref_img_urls' => [$ref_img_url],
  5706. 'width' => $width,
  5707. 'height' => $height
  5708. ];
  5709. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5710. $task_id = $task->id;
  5711. if (!$task_id) {
  5712. Utils::throwError('20003:创建图片生成任务失败');
  5713. }
  5714. // 轮询获取结果
  5715. // 只查询数据库,不调用API,不更新任务表
  5716. $start_time = time();
  5717. $timeout = 1800;
  5718. $img_url = '';
  5719. while (time() - $start_time < $timeout) {
  5720. sleep(5);
  5721. // 只查询数据库中的任务状态,不调用API,不更新任务表
  5722. $task = DB::table('mp_generate_pic_tasks')
  5723. ->where('id', $task_id)
  5724. ->first();
  5725. if (!$task) {
  5726. Utils::throwError('20003:任务不存在');
  5727. }
  5728. if ($task->status === 'success' && $task->result_url) {
  5729. $result_urls = is_string($task->result_url)
  5730. ? json_decode($task->result_url, true)
  5731. : $task->result_url;
  5732. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  5733. break;
  5734. } elseif ($task->status === 'failed') {
  5735. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  5736. }
  5737. // 其他状态继续轮询
  5738. }
  5739. if (empty($img_url)) {
  5740. Utils::throwError('20003:三视图生成超时,请稍后重试');
  5741. }
  5742. // 更新 mp_products 表(不是任务表)
  5743. DB::table('mp_products')
  5744. ->where('id', $id)
  5745. ->where('cpid', $cpid)
  5746. ->update([
  5747. 'three_view_image_url' => $img_url,
  5748. 'updated_at' => date('Y-m-d H:i:s')
  5749. ]);
  5750. return ['three_view_image_url' => $img_url];
  5751. } catch (\Exception $e) {
  5752. dLog('anime')->error('生成三视图失败', [
  5753. 'error' => $e->getMessage()
  5754. ]);
  5755. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  5756. Utils::throwError('20003:' . $e->getMessage());
  5757. }
  5758. }
  5759. /**
  5760. * 保存剧本资产关联关系
  5761. * @param array $data 请求参数
  5762. * @return bool
  5763. */
  5764. public function saveScriptProducts($data) {
  5765. $uid = Site::getUid();
  5766. $cpid = Site::getCpid();
  5767. $script_id = getProp($data, 'script_id');
  5768. $products = getProp($data, 'products', []);
  5769. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  5770. if (!$script_id) {
  5771. Utils::throwError('20003:请提供剧本ID');
  5772. }
  5773. // 验证剧本是否存在
  5774. $script = DB::table('mp_scripts')
  5775. ->where('id', $script_id)
  5776. ->where('is_deleted', 0)
  5777. ->first();
  5778. if (!$script) {
  5779. Utils::throwError('20003:剧本不存在');
  5780. }
  5781. // 处理图片模型
  5782. $model = getProp($data, 'model');
  5783. if (!$model) {
  5784. // 使用默认模型
  5785. $model = 'doubao-seedream-5-0-lite-260128';
  5786. }
  5787. // 验证模型是否在可用模型表中
  5788. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5789. Utils::throwError('20003:该模型已不可用,请更换!');
  5790. }
  5791. $ratio = getProp($data, 'ratio', '9:16');
  5792. $resolution = getProp($data, 'resolution', '2k');
  5793. // 定义分辨率和宽高比对应的尺寸映射表
  5794. $sizeMap = [
  5795. '2k' => [
  5796. '1:1' => ['width' => 2048, 'height' => 2048],
  5797. '4:3' => ['width' => 2304, 'height' => 1728],
  5798. '3:4' => ['width' => 1728, 'height' => 2304],
  5799. '16:9' => ['width' => 2848, 'height' => 1600],
  5800. '9:16' => ['width' => 1600, 'height' => 2848],
  5801. '3:2' => ['width' => 2496, 'height' => 1664],
  5802. '2:3' => ['width' => 1664, 'height' => 2496],
  5803. '21:9' => ['width' => 3136, 'height' => 1344],
  5804. ],
  5805. '3k' => [
  5806. '1:1' => ['width' => 3072, 'height' => 3072],
  5807. '4:3' => ['width' => 3456, 'height' => 2592],
  5808. '3:4' => ['width' => 2592, 'height' => 3456],
  5809. '16:9' => ['width' => 4096, 'height' => 2304],
  5810. '9:16' => ['width' => 2304, 'height' => 4096],
  5811. '2:3' => ['width' => 2496, 'height' => 3744],
  5812. '3:2' => ['width' => 3744, 'height' => 2496],
  5813. '21:9' => ['width' => 4704, 'height' => 2016],
  5814. ],
  5815. '4k' => [
  5816. '1:1' => ['width' => 4096, 'height' => 4096],
  5817. '3:4' => ['width' => 3520, 'height' => 4704],
  5818. '4:3' => ['width' => 4704, 'height' => 3520],
  5819. '16:9' => ['width' => 5504, 'height' => 3040],
  5820. '9:16' => ['width' => 3040, 'height' => 5504],
  5821. '2:3' => ['width' => 3328, 'height' => 4992],
  5822. '3:2' => ['width' => 4992, 'height' => 3328],
  5823. '21:9' => ['width' => 6240, 'height' => 2656],
  5824. ],
  5825. ];
  5826. // 参数验证
  5827. $resolution = strtolower($resolution);
  5828. if (!isset($sizeMap[$resolution])) {
  5829. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5830. }
  5831. if (!isset($sizeMap[$resolution][$ratio])) {
  5832. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5833. }
  5834. // 根据 ratio 和 resolution 确定宽高
  5835. $width = $sizeMap[$resolution][$ratio]['width'];
  5836. $height = $sizeMap[$resolution][$ratio]['height'];
  5837. $script_name = $script->script_name ?? 'script_' . $script_id;
  5838. // 检查是否已经有该剧本的资产数据
  5839. $existingMappings = DB::table('mp_script_product_mappings')
  5840. ->where('script_id', $script_id)
  5841. ->get();
  5842. if ($existingMappings->isNotEmpty()) {
  5843. // 已存在资产映射,检查是否所有资产都有图片生成任务
  5844. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  5845. // 查询这些资产的图片生成任务状态
  5846. $productsWithTasks = DB::table('mp_products')
  5847. ->whereIn('id', $productIds)
  5848. ->where('is_deleted', 0)
  5849. ->get();
  5850. $productTaskMap = [];
  5851. $typeFolderIds = [];
  5852. $hasAllTasks = true;
  5853. foreach ($productsWithTasks as $product) {
  5854. // 收集类型文件夹ID
  5855. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  5856. $parentFolder = DB::table('mp_products')
  5857. ->where('id', $product->parent_id)
  5858. ->where('type', 2)
  5859. ->first();
  5860. if ($parentFolder) {
  5861. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  5862. }
  5863. }
  5864. // 检查是否有图片生成任务
  5865. if (!empty($product->pic_task_id)) {
  5866. $productTaskMap[$product->id] = $product->pic_task_id;
  5867. } else if($product->url && $product->pic_task_status == '生成成功') {
  5868. continue;
  5869. }
  5870. else {
  5871. // 有资产没有图片任务
  5872. $hasAllTasks = false;
  5873. }
  5874. }
  5875. // 如果所有资产都有任务ID,直接轮询返回结果
  5876. if ($hasAllTasks && !empty($productTaskMap)) {
  5877. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  5878. 'script_id' => $script_id,
  5879. 'script_name' => $script_name,
  5880. 'product_count' => count($productTaskMap)
  5881. ]);
  5882. // 直接返回 SSE 流轮询结果
  5883. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  5884. }
  5885. // 如果部分资产没有任务ID,只为这些资产创建任务
  5886. if (!$hasAllTasks && $auto_generate_images) {
  5887. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  5888. 'script_id' => $script_id,
  5889. 'script_name' => $script_name
  5890. ]);
  5891. // 开启事务
  5892. DB::beginTransaction();
  5893. try {
  5894. foreach ($productsWithTasks as $product) {
  5895. // 跳过已有任务的资产
  5896. if (!empty($product->pic_task_id)) {
  5897. continue;
  5898. }
  5899. // 跳过没有提示词的资产
  5900. if (empty($product->pic_prompt)) {
  5901. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  5902. 'product_id' => $product->id,
  5903. 'product_name' => $product->product_name
  5904. ]);
  5905. continue;
  5906. }
  5907. try {
  5908. // 创建图片生成任务
  5909. $params = [
  5910. 'prompt' => $product->pic_prompt,
  5911. 'model' => $model,
  5912. 'ref_img_urls' => [],
  5913. 'width' => $width,
  5914. 'height' => $height
  5915. ];
  5916. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5917. $task_id = $task->id;
  5918. if ($task_id) {
  5919. $productTaskMap[$product->id] = $task_id;
  5920. // 在事务中更新资产表的任务ID和状态
  5921. DB::table('mp_products')
  5922. ->where('id', $product->id)
  5923. ->update([
  5924. 'pic_task_id' => $task_id,
  5925. 'pic_task_status' => '生成中',
  5926. 'updated_at' => now()
  5927. ]);
  5928. dLog('anime')->info('为已存在资产创建图片生成任务', [
  5929. 'product_id' => $product->id,
  5930. 'task_id' => $task_id
  5931. ]);
  5932. }
  5933. } catch (\Exception $e) {
  5934. dLog('anime')->error('创建资产图片生成任务失败', [
  5935. 'product_id' => $product->id,
  5936. 'error' => $e->getMessage()
  5937. ]);
  5938. // 标记为失败(仍在事务中)
  5939. DB::table('mp_products')
  5940. ->where('id', $product->id)
  5941. ->update([
  5942. 'pic_task_status' => '生成失败',
  5943. 'updated_at' => now()
  5944. ]);
  5945. }
  5946. }
  5947. // 提交事务
  5948. DB::commit();
  5949. // 如果有新创建的任务,返回 SSE 流
  5950. if (!empty($productTaskMap)) {
  5951. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  5952. }
  5953. } catch (\Exception $e) {
  5954. // 回滚事务
  5955. DB::rollback();
  5956. dLog('anime')->error('为已存在资产创建图片任务失败', [
  5957. 'script_id' => $script_id,
  5958. 'error' => $e->getMessage()
  5959. ]);
  5960. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  5961. }
  5962. }
  5963. // 如果不需要生成图片,返回已存在的信息
  5964. return [
  5965. 'success' => true,
  5966. 'message' => '剧本资产已存在',
  5967. 'script_id' => $script_id,
  5968. 'script_name' => $script_name,
  5969. 'type_folder_ids' => $typeFolderIds,
  5970. 'existing_products' => count($productIds),
  5971. 'tasks_count' => count($productTaskMap)
  5972. ];
  5973. }
  5974. // 解析 products(可能是 JSON 字符串或数组)
  5975. if (is_string($products)) {
  5976. $products = json_decode($products, true);
  5977. if (json_last_error() !== JSON_ERROR_NONE) {
  5978. Utils::throwError('20003:产品数据格式错误');
  5979. }
  5980. }
  5981. if (!is_array($products) || empty($products)) {
  5982. Utils::throwError('20003:产品数据不能为空');
  5983. }
  5984. // 以下是原有的创建逻辑...
  5985. // 开启事务
  5986. DB::beginTransaction();
  5987. try {
  5988. $now = now();
  5989. $mappingRecords = [];
  5990. $createdProductIds = []; // 记录所有创建的资产ID
  5991. // 获取剧本名称
  5992. $script_name = $script->script_name ?? 'script_' . $script_id;
  5993. // 存储每个类型的根文件夹ID
  5994. $typeFolderIds = [];
  5995. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  5996. foreach ($products as $productGroup) {
  5997. $type = getProp($productGroup, 'type');
  5998. $title = getProp($productGroup, 'title', '');
  5999. $content = getProp($productGroup, 'content', []);
  6000. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  6001. continue;
  6002. }
  6003. // 为当前类型创建根文件夹(如果还未创建)
  6004. if (!isset($typeFolderIds[$type])) {
  6005. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  6006. 'user_id' => $uid,
  6007. 'cpid' => $cpid,
  6008. 'type' => 2, // 1.资产 2文件夹
  6009. 'product' => $type, // 1.主体 2.场景 3.道具
  6010. 'parent_id' => 0, // 根文件夹,parent_id=0
  6011. 'level' => 1, // 第一层级
  6012. 'product_name' => $script_name,
  6013. 'sort_order' => time() + $type,
  6014. 'is_deleted' => 0,
  6015. 'created_at' => $now,
  6016. 'updated_at' => $now
  6017. ]);
  6018. }
  6019. $folder_id = $typeFolderIds[$type];
  6020. // 获取表头(第一行)并查找关键列的位置
  6021. $headers = $content[0];
  6022. $nameColumnIndex = -1; // 资产名称列索引
  6023. $sequenceColumnIndex = -1; // 使用范围列索引
  6024. $promptColumnIndex = -1; // 参考提示词列索引
  6025. foreach ($headers as $index => $header) {
  6026. // 查找"资产名称"列
  6027. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  6028. $nameColumnIndex = $index;
  6029. }
  6030. // 查找"使用范围"列
  6031. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  6032. $sequenceColumnIndex = $index;
  6033. }
  6034. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  6035. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  6036. $promptColumnIndex = $index;
  6037. }
  6038. }
  6039. // 验证必要的列是否都找到了
  6040. if ($nameColumnIndex === -1) {
  6041. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  6042. continue;
  6043. }
  6044. if ($sequenceColumnIndex === -1) {
  6045. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  6046. continue;
  6047. }
  6048. // 跳过表头,解析每一行数据
  6049. for ($i = 1; $i < count($content); $i++) {
  6050. $row = $content[$i];
  6051. // 确保行数据有效
  6052. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  6053. continue;
  6054. }
  6055. // 根据动态查找的列索引提取数据
  6056. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  6057. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6058. $pic_prompt = '';
  6059. // 提取参考提示词(如果找到了该列)
  6060. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6061. $pic_prompt = trim($row[$promptColumnIndex]);
  6062. }
  6063. // 解析使用范围(逗号分隔的序号)
  6064. $sequences = [];
  6065. if (!empty($sequence_str)) {
  6066. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  6067. foreach ($sequenceParts as $part) {
  6068. if (is_numeric($part)) {
  6069. $sequences[] = (int)$part;
  6070. }
  6071. }
  6072. }
  6073. if (empty($product_name)) {
  6074. continue;
  6075. }
  6076. // 处理product_name两边的符号
  6077. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6078. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  6079. $product_id = DB::table('mp_products')->insertGetId([
  6080. 'product_name' => $product_name,
  6081. 'type' => 1, // 1=资产 2.文件夹
  6082. 'product' => $type, // 1=角色, 2=场景, 3=道具
  6083. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  6084. 'level' => 2, // 第二层级
  6085. 'pic_prompt' => $pic_prompt,
  6086. 'user_id' => $uid,
  6087. 'cpid' => $cpid,
  6088. 'sort_order' => time(),
  6089. 'is_deleted' => 0,
  6090. 'created_at' => $now,
  6091. 'updated_at' => $now,
  6092. ]);
  6093. // 记录创建的资产ID
  6094. $createdProductIds[] = $product_id;
  6095. // 为每个序号创建映射记录
  6096. if (!empty($sequences)) {
  6097. foreach ($sequences as $sequence) {
  6098. $mappingRecords[] = [
  6099. 'script_id' => $script_id,
  6100. 'product_id' => $product_id,
  6101. 'episode_number' => $sequence,
  6102. 'created_at' => $now,
  6103. 'updated_at' => $now,
  6104. ];
  6105. }
  6106. } else {
  6107. // 如果没有指定序号,创建一个默认映射(序号为0)
  6108. $mappingRecords[] = [
  6109. 'script_id' => $script_id,
  6110. 'product_id' => $product_id,
  6111. 'episode_number' => 0,
  6112. 'created_at' => $now,
  6113. 'updated_at' => $now,
  6114. ];
  6115. }
  6116. }
  6117. }
  6118. if (empty($mappingRecords)) {
  6119. Utils::throwError('20003:没有有效的产品数据');
  6120. }
  6121. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  6122. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  6123. // 如果需要自动生成图片,在事务中创建图片生成任务
  6124. $productTaskMap = [];
  6125. if ($auto_generate_images && !empty($createdProductIds)) {
  6126. // 查询所有创建的资产
  6127. $productsToGenerate = DB::table('mp_products')
  6128. ->whereIn('id', $createdProductIds)
  6129. ->where('is_deleted', 0)
  6130. ->get();
  6131. foreach ($productsToGenerate as $product) {
  6132. if (empty($product->pic_prompt)) {
  6133. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6134. 'product_id' => $product->id,
  6135. 'product_name' => $product->product_name
  6136. ]);
  6137. continue;
  6138. }
  6139. try {
  6140. // 创建图片生成任务
  6141. $params = [
  6142. 'prompt' => $product->pic_prompt,
  6143. 'model' => $model,
  6144. 'ref_img_urls' => [],
  6145. 'width' => $width,
  6146. 'height' => $height
  6147. ];
  6148. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6149. $task_id = $task->id;
  6150. if ($task_id) {
  6151. $productTaskMap[$product->id] = $task_id;
  6152. // 在事务中更新资产表的任务ID和状态
  6153. DB::table('mp_products')
  6154. ->where('id', $product->id)
  6155. ->update([
  6156. 'pic_task_id' => $task_id,
  6157. 'pic_task_status' => '生成中',
  6158. 'updated_at' => now()
  6159. ]);
  6160. dLog('anime')->info('创建资产图片生成任务', [
  6161. 'product_id' => $product->id,
  6162. 'task_id' => $task_id
  6163. ]);
  6164. }
  6165. } catch (\Exception $e) {
  6166. dLog('anime')->error('创建资产图片生成任务失败', [
  6167. 'product_id' => $product->id,
  6168. 'error' => $e->getMessage()
  6169. ]);
  6170. // 标记为失败(仍在事务中)
  6171. DB::table('mp_products')
  6172. ->where('id', $product->id)
  6173. ->update([
  6174. 'pic_task_status' => '生成失败',
  6175. 'updated_at' => now()
  6176. ]);
  6177. }
  6178. }
  6179. }
  6180. // 提交事务
  6181. DB::commit();
  6182. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6183. if ($auto_generate_images && !empty($productTaskMap)) {
  6184. // 返回 SSE 流(事务外轮询)
  6185. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6186. }
  6187. // 如果不需要生成图片,返回普通结果
  6188. return [
  6189. 'success' => true,
  6190. 'type_folder_ids' => $typeFolderIds,
  6191. 'inserted_count' => $insertedCount,
  6192. 'total_records' => count($mappingRecords),
  6193. 'created_products' => count($createdProductIds),
  6194. 'image_tasks_created' => count($productTaskMap)
  6195. ];
  6196. } catch (\Exception $e) {
  6197. // 回滚事务
  6198. DB::rollback();
  6199. // 记录错误日志
  6200. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6201. 'script_id' => $script_id,
  6202. 'error' => $e->getMessage(),
  6203. 'trace' => $e->getTraceAsString()
  6204. ]);
  6205. // 统一使用 Utils::throwError 抛出错误
  6206. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6207. }
  6208. }
  6209. /**
  6210. * 批量为剧本资产生成图片
  6211. *
  6212. * @param array $data 请求参数
  6213. * @return \Generator 返回 SSE 流
  6214. */
  6215. public function batchGenerateProductImages($data) {
  6216. $script_id = getProp($data, 'script_id');
  6217. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  6218. if (!$script_id) {
  6219. Utils::throwError('20003:请提供剧本ID');
  6220. }
  6221. // 验证剧本是否存在
  6222. $script = DB::table('mp_scripts')
  6223. ->where('id', $script_id)
  6224. ->where('is_deleted', 0)
  6225. ->first();
  6226. if (!$script) {
  6227. Utils::throwError('20003:剧本不存在');
  6228. }
  6229. $script_name = $script->script_name ?? 'script_' . $script_id;
  6230. // 获取需要生成图片的所有资产
  6231. $products = DB::table('mp_products')
  6232. ->whereIn('parent_id', array_values($type_folder_ids))
  6233. ->where('is_deleted', 0)
  6234. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  6235. ->get();
  6236. if ($products->isEmpty()) {
  6237. Utils::throwError('20003:没有找到需要生成图片的资产');
  6238. }
  6239. // 默认参数
  6240. $model = 'doubao-seedream-5-0-lite-260128';
  6241. $width = 1600;
  6242. $height = 2848;
  6243. // 开始为每个资产创建图片生成任务
  6244. $taskIds = [];
  6245. $productTaskMap = []; // 资产ID到任务ID的映射
  6246. foreach ($products as $product) {
  6247. if (empty($product->pic_prompt)) {
  6248. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  6249. continue;
  6250. }
  6251. try {
  6252. // 创建图片生成任务
  6253. $params = [
  6254. 'prompt' => $product->pic_prompt,
  6255. 'model' => $model,
  6256. 'ref_img_urls' => [],
  6257. 'width' => $width,
  6258. 'height' => $height
  6259. ];
  6260. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6261. $task_id = $task->id;
  6262. if ($task_id) {
  6263. $taskIds[] = $task_id;
  6264. $productTaskMap[$product->id] = $task_id;
  6265. // 更新资产表的任务ID和状态
  6266. DB::table('mp_products')
  6267. ->where('id', $product->id)
  6268. ->update([
  6269. 'pic_task_id' => $task_id,
  6270. 'pic_task_status' => '生成中',
  6271. 'updated_at' => now()
  6272. ]);
  6273. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  6274. }
  6275. } catch (\Exception $e) {
  6276. dLog('anime')->error('创建资产图片生成任务失败', [
  6277. 'product_id' => $product->id,
  6278. 'error' => $e->getMessage()
  6279. ]);
  6280. // 标记为失败
  6281. DB::table('mp_products')
  6282. ->where('id', $product->id)
  6283. ->update([
  6284. 'pic_task_status' => '生成失败',
  6285. 'updated_at' => now()
  6286. ]);
  6287. }
  6288. }
  6289. if (empty($taskIds)) {
  6290. Utils::throwError('20003:没有成功创建任何图片生成任务');
  6291. }
  6292. // 返回 SSE 流
  6293. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  6294. }
  6295. /**
  6296. * 轮询资产图片生成任务状态(SSE流式返回)
  6297. * 只通过查询数据库获取任务状态,不主动调用API
  6298. *
  6299. * @param int $script_id 剧本ID
  6300. * @param string $script_name 剧本名称
  6301. * @param array $productTaskMap 资产ID到任务ID的映射
  6302. * @param array $type_folder_ids 类型文件夹ID映射
  6303. * @return \Generator
  6304. */
  6305. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  6306. $startTime = time();
  6307. $timeout = 1800; // 30分钟超时
  6308. $pollInterval = 10; // 10秒轮询一次
  6309. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  6310. // 定义类型名称映射
  6311. $typeNames = [
  6312. 1 => 'roles', // 角色
  6313. 2 => 'scenes', // 场景
  6314. 3 => 'props' // 道具
  6315. ];
  6316. while (time() - $startTime < $timeout) {
  6317. sleep($pollInterval);
  6318. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  6319. $mappings = DB::table('mp_script_product_mappings')
  6320. ->where('script_id', $script_id)
  6321. ->pluck('product_id')
  6322. ->unique()
  6323. ->toArray();
  6324. if (empty($mappings)) {
  6325. dLog('anime')->warning('该剧本没有关联的资产', [
  6326. 'script_id' => $script_id,
  6327. 'script_name' => $script_name
  6328. ]);
  6329. break;
  6330. }
  6331. // 查询所有资产的当前状态
  6332. $products = DB::table('mp_products')
  6333. ->whereIn('id', $mappings)
  6334. ->where('is_deleted', 0)
  6335. ->get();
  6336. // 统计各类型的状态(使用类型名称作为键名)
  6337. $stats = [
  6338. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  6339. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  6340. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  6341. ];
  6342. $allCompleted = true;
  6343. $hasStatusChange = false;
  6344. foreach ($products as $product) {
  6345. $type = $product->product;
  6346. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  6347. // 如果类型名称不在 stats 中,初始化
  6348. if (!isset($stats[$typeName])) {
  6349. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  6350. }
  6351. $stats[$typeName]['total']++;
  6352. $task_id = $product->pic_task_id;
  6353. $currentStatus = $product->pic_task_status;
  6354. // 检查状态是否有变化
  6355. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  6356. $hasStatusChange = true;
  6357. $lastStatus[$product->id] = $currentStatus;
  6358. }
  6359. // 如果是生成中,查询任务表状态
  6360. if ($currentStatus === '生成中' && $task_id) {
  6361. // 只查询数据库,不调用API
  6362. $task = DB::table('mp_generate_pic_tasks')
  6363. ->where('id', $task_id)
  6364. ->first();
  6365. if ($task) {
  6366. // 检查任务状态
  6367. if ($task->status === 'success' && $task->result_url) {
  6368. // 解析图片URL
  6369. $result_urls = $task->result_url;
  6370. if (is_string($result_urls)) {
  6371. $result_urls = json_decode($result_urls, true);
  6372. }
  6373. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6374. // 更新资产表状态
  6375. DB::table('mp_products')
  6376. ->where('id', $product->id)
  6377. ->update([
  6378. 'pic_task_status' => '生成成功',
  6379. 'url' => $img_url,
  6380. 'updated_at' => now()
  6381. ]);
  6382. $stats[$typeName]['success']++;
  6383. $stats[$typeName]['completed']++;
  6384. $hasStatusChange = true;
  6385. dLog('anime')->info('资产图片生成成功', [
  6386. 'product_id' => $product->id,
  6387. 'task_id' => $task_id,
  6388. 'img_url' => $img_url
  6389. ]);
  6390. } elseif ($task->status === 'failed') {
  6391. // 更新资产表状态
  6392. DB::table('mp_products')
  6393. ->where('id', $product->id)
  6394. ->update([
  6395. 'pic_task_status' => '生成失败',
  6396. 'updated_at' => now()
  6397. ]);
  6398. $stats[$typeName]['completed']++;
  6399. $hasStatusChange = true;
  6400. dLog('anime')->warning('资产图片生成失败', [
  6401. 'product_id' => $product->id,
  6402. 'task_id' => $task_id,
  6403. 'error' => $task->error_message ?? '未知错误'
  6404. ]);
  6405. } else {
  6406. // 任务还在处理中
  6407. $allCompleted = false;
  6408. }
  6409. } else {
  6410. // 任务不存在,标记为失败
  6411. DB::table('mp_products')
  6412. ->where('id', $product->id)
  6413. ->update([
  6414. 'pic_task_status' => '生成失败',
  6415. 'updated_at' => now()
  6416. ]);
  6417. $stats[$type]['completed']++;
  6418. $hasStatusChange = true;
  6419. dLog('anime')->error('图片生成任务不存在', [
  6420. 'product_id' => $product->id,
  6421. 'task_id' => $task_id
  6422. ]);
  6423. }
  6424. } elseif ($currentStatus === '生成成功') {
  6425. $stats[$typeName]['success']++;
  6426. $stats[$typeName]['completed']++;
  6427. } elseif ($currentStatus === '生成失败') {
  6428. $stats[$typeName]['completed']++;
  6429. } else {
  6430. // 其他状态也认为未完成
  6431. $allCompleted = false;
  6432. }
  6433. }
  6434. // 移除没有数据的类型(total=0)
  6435. foreach ($stats as $typeName => $stat) {
  6436. if ($stat['total'] === 0) {
  6437. unset($stats[$typeName]);
  6438. }
  6439. }
  6440. // 如果有状态变化,发送 SSE 更新
  6441. if ($hasStatusChange) {
  6442. $eventType = $allCompleted ? 'complete' : 'update';
  6443. $response = [
  6444. 'type' => $eventType,
  6445. 'script_id' => $script_id,
  6446. 'script_name' => $script_name,
  6447. 'stats' => $stats,
  6448. 'timestamp' => date('Y-m-d H:i:s')
  6449. ];
  6450. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  6451. dLog('anime')->info('SSE更新', [
  6452. 'event_type' => $eventType,
  6453. 'script_id' => $script_id,
  6454. 'script_name' => $script_name,
  6455. 'stats' => $stats
  6456. ]);
  6457. if ($allCompleted) {
  6458. dLog('anime')->info('所有资产图片生成任务已完成', [
  6459. 'script_id' => $script_id,
  6460. 'script_name' => $script_name,
  6461. 'stats' => $stats
  6462. ]);
  6463. break;
  6464. }
  6465. }
  6466. }
  6467. // 超时处理
  6468. if (time() - $startTime >= $timeout && !$allCompleted) {
  6469. $response = [
  6470. 'type' => 'timeout',
  6471. 'message' => '部分任务超时,请稍后查看结果',
  6472. 'script_id' => $script_id,
  6473. 'script_name' => $script_name,
  6474. 'timestamp' => date('Y-m-d H:i:s')
  6475. ];
  6476. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  6477. dLog('anime')->warning('资产图片生成任务超时', [
  6478. 'script_id' => $script_id,
  6479. 'script_name' => $script_name,
  6480. 'timeout' => $timeout
  6481. ]);
  6482. }
  6483. }
  6484. /**
  6485. * 获取剧本关联的资产列表
  6486. * @param array $data 请求参数
  6487. * @return array
  6488. */
  6489. public function getScriptProducts($data) {
  6490. $uid = Site::getUid();
  6491. $cpid = Site::getCpid();
  6492. $script_id = getProp($data, 'script_id');
  6493. $episode_number = getProp($data, 'episode_number');
  6494. if (!$script_id) {
  6495. Utils::throwError('20003:请提供剧本ID');
  6496. }
  6497. // 验证剧本是否存在
  6498. $script = DB::table('mp_scripts')
  6499. ->where('id', $script_id)
  6500. ->where('is_deleted', 0)
  6501. ->first();
  6502. if (!$script) {
  6503. Utils::throwError('20003:剧本不存在');
  6504. }
  6505. // 联表查询资产信息
  6506. $query = DB::table('mp_script_product_mappings as mapping')
  6507. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6508. ->where('mapping.script_id', $script_id)
  6509. ->where('product.cpid', $cpid)
  6510. ->where('product.is_deleted', 0);
  6511. // 如果提供了 episode_number,则过滤指定集数
  6512. if ($episode_number !== null && $episode_number !== '') {
  6513. $query->where('mapping.episode_number', $episode_number);
  6514. }
  6515. $mappings = $query->select(
  6516. 'mapping.script_id',
  6517. 'mapping.product_id',
  6518. 'mapping.episode_number',
  6519. 'product.product_name',
  6520. 'product.type',
  6521. 'product.product',
  6522. 'product.pic_prompt',
  6523. 'product.url',
  6524. 'product.pic_task_id',
  6525. 'product.pic_task_status',
  6526. 'product.three_view_image_url',
  6527. 'mapping.created_at'
  6528. )
  6529. ->orderBy('mapping.product_id', 'asc')
  6530. ->orderBy('mapping.episode_number', 'asc')
  6531. ->get();
  6532. // 按 product_id 分组,合并 episode_number
  6533. $productMap = [];
  6534. foreach ($mappings as $item) {
  6535. $product_id = $item->product_id;
  6536. if (!isset($productMap[$product_id])) {
  6537. $productMap[$product_id] = [
  6538. 'product_id' => $product_id,
  6539. 'product_name' => $item->product_name,
  6540. 'type' => (int)$item->type,
  6541. 'product' => (int)$item->product,
  6542. 'pic_prompt' => $item->pic_prompt,
  6543. 'url' => $item->url,
  6544. 'pic_task_id' => $item->pic_task_id,
  6545. 'pic_task_status' => $item->pic_task_status,
  6546. 'episode_numbers' => [],
  6547. 'created_at' => $item->created_at,
  6548. ];
  6549. }
  6550. // 添加 episode_number(去重)
  6551. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6552. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6553. }
  6554. }
  6555. // 按类型分组
  6556. $roles = []; // type=1 角色/主体
  6557. $scenes = []; // type=2 场景
  6558. $props = []; // type=3 道具
  6559. foreach ($productMap as $product) {
  6560. // 将 episode_numbers 数组转换为逗号分隔的字符串
  6561. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  6562. // 构造返回数据
  6563. $productData = [
  6564. 'product_id' => $product['product_id'],
  6565. 'product_name' => $product['product_name'],
  6566. 'product' => $product['product'],
  6567. 'pic_prompt' => $product['pic_prompt'],
  6568. 'url' => $product['url'],
  6569. 'pic_task_id' => $product['pic_task_id'],
  6570. 'pic_task_status' => $product['pic_task_status'],
  6571. 'episode_numbers' => $episodeNumbersStr,
  6572. 'created_at' => $product['created_at'],
  6573. ];
  6574. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  6575. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  6576. switch ($product['product']) {
  6577. case 1:
  6578. $roles[] = $productData;
  6579. break;
  6580. case 2:
  6581. $scenes[] = $productData;
  6582. break;
  6583. case 3:
  6584. $props[] = $productData;
  6585. break;
  6586. }
  6587. }
  6588. return [
  6589. 'script_id' => $script_id,
  6590. 'script_name' => $script->script_name ?? '',
  6591. 'roles' => $roles, // 主体
  6592. 'scenes' => $scenes, // 场景
  6593. 'props' => $props, // 道具
  6594. ];
  6595. }
  6596. /**
  6597. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  6598. * @param string $actContent 原始内容
  6599. * @param array $products 产品数组(包含product_name和url)
  6600. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  6601. */
  6602. public function processActContentWithProducts($actContent, $products) {
  6603. if (empty($actContent) || empty($products)) {
  6604. return [
  6605. 'content' => $actContent,
  6606. 'reference_images' => []
  6607. ];
  6608. }
  6609. // 构建产品名称到产品信息的映射
  6610. $product_dict = [];
  6611. foreach ($products as $product) {
  6612. $product_name = getProp($product, 'product_name');
  6613. if ($product_name) {
  6614. $product_dict[$product_name] = [
  6615. 'url' => getProp($product, 'url'),
  6616. 'voice_prompt' => getProp($product, 'voice_prompt')
  6617. ];
  6618. }
  6619. }
  6620. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  6621. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  6622. $reference_images = [];
  6623. $product_index_map = []; // 产品名称 => 图片序号的映射
  6624. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  6625. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  6626. $current_index = 1;
  6627. if (!empty($matches[1])) {
  6628. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  6629. $seen_products = []; // 用于去重
  6630. foreach ($matches[1] as $product_name) {
  6631. // 跳过已处理的产品
  6632. if (isset($seen_products[$product_name])) {
  6633. continue;
  6634. }
  6635. $seen_products[$product_name] = true;
  6636. // 检查产品是否在字典中
  6637. if (isset($product_dict[$product_name])) {
  6638. $url = $product_dict[$product_name]['url'];
  6639. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  6640. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  6641. if (!empty($voice_prompt) && $product_name !== '旁白') {
  6642. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  6643. }
  6644. // 只有URL非空才分配序号和添加到参考图片
  6645. if (!empty($url)) {
  6646. // 检查URL是否已经在reference_images中(去重)
  6647. if (!in_array($url, $reference_images)) {
  6648. $reference_images[] = $url;
  6649. $product_index_map[$product_name] = $current_index;
  6650. $current_index++;
  6651. } else {
  6652. // URL重复,找到已有的序号
  6653. $existing_index = array_search($url, $reference_images) + 1;
  6654. $product_index_map[$product_name] = $existing_index;
  6655. }
  6656. } else {
  6657. // URL为空,不分配序号(后续直接去掉{})
  6658. $product_index_map[$product_name] = 0;
  6659. }
  6660. } else {
  6661. // 产品不在字典中,不分配序号
  6662. $product_index_map[$product_name] = 0;
  6663. }
  6664. }
  6665. }
  6666. // 第二步:替换内容中的 {产品名称}
  6667. $processedContent = $actContent;
  6668. foreach ($product_index_map as $product_name => $index) {
  6669. $escaped_name = preg_quote($product_name, '/');
  6670. if ($index > 0) {
  6671. // 有图片,替换为:产品名称(图X)
  6672. $replacement = $product_name . '<图片' . $index . '>';
  6673. } else {
  6674. // 无图片,只保留产品名称
  6675. $replacement = $product_name;
  6676. }
  6677. // 替换所有 {产品名称} 为处理后的格式
  6678. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  6679. }
  6680. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  6681. foreach ($products as $product) {
  6682. $product_name = getProp($product, 'product_name');
  6683. $voice_prompt = getProp($product, 'voice_prompt');
  6684. if ($product_name === '旁白' && !empty($voice_prompt)) {
  6685. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  6686. break; // 找到旁白后退出循环
  6687. }
  6688. }
  6689. // 第四步:将voice_prompt信息添加到内容最前面
  6690. $voice_prompt_prefix = '';
  6691. if (!empty($voice_prompts)) {
  6692. $voice_prompt_prefix .= implode('', $voice_prompts);
  6693. }
  6694. // 旁白的voice_prompt放在最后
  6695. if (!empty($narrator_voice_prompt)) {
  6696. $voice_prompt_prefix .= $narrator_voice_prompt;
  6697. }
  6698. // 如果有voice_prompt信息,添加到内容开头
  6699. if (!empty($voice_prompt_prefix)) {
  6700. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  6701. }
  6702. return [
  6703. 'content' => $processedContent,
  6704. 'reference_images' => $reference_images
  6705. ];
  6706. }
  6707. public function saveActVideoGenerateParams($data) {
  6708. $episode_id = getProp($data, 'episode_id');
  6709. $model = getProp($data, 'video_model');
  6710. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  6711. Utils::throwError('20003:该模型不可用');
  6712. }
  6713. if (!$model) {
  6714. // 使用默认模型
  6715. $model = 'zhizhen-20-mini';
  6716. }
  6717. // 验证模型是否在可用模型表中
  6718. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6719. Utils::throwError('20003:该模型已不可用,请更换!');
  6720. }
  6721. $video_resolution = getProp($data, 'video_resolution', '720p');
  6722. $ratio = getProp($data, 'ratio');
  6723. if (!$ratio) $ratio = '9:16';
  6724. return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  6725. 'video_model' => $model,
  6726. 'video_resolution' => $video_resolution,
  6727. 'ratio' => $ratio,
  6728. 'updated_at' => date('Y-m-d H:i:s')
  6729. ]);
  6730. }
  6731. public function confirmActs($data) {
  6732. $episode_id = getProp($data, 'episode_id');
  6733. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  6734. if (!$episode) {
  6735. Utils::throwError('20003:分集不存在');
  6736. }
  6737. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  6738. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  6739. // 获取所有片段数据
  6740. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  6741. // 构建角色和场景名称数组
  6742. $role_names = [];
  6743. $scene_names = [];
  6744. foreach ($roles as $role) {
  6745. $role_name = getProp($role, 'role');
  6746. if ($role_name && $role_name != '旁白') {
  6747. $role_names[] = $role_name;
  6748. }
  6749. }
  6750. foreach ($scenes as $scene) {
  6751. $scene_name = getProp($scene, 'scene');
  6752. if ($scene_name) {
  6753. $scene_names[] = $scene_name;
  6754. }
  6755. }
  6756. // 按照字符长度降序排序,确保先匹配长的名称(避免部分匹配问题)
  6757. usort($role_names, function($a, $b) {
  6758. return mb_strlen($b) - mb_strlen($a);
  6759. });
  6760. usort($scene_names, function($a, $b) {
  6761. return mb_strlen($b) - mb_strlen($a);
  6762. });
  6763. try {
  6764. DB::beginTransaction();
  6765. // 处理每个片段
  6766. foreach ($acts as $act) {
  6767. $act_content = getProp($act, 'act_content');
  6768. if (!$act_content) continue;
  6769. $processed_content = $act_content;
  6770. // 标记已处理的位置,避免重复标记
  6771. $marked_positions = [];
  6772. // 先匹配场景(在"场景:"后面)
  6773. foreach ($scene_names as $scene_name) {
  6774. // 转义特殊字符
  6775. $escaped_scene = preg_quote($scene_name, '/');
  6776. // 匹配场景:后面的场景名称(可能换行,也可能不换行)
  6777. $pattern = '/(场景:[\s\r\n]*)(' . $escaped_scene . ')/u';
  6778. $processed_content = preg_replace_callback($pattern, function($matches) use (&$marked_positions) {
  6779. $full_match = $matches[0];
  6780. $prefix = $matches[1];
  6781. $scene_name = $matches[2];
  6782. // 检查是否已经被标记
  6783. if (strpos($scene_name, '{') === false && strpos($scene_name, '}') === false) {
  6784. return $prefix . '{' . $scene_name . '}';
  6785. }
  6786. return $full_match;
  6787. }, $processed_content);
  6788. }
  6789. // 再匹配角色名称(只在"画面:"部分)
  6790. foreach ($role_names as $role_name) {
  6791. // 转义特殊字符
  6792. $escaped_role = preg_quote($role_name, '/');
  6793. // 只匹配"画面:"开始到换行之前的内容
  6794. $pattern = '/(画面:[^\n]*)/u';
  6795. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
  6796. $line = $matches[1]; // 整行"画面:xxxxx"
  6797. // 在这一行中匹配所有角色名(避免重复标记)
  6798. $new_line = preg_replace(
  6799. '/(?<![{])(' . $escaped_role . ')(?![}])/u',
  6800. '{$1}',
  6801. $line
  6802. );
  6803. return $new_line;
  6804. }, $processed_content);
  6805. }
  6806. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  6807. $shot_counter = 0;
  6808. $processed_content = preg_replace_callback(
  6809. '/【(?:镜头|分镜)(\d+)】/u',
  6810. function($matches) use (&$shot_counter) {
  6811. $shot_counter++;
  6812. return '【镜头' . $shot_counter . '】';
  6813. },
  6814. $processed_content
  6815. );
  6816. // 更新数据库
  6817. $boolen = DB::table('mp_episode_segments')
  6818. ->where('id', $act->id)
  6819. ->update([
  6820. 'act_show_content' => $processed_content,
  6821. 'updated_at' => date('Y-m-d H:i:s')
  6822. ]);
  6823. if (!$boolen) {
  6824. Utils::throwError('20003:片段处理失败');
  6825. }
  6826. }
  6827. }catch (\Exception $e) {
  6828. DB::rollBack();
  6829. Utils::throwError('20003:'.$e->getMessage());
  6830. }
  6831. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  6832. 'is_generated' => 1,
  6833. 'updated_at' => date('Y-m-d H:i:s')
  6834. ]);
  6835. if (!$boolen1) {
  6836. DB::rollBack();
  6837. Utils::throwError('20003:分集处理失败!');
  6838. }
  6839. DB::commit();
  6840. // 重新查询更新后的片段数据
  6841. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  6842. // 合并角色、场景和extra_products作为products,统一字段名为product_name
  6843. // extra_products优先级更高,会覆盖同名的roles和scenes
  6844. $products = [];
  6845. // 先处理角色数组
  6846. foreach ($roles as $role) {
  6847. $product = $role;
  6848. // 将role字段重命名为product_name
  6849. if (isset($product['role'])) {
  6850. $product['product_name'] = $product['role'];
  6851. unset($product['role']);
  6852. }
  6853. $product['product'] = 1; // 标记类型为角色
  6854. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  6855. }
  6856. // 处理场景数组
  6857. foreach ($scenes as $scene) {
  6858. $product = $scene;
  6859. // 将scene字段重命名为product_name
  6860. if (isset($product['scene'])) {
  6861. $product['product_name'] = $product['scene'];
  6862. unset($product['scene']);
  6863. }
  6864. $product['product'] = 2; // 标记类型为场景
  6865. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  6866. }
  6867. // extra_products优先级更高,直接覆盖同名的roles和scenes
  6868. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  6869. foreach ($extra_products as $extra_product) {
  6870. $product_name = getProp($extra_product, 'product_name');
  6871. if ($product_name) {
  6872. $products[$product_name] = $extra_product; // 覆盖同名数据
  6873. }
  6874. }
  6875. // 重新索引数组(去除key)
  6876. $products = array_values($products);
  6877. // 构建返回的acts数组
  6878. $return_acts = [];
  6879. foreach ($acts as $act) {
  6880. $return_acts[] = [
  6881. 'act_id' => getProp($act, 'id'),
  6882. 'act_number' => getProp($act, 'act_number'),
  6883. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  6884. 'act_show_content' => getProp($act, 'act_show_content'),
  6885. 'video_url' => getProp($act, 'video_url'),
  6886. 'video_duration' => getProp($act, 'video_duration'),
  6887. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  6888. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  6889. ];
  6890. }
  6891. return [
  6892. 'anime_id' => getProp($episode, 'anime_id'),
  6893. 'episode_id' => $episode_id,
  6894. 'title' => getProp($episode, 'title'),
  6895. 'episode_number' => getProp($episode, 'episode_number'),
  6896. 'is_generated' => getProp($episode, 'is_generated'),
  6897. 'products' => $products,
  6898. 'acts' => $return_acts
  6899. ];
  6900. }
  6901. }