AnimeService.php 466 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Models\MpTaskCenter;
  9. use App\Services\AIGeneration\AIImageGenerationService;
  10. use App\Services\AIGeneration\AIVideoGenerationService;
  11. use App\Services\DeepSeek\DeepSeekService;
  12. use App\Services\PointsService;
  13. use App\Services\TaskCenterService;
  14. use Dflydev\DotAccessData\Util;
  15. use GuzzleHttp\Client;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Log;
  18. use Illuminate\Support\Facades\Redis;
  19. use OSS\Core\OssException;
  20. use OSS\OssClient;
  21. class AnimeService
  22. {
  23. protected $aiImageGenerationService;
  24. protected $aiVideoGenerationService;
  25. protected $DeepSeekService;
  26. protected $pointsService;
  27. protected $taskCenterService;
  28. private $url;
  29. private $api_key;
  30. private $headers;
  31. public function __construct(
  32. AIImageGenerationService $aiImageGenerationService,
  33. AIVideoGenerationService $aiVideoGenerationService,
  34. DeepSeekService $DeepSeekService,
  35. PointsService $pointsService,
  36. TaskCenterService $taskCenterService
  37. ) {
  38. $this->aiImageGenerationService = $aiImageGenerationService;
  39. $this->aiVideoGenerationService = $aiVideoGenerationService;
  40. $this->DeepSeekService = $DeepSeekService;
  41. $this->pointsService = $pointsService;
  42. $this->taskCenterService = $taskCenterService;
  43. $this->url = 'https://api.deepseek.com/chat/completions';
  44. $this->api_key = env('DEEPSEEK_API_KEY');
  45. $this->headers = [
  46. 'Authorization' => 'Bearer '.$this->api_key,
  47. 'Content-Type' => 'application/json; charset=UTF-8'
  48. ];
  49. }
  50. /**
  51. * 构建统一的分镜数据结构(episodeInfo格式)
  52. * @param array $segments 分镜数据数组
  53. * @return array 返回包含acts和total_duration的数组
  54. */
  55. public function buildEpisodeSegmentsStructure($segments) {
  56. $acts = [];
  57. $totalDuration = 0; // 初始化总时长
  58. foreach($segments as $segment) {
  59. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  60. $videoDuration = getProp($segment, 'video_duration');
  61. $audioDuration = getProp($segment, 'audio_duration');
  62. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  63. $totalDuration += floatval($videoDuration);
  64. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  65. $totalDuration += floatval($audioDuration);
  66. } else {
  67. $totalDuration += 5; // 默认5秒
  68. }
  69. $segment_content = getProp($segment, 'segment_content');
  70. // 判断是否有尾帧描述,如果有则去掉这部分内容
  71. if (strpos($segment_content, '尾帧') !== false) {
  72. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  73. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  74. }
  75. // 构建分镜信息
  76. $segmentInfo = [
  77. 'segment_id' => getProp($segment, 'segment_id'),
  78. 'segment_number' => getProp($segment, 'segment_number'),
  79. 'segment_content' => $segment_content,
  80. 'description' => getProp($segment, 'description'),
  81. 'composition' => getProp($segment, 'composition'),
  82. 'camera_movement' => getProp($segment, 'camera_movement'),
  83. 'voice_actor' => getProp($segment, 'voice_actor'),
  84. 'dialogue' => getProp($segment, 'dialogue'),
  85. 'frame_type' => getProp($segment, 'frame_type'),
  86. 'scene' => getProp($segment, 'scene'),
  87. 'characters' => getProp($segment, 'characters'),
  88. 'tail_frame' => getProp($segment, 'tail_frame'),
  89. 'emotion' => getProp($segment, 'emotion'),
  90. 'emotion_type' => getProp($segment, 'emotion_type'),
  91. 'gender' => getProp($segment, 'gender'),
  92. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  93. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  94. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  95. 'pitch' => getProp($segment, 'pitch'),
  96. 'voice_name' => getProp($segment, 'voice_name'),
  97. 'voice_type' => getProp($segment, 'voice_type'),
  98. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  99. 'img_url' => getProp($segment, 'img_url'),
  100. 'audio_url' => getProp($segment, 'audio_url'),
  101. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  102. 'video_url' => getProp($segment, 'video_url'),
  103. 'video_duration' => getProp($segment, 'video_duration', 0),
  104. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  105. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  106. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  107. 'current_type' => getProp($segment, 'current_type'),
  108. ];
  109. $actNumber = getProp($segment, 'act_number');
  110. if (isset($acts[$actNumber])) {
  111. $acts[$actNumber]['segments'][] = $segmentInfo;
  112. } else {
  113. $acts[$actNumber] = [
  114. 'act_number' => $actNumber,
  115. 'act_title' => getProp($segment, 'act_title'),
  116. 'act_duration' => getProp($segment, 'act_duration'),
  117. 'segments' => [$segmentInfo]
  118. ];
  119. }
  120. }
  121. return [
  122. 'acts' => array_values($acts),
  123. 'total_duration' => intval(round($totalDuration))
  124. ];
  125. }
  126. /**
  127. * 构建统一的分段数据结构(episodeInfoForAce格式)
  128. * @param array $segments 分段数据数组
  129. * @return array 返回包含acts和total_duration的数组
  130. */
  131. public function buildEpisodeActsStructureForAce($segments) {
  132. $acts = [];
  133. $totalDuration = 0; // 初始化总时长
  134. foreach($segments as $segment) {
  135. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  136. $videoDuration = getProp($segment, 'video_duration');
  137. $actDuration = getProp($segment, 'act_duration');
  138. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  139. $totalDuration += floatval($videoDuration);
  140. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  141. $totalDuration += floatval($actDuration);
  142. } else {
  143. $totalDuration += 5; // 默认5秒
  144. }
  145. // 构建分镜信息
  146. $segmentInfo = [
  147. 'act_id' => getProp($segment, 'id'),
  148. 'act_number' => getProp($segment, 'act_number'),
  149. 'act_title' => getProp($segment, 'act_title'),
  150. 'act_duration' => getProp($segment, 'act_duration'),
  151. 'act_content' => getProp($segment, 'act_content'),
  152. 'video_url' => getProp($segment, 'video_url'),
  153. 'video_duration' => getProp($segment, 'video_duration', 0),
  154. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  155. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  156. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  157. 'current_type' => getProp($segment, 'current_type'),
  158. ];
  159. $acts[] = $segmentInfo;
  160. }
  161. return [
  162. 'acts' => array_values($acts),
  163. 'total_duration' => intval(round($totalDuration))
  164. ];
  165. }
  166. /**
  167. * 验证画面比例是否有效
  168. * @param string $ratio 画面比例
  169. * @return bool
  170. */
  171. public function validateRatio($ratio) {
  172. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  173. }
  174. /**
  175. * 获取画面比例对应的宽高
  176. * @param string $ratio 画面比例
  177. * @return array ['width' => int, 'height' => int]
  178. * @throws \Exception
  179. */
  180. private function getRatioDimensions($ratio) {
  181. if ($ratio && !$this->validateRatio($ratio)) {
  182. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  183. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  184. }
  185. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  186. }
  187. public function createAnime($data) {
  188. $uid = Site::getUid();
  189. $cpid = Site::getCpid();
  190. $input_art_style = getProp($data, 'art_style');
  191. $file = getProp($data, 'file');
  192. $content = getProp($data, 'content', '');
  193. $bid = getProp($data, 'bid', 0);
  194. $script_id = getProp($data, 'script_id', 0);
  195. $ace_mode = getProp($data, 'ace_mode', 0);
  196. $extra_products = getProp($data, 'products', []);
  197. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  198. if (!is_array($extra_products)) {
  199. Utils::throwError('20003:传入的资产格式不正确');
  200. }
  201. // 替换美术风格
  202. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  203. // 提取文件内容
  204. if ($file) {
  205. $content = $this->DeepSeekService->extractFileContent($file);
  206. if (!$content) {
  207. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  208. }
  209. } elseif ($script_id) {
  210. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  211. if (!$content) {
  212. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  213. }
  214. } elseif ($bid) {
  215. $content = $this->DeepSeekService->getContentByBid($bid);
  216. if (!$content) {
  217. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  218. }
  219. } elseif ($content) {
  220. $content = filterContent($content);
  221. }else {
  222. $content = '';
  223. }
  224. $anime_data = [
  225. 'user_id' => $uid,
  226. 'cpid' => $cpid,
  227. 'anime_name' => '新剧本策划',
  228. 'is_multi' => getProp($data, 'is_multi', 1),
  229. 'content' => $content,
  230. 'art_style_type' => $input_art_style,
  231. 'ace_mode' => $ace_mode,
  232. 'script_id' => $script_id,
  233. 'extra_products' => json_encode($extra_products, 256),
  234. 'created_at' => date('Y-m-d H:i:s'),
  235. 'updated_at' => date('Y-m-d H:i:s'),
  236. ];
  237. // 处理文本模型
  238. $model = getProp($data, 'model');
  239. if (!$model) {
  240. // 用户没有输入,使用默认值
  241. $model = 'deepseek-v4-pro';
  242. }
  243. // 验证模型是否在可用模型表中
  244. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  245. $model = 'deepseek-v4-pro';
  246. }
  247. $anime_data['model'] = $model;
  248. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  249. return DB::table('mp_animes')->insertGetId($anime_data);
  250. }
  251. public function chatList($data) {
  252. $uid = Site::getUid();
  253. $anime_name = getProp($data, 'anime_name');
  254. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  255. if ($anime_name) {
  256. $query->where('anime_name', 'like', "%$anime_name%");
  257. }
  258. return $query->orderBy('id', 'desc')->paginate();
  259. }
  260. public function chatHistory($data) {
  261. $anime_id = getProp($data, 'anime_id');
  262. $sequence = getProp($data, 'sequence', 0);
  263. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  264. $query = DB::table('mp_anime_records as ar')->leftJoin('mp_anime_episodes as ae', 'ar.episode_id', '=', 'ae.id')->where('ar.anime_id', $anime_id)
  265. ->where('ar.sequence', $sequence)->where('segment_id', 0)->where('act_id', 0)->select('ar.role', 'ar.content', 'ar.created_at', 'ar.episode_id', 'ae.title as episode_title', 'ae.created_at as episode_created_at');
  266. return $query->orderBy('ar.id')->get()->map(function ($value) {
  267. $value = (array)$value;
  268. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  269. $value['created_at'] = transDate($value['created_at']);
  270. $value['episode_created_at'] = transDate($value['episode_created_at']);
  271. return $value;
  272. })->toArray();
  273. }
  274. public function batchSetRoleImg($data) {
  275. $episode_id = getProp($data, 'episode_id');
  276. if (!$episode_id) Utils::throwError('1002:请选择分集');
  277. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  278. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  279. $art_style = getProp($episode, 'art_style');
  280. $anime_id = getProp($episode, 'anime_id');
  281. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  282. $art_style_type = getProp($anime, 'art_style_type');
  283. $character_prefix = '';
  284. $scene_prefix = '';
  285. if ($art_style_type) {
  286. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  287. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  288. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  289. }
  290. foreach ($roles as &$role) {
  291. $role_name = getProp($role, 'role');
  292. if ($role_name == '旁白') continue;
  293. // 优先使用 pic_prompt,如果没有则使用 description
  294. $pic_prompt = getProp($role, 'pic_prompt');
  295. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  296. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  297. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  298. // 参考图地址
  299. $ref_img_url = getProp($role, 'url');
  300. if ($ref_img_url) continue; // 已有图片则跳过
  301. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  302. try {
  303. $params = [
  304. 'prompt' => $description,
  305. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  306. ];
  307. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  308. $task_id = $task->id;
  309. if (!$task_id) {
  310. Utils::throwError("20003:角色({$role_name})生成图片失败");
  311. }
  312. $role['task_id'] = $task_id;
  313. $role['task_status'] = 'processing';
  314. } catch (\Exception $e) {
  315. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  316. Utils::throwError("20003:" . $e->getMessage());
  317. }
  318. }
  319. // 保存角色信息
  320. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  321. 'roles' => json_encode($roles, 256),
  322. 'generate_status' => '执行中',
  323. 'generate_at' => date('Y-m-d H:i:s'),
  324. 'updated_at' => date('Y-m-d H:i:s')
  325. ]);
  326. if (!$boolen) {
  327. Utils::throwError('20003:保存角色信息失败');
  328. }
  329. return $boolen;
  330. }
  331. public function batchSetSceneImg($data) {
  332. $episode_id = getProp($data, 'episode_id');
  333. if (!$episode_id) Utils::throwError('1002:请选择分集');
  334. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  335. $scenes = json_decode(getProp($episode, 'scenes'), true);
  336. $art_style = getProp($episode, 'art_style');
  337. $target_scene = getProp($data, 'target_scene');
  338. $anime_id = getProp($episode, 'anime_id');
  339. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  340. $art_style_type = getProp($anime, 'art_style_type');
  341. $character_prefix = '';
  342. $scene_prefix = '';
  343. if ($art_style_type) {
  344. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  345. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  346. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  347. }
  348. foreach ($scenes as &$scene) {
  349. $scene_name = getProp($scene, 'scene');
  350. if ($scene_name != $target_scene) continue;
  351. // 优先使用 pic_prompt,如果没有则使用 description
  352. $pic_prompt = getProp($scene, 'pic_prompt');
  353. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  354. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  355. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  356. // 参考图地址
  357. $ref_img_url = getProp($scene, 'url');
  358. if ($ref_img_url) continue; // 已有图片则跳过
  359. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  360. try {
  361. $params = [
  362. 'prompt' => $description,
  363. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  364. ];
  365. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  366. $task_id = $task->id;
  367. if (!$task_id) {
  368. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  369. }
  370. $scene['task_id'] = $task_id;
  371. $scene['task_status'] = 'processing';
  372. } catch (\Exception $e) {
  373. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  374. Utils::throwError("20003:" . $e->getMessage());
  375. }
  376. }
  377. // 保存场景信息
  378. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  379. 'scenes' => json_encode($scenes, 256),
  380. 'generate_status' => '执行中',
  381. 'generate_at' => date('Y-m-d H:i:s'),
  382. 'updated_at' => date('Y-m-d H:i:s')
  383. ]);
  384. if (!$boolen) {
  385. Utils::throwError('20003:保存角色信息失败');
  386. }
  387. return $boolen;
  388. }
  389. public function editAnime($data) {
  390. $anime_id = getProp($data, 'anime_id');
  391. $anime_name = trim(getProp($data, 'anime_name'));
  392. // 确认对话名称唯一性
  393. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  394. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  395. }
  396. if (!$anime_id || !$anime_name) {
  397. Utils::throwError('20003:参数异常');
  398. }
  399. return DB::table('mp_animes')->where('id', $anime_id)->update([
  400. 'anime_name' => $anime_name,
  401. 'updated_at' => date('Y-m-d H:i:s')
  402. ]);
  403. // $script_arr =getProp($data, 'script', []);
  404. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  405. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  406. // $anime_id = getProp($data, 'anime_id');
  407. // try {
  408. // DB::beginTransaction();
  409. // $table_data = [
  410. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  411. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  412. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  413. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  414. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  415. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  416. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  417. // 'status' => 3,
  418. // 'start_episode_sequence' => $start_episode_sequence,
  419. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  420. // 'episode_num' => count($script_arr['episodes']),
  421. // 'updated_at' => date('Y-m-d H:i:s')
  422. // ];
  423. // // 保存剧本内容
  424. // if (!empty($anime_id)) {
  425. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  426. // if (!$boolen) {
  427. // dLog('anime')->info('对话保存失败', $table_data);
  428. // Utils::throwError('20003:对话保存失败');
  429. // }
  430. // }else {
  431. // $table['created_at'] = $table_data['updated_at'];
  432. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  433. // if (!$anime_id) {
  434. // dLog('anime')->info('对话保存失败', $table_data);
  435. // Utils::throwError('20003:对话保存失败');
  436. // }
  437. // }
  438. // // 保存分集内容
  439. // // 删除历史分集内容
  440. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  441. // $episodes = [];
  442. // $sequence = 1;
  443. // foreach ($script_arr['episodes'] as $episode) {
  444. // $segment_number = 1;
  445. // foreach($episode['segments'] as $segment) {
  446. // $episodes[] = [
  447. // 'anime_id' => $anime_id,
  448. // 'episode_number' => $episode['episode_number'],
  449. // 'title' => $episode['title'],
  450. // // 'content' => $episode['content'],
  451. // 'content' => '',
  452. // 'segment_number' => $segment_number,
  453. // 'segment_content' => $segment['segment_content'],
  454. // 'sequence' => $sequence,
  455. // 'created_at' => date('Y-m-d H:i:s'),
  456. // 'updated_at' => date('Y-m-d H:i:s')
  457. // ];
  458. // $sequence++;
  459. // $segment_number++;
  460. // }
  461. // }
  462. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  463. // if (!$boolen2) {
  464. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  465. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  466. // Utils::throwError('20003:分集内容保存失败');
  467. // }
  468. // } catch (\Exception $e) {
  469. // DB::rollBack();
  470. // Utils::throwError('20003:'.$e->getMessage());
  471. // }
  472. // DB::commit();
  473. // return true;
  474. }
  475. public function delAnime($data) {
  476. $anime_id = getProp($data, 'anime_id');
  477. if (!$anime_id) {
  478. Utils::throwError('20003:请选择剧本');
  479. }
  480. return DB::table('mp_animes')->where('id', $anime_id)->update([
  481. 'is_deleted' => 1,
  482. 'updated_at' => date('Y-m-d H:i:s')
  483. ]);
  484. }
  485. public function animeDetail($data) {
  486. $uid = Site::getUid();
  487. $anime_id = getProp($data, 'anime_id');
  488. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  489. ->selectRaw('id as anime_id, anime_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, remark, generate_status, created_at, ace_mode, end_episode_sequence')->first();
  490. if (!$anime) Utils::throwError('20003:权限不足');
  491. $anime = (array)$anime;
  492. $anime['roles'] = json_decode($anime['roles']);
  493. $anime['scenes'] = json_decode($anime['scenes']);
  494. // 获取分集信息
  495. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  496. ->select('id as episode_id', 'episode_number', 'title', 'is_generated', DB::raw("(select es.img_url from mp_episode_segments as es where es.episode_id = mp_anime_episodes.id order by es.segment_number limit 1) as first_frame_url"))
  497. ->orderBy('episode_number')->get()->map(function ($value) {
  498. return (array)$value;
  499. })->toArray();
  500. $anime['episodes'] = $episodes;
  501. // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
  502. $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
  503. $episodeTasks = DB::table('mp_batch_episode_generation_details')
  504. ->where('anime_id', $anime_id)
  505. ->whereIn('status', ['pending', 'processing', 'failed']) // 只获取待生成/生成中任务,已完成或失败的不显示
  506. ->orderBy('episode_number')
  507. ->get()
  508. ->map(function ($task) use ($episodeNumbers) {
  509. if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
  510. return null;
  511. }
  512. return [
  513. 'episode_number' => (int)$task->episode_number,
  514. 'status' => $task->status,
  515. 'error_message' => $task->status == 'failed' ? $task->error_message : '',
  516. ];
  517. })
  518. ->filter()
  519. ->values()
  520. ->toArray();
  521. $anime['episode_tasks'] = $episodeTasks;
  522. return $anime;
  523. }
  524. public function episodeInfo($data) {
  525. $uid = Site::getUid();
  526. $anime_id = getProp($data, 'anime_id');
  527. $episode_id = getProp($data, 'episode_id');
  528. if (!$anime_id || !$episode_id) {
  529. Utils::throwError('1002:请选择剧集');
  530. }
  531. // 验证用户权限
  532. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  533. if (!$anime) Utils::throwError('20003:权限不足');
  534. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->first();
  535. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  536. $episode = (array)$episode;
  537. $episode['roles'] = json_decode($episode['roles'], true);
  538. // foreach($episode['roles'] as &$item) {
  539. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  540. // }
  541. $episode['scenes'] = json_decode($episode['scenes'], true);
  542. // foreach($episode['scenes'] as &$item) {
  543. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  544. // }
  545. // 获取分镜信息
  546. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  547. ->select('*')->get()->map(function ($value) {
  548. return (array)$value;
  549. })->toArray();
  550. // 使用公共方法构建分镜结构
  551. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  552. $episode['acts'] = $segmentsStructure['acts'];
  553. $episode['total_duration'] = $segmentsStructure['total_duration'];
  554. return $episode;
  555. }
  556. public function episodeInfoForAce($data) {
  557. $anime_id = getProp($data, 'anime_id');
  558. $episode_id = getProp($data, 'episode_id');
  559. if (!$anime_id || !$episode_id) {
  560. Utils::throwError('1002:请选择剧集');
  561. }
  562. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'props', 'is_generated')->first();
  563. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  564. $episode = (array)$episode;
  565. $episode['roles'] = json_decode($episode['roles'], true);
  566. // foreach($episode['roles'] as &$item) {
  567. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  568. // }
  569. $episode['scenes'] = json_decode($episode['scenes'], true);
  570. // foreach($episode['scenes'] as &$item) {
  571. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  572. // }
  573. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  574. // 获取分镜信息
  575. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  576. ->select('*')->get()->map(function ($value) {
  577. return (array)$value;
  578. })->toArray();
  579. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  580. $episode['acts'] = $segmentsStructure['acts'];
  581. $episode['total_duration'] = $segmentsStructure['total_duration'];
  582. // 获取mp_animes表中的视频参数
  583. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  584. $episode['video_params'] = [
  585. 'video_model' => getProp($anime, 'video_model'),
  586. 'video_resolution' => getProp($anime, 'video_resolution'),
  587. 'ratio' => getProp($anime, 'video_ratio'),
  588. ];
  589. return $episode;
  590. }
  591. public function segmentInfo($data) {
  592. $uid = Site::getUid();
  593. $segment_id = getProp($data, 'segment_id');
  594. if (!$segment_id) {
  595. Utils::throwError('1002:请选择分镜');
  596. }
  597. // 获取分镜信息
  598. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  599. // 验证用户权限
  600. if ($segment) {
  601. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  602. if (!$anime) Utils::throwError('20003:权限不足');
  603. }
  604. $result = [
  605. 'segment_id' => getProp($segment, 'segment_id'),
  606. 'segment_number' => getProp($segment, 'segment_number'),
  607. 'segment_content' => getProp($segment, 'segment_content'),
  608. 'description' => getProp($segment, 'description'),
  609. 'composition' => getProp($segment, 'composition'),
  610. 'camera_movement' => getProp($segment, 'camera_movement'),
  611. 'voice_actor' => getProp($segment, 'voice_actor'),
  612. 'dialogue' => getProp($segment, 'dialogue'),
  613. 'frame_type' => getProp($segment, 'frame_type'),
  614. 'scene' => getProp($segment, 'scene'),
  615. 'characters' => getProp($segment, 'characters'),
  616. 'tail_frame' => getProp($segment, 'tail_frame'),
  617. 'emotion' => getProp($segment, 'emotion'),
  618. 'emotion_type' => getProp($segment, 'emotion_type'),
  619. 'gender' => getProp($segment, 'gender'),
  620. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  621. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  622. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  623. 'pitch' => getProp($segment, 'pitch'),
  624. 'voice_name' => getProp($segment, 'voice_name'),
  625. 'voice_type' => getProp($segment, 'voice_type'),
  626. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  627. 'img_url' => getProp($segment, 'img_url'),
  628. 'video_url' => getProp($segment, 'video_url'),
  629. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  630. ];
  631. return $result;
  632. }
  633. public function copyEpisodeVersion($data) {
  634. $episode_id = getProp($data, 'episode_id');
  635. $uid = Site::getUid();
  636. $cpid = Site::getCpid();
  637. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  638. if (!$episode) Utils::throwError('20003:该剧集不存在');
  639. $episode = (array)$episode;
  640. $anime_id = $episode['anime_id'];
  641. $episode_number = $episode['episode_number'];
  642. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  643. $sequence = $count + 1;
  644. unset($episode['id']);
  645. $now = date('Y-m-d H:i:s');
  646. $episode['created_at'] = $now;
  647. $episode['updated_at'] = $now;
  648. $episode['is_default'] = 1;
  649. // 获取版本中含有"(副本"字样的个数
  650. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  651. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  652. $episode['sequence'] = $sequence;
  653. $episode['is_generated'] = 0;
  654. $episode['cpid'] = $cpid;
  655. // 获取ace_mode
  656. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  657. try {
  658. DB::beginTransaction();
  659. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  660. // 新增副本
  661. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  662. if (!$new_episode_id) {
  663. Utils::throwError('20003:创建副本失败!');
  664. }
  665. // 获取分镜数据并准备插入
  666. $segments_for_insert = DB::table('mp_episode_segments')
  667. ->select('anime_id', 'episode_number', 'act_number', 'act_title', 'act_duration', 'act_content', 'segment_number', 'segment_content', 'description', 'composition', 'camera_movement', 'voice_actor', 'dialogue', 'frame_type', 'scene', 'characters', 'tail_frame', 'voice_name', 'voice_type', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  668. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  669. $item = (array)$item;
  670. $item['episode_id'] = $new_episode_id;
  671. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  672. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  673. return $item;
  674. })->toArray();
  675. // 写入分镜数据
  676. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  677. if (!$boolen2) {
  678. Utils::throwError('20003:写入分镜数据失败!');
  679. }
  680. // 写入对话历史
  681. $records = [
  682. [
  683. 'uid' => $uid,
  684. 'anime_id' => $anime_id,
  685. 'role' => 'user',
  686. 'content' => '创建副本',
  687. 'sequence' => $episode_number,
  688. 'episode_id' => $new_episode_id,
  689. 'created_at' => $now,
  690. 'updated_at' => $now
  691. ],
  692. [
  693. 'uid' => $uid,
  694. 'anime_id' => $anime_id,
  695. 'role' => 'assistant',
  696. 'content' => '好的,已为您创建副本',
  697. 'sequence' => $episode_number,
  698. 'episode_id' => $new_episode_id,
  699. 'created_at' => $now,
  700. 'updated_at' => $now
  701. ]
  702. ];
  703. $boolen3 = DB::table('mp_anime_records')->insert($records);
  704. if (!$boolen3) {
  705. Utils::throwError('20003:对话记录保存失败');
  706. }
  707. }catch (\Exception $e) {
  708. DB::rollBack();
  709. Utils::throwError('20003:'.$e->getMessage());
  710. }
  711. DB::commit();
  712. // 构建与 episodeInfo 方法一致的返回数据结构
  713. $result = [
  714. 'episode_id' => $new_episode_id,
  715. 'anime_id' => $anime_id,
  716. 'episode_number' => $episode_number,
  717. 'title' => $episode['title'],
  718. 'intro' => $episode['intro'],
  719. 'art_style' => $episode['art_style'],
  720. 'roles' => json_decode($episode['roles'], true),
  721. 'scenes' => json_decode($episode['scenes'], true),
  722. 'is_generated' => (int)$episode['is_generated']
  723. ];
  724. if ((int)$ace_mode === 1) {
  725. // 获取分镜信息
  726. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  727. ->select('*')->get()->map(function ($value) {
  728. return (array)$value;
  729. })->toArray();
  730. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  731. }else {
  732. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  733. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  734. }
  735. $result['acts'] = $segmentsStructure['acts'];
  736. $result['total_duration'] = $segmentsStructure['total_duration'];
  737. return $result;
  738. }
  739. public function episodeVersions($data) {
  740. $anime_id = getProp($data, 'anime_id');
  741. $episode_id = getProp($data, 'episode_id');
  742. if (!$anime_id || !$episode_id) {
  743. Utils::throwError('1002:请选择剧集');
  744. }
  745. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  746. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->select('id as episode_id', 'anime_id', 'episode_number', 'sequence', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->orderBy('sequence', 'desc')->get()->map(function($value) {
  747. return (array)$value;
  748. })->toArray();
  749. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  750. foreach($episodes as &$episode) {
  751. $episode['version'] = 'V'.$episode['sequence'];
  752. $episode['roles'] = json_decode($episode['roles'], true);
  753. $episode['scenes'] = json_decode($episode['scenes'], true);
  754. // 获取分镜信息
  755. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  756. ->select('*')->get()->map(function ($value) {
  757. return (array)$value;
  758. })->toArray();
  759. // 使用公共方法构建分镜结构
  760. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  761. $episode['acts'] = $segmentsStructure['acts'];
  762. $episode['total_duration'] = $segmentsStructure['total_duration'];
  763. }
  764. return $episodes;
  765. }
  766. public function bindEpisodeVersion($data) {
  767. $episode_id = getProp($data, 'episode_id');
  768. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  769. if (!$episode) Utils::throwError('20003:该剧集不存在');
  770. $episode = (array)$episode;
  771. if ((int)$episode['is_default'] === 1) return true;
  772. try {
  773. DB::beginTransaction();
  774. // 移除is_default标志
  775. $boolen = DB::table('mp_anime_episodes')->where('anime_id', $episode['anime_id'])->where('episode_number', $episode['episode_number'])->update(['is_default' => 0, 'updated_at'=>date('Y-m-d H:i:s')]);
  776. if (!$boolen) {
  777. Utils::throwError('20003:更新失败!');
  778. }
  779. // 绑定副本
  780. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  781. if (!$boolen2) {
  782. Utils::throwError('20003:绑定失败!');
  783. }
  784. }catch (\Exception $e) {
  785. DB::rollBack();
  786. Utils::throwError('20003:'.$e->getMessage());
  787. }
  788. DB::commit();
  789. return true;
  790. }
  791. public function chatChangeImg($data) {
  792. $segment_id = getProp($data, 'segment_id');
  793. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  794. $prompt = getProp($data, 'prompt');
  795. if (!$prompt || !$segment_id) {
  796. Utils::throwError('1002:请输入提示词,并且选择分镜');
  797. }
  798. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  799. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  800. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  801. else $ref_img_url = '';
  802. // $ref_img_url = '';
  803. if (empty($prompt)) {
  804. if (empty($ref_img_url)) {
  805. $prompt = getProp($segment, 'segment_content');
  806. }else {
  807. $prompt = '请根据图片生成';
  808. }
  809. }
  810. $anime_id = getProp($segment, 'anime_id');
  811. $episode_id = getProp($segment, 'episode_id');
  812. $episode_number = getProp($segment, 'episode_number');
  813. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  814. $ratio = getProp($data, 'ratio');
  815. if (!$ratio) {
  816. $ratio = getProp($episode, 'ratio');
  817. if (!$ratio) $ratio = '9:16';
  818. }
  819. $art_style = getProp($episode, 'art_style');
  820. if ($art_style) {
  821. $prompt = "美术风格:{$art_style}\n{$prompt}";
  822. }
  823. $dimensions = $this->getRatioDimensions($ratio);
  824. $width = $dimensions['width'];
  825. $height = $dimensions['height'];
  826. try {
  827. $params = [
  828. 'alias_segment_id' => $segment_id,
  829. 'prompt' => $prompt,
  830. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  831. 'width' => $width,
  832. 'height' => $height
  833. ];
  834. // 优化提示词(不要生成字幕)
  835. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  836. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  837. $task_id = $task->id;
  838. if (!$task_id) {
  839. Utils::throwError("20003:生成图片失败");
  840. }
  841. // 更新任务ID
  842. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update(['pic_task_id' => $task_id, 'pic_task_status' => '生成中', 'updated_at' => date('Y-m-d H:i:s')]);
  843. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  844. } catch (\Exception $e) {
  845. Utils::throwError("20003:" . $e->getMessage());
  846. }
  847. // 创建任务之后先暂停10s等待异步任务完成
  848. sleep(10);
  849. $img_url = $this->loopGetPicTaskResult($task_id);
  850. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  851. // 图片生成后新增对话记录
  852. try {
  853. $uid = Site::getUid();
  854. $now = date('Y-m-d H:i:s');
  855. // 使用AI反推图片提示词
  856. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  857. // 保存对话记录
  858. $records = [
  859. [
  860. 'uid' => $uid,
  861. 'anime_id' => $anime_id,
  862. 'sequence' => $episode_number,
  863. 'role' => 'user',
  864. 'content' => $prompt,
  865. 'segment_id' => $segment_id,
  866. 'pic_task_id' => $task_id,
  867. 'image_url' => '',
  868. 'created_at' => $now,
  869. 'updated_at' => $now
  870. ],
  871. [
  872. 'uid' => $uid,
  873. 'anime_id' => $anime_id,
  874. 'sequence' => $episode_number,
  875. 'role' => 'assistant',
  876. 'content' => $pic_prompt,
  877. 'segment_id' => $segment_id,
  878. 'pic_task_id' => $task_id,
  879. 'image_url' => $img_url,
  880. 'created_at' => $now,
  881. 'updated_at' => $now
  882. ]
  883. ];
  884. DB::table('mp_anime_records')->insert($records);
  885. } catch (\Exception $e) {
  886. // 记录日志但不影响主流程
  887. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  888. 'segment_id' => $segment_id,
  889. 'img_url' => $img_url
  890. ]);
  891. logDB('anime', 'error', '保存对话记录失败', [
  892. 'segment_id' => $segment_id,
  893. 'img_url' => $img_url,
  894. 'error' => $e->getMessage()
  895. ]);
  896. }
  897. return $img_url;
  898. }
  899. public function segmentChatHistory($data) {
  900. $segment_id = getProp($data, 'segment_id');
  901. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  902. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'video_task_id', 'pic_task_id', 'created_at');
  903. $chat = $query->orderBy('id')->get()->map(function ($value) {
  904. $value = (array)$value;
  905. $value['created_at'] = transDate($value['created_at']);
  906. return $value;
  907. })->toArray();
  908. // 获取历史图片
  909. $url = [];
  910. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  911. foreach($pic_history as $task) {
  912. $result_url = getProp($task, 'result_url');
  913. if (is_json($result_url)) {
  914. $url = array_merge($url, json_decode($result_url, true));
  915. }else {
  916. $url[] = $result_url;
  917. }
  918. }
  919. // 获取历史视频
  920. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  921. foreach($video_history as $task) {
  922. $result_url = getProp($task, 'compressed_url');
  923. if (is_json($result_url)) {
  924. $url = array_merge($url, json_decode($result_url, true));
  925. }else {
  926. $url[] = $result_url;
  927. }
  928. }
  929. return compact('chat', 'url');
  930. }
  931. public function changeEpisodeRoles($data) {
  932. $anime_id = getProp($data, 'anime_id');
  933. $episode_id = getProp($data, 'episode_id');
  934. $target_roles = getProp($data, 'roles');
  935. // 删除标志位于角色对象内部(roles.is_deleted),不在最外层
  936. $is_deleted = getProp($target_roles, 'is_deleted', 0);
  937. // 控制字段不随角色内容写入分集roles存储
  938. if (is_array($target_roles)) {
  939. unset($target_roles['is_deleted']);
  940. }
  941. // 参数验证
  942. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  943. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  944. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  945. // 验证剧集是否存在
  946. $episode = DB::table('mp_anime_episodes')
  947. ->where('anime_id', $anime_id)
  948. ->where('id', $episode_id)
  949. ->first();
  950. if (!$episode) Utils::throwError('20003:该剧集不存在');
  951. $roles = json_decode(getProp($episode, 'roles'), true);
  952. // 获取anime信息,检查是否有关联的script_id
  953. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  954. if (!$anime) Utils::throwError('20003:动漫不存在');
  955. $script_id = getProp($anime, 'script_id');
  956. $episode_number = getProp($episode, 'episode_number', 1);
  957. $uid = Site::getUid();
  958. $cpid = Site::getCpid();
  959. try {
  960. $target_role_name = getProp($target_roles, 'role');
  961. if (empty($target_role_name)) {
  962. Utils::throwError('20003:角色名称不能为空');
  963. }
  964. // 如果是删除操作
  965. if ($is_deleted == 1) {
  966. // 从角色列表中移除该角色
  967. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  968. return getProp($role, 'role') !== $target_role_name;
  969. }));
  970. // 更新角色列表
  971. $result = DB::table('mp_anime_episodes')
  972. ->where('anime_id', $anime_id)
  973. ->where('id', $episode_id)
  974. ->update([
  975. 'roles' => json_encode($roles, 256),
  976. 'updated_at' => date('Y-m-d H:i:s')
  977. ]);
  978. if ($result === false) {
  979. Utils::throwError('20003:删除角色失败');
  980. }
  981. } else {
  982. // 新增或更新操作
  983. $role_found = false;
  984. $is_new_role = false;
  985. // 查找并更新已存在的角色
  986. foreach($roles as &$role) {
  987. if (getProp($role, 'role') === $target_role_name) {
  988. $role = $target_roles;
  989. $role_found = true;
  990. break;
  991. }
  992. }
  993. // 如果角色不存在,则新增
  994. if (!$role_found) {
  995. $roles[] = $target_roles;
  996. $is_new_role = true;
  997. }
  998. // 更新角色列表
  999. $result = DB::table('mp_anime_episodes')
  1000. ->where('anime_id', $anime_id)
  1001. ->where('id', $episode_id)
  1002. ->update([
  1003. 'roles' => json_encode($roles, 256),
  1004. 'updated_at' => date('Y-m-d H:i:s')
  1005. ]);
  1006. if ($result === false) {
  1007. Utils::throwError('20003:更新角色列表失败');
  1008. }
  1009. // 同步更新分镜表中对应主体的音色信息
  1010. $voice_name = getProp($target_roles, 'voice_name');
  1011. $voice_type = getProp($target_roles, 'voice_type');
  1012. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  1013. DB::table('mp_episode_segments')
  1014. ->where('anime_id', $anime_id)
  1015. ->where('episode_id', $episode_id)
  1016. ->where('voice_actor', $target_role_name)
  1017. ->update([
  1018. 'voice_name' => $voice_name,
  1019. 'voice_type' => $voice_type,
  1020. 'voice_audio_url' => $voice_audio_url,
  1021. 'updated_at' => date('Y-m-d H:i:s')
  1022. ]);
  1023. // 如果有关联的script_id,则同步到mp_products表
  1024. if ($script_id) {
  1025. // 查询剧本信息
  1026. $script = DB::table('mp_scripts')
  1027. ->where('id', $script_id)
  1028. ->where('is_deleted', 0)
  1029. ->first();
  1030. if ($script) {
  1031. $script_name = $script->script_name ?? 'script_' . $script_id;
  1032. $product_name = getProp($target_roles, 'role');
  1033. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1034. $url = getProp($target_roles, 'url', '');
  1035. $product_type = 1; // 1=角色
  1036. // 查找或创建以script_name命名的文件夹
  1037. $folder = DB::table('mp_products')
  1038. ->where('cpid', $cpid)
  1039. ->where('type', 2) // 文件夹类型
  1040. ->where('product', $product_type) // 角色类型
  1041. ->where('product_name', $script_name)
  1042. ->where('parent_id', 0)
  1043. ->where('is_deleted', 0)
  1044. ->first();
  1045. if (!$folder) {
  1046. // 创建文件夹
  1047. $folder_id = DB::table('mp_products')->insertGetId([
  1048. 'user_id' => $uid,
  1049. 'cpid' => $cpid,
  1050. 'type' => 2, // 文件夹
  1051. 'product' => $product_type, // 角色类型
  1052. 'parent_id' => 0,
  1053. 'level' => 1,
  1054. 'product_name' => $script_name,
  1055. 'sort_order' => time(),
  1056. 'is_deleted' => 0,
  1057. 'created_at' => date('Y-m-d H:i:s'),
  1058. 'updated_at' => date('Y-m-d H:i:s')
  1059. ]);
  1060. } else {
  1061. $folder_id = $folder->id;
  1062. }
  1063. // 查找该文件夹下是否已存在同名资产
  1064. $existing_product = DB::table('mp_products')
  1065. ->where('cpid', $cpid)
  1066. ->where('type', 1) // 资产类型
  1067. ->where('product', $product_type)
  1068. ->where('parent_id', $folder_id)
  1069. ->where('product_name', $product_name)
  1070. ->where('is_deleted', 0)
  1071. ->first();
  1072. if ($existing_product) {
  1073. // 更新已存在的资产
  1074. $updateData = [
  1075. 'pic_task_status' => '生成成功',
  1076. ];
  1077. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1078. if ($url) $updateData['url'] = $url;
  1079. // 处理versions字段
  1080. $versions = getProp($target_roles, 'versions', []);
  1081. if ($versions && is_array($versions)) {
  1082. $updateData['versions'] = json_encode($versions, 256);
  1083. }
  1084. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1085. DB::table('mp_products')
  1086. ->where('id', $existing_product->id)
  1087. ->update($updateData);
  1088. $product_id = $existing_product->id;
  1089. } else {
  1090. // 创建新资产
  1091. $versions = getProp($target_roles, 'versions', []);
  1092. $product_id = DB::table('mp_products')->insertGetId([
  1093. 'user_id' => $uid,
  1094. 'cpid' => $cpid,
  1095. 'type' => 1, // 资产
  1096. 'product' => $product_type, // 角色
  1097. 'parent_id' => $folder_id,
  1098. 'level' => 2,
  1099. 'product_name' => $product_name,
  1100. 'url' => $url,
  1101. 'pic_prompt' => $pic_prompt,
  1102. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1103. 'sort_order' => time(),
  1104. 'is_deleted' => 0,
  1105. 'pic_task_status' => '生成成功',
  1106. 'created_at' => date('Y-m-d H:i:s'),
  1107. 'updated_at' => date('Y-m-d H:i:s')
  1108. ]);
  1109. }
  1110. // 建立或更新绑定关系
  1111. $existing_mapping = DB::table('mp_script_product_mappings')
  1112. ->where('script_id', $script_id)
  1113. ->where('product_id', $product_id)
  1114. ->where('episode_number', $episode_number)
  1115. ->first();
  1116. if (!$existing_mapping) {
  1117. // 创建绑定关系
  1118. DB::table('mp_script_product_mappings')->insert([
  1119. 'script_id' => $script_id,
  1120. 'product_id' => $product_id,
  1121. 'episode_number' => $episode_number,
  1122. 'created_at' => date('Y-m-d H:i:s'),
  1123. 'updated_at' => date('Y-m-d H:i:s')
  1124. ]);
  1125. }
  1126. }
  1127. }
  1128. }
  1129. } catch (\Exception $e) {
  1130. dLog('anime')->error('更新剧集角色失败', [
  1131. 'anime_id' => $anime_id,
  1132. 'episode_id' => $episode_id,
  1133. 'error' => $e->getMessage()
  1134. ]);
  1135. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1136. }
  1137. return true;
  1138. }
  1139. public function changeEpisodeScenes($data) {
  1140. $anime_id = getProp($data, 'anime_id');
  1141. $episode_id = getProp($data, 'episode_id');
  1142. $target_scenes = getProp($data, 'scenes');
  1143. // 删除标志位于场景对象内部(scenes.is_deleted),不在最外层
  1144. $is_deleted = getProp($target_scenes, 'is_deleted', 0);
  1145. // 控制字段不随场景内容写入分集scenes存储
  1146. if (is_array($target_scenes)) {
  1147. unset($target_scenes['is_deleted']);
  1148. }
  1149. // 参数验证
  1150. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1151. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1152. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1153. // 验证剧集是否存在
  1154. $episode = DB::table('mp_anime_episodes')
  1155. ->where('anime_id', $anime_id)
  1156. ->where('id', $episode_id)
  1157. ->first();
  1158. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1159. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1160. // 获取anime信息,检查是否有关联的script_id
  1161. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1162. if (!$anime) Utils::throwError('20003:动漫不存在');
  1163. $script_id = getProp($anime, 'script_id');
  1164. $episode_number = getProp($episode, 'episode_number', 1);
  1165. $uid = Site::getUid();
  1166. $cpid = Site::getCpid();
  1167. try {
  1168. $target_scene_name = getProp($target_scenes, 'scene');
  1169. if (empty($target_scene_name)) {
  1170. Utils::throwError('20003:场景名称不能为空');
  1171. }
  1172. // 如果是删除操作
  1173. if ($is_deleted == 1) {
  1174. // 从场景列表中移除该场景
  1175. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1176. return getProp($scene, 'scene') !== $target_scene_name;
  1177. }));
  1178. // 更新场景列表
  1179. $result = DB::table('mp_anime_episodes')
  1180. ->where('anime_id', $anime_id)
  1181. ->where('id', $episode_id)
  1182. ->update([
  1183. 'scenes' => json_encode($scenes, 256),
  1184. 'updated_at' => date('Y-m-d H:i:s')
  1185. ]);
  1186. if ($result === false) {
  1187. Utils::throwError('20003:删除场景失败');
  1188. }
  1189. } else {
  1190. // 新增或更新操作
  1191. $scene_found = false;
  1192. $is_new_scene = false;
  1193. // 查找并更新已存在的场景
  1194. foreach($scenes as &$scene) {
  1195. if (getProp($scene, 'scene') === $target_scene_name) {
  1196. $scene = $target_scenes;
  1197. $scene_found = true;
  1198. break;
  1199. }
  1200. }
  1201. // 如果场景不存在,则新增
  1202. if (!$scene_found) {
  1203. $scenes[] = $target_scenes;
  1204. $is_new_scene = true;
  1205. }
  1206. // 更新场景列表
  1207. $result = DB::table('mp_anime_episodes')
  1208. ->where('anime_id', $anime_id)
  1209. ->where('id', $episode_id)
  1210. ->update([
  1211. 'scenes' => json_encode($scenes, 256),
  1212. 'updated_at' => date('Y-m-d H:i:s')
  1213. ]);
  1214. if ($result === false) {
  1215. Utils::throwError('20003:更新场景列表失败');
  1216. }
  1217. // 如果有关联的script_id,则同步到mp_products表
  1218. if ($script_id) {
  1219. // 查询剧本信息
  1220. $script = DB::table('mp_scripts')
  1221. ->where('id', $script_id)
  1222. ->where('is_deleted', 0)
  1223. ->first();
  1224. if ($script) {
  1225. $script_name = $script->script_name ?? 'script_' . $script_id;
  1226. $product_name = getProp($target_scenes, 'scene');
  1227. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1228. $url = getProp($target_scenes, 'url', '');
  1229. $product_type = 2; // 2=场景
  1230. // 查找或创建以script_name命名的文件夹
  1231. $folder = DB::table('mp_products')
  1232. ->where('cpid', $cpid)
  1233. ->where('type', 2) // 文件夹类型
  1234. ->where('product', $product_type) // 场景类型
  1235. ->where('product_name', $script_name)
  1236. ->where('parent_id', 0)
  1237. ->where('is_deleted', 0)
  1238. ->first();
  1239. if (!$folder) {
  1240. // 创建文件夹
  1241. $folder_id = DB::table('mp_products')->insertGetId([
  1242. 'user_id' => $uid,
  1243. 'cpid' => $cpid,
  1244. 'type' => 2, // 文件夹
  1245. 'product' => $product_type, // 场景类型
  1246. 'parent_id' => 0,
  1247. 'level' => 1,
  1248. 'product_name' => $script_name,
  1249. 'sort_order' => time(),
  1250. 'is_deleted' => 0,
  1251. 'created_at' => date('Y-m-d H:i:s'),
  1252. 'updated_at' => date('Y-m-d H:i:s')
  1253. ]);
  1254. } else {
  1255. $folder_id = $folder->id;
  1256. }
  1257. // 查找该文件夹下是否已存在同名资产
  1258. $existing_product = DB::table('mp_products')
  1259. ->where('cpid', $cpid)
  1260. ->where('type', 1) // 资产类型
  1261. ->where('product', $product_type)
  1262. ->where('parent_id', $folder_id)
  1263. ->where('product_name', $product_name)
  1264. ->where('is_deleted', 0)
  1265. ->first();
  1266. if ($existing_product) {
  1267. // 更新已存在的资产
  1268. $updateData = [
  1269. 'pic_task_status' => '生成成功'
  1270. ];
  1271. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1272. if ($url) $updateData['url'] = $url;
  1273. // 处理versions字段
  1274. $versions = getProp($target_scenes, 'versions', []);
  1275. if ($versions && is_array($versions)) {
  1276. $updateData['versions'] = json_encode($versions, 256);
  1277. }
  1278. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1279. DB::table('mp_products')
  1280. ->where('id', $existing_product->id)
  1281. ->update($updateData);
  1282. $product_id = $existing_product->id;
  1283. } else {
  1284. // 创建新资产
  1285. $versions = getProp($target_scenes, 'versions', []);
  1286. $product_id = DB::table('mp_products')->insertGetId([
  1287. 'user_id' => $uid,
  1288. 'cpid' => $cpid,
  1289. 'type' => 1, // 资产
  1290. 'product' => $product_type, // 场景
  1291. 'parent_id' => $folder_id,
  1292. 'level' => 2,
  1293. 'product_name' => $product_name,
  1294. 'url' => $url,
  1295. 'pic_prompt' => $pic_prompt,
  1296. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1297. 'sort_order' => time(),
  1298. 'is_deleted' => 0,
  1299. 'pic_task_status' => '生成成功',
  1300. 'created_at' => date('Y-m-d H:i:s'),
  1301. 'updated_at' => date('Y-m-d H:i:s')
  1302. ]);
  1303. }
  1304. // 建立或更新绑定关系
  1305. $existing_mapping = DB::table('mp_script_product_mappings')
  1306. ->where('script_id', $script_id)
  1307. ->where('product_id', $product_id)
  1308. ->where('episode_number', $episode_number)
  1309. ->first();
  1310. if (!$existing_mapping) {
  1311. // 创建绑定关系
  1312. DB::table('mp_script_product_mappings')->insert([
  1313. 'script_id' => $script_id,
  1314. 'product_id' => $product_id,
  1315. 'episode_number' => $episode_number,
  1316. 'created_at' => date('Y-m-d H:i:s'),
  1317. 'updated_at' => date('Y-m-d H:i:s')
  1318. ]);
  1319. }
  1320. }
  1321. }
  1322. }
  1323. } catch (\Exception $e) {
  1324. dLog('anime')->error('更新剧集场景失败', [
  1325. 'anime_id' => $anime_id,
  1326. 'episode_id' => $episode_id,
  1327. 'error' => $e->getMessage()
  1328. ]);
  1329. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1330. }
  1331. return true;
  1332. }
  1333. public function changeEpisodeProps($data) {
  1334. $anime_id = getProp($data, 'anime_id');
  1335. $episode_id = getProp($data, 'episode_id');
  1336. $target_props = getProp($data, 'props');
  1337. // 删除标志位于道具对象内部(props.is_deleted),不在最外层
  1338. $is_deleted = getProp($target_props, 'is_deleted', 0);
  1339. // 控制字段不随道具内容写入分集props存储
  1340. if (is_array($target_props)) {
  1341. unset($target_props['is_deleted']);
  1342. }
  1343. // 参数验证
  1344. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1345. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1346. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1347. // 验证剧集是否存在
  1348. $episode = DB::table('mp_anime_episodes')
  1349. ->where('anime_id', $anime_id)
  1350. ->where('id', $episode_id)
  1351. ->first();
  1352. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1353. $props = json_decode(getProp($episode, 'props'), true);
  1354. // 获取anime信息,检查是否有关联的script_id
  1355. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1356. if (!$anime) Utils::throwError('20003:动漫不存在');
  1357. $script_id = getProp($anime, 'script_id');
  1358. $episode_number = getProp($episode, 'episode_number', 1);
  1359. $uid = Site::getUid();
  1360. $cpid = Site::getCpid();
  1361. try {
  1362. $target_prop_name = getProp($target_props, 'prop');
  1363. if (empty($target_prop_name)) {
  1364. Utils::throwError('20003:道具名称不能为空');
  1365. }
  1366. // 如果是删除操作
  1367. if ($is_deleted == 1) {
  1368. // 从道具列表中移除该道具
  1369. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1370. return getProp($prop, 'prop') !== $target_prop_name;
  1371. }));
  1372. // 更新道具列表
  1373. $result = DB::table('mp_anime_episodes')
  1374. ->where('anime_id', $anime_id)
  1375. ->where('id', $episode_id)
  1376. ->update([
  1377. 'props' => json_encode($props, 256),
  1378. 'updated_at' => date('Y-m-d H:i:s')
  1379. ]);
  1380. if ($result === false) {
  1381. Utils::throwError('20003:删除道具失败');
  1382. }
  1383. } else {
  1384. // 新增或更新操作
  1385. $prop_found = false;
  1386. $is_new_prop = false;
  1387. // 查找并更新已存在的道具
  1388. foreach($props as &$prop) {
  1389. if (getProp($prop, 'prop') === $target_prop_name) {
  1390. $prop = $target_props;
  1391. $prop_found = true;
  1392. break;
  1393. }
  1394. }
  1395. // 如果道具不存在,则新增
  1396. if (!$prop_found) {
  1397. $props[] = $target_props;
  1398. $is_new_prop = true;
  1399. }
  1400. // 更新道具列表
  1401. $result = DB::table('mp_anime_episodes')
  1402. ->where('anime_id', $anime_id)
  1403. ->where('id', $episode_id)
  1404. ->update([
  1405. 'props' => json_encode($props, 256),
  1406. 'updated_at' => date('Y-m-d H:i:s')
  1407. ]);
  1408. if ($result === false) {
  1409. Utils::throwError('20003:更新道具列表失败');
  1410. }
  1411. // 如果有关联的script_id,则同步到mp_products表
  1412. if ($script_id) {
  1413. // 查询剧本信息
  1414. $script = DB::table('mp_scripts')
  1415. ->where('id', $script_id)
  1416. ->where('is_deleted', 0)
  1417. ->first();
  1418. if ($script) {
  1419. $script_name = $script->script_name ?? 'script_' . $script_id;
  1420. $product_name = getProp($target_props, 'prop');
  1421. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1422. $url = getProp($target_props, 'url', '');
  1423. $product_type = 3; // 3=道具
  1424. // 查找或创建以script_name命名的文件夹
  1425. $folder = DB::table('mp_products')
  1426. ->where('cpid', $cpid)
  1427. ->where('type', 2) // 文件夹类型
  1428. ->where('product', $product_type) // 道具类型
  1429. ->where('product_name', $script_name)
  1430. ->where('parent_id', 0)
  1431. ->where('is_deleted', 0)
  1432. ->first();
  1433. if (!$folder) {
  1434. // 创建文件夹
  1435. $folder_id = DB::table('mp_products')->insertGetId([
  1436. 'user_id' => $uid,
  1437. 'cpid' => $cpid,
  1438. 'type' => 2, // 文件夹
  1439. 'product' => $product_type, // 道具类型
  1440. 'parent_id' => 0,
  1441. 'level' => 1,
  1442. 'product_name' => $script_name,
  1443. 'sort_order' => time(),
  1444. 'is_deleted' => 0,
  1445. 'created_at' => date('Y-m-d H:i:s'),
  1446. 'updated_at' => date('Y-m-d H:i:s')
  1447. ]);
  1448. } else {
  1449. $folder_id = $folder->id;
  1450. }
  1451. // 查找该文件夹下是否已存在同名资产
  1452. $existing_product = DB::table('mp_products')
  1453. ->where('cpid', $cpid)
  1454. ->where('type', 1) // 资产类型
  1455. ->where('product', $product_type)
  1456. ->where('parent_id', $folder_id)
  1457. ->where('product_name', $product_name)
  1458. ->where('is_deleted', 0)
  1459. ->first();
  1460. if ($existing_product) {
  1461. // 更新已存在的资产
  1462. $updateData = [
  1463. 'pic_task_status' => '生成成功'
  1464. ];
  1465. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1466. if ($url) $updateData['url'] = $url;
  1467. // 处理versions字段
  1468. $versions = getProp($target_props, 'versions', []);
  1469. if ($versions && is_array($versions)) {
  1470. $updateData['versions'] = json_encode($versions, 256);
  1471. }
  1472. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1473. DB::table('mp_products')
  1474. ->where('id', $existing_product->id)
  1475. ->update($updateData);
  1476. $product_id = $existing_product->id;
  1477. } else {
  1478. // 创建新资产
  1479. $versions = getProp($target_props, 'versions', []);
  1480. $product_id = DB::table('mp_products')->insertGetId([
  1481. 'user_id' => $uid,
  1482. 'cpid' => $cpid,
  1483. 'type' => 1, // 资产
  1484. 'product' => $product_type, // 道具
  1485. 'parent_id' => $folder_id,
  1486. 'level' => 2,
  1487. 'product_name' => $product_name,
  1488. 'url' => $url,
  1489. 'pic_prompt' => $pic_prompt,
  1490. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1491. 'sort_order' => time(),
  1492. 'is_deleted' => 0,
  1493. 'pic_task_status' => '生成成功',
  1494. 'created_at' => date('Y-m-d H:i:s'),
  1495. 'updated_at' => date('Y-m-d H:i:s')
  1496. ]);
  1497. }
  1498. // 建立或更新绑定关系
  1499. $existing_mapping = DB::table('mp_script_product_mappings')
  1500. ->where('script_id', $script_id)
  1501. ->where('product_id', $product_id)
  1502. ->where('episode_number', $episode_number)
  1503. ->first();
  1504. if (!$existing_mapping) {
  1505. // 创建绑定关系
  1506. DB::table('mp_script_product_mappings')->insert([
  1507. 'script_id' => $script_id,
  1508. 'product_id' => $product_id,
  1509. 'episode_number' => $episode_number,
  1510. 'created_at' => date('Y-m-d H:i:s'),
  1511. 'updated_at' => date('Y-m-d H:i:s')
  1512. ]);
  1513. }
  1514. }
  1515. }
  1516. }
  1517. } catch (\Exception $e) {
  1518. dLog('anime')->error('更新剧集道具失败', [
  1519. 'anime_id' => $anime_id,
  1520. 'episode_id' => $episode_id,
  1521. 'error' => $e->getMessage()
  1522. ]);
  1523. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1524. }
  1525. return true;
  1526. }
  1527. public function editSegment($data) {
  1528. $segment_id = getProp($data, 'segment_id');
  1529. $segment_content = getProp($data, 'segment_content');
  1530. $image_url = getProp($data, 'image_url');
  1531. $video_url = getProp($data, 'video_url');
  1532. // 参数验证
  1533. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1534. // 验证分镜是否存在
  1535. $segment = DB::table('mp_episode_segments')
  1536. ->where('segment_id', $segment_id)
  1537. ->first();
  1538. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1539. $dubTaskId = 0;
  1540. try {
  1541. DB::beginTransaction();
  1542. // 准备更新数据
  1543. $update_data = [
  1544. 'updated_at' => date('Y-m-d H:i:s')
  1545. ];
  1546. if ($segment_content) {
  1547. // 先将segment_content赋值到update_data
  1548. $update_data['segment_content'] = $segment_content;
  1549. // 使用现有方法分析segment_content,提取各个字段
  1550. $this->handleSegmentContent($update_data);
  1551. // 如果有对话内容,创建视频配音合成任务
  1552. $dialogue = getProp($update_data, 'dialogue');
  1553. if (!empty($dialogue)) {
  1554. $now = date('Y-m-d H:i:s');
  1555. $generate_json = [
  1556. 'text' => $dialogue,
  1557. 'role' => getProp($update_data, 'voice_actor'),
  1558. 'voice_type' => getProp($update_data, 'voice_type'),
  1559. 'voice_name' => getProp($update_data, 'voice_name'),
  1560. 'emotion' => getProp($update_data, 'emotion'),
  1561. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1562. 'gender' => getProp($update_data, 'gender'),
  1563. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1564. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1565. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1566. 'pitch' => getProp($update_data, 'pitch', 0),
  1567. ];
  1568. // 插入视频配音合成任务
  1569. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1570. 'alias_segment_id' => $segment_id,
  1571. 'generate_status' => '执行中',
  1572. 'audio_url' => '',
  1573. 'generate_json' => json_encode($generate_json, 256),
  1574. 'created_at' => $now,
  1575. 'updated_at' => $now,
  1576. ]);
  1577. if (!$dubTaskId) {
  1578. Utils::throwError('20003:创建配音任务失败!');
  1579. }
  1580. $update_data['audio_url'] = '';
  1581. } else {
  1582. // dialogue为空时,直接写入默认音频信息
  1583. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1584. $update_data['audio_duration'] = 2.0;
  1585. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1586. }
  1587. }
  1588. if ($image_url) {
  1589. $update_data['img_url'] = $image_url;
  1590. // 同时写入一个简单的图片生成任务
  1591. $pic_task = [
  1592. 'alias_segment_id' => $segment_id,
  1593. 'ref_img_url' => json_encode([]),
  1594. 'status' => 'success',
  1595. 'result_url' => json_encode([$image_url], 256),
  1596. 'model' => '',
  1597. 'created_at' => date('Y-m-d H:i:s'),
  1598. 'updated_at' => date('Y-m-d H:i:s'),
  1599. ];
  1600. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1601. }
  1602. if ($video_url) {
  1603. $update_data['origin_video_url'] = $video_url;
  1604. $compressed_video_url = compressVideo($video_url);
  1605. $update_data['current_type'] = 2;
  1606. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1607. // 同时写入一个简单的视频生成任务
  1608. $video_task = [
  1609. 'alias_segment_id' => $segment_id,
  1610. 'status' => 'success',
  1611. 'result_url' => $update_data['origin_video_url'],
  1612. 'compressed_url' => $update_data['video_url'],
  1613. 'created_at' => date('Y-m-d H:i:s'),
  1614. 'updated_at' => date('Y-m-d H:i:s'),
  1615. ];
  1616. DB::table('mp_generate_video_tasks')->insert($video_task);
  1617. }
  1618. // 更新分镜信息
  1619. $result = DB::table('mp_episode_segments')
  1620. ->where('segment_id', $segment_id)
  1621. ->update($update_data);
  1622. if ($result === false) {
  1623. Utils::throwError('20003:更新分镜剧本失败');
  1624. }
  1625. DB::commit();
  1626. // 如果有创建音频生成任务则调用API
  1627. if ($dubTaskId) {
  1628. // 请求远程服务器执行生成
  1629. $client = new Client(['timeout' => 300, 'verify' => false]);
  1630. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1631. $response = $result->getBody()->getContents();
  1632. $response_arr = json_decode($response, true);
  1633. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1634. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1635. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1636. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1637. Utils::throwError('20003:火山生成音频失败');
  1638. }
  1639. }
  1640. return true;
  1641. } catch (\Exception $e) {
  1642. DB::rollBack();
  1643. dLog('anime')->error('更新分镜剧本失败', [
  1644. 'segment_id' => $segment_id,
  1645. 'error' => $e->getMessage()
  1646. ]);
  1647. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1648. }
  1649. }
  1650. public function batchSetSegmentPics($data) {
  1651. $anime_id = getProp($data, 'anime_id');
  1652. $episode_id = getProp($data, 'episode_id');
  1653. $ratio = getProp($data, 'ratio');
  1654. $dimensions = $this->getRatioDimensions($ratio);
  1655. $width = $dimensions['width'];
  1656. $height = $dimensions['height'];
  1657. if (!$anime_id || !$episode_id) {
  1658. Utils::throwError('1002:请选择剧集');
  1659. }
  1660. // 获取剧集信息
  1661. $episode = DB::table('mp_anime_episodes')
  1662. ->where('anime_id', $anime_id)
  1663. ->where('id', $episode_id)
  1664. ->where('is_default', 1)
  1665. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1666. ->first();
  1667. if (!$episode) {
  1668. Utils::throwError('20003:该剧集不存在');
  1669. }
  1670. $model = getProp($data, 'model');
  1671. if (!$model) {
  1672. $model = getProp($episode, 'image_model');
  1673. if (!$model) {
  1674. // episode表也没有,使用默认值
  1675. $model = 'doubao-seedream-5-0-lite-260128';
  1676. }
  1677. }
  1678. // 验证模型是否在可用模型表中
  1679. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1680. $model = 'doubao-seedream-5-0-lite-260128';
  1681. }
  1682. $roles = json_decode(getProp($episode, 'roles'), true);
  1683. if (!$roles) {
  1684. Utils::throwError('20003:角色信息格式错误');
  1685. }
  1686. // 构建角色名称到参考图的映射
  1687. $role_map = [];
  1688. foreach ($roles as $role) {
  1689. $role_name = getProp($role, 'role');
  1690. $role_url = getProp($role, 'url');
  1691. if (!empty($role_name) && !empty($role_url)) {
  1692. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1693. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1694. // $role_map[$base_name] = $role_url;
  1695. // 同时保存完整名称的映射
  1696. $role_map[$role_name] = $role_url;
  1697. }
  1698. }
  1699. $scenes = json_decode(getProp($episode, 'roles'), true);
  1700. if (!$scenes) {
  1701. Utils::throwError('20003:场景信息格式错误');
  1702. }
  1703. // 构建角色名称到参考图的映射
  1704. $scene_map = [];
  1705. foreach ($scenes as $scene) {
  1706. $scene_name = getProp($scene, 'scene');
  1707. $scene_url = getProp($scene, 'url');
  1708. if (!empty($scene_name) && !empty($scene_url)) {
  1709. $scene_map[$scene_name] = $scene_url;
  1710. }
  1711. }
  1712. // 获取所有分镜信息
  1713. $segments = DB::table('mp_episode_segments')
  1714. ->where('anime_id', $anime_id)
  1715. ->where('episode_id', $episode_id)
  1716. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1717. ->orderBy('segment_number')
  1718. ->get()
  1719. ->toArray();
  1720. if (empty($segments)) {
  1721. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1722. }
  1723. // 保存图片比例
  1724. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1725. $updated_segments = [];
  1726. $failed_segments = [];
  1727. // 批量为每个分镜生成图片任务
  1728. foreach ($segments as $segment) {
  1729. $segment_id = $segment->segment_id;
  1730. $segment_content = $segment->segment_content;
  1731. if (empty($segment_content)) {
  1732. $failed_segments[] = [
  1733. 'segment_id' => $segment_id,
  1734. 'error' => '分镜内容为空'
  1735. ];
  1736. continue;
  1737. }
  1738. try {
  1739. $dubTaskId = 0;
  1740. // 解析分镜内容,提取画面描述作为主要提示词
  1741. $prompt = $segment_content;
  1742. $ref_img_urls = [];
  1743. // 分镜场景
  1744. $scene = getProp($segment, 'scene');
  1745. $matched_scene = '';
  1746. if (isset($scene_map[$scene])) {
  1747. $img_index = count($ref_img_urls) + 1;
  1748. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1749. $ref_img_urls[] = $scene_map[$scene];
  1750. $matched_scene = $scene;
  1751. }
  1752. // 分镜角色
  1753. $characters = getProp($segment, 'characters');
  1754. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1755. $roles = explode(',', $characters);
  1756. // 从分镜内容中提取涉及的角色
  1757. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1758. // 获取匹配角色的参考图
  1759. foreach ($segment_characters as $character) {
  1760. if (isset($role_map[$character])) {
  1761. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1762. $img_index = count($ref_img_urls) + 1;
  1763. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1764. $ref_img_urls[] = $role_map[$character];
  1765. }
  1766. }
  1767. // 如果没有找到匹配的角色参考图,不使用参考图
  1768. if (empty($ref_img_urls)) {
  1769. $ref_img_urls = [];
  1770. }
  1771. // 准备生成任务参数
  1772. $params = [
  1773. 'model' => $model,
  1774. 'alias_segment_id' => $segment_id,
  1775. 'prompt' => $prompt,
  1776. 'ref_img_urls' => $ref_img_urls,
  1777. 'width' => $width,
  1778. 'height' => $height,
  1779. ];
  1780. // 优化提示词(不要生成字幕)
  1781. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1782. // $task_id = mt_rand(100000, 999999);
  1783. // 调用AI图片生成服务
  1784. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1785. $task_id = $task->id;
  1786. if (!$task_id) {
  1787. $failed_segments[] = [
  1788. 'segment_id' => $segment_id,
  1789. 'error' => '创建生成任务失败'
  1790. ];
  1791. continue;
  1792. }
  1793. $update_data = [
  1794. 'pic_task_id' => $task_id,
  1795. 'pic_task_status' => '生成中',
  1796. 'audio_url' => '',
  1797. 'updated_at' => date('Y-m-d H:i:s')
  1798. ];
  1799. // 如果有对话内容,创建视频配音合成任务
  1800. $dialogue = getProp($segment, 'dialogue');
  1801. if (!empty($dialogue)) {
  1802. $now = date('Y-m-d H:i:s');
  1803. $generate_json = [
  1804. 'text' => $dialogue,
  1805. 'role' => getProp($segment, 'voice_actor'),
  1806. 'voice_type' => getProp($segment, 'voice_type'),
  1807. 'voice_name' => getProp($segment, 'voice_name'),
  1808. 'emotion' => getProp($segment, 'emotion'),
  1809. 'emotion_type' => getProp($segment, 'emotion_type'),
  1810. 'gender' => getProp($segment, 'gender'),
  1811. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1812. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1813. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1814. 'pitch' => getProp($segment, 'pitch', 0),
  1815. ];
  1816. // 插入视频配音合成任务
  1817. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1818. 'alias_segment_id' => $segment_id,
  1819. 'generate_status' => '执行中',
  1820. 'audio_url' => '',
  1821. 'generate_json' => json_encode($generate_json, 256),
  1822. 'created_at' => $now,
  1823. 'updated_at' => $now,
  1824. ]);
  1825. if (!$dubTaskId) {
  1826. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1827. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1828. // Utils::throwError('20003:创建配音任务失败!');
  1829. }
  1830. } else {
  1831. // dialogue为空时,直接写入默认音频信息到分镜表
  1832. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1833. $update_data['audio_duration'] = 2.0;
  1834. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1835. }
  1836. // 更新分镜的任务信息
  1837. $update_result = DB::table('mp_episode_segments')
  1838. ->where('segment_id', $segment_id)
  1839. ->update($update_data);
  1840. // 如果是第一集的首帧图片,则存入待更新数组
  1841. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1842. Redis::sadd('anime_first_frame_urls', $segment_id);
  1843. }
  1844. if ($update_result) {
  1845. $updated_segments[] = [
  1846. 'segment_id' => $segment_id,
  1847. 'task_id' => $task_id,
  1848. 'status' => '生成中',
  1849. 'matched_scenes' => $matched_scene,
  1850. 'matched_roles' => $segment_characters,
  1851. 'ref_urls_count' => count($ref_img_urls)
  1852. ];
  1853. } else {
  1854. $failed_segments[] = [
  1855. 'segment_id' => $segment_id,
  1856. 'error' => '更新分镜任务状态失败'
  1857. ];
  1858. }
  1859. if ($dubTaskId) {
  1860. sleep(1);
  1861. // 请求远程服务器执行生成
  1862. $client = new Client(['timeout' => 300, 'verify' => false]);
  1863. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1864. $response = $result->getBody()->getContents();
  1865. $response_arr = json_decode($response, true);
  1866. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1867. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1868. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1869. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1870. }
  1871. }
  1872. } catch (\Exception $e) {
  1873. $failed_segments[] = [
  1874. 'segment_id' => $segment_id,
  1875. 'error' => $e->getMessage()
  1876. ];
  1877. }
  1878. }
  1879. // 更新剧集生成状态
  1880. if (!empty($updated_segments)) {
  1881. DB::table('mp_anime_episodes')
  1882. ->where('id', $episode_id)
  1883. ->update([
  1884. 'is_generated' => 1,
  1885. 'updated_at' => date('Y-m-d H:i:s')
  1886. ]);
  1887. }
  1888. return [
  1889. 'success_count' => count($updated_segments),
  1890. 'failed_count' => count($failed_segments),
  1891. 'success_segments' => $updated_segments,
  1892. 'failed_segments' => $failed_segments,
  1893. 'total_segments' => count($segments)
  1894. ];
  1895. }
  1896. public function reGenerateSegment($data) {
  1897. $segment_id = getProp($data, 'segment_id');
  1898. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1899. $anime_id = getProp($segment, 'anime_id');
  1900. $episode_id = getProp($segment, 'episode_id');
  1901. $episode_number = getProp($segment, 'episode_number');
  1902. $segment_content = getProp($data, 'segment_content');
  1903. $ratio = getProp($data, 'ratio');
  1904. if (!$ratio) {
  1905. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1906. if (!$ratio) $ratio = '9:16';
  1907. }
  1908. $dimensions = $this->getRatioDimensions($ratio);
  1909. $width = $dimensions['width'];
  1910. $height = $dimensions['height'];
  1911. if (!$anime_id || !$episode_id) {
  1912. Utils::throwError('1002:请选择分镜');
  1913. }
  1914. // 使用文生文模型重新解析segment_content
  1915. if (!empty($segment_content)) {
  1916. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1917. }
  1918. // 获取动漫的角色信息(包含参考图)
  1919. $anime = DB::table('mp_animes')
  1920. ->where('id', $anime_id)
  1921. ->select('roles', 'scenes')
  1922. ->first();
  1923. if (!$anime || !$anime->roles) {
  1924. Utils::throwError('20003:未找到角色信息');
  1925. }
  1926. $roles = json_decode($anime->roles, true);
  1927. if (!$roles) {
  1928. Utils::throwError('20003:角色信息格式错误');
  1929. }
  1930. // 构建角色名称到参考图的映射
  1931. $role_map = [];
  1932. foreach ($roles as $role) {
  1933. $role_name = getProp($role, 'role');
  1934. $role_url = getProp($role, 'url');
  1935. if (!empty($role_name) && !empty($role_url)) {
  1936. $role_map[$role_name] = $role_url;
  1937. }
  1938. }
  1939. $scenes = json_decode($anime->scenes, true);
  1940. if (!$scenes) {
  1941. Utils::throwError('20003:角色信息格式错误');
  1942. }
  1943. // 构建角色名称到参考图的映射
  1944. $scene_map = [];
  1945. foreach ($scenes as $scene) {
  1946. $scene_name = getProp($scene, 'scene');
  1947. $scene_url = getProp($scene, 'url');
  1948. if (!empty($scene_name) && !empty($scene_url)) {
  1949. $scene_map[$scene_name] = $scene_url;
  1950. }
  1951. }
  1952. $segment_id = $segment->segment_id;
  1953. $original_segment_content = $segment->segment_content;
  1954. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1955. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1956. if (empty($final_segment_content)) {
  1957. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1958. }
  1959. try {
  1960. $dubTaskId = 0;
  1961. // 分镜剧本数组
  1962. $update_data = [
  1963. 'segment_content' => $final_segment_content,
  1964. 'pic_task_status' => '生成中',
  1965. 'updated_at' => date('Y-m-d H:i:s')
  1966. ];
  1967. // 解析分镜内容,提取画面描述作为主要提示词
  1968. $prompt = $final_segment_content;
  1969. $ref_img_urls = [];
  1970. // 分镜场景
  1971. $scene = getProp($data, 'scene');
  1972. if ($scene) {
  1973. $matched_scene = '';
  1974. if (isset($scene_map[$scene])) {
  1975. $img_index = count($ref_img_urls) + 1;
  1976. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1977. $ref_img_urls[] = $scene_map[$scene];
  1978. $matched_scene = $scene;
  1979. }
  1980. $update_data['scene'] = $scene;
  1981. }
  1982. // 分镜角色
  1983. $characters = getProp($data, 'characters');
  1984. if ($characters) {
  1985. $update_data['characters'] = $characters;
  1986. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1987. $characters = explode(',', $characters);
  1988. // 从分镜内容中提取涉及的角色
  1989. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1990. // 获取匹配角色的参考图
  1991. foreach ($segment_characters as $character) {
  1992. if (isset($role_map[$character])) {
  1993. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1994. $img_index = count($ref_img_urls) + 1;
  1995. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1996. $ref_img_urls[] = $role_map[$character];
  1997. }
  1998. }
  1999. }
  2000. // 如果没有找到匹配的角色参考图,不使用参考图
  2001. if (empty($ref_img_urls)) {
  2002. $ref_img_urls = [];
  2003. }
  2004. // 准备生成任务参数
  2005. $params = [
  2006. 'alias_segment_id' => $segment_id,
  2007. 'prompt' => $prompt,
  2008. 'ref_img_urls' => $ref_img_urls,
  2009. 'width' => $width,
  2010. 'height' => $height,
  2011. ];
  2012. // 优化提示词(不要生成字幕)
  2013. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  2014. // 调用AI图片生成服务
  2015. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2016. $task_id = $task->id;
  2017. if (!$task_id) {
  2018. Utils::throwError('20003:创建生成任务失败!');
  2019. }
  2020. $update_data['pic_task_id'] = $task_id;
  2021. // 更新分镜剧本信息
  2022. $this->handleSegmentContent($update_data);
  2023. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2024. if ($segment_content) {
  2025. $dialogue = getProp($update_data, 'dialogue');
  2026. if (!empty($dialogue)) {
  2027. $now = date('Y-m-d H:i:s');
  2028. $generate_json = [
  2029. 'text' => $dialogue,
  2030. 'role' => getProp($update_data, 'voice_actor'),
  2031. 'voice_type' => getProp($update_data, 'voice_type'),
  2032. 'voice_name' => getProp($update_data, 'voice_name'),
  2033. 'emotion' => getProp($update_data, 'emotion'),
  2034. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2035. 'gender' => getProp($update_data, 'gender'),
  2036. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2037. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2038. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2039. 'pitch' => getProp($update_data, 'pitch', 0),
  2040. ];
  2041. // 插入视频配音合成任务
  2042. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2043. 'alias_segment_id' => $segment_id,
  2044. 'generate_status' => '执行中',
  2045. 'audio_url' => '',
  2046. 'generate_json' => json_encode($generate_json, 256),
  2047. 'created_at' => date('Y-m-d H:i:s'),
  2048. 'updated_at' => date('Y-m-d H:i:s'),
  2049. ]);
  2050. if (!$dubTaskId) {
  2051. Utils::throwError('20003:创建配音任务失败!');
  2052. }
  2053. $update_data['audio_url'] = '';
  2054. } else {
  2055. // dialogue为空时,直接写入默认音频信息
  2056. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2057. $update_data['audio_duration'] = 2.0;
  2058. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2059. }
  2060. }
  2061. $boolen = DB::table('mp_episode_segments')
  2062. ->where('segment_id', $segment_id)
  2063. ->update($update_data);
  2064. // 如果是第一集的首帧图片,则存入待更新数组
  2065. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2066. Redis::sadd('anime_first_frame_urls', $segment_id);
  2067. }
  2068. if ($dubTaskId) {
  2069. // 请求远程服务器执行生成
  2070. $client = new Client(['timeout' => 300, 'verify' => false]);
  2071. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2072. $response = $result->getBody()->getContents();
  2073. $response_arr = json_decode($response, true);
  2074. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2075. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2076. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2077. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2078. Utils::throwError('20003:火山生成音频失败');
  2079. }
  2080. }
  2081. } catch (\Exception $e) {
  2082. $failed_segments[] = [
  2083. 'segment_id' => $segment_id,
  2084. 'error' => $e->getMessage()
  2085. ];
  2086. }
  2087. // 创建任务之后先暂停10s等待异步任务完成
  2088. sleep(10);
  2089. $img_url = $this->loopGetPicTaskResult($task_id);
  2090. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2091. // 图片生成后新增对话记录
  2092. try {
  2093. $uid = Site::getUid();
  2094. $now = date('Y-m-d H:i:s');
  2095. // 使用AI反推图片提示词
  2096. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2097. // 保存对话记录
  2098. $records = [
  2099. [
  2100. 'uid' => $uid,
  2101. 'anime_id' => $anime_id,
  2102. 'sequence' => $episode_number,
  2103. 'role' => 'user',
  2104. 'content' => '重新生成',
  2105. 'segment_id' => $segment_id,
  2106. 'pic_task_id' => $task_id,
  2107. 'image_url' => '',
  2108. 'created_at' => $now,
  2109. 'updated_at' => $now
  2110. ],
  2111. [
  2112. 'uid' => $uid,
  2113. 'anime_id' => $anime_id,
  2114. 'sequence' => $episode_number,
  2115. 'role' => 'assistant',
  2116. 'content' => $pic_prompt,
  2117. 'segment_id' => $segment_id,
  2118. 'pic_task_id' => $task_id,
  2119. 'image_url' => $img_url,
  2120. 'created_at' => $now,
  2121. 'updated_at' => $now
  2122. ]
  2123. ];
  2124. DB::table('mp_anime_records')->insert($records);
  2125. } catch (\Exception $e) {
  2126. // 记录日志但不影响主流程
  2127. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2128. 'segment_id' => $segment_id,
  2129. 'img_url' => $img_url
  2130. ]);
  2131. }
  2132. return $img_url;
  2133. }
  2134. public function addSegment($data) {
  2135. $prev_segment_id = getProp($data, 'prev_segment_id');
  2136. $img_url = getProp($data, 'img_url');
  2137. $video_url = getProp($data, 'video_url');
  2138. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2139. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2140. $anime_id = getProp($segment, 'anime_id');
  2141. $episode_id = getProp($segment, 'episode_id');
  2142. $episode_number = getProp($segment, 'episode_number');
  2143. $segment_number = getProp($segment, 'segment_number');
  2144. $new_segment_number = $segment_number + 1;
  2145. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2146. // 分镜剧本数组
  2147. $insert_data = [
  2148. 'anime_id' => $anime_id,
  2149. 'episode_id' => $episode_id,
  2150. 'episode_number' => $episode_number,
  2151. 'act_number' => getProp($segment, 'act_number'),
  2152. 'act_title' => getProp($segment, 'act_title'),
  2153. 'segment_id' => $segment_id,
  2154. 'segment_number' => $new_segment_number,
  2155. 'segment_content' => '',
  2156. 'img_url' => '',
  2157. 'video_url' => '',
  2158. 'created_at' => date('Y-m-d H:i:s'),
  2159. 'updated_at' => date('Y-m-d H:i:s')
  2160. ];
  2161. if ($img_url) $insert_data['img_url'] = $img_url;
  2162. if ($video_url) {
  2163. $insert_data['origin_video_url'] = $video_url;
  2164. $insert_data['current_type'] = 2;
  2165. $compressed_video_url = compressVideo($video_url);
  2166. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2167. }
  2168. try {
  2169. DB::beginTransaction();
  2170. // 先更新序号
  2171. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2172. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2173. if (!$id) {
  2174. Utils::throwError('20003:新增分镜失败!');
  2175. }
  2176. }catch (\Exception $e) {
  2177. DB::rollBack();
  2178. Utils::throwError('20003:'.$e->getMessage());
  2179. }
  2180. DB::commit();
  2181. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2182. $segment = $segment ? (array)$segment : [];
  2183. return $segment;
  2184. // 以下代码暂弃用
  2185. $anime_id = getProp($segment, 'anime_id');
  2186. $episode_id = getProp($segment, 'episode_id');
  2187. $episode_number = getProp($segment, 'episode_number');
  2188. $segment_number = getProp($segment, 'segment_number');
  2189. $segment_content = getProp($data, 'segment_content');
  2190. $img_url = getProp($data, 'img_url');
  2191. $video_url = getProp($data, 'video_url');
  2192. $ratio = getProp($data, 'ratio');
  2193. $dimensions = $this->getRatioDimensions($ratio);
  2194. $width = $dimensions['width'];
  2195. $height = $dimensions['height'];
  2196. if (!$anime_id || !$episode_id) {
  2197. Utils::throwError('1002:请选择分镜');
  2198. }
  2199. // 使用文生文模型重新解析segment_content
  2200. if (!empty($segment_content)) {
  2201. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2202. }
  2203. // 获取动漫的角色信息(包含参考图)
  2204. $anime = DB::table('mp_animes')
  2205. ->where('id', $anime_id)
  2206. ->select('roles', 'scenes')
  2207. ->first();
  2208. if (!$anime || !$anime->roles) {
  2209. Utils::throwError('20003:未找到角色信息');
  2210. }
  2211. $roles = json_decode($anime->roles, true);
  2212. if (!$roles) {
  2213. Utils::throwError('20003:角色信息格式错误');
  2214. }
  2215. // 构建角色名称到参考图的映射
  2216. $role_map = [];
  2217. foreach ($roles as $role) {
  2218. $role_name = getProp($role, 'role');
  2219. $role_url = getProp($role, 'url');
  2220. if (!empty($role_name) && !empty($role_url)) {
  2221. $role_map[$role_name] = $role_url;
  2222. }
  2223. }
  2224. $scenes = json_decode($anime->scenes, true);
  2225. if (!$scenes) {
  2226. Utils::throwError('20003:角色信息格式错误');
  2227. }
  2228. // 构建角色名称到参考图的映射
  2229. $scene_map = [];
  2230. foreach ($scenes as $scene) {
  2231. $scene_name = getProp($scene, 'scene');
  2232. $scene_url = getProp($scene, 'url');
  2233. if (!empty($scene_name) && !empty($scene_url)) {
  2234. $scene_map[$scene_name] = $scene_url;
  2235. }
  2236. }
  2237. $segment_id = $segment->segment_id;
  2238. $original_segment_content = $segment->segment_content;
  2239. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2240. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2241. if (empty($final_segment_content)) {
  2242. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2243. }
  2244. try {
  2245. $dubTaskId = 0;
  2246. DB::beginTransaction();
  2247. $new_segment_number = $segment_number + 1;
  2248. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2249. // 分镜剧本数组
  2250. $insert_data = [
  2251. 'anime_id' => $anime_id,
  2252. 'episode_id' => $episode_id,
  2253. 'episode_number' => $episode_number,
  2254. 'act_number' => getProp($segment, 'act_number'),
  2255. 'act_title' => getProp($segment, 'act_title'),
  2256. 'segment_id' => $segment_id,
  2257. 'segment_number' => $new_segment_number,
  2258. 'segment_content' => $final_segment_content,
  2259. 'img_url' => $img_url,
  2260. 'video_url' => $video_url,
  2261. 'created_at' => date('Y-m-d H:i:s'),
  2262. 'updated_at' => date('Y-m-d H:i:s')
  2263. ];
  2264. // 更新分镜剧本信息
  2265. $this->handleSegmentContent($insert_data);
  2266. // 如果有对话内容,创建视频配音合成任务
  2267. $dialogue = getProp($insert_data, 'dialogue');
  2268. if (!empty($dialogue)) {
  2269. $now = date('Y-m-d H:i:s');
  2270. $generate_json = [
  2271. 'text' => $dialogue,
  2272. 'role' => getProp($insert_data, 'voice_actor'),
  2273. 'voice_type' => getProp($insert_data, 'voice_type'),
  2274. 'voice_name' => getProp($insert_data, 'voice_name'),
  2275. 'emotion' => getProp($insert_data, 'emotion'),
  2276. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2277. 'gender' => getProp($insert_data, 'gender'),
  2278. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2279. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2280. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2281. 'pitch' => getProp($insert_data, 'pitch', 0),
  2282. ];
  2283. // 插入视频配音合成任务
  2284. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2285. 'alias_segment_id' => $segment_id,
  2286. 'generate_status' => '执行中',
  2287. 'audio_url' => '',
  2288. 'generate_json' => json_encode($generate_json, 256),
  2289. 'created_at' => $now,
  2290. 'updated_at' => $now,
  2291. ]);
  2292. if (!$dubTaskId) {
  2293. Utils::throwError('20003:创建配音任务失败!');
  2294. }
  2295. $insert_data['audio_url'] = '';
  2296. } else {
  2297. // dialogue为空时,直接写入默认音频信息
  2298. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2299. $insert_data['audio_duration'] = 2.0;
  2300. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2301. }
  2302. // 如果没有上传图片则使用当前描述进行生成
  2303. if (!$img_url) {
  2304. // 解析分镜内容,提取画面描述作为主要提示词
  2305. $prompt = $final_segment_content;
  2306. $ref_img_urls = [];
  2307. // 分镜场景
  2308. $scene = getProp($insert_data, 'scene');
  2309. if ($scene) {
  2310. $matched_scene = '';
  2311. if (isset($scene_map[$scene])) {
  2312. $img_index = count($ref_img_urls) + 1;
  2313. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2314. $ref_img_urls[] = $scene_map[$scene];
  2315. $matched_scene = $scene;
  2316. }
  2317. $update_data['scene'] = $scene;
  2318. }
  2319. // 分镜角色
  2320. $characters = getProp($insert_data, 'characters');
  2321. if ($characters) {
  2322. $update_data['characters'] = $characters;
  2323. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2324. $characters = explode(',', $characters);
  2325. // 从分镜内容中提取涉及的角色
  2326. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2327. // 获取匹配角色的参考图
  2328. foreach ($segment_characters as $character) {
  2329. if (isset($role_map[$character])) {
  2330. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2331. $img_index = count($ref_img_urls) + 1;
  2332. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2333. $ref_img_urls[] = $role_map[$character];
  2334. }
  2335. }
  2336. }
  2337. // 如果没有找到匹配的角色参考图,不使用参考图
  2338. if (empty($ref_img_urls)) {
  2339. $ref_img_urls = [];
  2340. }
  2341. // 准备生成任务参数
  2342. $params = [
  2343. 'alias_segment_id' => $segment_id,
  2344. 'prompt' => $prompt,
  2345. 'ref_img_urls' => $ref_img_urls,
  2346. 'width' => $width,
  2347. 'height' => $height,
  2348. ];
  2349. // 调用AI图片生成服务
  2350. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2351. $task_id = $task->id;
  2352. // $task_id = 'whatever';
  2353. if (!$task_id) {
  2354. Utils::throwError('20003:创建生成任务失败!');
  2355. }
  2356. $insert_data['pic_task_status'] = '生成中';
  2357. $insert_data['pic_task_id'] = $task_id;
  2358. }
  2359. // 先更新序号
  2360. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2361. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2362. if (!$boolen) {
  2363. Utils::throwError('20003:新增分镜失败!');
  2364. }
  2365. // 如果是第一集的首帧图片,则存入待更新数组
  2366. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2367. Redis::sadd('anime_first_frame_urls', $segment_id);
  2368. }
  2369. if ($dubTaskId) {
  2370. // 请求远程服务器执行生成
  2371. $client = new Client(['timeout' => 300, 'verify' => false]);
  2372. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2373. $response = $result->getBody()->getContents();
  2374. $response_arr = json_decode($response, true);
  2375. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2376. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2377. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2378. Utils::throwError('20003:火山生成音频失败');
  2379. }
  2380. }
  2381. } catch (\Exception $e) {
  2382. DB::rollBack();
  2383. Utils::throwError('20003:'.$e->getMessage());
  2384. }
  2385. DB::commit();
  2386. // 创建任务之后先暂停10s等待异步任务完成
  2387. sleep(10);
  2388. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2389. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2390. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2391. $segment = $segment ? (array)$segment : [];
  2392. return $segment;
  2393. }
  2394. public function copySegment($data) {
  2395. $segment_id = getProp($data, 'segment_id');
  2396. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2397. if (!$segment) Utils::throwError('20003:请选择分镜');
  2398. $anime_id = getProp($segment, 'anime_id');
  2399. $episode_id = getProp($segment, 'episode_id');
  2400. $episode_number = getProp($segment, 'episode_number');
  2401. $segment_number = getProp($segment, 'segment_number');
  2402. $new_segment_id = 0;
  2403. try {
  2404. DB::beginTransaction();
  2405. $segment = (array)$segment;
  2406. unset($segment['id']);
  2407. $segment['segment_number'] += 1;
  2408. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2409. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2410. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2411. // 更新其他分镜序号
  2412. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2413. // 复制分镜
  2414. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2415. if (!$id) {
  2416. Utils::throwError('20003:复制分镜失败');
  2417. }
  2418. }catch (\Exception $e) {
  2419. DB::rollBack();
  2420. Utils::throwError('20003:'.$e->getMessage());
  2421. }
  2422. DB::commit();
  2423. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2424. $segment = $segment ? (array)$segment : [];
  2425. return $segment;
  2426. }
  2427. public function moveSegment($data) {
  2428. $segment_id = getProp($data, 'segment_id');
  2429. $target_segment_id = getProp($data, 'target_segment_id');
  2430. // 获取源分镜信息
  2431. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2432. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2433. // 获取目标分镜信息
  2434. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2435. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2436. $anime_id = getProp($source_segment, 'anime_id');
  2437. $episode_id = getProp($source_segment, 'episode_id');
  2438. $episode_number = getProp($source_segment, 'episode_number');
  2439. $source_segment_number = getProp($source_segment, 'segment_number');
  2440. $target_segment_number = getProp($target_segment, 'segment_number');
  2441. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2442. $target_anime_id = getProp($target_segment, 'anime_id');
  2443. $target_episode_number = getProp($target_segment, 'episode_number');
  2444. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2445. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2446. }
  2447. // 如果源分镜和目标分镜相同,无需移动
  2448. if ($source_segment_number == $target_segment_number) {
  2449. return true;
  2450. }
  2451. try {
  2452. DB::beginTransaction();
  2453. if ($source_segment_number < $target_segment_number) {
  2454. // 向后移动:源分镜移动到目标分镜之后
  2455. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2456. DB::table('mp_episode_segments')
  2457. ->where('anime_id', $anime_id)
  2458. ->where('episode_id', $episode_id)
  2459. ->where('segment_number', '>', $source_segment_number)
  2460. ->where('segment_number', '<=', $target_segment_number)
  2461. ->decrement('segment_number');
  2462. // 2. 将源分镜移动到目标分镜之后
  2463. $new_segment_number = $target_segment_number;
  2464. } else {
  2465. // 向前移动:源分镜移动到目标分镜之后
  2466. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2467. DB::table('mp_episode_segments')
  2468. ->where('anime_id', $anime_id)
  2469. ->where('episode_id', $episode_id)
  2470. ->where('segment_number', '>', $target_segment_number)
  2471. ->where('segment_number', '<', $source_segment_number)
  2472. ->increment('segment_number');
  2473. // 2. 将源分镜移动到目标分镜之后
  2474. $new_segment_number = $target_segment_number + 1;
  2475. }
  2476. // 3. 更新源分镜的序号
  2477. $update_result = DB::table('mp_episode_segments')
  2478. ->where('segment_id', $segment_id)
  2479. ->update([
  2480. 'segment_number' => $new_segment_number,
  2481. 'updated_at' => date('Y-m-d H:i:s')
  2482. ]);
  2483. if (!$update_result) {
  2484. Utils::throwError('20003:更新分镜序号失败');
  2485. }
  2486. DB::commit();
  2487. return true;
  2488. } catch (\Exception $e) {
  2489. DB::rollBack();
  2490. Utils::throwError('20003:' . $e->getMessage());
  2491. }
  2492. }
  2493. public function delSegment($data) {
  2494. $segment_id = getProp($data, 'segment_id');
  2495. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2496. if (!$segment) Utils::throwError('20003:请选择分镜');
  2497. $anime_id = getProp($segment, 'anime_id');
  2498. $episode_id = getProp($segment, 'episode_id');
  2499. $episode_number = getProp($segment, 'episode_number');
  2500. $segment_number = getProp($segment, 'segment_number');
  2501. try {
  2502. DB::beginTransaction();
  2503. // 删除分镜
  2504. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2505. if (!$boolen) {
  2506. Utils::throwError('20003:删除分镜失败');
  2507. }
  2508. // 更新其他分镜序号
  2509. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2510. }catch (\Exception $e) {
  2511. DB::rollBack();
  2512. Utils::throwError('20003:'.$e->getMessage());
  2513. }
  2514. DB::commit();
  2515. return true;
  2516. }
  2517. public function applySegment($data) {
  2518. $segment_id = getProp($data, 'segment_id');
  2519. $url = getProp($data, 'url');
  2520. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2521. if (!$url) Utils::throwError('20003:URL不能为空');
  2522. // 获取URL的文件扩展名
  2523. $urlPath = parse_url($url, PHP_URL_PATH);
  2524. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2525. // 定义图片和视频的扩展名
  2526. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2527. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2528. // 判断是图片还是视频
  2529. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2530. if (in_array($extension, $imageExtensions)) {
  2531. // 图片类型
  2532. $updateData['img_url'] = $url;
  2533. $updateData['current_type'] = 1;
  2534. } elseif (in_array($extension, $videoExtensions)) {
  2535. // 视频类型
  2536. $updateData['video_url'] = $url;
  2537. $updateData['current_type'] = 2;
  2538. } else {
  2539. Utils::throwError('20003:不支持的文件类型');
  2540. }
  2541. // 更新分镜表
  2542. $result = DB::table('mp_episode_segments')
  2543. ->where('segment_id', $segment_id)
  2544. ->update($updateData);
  2545. if (!$result) {
  2546. Utils::throwError('20003:更新分镜失败');
  2547. }
  2548. return true;
  2549. }
  2550. public function segmentHistory($data) {
  2551. $segment_id = getProp($data, 'segment_id');
  2552. // 获取历史图片
  2553. $pics = [];
  2554. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2555. foreach($pic_history as $task) {
  2556. $result_url = getProp($task, 'result_url');
  2557. if (is_json($result_url)) {
  2558. $pics = array_merge($pics, json_decode($result_url, true));
  2559. }else {
  2560. $pics[] = $result_url;
  2561. }
  2562. }
  2563. // 获取历史视频
  2564. $videos = [];
  2565. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2566. foreach($video_history as $task) {
  2567. $result_url = getProp($task, 'result_url');
  2568. if (is_json($result_url)) {
  2569. $videos = array_merge($videos, json_decode($result_url, true));
  2570. }else {
  2571. $videos[] = $result_url;
  2572. }
  2573. }
  2574. return compact('pics', 'videos');
  2575. }
  2576. public function addAct($data) {
  2577. $prev_act_id = getProp($data, 'prev_act_id');
  2578. $act_title = getProp($data, 'act_title', '');
  2579. $act_content = getProp($data, 'act_content', '');
  2580. $act_duration = getProp($data, 'act_duration', 5);
  2581. $video_url = getProp($data, 'video_url');
  2582. // 根据prev_act_id获取记录
  2583. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2584. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2585. $anime_id = getProp($prev_segment, 'anime_id');
  2586. $episode_id = getProp($prev_segment, 'episode_id');
  2587. $episode_number = getProp($prev_segment, 'episode_number');
  2588. $prev_act_number = getProp($prev_segment, 'act_number');
  2589. // 获取新的act_number
  2590. $new_act_number = $prev_act_number + 1;
  2591. try {
  2592. DB::beginTransaction();
  2593. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2594. DB::table('mp_episode_segments')
  2595. ->where('anime_id', $anime_id)
  2596. ->where('episode_id', $episode_id)
  2597. ->where('act_number', '>', $prev_act_number)
  2598. ->increment('act_number');
  2599. // 插入新片段记录
  2600. $insert_data = [
  2601. 'anime_id' => $anime_id,
  2602. 'episode_id' => $episode_id,
  2603. 'episode_number' => $episode_number,
  2604. 'act_number' => $new_act_number,
  2605. 'created_at' => date('Y-m-d H:i:s'),
  2606. 'updated_at' => date('Y-m-d H:i:s')
  2607. ];
  2608. if ($act_title) {
  2609. $insert_data['act_title'] = $act_title;
  2610. }
  2611. if ($act_content) {
  2612. $insert_data['act_content'] = $act_content;
  2613. }
  2614. if ($act_duration) {
  2615. $insert_data['act_duration'] = $act_duration;
  2616. }
  2617. if ($video_url) {
  2618. $insert_data['origin_video_url'] = $video_url;
  2619. $insert_data['current_type'] = 2;
  2620. $compressed_video_url = compressVideo($video_url);
  2621. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2622. }
  2623. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2624. if (!$id) {
  2625. Utils::throwError('20003:新增片段失败!');
  2626. }
  2627. DB::commit();
  2628. }catch (\Exception $e) {
  2629. DB::rollBack();
  2630. Utils::throwError('20003:'.$e->getMessage());
  2631. }
  2632. $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();
  2633. $segment = $segment ? (array)$segment : [];
  2634. return $segment;
  2635. }
  2636. public function editAct($data) {
  2637. $act_id = getProp($data, 'act_id');
  2638. $act_content = getProp($data, 'act_content');
  2639. $act_duration = getProp($data, 'act_duration');
  2640. $act_title = getProp($data, 'act_title');
  2641. $image_url = getProp($data, 'image_url');
  2642. $video_url = getProp($data, 'video_url');
  2643. // 参数验证
  2644. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2645. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2646. $segment = DB::table('mp_episode_segments')
  2647. ->where('id', $act_id)
  2648. ->first();
  2649. if (!$segment) Utils::throwError('20003:该片段不存在');
  2650. try {
  2651. DB::beginTransaction();
  2652. // 准备更新数据
  2653. $update_data = [
  2654. 'updated_at' => date('Y-m-d H:i:s')
  2655. ];
  2656. // 更新act相关字段
  2657. if (!empty($act_content)) {
  2658. $update_data['act_show_content'] = $act_content;
  2659. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2660. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2661. $shot_counter = 0;
  2662. $update_data['act_show_content'] = preg_replace_callback(
  2663. '/【(?:镜头|分镜)(\d+)】/u',
  2664. function($matches) use (&$shot_counter) {
  2665. $shot_counter++;
  2666. return '【镜头' . $shot_counter . '】';
  2667. },
  2668. $update_data['act_show_content']
  2669. );
  2670. }
  2671. if (!empty($act_duration)) {
  2672. $update_data['act_duration'] = $act_duration;
  2673. }
  2674. if (!empty($act_title)) {
  2675. $update_data['act_title'] = $act_title;
  2676. }
  2677. // 处理图片上传
  2678. if ($image_url) {
  2679. $update_data['img_url'] = $image_url;
  2680. $update_data['current_type'] = 1;
  2681. // 同时写入一个图片生成任务记录
  2682. if ($act_id) {
  2683. $pic_task = [
  2684. 'alias_act_id' => $act_id,
  2685. 'ref_img_url' => json_encode([]),
  2686. 'status' => 'success',
  2687. 'result_url' => json_encode([$image_url], 256),
  2688. 'model' => '',
  2689. 'created_at' => date('Y-m-d H:i:s'),
  2690. 'updated_at' => date('Y-m-d H:i:s'),
  2691. ];
  2692. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2693. }
  2694. }
  2695. // 处理视频上传
  2696. if ($video_url) {
  2697. $update_data['origin_video_url'] = $video_url;
  2698. $compressed_video_url = compressVideo($video_url);
  2699. $update_data['current_type'] = 2;
  2700. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2701. // 同时写入一个视频生成任务记录
  2702. if ($act_id) {
  2703. $video_task = [
  2704. 'alias_act_id' => $act_id,
  2705. 'status' => 'success',
  2706. 'result_url' => $update_data['origin_video_url'],
  2707. 'compressed_url' => $update_data['video_url'],
  2708. 'created_at' => date('Y-m-d H:i:s'),
  2709. 'updated_at' => date('Y-m-d H:i:s'),
  2710. ];
  2711. DB::table('mp_generate_video_tasks')->insert($video_task);
  2712. }
  2713. }
  2714. // 更新片段信息
  2715. $result = DB::table('mp_episode_segments')
  2716. ->where('id', $act_id)
  2717. ->update($update_data);
  2718. if ($result === false) {
  2719. Utils::throwError('20003:更新片段失败');
  2720. }
  2721. DB::commit();
  2722. // 返回新复制的记录
  2723. $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,act_show_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $act_id)->first();
  2724. $new_segment = (array)$new_segment;
  2725. return $new_segment;
  2726. } catch (\Exception $e) {
  2727. DB::rollBack();
  2728. dLog('anime')->error('更新片段失败', [
  2729. 'act_id' => $act_id,
  2730. 'error' => $e->getMessage()
  2731. ]);
  2732. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2733. }
  2734. }
  2735. public function copyAct($data) {
  2736. $act_id = getProp($data, 'act_id');
  2737. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2738. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2739. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2740. $anime_id = getProp($source_segment, 'anime_id');
  2741. $episode_id = getProp($source_segment, 'episode_id');
  2742. $episode_number = getProp($source_segment, 'episode_number');
  2743. $act_number = getProp($source_segment, 'act_number');
  2744. try {
  2745. DB::beginTransaction();
  2746. // 新act的编号
  2747. $new_act_number = $act_number + 1;
  2748. // 更新后续所有act的act_number
  2749. DB::table('mp_episode_segments')
  2750. ->where('anime_id', $anime_id)
  2751. ->where('episode_id', $episode_id)
  2752. ->where('act_number', '>', $act_number)
  2753. ->increment('act_number');
  2754. // 复制该片段记录
  2755. $segment_data = (array)$source_segment;
  2756. unset($segment_data['id']);
  2757. $segment_data['video_url'] = '';
  2758. $segment_data['video_task_id'] = '';
  2759. $segment_data['video_task_status'] = '';
  2760. $segment_data['act_number'] = $new_act_number;
  2761. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2762. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2763. if (!$id) {
  2764. Utils::throwError('20003:复制片段失败');
  2765. }
  2766. DB::commit();
  2767. }catch (\Exception $e) {
  2768. DB::rollBack();
  2769. Utils::throwError('20003:'.$e->getMessage());
  2770. }
  2771. // 返回新复制的记录
  2772. $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();
  2773. $new_segment = $new_segment ? (array)$new_segment : [];
  2774. $new_segment['act_id'] = $id;
  2775. return $new_segment;
  2776. }
  2777. public function moveAct($data) {
  2778. $act_id = getProp($data, 'act_id');
  2779. $target_act_id = getProp($data, 'target_act_id');
  2780. // 获取源片段信息
  2781. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2782. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2783. // 获取目标片段信息
  2784. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2785. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2786. $anime_id = getProp($source_segment, 'anime_id');
  2787. $episode_id = getProp($source_segment, 'episode_id');
  2788. $source_act_number = getProp($source_segment, 'act_number');
  2789. $target_act_number = getProp($target_segment, 'act_number');
  2790. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2791. $target_anime_id = getProp($target_segment, 'anime_id');
  2792. $target_episode_id = getProp($target_segment, 'episode_id');
  2793. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2794. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2795. }
  2796. // 如果源片段和目标片段相同,无需移动
  2797. if ($source_act_number == $target_act_number) {
  2798. return true;
  2799. }
  2800. try {
  2801. DB::beginTransaction();
  2802. if ($source_act_number < $target_act_number) {
  2803. // 向后移动:源片段移动到目标片段之后
  2804. // 1. 将源片段和目标片段之间的所有片段编号减1
  2805. DB::table('mp_episode_segments')
  2806. ->where('anime_id', $anime_id)
  2807. ->where('episode_id', $episode_id)
  2808. ->where('act_number', '>', $source_act_number)
  2809. ->where('act_number', '<=', $target_act_number)
  2810. ->decrement('act_number');
  2811. // 2. 将源片段移动到目标片段之后
  2812. $new_act_number = $target_act_number;
  2813. } else {
  2814. // 向前移动:源片段移动到目标片段之后
  2815. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2816. DB::table('mp_episode_segments')
  2817. ->where('anime_id', $anime_id)
  2818. ->where('episode_id', $episode_id)
  2819. ->where('act_number', '>', $target_act_number)
  2820. ->where('act_number', '<', $source_act_number)
  2821. ->increment('act_number');
  2822. // 2. 将源片段移动到目标片段之后
  2823. $new_act_number = $target_act_number + 1;
  2824. }
  2825. // 3. 更新源片段的编号
  2826. $update_result = DB::table('mp_episode_segments')
  2827. ->where('id', $act_id)
  2828. ->update([
  2829. 'act_number' => $new_act_number,
  2830. 'updated_at' => date('Y-m-d H:i:s')
  2831. ]);
  2832. if (!$update_result) {
  2833. Utils::throwError('20003:更新片段编号失败');
  2834. }
  2835. DB::commit();
  2836. return true;
  2837. } catch (\Exception $e) {
  2838. DB::rollBack();
  2839. Utils::throwError('20003:' . $e->getMessage());
  2840. }
  2841. }
  2842. public function delAct($data) {
  2843. $act_id = getProp($data, 'act_id');
  2844. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2845. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2846. if (!$segment) Utils::throwError('20003:请选择片段');
  2847. $anime_id = getProp($segment, 'anime_id');
  2848. $episode_id = getProp($segment, 'episode_id');
  2849. $act_number = getProp($segment, 'act_number');
  2850. try {
  2851. DB::beginTransaction();
  2852. // 删除该片段记录
  2853. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2854. if (!$deleted) {
  2855. Utils::throwError('20003:删除片段失败');
  2856. }
  2857. // 更新后续act的编号
  2858. DB::table('mp_episode_segments')
  2859. ->where('anime_id', $anime_id)
  2860. ->where('episode_id', $episode_id)
  2861. ->where('act_number', '>', $act_number)
  2862. ->decrement('act_number');
  2863. DB::commit();
  2864. }catch (\Exception $e) {
  2865. DB::rollBack();
  2866. Utils::throwError('20003:'.$e->getMessage());
  2867. }
  2868. return true;
  2869. }
  2870. public function applyAct($data) {
  2871. $act_id = getProp($data, 'act_id');
  2872. $url = getProp($data, 'url');
  2873. if (!$act_id) Utils::throwError('20003:请选择片段');
  2874. if (!$url) Utils::throwError('20003:URL不能为空');
  2875. // 获取URL的文件扩展名
  2876. $urlPath = parse_url($url, PHP_URL_PATH);
  2877. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2878. // 定义图片和视频的扩展名
  2879. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2880. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2881. // 判断是图片还是视频
  2882. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2883. if (in_array($extension, $imageExtensions)) {
  2884. // 图片类型
  2885. $updateData['img_url'] = $url;
  2886. $updateData['current_type'] = 1;
  2887. } elseif (in_array($extension, $videoExtensions)) {
  2888. // 视频类型
  2889. $updateData['video_url'] = $url;
  2890. $updateData['current_type'] = 2;
  2891. } else {
  2892. Utils::throwError('20003:不支持的文件类型');
  2893. }
  2894. // 更新片段记录(全能模式下每个act只有一条记录)
  2895. $result = DB::table('mp_episode_segments')
  2896. ->where('id', $act_id)
  2897. ->update($updateData);
  2898. if (!$result) {
  2899. Utils::throwError('20003:更新片段失败');
  2900. }
  2901. return true;
  2902. }
  2903. public function actChatHistory($data) {
  2904. $act_id = getProp($data, 'act_id');
  2905. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2906. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'video_task_id', 'pic_task_id', 'reference_images', 'created_at');
  2907. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2908. $value = (array)$value;
  2909. $value['created_at'] = transDate($value['created_at']);
  2910. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2911. else $value['reference_images'] = [];
  2912. return $value;
  2913. })->toArray();
  2914. // 获取历史图片
  2915. $url = [];
  2916. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2917. foreach($pic_history as $task) {
  2918. $result_url = getProp($task, 'result_url');
  2919. if (is_json($result_url)) {
  2920. $url = array_merge($url, json_decode($result_url, true));
  2921. }else {
  2922. $url[] = $result_url;
  2923. }
  2924. }
  2925. // 获取历史视频
  2926. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2927. foreach($video_history as $task) {
  2928. $result_url = getProp($task, 'result_url');
  2929. if (is_json($result_url)) {
  2930. $url = array_merge($url, json_decode($result_url, true));
  2931. }else {
  2932. $url[] = $result_url;
  2933. }
  2934. }
  2935. // 获取资产库
  2936. $products = [];
  2937. // 通过act_id查询片段信息获取episode_id
  2938. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2939. if ($segment) {
  2940. $episode_id = getProp($segment, 'episode_id');
  2941. // 查询剧集信息获取roles、scenes和extra_products
  2942. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2943. if ($episode) {
  2944. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2945. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2946. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2947. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2948. // 先合并roles、scenes和props
  2949. // 处理角色数组
  2950. foreach ($roles as $role) {
  2951. $product = $role;
  2952. // 将role字段重命名为product_name
  2953. if (is_array($product) && !empty($product['role'] ?? null)) {
  2954. $product['product_name'] = $product['role'];
  2955. unset($product['role']);
  2956. $product['product'] = 1; // 标记类型为角色
  2957. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2958. }
  2959. }
  2960. // 处理场景数组
  2961. foreach ($scenes as $scene) {
  2962. $product = $scene;
  2963. // 将scene字段重命名为product_name
  2964. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2965. $product['product_name'] = $product['scene'];
  2966. unset($product['scene']);
  2967. $product['product'] = 2; // 标记类型为场景
  2968. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2969. }
  2970. }
  2971. // 处理道具数组
  2972. foreach ($props as $prop) {
  2973. $product = $prop;
  2974. // 将prop字段重命名为product_name
  2975. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2976. $product['product_name'] = $product['prop'];
  2977. unset($product['prop']);
  2978. $product['product'] = 3; // 标记类型为道具
  2979. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2980. }
  2981. }
  2982. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2983. foreach ($extra_products as $extra_product) {
  2984. $product_name = getProp($extra_product, 'product_name');
  2985. if ($product_name) {
  2986. $products[$product_name] = $extra_product; // 覆盖同名数据
  2987. }
  2988. }
  2989. // 重新索引数组(去除key)
  2990. $products = array_values($products);
  2991. }
  2992. }
  2993. // 获取执行中的任务
  2994. $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) {
  2995. $value = (array)$value;
  2996. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2997. else $value['ref_image_url'] = [];
  2998. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2999. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  3000. if (!empty($value['prompt'])) {
  3001. $prompt = $value['prompt'];
  3002. // 查找第一个【镜头】的位置
  3003. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  3004. // 从【镜头】开始截取
  3005. $prompt = substr($prompt, $matches[0][1]);
  3006. }
  3007. // 去除所有<图片X>格式的标记(X可以是任意数字)
  3008. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  3009. $value['prompt'] = $prompt;
  3010. }
  3011. return $value;
  3012. })->toArray();
  3013. return compact('chat', 'url', 'products', 'tasks');
  3014. }
  3015. public function applyAudioData($data) {
  3016. $segment_id = getProp($data, 'segment_id');
  3017. $global_data = getProp($data, 'global_data');
  3018. $segment_data = getProp($data, 'segment_data');
  3019. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3020. $global_data = is_array($global_data) ? $global_data : [];
  3021. $segment_data = is_array($segment_data) ? $segment_data : [];
  3022. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3023. $dialogue_item = null;
  3024. foreach ($global_data as $key => $item) {
  3025. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3026. $dialogue_item = $item;
  3027. unset($global_data[$key]);
  3028. break;
  3029. }
  3030. }
  3031. if ($dialogue_item) {
  3032. $segment_data[] = $dialogue_item;
  3033. }
  3034. // 特殊参数: audio_url,audio_duration,subtitle_info
  3035. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3036. // 如果不是全部存在,则仍需创建音频任务
  3037. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3038. $special_update_data = [];
  3039. $has_all_special_params = false;
  3040. // 从segment_data中提取特殊参数
  3041. $filtered_segment_data = [];
  3042. foreach ($segment_data as $item) {
  3043. $field_name = trim((string)getProp($item, 'name'));
  3044. if (in_array($field_name, $special_fields)) {
  3045. $special_update_data[$field_name] = getProp($item, 'value');
  3046. } else {
  3047. // 非特殊参数保留,继续后续处理
  3048. $filtered_segment_data[] = $item;
  3049. }
  3050. }
  3051. // 检查是否三个特殊参数都存在
  3052. if (count($special_update_data) === 3 &&
  3053. isset($special_update_data['audio_url']) &&
  3054. isset($special_update_data['audio_duration']) &&
  3055. isset($special_update_data['subtitle_info'])) {
  3056. $has_all_special_params = true;
  3057. // 立即更新到当前分镜
  3058. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3059. DB::table('mp_episode_segments')
  3060. ->where('segment_id', $segment_id)
  3061. ->update($special_update_data);
  3062. }
  3063. // 使用过滤后的segment_data继续处理其他参数
  3064. $segment_data = $filtered_segment_data;
  3065. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3066. $global_update_data = [];
  3067. $segment_update_data = [];
  3068. $global_voice_type = '';
  3069. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3070. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3071. $episode_id = getProp($target_segment, 'episode_id');
  3072. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3073. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3074. if (!$episode) Utils::throwError('20003:分集不存在');
  3075. foreach ($global_data as $item) {
  3076. $field_name = trim((string)getProp($item, 'name'));
  3077. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3078. continue;
  3079. }
  3080. $global_update_data[$field_name] = getProp($item, 'value');
  3081. if ($field_name === 'voice_type') {
  3082. $global_voice_type = trim((string)getProp($item, 'value'));
  3083. }
  3084. }
  3085. foreach ($segment_data as $item) {
  3086. $field_name = trim((string)getProp($item, 'name'));
  3087. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3088. continue;
  3089. }
  3090. $segment_update_data[$field_name] = getProp($item, 'value');
  3091. }
  3092. if ($global_voice_type) {
  3093. $timbre_info = DB::table('mp_timbres')
  3094. ->where('timbre_type', $global_voice_type)
  3095. ->select('audio_url', 'timbre_name')
  3096. ->first();
  3097. if ($timbre_info) {
  3098. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3099. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3100. }
  3101. }
  3102. try {
  3103. DB::beginTransaction();
  3104. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3105. $segment_ids_to_create_task = [];
  3106. $segments_data = [];
  3107. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3108. if (!empty($global_update_data)) {
  3109. // 如果角色不存在,则只更新当前分镜
  3110. if (!$target_voice_actor) {
  3111. // 只处理当前分镜
  3112. $affected_segments = DB::table('mp_episode_segments')
  3113. ->where('segment_id', $segment_id)
  3114. ->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')
  3115. ->get();
  3116. } else {
  3117. // 获取该角色的所有分镜
  3118. $affected_segments = DB::table('mp_episode_segments')
  3119. ->where('episode_id', $episode_id)
  3120. ->where('voice_actor', $target_voice_actor)
  3121. ->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')
  3122. ->get();
  3123. }
  3124. foreach ($affected_segments as $seg) {
  3125. $seg = (array)$seg;
  3126. $sid = getProp($seg, 'segment_id');
  3127. // 检查参数是否发生变化
  3128. $has_changed = false;
  3129. foreach ($global_update_data as $field => $new_value) {
  3130. $old_value = getProp($seg, $field);
  3131. if ($old_value != $new_value) {
  3132. $has_changed = true;
  3133. break;
  3134. }
  3135. }
  3136. if ($has_changed) {
  3137. $segment_ids_to_create_task[] = $sid;
  3138. $segments_data[$sid] = $seg;
  3139. }
  3140. }
  3141. // 只有在有变化的分镜时才更新
  3142. if (!empty($segment_ids_to_create_task)) {
  3143. $global_segment_update_data = $global_update_data;
  3144. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3145. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3146. DB::table('mp_episode_segments')
  3147. ->where('episode_id', $episode_id)
  3148. ->where('voice_actor', $target_voice_actor)
  3149. ->whereIn('segment_id', $segment_ids_to_create_task)
  3150. ->update($global_segment_update_data);
  3151. }
  3152. if ($global_voice_type) {
  3153. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3154. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3155. $roles_updated = false;
  3156. foreach ($episode_roles as &$role) {
  3157. // 通过 role 字段匹配角色名,而不是 voice_name
  3158. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3159. continue;
  3160. }
  3161. $role['voice_type'] = $global_voice_type;
  3162. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3163. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3164. $roles_updated = true;
  3165. }
  3166. unset($role);
  3167. if ($roles_updated) {
  3168. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3169. 'roles' => json_encode($episode_roles, 256),
  3170. 'updated_at' => date('Y-m-d H:i:s'),
  3171. ]);
  3172. }
  3173. }
  3174. }
  3175. // 如果有单个分镜更新,检查是否有变化
  3176. if (!empty($segment_update_data)) {
  3177. // 获取当前分镜数据
  3178. $current_segment = DB::table('mp_episode_segments')
  3179. ->where('segment_id', $segment_id)
  3180. ->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')
  3181. ->first();
  3182. if ($current_segment) {
  3183. $current_segment = (array)$current_segment;
  3184. // 检查参数是否发生变化
  3185. $has_changed = false;
  3186. foreach ($segment_update_data as $field => $new_value) {
  3187. $old_value = getProp($current_segment, $field);
  3188. if ($old_value != $new_value) {
  3189. $has_changed = true;
  3190. break;
  3191. }
  3192. }
  3193. if ($has_changed) {
  3194. // 如果该分镜还未在列表中,添加进去
  3195. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3196. $segment_ids_to_create_task[] = $segment_id;
  3197. $segments_data[$segment_id] = $current_segment;
  3198. }
  3199. // 更新分镜数据并清空音频URL
  3200. $segment_update_data['audio_url'] = '';
  3201. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3202. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3203. }
  3204. }
  3205. }
  3206. // 为所有有变化的分镜创建音频合成任务
  3207. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3208. if (!empty($segment_ids_to_create_task)) {
  3209. foreach ($segment_ids_to_create_task as $sid) {
  3210. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3211. if ($sid === $segment_id && $has_all_special_params) {
  3212. continue;
  3213. }
  3214. // 重新获取更新后的分镜数据
  3215. $updated_segment = DB::table('mp_episode_segments')
  3216. ->where('segment_id', $sid)
  3217. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3218. ->first();
  3219. if (!$updated_segment) continue;
  3220. $updated_segment = (array)$updated_segment;
  3221. // 检查dialogue是否为空
  3222. $dialogue = getProp($updated_segment, 'dialogue');
  3223. if (empty($dialogue)) {
  3224. // dialogue为空时,直接写入默认音频信息
  3225. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3226. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3227. 'audio_duration' => 2.0,
  3228. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3229. 'updated_at' => date('Y-m-d H:i:s')
  3230. ]);
  3231. continue;
  3232. }
  3233. $generate_json = [
  3234. 'text' => $dialogue,
  3235. 'role' => getProp($updated_segment, 'voice_actor'),
  3236. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3237. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3238. 'emotion' => getProp($updated_segment, 'emotion'),
  3239. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3240. 'gender' => getProp($updated_segment, 'gender'),
  3241. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3242. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3243. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3244. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3245. ];
  3246. // 插入视频配音合成任务
  3247. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3248. 'alias_segment_id' => $sid,
  3249. 'generate_status' => '执行中',
  3250. 'audio_url' => '',
  3251. 'generate_json' => json_encode($generate_json, 256),
  3252. 'created_at' => date('Y-m-d H:i:s'),
  3253. 'updated_at' => date('Y-m-d H:i:s'),
  3254. ]);
  3255. if (!$dubTaskId) {
  3256. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3257. continue;
  3258. }
  3259. // 将任务ID添加到Redis列表中
  3260. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3261. // 请求远程服务器执行生成
  3262. try {
  3263. sleep(1);
  3264. $client = new Client(['timeout' => 300, 'verify' => false]);
  3265. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3266. $response = $result->getBody()->getContents();
  3267. $response_arr = json_decode($response, true);
  3268. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3269. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3270. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3271. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3272. }
  3273. } catch (\Exception $e) {
  3274. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3275. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3276. }
  3277. }
  3278. }
  3279. DB::commit();
  3280. } catch (\Exception $e) {
  3281. DB::rollBack();
  3282. Utils::throwError('20003:'.$e->getMessage());
  3283. }
  3284. return true;
  3285. }
  3286. public function episodePicsInfo($data) {
  3287. $anime_id = getProp($data, 'anime_id');
  3288. $episode_id = getProp($data, 'episode_id');
  3289. // 参数验证
  3290. if (!$anime_id && !$episode_id) {
  3291. Utils::throwError('20003:请提供动漫ID或分集ID');
  3292. }
  3293. // 根据参数获取数据源
  3294. if ($episode_id) {
  3295. // 从剧集表获取
  3296. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3297. if (!$source) Utils::throwError('20003:该剧集不存在');
  3298. $table_name = 'mp_anime_episodes';
  3299. $id_field = 'id';
  3300. $id_value = $episode_id;
  3301. // 获取剧集的anime_id用于继承全局数据
  3302. $anime_id = getProp($source, 'anime_id');
  3303. } else {
  3304. // 从动漫表获取
  3305. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3306. if (!$source) Utils::throwError('20003:该动漫不存在');
  3307. $table_name = 'mp_animes';
  3308. $id_field = 'id';
  3309. $id_value = $anime_id;
  3310. }
  3311. $source = (array)$source;
  3312. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3313. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3314. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3315. // 如果是分集数据,需要处理继承和任务创建逻辑
  3316. if ($episode_id) {
  3317. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3318. }
  3319. // 返回生成器函数,用于 SSE 流式输出
  3320. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3321. $startTime = time();
  3322. $maxDuration = 600; // 10分钟超时
  3323. $checkInterval = 3; // 每3秒检查一次
  3324. // Redis 缓存键
  3325. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3326. // 生成当前数据的哈希值用于比较
  3327. $generateHash = function($roles, $scenes, $props) {
  3328. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3329. };
  3330. // 发送初始数据
  3331. $currentHash = $generateHash($roles, $scenes, $props);
  3332. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3333. echo "data: " . json_encode([
  3334. 'type' => 'init',
  3335. 'data' => [
  3336. 'roles' => $roles,
  3337. 'scenes' => $scenes,
  3338. 'props' => $props,
  3339. 'start_time' => $startTime
  3340. ]
  3341. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3342. if (ob_get_level() > 0) {
  3343. ob_flush();
  3344. }
  3345. flush();
  3346. // 持续轮询任务状态
  3347. while (time() - $startTime < $maxDuration) {
  3348. $hasProcessing = false;
  3349. $updated = false;
  3350. // 检查角色任务状态
  3351. foreach ($roles as $index => &$role) {
  3352. $task_id = getProp($role, 'task_id');
  3353. $task_status = getProp($role, 'task_status');
  3354. $existing_url = getProp($role, 'url');
  3355. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3356. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3357. $hasProcessing = ($task_status === 'processing');
  3358. // 查询任务状态
  3359. $task = DB::table('mp_generate_pic_tasks')
  3360. ->where('id', $task_id)
  3361. ->select('id', 'status', 'result_url', 'error_message')
  3362. ->first();
  3363. if ($task) {
  3364. $task = (array)$task;
  3365. $status = getProp($task, 'status');
  3366. // 如果任务完成或失败
  3367. if (in_array($status, ['success', 'failed'])) {
  3368. $role['task_status'] = $status;
  3369. if ($status === 'success') {
  3370. $result_url = getProp($task, 'result_url');
  3371. if ($result_url) {
  3372. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3373. if (is_array($result_urls) && !empty($result_urls[0])) {
  3374. $role['url'] = $result_urls[0];
  3375. }
  3376. }
  3377. }
  3378. $updated = true;
  3379. } else if ($status === 'processing') {
  3380. $hasProcessing = true;
  3381. }
  3382. }
  3383. }
  3384. }
  3385. // 检查场景任务状态
  3386. foreach ($scenes as $index => &$scene) {
  3387. $task_id = getProp($scene, 'task_id');
  3388. $task_status = getProp($scene, 'task_status');
  3389. $existing_url = getProp($scene, 'url');
  3390. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3391. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3392. $hasProcessing = ($task_status === 'processing');
  3393. // 查询任务状态
  3394. $task = DB::table('mp_generate_pic_tasks')
  3395. ->where('id', $task_id)
  3396. ->select('id', 'status', 'result_url', 'error_message')
  3397. ->first();
  3398. if ($task) {
  3399. $task = (array)$task;
  3400. $status = getProp($task, 'status');
  3401. // 如果任务完成或失败
  3402. if (in_array($status, ['success', 'failed'])) {
  3403. $scene['task_status'] = $status;
  3404. if ($status === 'success') {
  3405. $result_url = getProp($task, 'result_url');
  3406. if ($result_url) {
  3407. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3408. if (is_array($result_urls) && !empty($result_urls[0])) {
  3409. $scene['url'] = $result_urls[0];
  3410. }
  3411. }
  3412. }
  3413. $updated = true;
  3414. } else if ($status === 'processing') {
  3415. $hasProcessing = true;
  3416. }
  3417. }
  3418. }
  3419. }
  3420. // 检查道具任务状态
  3421. foreach ($props as $index => &$prop) {
  3422. $task_id = getProp($prop, 'task_id');
  3423. $task_status = getProp($prop, 'task_status');
  3424. $existing_url = getProp($prop, 'url');
  3425. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3426. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3427. $hasProcessing = ($task_status === 'processing');
  3428. // 查询任务状态
  3429. $task = DB::table('mp_generate_pic_tasks')
  3430. ->where('id', $task_id)
  3431. ->select('id', 'status', 'result_url', 'error_message')
  3432. ->first();
  3433. if ($task) {
  3434. $task = (array)$task;
  3435. $status = getProp($task, 'status');
  3436. // 如果任务完成或失败
  3437. if (in_array($status, ['success', 'failed'])) {
  3438. $prop['task_status'] = $status;
  3439. if ($status === 'success') {
  3440. $result_url = getProp($task, 'result_url');
  3441. if ($result_url) {
  3442. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3443. if (is_array($result_urls) && !empty($result_urls[0])) {
  3444. $prop['url'] = $result_urls[0];
  3445. }
  3446. }
  3447. }
  3448. $updated = true;
  3449. } else if ($status === 'processing') {
  3450. $hasProcessing = true;
  3451. }
  3452. }
  3453. }
  3454. }
  3455. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3456. if ($updated) {
  3457. $newHash = $generateHash($roles, $scenes, $props);
  3458. $cachedHash = Redis::get($cacheKey);
  3459. // 只有当数据真正变化时才更新数据库和发送事件
  3460. if ($newHash !== $cachedHash) {
  3461. try {
  3462. // 更新数据库
  3463. DB::table($table_name)->where($id_field, $id_value)->update([
  3464. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3465. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3466. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3467. 'updated_at' => date('Y-m-d H:i:s')
  3468. ]);
  3469. // 更新缓存
  3470. Redis::setex($cacheKey, 600, $newHash);
  3471. // 发送更新事件
  3472. echo "data: " . json_encode([
  3473. 'type' => 'update',
  3474. 'data' => [
  3475. 'roles' => $roles,
  3476. 'scenes' => $scenes,
  3477. 'props' => $props,
  3478. 'elapsed_time' => time() - $startTime
  3479. ]
  3480. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3481. if (ob_get_level() > 0) {
  3482. ob_flush();
  3483. }
  3484. flush();
  3485. } catch (\Exception $e) {
  3486. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3487. }
  3488. } else {
  3489. // 即使哈希相同,如果有URL更新也要发送事件
  3490. $hasUrlUpdate = false;
  3491. foreach ($roles as $role) {
  3492. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3493. $hasUrlUpdate = true;
  3494. break;
  3495. }
  3496. }
  3497. if (!$hasUrlUpdate) {
  3498. foreach ($scenes as $scene) {
  3499. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3500. $hasUrlUpdate = true;
  3501. break;
  3502. }
  3503. }
  3504. }
  3505. if (!$hasUrlUpdate) {
  3506. foreach ($props as $prop) {
  3507. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3508. $hasUrlUpdate = true;
  3509. break;
  3510. }
  3511. }
  3512. }
  3513. if ($hasUrlUpdate) {
  3514. // 强制更新数据库和发送事件
  3515. try {
  3516. DB::table($table_name)->where($id_field, $id_value)->update([
  3517. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3518. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3519. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3520. 'updated_at' => date('Y-m-d H:i:s')
  3521. ]);
  3522. // 更新缓存
  3523. Redis::setex($cacheKey, 600, $newHash);
  3524. // 发送更新事件
  3525. echo "data: " . json_encode([
  3526. 'type' => 'update',
  3527. 'data' => [
  3528. 'roles' => $roles,
  3529. 'scenes' => $scenes,
  3530. 'props' => $props,
  3531. 'elapsed_time' => time() - $startTime
  3532. ]
  3533. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3534. if (ob_get_level() > 0) {
  3535. ob_flush();
  3536. }
  3537. flush();
  3538. } catch (\Exception $e) {
  3539. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3540. }
  3541. }
  3542. }
  3543. }
  3544. // 如果所有任务都已完成,发送完成事件并退出
  3545. if (!$hasProcessing) {
  3546. // 查询数据库中的最终数据,确保返回最新的完整数据
  3547. try {
  3548. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3549. if ($finalSource) {
  3550. $finalSource = (array)$finalSource;
  3551. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3552. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3553. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3554. // 使用数据库中的最终数据
  3555. $roles = $finalRoles;
  3556. $scenes = $finalScenes;
  3557. $props = $finalProps;
  3558. }
  3559. } catch (\Exception $e) {
  3560. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3561. // 如果查询失败,继续使用内存中的数据
  3562. }
  3563. // 清理缓存
  3564. Redis::del($cacheKey);
  3565. echo "data: " . json_encode([
  3566. 'type' => 'completed',
  3567. 'data' => [
  3568. 'roles' => $roles,
  3569. 'scenes' => $scenes,
  3570. 'props' => $props,
  3571. 'total_time' => time() - $startTime
  3572. ]
  3573. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3574. if (ob_get_level() > 0) {
  3575. ob_flush();
  3576. }
  3577. flush();
  3578. break;
  3579. }
  3580. // 等待下次检查
  3581. sleep($checkInterval);
  3582. }
  3583. // 超时处理
  3584. if (time() - $startTime >= $maxDuration) {
  3585. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3586. try {
  3587. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3588. if ($finalSource) {
  3589. $finalSource = (array)$finalSource;
  3590. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3591. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3592. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3593. // 使用数据库中的最终数据
  3594. $roles = $finalRoles;
  3595. $scenes = $finalScenes;
  3596. $props = $finalProps;
  3597. }
  3598. } catch (\Exception $e) {
  3599. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3600. // 如果查询失败,继续使用内存中的数据
  3601. }
  3602. // 清理缓存
  3603. Redis::del($cacheKey);
  3604. echo "data: " . json_encode([
  3605. 'type' => 'timeout',
  3606. 'message' => '轮询超时,请刷新页面查看最新状态',
  3607. 'data' => [
  3608. 'roles' => $roles,
  3609. 'scenes' => $scenes,
  3610. 'props' => $props
  3611. ]
  3612. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3613. if (ob_get_level() > 0) {
  3614. ob_flush();
  3615. }
  3616. flush();
  3617. }
  3618. };
  3619. }
  3620. public function clipSegmentVideo($data) {
  3621. $segment_id = getProp($data, 'segment_id');
  3622. $video_time_point_start = getProp($data, 'video_time_point_start');
  3623. $video_time_point_end = getProp($data, 'video_time_point_end');
  3624. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3625. Utils::throwError('20003:参数异常');
  3626. }
  3627. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3628. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3629. }
  3630. $video_duration = $video_time_point_end - $video_time_point_start;
  3631. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3632. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3633. 'video_duration' => $video_duration,
  3634. 'video_time_point_start' => $video_time_point_start,
  3635. 'video_time_point_end' => $video_time_point_end,
  3636. 'updated_at' => date('Y-m-d H:i:s')
  3637. ]);
  3638. }
  3639. // 轮训获取图片任务结果
  3640. private function loopGetPicTaskResult($task_id) {
  3641. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3642. if (!$task) {
  3643. return '';
  3644. }
  3645. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3646. $model = getProp($task, 'model');
  3647. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3648. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3649. $isSyncModel = $isVolcModel || $isGptModel;
  3650. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3651. $start_count = 0;
  3652. $img_url = '';
  3653. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3654. sleep(3);
  3655. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3656. // 如果任务已经完成,直接返回结果
  3657. if ($task->status === 'success' && $task->result_url) {
  3658. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3659. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3660. }
  3661. // 如果任务已失败,返回空
  3662. if ($task->status === 'failed') {
  3663. return '';
  3664. }
  3665. if ($isSyncModel) continue;
  3666. // 查询任务状态
  3667. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3668. if ($statusInfo['status'] === 'success') {
  3669. $task->updateStatus('success', [
  3670. 'result_url' => $statusInfo['result_url'],
  3671. 'result_json' => $statusInfo['result_json'] ?? []
  3672. ]);
  3673. // 同步调整分镜图片状态和结果
  3674. if (getProp($task, 'alias_segment_id')) {
  3675. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3676. 'img_url' => $statusInfo['result_url'][0],
  3677. 'pic_task_status' => '已完成',
  3678. ]);
  3679. }
  3680. $img_url = $statusInfo['result_url'][0];
  3681. break;
  3682. } elseif ($statusInfo['status'] === 'failed') {
  3683. $task->updateStatus('failed', [
  3684. 'error_message' => $statusInfo['error_message'],
  3685. 'result_json' => $statusInfo['result_json'] ?? []
  3686. ]);
  3687. if (getProp($task, 'alias_segment_id')) {
  3688. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3689. 'pic_task_status' => '失败',
  3690. ]);
  3691. }
  3692. break;
  3693. }
  3694. $start_count++;
  3695. }
  3696. return $img_url;
  3697. }
  3698. /**
  3699. * 从分镜内容中提取涉及的角色
  3700. */
  3701. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3702. $found_characters = [];
  3703. foreach ($available_characters as $character) {
  3704. // 检查角色名称是否在分镜内容中出现
  3705. if (strpos($segment_content, $character) !== false) {
  3706. $found_characters[] = $character;
  3707. }
  3708. }
  3709. if (!$found_characters) {
  3710. foreach ($roles as $character) {
  3711. // 检查角色名称是否在分镜内容中出现
  3712. if (strpos($segment_content, $character) !== false) {
  3713. $found_characters[] = $character;
  3714. }
  3715. }
  3716. }
  3717. return array_unique($found_characters);
  3718. }
  3719. // 从分镜剧本中提取关键字段
  3720. private function handleSegmentContent(&$data) {
  3721. $segmentContent = getProp($data, 'segment_content');
  3722. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3723. $segmentData = [
  3724. 'description' => '',
  3725. 'composition' => '',
  3726. 'camera_movement' => '',
  3727. 'voice_actor' => '',
  3728. 'dialogue' => '',
  3729. 'frame_type' => '',
  3730. 'scene' => '', // 场景
  3731. 'characters' => '', // 出镜角色
  3732. 'tail_frame' => '', // 尾帧描述
  3733. 'emotion' => '中性', // 情感
  3734. 'gender' => '0', // 性别(0未知,1男,2女)
  3735. 'speed_ratio' => 0, // 语速
  3736. 'loudness_ratio' => 0, // 音量
  3737. 'emotion_scale' => 4, // 情感强度
  3738. 'pitch' => 0, // 音调
  3739. ];
  3740. // 用于存储需要从 segment_content 中移除的匹配项
  3741. $replaceEmptyArr = [];
  3742. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3743. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3744. $segmentData['description'] = trim($descMatch[1]);
  3745. $data['description'] = trim($descMatch[1]);
  3746. }
  3747. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3748. $segmentData['composition'] = trim($compMatch[1]);
  3749. $data['composition'] = trim($compMatch[1]);
  3750. }
  3751. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3752. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3753. $data['camera_movement'] = trim($cameraMatch[1]);
  3754. }
  3755. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3756. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3757. $data['voice_actor'] = trim($voiceMatch[1]);
  3758. }
  3759. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3760. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3761. $data['dialogue'] = trim($dialogueMatch[1]);
  3762. }
  3763. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3764. $segmentData['frame_type'] = trim($frameMatch[1]);
  3765. $data['frame_type'] = trim($frameMatch[1]);
  3766. }
  3767. // 场景字段
  3768. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3769. $segmentData['scene'] = trim($sceneMatch[1]);
  3770. $data['scene'] = trim($sceneMatch[1]);
  3771. }
  3772. // 出镜角色字段
  3773. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3774. $segmentData['characters'] = trim($charactersMatch[1]);
  3775. $data['characters'] = trim($charactersMatch[1]);
  3776. }
  3777. // 尾帧描述字段
  3778. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3779. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3780. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3781. }
  3782. // 情感字段
  3783. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3784. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3785. $segmentData['emotion'] = trim($emotionMatch[1]);
  3786. $data['emotion'] = trim($emotionMatch[1]);
  3787. }
  3788. // 性别字段
  3789. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3790. $replaceEmptyArr[] = trim($genderMatch[0]);
  3791. $genderStr = trim($genderMatch[1]);
  3792. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3793. $segmentData['gender'] = '1';
  3794. $data['gender'] = '1';
  3795. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3796. $segmentData['gender'] = '2';
  3797. $data['gender'] = '2';
  3798. } else {
  3799. $segmentData['gender'] = '0';
  3800. $data['gender'] = '0';
  3801. }
  3802. }
  3803. // 语速字段
  3804. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3805. $replaceEmptyArr[] = trim($speedMatch[0]);
  3806. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3807. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3808. }
  3809. // 音量字段
  3810. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3811. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3812. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3813. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3814. }
  3815. // 情感强度字段
  3816. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3817. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3818. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3819. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3820. }
  3821. // 音调字段
  3822. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3823. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3824. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3825. $data['pitch'] = (int)trim($pitchMatch[1]);
  3826. }
  3827. // 从 segment_content 中移除已提取的配音参数字段
  3828. if (!empty($replaceEmptyArr)) {
  3829. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3830. }
  3831. // 如果有配音角色,查询音色信息并验证情感
  3832. $voice_actor = $segmentData['voice_actor'];
  3833. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3834. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3835. $anime_id = getProp($data, 'anime_id');
  3836. $episode_id = getProp($data, 'episode_id');
  3837. // 优先从剧集的角色列表中查找
  3838. $roles = [];
  3839. if ($episode_id) {
  3840. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3841. if ($episode && getProp($episode, 'roles')) {
  3842. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3843. }
  3844. }
  3845. // 如果剧集中没有,从动漫的角色列表中查找
  3846. if (empty($roles) && $anime_id) {
  3847. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3848. if ($anime && getProp($anime, 'roles')) {
  3849. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3850. }
  3851. }
  3852. // 查找匹配的角色音色信息
  3853. $timbre_info = null;
  3854. foreach ($roles as $role) {
  3855. if (getProp($role, 'role') === $voice_actor) {
  3856. $timbre_info = $role;
  3857. break;
  3858. }
  3859. }
  3860. // 如果找到音色信息,添加到数据中
  3861. if ($timbre_info) {
  3862. $voice_type = getProp($timbre_info, 'voice_type');
  3863. $voice_name = getProp($timbre_info, 'voice_name');
  3864. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3865. if ($voice_type) {
  3866. $data['voice_type'] = $voice_type;
  3867. $segmentData['voice_type'] = $voice_type;
  3868. }
  3869. if ($voice_name) {
  3870. $data['voice_name'] = $voice_name;
  3871. $segmentData['voice_name'] = $voice_name;
  3872. }
  3873. if ($voice_audio_url) {
  3874. $data['voice_audio_url'] = $voice_audio_url;
  3875. $segmentData['voice_audio_url'] = $voice_audio_url;
  3876. }
  3877. // 验证情感是否在音色支持的情感列表中
  3878. if ($voice_type) {
  3879. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3880. if ($timbre_emotion) {
  3881. $timbre_emotion = explode(',', $timbre_emotion);
  3882. } else {
  3883. $timbre_emotion = [];
  3884. }
  3885. $emotion = getProp($segmentData, 'emotion', '中性');
  3886. if (!in_array($emotion, $timbre_emotion)) {
  3887. $emotion = '中性';
  3888. }
  3889. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3890. $emotion_list = array_flip($emotion_list);
  3891. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3892. $data['emotion_type'] = $emotion_type;
  3893. $segmentData['emotion_type'] = $emotion_type;
  3894. }
  3895. }
  3896. }
  3897. return $segmentData;
  3898. }
  3899. public function createSegmentVideoTask($data) {
  3900. $segment_id = getProp($data, 'segment_id');
  3901. $tail_frame = getProp($data, 'tail_frame');
  3902. $first_frame_url = getProp($data, 'first_frame_url');
  3903. $tail_frame_url = getProp($data, 'tail_frame_url');
  3904. $generate_audio = getProp($data, 'generate_audio', 0);
  3905. if (!$segment_id) {
  3906. Utils::throwError('1002:分镜ID不能为空');
  3907. }
  3908. // 获取分镜信息
  3909. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3910. if (!$segment) {
  3911. Utils::throwError('20003:分镜不存在');
  3912. }
  3913. $segment = (array)$segment;
  3914. $episode_id = getProp($segment, 'episode_id');
  3915. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3916. if (!$ratio) $ratio = '9:16';
  3917. // 获取分镜内容
  3918. $segmentContent = getProp($segment, 'segment_content', '');
  3919. // 检查 $segmentContent 中是否已有尾帧描述
  3920. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3921. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3922. $finalTailFrame = '';
  3923. if ($tail_frame) {
  3924. // 用户输入了尾帧描述,优先使用
  3925. $finalTailFrame = $tail_frame;
  3926. // 如果 segmentContent 中已有尾帧描述,需要替换
  3927. if ($contentHasTailFrame) {
  3928. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3929. }
  3930. } elseif ($contentHasTailFrame) {
  3931. // segmentContent 中有尾帧描述,使用它
  3932. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3933. } else {
  3934. // 两者都没有,使用分镜表中的尾帧描述
  3935. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3936. }
  3937. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3938. $hasDialogue = false;
  3939. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3940. $dialogue = trim($dialogueMatch[1]);
  3941. // 如果台词不为空且不是"无"
  3942. if (!empty($dialogue) && $dialogue !== '无') {
  3943. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3944. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3945. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3946. $hasDialogue = true;
  3947. }
  3948. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3949. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3950. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3951. if (!preg_match('/^[“]/', $dialogue)) {
  3952. $dialogue = '“' . $dialogue;
  3953. }
  3954. if (!preg_match('/[”]$/', $dialogue)) {
  3955. $dialogue .= '”';
  3956. }
  3957. // 将修改后的台词替换回 $segmentContent
  3958. $originalDialogue = $dialogueMatch[1];
  3959. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3960. }
  3961. }
  3962. // 构建完整的提示词
  3963. $fullPrompt = $segmentContent;
  3964. if ($finalTailFrame && !$contentHasTailFrame) {
  3965. // 只有当 segmentContent 中没有尾帧描述时才追加
  3966. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3967. }
  3968. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3969. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3970. $fullPrompt = trim($fullPrompt);
  3971. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3972. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3973. // 智能选择视频时长
  3974. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3975. $videoDuration = -1;
  3976. // 处理视频模型
  3977. $model = getProp($data, 'model');
  3978. if (!$model) {
  3979. // 用户没有输入,从episode表获取
  3980. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3981. $model = getProp($episode, 'video_model');
  3982. if (!$model) {
  3983. // episode表也没有,使用默认值
  3984. $model = 'doubao-seedance-1-5-pro-251215';
  3985. }
  3986. }
  3987. // 验证模型是否在可用模型表中
  3988. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3989. $model = 'doubao-seedance-1-5-pro-251215';
  3990. }
  3991. // 保存到episode表
  3992. $episode_id = getProp($segment, 'episode_id');
  3993. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3994. 'video_model' => $model,
  3995. 'updated_at' => date('Y-m-d H:i:s')
  3996. ]);
  3997. // 构建视频生成参数
  3998. $videoParams = [
  3999. 'model' => $model,
  4000. 'alias_segment_id' => $segment_id,
  4001. 'prompt' => trim($fullPrompt),
  4002. 'video_duration' => $videoDuration,
  4003. 'video_resolution' => '720P',
  4004. 'seed' => -1,
  4005. 'ratio' => $ratio,
  4006. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4007. 'draft' => false,
  4008. 'watermark' => false,
  4009. 'camera_fixed' => false,
  4010. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4011. ];
  4012. // 如果分镜有图片,作为首帧
  4013. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  4014. $hasVideo = !empty(getProp($segment, 'video_url'));
  4015. if ($hasImage) {
  4016. if ($first_frame_url) {
  4017. $videoParams['first_frame_url'] = $first_frame_url;
  4018. }else {
  4019. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4020. }
  4021. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4022. }
  4023. // 构建content数组
  4024. $videoParams['content'] = [
  4025. [
  4026. 'type' => 'text',
  4027. 'text' => $videoParams['prompt'],
  4028. ]
  4029. ];
  4030. // 如果有首帧图片,添加到content中
  4031. if ($hasImage) {
  4032. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615'])) {
  4033. $videoParams['content'][] = [
  4034. 'type' => 'image_url',
  4035. 'image_url' => [
  4036. 'url' => $videoParams['first_frame_url'],
  4037. ],
  4038. 'role' => 'reference_image',
  4039. ];
  4040. if (isset($videoParams['tail_frame_url'])) {
  4041. $videoParams['content'][] = [
  4042. 'type' => 'image_url',
  4043. 'image_url' => [
  4044. 'url' => $videoParams['tail_frame_url'],
  4045. ],
  4046. 'role' => 'reference_image',
  4047. ];
  4048. }
  4049. }else {
  4050. $videoParams['content'][] = [
  4051. 'type' => 'image_url',
  4052. 'image_url' => [
  4053. 'url' => $videoParams['first_frame_url'],
  4054. ],
  4055. 'role' => 'first_frame',
  4056. ];
  4057. if (isset($videoParams['tail_frame_url'])) {
  4058. $videoParams['content'][] = [
  4059. 'type' => 'image_url',
  4060. 'image_url' => [
  4061. 'url' => $videoParams['tail_frame_url'],
  4062. ],
  4063. 'role' => 'last_frame',
  4064. ];
  4065. }
  4066. }
  4067. }
  4068. // 获取配音音频URL
  4069. $audioUrl = getProp($segment, 'audio_url');
  4070. $audioDuration = getProp($segment, 'audio_duration');
  4071. // 音频传入的前提:必须有至少一张图片或一个视频
  4072. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4073. // 余额预检:按预估时长计算所需积分,不足直接报错
  4074. $chargeDuration = (int)ceil((float)$audioDuration);
  4075. if ($chargeDuration <= 0) {
  4076. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4077. }
  4078. $this->pointsService->checkUserPointsEnough(
  4079. $this->pointsService->getVideoChargePoints([
  4080. 'model' => $model,
  4081. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4082. 'video_duration' => $chargeDuration,
  4083. 'ratio' => $ratio,
  4084. 'generate_audio' => $current_generate_audio,
  4085. ])
  4086. );
  4087. // dd($videoParams);
  4088. // 根据模型选择不同的视频生成方法
  4089. if (strpos($model, 'jimeng') !== false) {
  4090. // 即梦模型参数调整
  4091. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4092. unset($videoParams['content']); // 即梦不使用content格式
  4093. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4094. } elseif (strpos($model, 'kling') !== false) {
  4095. // Keling模型参数调整
  4096. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4097. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4098. unset($videoParams['ratio']);
  4099. unset($videoParams['content']); // Keling不使用content格式
  4100. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4101. } elseif (strpos($model, 'zhizhen') !== false) {
  4102. // 智帧20等新模型使用统一API
  4103. // 构建统一API参数
  4104. $unifiedParams = [
  4105. 'model_code' => $model,
  4106. 'alias_segment_id' => $segment_id,
  4107. 'prompt' => trim($fullPrompt),
  4108. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4109. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4110. 'video_ratio' => $ratio,
  4111. 'seed' => -1,
  4112. ];
  4113. // 构建parameters参数
  4114. $parameters = [
  4115. 'seconds' => $unifiedParams['video_duration'],
  4116. 'resolution' => $unifiedParams['video_resolution'],
  4117. 'ratio' => $ratio,
  4118. // 'video_mode' => 'multi_image',
  4119. // 'mode' => 'multi_image',
  4120. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4121. ];
  4122. $hasImage = false;
  4123. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4124. if ($hasImage) {
  4125. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4126. if (isset($videoParams['tail_frame_url'])) {
  4127. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4128. }
  4129. // 只有在有图片的情况下才能添加参考音频
  4130. if ($audioUrl) {
  4131. // $parameters['reference_audios'] = [$audioUrl];
  4132. }
  4133. } else {
  4134. // 没有图片时,记录错误日志
  4135. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4136. 'segment_id' => $segment_id,
  4137. 'model' => $model
  4138. ]);
  4139. }
  4140. $unifiedParams['parameters'] = $parameters;
  4141. // 调用统一API创建任务
  4142. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4143. } else {
  4144. // Seedance模型(默认)
  4145. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4146. if ($this->isKuaikuaiSeedanceModel($model)) {
  4147. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4148. if ($canUseAudio && $audioUrl) {
  4149. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4150. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4151. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4152. // 优化提示词,增加音频相关描述
  4153. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4154. $videoParams['prompt'] = $audioPrompt;
  4155. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4156. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4157. }
  4158. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4159. } elseif ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615'])) {
  4160. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4161. // 添加配音音频到content中
  4162. $videoParams['content'][] = [
  4163. 'type' => 'audio_url',
  4164. 'audio_url' => [
  4165. 'url' => $audioUrl,
  4166. ],
  4167. 'role' => 'reference_audio',
  4168. ];
  4169. // 优化提示词,增加音频相关描述
  4170. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4171. $videoParams['prompt'] = $audioPrompt;
  4172. $videoParams['content'][0]['text'] = $audioPrompt;
  4173. } else {
  4174. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4175. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4176. }
  4177. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4178. }
  4179. }
  4180. // 更新分镜表的视频任务信息
  4181. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4182. 'video_task_id' => $task->id,
  4183. 'video_task_status' => '生成中',
  4184. 'generate_audio' => $generate_audio,
  4185. 'updated_at' => date('Y-m-d H:i:s')
  4186. ]);
  4187. return [
  4188. 'task_id' => $task->id,
  4189. 'status' => $task->status,
  4190. 'segment_id' => $segment_id,
  4191. 'video_duration' => $videoDuration
  4192. ];
  4193. }
  4194. /**
  4195. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4196. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4197. *
  4198. * @param string $model
  4199. * @return bool
  4200. */
  4201. public function isKuaikuaiSeedanceModel(string $model): bool
  4202. {
  4203. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4204. }
  4205. /**
  4206. * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
  4207. *
  4208. * @param string $model
  4209. * @return bool
  4210. */
  4211. public function isBaiduSeedanceModel(string $model): bool
  4212. {
  4213. return in_array($model, [
  4214. 'baidu-doubao-seedance-2-0-260128',
  4215. 'baidu-doubao-seedance-2-0-fast-260128',
  4216. 'baidu-doubao-seedance-2-0-mini-260615',
  4217. 'baidu-doubao-seedance-2-5-260628',
  4218. ], true);
  4219. }
  4220. /**
  4221. * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-* / 快快AI seed-2 系列)
  4222. * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
  4223. *
  4224. * @param string $model
  4225. * @return bool
  4226. */
  4227. public function isSeedance20SeriesModel(string $model): bool
  4228. {
  4229. return strpos($model, 'doubao-seedance-2.0') !== false
  4230. || $this->isKuaikuaiSeedanceModel($model)
  4231. || $this->isBaiduSeedanceModel($model);
  4232. }
  4233. public function createActVideoTask($data) {
  4234. $act_id = getProp($data, 'act_id');
  4235. $first_frame_url = getProp($data, 'first_frame_url');
  4236. $tail_frame_url = getProp($data, 'tail_frame_url');
  4237. $generate_audio = getProp($data, 'generate_audio', 1);
  4238. $video_duration = getProp($data, 'video_duration');
  4239. $video_resolution = getProp($data, 'video_resolution');
  4240. $ratio = getProp($data, 'ratio');
  4241. $products = getProp($data, 'products', []);
  4242. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4243. if (!is_array($reference_images) || !is_array($products)) {
  4244. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4245. }
  4246. if (!$act_id) {
  4247. Utils::throwError('1002:片段ID不能为空');
  4248. }
  4249. // 获取片段信息
  4250. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4251. if (!$act) {
  4252. Utils::throwError('20003:片段不存在');
  4253. }
  4254. $act = (array)$act;
  4255. $anime_id = getProp($act, 'anime_id');
  4256. $episode_id = getProp($act, 'episode_id');
  4257. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4258. $ace_mode = getProp($anime, 'ace_mode');
  4259. $art_style_type = getProp($anime, 'art_style_type');
  4260. $art_style = getProp($anime, 'art_style');
  4261. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4262. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4263. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4264. // 将资产中新出现的资产放到extra_products中
  4265. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4266. if (!empty($products) && $episode) {
  4267. // 获取剧集中的角色、场景和道具列表
  4268. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4269. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4270. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4271. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4272. // 构建角色名称列表
  4273. $role_names = array_column($roles, 'role');
  4274. // 构建场景名称列表
  4275. $scene_names = array_column($scenes, 'scene');
  4276. // 构建道具名称列表
  4277. $prop_names = array_column($props, 'prop');
  4278. // 遍历传入的products
  4279. foreach ($products as $product) {
  4280. $product_name = getProp($product, 'product_name');
  4281. // 如果product_name不在roles、scenes和props中
  4282. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4283. // 查找是否在extra_products中存在同名的
  4284. $found = false;
  4285. foreach ($extra_products as $key => $extra_product) {
  4286. if (getProp($extra_product, 'product_name') === $product_name) {
  4287. // 有同名的则覆盖
  4288. $extra_products[$key] = $product;
  4289. $found = true;
  4290. break;
  4291. }
  4292. }
  4293. // 没有则新增
  4294. if (!$found) {
  4295. $extra_products[] = $product;
  4296. }
  4297. }
  4298. }
  4299. if ($extra_products) {
  4300. // 保存到数据库
  4301. DB::table('mp_anime_episodes')
  4302. ->where('id', $episode_id)
  4303. ->update([
  4304. 'extra_products' => json_encode($extra_products, 256),
  4305. 'updated_at' => date('Y-m-d H:i:s')
  4306. ]);
  4307. }
  4308. }
  4309. // 获取分镜内容
  4310. $actContent = getProp($act, 'act_show_content', '');
  4311. // 音效同出(默认使用)
  4312. $current_generate_audio = $generate_audio ? 1 : 0;
  4313. // 构建完整的提示词
  4314. $processResult = $this->processActContentWithProducts($actContent, $products);
  4315. $fullPrompt = $processResult['content'];
  4316. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4317. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4318. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4319. // 处理视频模型
  4320. $model = getProp($data, 'model');
  4321. if (!$model) {
  4322. $model = getProp($episode, 'video_model');
  4323. if (!$model) {
  4324. // episode表也没有,使用默认值
  4325. $model = 'seed-2';
  4326. }
  4327. }
  4328. // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
  4329. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  4330. if (!in_array($model, $valid_models)) {
  4331. $model = 'seed-2';
  4332. }
  4333. // 保存到episode表(仅在专用方法中更新模型)
  4334. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4335. // 'video_model' => $model,
  4336. // 'updated_at' => date('Y-m-d H:i:s')
  4337. // ]);
  4338. // 余额预检:按预估时长计算所需积分,不足直接报错
  4339. $chargeDuration = (int)$videoDuration;
  4340. if ($chargeDuration <= 0) {
  4341. $chargeDuration = 5; // 无时长时按默认5秒预估
  4342. }
  4343. $this->pointsService->checkUserPointsEnough(
  4344. $this->pointsService->getVideoChargePoints([
  4345. 'model' => $model,
  4346. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4347. 'video_duration' => $chargeDuration,
  4348. 'ratio' => $ratio,
  4349. 'generate_audio' => $current_generate_audio,
  4350. ])
  4351. );
  4352. // 构建视频生成参数
  4353. $videoParams = [
  4354. 'model' => $model,
  4355. 'alias_act_id' => $act_id,
  4356. 'prompt' => trim($fullPrompt),
  4357. 'video_duration' => $videoDuration,
  4358. 'video_resolution' => $video_resolution,
  4359. 'seed' => -1,
  4360. 'ratio' => $ratio,
  4361. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4362. 'draft' => false,
  4363. 'watermark' => false,
  4364. 'camera_fixed' => false,
  4365. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4366. ];
  4367. // 如果分镜有图片,作为首帧
  4368. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4369. $hasVideo = !empty(getProp($act, 'video_url'));
  4370. if ($hasImage) {
  4371. if ($first_frame_url) {
  4372. $videoParams['first_frame_url'] = $first_frame_url;
  4373. }else {
  4374. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4375. }
  4376. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4377. }
  4378. // 构建content数组
  4379. $videoParams['content'] = [
  4380. [
  4381. 'type' => 'text',
  4382. 'text' => $videoParams['prompt'],
  4383. ]
  4384. ];
  4385. // 如果有首帧图片,添加到content中
  4386. if ($hasImage) {
  4387. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615'])) {
  4388. $videoParams['content'][] = [
  4389. 'type' => 'image_url',
  4390. 'image_url' => [
  4391. 'url' => $videoParams['first_frame_url'],
  4392. ],
  4393. 'role' => 'reference_image',
  4394. ];
  4395. if (isset($videoParams['tail_frame_url'])) {
  4396. $videoParams['content'][] = [
  4397. 'type' => 'image_url',
  4398. 'image_url' => [
  4399. 'url' => $videoParams['tail_frame_url'],
  4400. ],
  4401. 'role' => 'reference_image',
  4402. ];
  4403. }
  4404. }else {
  4405. $videoParams['content'][] = [
  4406. 'type' => 'image_url',
  4407. 'image_url' => [
  4408. 'url' => $videoParams['first_frame_url'],
  4409. ],
  4410. 'role' => 'first_frame',
  4411. ];
  4412. if (isset($videoParams['tail_frame_url'])) {
  4413. $videoParams['content'][] = [
  4414. 'type' => 'image_url',
  4415. 'image_url' => [
  4416. 'url' => $videoParams['tail_frame_url'],
  4417. ],
  4418. 'role' => 'last_frame',
  4419. ];
  4420. }
  4421. }
  4422. }
  4423. // dd($videoParams);
  4424. // 根据模型选择不同的视频生成方法
  4425. if (strpos($model, 'jimeng') !== false) {
  4426. // 即梦模型参数调整
  4427. unset($videoParams['content']); // 即梦不使用content格式
  4428. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4429. } elseif (strpos($model, 'kling') !== false) {
  4430. // Keling模型参数调整
  4431. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4432. unset($videoParams['ratio']);
  4433. unset($videoParams['content']); // Keling不使用content格式
  4434. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4435. } elseif (strpos($model, 'zhizhen') !== false) {
  4436. // 智帧20等新模型使用统一API
  4437. // 构建统一API参数
  4438. $unifiedParams = [
  4439. 'model_code' => $model,
  4440. 'alias_act_id' => $act_id,
  4441. 'prompt' => trim($fullPrompt),
  4442. 'video_duration' => $videoDuration,
  4443. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4444. 'video_ratio' => $ratio,
  4445. 'seed' => -1,
  4446. ];
  4447. // 构建parameters参数
  4448. $parameters = [
  4449. 'seconds' => $unifiedParams['video_duration'],
  4450. 'resolution' => $unifiedParams['video_resolution'],
  4451. 'ratio' => $ratio,
  4452. // 'video_mode' => 'multi_image',
  4453. // 'mode' => 'multi_image',
  4454. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4455. ];
  4456. $hasImage = false;
  4457. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4458. if ($hasImage) {
  4459. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4460. if (isset($videoParams['tail_frame_url'])) {
  4461. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4462. }
  4463. } else {
  4464. // 没有图片时,记录错误日志
  4465. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4466. 'act_id' => $act_id,
  4467. 'model' => $model
  4468. ]);
  4469. }
  4470. if ($reference_images) {
  4471. // 限制只传入9张参考图
  4472. $reference_images = array_slice($reference_images, 0, 9);
  4473. // 在处理之前先保存原始reference_images到任务参数中
  4474. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4475. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4476. $parameters['reference_images'] = $reference_images;
  4477. $parameters['video_mode'] = 'multi_image';
  4478. $parameters['mode'] = 'multi_image';
  4479. }
  4480. $unifiedParams['parameters'] = $parameters;
  4481. // 调用统一API创建任务
  4482. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4483. } elseif ($this->isSeedance20SeriesModel($model)) {
  4484. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4485. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4486. // 保存原始参考图用于任务记录
  4487. $videoParams['reference_images'] = $reference_images;
  4488. if ($reference_images) {
  4489. // 限制只传入9张参考图
  4490. $reference_images = array_slice($reference_images, 0, 9);
  4491. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4492. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4493. // 参考图上传为素材(百度网关/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4494. $reference_image_assets = $isKuaikuai
  4495. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4496. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4497. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4498. $videoParams['prompt'] = trim($fullPrompt);
  4499. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4500. $videoParams['reference_image_assets'] = $reference_image_assets;
  4501. }
  4502. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4503. if ($isKuaikuai) {
  4504. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4505. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4506. } else {
  4507. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4508. }
  4509. } else {
  4510. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4511. }
  4512. // 更新分镜表的视频任务信息
  4513. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4514. 'video_task_id' => $task->id,
  4515. 'video_task_status' => '生成中',
  4516. 'generate_audio' => $generate_audio,
  4517. 'updated_at' => date('Y-m-d H:i:s')
  4518. ]);
  4519. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4520. $episode_number = getProp($act, 'episode_number');
  4521. $act_number = getProp($act, 'act_number');
  4522. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4523. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4524. }
  4525. return [
  4526. 'task_id' => $task->id,
  4527. 'status' => $task->status,
  4528. 'act_id' => $act_id,
  4529. 'video_duration' => $videoDuration
  4530. ];
  4531. }
  4532. /**
  4533. * 文生视频通用方法
  4534. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4535. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4536. *
  4537. * @param array $data 请求参数
  4538. * @return array
  4539. */
  4540. public function generateVideo($data) {
  4541. $prompt = getProp($data, 'prompt');
  4542. if (empty($prompt)) {
  4543. Utils::throwError('20003:提示词不能为空');
  4544. }
  4545. $model = getProp($data, 'model');
  4546. if (!$model) {
  4547. $model = 'seed-2';
  4548. }
  4549. // 验证模型是否在可用模型表中
  4550. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4551. Utils::throwError('20003:该模型已不可用,请更换!');
  4552. }
  4553. $video_duration = getProp($data, 'video_duration', 5);
  4554. $video_resolution = getProp($data, 'video_resolution', '480p');
  4555. $ratio = getProp($data, 'ratio', '9:16');
  4556. $generate_audio = getProp($data, 'generate_audio', 1);
  4557. $seed = getProp($data, 'seed', -1);
  4558. $first_frame_url = getProp($data, 'first_frame_url');
  4559. $tail_frame_url = getProp($data, 'tail_frame_url');
  4560. // 参考图(支持数组或JSON字符串,最多9张)
  4561. $reference_images = getProp($data, 'reference_images', []);
  4562. if (is_string($reference_images)) {
  4563. $reference_images = json_decode($reference_images, true) ?: [];
  4564. }
  4565. if (!is_array($reference_images)) {
  4566. Utils::throwError('20003:参考图格式不正确');
  4567. }
  4568. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4569. $reference_images = array_slice($reference_images, 0, 9);
  4570. // 参考视频(支持数组或JSON字符串,最多3个)
  4571. $reference_videos = getProp($data, 'reference_videos', []);
  4572. if (is_string($reference_videos)) {
  4573. $reference_videos = json_decode($reference_videos, true) ?: [];
  4574. }
  4575. if (!is_array($reference_videos)) {
  4576. Utils::throwError('20003:参考视频格式不正确');
  4577. }
  4578. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4579. if (count($reference_videos) > 3) {
  4580. Utils::throwError('20003:参考视频最多选择3个');
  4581. }
  4582. $reference_videos = array_slice($reference_videos, 0, 3);
  4583. // 参考音频(支持数组或JSON字符串,最多3个)
  4584. $reference_audios = getProp($data, 'reference_audios', []);
  4585. if (is_string($reference_audios)) {
  4586. $reference_audios = json_decode($reference_audios, true) ?: [];
  4587. }
  4588. if (!is_array($reference_audios)) {
  4589. Utils::throwError('20003:参考音频格式不正确');
  4590. }
  4591. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4592. if (count($reference_audios) > 3) {
  4593. Utils::throwError('20003:参考音频最多选择3个');
  4594. }
  4595. $reference_audios = array_slice($reference_audios, 0, 3);
  4596. // 余额预检:按预估时长计算所需积分,不足直接报错
  4597. $chargeDuration = (int)ceil((float)$video_duration);
  4598. if ($chargeDuration <= 0) {
  4599. $chargeDuration = 5; // 无时长时按默认5秒预估
  4600. }
  4601. $this->pointsService->checkUserPointsEnough(
  4602. $this->pointsService->getVideoChargePoints([
  4603. 'model' => $model,
  4604. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4605. 'video_duration' => $chargeDuration,
  4606. 'ratio' => $ratio,
  4607. 'generate_audio' => (int)$generate_audio,
  4608. ])
  4609. );
  4610. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4611. $videoParams = [
  4612. 'model' => $model,
  4613. 'prompt' => $prompt,
  4614. 'video_duration' => $video_duration,
  4615. 'video_resolution' => $video_resolution,
  4616. 'seed' => $seed,
  4617. 'ratio' => $ratio,
  4618. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4619. 'draft' => getProp($data, 'draft', false),
  4620. 'watermark' => getProp($data, 'watermark', false),
  4621. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4622. ];
  4623. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4624. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4625. // 构建content数组
  4626. $videoParams['content'] = [
  4627. [
  4628. 'type' => 'text',
  4629. 'text' => $prompt,
  4630. ]
  4631. ];
  4632. // 根据模型选择不同的视频生成方法
  4633. if (strpos($model, 'jimeng') !== false) {
  4634. // 即梦模型参数调整
  4635. unset($videoParams['content']); // 即梦不使用content格式
  4636. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4637. } elseif (strpos($model, 'kling') !== false) {
  4638. // 可灵模型参数调整
  4639. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4640. unset($videoParams['ratio']);
  4641. unset($videoParams['content']); // 可灵不使用content格式
  4642. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4643. } elseif (strpos($model, 'zhizhen') !== false) {
  4644. // 智帧等新模型使用统一API
  4645. $unifiedParams = [
  4646. 'model_code' => $model,
  4647. 'prompt' => $prompt,
  4648. 'video_duration' => $video_duration,
  4649. 'video_resolution' => strtolower($video_resolution),
  4650. 'video_ratio' => $ratio,
  4651. 'seed' => $seed,
  4652. ];
  4653. // 构建parameters参数
  4654. $parameters = [
  4655. 'seconds' => $unifiedParams['video_duration'],
  4656. 'resolution' => $unifiedParams['video_resolution'],
  4657. 'ratio' => $ratio,
  4658. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4659. ];
  4660. // 首帧和尾帧
  4661. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4662. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4663. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4664. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4665. if ($refImageUrls) {
  4666. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4667. }
  4668. // 参考图处理
  4669. if ($reference_images) {
  4670. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4671. $parameters['reference_images'] = $reference_images;
  4672. $parameters['video_mode'] = 'multi_image';
  4673. $parameters['mode'] = 'multi_image';
  4674. }
  4675. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4676. if ($reference_videos) {
  4677. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4678. $parameters['reference_videos'] = $reference_videos;
  4679. }
  4680. if ($reference_audios) {
  4681. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4682. $parameters['reference_audios'] = $reference_audios;
  4683. }
  4684. $unifiedParams['parameters'] = $parameters;
  4685. // 调用统一API创建任务
  4686. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4687. } elseif ($this->isSeedance20SeriesModel($model)) {
  4688. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4689. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4690. $videoParams['reference_images'] = $reference_images;
  4691. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4692. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4693. if ($refImageUrls) {
  4694. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4695. }
  4696. if ($reference_images) {
  4697. // 参考图上传为素材(百度网关/快快AI)
  4698. $reference_image_assets = $isKuaikuai
  4699. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4700. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']);
  4701. $videoParams['reference_image_assets'] = $reference_image_assets;
  4702. }
  4703. // 参考视频上传为素材(百度网关/快快AI)
  4704. if ($reference_videos) {
  4705. $reference_video_assets = $isKuaikuai
  4706. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4707. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']);
  4708. $videoParams['reference_video_assets'] = $reference_video_assets;
  4709. }
  4710. // 参考音频上传为素材(百度网关/快快AI)
  4711. if ($reference_audios) {
  4712. $reference_audio_assets = $isKuaikuai
  4713. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4714. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']);
  4715. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4716. }
  4717. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4718. if ($reference_images || $reference_videos || $reference_audios) {
  4719. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4720. }
  4721. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4722. if ($isKuaikuai) {
  4723. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4724. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4725. } else {
  4726. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4727. }
  4728. } else {
  4729. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4730. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4731. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4732. if ($refImageUrls) {
  4733. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4734. }
  4735. if ($reference_videos) {
  4736. foreach ($reference_videos as $videoUrl) {
  4737. $videoParams['content'][] = [
  4738. 'type' => 'video_url',
  4739. 'video_url' => [
  4740. 'url' => $videoUrl,
  4741. ],
  4742. 'role' => 'reference_video',
  4743. ];
  4744. }
  4745. }
  4746. if ($reference_audios) {
  4747. foreach ($reference_audios as $audioUrl) {
  4748. $videoParams['content'][] = [
  4749. 'type' => 'audio_url',
  4750. 'audio_url' => [
  4751. 'url' => $audioUrl,
  4752. ],
  4753. 'role' => 'reference_audio',
  4754. ];
  4755. }
  4756. }
  4757. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4758. }
  4759. return [
  4760. 'task_id' => $task->id,
  4761. 'status' => $task->status,
  4762. 'model' => $model,
  4763. 'video_duration' => $video_duration,
  4764. 'video_resolution' => $video_resolution,
  4765. 'ratio' => $ratio
  4766. ];
  4767. }
  4768. /**
  4769. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4770. *
  4771. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4772. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4773. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4774. *
  4775. * @param array $data
  4776. * @return array
  4777. */
  4778. public function previewCharge(array $data): array
  4779. {
  4780. $mode = (string)getProp($data, 'mode', '');
  4781. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4782. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4783. }
  4784. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4785. $scene = (string)getProp($data, 'scene', 'video_generation');
  4786. // 未显式传scene且带参考视频时,自动按video_to_video定价
  4787. if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
  4788. $scene = 'video_to_video';
  4789. }
  4790. $items = [];
  4791. $model = '';
  4792. $resolution = '';
  4793. if ($mode === 'video') {
  4794. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4795. $model = (string)getProp($data, 'model', '');
  4796. if (!$model) {
  4797. Utils::throwError('1002:model参数不能为空');
  4798. }
  4799. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4800. $duration = (int)getProp($data, 'video_duration', 5);
  4801. if ($duration <= 0) {
  4802. $duration = 5;
  4803. }
  4804. $count = max(1, (int)getProp($data, 'count', 1));
  4805. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4806. 'model' => $model,
  4807. 'video_resolution' => $resolution,
  4808. 'video_duration' => $duration,
  4809. 'mode' => $scene,
  4810. ]);
  4811. $points = $pointsPerVideo * $count;
  4812. $items[] = [
  4813. 'type' => 'video',
  4814. 'model' => $model,
  4815. 'video_resolution' => $resolution,
  4816. 'video_duration' => $duration,
  4817. 'count' => $count,
  4818. 'points' => $points,
  4819. ];
  4820. } elseif ($mode === 'image') {
  4821. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4822. $model = (string)getProp($data, 'model', '');
  4823. if (!$model) {
  4824. Utils::throwError('1002:model参数不能为空');
  4825. }
  4826. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4827. if (!$resolution) {
  4828. $width = (int)getProp($data, 'width', 0);
  4829. $height = (int)getProp($data, 'height', 0);
  4830. if ($width <= 0 || $height <= 0) {
  4831. $width = 1600;
  4832. $height = 2848;
  4833. }
  4834. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4835. }
  4836. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4837. $points = $this->pointsService->getImageChargePoints([
  4838. 'model' => $model,
  4839. 'resolution' => $resolution,
  4840. ]) * $imageNum;
  4841. $items[] = [
  4842. 'type' => 'image',
  4843. 'model' => $model,
  4844. 'resolution' => $resolution,
  4845. 'image_num' => $imageNum,
  4846. 'points' => $points,
  4847. ];
  4848. } else {
  4849. // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
  4850. // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
  4851. $priceType = (string)getProp($data, 'price_type', 'special');
  4852. if (!in_array($priceType, ['special', 'normal'], true)) {
  4853. Utils::throwError('1003:price_type参数仅支持special或normal');
  4854. }
  4855. $count = max(1, (int)getProp($data, 'count', 1));
  4856. $animeId = getProp($data, 'anime_id');
  4857. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4858. if ($animeId && $generateEpisodes > 0) {
  4859. // 批量生成分集按 special 档预估,与实际扣费口径一致
  4860. $priceType = 'special';
  4861. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4862. ->where('anime_id', $animeId)
  4863. ->where('is_default', 1)
  4864. ->max('episode_number');
  4865. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4866. $startEpisodeNumber = $currentMaxEpisode + 1;
  4867. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4868. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4869. ->where('anime_id', $animeId)
  4870. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4871. ->whereIn('status', ['pending', 'processing', 'completed'])
  4872. ->count();
  4873. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4874. if ($count < 0) {
  4875. $count = 0;
  4876. }
  4877. }
  4878. $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
  4879. $items[] = [
  4880. 'type' => 'chat',
  4881. 'count' => $count,
  4882. 'price_type' => $priceType,
  4883. 'points' => $points,
  4884. ];
  4885. }
  4886. $totalPoints = 0;
  4887. foreach ($items as $item) {
  4888. $totalPoints += $item['points'];
  4889. }
  4890. return [
  4891. 'mode' => $mode,
  4892. 'total_points' => $totalPoints,
  4893. 'items' => $items,
  4894. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4895. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4896. ];
  4897. }
  4898. /**
  4899. * 根据提示词内容智能计算最优视频时长
  4900. *
  4901. * @param string $segmentContent 分镜内容
  4902. * @param string $tailFrame 尾帧描述
  4903. * @return int 视频时长(2-12秒)
  4904. */
  4905. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4906. // 合并所有文本内容
  4907. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4908. // 如果没有内容,返回默认时长
  4909. if (empty($fullText)) {
  4910. return 5;
  4911. }
  4912. // 计算文本长度(中文字符按2个字符计算)
  4913. $textLength = mb_strlen($fullText, 'UTF-8');
  4914. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4915. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4916. // 分析内容复杂度
  4917. $complexityScore = $this->analyzeContentComplexity($fullText);
  4918. // 基础时长计算(根据文本长度)
  4919. $baseDuration = 3; // 默认2秒
  4920. // if ($adjustedLength <= 20) {
  4921. // $baseDuration = 3;
  4922. // } elseif ($adjustedLength <= 40) {
  4923. // $baseDuration = 4;
  4924. // } elseif ($adjustedLength <= 60) {
  4925. // $baseDuration = 5;
  4926. // } elseif ($adjustedLength <= 80) {
  4927. // $baseDuration = 6;
  4928. // } elseif ($adjustedLength <= 100) {
  4929. // $baseDuration = 7;
  4930. // } elseif ($adjustedLength <= 120) {
  4931. // $baseDuration = 8;
  4932. // } else {
  4933. // $baseDuration = 9;
  4934. // }
  4935. // 根据内容复杂度调整时长
  4936. $finalDuration = $baseDuration + $complexityScore;
  4937. // 确保时长在2-12秒范围内
  4938. return max(4, min(12, $finalDuration));
  4939. }
  4940. /**
  4941. * 分析内容复杂度,返回时长调整值
  4942. *
  4943. * @param string $text 文本内容
  4944. * @return int 调整值(-2到+3)
  4945. */
  4946. private function analyzeContentComplexity($text) {
  4947. $score = 0;
  4948. // 动作关键词(需要更长时间展现)
  4949. $actionKeywords = [
  4950. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4951. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4952. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4953. ];
  4954. // 静态关键词(可以用较短时间)
  4955. $staticKeywords = [
  4956. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4957. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4958. ];
  4959. // 复杂场景关键词(需要更长时间)
  4960. $complexSceneKeywords = [
  4961. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4962. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4963. ];
  4964. // 情感关键词(需要适中时间表现)
  4965. $emotionKeywords = [
  4966. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4967. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4968. ];
  4969. // 检查动作关键词
  4970. foreach ($actionKeywords as $keyword) {
  4971. if (strpos($text, $keyword) !== false) {
  4972. $score += 1;
  4973. break; // 避免重复加分
  4974. }
  4975. }
  4976. // 检查静态关键词
  4977. foreach ($staticKeywords as $keyword) {
  4978. if (strpos($text, $keyword) !== false) {
  4979. $score -= 1;
  4980. break;
  4981. }
  4982. }
  4983. // 检查复杂场景关键词
  4984. foreach ($complexSceneKeywords as $keyword) {
  4985. if (strpos($text, $keyword) !== false) {
  4986. $score += 1;
  4987. break;
  4988. }
  4989. }
  4990. // 检查情感关键词
  4991. foreach ($emotionKeywords as $keyword) {
  4992. if (strpos($text, $keyword) !== false) {
  4993. $score += 1;
  4994. break;
  4995. }
  4996. }
  4997. // 检查时间相关词汇
  4998. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4999. $score += 1;
  5000. }
  5001. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  5002. $score -= 1;
  5003. }
  5004. // 检查转场词汇
  5005. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  5006. $score += 1;
  5007. }
  5008. // 检查环境描述(复杂环境需要更多时间)
  5009. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  5010. $score += 1;
  5011. }
  5012. // 检查对话内容(对话需要更多时间)
  5013. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  5014. $score += 1;
  5015. }
  5016. // 限制调整范围
  5017. return max(-1, min(4, $score));
  5018. }
  5019. /**
  5020. * 创建完整视频合成任务
  5021. *
  5022. * @param array $data
  5023. * @return array
  5024. */
  5025. public function createCompleteVideoTask($data)
  5026. {
  5027. $animeId = getProp($data, 'anime_id');
  5028. $episodeId = getProp($data, 'episode_id');
  5029. // 验证参数
  5030. if (!$animeId || !$episodeId) {
  5031. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  5032. }
  5033. // 检查是否已存在处理中的任务
  5034. $existingTask = DB::table('mp_complete_video_tasks')
  5035. ->where('anime_id', $animeId)
  5036. ->where('episode_id', $episodeId)
  5037. ->whereIn('generate_status', ['执行中'])
  5038. ->first();
  5039. if ($existingTask) {
  5040. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  5041. }
  5042. // 获取全能模式状态
  5043. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  5044. if ((int)$ace_mode === 1) {
  5045. // 获取所有片段的配音视频,按 act_number 排序
  5046. $segments = DB::table('mp_episode_segments')
  5047. ->where('anime_id', $animeId)
  5048. ->where('episode_id', $episodeId)
  5049. ->orderBy('segment_number')
  5050. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5051. ->get();
  5052. // 检查是否所有片段都有视频
  5053. $missingVideos = $segments->filter(function($segment) {
  5054. return empty($segment->video_url);
  5055. });
  5056. if ($missingVideos->isNotEmpty()) {
  5057. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  5058. }
  5059. }else {
  5060. // 获取所有分镜的配音视频,按 segment_number 排序
  5061. $segments = DB::table('mp_episode_segments')
  5062. ->where('anime_id', $animeId)
  5063. ->where('episode_id', $episodeId)
  5064. ->orderBy('segment_number')
  5065. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5066. ->get();
  5067. // 检查是否所有分镜都有配音和视频
  5068. $missingVideos = $segments->filter(function($segment) {
  5069. return empty($segment->audio_url) || empty($segment->video_url);
  5070. });
  5071. if ($missingVideos->isNotEmpty()) {
  5072. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5073. }
  5074. }
  5075. if ($segments->isEmpty()) {
  5076. Utils::throwError('20003:未找到该剧集的分镜数据');
  5077. }
  5078. // 获取当前完整视频url
  5079. $completeVideoUrl = DB::table('mp_anime_episodes')
  5080. ->where('anime_id', $animeId)
  5081. ->where('id', $episodeId)
  5082. ->value('complete_video_url');
  5083. // 构建 generate_json
  5084. $generateJson = [];
  5085. $sequence = 1;
  5086. foreach ($segments as $segment) {
  5087. if ((int)$ace_mode === 1) {
  5088. $generateJson[] = [
  5089. 'sequence' => $sequence++,
  5090. 'video_url' => $segment->video_url,
  5091. 'video_time_point_start' => $segment->video_time_point_start,
  5092. 'video_time_point_end' => $segment->video_time_point_end
  5093. ];
  5094. }else {
  5095. $generateJson[] = [
  5096. 'sequence' => $sequence++,
  5097. 'video_url' => $segment->video_url,
  5098. 'audio_url' => $segment->audio_url,
  5099. 'video_time_point_start' => $segment->video_time_point_start,
  5100. 'video_time_point_end' => $segment->video_time_point_end
  5101. ];
  5102. }
  5103. }
  5104. // 创建任务
  5105. $now = date('Y-m-d H:i:s');
  5106. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5107. 'anime_id' => $animeId,
  5108. 'episode_id' => $episodeId,
  5109. 'generate_json' => json_encode($generateJson, 256),
  5110. 'generate_status' => '执行中',
  5111. 'complete_video_url' => '',
  5112. 'created_at' => $now,
  5113. 'updated_at' => $now
  5114. ]);
  5115. if (!$taskId) {
  5116. Utils::throwError('20003:创建任务失败');
  5117. }
  5118. // 更新剧集表的任务ID和状态
  5119. $boolen = DB::table('mp_anime_episodes')
  5120. ->where('anime_id', $animeId)
  5121. ->where('id', $episodeId)
  5122. ->update([
  5123. 'complete_video_task_id' => $taskId,
  5124. 'complete_video_task_status' => '执行中',
  5125. 'updated_at' => $now
  5126. ]);
  5127. if (!$boolen) {
  5128. Utils::throwError('20003:更新剧集表失败');
  5129. }
  5130. dLog('anime')->info('创建完整视频合成任务', [
  5131. 'task_id' => $taskId,
  5132. 'anime_id' => $animeId,
  5133. 'episode_id' => $episodeId,
  5134. 'segment_count' => count($generateJson)
  5135. ]);
  5136. // 请求远程服务器执行生成
  5137. $client = new Client(['timeout' => 600, 'verify' => false]);
  5138. try {
  5139. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5140. $response = $result->getBody()->getContents();
  5141. $response_arr = json_decode($response, true);
  5142. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5143. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5144. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5145. // // 更新任务状态为失败
  5146. // DB::table('mp_complete_video_tasks')
  5147. // ->where('id', $taskId)
  5148. // ->update([
  5149. // 'generate_status' => '执行失败',
  5150. // 'error_message' => $error_msg,
  5151. // 'updated_at' => date('Y-m-d H:i:s')
  5152. // ]);
  5153. // // 同步更新剧集表状态
  5154. // DB::table('mp_anime_episodes')
  5155. // ->where('complete_video_task_id', $taskId)
  5156. // ->update([
  5157. // 'complete_video_task_status' => '执行失败',
  5158. // 'updated_at' => date('Y-m-d H:i:s')
  5159. // ]);
  5160. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5161. }
  5162. } catch (\Exception $e) {
  5163. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5164. // 更新任务状态为失败
  5165. DB::table('mp_complete_video_tasks')
  5166. ->where('id', $taskId)
  5167. ->update([
  5168. 'generate_status' => '执行失败',
  5169. 'error_message' => $e->getMessage(),
  5170. 'updated_at' => date('Y-m-d H:i:s')
  5171. ]);
  5172. // 同步更新剧集表状态
  5173. DB::table('mp_anime_episodes')
  5174. ->where('complete_video_task_id', $taskId)
  5175. ->update([
  5176. 'complete_video_task_status' => '执行失败',
  5177. 'updated_at' => date('Y-m-d H:i:s')
  5178. ]);
  5179. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5180. }
  5181. // 开始轮询任务状态
  5182. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5183. $pollInterval = 5; // 每5秒轮询一次
  5184. $attempt = 0;
  5185. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5186. while ($attempt < $maxAttempts) {
  5187. sleep($pollInterval);
  5188. $attempt++;
  5189. // 查询任务状态
  5190. $task = DB::table('mp_complete_video_tasks')
  5191. ->where('id', $taskId)
  5192. ->first();
  5193. if (!$task) {
  5194. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5195. Utils::throwError('20003:任务不存在');
  5196. }
  5197. dLog('anime')->info('轮询任务状态', [
  5198. 'task_id' => $taskId,
  5199. 'attempt' => $attempt,
  5200. 'status' => $task->generate_status
  5201. ]);
  5202. // 检查任务是否完成
  5203. if ($task->generate_status === '执行成功') {
  5204. // 同步更新剧集表状态
  5205. $boolen3 = DB::table('mp_anime_episodes')
  5206. ->where('anime_id', $animeId)
  5207. ->where('id', $episodeId)
  5208. ->update([
  5209. 'complete_video_url' => $task->complete_video_url,
  5210. 'complete_video_task_status' => '执行成功',
  5211. 'updated_at' => date('Y-m-d H:i:s')
  5212. ]);
  5213. dLog('anime')->info('视频合成任务完成', [
  5214. 'task_id' => $taskId,
  5215. 'video_url' => $task->complete_video_url,
  5216. 'attempts' => $attempt
  5217. ]);
  5218. // 如果更新成功则远程删除之前的文件
  5219. if ($boolen3 && $completeVideoUrl) {
  5220. $encode_url = urlencode($completeVideoUrl);
  5221. $client = new Client(['timeout' => 300, 'verify' => false]);
  5222. // 根据ID通过API通知合成音频
  5223. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5224. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5225. $response = $result->getBody()->getContents();
  5226. $response_arr = json_decode($response, true);
  5227. Log::info('火山删除音频返回: '.$response);
  5228. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5229. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5230. Log::info('火山删除音频失败: '.$error_msg);
  5231. // Utils::throwError('20003:火山删除音频失败');
  5232. }
  5233. }
  5234. return [
  5235. 'task_id' => $taskId,
  5236. 'anime_id' => $animeId,
  5237. 'episode_id' => $episodeId,
  5238. 'segment_count' => count($generateJson),
  5239. 'generate_status' => '执行成功',
  5240. 'complete_video_url' => $task->complete_video_url,
  5241. ];
  5242. }
  5243. // 检查任务是否失败
  5244. if ($task->generate_status === '执行失败') {
  5245. // 同步更新剧集表状态
  5246. DB::table('mp_anime_episodes')
  5247. ->where('anime_id', $animeId)
  5248. ->where('id', $episodeId)
  5249. ->update([
  5250. 'complete_video_task_status' => '执行失败',
  5251. 'updated_at' => date('Y-m-d H:i:s')
  5252. ]);
  5253. $errorMessage = $task->error_message ?? '未知错误';
  5254. dLog('anime')->error('视频合成任务失败', [
  5255. 'task_id' => $taskId,
  5256. 'error' => $errorMessage,
  5257. 'attempts' => $attempt
  5258. ]);
  5259. return [
  5260. 'task_id' => $taskId,
  5261. 'anime_id' => $animeId,
  5262. 'episode_id' => $episodeId,
  5263. 'segment_count' => count($generateJson),
  5264. 'generate_status' => '执行失败',
  5265. 'error_message' => $errorMessage
  5266. ];
  5267. }
  5268. }
  5269. // 超时处理
  5270. dLog('anime')->warning('视频合成任务超时', [
  5271. 'task_id' => $taskId,
  5272. 'max_attempts' => $maxAttempts,
  5273. 'timeout_seconds' => $maxAttempts * $pollInterval
  5274. ]);
  5275. // 更新任务状态为超时
  5276. DB::table('mp_complete_video_tasks')
  5277. ->where('id', $taskId)
  5278. ->update([
  5279. 'generate_status' => '超时',
  5280. 'error_message' => '任务执行超时(5分钟)',
  5281. 'updated_at' => date('Y-m-d H:i:s')
  5282. ]);
  5283. return [
  5284. 'task_id' => $taskId,
  5285. 'anime_id' => $animeId,
  5286. 'episode_id' => $episodeId,
  5287. 'segment_count' => count($generateJson),
  5288. 'generate_status' => '超时',
  5289. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5290. ];
  5291. }
  5292. /**
  5293. * 根据 inner_prompt_type 附加内置提示词
  5294. *
  5295. * @param string $prompt 用户提示词
  5296. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5297. * @return string 合并后的提示词
  5298. */
  5299. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5300. {
  5301. $innerPromptMap = [
  5302. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  5303. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5304. ];
  5305. if (!isset($innerPromptMap[$innerPromptType])) {
  5306. return $prompt;
  5307. }
  5308. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5309. }
  5310. /**
  5311. * 根据 inner_prompt_type 获取生成图片数量
  5312. *
  5313. * @param int $innerPromptType 内置提示词类型
  5314. * @param int $imageNum 传入的图片张数
  5315. * @return int 图片数量
  5316. */
  5317. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5318. {
  5319. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5320. }
  5321. /**
  5322. * 提取图片生成结果URL
  5323. *
  5324. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5325. * @param int $innerPromptType 内置提示词类型
  5326. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5327. */
  5328. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5329. {
  5330. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5331. if (is_array($resultUrls) && !empty($resultUrls)) {
  5332. $resultUrls = array_values($resultUrls);
  5333. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5334. }
  5335. if (!empty($resultUrl)) {
  5336. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5337. }
  5338. return (int)$innerPromptType === 2 ? [] : '';
  5339. }
  5340. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5341. $prompt = getProp($data, 'prompt');
  5342. $episode_id = getProp($data, 'episode_id');
  5343. $ref_img_urls = getProp($data, 'ref_img_urls');
  5344. $ratio = getProp($data, 'ratio', '9:16');
  5345. $resolution = getProp($data, 'resolution', '2k');
  5346. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5347. $imageNum = (int)getProp($data, 'image_num', 1);
  5348. // 定义分辨率和宽高比对应的尺寸映射表
  5349. $sizeMap = [
  5350. '2k' => [
  5351. '1:1' => ['width' => 2048, 'height' => 2048],
  5352. '4:3' => ['width' => 2304, 'height' => 1728],
  5353. '3:4' => ['width' => 1728, 'height' => 2304],
  5354. '16:9' => ['width' => 2848, 'height' => 1600],
  5355. '9:16' => ['width' => 1600, 'height' => 2848],
  5356. '3:2' => ['width' => 2496, 'height' => 1664],
  5357. '2:3' => ['width' => 1664, 'height' => 2496],
  5358. '21:9' => ['width' => 3136, 'height' => 1344],
  5359. ],
  5360. '3k' => [
  5361. '1:1' => ['width' => 3072, 'height' => 3072],
  5362. '4:3' => ['width' => 3456, 'height' => 2592],
  5363. '3:4' => ['width' => 2592, 'height' => 3456],
  5364. '16:9' => ['width' => 4096, 'height' => 2304],
  5365. '9:16' => ['width' => 2304, 'height' => 4096],
  5366. '2:3' => ['width' => 2496, 'height' => 3744],
  5367. '3:2' => ['width' => 3744, 'height' => 2496],
  5368. '21:9' => ['width' => 4704, 'height' => 2016],
  5369. ],
  5370. '4k' => [
  5371. '1:1' => ['width' => 4096, 'height' => 4096],
  5372. '3:4' => ['width' => 3520, 'height' => 4704],
  5373. '4:3' => ['width' => 4704, 'height' => 3520],
  5374. '16:9' => ['width' => 5504, 'height' => 3040],
  5375. '9:16' => ['width' => 3040, 'height' => 5504],
  5376. '2:3' => ['width' => 3328, 'height' => 4992],
  5377. '3:2' => ['width' => 4992, 'height' => 3328],
  5378. '21:9' => ['width' => 6240, 'height' => 2656],
  5379. ],
  5380. ];
  5381. // 参数验证
  5382. $resolution = strtolower($resolution);
  5383. if (!isset($sizeMap[$resolution])) {
  5384. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5385. }
  5386. if (!isset($sizeMap[$resolution][$ratio])) {
  5387. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5388. }
  5389. // 根据 ratio 和 resolution 确定宽高
  5390. $width = $sizeMap[$resolution][$ratio]['width'];
  5391. $height = $sizeMap[$resolution][$ratio]['height'];
  5392. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5393. if (is_json($ref_img_urls)) {
  5394. $ref_img_urls = json_decode($ref_img_urls, true);
  5395. }else {
  5396. $ref_img_urls = explode(',', $ref_img_urls);
  5397. }
  5398. }
  5399. // 处理图片模型
  5400. $model = getProp($data, 'model');
  5401. if (!$model) {
  5402. // 用户没有输入,从episode表获取
  5403. if ($episode_id) {
  5404. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5405. $model = getProp($episode, 'image_model');
  5406. }
  5407. if (!$model) {
  5408. // episode表也没有,使用默认值
  5409. $model = 'doubao-seedream-5-0-lite-260128';
  5410. }
  5411. }
  5412. // 验证模型是否在可用模型表中
  5413. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5414. // $model = 'doubao-seedream-5-0-lite-260128';
  5415. Utils::throwError('20003:该模型已不可用,请更换!');
  5416. }
  5417. // 保存到episode表
  5418. if ($episode_id) {
  5419. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5420. 'image_model' => $model,
  5421. 'updated_at' => date('Y-m-d H:i:s')
  5422. ]);
  5423. }
  5424. // 参数验证
  5425. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5426. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5427. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5428. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5429. try {
  5430. // 创建图片生成任务
  5431. $params = [
  5432. 'prompt' => $prompt,
  5433. 'model' => $model,
  5434. 'ref_img_urls' => '',
  5435. 'width' => $width,
  5436. 'height' => $height,
  5437. 'image_num' => $imageNum
  5438. ];
  5439. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5440. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5441. $task_id = $task->id;
  5442. if (!$task_id) {
  5443. Utils::throwError('20003:创建图片生成任务失败');
  5444. }
  5445. // 创建任务中心记录并关联图片任务ID
  5446. $taskCenter = $this->taskCenterService->createTask('image', [
  5447. 'title' => '文生图',
  5448. 'ref_task_id' => $task_id,
  5449. // 'prompt' => $prompt,
  5450. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5451. ]);
  5452. $taskCenterId = $taskCenter->id;
  5453. // 组装本次任务信息(用于init消息,类似generateVideo)
  5454. $taskInfo = [
  5455. 'task_id' => $task_id,
  5456. 'status' => getProp($task, 'status', 'processing'),
  5457. 'model' => $model,
  5458. 'ratio' => $ratio,
  5459. 'resolution' => $resolution,
  5460. 'image_num' => $imageNum,
  5461. ];
  5462. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5463. if (is_callable($onTaskCreated)) {
  5464. $onTaskCreated($taskCenterId, $taskInfo);
  5465. }
  5466. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5467. $model = getProp($task, 'model');
  5468. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5469. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5470. $isSyncModel = $isVolcModel || $isGptModel;
  5471. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5472. $start_time = time();
  5473. $timeout = 300; // 5分钟
  5474. $img_url = '';
  5475. $img_urls = [];
  5476. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5477. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5478. while (time() - $start_time < $timeout) {
  5479. sleep(3);
  5480. // 每分钟发送一次队列状态消息(仅流式模式)
  5481. if (is_callable($onPoll)) {
  5482. $currentTime = time();
  5483. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5484. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5485. $lastQueueMessageTime = $currentTime;
  5486. }
  5487. }
  5488. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5489. if ($isSyncModel) {
  5490. // 刷新任务状态
  5491. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5492. if ($task->status === 'success' && $task->result_url) {
  5493. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5494. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5495. if (!empty($resultUrls)) {
  5496. $img_urls = $resultUrls;
  5497. $img_url = $resultUrls[0];
  5498. } else {
  5499. $img_url = (string)$task->result_url;
  5500. }
  5501. break;
  5502. } elseif ($task->status === 'failed') {
  5503. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5504. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5505. }
  5506. // // 如果还在处理中,提示用户稍后查看
  5507. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5508. }else {
  5509. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5510. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5511. if ($statusInfo['status'] === 'success') {
  5512. $task->updateStatus('success', [
  5513. 'result_url' => $statusInfo['result_url'],
  5514. 'result_json' => $statusInfo['result_json'] ?? []
  5515. ]);
  5516. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5517. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5518. if (!empty($resultUrls)) {
  5519. $img_urls = $resultUrls;
  5520. $img_url = $resultUrls[0];
  5521. } else {
  5522. $img_url = (string)$statusInfo['result_url'];
  5523. }
  5524. break;
  5525. } elseif ($statusInfo['status'] === 'failed') {
  5526. $task->updateStatus('failed', [
  5527. 'error_message' => $statusInfo['error_message'],
  5528. 'result_json' => $statusInfo['result_json'] ?? []
  5529. ]);
  5530. dLog('anime')->error('图片生成失败,', [
  5531. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5532. ]);
  5533. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5534. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5535. }
  5536. }
  5537. }
  5538. if (empty($img_url)) {
  5539. Utils::throwError('20003:图片生成超时,请稍后重试');
  5540. }
  5541. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5542. if (count($img_urls) > 1) {
  5543. return [
  5544. 'img_url' => $img_url,
  5545. 'image_urls' => $img_urls,
  5546. 'task_id' => $taskCenterId,
  5547. ];
  5548. }
  5549. return [
  5550. 'img_url' => $img_url,
  5551. 'task_id' => $taskCenterId,
  5552. ];
  5553. } catch (\Exception $e) {
  5554. dLog('anime')->error('更新角色或场景失败', [
  5555. 'error' => $e->getMessage()
  5556. ]);
  5557. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5558. Utils::throwError('20003:' . $e->getMessage());
  5559. }
  5560. }
  5561. /**
  5562. * 使用文生文模型解析分镜内容
  5563. */
  5564. private function parseSegmentContentWithAI($segment_content) {
  5565. try {
  5566. // 使用DeepSeek服务的公开方法解析分镜内容
  5567. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5568. } catch (\Exception $e) {
  5569. // 如果AI解析失败,记录日志并返回原内容
  5570. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5571. return $segment_content;
  5572. }
  5573. }
  5574. /**
  5575. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5576. *
  5577. * @param int $episode_id 分集ID
  5578. * @param int $anime_id 动漫ID
  5579. * @param array $roles 分集角色数组(引用传递)
  5580. * @param array $scenes 分集场景数组(引用传递)
  5581. * @param array $episode 分集数据
  5582. */
  5583. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5584. // 获取全局动漫的角色和场景数据
  5585. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5586. if (!$anime) return;
  5587. $art_style_type = getProp($anime, 'art_style_type');
  5588. $character_prefix = '';
  5589. $scene_prefix = '';
  5590. if ($art_style_type) {
  5591. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5592. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5593. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5594. }
  5595. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5596. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5597. $roles_updated = false;
  5598. $scenes_updated = false;
  5599. // 处理角色
  5600. foreach ($roles as &$role) {
  5601. $role_name = getProp($role, 'role');
  5602. $role_description = getProp($role, 'description');
  5603. $role_pic_prompt = getProp($role, 'pic_prompt');
  5604. $role_url = getProp($role, 'url');
  5605. $role_task_id = getProp($role, 'task_id');
  5606. // 如果已有URL或已有任务ID,跳过
  5607. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5608. continue;
  5609. }
  5610. $url_inherited = false;
  5611. // 尝试从全局数据中继承
  5612. foreach ($global_roles as $global_role) {
  5613. $global_role_name = getProp($global_role, 'role');
  5614. $global_role_description = getProp($global_role, 'description');
  5615. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5616. $global_role_url = getProp($global_role, 'url');
  5617. $global_role_task_id = getProp($global_role, 'task_id');
  5618. $global_role_task_status = getProp($global_role, 'task_status');
  5619. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5620. if ($role_name === $global_role_name
  5621. && $role_description === $global_role_description
  5622. && $role_pic_prompt === $global_role_pic_prompt
  5623. && !empty($global_role_url)) {
  5624. // 继承 task_id、task_status 和 url
  5625. $role['task_id'] = $global_role_task_id;
  5626. $role['task_status'] = $global_role_task_status;
  5627. $role['url'] = $global_role_url;
  5628. $roles_updated = true;
  5629. $url_inherited = true;
  5630. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5631. break;
  5632. }
  5633. }
  5634. // 如果无法继承且没有任务ID,创建新任务
  5635. if (!$url_inherited && empty($role_task_id)) {
  5636. try {
  5637. $art_style = getProp($episode, 'art_style');
  5638. // 优先使用 pic_prompt,如果没有则使用 description
  5639. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5640. // if ($art_style) {
  5641. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5642. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5643. // }
  5644. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5645. $params = [
  5646. 'prompt' => $description,
  5647. 'ref_img_urls' => []
  5648. ];
  5649. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5650. $task_id = $task->id;
  5651. if ($task_id) {
  5652. $role['task_id'] = $task_id;
  5653. $role['task_status'] = 'processing';
  5654. $roles_updated = true;
  5655. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5656. }
  5657. } catch (\Exception $e) {
  5658. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5659. }
  5660. }
  5661. }
  5662. // 处理场景
  5663. foreach ($scenes as &$scene) {
  5664. $scene_name = getProp($scene, 'scene');
  5665. $scene_description = getProp($scene, 'description');
  5666. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5667. $scene_url = getProp($scene, 'url');
  5668. $scene_task_id = getProp($scene, 'task_id');
  5669. // 如果已有URL或已有任务ID,跳过
  5670. if (!empty($scene_url) || !empty($scene_task_id)) {
  5671. continue;
  5672. }
  5673. $url_inherited = false;
  5674. // 尝试从全局数据中继承
  5675. foreach ($global_scenes as $global_scene) {
  5676. $global_scene_name = getProp($global_scene, 'scene');
  5677. $global_scene_description = getProp($global_scene, 'description');
  5678. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5679. $global_scene_url = getProp($global_scene, 'url');
  5680. $global_scene_task_id = getProp($global_scene, 'task_id');
  5681. $global_scene_task_status = getProp($global_scene, 'task_status');
  5682. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5683. if ($scene_name === $global_scene_name
  5684. && $scene_description === $global_scene_description
  5685. && $scene_pic_prompt === $global_scene_pic_prompt
  5686. && !empty($global_scene_url)) {
  5687. // 继承 task_id、task_status 和 url
  5688. $scene['task_id'] = $global_scene_task_id;
  5689. $scene['task_status'] = $global_scene_task_status;
  5690. $scene['url'] = $global_scene_url;
  5691. $scenes_updated = true;
  5692. $url_inherited = true;
  5693. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5694. break;
  5695. }
  5696. }
  5697. // 如果无法继承且没有任务ID,创建新任务
  5698. if (!$url_inherited && empty($scene_task_id)) {
  5699. try {
  5700. $art_style = getProp($episode, 'art_style');
  5701. // 优先使用 pic_prompt,如果没有则使用 description
  5702. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5703. // if ($art_style) {
  5704. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5705. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5706. // }
  5707. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5708. $params = [
  5709. 'prompt' => $description,
  5710. 'ref_img_urls' => []
  5711. ];
  5712. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5713. $task_id = $task->id;
  5714. if ($task_id) {
  5715. $scene['task_id'] = $task_id;
  5716. $scene['task_status'] = 'processing';
  5717. $scenes_updated = true;
  5718. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5719. }
  5720. } catch (\Exception $e) {
  5721. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5722. }
  5723. }
  5724. }
  5725. // 如果有更新,保存到数据库
  5726. if ($roles_updated || $scenes_updated) {
  5727. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5728. if ($roles_updated) {
  5729. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5730. }
  5731. if ($scenes_updated) {
  5732. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5733. }
  5734. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5735. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5736. }
  5737. }
  5738. /**
  5739. * 根据图片URL使用AI反推图片提示词
  5740. *
  5741. * @param string $img_url 图片URL
  5742. * @return string 反推的提示词
  5743. */
  5744. private function generateImagePromptFromUrl($img_url) {
  5745. try {
  5746. // 获取默认模型
  5747. $model = 'doubao-seed-2-0-mini-260215';
  5748. // 构建messages参数
  5749. $messages = [
  5750. [
  5751. 'role' => 'user',
  5752. 'content' => [
  5753. [
  5754. 'type' => 'text',
  5755. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5756. ],
  5757. [
  5758. 'type' => 'image_url',
  5759. 'image_url' => [
  5760. 'url' => $img_url
  5761. ]
  5762. ]
  5763. ]
  5764. ]
  5765. ];
  5766. // 构建请求参数
  5767. $params = [
  5768. 'model' => $model,
  5769. 'messages' => $messages,
  5770. 'stream' => false,
  5771. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5772. ];
  5773. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5774. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5775. // 仅记录 token 使用明细(不扣积分)
  5776. $uid = 0;
  5777. try {
  5778. $uid = (int)Site::getUid();
  5779. } catch (\Throwable $e) {
  5780. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5781. }
  5782. $this->pointsService->recordTokenOnlyDetail(
  5783. $uid,
  5784. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5785. [
  5786. 'model' => $model,
  5787. 'img_url' => $img_url,
  5788. 'source' => 'generateImagePromptFromUrl',
  5789. ],
  5790. 'chat',
  5791. $model,
  5792. ''
  5793. );
  5794. // 返回生成的内容
  5795. return getProp($result, 'fullContent', '图片描述生成失败');
  5796. } catch (\Exception $e) {
  5797. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5798. 'img_url' => $img_url
  5799. ]);
  5800. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5801. 'error' => $e->getMessage(),
  5802. 'img_url' => $img_url
  5803. ]);
  5804. return '图片描述生成失败: ' . $e->getMessage();
  5805. }
  5806. }
  5807. /**
  5808. * 音频试听接口
  5809. * 创建音频任务并轮询获取结果
  5810. *
  5811. * @param array $data 参数数组
  5812. * @return array 返回音频URL或错误信息
  5813. */
  5814. public function previewAudio($data) {
  5815. $dialogue = getProp($data, 'dialogue');
  5816. // 必填参数验证
  5817. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5818. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5819. $voice_type = getProp($data, 'voice_type');
  5820. $voice_name = getProp($data, 'voice_name');
  5821. $voice_actor = getProp($data, 'voice_actor');
  5822. $emotion_type = getProp($data, 'emotion_type');
  5823. $gender = getProp($data, 'gender', 0);
  5824. $emotion = getProp($data, 'emotion');
  5825. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5826. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5827. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5828. $pitch = getProp($data, 'pitch', 0);
  5829. try {
  5830. $now = date('Y-m-d H:i:s');
  5831. // 构建生成参数
  5832. $generate_json = json_encode([
  5833. 'text' => $dialogue,
  5834. 'role' => $voice_actor,
  5835. 'voice_type' => $voice_type,
  5836. 'voice_name' => $voice_name,
  5837. 'emotion' => $emotion,
  5838. 'emotion_type' => $emotion_type,
  5839. 'gender' => $gender,
  5840. 'speed_ratio' => $speed_ratio,
  5841. 'loudness_ratio' => $loudness_ratio,
  5842. 'emotion_scale' => $emotion_scale,
  5843. 'pitch' => $pitch,
  5844. ], 256);
  5845. // 请求远程服务器执行生成
  5846. $client = new Client(['timeout' => 600, 'verify' => false]);
  5847. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5848. $response = $result->getBody()->getContents();
  5849. $response_arr = json_decode($response, true);
  5850. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5851. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5852. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5853. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5854. }
  5855. $arr = $response_arr['data'];
  5856. $subtitle_info = $arr['subtitle_info'];
  5857. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5858. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5859. return [
  5860. 'audio_url' => $arr['url'],
  5861. 'subtitle_info' => $subtitle_info,
  5862. 'audio_duration' => round($audio_duration, 2)
  5863. ];
  5864. } catch (\Exception $e) {
  5865. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5866. Utils::throwError('20003:' . $e->getMessage());
  5867. }
  5868. }
  5869. /**
  5870. * 获取角色库列表(支持文件夹递归查询)
  5871. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5872. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5873. */
  5874. public function globalProducts($data) {
  5875. $uid = Site::getUid();
  5876. $cpid = Site::getCpid();
  5877. $role = Site::getRole();
  5878. $id = getProp($data, 'id', 0);
  5879. $parent_id = getProp($data, 'parent_id', 0);
  5880. $product_name = getProp($data, 'product_name');
  5881. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5882. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5883. if (!$product) {
  5884. Utils::throwError('20003:请选择产品类型');
  5885. }
  5886. // 根据角色和is_public参数确定查询范围
  5887. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5888. // user角色:根据is_public参数筛选
  5889. $query_user_ids = [];
  5890. if ($role === 'admin') {
  5891. // admin获取所有个人库和公共库
  5892. $query_user_ids = [$uid, 0];
  5893. } else {
  5894. // user角色根据is_public参数筛选
  5895. if ($is_public == 2) {
  5896. // 个人库+公共库
  5897. $query_user_ids = [$uid, 0];
  5898. } elseif ($is_public == 0) {
  5899. // 仅个人库
  5900. $query_user_ids = [$uid];
  5901. } elseif ($is_public == 1) {
  5902. // 仅公共库
  5903. $query_user_ids = [0];
  5904. }
  5905. }
  5906. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5907. if ($id || $product_name) {
  5908. $query = DB::table('mp_products')
  5909. ->where('cpid', $cpid)
  5910. ->whereIn('user_id', $query_user_ids)
  5911. ->where('is_deleted', 0);
  5912. // 如果指定了 id,按 id 精确查询
  5913. if ($id) {
  5914. $query->where('id', $id);
  5915. }
  5916. // 如果指定了 product_name,按名称模糊查询
  5917. if ($product_name) {
  5918. $query->where('product_name', 'like', "%{$product_name}%");
  5919. }
  5920. // 如果指定了 product,添加筛选条件
  5921. if ($product) {
  5922. $query->where('product', $product);
  5923. }
  5924. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5925. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5926. ->get()
  5927. ->map(function($value) {
  5928. $value = (array)$value;
  5929. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5930. $value['type'] = (int)$value['type'];
  5931. $value['parent_id'] = (int)$value['parent_id'];
  5932. $value['level'] = (int)$value['level'];
  5933. $value['product'] = (int)($value['product'] ?? 1);
  5934. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5935. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5936. unset($value['user_id']);
  5937. return $value;
  5938. })
  5939. ->toArray();
  5940. return $result;
  5941. }
  5942. // 递归获取所有子目录和角色
  5943. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5944. }
  5945. /**
  5946. * 递归获取指定目录下的所有子目录和角色
  5947. * @param int $cpid 公司ID
  5948. * @param int $parent_id 父目录ID
  5949. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5950. * @param array $query_user_ids 用户ID数组(支持多个)
  5951. * @param int $current_uid 当前用户ID(用于排序)
  5952. * @return array
  5953. */
  5954. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5955. // 查询当前层级的所有项(文件夹和角色)
  5956. $query = DB::table('mp_products')
  5957. ->where('cpid', $cpid)
  5958. ->where('is_deleted', 0)
  5959. ->where('parent_id', $parent_id);
  5960. // 添加用户ID验证(支持多个user_id)
  5961. if (!empty($query_user_ids)) {
  5962. $query->whereIn('user_id', $query_user_ids);
  5963. }
  5964. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5965. if ($product) {
  5966. $query->where('product', $product);
  5967. }
  5968. // 排序规则:
  5969. // 1. 文件夹在前(type DESC)
  5970. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5971. // 3. 其他排序规则
  5972. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5973. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5974. ->get();
  5975. $result = [];
  5976. foreach ($items as $item) {
  5977. $itemArray = [
  5978. 'id' => $item->id,
  5979. 'type' => (int)$item->type,
  5980. 'parent_id' => (int)$item->parent_id,
  5981. 'level' => (int)$item->level,
  5982. 'product_name' => $item->product_name,
  5983. 'url' => $item->url,
  5984. 'pic_prompt' => $item->pic_prompt ?? '',
  5985. 'three_view_image_url' => $item->three_view_image_url,
  5986. 'product' => (int)($item->product ?? 1),
  5987. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5988. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5989. ];
  5990. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5991. // 如果是文件夹,递归获取其子项
  5992. if ($item->type == 2) {
  5993. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5994. if (!empty($children)) {
  5995. $itemArray['children'] = $children;
  5996. }
  5997. }
  5998. $result[] = $itemArray;
  5999. }
  6000. return $result;
  6001. }
  6002. /**
  6003. * 创建文件夹
  6004. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  6005. * @return int 返回新建文件夹ID
  6006. */
  6007. public function createFolder($data) {
  6008. $uid = Site::getUid();
  6009. $cpid = Site::getCpid();
  6010. $role = Site::getRole();
  6011. $parent_id = getProp($data, 'parent_id', 0);
  6012. $folder_name = getProp($data, 'product_name', '新建文件夹');
  6013. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6014. // 如果是公共库操作,需要admin权限
  6015. if ($is_public && $role !== 'admin') {
  6016. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6017. }
  6018. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6019. $store_uid = $is_public ? 0 : $uid;
  6020. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6021. $product = getProp($data, 'product');
  6022. if (!in_array($product, [1, 2, 3])) {
  6023. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  6024. }
  6025. // 验证父文件夹
  6026. $parent_level = 0;
  6027. if ($parent_id > 0) {
  6028. $parent = DB::table('mp_products')
  6029. ->where('id', $parent_id)
  6030. ->where('cpid', $cpid)
  6031. ->where('user_id', $store_uid)
  6032. ->where('type', 2)
  6033. ->where('is_deleted', 0)
  6034. ->first();
  6035. if (!$parent) {
  6036. Utils::throwError('20003:父文件夹不存在');
  6037. }
  6038. // 检查父文件夹的 product 类型是否一致
  6039. if ($parent->product != $product) {
  6040. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  6041. }
  6042. $parent_level = $parent->level;
  6043. // 检查层级限制(最多3层)
  6044. if ($parent_level >= 3) {
  6045. Utils::throwError('20003:文件夹层级不能超过3层');
  6046. }
  6047. }
  6048. // 检查当前目录下是否已存在空白文件夹
  6049. $empty_folder_exists = DB::table('mp_products')
  6050. ->where('parent_id', $parent_id)
  6051. ->where('cpid', $cpid)
  6052. ->where('user_id', $store_uid)
  6053. ->where('type', 2)
  6054. ->where('product', $product)
  6055. ->where('product_name', '新建文件夹')
  6056. ->where('is_deleted', 0)
  6057. ->exists();
  6058. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  6059. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  6060. }
  6061. // 创建文件夹
  6062. $folder_id = DB::table('mp_products')->insertGetId([
  6063. 'user_id' => $store_uid,
  6064. 'cpid' => $cpid,
  6065. 'type' => 2,
  6066. 'parent_id' => $parent_id,
  6067. 'level' => $parent_level + 1,
  6068. 'product_name' => $folder_name,
  6069. 'product' => $product,
  6070. 'sort_order' => time(), // 使用时间戳作为排序权重
  6071. 'is_deleted' => 0,
  6072. 'created_at' => date('Y-m-d H:i:s'),
  6073. 'updated_at' => date('Y-m-d H:i:s')
  6074. ]);
  6075. return [
  6076. 'id' => $folder_id,
  6077. 'type' => 2,
  6078. 'parent_id' => $parent_id,
  6079. 'level' => $parent_level + 1,
  6080. 'product_name' => $folder_name,
  6081. 'product' => $product,
  6082. ];
  6083. }
  6084. /**
  6085. * 重命名文件夹或角色
  6086. * @param array $data 包含 id、product_name(新名称)
  6087. * @return bool
  6088. */
  6089. public function renameFolder($data) {
  6090. $uid = Site::getUid();
  6091. $cpid = Site::getCpid();
  6092. $role = Site::getRole();
  6093. $id = getProp($data, 'id');
  6094. $new_name = getProp($data, 'product_name');
  6095. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6096. if (!$id || !$new_name) {
  6097. Utils::throwError('20003:参数不完整');
  6098. }
  6099. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6100. $query_uid = $is_public ? 0 : $uid;
  6101. // 如果是公共库操作,需要admin权限
  6102. if ($is_public && $role !== 'admin') {
  6103. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6104. }
  6105. // 检查是否存在
  6106. $item = DB::table('mp_products')
  6107. ->where('id', $id)
  6108. ->where('cpid', $cpid)
  6109. ->where('user_id', $query_uid)
  6110. ->where('is_deleted', 0)
  6111. ->first();
  6112. if (!$item) {
  6113. Utils::throwError('20003:项目不存在');
  6114. }
  6115. return DB::table('mp_products')
  6116. ->where('id', $id)
  6117. ->where('cpid', $cpid)
  6118. ->where('user_id', $query_uid)
  6119. ->update([
  6120. 'product_name' => $new_name,
  6121. 'updated_at' => date('Y-m-d H:i:s')
  6122. ]);
  6123. }
  6124. /**
  6125. * 移动角色或文件夹到指定文件夹
  6126. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6127. * @return bool
  6128. */
  6129. public function moveProductOrFolder($data) {
  6130. $uid = Site::getUid();
  6131. $cpid = Site::getCpid();
  6132. $role = Site::getRole();
  6133. $id = getProp($data, 'id');
  6134. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6135. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6136. if (!$id) {
  6137. Utils::throwError('20003:请选择要移动的项目');
  6138. }
  6139. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6140. $query_uid = $is_public ? 0 : $uid;
  6141. // 如果是公共库操作,需要admin权限
  6142. if ($is_public && $role !== 'admin') {
  6143. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6144. }
  6145. // 检查要移动的项目
  6146. $item = DB::table('mp_products')
  6147. ->where('id', $id)
  6148. ->where('cpid', $cpid)
  6149. ->where('user_id', $query_uid)
  6150. ->where('is_deleted', 0)
  6151. ->first();
  6152. if (!$item) {
  6153. Utils::throwError('20003:项目不存在');
  6154. }
  6155. // 验证目标文件夹
  6156. $target_level = 0;
  6157. $target_product = $item->product; // 默认使用当前项目的 product
  6158. if ($target_parent_id > 0) {
  6159. $target_parent = DB::table('mp_products')
  6160. ->where('id', $target_parent_id)
  6161. ->where('cpid', $cpid)
  6162. ->where('user_id', $query_uid)
  6163. ->where('type', 2)
  6164. ->where('is_deleted', 0)
  6165. ->first();
  6166. if (!$target_parent) {
  6167. Utils::throwError('20003:目标文件夹不存在');
  6168. }
  6169. // 检查 product 类型是否一致
  6170. if ($target_parent->product != $item->product) {
  6171. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6172. }
  6173. $target_level = $target_parent->level;
  6174. $target_product = $target_parent->product;
  6175. // 如果移动的是文件夹,需要检查层级
  6176. if ($item->type == 2) {
  6177. // 计算移动后的最大层级
  6178. $max_child_level = $this->getMaxChildLevel($id);
  6179. $depth = $max_child_level - $item->level;
  6180. if ($target_level + 1 + $depth > 3) {
  6181. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6182. }
  6183. // 不能移动到自己或自己的子文件夹下
  6184. if ($this->isDescendant($target_parent_id, $id)) {
  6185. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6186. }
  6187. }
  6188. }
  6189. // 更新父文件夹和层级
  6190. $new_level = $target_level + 1;
  6191. DB::table('mp_products')
  6192. ->where('id', $id)
  6193. ->update([
  6194. 'parent_id' => $target_parent_id,
  6195. 'level' => $new_level,
  6196. 'updated_at' => date('Y-m-d H:i:s')
  6197. ]);
  6198. // 如果是文件夹,需要递归更新所有子项的层级
  6199. if ($item->type == 2) {
  6200. $this->updateChildrenLevel($id, $new_level);
  6201. }
  6202. return true;
  6203. }
  6204. /**
  6205. * 获取文件夹下最大子层级
  6206. * @param int $folder_id
  6207. * @return int
  6208. */
  6209. private function getMaxChildLevel($folder_id) {
  6210. $max_level = DB::table('mp_products')
  6211. ->where('parent_id', $folder_id)
  6212. ->where('is_deleted', 0)
  6213. ->max('level');
  6214. if (!$max_level) {
  6215. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6216. }
  6217. // 递归查找子文件夹
  6218. $children = DB::table('mp_products')
  6219. ->where('parent_id', $folder_id)
  6220. ->where('type', 2)
  6221. ->where('is_deleted', 0)
  6222. ->pluck('id');
  6223. foreach ($children as $child_id) {
  6224. $child_max = $this->getMaxChildLevel($child_id);
  6225. if ($child_max > $max_level) {
  6226. $max_level = $child_max;
  6227. }
  6228. }
  6229. return $max_level;
  6230. }
  6231. /**
  6232. * 检查 target_id 是否是 folder_id 的后代
  6233. * @param int $target_id
  6234. * @param int $folder_id
  6235. * @return bool
  6236. */
  6237. private function isDescendant($target_id, $folder_id) {
  6238. if ($target_id == $folder_id) {
  6239. return true;
  6240. }
  6241. $parent = DB::table('mp_products')
  6242. ->where('id', $target_id)
  6243. ->where('is_deleted', 0)
  6244. ->first();
  6245. if (!$parent || $parent->parent_id == 0) {
  6246. return false;
  6247. }
  6248. return $this->isDescendant($parent->parent_id, $folder_id);
  6249. }
  6250. /**
  6251. * 递归更新子项层级
  6252. * @param int $parent_id
  6253. * @param int $parent_level
  6254. */
  6255. private function updateChildrenLevel($parent_id, $parent_level) {
  6256. $children = DB::table('mp_products')
  6257. ->where('parent_id', $parent_id)
  6258. ->where('is_deleted', 0)
  6259. ->get();
  6260. foreach ($children as $child) {
  6261. $new_level = $parent_level + 1;
  6262. DB::table('mp_products')
  6263. ->where('id', $child->id)
  6264. ->update([
  6265. 'level' => $new_level,
  6266. 'updated_at' => date('Y-m-d H:i:s')
  6267. ]);
  6268. // 如果是文件夹,继续递归
  6269. if ($child->type == 2) {
  6270. $this->updateChildrenLevel($child->id, $new_level);
  6271. }
  6272. }
  6273. }
  6274. /**
  6275. * 获取文件夹路径(面包屑导航)
  6276. * @param array $data 包含 folder_id
  6277. * @return array 返回路径数组
  6278. */
  6279. public function getFolderPath($data) {
  6280. $uid = Site::getUid();
  6281. $cpid = Site::getCpid();
  6282. $folder_id = getProp($data, 'id', 0);
  6283. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6284. if ($folder_id == 0) {
  6285. return [
  6286. ['id' => 0, 'name' => '根目录']
  6287. ];
  6288. }
  6289. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6290. $query_uid = $is_public ? 0 : $uid;
  6291. $path = [];
  6292. $current_id = $folder_id;
  6293. while ($current_id > 0) {
  6294. $folder = DB::table('mp_products')
  6295. ->where('id', $current_id)
  6296. ->where('cpid', $cpid)
  6297. ->where('user_id', $query_uid)
  6298. ->where('type', 2)
  6299. ->where('is_deleted', 0)
  6300. ->first();
  6301. if (!$folder) {
  6302. break;
  6303. }
  6304. array_unshift($path, [
  6305. 'id' => $folder->id,
  6306. 'name' => $folder->product_name
  6307. ]);
  6308. $current_id = $folder->parent_id;
  6309. }
  6310. // 添加根目录
  6311. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6312. return $path;
  6313. }
  6314. public function createProduct($data) {
  6315. $uid = Site::getUid();
  6316. $cpid = Site::getCpid();
  6317. $role = Site::getRole();
  6318. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6319. // 如果是公共库操作,需要admin权限
  6320. if ($is_public && $role !== 'admin') {
  6321. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6322. }
  6323. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6324. $store_uid = $is_public ? 0 : $uid;
  6325. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6326. $script_id = (int)getProp($data, 'script_id', 0);
  6327. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6328. if ($script_id && empty($episode_numbers)) {
  6329. Utils::throwError('20003:剧集序号不能为空');
  6330. }
  6331. if (!$script_id && !empty($episode_numbers)) {
  6332. Utils::throwError('20003:请提供剧本ID');
  6333. }
  6334. $product_name = trim(getProp($data, 'product_name'));
  6335. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6336. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6337. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6338. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6339. $url = trim(getProp($data, 'url'));
  6340. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6341. $versions = getProp($data, 'versions');
  6342. // 检查是否是正确的图片格式
  6343. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6344. $urlPath = parse_url($url, PHP_URL_PATH);
  6345. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6346. if (!in_array($extension, $allowedExtensions)) {
  6347. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6348. }
  6349. // 选填三视图图片地址,格式校验与 url 一致
  6350. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6351. if ($three_view_image_url) {
  6352. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6353. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6354. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6355. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6356. }
  6357. }
  6358. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6359. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6360. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6361. $product = getProp($data, 'product');
  6362. if (!in_array($product, [1, 2, 3])) {
  6363. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6364. }
  6365. // 获取父文件夹ID和层级
  6366. $parent_id = getProp($data, 'parent_id', 0);
  6367. $parent_level = 0;
  6368. if ($parent_id > 0) {
  6369. $parent = DB::table('mp_products')
  6370. ->where('id', $parent_id)
  6371. ->where('cpid', $cpid)
  6372. ->where('user_id', $store_uid)
  6373. ->where('type', 2)
  6374. ->where('is_deleted', 0)
  6375. ->first();
  6376. if (!$parent) {
  6377. Utils::throwError('20003:父文件夹不存在');
  6378. }
  6379. $parent_level = $parent->level;
  6380. }
  6381. // 创建资产并保存剧本资产关联关系(同一事务)
  6382. DB::beginTransaction();
  6383. try {
  6384. $id = DB::table('mp_products')->insertGetId([
  6385. 'user_id' => $store_uid,
  6386. 'cpid' => $cpid,
  6387. 'type' => 1, // 1=角色图片
  6388. 'parent_id' => $parent_id,
  6389. 'level' => $parent_level + 1,
  6390. 'product_name' => $product_name,
  6391. 'url' => $url,
  6392. 'three_view_image_url' => $three_view_image_url,
  6393. 'pic_prompt' => $pic_prompt,
  6394. 'product' => $product,
  6395. 'versions' => json_encode($versions, 256),
  6396. 'sort_order' => time(), // 使用时间戳作为排序权重
  6397. 'created_at' => date('Y-m-d H:i:s'),
  6398. 'updated_at' => date('Y-m-d H:i:s')
  6399. ]);
  6400. if (!$id) Utils::throwError('20003:创建失败');
  6401. // 保存剧本资产关联关系
  6402. if ($script_id) {
  6403. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6404. }
  6405. DB::commit();
  6406. } catch (\Exception $e) {
  6407. DB::rollback();
  6408. throw $e;
  6409. }
  6410. return [
  6411. 'id' => $id,
  6412. 'type' => 1,
  6413. 'parent_id' => $parent_id,
  6414. 'level' => $parent_level + 1,
  6415. 'product_name' => $product_name,
  6416. 'url' => $url,
  6417. 'three_view_image_url' => $three_view_image_url,
  6418. 'pic_prompt' => $pic_prompt,
  6419. 'product' => $product,
  6420. 'versions' => $versions
  6421. ];
  6422. }
  6423. public function editProduct($data) {
  6424. $uid = Site::getUid();
  6425. $cpid = Site::getCpid();
  6426. $role = Site::getRole();
  6427. $id = getProp($data, 'id');
  6428. if (!$id) Utils::throwError('20003:ID不能为空');
  6429. $versions = getProp($data, 'versions');
  6430. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6431. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6432. $script_id = (int)getProp($data, 'script_id', 0);
  6433. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6434. if ($script_id && empty($episode_numbers)) {
  6435. Utils::throwError('20003:剧集序号不能为空');
  6436. }
  6437. if (!$script_id && !empty($episode_numbers)) {
  6438. Utils::throwError('20003:请提供剧本ID');
  6439. }
  6440. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6441. $query_uid = $is_public ? 0 : $uid;
  6442. // 如果是公共库操作,需要admin权限
  6443. if ($is_public && $role !== 'admin') {
  6444. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6445. }
  6446. // 检查是否存在且属于当前用户或公共库
  6447. $role = DB::table('mp_products')
  6448. ->where('id', $id)
  6449. ->where('cpid', $cpid)
  6450. ->where('user_id', $query_uid)
  6451. ->where('type', 1)->first();
  6452. if (!$role) Utils::throwError('20003:记录不存在');
  6453. $updateData = [];
  6454. // $needVersionRecord = false; // 是否需要记录版本
  6455. // 名称
  6456. $product_name = trim(getProp($data, 'product_name'));
  6457. if ($product_name) {
  6458. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6459. $updateData['product_name'] = $product_name;
  6460. }
  6461. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6462. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6463. // 图片地址
  6464. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6465. $url = trim(getProp($data, 'url'));
  6466. if ($url) {
  6467. // 检查是否是正确的图片格式
  6468. $urlPath = parse_url($url, PHP_URL_PATH);
  6469. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6470. if (!in_array($extension, $allowedExtensions)) {
  6471. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6472. }
  6473. // // 如果 url 有变更,记录版本
  6474. // if ($url !== $role->url) {
  6475. // $needVersionRecord = true;
  6476. // }
  6477. $updateData['url'] = $url;
  6478. }
  6479. // 三视图图片地址(选填),格式校验与 url 一致
  6480. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6481. if ($three_view_image_url) {
  6482. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6483. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6484. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6485. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6486. }
  6487. $updateData['three_view_image_url'] = $three_view_image_url;
  6488. }
  6489. // 提示词
  6490. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6491. if ($pic_prompt) {
  6492. // // 如果 pic_prompt 有变更,记录版本
  6493. // if ($pic_prompt !== $role->pic_prompt) {
  6494. // $needVersionRecord = true;
  6495. // }
  6496. $updateData['pic_prompt'] = $pic_prompt;
  6497. }
  6498. if (empty($updateData) && !$script_id) {
  6499. Utils::throwError('20003:没有需要更新的数据');
  6500. }
  6501. // // 如果需要记录版本,将数据添加到 versions 数组
  6502. // if ($needVersionRecord) {
  6503. // // 获取现有的 versions 数据
  6504. // $versions = json_decode($role->versions, true) ?: [];
  6505. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6506. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6507. // if ($isFirstVersion) {
  6508. // $oldVersion = [
  6509. // 'url' => $role->url,
  6510. // 'description' => $role->pic_prompt,
  6511. // ];
  6512. // // 旧版本添加到数组末尾
  6513. // $versions[] = $oldVersion;
  6514. // }
  6515. // // 构建新版本(变更后)
  6516. // $newVersion = [
  6517. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6518. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6519. // ];
  6520. // // 检查新版本是否已存在于历史版本中
  6521. // $existingIndex = -1;
  6522. // foreach ($versions as $index => $version) {
  6523. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6524. // $existingIndex = $index;
  6525. // break;
  6526. // }
  6527. // }
  6528. // if ($existingIndex !== -1) {
  6529. // // 如果已存在,移除旧的位置
  6530. // array_splice($versions, $existingIndex, 1);
  6531. // }
  6532. // // 新版本添加到数组开头(最新的在前)
  6533. // array_unshift($versions, $newVersion);
  6534. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6535. // // if (count($versions) > 10) {
  6536. // // $versions = array_slice($versions, 0, 10);
  6537. // // }
  6538. // $updateData['versions'] = json_encode($versions, 256);
  6539. // }
  6540. if ($versions) {
  6541. $updateData['versions'] = json_encode($versions, 256);
  6542. }
  6543. if (!empty($updateData)) {
  6544. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6545. }
  6546. // 更新资产并保存剧本资产关联关系(同一事务)
  6547. DB::beginTransaction();
  6548. try {
  6549. $updated = true;
  6550. if (!empty($updateData)) {
  6551. $updated = DB::table('mp_products')
  6552. ->where('cpid', $cpid)
  6553. ->where('id', $id)
  6554. ->update($updateData);
  6555. }
  6556. // 保存剧本资产关联关系
  6557. if ($script_id) {
  6558. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6559. }
  6560. DB::commit();
  6561. } catch (\Exception $e) {
  6562. DB::rollback();
  6563. throw $e;
  6564. }
  6565. return $updated;
  6566. }
  6567. /**
  6568. * 保存单一资产与剧本剧集的关联关系
  6569. *
  6570. * @param int $product_id 资产ID
  6571. * @param int $script_id 剧本ID
  6572. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6573. * @return int 新增关联数量
  6574. */
  6575. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6576. $uid = Site::getUid();
  6577. // 验证剧本是否存在
  6578. $script = DB::table('mp_scripts')
  6579. ->where('id', $script_id)
  6580. ->where('is_deleted', 0)
  6581. ->first();
  6582. if (!$script) {
  6583. Utils::throwError('20003:剧本不存在');
  6584. }
  6585. // 验证剧本归属:只能关联自己的剧本
  6586. if ((int)$script->user_id !== (int)$uid) {
  6587. Utils::throwError('20003:只能添加到自己的剧本');
  6588. }
  6589. // 使用 splitContent 拆分剧本内容获取总集数
  6590. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6591. // 解析剧集序号(数组)
  6592. $episodes = [];
  6593. foreach ($episode_numbers as $item) {
  6594. if (is_array($item)) {
  6595. continue;
  6596. }
  6597. $item = trim((string)$item);
  6598. if ($item === '' || !is_numeric($item)) {
  6599. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6600. }
  6601. $episodes[] = (int)$item;
  6602. }
  6603. // 去重并校验序号范围(序号从1开始)
  6604. $episodes = array_values(array_unique($episodes));
  6605. if (empty($episodes)) {
  6606. Utils::throwError('20003:剧集序号不能为空');
  6607. }
  6608. foreach ($episodes as $episode) {
  6609. if ($episode < 1 || $episode > $totalEpisodes) {
  6610. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6611. }
  6612. }
  6613. $now = now();
  6614. // 过滤已存在的关联,避免重复
  6615. $existingEpisodes = DB::table('mp_script_product_mappings')
  6616. ->where('script_id', $script_id)
  6617. ->where('product_id', $product_id)
  6618. ->whereIn('episode_number', $episodes)
  6619. ->pluck('episode_number')
  6620. ->all();
  6621. $mappingRecords = [];
  6622. foreach ($episodes as $episode) {
  6623. if (in_array($episode, $existingEpisodes)) {
  6624. continue;
  6625. }
  6626. $mappingRecords[] = [
  6627. 'script_id' => $script_id,
  6628. 'product_id' => $product_id,
  6629. 'episode_number' => $episode,
  6630. 'created_at' => $now,
  6631. 'updated_at' => $now,
  6632. ];
  6633. }
  6634. $insertedCount = 0;
  6635. if (!empty($mappingRecords)) {
  6636. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6637. }
  6638. return $insertedCount;
  6639. }
  6640. /**
  6641. * 规范化剧集序号参数,统一为数组
  6642. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6643. *
  6644. * @param mixed $episode_number 剧集序号参数
  6645. * @return array
  6646. */
  6647. private function normalizeEpisodeNumbers($episode_number) {
  6648. if (!is_array($episode_number)) {
  6649. $episode_number = explode(',', (string)$episode_number);
  6650. }
  6651. $items = [];
  6652. foreach ($episode_number as $item) {
  6653. if (is_array($item)) {
  6654. continue;
  6655. }
  6656. foreach (explode(',', (string)$item) as $part) {
  6657. $part = trim($part);
  6658. if ($part !== '') {
  6659. $items[] = $part;
  6660. }
  6661. }
  6662. }
  6663. return $items;
  6664. }
  6665. /**
  6666. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6667. *
  6668. * @param object $script 剧本记录
  6669. * @return int 总集数
  6670. */
  6671. private function getScriptTotalEpisodeCount($script) {
  6672. if (empty($script->content)) {
  6673. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6674. }
  6675. $totalEpisodes = count(splitContent($script->content));
  6676. if ($totalEpisodes < 1) {
  6677. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6678. }
  6679. return $totalEpisodes;
  6680. }
  6681. /**
  6682. * 获取剧本总集数
  6683. *
  6684. * @param array $data 包含 script_id(剧本ID)
  6685. * @return array
  6686. */
  6687. public function getScriptTotalEpisodes($data) {
  6688. $script_id = (int)getProp($data, 'script_id', 0);
  6689. if (!$script_id) {
  6690. Utils::throwError('20003:请提供剧本ID');
  6691. }
  6692. // 验证剧本是否存在
  6693. $script = DB::table('mp_scripts')
  6694. ->where('id', $script_id)
  6695. ->where('is_deleted', 0)
  6696. ->first();
  6697. if (!$script) {
  6698. Utils::throwError('20003:剧本不存在');
  6699. }
  6700. return [
  6701. 'script_id' => $script_id,
  6702. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6703. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6704. ];
  6705. }
  6706. /**
  6707. * 获取角色版本历史
  6708. * @param array $data 包含 id(角色ID)
  6709. * @return array 返回版本历史列表
  6710. */
  6711. public function getProductVersions($data) {
  6712. $cpid = Site::getCpid();
  6713. $id = getProp($data, 'id');
  6714. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6715. $role = DB::table('mp_products')
  6716. ->where('id', $id)
  6717. ->where('cpid', $cpid)
  6718. ->where('type', 1)
  6719. ->first();
  6720. if (!$role) Utils::throwError('20003:角色不存在');
  6721. // 获取版本历史
  6722. $versions = json_decode($role->versions, true) ?: [];
  6723. // 添加当前版本作为最新版本
  6724. $currentVersion = [
  6725. 'version' => 0, // 0 表示当前版本
  6726. 'url' => $role->url,
  6727. 'pic_prompt' => $role->pic_prompt,
  6728. 'updated_at' => $role->updated_at,
  6729. 'is_current' => true
  6730. ];
  6731. array_unshift($versions, $currentVersion);
  6732. return $versions;
  6733. }
  6734. /**
  6735. * 恢复到指定版本
  6736. * @param array $data 包含 id(角色ID)、version(版本号)
  6737. * @return bool
  6738. */
  6739. public function restoreProductVersion($data) {
  6740. $uid = Site::getUid();
  6741. $cpid = Site::getCpid();
  6742. $id = getProp($data, 'id');
  6743. $version = getProp($data, 'version');
  6744. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6745. if (!$version) Utils::throwError('20003:版本号不能为空');
  6746. $role = DB::table('mp_products')
  6747. ->where('id', $id)
  6748. ->where('cpid', $cpid)
  6749. ->where('type', 1)
  6750. ->first();
  6751. if (!$role) Utils::throwError('20003:角色不存在');
  6752. // 获取版本历史
  6753. $versions = json_decode($role->versions, true) ?: [];
  6754. // 查找指定版本
  6755. $targetVersion = null;
  6756. foreach ($versions as $v) {
  6757. if ($v['version'] == $version) {
  6758. $targetVersion = $v;
  6759. break;
  6760. }
  6761. }
  6762. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6763. // 先将当前版本保存到历史
  6764. $newVersion = [
  6765. 'version' => count($versions) + 1,
  6766. 'url' => $role->url,
  6767. 'pic_prompt' => $role->pic_prompt,
  6768. 'updated_at' => date('Y-m-d H:i:s'),
  6769. 'updated_by' => $uid
  6770. ];
  6771. array_unshift($versions, $newVersion);
  6772. // 限制版本数量
  6773. if (count($versions) > 10) {
  6774. $versions = array_slice($versions, 0, 10);
  6775. }
  6776. // 恢复到指定版本
  6777. return DB::table('mp_products')
  6778. ->where('id', $id)
  6779. ->where('cpid', $cpid)
  6780. ->update([
  6781. 'url' => $targetVersion['url'],
  6782. 'pic_prompt' => $targetVersion['pic_prompt'],
  6783. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6784. 'updated_at' => date('Y-m-d H:i:s')
  6785. ]);
  6786. }
  6787. public function deleteProduct($data) {
  6788. $uid = Site::getUid();
  6789. $cpid = Site::getCpid();
  6790. $role = Site::getRole();
  6791. $id = getProp($data, 'id');
  6792. if (!$id) Utils::throwError('20003:ID不能为空');
  6793. $ids = explode(',', $id);
  6794. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6795. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6796. $query_uid = $is_public ? 0 : $uid;
  6797. // 如果是公共库操作,需要admin权限
  6798. if ($is_public && $role !== 'admin') {
  6799. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6800. }
  6801. // 检查是否存在且属于当前用户或公共库
  6802. $role = DB::table('mp_products')
  6803. ->whereIn('id', $ids)
  6804. ->where('cpid', $cpid)
  6805. ->where('user_id', $query_uid)
  6806. ->get();
  6807. if (!$role) Utils::throwError('20003:记录不存在');
  6808. return DB::table('mp_products')
  6809. ->where('cpid', $cpid)
  6810. ->where('user_id', $query_uid)
  6811. ->whereIn('id', $ids)
  6812. ->update([
  6813. 'is_deleted' => 1,
  6814. 'updated_at' => date('Y-m-d H:i:s')
  6815. ]);
  6816. }
  6817. public function generateThreeView($data) {
  6818. $uid = Site::getUid();
  6819. $cpid = Site::getCpid();
  6820. $role = Site::getRole();
  6821. $id = getProp($data, 'id');
  6822. if (!$id) Utils::throwError('20003:ID不能为空');
  6823. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6824. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6825. $query_uid = $is_public ? 0 : $uid;
  6826. // 如果是公共库操作,需要admin权限
  6827. if ($is_public && $role !== 'admin') {
  6828. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6829. }
  6830. // 检查是否存在且属于当前用户或公共库
  6831. $product = DB::table('mp_products')
  6832. ->where('id', $id)
  6833. ->where('cpid', $cpid)
  6834. ->where('user_id', $query_uid)
  6835. ->where('type', 1)->first();
  6836. if (!$product) Utils::throwError('20003:资产不存在');
  6837. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6838. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6839. if (!$ref_img_url) {
  6840. // 如果没有传入参考图,使用角色表中的图片
  6841. $ref_img_url = $product->url ?? '';
  6842. if (!$ref_img_url) {
  6843. Utils::throwError('20003:参考图不能为空');
  6844. }
  6845. }
  6846. $pic_prompt = getProp($product, 'pic_prompt');
  6847. if ($pic_prompt) {
  6848. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6849. }
  6850. // 检查参考图是否是正确的图片格式
  6851. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6852. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6853. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6854. if (!in_array($extension, $allowedExtensions)) {
  6855. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6856. }
  6857. // 处理图片模型
  6858. $model = getProp($data, 'model');
  6859. if (!$model) {
  6860. // 使用默认模型
  6861. $model = 'doubao-seedream-5-0-lite-260128';
  6862. }
  6863. // 验证模型是否在可用模型表中
  6864. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6865. Utils::throwError('20003:该模型已不可用,请更换!');
  6866. }
  6867. $ratio = getProp($data, 'ratio', '16:9');
  6868. $resolution = getProp($data, 'resolution', '2k');
  6869. // 定义分辨率和宽高比对应的尺寸映射表
  6870. $sizeMap = [
  6871. '2k' => [
  6872. '1:1' => ['width' => 2048, 'height' => 2048],
  6873. '4:3' => ['width' => 2304, 'height' => 1728],
  6874. '3:4' => ['width' => 1728, 'height' => 2304],
  6875. '16:9' => ['width' => 2848, 'height' => 1600],
  6876. '9:16' => ['width' => 1600, 'height' => 2848],
  6877. '3:2' => ['width' => 2496, 'height' => 1664],
  6878. '2:3' => ['width' => 1664, 'height' => 2496],
  6879. '21:9' => ['width' => 3136, 'height' => 1344],
  6880. ],
  6881. '3k' => [
  6882. '1:1' => ['width' => 3072, 'height' => 3072],
  6883. '4:3' => ['width' => 3456, 'height' => 2592],
  6884. '3:4' => ['width' => 2592, 'height' => 3456],
  6885. '16:9' => ['width' => 4096, 'height' => 2304],
  6886. '9:16' => ['width' => 2304, 'height' => 4096],
  6887. '2:3' => ['width' => 2496, 'height' => 3744],
  6888. '3:2' => ['width' => 3744, 'height' => 2496],
  6889. '21:9' => ['width' => 4704, 'height' => 2016],
  6890. ],
  6891. '4k' => [
  6892. '1:1' => ['width' => 4096, 'height' => 4096],
  6893. '3:4' => ['width' => 3520, 'height' => 4704],
  6894. '4:3' => ['width' => 4704, 'height' => 3520],
  6895. '16:9' => ['width' => 5504, 'height' => 3040],
  6896. '9:16' => ['width' => 3040, 'height' => 5504],
  6897. '2:3' => ['width' => 3328, 'height' => 4992],
  6898. '3:2' => ['width' => 4992, 'height' => 3328],
  6899. '21:9' => ['width' => 6240, 'height' => 2656],
  6900. ],
  6901. ];
  6902. // 参数验证
  6903. $resolution = strtolower($resolution);
  6904. if (!isset($sizeMap[$resolution])) {
  6905. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6906. }
  6907. if (!isset($sizeMap[$resolution][$ratio])) {
  6908. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6909. }
  6910. // 根据 ratio 和 resolution 确定宽高
  6911. $width = $sizeMap[$resolution][$ratio]['width'];
  6912. $height = $sizeMap[$resolution][$ratio]['height'];
  6913. try {
  6914. // 创建图片生成任务
  6915. $params = [
  6916. 'prompt' => $prompt,
  6917. 'model' => $model,
  6918. 'ref_img_urls' => [$ref_img_url],
  6919. 'width' => $width,
  6920. 'height' => $height
  6921. ];
  6922. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6923. $task_id = $task->id;
  6924. if (!$task_id) {
  6925. Utils::throwError('20003:创建图片生成任务失败');
  6926. }
  6927. // 轮询获取结果
  6928. // 只查询数据库,不调用API,不更新任务表
  6929. $start_time = time();
  6930. $timeout = 1800;
  6931. $img_url = '';
  6932. while (time() - $start_time < $timeout) {
  6933. sleep(5);
  6934. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6935. $task = DB::table('mp_generate_pic_tasks')
  6936. ->where('id', $task_id)
  6937. ->first();
  6938. if (!$task) {
  6939. Utils::throwError('20003:任务不存在');
  6940. }
  6941. if ($task->status === 'success' && $task->result_url) {
  6942. $result_urls = is_string($task->result_url)
  6943. ? json_decode($task->result_url, true)
  6944. : $task->result_url;
  6945. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6946. break;
  6947. } elseif ($task->status === 'failed') {
  6948. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6949. }
  6950. // 其他状态继续轮询
  6951. }
  6952. if (empty($img_url)) {
  6953. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6954. }
  6955. // 更新 mp_products 表(不是任务表)
  6956. DB::table('mp_products')
  6957. ->where('id', $id)
  6958. ->where('cpid', $cpid)
  6959. ->update([
  6960. 'three_view_image_url' => $img_url,
  6961. 'updated_at' => date('Y-m-d H:i:s')
  6962. ]);
  6963. return ['three_view_image_url' => $img_url];
  6964. } catch (\Exception $e) {
  6965. dLog('anime')->error('生成三视图失败', [
  6966. 'error' => $e->getMessage()
  6967. ]);
  6968. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6969. Utils::throwError('20003:' . $e->getMessage());
  6970. }
  6971. }
  6972. /**
  6973. * 推送(复制)资产或文件夹到目标位置
  6974. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6975. * @return array 返回推送结果
  6976. */
  6977. public function pushProductOrFolder($data) {
  6978. $uid = Site::getUid();
  6979. $cpid = Site::getCpid();
  6980. $role = Site::getRole();
  6981. $product_id = getProp($data, 'product_id');
  6982. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6983. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6984. if (!$product_id) {
  6985. Utils::throwError('20003:请选择要推送的项目');
  6986. }
  6987. // 查询源项目(只通过cpid查询,不限制user_id)
  6988. $sourceItem = DB::table('mp_products')
  6989. ->where('id', $product_id)
  6990. ->where('cpid', $cpid)
  6991. ->where('is_deleted', 0)
  6992. ->first();
  6993. if (!$sourceItem) {
  6994. Utils::throwError('20003:要推送的项目不存在');
  6995. }
  6996. // 通过user_id判断源是公共库还是个人库
  6997. $source_uid = $sourceItem->user_id;
  6998. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6999. // 验证目标文件夹并确定目标是公共库还是个人库
  7000. $target_level = 0;
  7001. $target_uid = $uid; // 默认推送到个人库
  7002. $target_is_public = 0;
  7003. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  7004. if ($target_parent_id > 0) {
  7005. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  7006. $targetParent = DB::table('mp_products')
  7007. ->where('id', $target_parent_id)
  7008. ->where('cpid', $cpid)
  7009. ->where('type', 2)
  7010. ->where('is_deleted', 0)
  7011. ->first();
  7012. if (!$targetParent) {
  7013. Utils::throwError('20003:目标文件夹不存在');
  7014. }
  7015. // 通过user_id判断目标是公共库还是个人库
  7016. $target_level = $targetParent->level;
  7017. $target_uid = $targetParent->user_id;
  7018. $target_is_public = ($target_uid == 0) ? 1 : 0;
  7019. // 使用目标文件夹的 product 类型
  7020. $final_product_type = $targetParent->product;
  7021. }
  7022. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  7023. else {
  7024. $push_to_public = getProp($data, 'push_to_public');
  7025. if ($push_to_public === '') {
  7026. Utils::throwError('20003:请选择是否推送到公共库');
  7027. }
  7028. if ($push_to_public) {
  7029. $target_uid = 0;
  7030. $target_is_public = 1;
  7031. }
  7032. // 推送到根目录时,必须指定 product 类型
  7033. if ($target_product === null || $target_product === '') {
  7034. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  7035. }
  7036. $final_product_type = $target_product;
  7037. }
  7038. // 如果目标是公共库,需要admin权限
  7039. if ($target_is_public && $role !== 'admin') {
  7040. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  7041. }
  7042. // 权限验证:验证是否符合允许的推送规则
  7043. $this->validatePushPermission($source_uid, $target_uid, $uid);
  7044. try {
  7045. DB::beginTransaction();
  7046. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  7047. if ($sourceItem->type == 1) {
  7048. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  7049. DB::commit();
  7050. return [
  7051. 'product_id' => $newId,
  7052. ];
  7053. }
  7054. // 如果是文件夹,递归复制(支持跨类型推送)
  7055. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  7056. DB::commit();
  7057. return [
  7058. 'product_id' => $newFolderId,
  7059. ];
  7060. } catch (\Exception $e) {
  7061. DB::rollBack();
  7062. dLog('anime')->error('推送失败', [
  7063. 'error' => $e->getMessage(),
  7064. 'product_id' => $product_id
  7065. ]);
  7066. Utils::throwError('20003:' . $e->getMessage());
  7067. }
  7068. }
  7069. /**
  7070. * 验证推送权限
  7071. * 允许的推送规则:
  7072. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7073. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  7074. * 3. 公共库推送给公共库(公共库 → 公共库)
  7075. *
  7076. * @param int $source_uid 源的user_id
  7077. * @param int $target_uid 目标的user_id
  7078. * @param int $current_uid 当前用户ID
  7079. * @throws \Exception
  7080. */
  7081. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  7082. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7083. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  7084. return; // 允许
  7085. }
  7086. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  7087. if ($source_uid == 0 && $target_uid == $current_uid) {
  7088. return; // 允许
  7089. }
  7090. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7091. if ($source_uid == 0 && $target_uid == 0) {
  7092. return; // 允许
  7093. }
  7094. // 其他情况都不允许
  7095. if ($source_uid != 0 && $source_uid != $current_uid) {
  7096. // 源是别人的个人库
  7097. Utils::throwError('20003:无权限访问该资产');
  7098. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7099. // 个人库推送给公共库(不允许)
  7100. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7101. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7102. // 不同用户的个人库之间推送(不允许)
  7103. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7104. } else {
  7105. // 其他未知情况
  7106. Utils::throwError('20003:不允许的推送操作');
  7107. }
  7108. }
  7109. /**
  7110. * 复制单个资产
  7111. * @param object $sourceProduct 源资产对象
  7112. * @param int $targetParentId 目标父文件夹ID
  7113. * @param int $targetLevel 目标层级
  7114. * @param int $cpid 公司ID
  7115. * @param int $targetUid 目标用户ID
  7116. * @return int 返回新资产ID
  7117. */
  7118. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7119. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7120. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7121. $newProductData = [
  7122. 'user_id' => $targetUid,
  7123. 'cpid' => $cpid,
  7124. 'type' => 1,
  7125. 'parent_id' => $targetParentId,
  7126. 'level' => $targetLevel,
  7127. 'product_name' => $sourceProduct->product_name,
  7128. 'url' => $sourceProduct->url,
  7129. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7130. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7131. 'product' => $finalProductType,
  7132. 'versions' => $sourceProduct->versions ?? '',
  7133. 'sort_order' => time(),
  7134. 'is_deleted' => 0,
  7135. 'created_at' => date('Y-m-d H:i:s'),
  7136. 'updated_at' => date('Y-m-d H:i:s')
  7137. ];
  7138. return DB::table('mp_products')->insertGetId($newProductData);
  7139. }
  7140. /**
  7141. * 递归复制文件夹及其子项
  7142. * @param object $sourceFolder 源文件夹对象
  7143. * @param int $targetParentId 目标父文件夹ID
  7144. * @param int $targetLevel 目标层级
  7145. * @param int $cpid 公司ID
  7146. * @param int $targetUid 目标用户ID
  7147. * @param int $sourceUid 源用户ID
  7148. * @return int 返回新文件夹ID
  7149. */
  7150. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7151. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7152. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7153. // 创建新文件夹
  7154. $newFolderData = [
  7155. 'user_id' => $targetUid,
  7156. 'cpid' => $cpid,
  7157. 'type' => 2,
  7158. 'parent_id' => $targetParentId,
  7159. 'level' => $targetLevel,
  7160. 'product_name' => $sourceFolder->product_name,
  7161. 'product' => $finalProductType,
  7162. 'sort_order' => time(),
  7163. 'is_deleted' => 0,
  7164. 'created_at' => date('Y-m-d H:i:s'),
  7165. 'updated_at' => date('Y-m-d H:i:s')
  7166. ];
  7167. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7168. // 获取源文件夹下的所有子项
  7169. $children = DB::table('mp_products')
  7170. ->where('parent_id', $sourceFolder->id)
  7171. ->where('cpid', $cpid)
  7172. ->where('user_id', $sourceUid)
  7173. ->where('is_deleted', 0)
  7174. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7175. ->get();
  7176. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7177. foreach ($children as $child) {
  7178. if ($child->type == 1) {
  7179. // 资产
  7180. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7181. } else {
  7182. // 文件夹
  7183. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7184. }
  7185. }
  7186. return $newFolderId;
  7187. }
  7188. /**
  7189. * 保存剧本资产关联关系
  7190. * @param array $data 请求参数
  7191. * @return bool
  7192. */
  7193. public function saveScriptProducts($data) {
  7194. $uid = Site::getUid();
  7195. $cpid = Site::getCpid();
  7196. $script_id = getProp($data, 'script_id');
  7197. $products = getProp($data, 'products', []);
  7198. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  7199. if (!$script_id) {
  7200. Utils::throwError('20003:请提供剧本ID');
  7201. }
  7202. // 验证剧本是否存在
  7203. $script = DB::table('mp_scripts')
  7204. ->where('id', $script_id)
  7205. ->where('is_deleted', 0)
  7206. ->first();
  7207. if (!$script) {
  7208. Utils::throwError('20003:剧本不存在');
  7209. }
  7210. // 处理图片模型
  7211. $model = getProp($data, 'model');
  7212. if (!$model) {
  7213. // 使用默认模型
  7214. $model = 'doubao-seedream-5-0-lite-260128';
  7215. }
  7216. // 验证模型是否在可用模型表中
  7217. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7218. Utils::throwError('20003:该模型已不可用,请更换!');
  7219. }
  7220. $ratio = getProp($data, 'ratio', '9:16');
  7221. $resolution = getProp($data, 'resolution', '2k');
  7222. // 定义分辨率和宽高比对应的尺寸映射表
  7223. $sizeMap = [
  7224. '2k' => [
  7225. '1:1' => ['width' => 2048, 'height' => 2048],
  7226. '4:3' => ['width' => 2304, 'height' => 1728],
  7227. '3:4' => ['width' => 1728, 'height' => 2304],
  7228. '16:9' => ['width' => 2848, 'height' => 1600],
  7229. '9:16' => ['width' => 1600, 'height' => 2848],
  7230. '3:2' => ['width' => 2496, 'height' => 1664],
  7231. '2:3' => ['width' => 1664, 'height' => 2496],
  7232. '21:9' => ['width' => 3136, 'height' => 1344],
  7233. ],
  7234. '3k' => [
  7235. '1:1' => ['width' => 3072, 'height' => 3072],
  7236. '4:3' => ['width' => 3456, 'height' => 2592],
  7237. '3:4' => ['width' => 2592, 'height' => 3456],
  7238. '16:9' => ['width' => 4096, 'height' => 2304],
  7239. '9:16' => ['width' => 2304, 'height' => 4096],
  7240. '2:3' => ['width' => 2496, 'height' => 3744],
  7241. '3:2' => ['width' => 3744, 'height' => 2496],
  7242. '21:9' => ['width' => 4704, 'height' => 2016],
  7243. ],
  7244. '4k' => [
  7245. '1:1' => ['width' => 4096, 'height' => 4096],
  7246. '3:4' => ['width' => 3520, 'height' => 4704],
  7247. '4:3' => ['width' => 4704, 'height' => 3520],
  7248. '16:9' => ['width' => 5504, 'height' => 3040],
  7249. '9:16' => ['width' => 3040, 'height' => 5504],
  7250. '2:3' => ['width' => 3328, 'height' => 4992],
  7251. '3:2' => ['width' => 4992, 'height' => 3328],
  7252. '21:9' => ['width' => 6240, 'height' => 2656],
  7253. ],
  7254. ];
  7255. // 参数验证
  7256. $resolution = strtolower($resolution);
  7257. if (!isset($sizeMap[$resolution])) {
  7258. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7259. }
  7260. if (!isset($sizeMap[$resolution][$ratio])) {
  7261. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7262. }
  7263. // 根据 ratio 和 resolution 确定宽高
  7264. $width = $sizeMap[$resolution][$ratio]['width'];
  7265. $height = $sizeMap[$resolution][$ratio]['height'];
  7266. $script_name = $script->script_name ?? 'script_' . $script_id;
  7267. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  7268. $taskCenterId = $this->createScriptProductTaskCenter(
  7269. $uid,
  7270. $cpid,
  7271. $script_id,
  7272. $products,
  7273. $model,
  7274. $ratio,
  7275. $resolution,
  7276. $auto_generate_images
  7277. );
  7278. // 检查是否已经有该剧本的资产数据
  7279. $existingMappings = DB::table('mp_script_product_mappings')
  7280. ->where('script_id', $script_id)
  7281. ->get();
  7282. if ($existingMappings->isNotEmpty()) {
  7283. // 已存在资产映射,检查是否所有资产都有图片生成任务
  7284. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  7285. // 查询这些资产的图片生成任务状态
  7286. $productsWithTasks = DB::table('mp_products')
  7287. ->whereIn('id', $productIds)
  7288. ->where('is_deleted', 0)
  7289. ->get();
  7290. $productTaskMap = [];
  7291. $typeFolderIds = [];
  7292. $hasAllTasks = true;
  7293. foreach ($productsWithTasks as $product) {
  7294. // 收集类型文件夹ID
  7295. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  7296. $parentFolder = DB::table('mp_products')
  7297. ->where('id', $product->parent_id)
  7298. ->where('type', 2)
  7299. ->first();
  7300. if ($parentFolder) {
  7301. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  7302. }
  7303. }
  7304. // 检查是否有图片生成任务
  7305. if (!empty($product->pic_task_id)) {
  7306. $productTaskMap[$product->id] = $product->pic_task_id;
  7307. } else if($product->url && $product->pic_task_status == '生成成功') {
  7308. continue;
  7309. } else {
  7310. // 有资产没有图片任务
  7311. $hasAllTasks = false;
  7312. }
  7313. }
  7314. // 如果所有资产都有任务ID,直接轮询返回结果
  7315. if ($hasAllTasks && !empty($productTaskMap)) {
  7316. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  7317. 'script_id' => $script_id,
  7318. 'script_name' => $script_name,
  7319. 'product_count' => count($productTaskMap)
  7320. ]);
  7321. // 直接返回 SSE 流轮询结果
  7322. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7323. }
  7324. // 如果部分资产没有任务ID,只为这些资产创建任务
  7325. if (!$hasAllTasks && $auto_generate_images) {
  7326. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  7327. 'script_id' => $script_id,
  7328. 'script_name' => $script_name
  7329. ]);
  7330. // 开启事务
  7331. DB::beginTransaction();
  7332. try {
  7333. foreach ($productsWithTasks as $product) {
  7334. // 跳过已有任务的资产
  7335. if (!empty($product->pic_task_id)) {
  7336. continue;
  7337. }
  7338. // 跳过没有提示词的资产
  7339. if (empty($product->pic_prompt)) {
  7340. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7341. 'product_id' => $product->id,
  7342. 'product_name' => $product->product_name
  7343. ]);
  7344. continue;
  7345. }
  7346. try {
  7347. // 创建图片生成任务
  7348. $params = [
  7349. 'prompt' => $product->pic_prompt,
  7350. 'model' => $model,
  7351. 'ref_img_urls' => [],
  7352. 'width' => $width,
  7353. 'height' => $height
  7354. ];
  7355. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7356. $task_id = $task->id;
  7357. if ($task_id) {
  7358. $productTaskMap[$product->id] = $task_id;
  7359. // 在事务中更新资产表的任务ID和状态
  7360. DB::table('mp_products')
  7361. ->where('id', $product->id)
  7362. ->update([
  7363. 'pic_task_id' => $task_id,
  7364. 'pic_task_status' => '生成中',
  7365. 'updated_at' => now()
  7366. ]);
  7367. dLog('anime')->info('为已存在资产创建图片生成任务', [
  7368. 'product_id' => $product->id,
  7369. 'task_id' => $task_id
  7370. ]);
  7371. }
  7372. } catch (\Exception $e) {
  7373. dLog('anime')->error('创建资产图片生成任务失败', [
  7374. 'product_id' => $product->id,
  7375. 'error' => $e->getMessage()
  7376. ]);
  7377. // 标记为失败(仍在事务中)
  7378. DB::table('mp_products')
  7379. ->where('id', $product->id)
  7380. ->update([
  7381. 'pic_task_status' => '生成失败',
  7382. 'updated_at' => now()
  7383. ]);
  7384. }
  7385. }
  7386. // 提交事务
  7387. DB::commit();
  7388. // 如果有新创建的任务,返回 SSE 流
  7389. if (!empty($productTaskMap)) {
  7390. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7391. }
  7392. } catch (\Exception $e) {
  7393. // 回滚事务
  7394. DB::rollback();
  7395. dLog('anime')->error('为已存在资产创建图片任务失败', [
  7396. 'script_id' => $script_id,
  7397. 'error' => $e->getMessage()
  7398. ]);
  7399. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  7400. }
  7401. }
  7402. // 如果不需要生成图片,返回已存在的信息
  7403. $resultData = [
  7404. 'success' => true,
  7405. 'message' => '剧本资产已存在',
  7406. 'script_id' => $script_id,
  7407. 'script_name' => $script_name,
  7408. 'type_folder_ids' => $typeFolderIds,
  7409. 'existing_products' => count($productIds),
  7410. 'tasks_count' => count($productTaskMap),
  7411. 'task_center_id' => $taskCenterId
  7412. ];
  7413. // 接口已正常完成,更新任务中心状态和结果
  7414. if ($taskCenterId) {
  7415. $this->taskCenterService->updateTask($taskCenterId, [
  7416. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7417. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7418. 'error_message' => null
  7419. ]);
  7420. }
  7421. return $resultData;
  7422. }
  7423. // 解析 products(可能是 JSON 字符串或数组)
  7424. if (is_string($products)) {
  7425. $products = json_decode($products, true);
  7426. if (json_last_error() !== JSON_ERROR_NONE) {
  7427. Utils::throwError('20003:产品数据格式错误');
  7428. }
  7429. }
  7430. if (!is_array($products) || empty($products)) {
  7431. Utils::throwError('20003:产品数据不能为空');
  7432. }
  7433. // 以下是原有的创建逻辑...
  7434. // 开启事务
  7435. DB::beginTransaction();
  7436. try {
  7437. $now = now();
  7438. $mappingRecords = [];
  7439. $createdProductIds = []; // 记录所有创建的资产ID
  7440. // 获取剧本名称
  7441. $script_name = $script->script_name ?? 'script_' . $script_id;
  7442. // 存储每个类型的根文件夹ID
  7443. $typeFolderIds = [];
  7444. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  7445. foreach ($products as $productGroup) {
  7446. $type = getProp($productGroup, 'type');
  7447. $title = getProp($productGroup, 'title', '');
  7448. $content = getProp($productGroup, 'content', []);
  7449. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  7450. continue;
  7451. }
  7452. // 为当前类型创建根文件夹(如果还未创建)
  7453. if (!isset($typeFolderIds[$type])) {
  7454. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7455. 'user_id' => $uid,
  7456. 'cpid' => $cpid,
  7457. 'type' => 2, // 1.资产 2文件夹
  7458. 'product' => $type, // 1.主体 2.场景 3.道具
  7459. 'parent_id' => 0, // 根文件夹,parent_id=0
  7460. 'level' => 1, // 第一层级
  7461. 'product_name' => $script_name,
  7462. 'sort_order' => time() + $type,
  7463. 'is_deleted' => 0,
  7464. 'created_at' => $now,
  7465. 'updated_at' => $now
  7466. ]);
  7467. }
  7468. $folder_id = $typeFolderIds[$type];
  7469. // 获取表头(第一行)并查找关键列的位置
  7470. $headers = $content[0];
  7471. $nameColumnIndex = -1; // 资产名称列索引
  7472. $sequenceColumnIndex = -1; // 使用范围列索引
  7473. $promptColumnIndex = -1; // 参考提示词列索引
  7474. foreach ($headers as $index => $header) {
  7475. // 查找"资产名称"列
  7476. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  7477. $nameColumnIndex = $index;
  7478. }
  7479. // 查找"使用范围"列
  7480. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  7481. $sequenceColumnIndex = $index;
  7482. }
  7483. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  7484. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  7485. $promptColumnIndex = $index;
  7486. }
  7487. }
  7488. // 验证必要的列是否都找到了
  7489. if ($nameColumnIndex === -1) {
  7490. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  7491. continue;
  7492. }
  7493. if ($sequenceColumnIndex === -1) {
  7494. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  7495. continue;
  7496. }
  7497. // 跳过表头,解析每一行数据
  7498. for ($i = 1; $i < count($content); $i++) {
  7499. $row = $content[$i];
  7500. // 确保行数据有效
  7501. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  7502. continue;
  7503. }
  7504. // 根据动态查找的列索引提取数据
  7505. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  7506. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  7507. $pic_prompt = '';
  7508. // 提取参考提示词(如果找到了该列)
  7509. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  7510. $pic_prompt = trim($row[$promptColumnIndex]);
  7511. }
  7512. // 解析使用范围(逗号分隔的序号)
  7513. $sequences = [];
  7514. if (!empty($sequence_str)) {
  7515. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  7516. foreach ($sequenceParts as $part) {
  7517. if (is_numeric($part)) {
  7518. $sequences[] = (int)$part;
  7519. }
  7520. }
  7521. }
  7522. if (empty($product_name)) {
  7523. continue;
  7524. }
  7525. // 处理product_name两边的符号
  7526. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7527. // 如果名称不存在或仅剩占位符号,则跳过
  7528. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  7529. dLog('anime')->warning('资产名称无效,跳过保存', [
  7530. 'script_id' => $script_id,
  7531. 'type' => $type,
  7532. 'product_name' => $product_name
  7533. ]);
  7534. continue;
  7535. }
  7536. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  7537. $product_id = DB::table('mp_products')->insertGetId([
  7538. 'product_name' => $product_name,
  7539. 'type' => 1, // 1=资产 2.文件夹
  7540. 'product' => $type, // 1=角色, 2=场景, 3=道具
  7541. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  7542. 'level' => 2, // 第二层级
  7543. 'pic_prompt' => $pic_prompt,
  7544. 'user_id' => $uid,
  7545. 'cpid' => $cpid,
  7546. 'sort_order' => time(),
  7547. 'is_deleted' => 0,
  7548. 'created_at' => $now,
  7549. 'updated_at' => $now,
  7550. ]);
  7551. // 记录创建的资产ID
  7552. $createdProductIds[] = $product_id;
  7553. // 为每个序号创建映射记录
  7554. if (!empty($sequences)) {
  7555. foreach ($sequences as $sequence) {
  7556. $mappingRecords[] = [
  7557. 'script_id' => $script_id,
  7558. 'product_id' => $product_id,
  7559. 'episode_number' => $sequence,
  7560. 'created_at' => $now,
  7561. 'updated_at' => $now,
  7562. ];
  7563. }
  7564. } else {
  7565. // 如果没有指定序号,创建一个默认映射(序号为0)
  7566. $mappingRecords[] = [
  7567. 'script_id' => $script_id,
  7568. 'product_id' => $product_id,
  7569. 'episode_number' => 0,
  7570. 'created_at' => $now,
  7571. 'updated_at' => $now,
  7572. ];
  7573. }
  7574. }
  7575. }
  7576. if (empty($mappingRecords)) {
  7577. Utils::throwError('20003:没有有效的产品数据');
  7578. }
  7579. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7580. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7581. // 剧本已有资产,同步更新is_products标记
  7582. DB::table('mp_scripts')->where('id', $script_id)->update([
  7583. 'is_products' => 1,
  7584. 'updated_at' => $now
  7585. ]);
  7586. // 如果需要自动生成图片,在事务中创建图片生成任务
  7587. $productTaskMap = [];
  7588. if ($auto_generate_images && !empty($createdProductIds)) {
  7589. // 查询所有创建的资产
  7590. $productsToGenerate = DB::table('mp_products')
  7591. ->whereIn('id', $createdProductIds)
  7592. ->where('is_deleted', 0)
  7593. ->get();
  7594. foreach ($productsToGenerate as $product) {
  7595. if (empty($product->pic_prompt)) {
  7596. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7597. 'product_id' => $product->id,
  7598. 'product_name' => $product->product_name
  7599. ]);
  7600. continue;
  7601. }
  7602. try {
  7603. // 创建图片生成任务
  7604. $params = [
  7605. 'prompt' => $product->pic_prompt,
  7606. 'model' => $model,
  7607. 'ref_img_urls' => [],
  7608. 'width' => $width,
  7609. 'height' => $height
  7610. ];
  7611. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7612. $task_id = $task->id;
  7613. if ($task_id) {
  7614. $productTaskMap[$product->id] = $task_id;
  7615. // 在事务中更新资产表的任务ID和状态
  7616. DB::table('mp_products')
  7617. ->where('id', $product->id)
  7618. ->update([
  7619. 'pic_task_id' => $task_id,
  7620. 'pic_task_status' => '生成中',
  7621. 'updated_at' => now()
  7622. ]);
  7623. dLog('anime')->info('创建资产图片生成任务', [
  7624. 'product_id' => $product->id,
  7625. 'task_id' => $task_id
  7626. ]);
  7627. }
  7628. } catch (\Exception $e) {
  7629. dLog('anime')->error('创建资产图片生成任务失败', [
  7630. 'product_id' => $product->id,
  7631. 'error' => $e->getMessage()
  7632. ]);
  7633. // 标记为失败(仍在事务中)
  7634. DB::table('mp_products')
  7635. ->where('id', $product->id)
  7636. ->update([
  7637. 'pic_task_status' => '生成失败',
  7638. 'updated_at' => now()
  7639. ]);
  7640. }
  7641. }
  7642. }
  7643. // 提交事务
  7644. DB::commit();
  7645. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  7646. if ($auto_generate_images && !empty($productTaskMap)) {
  7647. // 返回 SSE 流(事务外轮询)
  7648. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7649. }
  7650. // 如果不需要生成图片,返回普通结果
  7651. $resultData = [
  7652. 'success' => true,
  7653. 'type_folder_ids' => $typeFolderIds,
  7654. 'inserted_count' => $insertedCount,
  7655. 'total_records' => count($mappingRecords),
  7656. 'created_products' => count($createdProductIds),
  7657. 'image_tasks_created' => count($productTaskMap),
  7658. 'task_center_id' => $taskCenterId
  7659. ];
  7660. // 接口已正常完成,更新任务中心状态和结果
  7661. if ($taskCenterId) {
  7662. $this->taskCenterService->updateTask($taskCenterId, [
  7663. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7664. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7665. 'error_message' => null
  7666. ]);
  7667. }
  7668. return $resultData;
  7669. } catch (\Exception $e) {
  7670. // 回滚事务
  7671. DB::rollback();
  7672. // 更新任务中心状态为失败
  7673. if (!empty($taskCenterId)) {
  7674. $this->taskCenterService->updateTask($taskCenterId, [
  7675. 'status' => MpTaskCenter::STATUS_FAILED,
  7676. 'error_message' => $e->getMessage()
  7677. ]);
  7678. }
  7679. // 记录错误日志
  7680. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  7681. 'script_id' => $script_id,
  7682. 'error' => $e->getMessage(),
  7683. 'trace' => $e->getTraceAsString()
  7684. ]);
  7685. // 统一使用 Utils::throwError 抛出错误
  7686. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  7687. }
  7688. }
  7689. /**
  7690. * 根据入参创建或复用任务中心记录
  7691. *
  7692. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  7693. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  7694. * 避免生成重复任务。
  7695. *
  7696. * @param int|string $uid
  7697. * @param int|string $cpid
  7698. * @param int|string $script_id
  7699. * @param mixed $products
  7700. * @param string $model
  7701. * @param string $ratio
  7702. * @param string $resolution
  7703. * @param mixed $auto_generate_images
  7704. * @return int 任务中心ID
  7705. */
  7706. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  7707. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  7708. if (is_string($products)) {
  7709. $decoded = json_decode($products, true);
  7710. if (json_last_error() === JSON_ERROR_NONE) {
  7711. $products = $decoded;
  7712. }
  7713. }
  7714. $params = [
  7715. 'script_id' => (int)$script_id,
  7716. 'products' => $products,
  7717. 'model' => $model,
  7718. 'ratio' => $ratio,
  7719. 'resolution' => $resolution,
  7720. 'auto_generate_images' => (bool)$auto_generate_images,
  7721. ];
  7722. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  7723. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  7724. $existing = DB::table('mp_task_center')
  7725. ->where('uid', (int)$uid)
  7726. ->where('cpid', (int)$cpid)
  7727. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  7728. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  7729. ->where('params_md5', $paramsMd5)
  7730. ->orderBy('id', 'desc')
  7731. ->first();
  7732. if ($existing) {
  7733. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  7734. 'script_id' => $script_id,
  7735. 'task_center_id' => $existing->id,
  7736. 'params_md5' => $paramsMd5,
  7737. ]);
  7738. return (int)$existing->id;
  7739. }
  7740. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  7741. $now = date('Y-m-d H:i:s');
  7742. DB::table('mp_task_center')->insertOrIgnore([
  7743. 'uid' => (int)$uid,
  7744. 'cpid' => (int)$cpid,
  7745. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  7746. 'title' => '剧本资产图片生成',
  7747. 'ref_task_id' => 0,
  7748. 'status' => MpTaskCenter::STATUS_PROCESSING,
  7749. 'result' => null,
  7750. 'error_message' => null,
  7751. 'prompt' => null,
  7752. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  7753. 'params_md5' => $paramsMd5,
  7754. 'created_at' => $now,
  7755. 'updated_at' => $now,
  7756. ]);
  7757. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  7758. $taskId = (int)DB::table('mp_task_center')
  7759. ->where('uid', (int)$uid)
  7760. ->where('cpid', (int)$cpid)
  7761. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  7762. ->where('params_md5', $paramsMd5)
  7763. ->orderBy('id', 'desc')
  7764. ->value('id');
  7765. dLog('anime')->info('创建任务中心记录', [
  7766. 'script_id' => $script_id,
  7767. 'task_center_id' => $taskId,
  7768. 'params_md5' => $paramsMd5,
  7769. ]);
  7770. return $taskId;
  7771. }
  7772. /**
  7773. * 任务结束时更新任务中心记录的状态和结果
  7774. *
  7775. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  7776. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  7777. *
  7778. * @param int|null $taskCenterId
  7779. * @param array $resultData 接口返回结果数组
  7780. * @param bool $timeout 是否超时未完成
  7781. */
  7782. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  7783. if (!$taskCenterId) {
  7784. return;
  7785. }
  7786. $stats = $resultData['stats'] ?? [];
  7787. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  7788. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  7789. $failedCount = $completedCount - $successCount;
  7790. // 与接口返回给客户端的结果保持一致
  7791. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  7792. if ($timeout) {
  7793. $this->taskCenterService->updateTask((int)$taskCenterId, [
  7794. 'status' => MpTaskCenter::STATUS_FAILED,
  7795. 'result' => $result,
  7796. 'error_message' => '部分任务超时,请稍后查看结果',
  7797. ]);
  7798. return;
  7799. }
  7800. $this->taskCenterService->updateTask((int)$taskCenterId, [
  7801. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  7802. 'result' => $result,
  7803. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  7804. ]);
  7805. }
  7806. /**
  7807. * 批量为剧本资产生成图片
  7808. *
  7809. * @param array $data 请求参数
  7810. * @return \Generator 返回 SSE 流
  7811. */
  7812. public function batchGenerateProductImages($data) {
  7813. $script_id = getProp($data, 'script_id');
  7814. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  7815. if (!$script_id) {
  7816. Utils::throwError('20003:请提供剧本ID');
  7817. }
  7818. // 验证剧本是否存在
  7819. $script = DB::table('mp_scripts')
  7820. ->where('id', $script_id)
  7821. ->where('is_deleted', 0)
  7822. ->first();
  7823. if (!$script) {
  7824. Utils::throwError('20003:剧本不存在');
  7825. }
  7826. $script_name = $script->script_name ?? 'script_' . $script_id;
  7827. // 获取需要生成图片的所有资产
  7828. $products = DB::table('mp_products')
  7829. ->whereIn('parent_id', array_values($type_folder_ids))
  7830. ->where('is_deleted', 0)
  7831. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7832. ->get();
  7833. if ($products->isEmpty()) {
  7834. Utils::throwError('20003:没有找到需要生成图片的资产');
  7835. }
  7836. // 默认参数
  7837. $model = 'doubao-seedream-5-0-lite-260128';
  7838. $width = 1600;
  7839. $height = 2848;
  7840. // 开始为每个资产创建图片生成任务
  7841. $taskIds = [];
  7842. $productTaskMap = []; // 资产ID到任务ID的映射
  7843. foreach ($products as $product) {
  7844. if (empty($product->pic_prompt)) {
  7845. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7846. continue;
  7847. }
  7848. try {
  7849. // 创建图片生成任务
  7850. $params = [
  7851. 'prompt' => $product->pic_prompt,
  7852. 'model' => $model,
  7853. 'ref_img_urls' => [],
  7854. 'width' => $width,
  7855. 'height' => $height
  7856. ];
  7857. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7858. $task_id = $task->id;
  7859. if ($task_id) {
  7860. $taskIds[] = $task_id;
  7861. $productTaskMap[$product->id] = $task_id;
  7862. // 更新资产表的任务ID和状态
  7863. DB::table('mp_products')
  7864. ->where('id', $product->id)
  7865. ->update([
  7866. 'pic_task_id' => $task_id,
  7867. 'pic_task_status' => '生成中',
  7868. 'updated_at' => now()
  7869. ]);
  7870. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7871. }
  7872. } catch (\Exception $e) {
  7873. dLog('anime')->error('创建资产图片生成任务失败', [
  7874. 'product_id' => $product->id,
  7875. 'error' => $e->getMessage()
  7876. ]);
  7877. // 标记为失败
  7878. DB::table('mp_products')
  7879. ->where('id', $product->id)
  7880. ->update([
  7881. 'pic_task_status' => '生成失败',
  7882. 'updated_at' => now()
  7883. ]);
  7884. }
  7885. }
  7886. if (empty($taskIds)) {
  7887. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7888. }
  7889. // 返回 SSE 流
  7890. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7891. }
  7892. /**
  7893. * 轮询资产图片生成任务状态(SSE流式返回)
  7894. * 只通过查询数据库获取任务状态,不主动调用API
  7895. *
  7896. * @param int $script_id 剧本ID
  7897. * @param string $script_name 剧本名称
  7898. * @param array $productTaskMap 资产ID到任务ID的映射
  7899. * @param array $type_folder_ids 类型文件夹ID映射
  7900. * @return \Generator
  7901. */
  7902. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null) {
  7903. $startTime = time();
  7904. $timeout = 1800; // 30分钟超时
  7905. $pollInterval = 10; // 10秒轮询一次
  7906. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7907. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  7908. if ($taskCenterId) {
  7909. $initResponse = [
  7910. 'type' => 'init',
  7911. 'script_id' => $script_id,
  7912. 'script_name' => $script_name,
  7913. 'timestamp' => date('Y-m-d H:i:s'),
  7914. 'task_center_id' => (int)$taskCenterId,
  7915. ];
  7916. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  7917. }
  7918. // 定义类型名称映射
  7919. $typeNames = [
  7920. 1 => 'roles', // 角色
  7921. 2 => 'scenes', // 场景
  7922. 3 => 'props' // 道具
  7923. ];
  7924. while (time() - $startTime < $timeout) {
  7925. sleep($pollInterval);
  7926. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7927. $mappings = DB::table('mp_script_product_mappings')
  7928. ->where('script_id', $script_id)
  7929. ->pluck('product_id')
  7930. ->unique()
  7931. ->toArray();
  7932. if (empty($mappings)) {
  7933. dLog('anime')->warning('该剧本没有关联的资产', [
  7934. 'script_id' => $script_id,
  7935. 'script_name' => $script_name
  7936. ]);
  7937. break;
  7938. }
  7939. // 查询所有资产的当前状态
  7940. $products = DB::table('mp_products')
  7941. ->whereIn('id', $mappings)
  7942. ->where('is_deleted', 0)
  7943. ->get();
  7944. // 统计各类型的状态(使用类型名称作为键名)
  7945. $stats = [
  7946. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7947. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7948. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7949. ];
  7950. $allCompleted = true;
  7951. $hasStatusChange = false;
  7952. foreach ($products as $product) {
  7953. $type = $product->product;
  7954. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7955. // 如果类型名称不在 stats 中,初始化
  7956. if (!isset($stats[$typeName])) {
  7957. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7958. }
  7959. $stats[$typeName]['total']++;
  7960. $task_id = $product->pic_task_id;
  7961. $currentStatus = $product->pic_task_status;
  7962. // 检查状态是否有变化
  7963. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7964. $hasStatusChange = true;
  7965. $lastStatus[$product->id] = $currentStatus;
  7966. }
  7967. // 如果是生成中,查询任务表状态
  7968. if ($currentStatus === '生成中' && $task_id) {
  7969. // 只查询数据库,不调用API
  7970. $task = DB::table('mp_generate_pic_tasks')
  7971. ->where('id', $task_id)
  7972. ->first();
  7973. if ($task) {
  7974. // 检查任务状态
  7975. if ($task->status === 'success' && $task->result_url) {
  7976. // 解析图片URL
  7977. $result_urls = $task->result_url;
  7978. if (is_string($result_urls)) {
  7979. $result_urls = json_decode($result_urls, true);
  7980. }
  7981. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7982. // 更新资产表状态
  7983. DB::table('mp_products')
  7984. ->where('id', $product->id)
  7985. ->update([
  7986. 'pic_task_status' => '生成成功',
  7987. 'url' => $img_url,
  7988. 'updated_at' => now()
  7989. ]);
  7990. $stats[$typeName]['success']++;
  7991. $stats[$typeName]['completed']++;
  7992. $hasStatusChange = true;
  7993. dLog('anime')->info('资产图片生成成功', [
  7994. 'product_id' => $product->id,
  7995. 'task_id' => $task_id,
  7996. 'img_url' => $img_url
  7997. ]);
  7998. } elseif ($task->status === 'failed') {
  7999. // 更新资产表状态
  8000. DB::table('mp_products')
  8001. ->where('id', $product->id)
  8002. ->update([
  8003. 'pic_task_status' => '生成失败',
  8004. 'updated_at' => now()
  8005. ]);
  8006. $stats[$typeName]['completed']++;
  8007. $hasStatusChange = true;
  8008. dLog('anime')->warning('资产图片生成失败', [
  8009. 'product_id' => $product->id,
  8010. 'task_id' => $task_id,
  8011. 'error' => $task->error_message ?? '未知错误'
  8012. ]);
  8013. } else {
  8014. // 任务还在处理中
  8015. $allCompleted = false;
  8016. }
  8017. } else {
  8018. // 任务不存在,标记为失败
  8019. DB::table('mp_products')
  8020. ->where('id', $product->id)
  8021. ->update([
  8022. 'pic_task_status' => '生成失败',
  8023. 'updated_at' => now()
  8024. ]);
  8025. $stats[$type]['completed']++;
  8026. $hasStatusChange = true;
  8027. dLog('anime')->error('图片生成任务不存在', [
  8028. 'product_id' => $product->id,
  8029. 'task_id' => $task_id
  8030. ]);
  8031. }
  8032. } elseif ($currentStatus === '生成成功') {
  8033. $stats[$typeName]['success']++;
  8034. $stats[$typeName]['completed']++;
  8035. } elseif ($currentStatus === '生成失败') {
  8036. $stats[$typeName]['completed']++;
  8037. } else {
  8038. // 其他状态也认为未完成
  8039. $allCompleted = false;
  8040. }
  8041. }
  8042. // 移除没有数据的类型(total=0)
  8043. foreach ($stats as $typeName => $stat) {
  8044. if ($stat['total'] === 0) {
  8045. unset($stats[$typeName]);
  8046. }
  8047. }
  8048. // 如果有状态变化,发送 SSE 更新
  8049. if ($hasStatusChange) {
  8050. $eventType = $allCompleted ? 'complete' : 'update';
  8051. $response = [
  8052. 'type' => $eventType,
  8053. 'script_id' => $script_id,
  8054. 'script_name' => $script_name,
  8055. 'stats' => $stats,
  8056. 'timestamp' => date('Y-m-d H:i:s')
  8057. ];
  8058. if ($taskCenterId) {
  8059. $response['task_center_id'] = $taskCenterId;
  8060. }
  8061. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  8062. dLog('anime')->info('SSE更新', [
  8063. 'event_type' => $eventType,
  8064. 'script_id' => $script_id,
  8065. 'script_name' => $script_name,
  8066. 'stats' => $stats
  8067. ]);
  8068. if ($allCompleted) {
  8069. dLog('anime')->info('所有资产图片生成任务已完成', [
  8070. 'script_id' => $script_id,
  8071. 'script_name' => $script_name,
  8072. 'stats' => $stats
  8073. ]);
  8074. // 全部任务完成,更新任务中心状态和结果
  8075. $this->finishScriptProductTask($taskCenterId, $response);
  8076. break;
  8077. }
  8078. }
  8079. }
  8080. // 超时处理
  8081. if (time() - $startTime >= $timeout && !$allCompleted) {
  8082. $response = [
  8083. 'type' => 'timeout',
  8084. 'message' => '部分任务超时,请稍后查看结果',
  8085. 'script_id' => $script_id,
  8086. 'script_name' => $script_name,
  8087. 'timestamp' => date('Y-m-d H:i:s')
  8088. ];
  8089. if ($taskCenterId) {
  8090. $response['task_center_id'] = $taskCenterId;
  8091. }
  8092. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  8093. dLog('anime')->warning('资产图片生成任务超时', [
  8094. 'script_id' => $script_id,
  8095. 'script_name' => $script_name,
  8096. 'timeout' => $timeout
  8097. ]);
  8098. // 超时未完成,更新任务中心状态和结果
  8099. $this->finishScriptProductTask($taskCenterId, $response, true);
  8100. }
  8101. }
  8102. /**
  8103. * 定时任务:检查产品图片生成任务状态并更新产品记录
  8104. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  8105. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  8106. *
  8107. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  8108. */
  8109. public function checkProductPicTasks() {
  8110. // 查询所有生成中的产品图片任务
  8111. $products = DB::table('mp_products')
  8112. ->whereNotNull('pic_task_id')
  8113. ->where('pic_task_status', '生成中')
  8114. ->where('is_deleted', 0)
  8115. ->get();
  8116. $stats = [
  8117. 'total' => $products->count(),
  8118. 'success' => 0,
  8119. 'failed' => 0,
  8120. 'pending' => 0,
  8121. ];
  8122. foreach ($products as $product) {
  8123. try {
  8124. $task_id = $product->pic_task_id;
  8125. // 通过 pic_task_id 查询图片生成任务结果
  8126. $task = DB::table('mp_generate_pic_tasks')
  8127. ->where('id', $task_id)
  8128. ->first();
  8129. if ($task) {
  8130. if ($task->status === 'success' && $task->result_url) {
  8131. // 解析图片URL
  8132. $result_urls = $task->result_url;
  8133. if (is_string($result_urls)) {
  8134. $result_urls = json_decode($result_urls, true);
  8135. }
  8136. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  8137. // 更新资产表状态
  8138. DB::table('mp_products')
  8139. ->where('id', $product->id)
  8140. ->update([
  8141. 'pic_task_status' => '生成成功',
  8142. 'url' => $img_url,
  8143. 'updated_at' => now()
  8144. ]);
  8145. $stats['success']++;
  8146. dLog('anime')->info('资产图片生成成功', [
  8147. 'product_id' => $product->id,
  8148. 'task_id' => $task_id,
  8149. 'img_url' => $img_url
  8150. ]);
  8151. } elseif ($task->status === 'failed') {
  8152. // 更新资产表状态
  8153. DB::table('mp_products')
  8154. ->where('id', $product->id)
  8155. ->update([
  8156. 'pic_task_status' => '生成失败',
  8157. 'updated_at' => now()
  8158. ]);
  8159. $stats['failed']++;
  8160. dLog('anime')->warning('资产图片生成失败', [
  8161. 'product_id' => $product->id,
  8162. 'task_id' => $task_id,
  8163. 'error' => $task->error_message ?? '未知错误'
  8164. ]);
  8165. } else {
  8166. // 任务还在处理中
  8167. $stats['pending']++;
  8168. }
  8169. } else {
  8170. // 任务不存在,标记为失败
  8171. DB::table('mp_products')
  8172. ->where('id', $product->id)
  8173. ->update([
  8174. 'pic_task_status' => '生成失败',
  8175. 'updated_at' => now()
  8176. ]);
  8177. $stats['failed']++;
  8178. dLog('anime')->error('图片生成任务不存在', [
  8179. 'product_id' => $product->id,
  8180. 'task_id' => $task_id
  8181. ]);
  8182. }
  8183. } catch (\Exception $e) {
  8184. dLog('anime')->error('检查产品图片生成任务异常', [
  8185. 'product_id' => $product->id,
  8186. 'task_id' => $product->pic_task_id ?? null,
  8187. 'error' => $e->getMessage()
  8188. ]);
  8189. }
  8190. }
  8191. return $stats;
  8192. }
  8193. /**
  8194. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  8195. *
  8196. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  8197. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  8198. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  8199. *
  8200. * @return int 更新的任务中心记录数
  8201. */
  8202. public function checkSaveScriptProductTaskCenters() {
  8203. $updated = 0;
  8204. // 只扫描尚未结束的 saveScriptProducts 任务
  8205. $tasks = DB::table('mp_task_center')
  8206. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8207. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  8208. ->orderBy('id', 'desc')
  8209. ->limit(500)
  8210. ->get();
  8211. // 与 pollProductImageTasks 保持一致的类型名称映射
  8212. $typeNames = [
  8213. 1 => 'roles', // 角色
  8214. 2 => 'scenes', // 场景
  8215. 3 => 'props', // 道具
  8216. ];
  8217. foreach ($tasks as $task) {
  8218. try {
  8219. $taskParams = json_decode((string)$task->params, true);
  8220. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  8221. if (!$script_id) {
  8222. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  8223. 'task_center_id' => $task->id,
  8224. ]);
  8225. continue;
  8226. }
  8227. // 获取该剧本关联的全部资产ID
  8228. $productIds = DB::table('mp_script_product_mappings')
  8229. ->where('script_id', $script_id)
  8230. ->pluck('product_id')
  8231. ->unique()
  8232. ->toArray();
  8233. if (empty($productIds)) {
  8234. // 剧本没有关联资产,不视为完成,等待下一次检查
  8235. continue;
  8236. }
  8237. $products = DB::table('mp_products')
  8238. ->whereIn('id', $productIds)
  8239. ->where('is_deleted', 0)
  8240. ->get();
  8241. $stats = [];
  8242. $allCompleted = true;
  8243. foreach ($products as $product) {
  8244. $typeName = $typeNames[$product->product] ?? 'unknown';
  8245. if (!isset($stats[$typeName])) {
  8246. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  8247. }
  8248. $stats[$typeName]['total']++;
  8249. if ($product->pic_task_status === '生成成功') {
  8250. $stats[$typeName]['success']++;
  8251. $stats[$typeName]['completed']++;
  8252. } elseif ($product->pic_task_status === '生成失败') {
  8253. $stats[$typeName]['completed']++;
  8254. } else {
  8255. // 仍有资产在生成中或未生成,任务未完成
  8256. $allCompleted = false;
  8257. }
  8258. }
  8259. if (!$allCompleted) {
  8260. continue;
  8261. }
  8262. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  8263. $script = DB::table('mp_scripts')
  8264. ->where('id', $script_id)
  8265. ->where('is_deleted', 0)
  8266. ->first();
  8267. $script_name = $script->script_name ?? 'script_' . $script_id;
  8268. $this->finishScriptProductTask($task->id, [
  8269. 'type' => 'complete',
  8270. 'script_id' => $script_id,
  8271. 'script_name' => $script_name,
  8272. 'stats' => $stats,
  8273. 'timestamp' => date('Y-m-d H:i:s'),
  8274. 'task_center_id' => (int)$task->id,
  8275. ]);
  8276. $updated++;
  8277. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  8278. 'task_center_id' => $task->id,
  8279. 'script_id' => $script_id,
  8280. 'stats' => $stats,
  8281. ]);
  8282. } catch (\Exception $e) {
  8283. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  8284. 'task_center_id' => $task->id,
  8285. 'error' => $e->getMessage(),
  8286. ]);
  8287. }
  8288. }
  8289. return $updated;
  8290. }
  8291. /**
  8292. * 获取剧本关联的资产列表
  8293. * @param array $data 请求参数
  8294. * @return array
  8295. */
  8296. public function getScriptProducts($data) {
  8297. $uid = Site::getUid();
  8298. $cpid = Site::getCpid();
  8299. $script_id = getProp($data, 'script_id');
  8300. $episode_number = getProp($data, 'episode_number');
  8301. if (!$script_id) {
  8302. Utils::throwError('20003:请提供剧本ID');
  8303. }
  8304. // 验证剧本是否存在
  8305. $script = DB::table('mp_scripts')
  8306. ->where('id', $script_id)
  8307. ->where('is_deleted', 0)
  8308. ->first();
  8309. if (!$script) {
  8310. Utils::throwError('20003:剧本不存在');
  8311. }
  8312. // 联表查询资产信息
  8313. $query = DB::table('mp_script_product_mappings as mapping')
  8314. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8315. ->where('mapping.script_id', $script_id)
  8316. ->where('product.cpid', $cpid)
  8317. ->where('product.is_deleted', 0);
  8318. // 如果提供了 episode_number,则过滤指定集数
  8319. if ($episode_number !== null && $episode_number !== '') {
  8320. $query->where('mapping.episode_number', $episode_number);
  8321. }
  8322. $mappings = $query->select(
  8323. 'mapping.script_id',
  8324. 'mapping.product_id',
  8325. 'mapping.episode_number',
  8326. 'product.product_name',
  8327. 'product.type',
  8328. 'product.product',
  8329. 'product.pic_prompt',
  8330. 'product.url',
  8331. 'product.pic_task_id',
  8332. 'product.pic_task_status',
  8333. 'product.three_view_image_url',
  8334. 'mapping.created_at'
  8335. )
  8336. ->orderBy('mapping.product_id', 'asc')
  8337. ->orderBy('mapping.episode_number', 'asc')
  8338. ->get();
  8339. // 按 product_id 分组,合并 episode_number
  8340. $productMap = [];
  8341. foreach ($mappings as $item) {
  8342. $product_id = $item->product_id;
  8343. if (!isset($productMap[$product_id])) {
  8344. $productMap[$product_id] = [
  8345. 'product_id' => $product_id,
  8346. 'product_name' => $item->product_name,
  8347. 'type' => (int)$item->type,
  8348. 'product' => (int)$item->product,
  8349. 'pic_prompt' => $item->pic_prompt,
  8350. 'url' => $item->url,
  8351. 'pic_task_id' => $item->pic_task_id,
  8352. 'pic_task_status' => $item->pic_task_status,
  8353. 'episode_numbers' => [],
  8354. 'created_at' => $item->created_at,
  8355. ];
  8356. }
  8357. // 添加 episode_number(去重)
  8358. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8359. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8360. }
  8361. }
  8362. // 按类型分组
  8363. $roles = []; // type=1 角色/主体
  8364. $scenes = []; // type=2 场景
  8365. $props = []; // type=3 道具
  8366. foreach ($productMap as $product) {
  8367. // 将 episode_numbers 数组转换为逗号分隔的字符串
  8368. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  8369. // 构造返回数据
  8370. $productData = [
  8371. 'product_id' => $product['product_id'],
  8372. 'product_name' => $product['product_name'],
  8373. 'product' => $product['product'],
  8374. 'pic_prompt' => $product['pic_prompt'],
  8375. 'url' => $product['url'],
  8376. 'pic_task_id' => $product['pic_task_id'],
  8377. 'pic_task_status' => $product['pic_task_status'],
  8378. 'episode_numbers' => $episodeNumbersStr,
  8379. 'created_at' => $product['created_at'],
  8380. ];
  8381. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  8382. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  8383. switch ($product['product']) {
  8384. case 1:
  8385. $roles[] = $productData;
  8386. break;
  8387. case 2:
  8388. $scenes[] = $productData;
  8389. break;
  8390. case 3:
  8391. $props[] = $productData;
  8392. break;
  8393. }
  8394. }
  8395. return [
  8396. 'script_id' => $script_id,
  8397. 'script_name' => $script->script_name ?? '',
  8398. 'roles' => $roles, // 主体
  8399. 'scenes' => $scenes, // 场景
  8400. 'props' => $props, // 道具
  8401. ];
  8402. }
  8403. /**
  8404. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  8405. * @param string $actContent 原始内容
  8406. * @param array $products 产品数组(包含product_name和url)
  8407. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  8408. */
  8409. public function processActContentWithProducts($actContent, $products) {
  8410. if (empty($actContent) || empty($products)) {
  8411. return [
  8412. 'content' => $actContent,
  8413. 'reference_images' => []
  8414. ];
  8415. }
  8416. // 构建产品名称到产品信息的映射
  8417. $product_dict = [];
  8418. foreach ($products as $product) {
  8419. $product_name = getProp($product, 'product_name');
  8420. if ($product_name) {
  8421. $product_dict[$product_name] = [
  8422. // 优先使用三视图图片作为素材/参考图,否则使用原图 url
  8423. 'url' => getProp($product, 'three_view_image_url') ?: getProp($product, 'url'),
  8424. 'voice_prompt' => getProp($product, 'voice_prompt')
  8425. ];
  8426. }
  8427. }
  8428. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  8429. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  8430. $reference_images = [];
  8431. $product_index_map = []; // 产品名称 => 图片序号的映射
  8432. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  8433. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  8434. $current_index = 1;
  8435. if (!empty($matches[1])) {
  8436. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  8437. $seen_products = []; // 用于去重
  8438. foreach ($matches[1] as $product_name) {
  8439. // 跳过已处理的产品
  8440. if (isset($seen_products[$product_name])) {
  8441. continue;
  8442. }
  8443. $seen_products[$product_name] = true;
  8444. // 检查产品是否在字典中
  8445. if (isset($product_dict[$product_name])) {
  8446. $url = $product_dict[$product_name]['url'];
  8447. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  8448. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  8449. if (!empty($voice_prompt) && $product_name !== '旁白') {
  8450. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  8451. }
  8452. // 只有URL非空才分配序号和添加到参考图片
  8453. if (!empty($url)) {
  8454. // 检查URL是否已经在reference_images中(去重)
  8455. if (!in_array($url, $reference_images)) {
  8456. $reference_images[] = $url;
  8457. $product_index_map[$product_name] = $current_index;
  8458. $current_index++;
  8459. } else {
  8460. // URL重复,找到已有的序号
  8461. $existing_index = array_search($url, $reference_images) + 1;
  8462. $product_index_map[$product_name] = $existing_index;
  8463. }
  8464. } else {
  8465. // URL为空,不分配序号(后续直接去掉{})
  8466. $product_index_map[$product_name] = 0;
  8467. }
  8468. } else {
  8469. // 产品不在字典中,不分配序号
  8470. $product_index_map[$product_name] = 0;
  8471. }
  8472. }
  8473. }
  8474. // 第二步:替换内容中的 {产品名称}
  8475. $processedContent = $actContent;
  8476. foreach ($product_index_map as $product_name => $index) {
  8477. $escaped_name = preg_quote($product_name, '/');
  8478. if ($index > 0) {
  8479. // 有图片,替换为:产品名称(图X)
  8480. $replacement = $product_name . '<图片' . $index . '>';
  8481. } else {
  8482. // 无图片,只保留产品名称
  8483. $replacement = $product_name;
  8484. }
  8485. // 替换所有 {产品名称} 为处理后的格式
  8486. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  8487. }
  8488. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  8489. foreach ($products as $product) {
  8490. $product_name = getProp($product, 'product_name');
  8491. $voice_prompt = getProp($product, 'voice_prompt');
  8492. if ($product_name === '旁白' && !empty($voice_prompt)) {
  8493. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  8494. break; // 找到旁白后退出循环
  8495. }
  8496. }
  8497. // 第四步:将voice_prompt信息添加到内容最前面
  8498. $voice_prompt_prefix = '';
  8499. if (!empty($voice_prompts)) {
  8500. $voice_prompt_prefix .= implode('', $voice_prompts);
  8501. }
  8502. // 旁白的voice_prompt放在最后
  8503. if (!empty($narrator_voice_prompt)) {
  8504. $voice_prompt_prefix .= $narrator_voice_prompt;
  8505. }
  8506. // 如果有voice_prompt信息,添加到内容开头
  8507. if (!empty($voice_prompt_prefix)) {
  8508. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  8509. }
  8510. return [
  8511. 'content' => $processedContent,
  8512. 'reference_images' => $reference_images
  8513. ];
  8514. }
  8515. public function saveActVideoGenerateParams($data) {
  8516. $episode_id = getProp($data, 'episode_id');
  8517. $model = getProp($data, 'video_model');
  8518. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  8519. if (!in_array($model, $valid_models)) {
  8520. Utils::throwError('20003:该模型不可用');
  8521. }
  8522. // 验证模型是否在可用模型表中
  8523. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8524. Utils::throwError('20003:该模型已不可用,请更换!');
  8525. }
  8526. $video_resolution = getProp($data, 'video_resolution', '720p');
  8527. $ratio = getProp($data, 'ratio');
  8528. if (!$ratio) $ratio = '9:16';
  8529. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  8530. if (!$episode) {
  8531. Utils::throwError('20003:分集不存在');
  8532. }
  8533. dLog('anime')->info('保存分集视频参数', $data);
  8534. try {
  8535. DB::beginTransaction();
  8536. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8537. 'video_model' => $model,
  8538. 'video_resolution' => $video_resolution,
  8539. 'ratio' => $ratio,
  8540. 'updated_at' => date('Y-m-d H:i:s')
  8541. ]);
  8542. if ($result === false) {
  8543. Utils::throwError('20003:分集视频参数保存失败');
  8544. }
  8545. // 同步更新mp_animes表
  8546. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  8547. 'video_model' => $model,
  8548. 'video_resolution' => $video_resolution,
  8549. 'video_ratio' => $ratio,
  8550. 'updated_at' => date('Y-m-d H:i:s')
  8551. ]);
  8552. if ($anime_result === false) {
  8553. Utils::throwError('20003:动漫视频参数保存失败');
  8554. }
  8555. } catch (\Exception $e) {
  8556. DB::rollBack();
  8557. Utils::throwError('20003:'.$e->getMessage());
  8558. }
  8559. DB::commit();
  8560. return $result;
  8561. }
  8562. public function confirmActs($data) {
  8563. $episode_id = getProp($data, 'episode_id');
  8564. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  8565. if (!$episode) {
  8566. Utils::throwError('20003:分集不存在');
  8567. }
  8568. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  8569. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  8570. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  8571. // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
  8572. $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
  8573. // 获取所有片段数据
  8574. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8575. // 收集所有资产名称(角色、场景、道具)
  8576. $product_names = [];
  8577. // 收集角色名称
  8578. foreach ($roles as $role) {
  8579. $role_name = getProp($role, 'role');
  8580. if ($role_name && $role_name != '旁白') {
  8581. $product_names[] = $role_name;
  8582. }
  8583. }
  8584. // 收集场景名称
  8585. foreach ($scenes as $scene) {
  8586. $scene_name = getProp($scene, 'scene');
  8587. if ($scene_name) {
  8588. $product_names[] = $scene_name;
  8589. }
  8590. }
  8591. // 收集道具名称
  8592. foreach ($props as $prop) {
  8593. $prop_name = getProp($prop, 'prop');
  8594. if ($prop_name) {
  8595. $product_names[] = $prop_name;
  8596. }
  8597. }
  8598. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8599. $product_names = array_unique($product_names);
  8600. usort($product_names, function($a, $b) {
  8601. return mb_strlen($b) - mb_strlen($a);
  8602. });
  8603. try {
  8604. DB::beginTransaction();
  8605. // 处理每个片段
  8606. foreach ($acts as $act) {
  8607. $act_content = getProp($act, 'act_content');
  8608. if (!$act_content) continue;
  8609. $processed_content = $act_content;
  8610. // 统一替换所有资产名称为 {资产名} 格式
  8611. // 使用占位符避免嵌套替换问题
  8612. $placeholder_map = [];
  8613. $placeholder_index = 0;
  8614. foreach ($product_names as $product_name) {
  8615. // 转义特殊字符
  8616. $escaped_product = preg_quote($product_name, '/');
  8617. // 检查是否匹配且未被 {} 包裹
  8618. $processed_content = preg_replace_callback(
  8619. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8620. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8621. // 使用唯一占位符
  8622. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8623. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8624. $placeholder_index++;
  8625. return $placeholder;
  8626. },
  8627. $processed_content
  8628. );
  8629. }
  8630. // 将所有占位符替换回实际内容
  8631. foreach ($placeholder_map as $placeholder => $replacement) {
  8632. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8633. }
  8634. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8635. $shot_counter = 0;
  8636. $processed_content = preg_replace_callback(
  8637. '/【(?:镜头|分镜)(\d+)】/u',
  8638. function($matches) use (&$shot_counter) {
  8639. $shot_counter++;
  8640. return '【镜头' . $shot_counter . '】';
  8641. },
  8642. $processed_content
  8643. );
  8644. // 更新数据库
  8645. $boolen = DB::table('mp_episode_segments')
  8646. ->where('id', $act->id)
  8647. ->update([
  8648. 'act_show_content' => $processed_content,
  8649. 'updated_at' => date('Y-m-d H:i:s')
  8650. ]);
  8651. if (!$boolen) {
  8652. Utils::throwError('20003:片段处理失败');
  8653. }
  8654. }
  8655. }catch (\Exception $e) {
  8656. DB::rollBack();
  8657. Utils::throwError('20003:'.$e->getMessage());
  8658. }
  8659. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8660. 'is_generated' => 1,
  8661. 'updated_at' => date('Y-m-d H:i:s')
  8662. ]);
  8663. if (!$boolen1) {
  8664. DB::rollBack();
  8665. Utils::throwError('20003:分集处理失败!');
  8666. }
  8667. DB::commit();
  8668. // 重新查询更新后的片段数据
  8669. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8670. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  8671. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  8672. $products = [];
  8673. // 先处理角色数组
  8674. foreach ($roles as $role) {
  8675. $product = $role;
  8676. // 将role字段重命名为product_name
  8677. if (isset($product['role'])) {
  8678. $product['product_name'] = $product['role'];
  8679. unset($product['role']);
  8680. $product['product'] = 1; // 标记类型为角色
  8681. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8682. }
  8683. }
  8684. // 处理场景数组
  8685. foreach ($scenes as $scene) {
  8686. $product = $scene;
  8687. // 将scene字段重命名为product_name
  8688. if (isset($product['scene'])) {
  8689. $product['product_name'] = $product['scene'];
  8690. unset($product['scene']);
  8691. $product['product'] = 2; // 标记类型为场景
  8692. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8693. }
  8694. }
  8695. // 处理道具数组(逻辑与场景一致)
  8696. foreach ($props as $prop) {
  8697. $product = $prop;
  8698. // 将prop字段重命名为product_name
  8699. if (isset($product['prop'])) {
  8700. $product['product_name'] = $product['prop'];
  8701. unset($product['prop']);
  8702. $product['product'] = 3; // 标记类型为道具
  8703. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8704. }
  8705. }
  8706. // extra_products优先级更高,直接覆盖同名的roles和scenes
  8707. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  8708. foreach ($extra_products as $extra_product) {
  8709. $product_name = getProp($extra_product, 'product_name');
  8710. if ($product_name) {
  8711. $products[$product_name] = $extra_product; // 覆盖同名数据
  8712. }
  8713. }
  8714. // mp_script_product_mappings 信息优先级更高:
  8715. // 获取当前剧集所属动漫剧本下、与本集资产同名的资产库最新数据(url/三视图/提示词等),
  8716. // 覆盖分集 JSON 中保存的同名旧快照;分集内独有的 description、voice_prompt 等字段保留
  8717. $anime = DB::table('mp_animes')->where('id', getProp($episode, 'anime_id'))->first();
  8718. $script_id = $anime ? (int)getProp($anime, 'script_id', 0) : 0;
  8719. if ($script_id && !empty($products)) {
  8720. $currentProductNames = array_keys($products);
  8721. $normalizeName = function($name) {
  8722. return trim(preg_replace(
  8723. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  8724. '',
  8725. trim((string)$name)
  8726. ));
  8727. };
  8728. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  8729. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8730. ->where('mapping.script_id', $script_id)
  8731. ->where('product.is_deleted', 0)
  8732. ->whereIn('product.product_name', $currentProductNames)
  8733. ->select(
  8734. 'mapping.product_id',
  8735. 'product.product_name',
  8736. 'product.product',
  8737. 'product.pic_prompt',
  8738. 'product.url',
  8739. 'product.three_view_image_url',
  8740. )
  8741. ->get();
  8742. $mappingByName = [];
  8743. foreach ($mappingItems as $mappingItem) {
  8744. $normalizedName = $normalizeName($mappingItem->product_name);
  8745. if (!$normalizedName) continue;
  8746. $mappingByName[$normalizedName] = [
  8747. 'product_id' => (int)$mappingItem->product_id,
  8748. 'product_name' => $mappingItem->product_name,
  8749. 'product' => (int)$mappingItem->product,
  8750. 'pic_prompt' => $mappingItem->pic_prompt ?? '',
  8751. 'url' => $mappingItem->url ?? '',
  8752. 'three_view_image_url' => $mappingItem->three_view_image_url ?? '',
  8753. ];
  8754. }
  8755. foreach ($products as $key => &$product) {
  8756. $normalizedKey = $normalizeName($key);
  8757. if ($normalizedKey && isset($mappingByName[$normalizedKey])) {
  8758. $product = array_merge($product, $mappingByName[$normalizedKey]);
  8759. }
  8760. }
  8761. unset($product);
  8762. }
  8763. // 兼容返回 three_view_image_url 字段(旧数据可能没有该键,统一补空值)
  8764. foreach ($products as &$product) {
  8765. if (!isset($product['three_view_image_url'])) {
  8766. $product['three_view_image_url'] = '';
  8767. }
  8768. }
  8769. unset($product);
  8770. // 重新索引数组(去除key)
  8771. $products = array_values($products);
  8772. // 构建返回的acts数组
  8773. $return_acts = [];
  8774. foreach ($acts as $act) {
  8775. $return_acts[] = [
  8776. 'act_id' => getProp($act, 'id'),
  8777. 'act_number' => getProp($act, 'act_number'),
  8778. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  8779. 'act_show_content' => getProp($act, 'act_show_content'),
  8780. 'video_url' => getProp($act, 'video_url'),
  8781. 'video_duration' => getProp($act, 'video_duration'),
  8782. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  8783. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  8784. ];
  8785. }
  8786. return [
  8787. 'anime_id' => getProp($episode, 'anime_id'),
  8788. 'episode_id' => $episode_id,
  8789. 'title' => getProp($episode, 'title'),
  8790. 'episode_number' => getProp($episode, 'episode_number'),
  8791. 'is_generated' => getProp($episode, 'is_generated'),
  8792. 'video_params' => [
  8793. 'video_model' => getProp($episode, 'video_model'),
  8794. 'video_resolution' => getProp($episode, 'video_resolution'),
  8795. 'ratio' => getProp($episode, 'ratio'),
  8796. ],
  8797. 'products' => $products,
  8798. 'acts' => $return_acts
  8799. ];
  8800. }
  8801. /**
  8802. * 参照 episodePicsInfo 的更新与监控逻辑:
  8803. * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
  8804. * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
  8805. */
  8806. private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
  8807. $pollInterval = 5; // 每5秒查询一次
  8808. $maxWaitSeconds = 60; // 最多持续1分钟
  8809. $startTime = time();
  8810. while (true) {
  8811. // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
  8812. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  8813. if (!$episode) {
  8814. Utils::throwError('20003:分集不存在');
  8815. }
  8816. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  8817. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  8818. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  8819. $updated = false;
  8820. $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
  8821. $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
  8822. $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
  8823. $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
  8824. $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
  8825. // 有图片任务结果更新时写回分集表
  8826. if ($updated) {
  8827. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8828. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  8829. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  8830. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  8831. 'updated_at' => date('Y-m-d H:i:s')
  8832. ]);
  8833. }
  8834. // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
  8835. if (empty($waitingAssets) && empty($missingAssets)) {
  8836. return;
  8837. }
  8838. // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
  8839. if (empty($waitingAssets)) {
  8840. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  8841. }
  8842. // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
  8843. if (time() - $startTime >= $maxWaitSeconds) {
  8844. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  8845. }
  8846. sleep($pollInterval);
  8847. }
  8848. }
  8849. /**
  8850. * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
  8851. * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
  8852. * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
  8853. */
  8854. private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
  8855. foreach ($assets as &$asset) {
  8856. $assetName = getProp($asset, $nameKey);
  8857. if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
  8858. continue;
  8859. }
  8860. // 已有图片URL的资产视为已生成
  8861. if (getProp($asset, 'url')) {
  8862. continue;
  8863. }
  8864. $task_id = getProp($asset, 'task_id');
  8865. // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
  8866. if (!$task_id) {
  8867. $missingAssets[] = $assetName;
  8868. continue;
  8869. }
  8870. $task = DB::table('mp_generate_pic_tasks')
  8871. ->where('id', $task_id)
  8872. ->select('status', 'result_url')
  8873. ->first();
  8874. // 任务不存在:同样记录为缺失项,不在此处直接报错
  8875. if (!$task) {
  8876. $missingAssets[] = $assetName;
  8877. continue;
  8878. }
  8879. if ($task->status === 'success') {
  8880. $result_url = getProp($task, 'result_url');
  8881. if ($result_url) {
  8882. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  8883. if (is_array($result_urls) && !empty($result_urls[0])) {
  8884. $asset['url'] = $result_urls[0];
  8885. $asset['task_status'] = 'success';
  8886. $updated = true;
  8887. continue;
  8888. }
  8889. }
  8890. // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
  8891. $waitingAssets[] = $assetName;
  8892. } elseif ($task->status === 'failed') {
  8893. // 生成失败:记录为缺失项,待其他任务处理完后统一报错
  8894. $missingAssets[] = $assetName;
  8895. } else {
  8896. // 任务仍在生成中,等待下一次轮询
  8897. $waitingAssets[] = $assetName;
  8898. }
  8899. }
  8900. unset($asset);
  8901. }
  8902. /**
  8903. * 导出动漫剧本为PDF(参照示例PDF版式)
  8904. * @param int $animeId 动漫ID
  8905. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  8906. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  8907. * @return string|null
  8908. */
  8909. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  8910. // 图片下载与转换可能占用较多内存
  8911. ini_set('memory_limit', '512M');
  8912. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  8913. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  8914. $anime = (array)$anime;
  8915. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  8916. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  8917. // 获取分集(默认展示版本,按集数升序)
  8918. $episodeQuery = DB::table('mp_anime_episodes')
  8919. ->where('anime_id', $animeId)
  8920. ->where('is_default', 1)
  8921. ->orderBy('episode_number')
  8922. ->orderBy('id');
  8923. if ($episodeCount > 0) {
  8924. $episodeQuery->limit($episodeCount);
  8925. }
  8926. $episodes = $episodeQuery->get()->map(function ($value) {
  8927. return (array)$value;
  8928. })->toArray();
  8929. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  8930. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  8931. $roles = $this->mergeEpisodeItems($episodes, 'role');
  8932. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  8933. $props = $this->mergeEpisodeItems($episodes, 'prop');
  8934. // 组装分集剧本数据
  8935. $episodeScripts = [];
  8936. foreach ($episodes as $episode) {
  8937. $segments = DB::table('mp_episode_segments')
  8938. ->where('anime_id', $animeId)
  8939. ->where('episode_id', $episode['id'])
  8940. ->get();
  8941. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  8942. $acts = [];
  8943. foreach ($segments as $segment) {
  8944. $segment = (array)$segment;
  8945. $actNumber = (int)getProp($segment, 'act_number', 0);
  8946. if ($actNumber <= 0) continue;
  8947. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  8948. $acts[$actNumber] = [
  8949. 'id' => (int)$segment['id'],
  8950. 'act_number' => $actNumber,
  8951. 'duration' => getProp($segment, 'act_duration', ''),
  8952. 'content' => getProp($segment, 'act_content', ''),
  8953. ];
  8954. }
  8955. }
  8956. ksort($acts);
  8957. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  8958. $segmentCounter = 0;
  8959. foreach ($acts as &$act) {
  8960. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  8961. }
  8962. unset($act);
  8963. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  8964. $narratorVoice = '';
  8965. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  8966. foreach ($episodeRoles as $role) {
  8967. if (getProp($role, 'role') === '旁白') {
  8968. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  8969. break;
  8970. }
  8971. }
  8972. if ($narratorVoice === '') {
  8973. foreach ($acts as $act) {
  8974. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  8975. $narratorVoice = trim($match[1]);
  8976. break;
  8977. }
  8978. }
  8979. }
  8980. $episodeScripts[] = [
  8981. 'episode_number' => getProp($episode, 'episode_number'),
  8982. 'title' => getProp($episode, 'title', ''),
  8983. 'act_count' => count($acts),
  8984. 'narrator_voice' => $narratorVoice,
  8985. 'acts' => array_values($acts),
  8986. ];
  8987. }
  8988. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  8989. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  8990. // 构建PDF
  8991. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  8992. // 图片已嵌入PDF,清理临时文件
  8993. foreach ($imageCache as $imgFile) {
  8994. @unlink($imgFile);
  8995. }
  8996. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  8997. if ($savePath) {
  8998. $pdf->Output($savePath, 'F');
  8999. return $savePath;
  9000. }
  9001. // 直接下载输出
  9002. header('Content-Type: application/pdf');
  9003. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  9004. $pdf->Output($filename . '.pdf', 'D');
  9005. exit();
  9006. }
  9007. /**
  9008. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  9009. * @param array $episodes 分集数据
  9010. * @param string $nameKey role|scene|prop
  9011. * @return array
  9012. */
  9013. private function mergeEpisodeItems(array $episodes, $nameKey) {
  9014. $fieldMap = [
  9015. 'role' => 'roles',
  9016. 'scene' => 'scenes',
  9017. 'prop' => 'props',
  9018. ];
  9019. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  9020. $items = [];
  9021. foreach ($episodes as $episode) {
  9022. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  9023. foreach ($list as $item) {
  9024. if (!is_array($item)) continue;
  9025. $name = trim((string)getProp($item, $nameKey, ''));
  9026. if ($name === '') continue;
  9027. // 旁白不进入主体列表(仅作为旁白音色来源)
  9028. if ($nameKey === 'role' && $name === '旁白') continue;
  9029. if (!isset($items[$name])) {
  9030. $items[$name] = $item;
  9031. }
  9032. }
  9033. }
  9034. return array_values($items);
  9035. }
  9036. /**
  9037. * 构建动漫剧本PDF
  9038. * @param array $anime 动漫信息
  9039. * @param array $roles 主体列表
  9040. * @param array $scenes 场景列表
  9041. * @param array $props 道具列表
  9042. * @param array $episodeScripts 分集剧本数据
  9043. * @param array $imageCache 图片缓存(url => 临时文件路径)
  9044. * @return \TCPDF
  9045. */
  9046. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  9047. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  9048. $pdf->SetCreator('动漫剧本导出系统');
  9049. $pdf->SetAuthor('系统');
  9050. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  9051. $pdf->SetSubject('动漫剧本导出');
  9052. $pdf->SetMargins(15, 15, 15);
  9053. $pdf->SetAutoPageBreak(true, 15);
  9054. // 剧本名
  9055. $pdf->AddPage();
  9056. $pdf->SetFont('simsun', 'B', 20);
  9057. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  9058. $pdf->Ln(5);
  9059. // 故事梗概
  9060. $intro = trim((string)getProp($anime, 'intro', ''));
  9061. if ($intro !== '') {
  9062. $this->pdfSectionTitle($pdf, '故事梗概');
  9063. $this->pdfBody($pdf, $intro);
  9064. }
  9065. // 美术风格
  9066. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  9067. if ($artStyle !== '') {
  9068. $this->pdfSectionTitle($pdf, '美术风格');
  9069. $this->pdfBody($pdf, $artStyle);
  9070. }
  9071. // 主体列表(文字+图片)
  9072. $this->pdfSectionTitle($pdf, '主体列表');
  9073. foreach ($roles as $index => $role) {
  9074. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  9075. }
  9076. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  9077. // 场景列表(文字+图片)
  9078. $this->pdfSectionTitle($pdf, '场景列表');
  9079. foreach ($scenes as $index => $scene) {
  9080. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  9081. }
  9082. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  9083. // 道具列表(文字+图片)
  9084. $this->pdfSectionTitle($pdf, '道具列表');
  9085. foreach ($props as $index => $prop) {
  9086. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  9087. }
  9088. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  9089. // 分镜剧本
  9090. $this->pdfSectionTitle($pdf, '分镜剧本');
  9091. foreach ($episodeScripts as $episodeScript) {
  9092. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  9093. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  9094. if ($episodeTitleRaw !== '') {
  9095. // title 字段可能已带"第N集"前缀,避免重复
  9096. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  9097. $episodeTitle = $episodeTitleRaw;
  9098. } else {
  9099. $episodeTitle .= ':' . $episodeTitleRaw;
  9100. }
  9101. }
  9102. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  9103. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  9104. if (getProp($episodeScript, 'narrator_voice') !== '') {
  9105. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  9106. }
  9107. foreach (getProp($episodeScript, 'acts', []) as $act) {
  9108. $actTitle = '片段' . getProp($act, 'act_number');
  9109. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  9110. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  9111. }
  9112. $this->pdfSubTitle($pdf, $actTitle, 12);
  9113. if (getProp($act, 'content') !== '') {
  9114. $this->pdfBody($pdf, getProp($act, 'content'));
  9115. }
  9116. }
  9117. }
  9118. return $pdf;
  9119. }
  9120. /**
  9121. * PDF章节标题(带分隔线)
  9122. */
  9123. private function pdfSectionTitle($pdf, $title) {
  9124. if ($pdf->GetY() > 230) {
  9125. $pdf->AddPage();
  9126. }
  9127. $pdf->SetFont('simsun', 'B', 15);
  9128. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  9129. $y = $pdf->GetY();
  9130. $pdf->SetLineWidth(0.4);
  9131. $pdf->Line(15, $y, 195, $y);
  9132. $pdf->Ln(4);
  9133. }
  9134. /**
  9135. * PDF子标题(集数/片段标题)
  9136. */
  9137. private function pdfSubTitle($pdf, $title, $size = 13) {
  9138. if ($pdf->GetY() > 240) {
  9139. $pdf->AddPage();
  9140. }
  9141. $pdf->SetFont('simsun', 'B', $size);
  9142. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  9143. $pdf->Ln(1);
  9144. }
  9145. /**
  9146. * PDF正文段落
  9147. */
  9148. private function pdfBody($pdf, $text) {
  9149. $pdf->SetFont('simsun', '', 11);
  9150. $pdf->MultiCell(0, 6, $text, 0, 'L');
  9151. $pdf->Ln(2);
  9152. }
  9153. /**
  9154. * 输出列表项图片(每张图单独一页,图下标注名称)
  9155. * @param \TCPDF $pdf
  9156. * @param array $items 列表项
  9157. * @param string $nameKey role|scene|prop
  9158. * @param array $imageCache 图片缓存(url => 临时文件路径)
  9159. */
  9160. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  9161. foreach ($items as $item) {
  9162. $url = trim((string)getProp($item, 'url', ''));
  9163. $name = trim((string)getProp($item, $nameKey, ''));
  9164. if ($url === '' || !isset($imageCache[$url])) continue;
  9165. $imgPath = $imageCache[$url];
  9166. $size = @getimagesize($imgPath);
  9167. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  9168. continue;
  9169. }
  9170. $pdf->AddPage();
  9171. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  9172. $maxW = 160;
  9173. $maxH = 170;
  9174. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  9175. $drawW = $size[0] * $ratio;
  9176. $drawH = $size[1] * $ratio;
  9177. $x = (210 - $drawW) / 2;
  9178. $y = max(15, (297 - $drawH) / 2 - 10);
  9179. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  9180. // 图下标注名称
  9181. $pdf->SetFont('simsun', 'B', 13);
  9182. $pdf->SetY(297 - 28);
  9183. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  9184. }
  9185. }
  9186. /**
  9187. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  9188. * @param array $items 包含url字段的列表项
  9189. * @return array url => 临时文件路径
  9190. */
  9191. private function downloadImagesConcurrently(array $items) {
  9192. // 收集唯一的图片URL
  9193. $urls = [];
  9194. foreach ($items as $item) {
  9195. $url = trim((string)getProp($item, 'url', ''));
  9196. if ($url !== '') $urls[$url] = true;
  9197. }
  9198. if (!$urls) return [];
  9199. $urls = array_keys($urls);
  9200. $tmpDir = sys_get_temp_dir();
  9201. $rawFiles = [];
  9202. foreach ($urls as $url) {
  9203. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  9204. $rawFiles[$url] = $rawFile;
  9205. }
  9206. $client = new Client(['timeout' => 180, 'verify' => false]);
  9207. // 低并发下载,sink写入文件避免大图占用内存
  9208. $generator = (function () use ($urls, $client, $rawFiles) {
  9209. foreach ($urls as $url) {
  9210. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  9211. }
  9212. })();
  9213. $errors = [];
  9214. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  9215. 'concurrency' => 4,
  9216. 'rejected' => function ($reason, $url) use (&$errors) {
  9217. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  9218. },
  9219. ]);
  9220. $each->promise()->wait();
  9221. // 失败的图片串行重试一次(独占带宽,提高成功率)
  9222. foreach ($urls as $url) {
  9223. if (!isset($errors[$url])) continue;
  9224. try {
  9225. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  9226. unset($errors[$url]);
  9227. } catch (\Throwable $e) {
  9228. // 重试仍失败
  9229. }
  9230. }
  9231. $cache = [];
  9232. foreach ($urls as $url) {
  9233. $rawFile = $rawFiles[$url];
  9234. if (isset($errors[$url])) {
  9235. dLog('anime')->error('导出PDF图片下载失败', [
  9236. 'url' => $url,
  9237. 'error' => $errors[$url],
  9238. ]);
  9239. @unlink($rawFile);
  9240. continue;
  9241. }
  9242. $converted = $this->convertImageFile($rawFile, $url);
  9243. if ($converted !== null) {
  9244. $cache[$url] = $converted;
  9245. } else {
  9246. @unlink($rawFile);
  9247. }
  9248. }
  9249. return $cache;
  9250. }
  9251. /**
  9252. * 将已下载的图片文件缩放并转为JPEG
  9253. * @param string $rawFile 原始图片临时文件
  9254. * @param string $url 图片地址(用于命名)
  9255. * @return string|null 转换后的文件路径,转换失败返回null
  9256. */
  9257. private function convertImageFile($rawFile, $url) {
  9258. $content = @file_get_contents($rawFile);
  9259. if ($content === false || $content === '') return null;
  9260. if (!function_exists('imagecreatefromstring')) return null;
  9261. $image = @imagecreatefromstring($content);
  9262. if ($image === false) return null;
  9263. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  9264. imagedestroy($image);
  9265. if ($jpeg !== null) {
  9266. @unlink($rawFile);
  9267. }
  9268. return $jpeg;
  9269. }
  9270. /**
  9271. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  9272. * @param resource $srcImage GD图片资源
  9273. * @param string $rawFile 原始图片临时文件
  9274. * @param string $url 图片地址(用于命名)
  9275. * @return string|null 压缩后的JPEG文件路径
  9276. */
  9277. private function compressImageForPdf($srcImage, $rawFile, $url) {
  9278. $maxBytes = 2 * 1024 * 1024; // 2MB
  9279. $sizes = [2048, 1600, 1280, 1024, 800];
  9280. $qualities = [85, 70, 55, 40];
  9281. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  9282. foreach ($sizes as $size) {
  9283. $resized = $this->copyAndResize($srcImage, $size);
  9284. $flat = $this->flattenToWhite($resized);
  9285. imagedestroy($resized);
  9286. foreach ($qualities as $quality) {
  9287. ob_start();
  9288. $saved = imagejpeg($flat, null, $quality);
  9289. $data = ob_get_clean();
  9290. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  9291. file_put_contents($jpeg, $data);
  9292. imagedestroy($flat);
  9293. dLog('anime')->info('导出PDF图片压缩完成', [
  9294. 'url' => $url,
  9295. 'size' => filesize($jpeg),
  9296. 'edge' => $size,
  9297. 'quality' => $quality,
  9298. ]);
  9299. return $jpeg;
  9300. }
  9301. }
  9302. imagedestroy($flat);
  9303. }
  9304. // 兜底:最小尺寸、最低质量强制输出
  9305. $resized = $this->copyAndResize($srcImage, 800);
  9306. $flat = $this->flattenToWhite($resized);
  9307. imagedestroy($resized);
  9308. $saved = imagejpeg($flat, $jpeg, 30);
  9309. imagedestroy($flat);
  9310. if (!$saved) return null;
  9311. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  9312. 'url' => $url,
  9313. 'size' => filesize($jpeg),
  9314. ]);
  9315. return $jpeg;
  9316. }
  9317. /**
  9318. * 等比缩放图片副本(不销毁原图)
  9319. * @param resource $srcImage GD图片资源
  9320. * @param int $maxEdge 最大边长
  9321. * @return resource
  9322. */
  9323. private function copyAndResize($srcImage, $maxEdge) {
  9324. $width = imagesx($srcImage);
  9325. $height = imagesy($srcImage);
  9326. $max = max($width, $height);
  9327. if ($max <= $maxEdge) {
  9328. $copy = imagecreatetruecolor($width, $height);
  9329. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  9330. return $copy;
  9331. }
  9332. $ratio = $maxEdge / $max;
  9333. $newWidth = max(1, (int)round($width * $ratio));
  9334. $newHeight = max(1, (int)round($height * $ratio));
  9335. $resized = imagecreatetruecolor($newWidth, $newHeight);
  9336. imagealphablending($resized, false);
  9337. imagesavealpha($resized, true);
  9338. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  9339. return $resized;
  9340. }
  9341. /**
  9342. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  9343. * @param resource $image GD图片资源
  9344. * @return resource
  9345. */
  9346. private function flattenToWhite($image) {
  9347. $width = imagesx($image);
  9348. $height = imagesy($image);
  9349. $flat = imagecreatetruecolor($width, $height);
  9350. $white = imagecolorallocate($flat, 255, 255, 255);
  9351. imagefill($flat, 0, 0, $white);
  9352. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  9353. return $flat;
  9354. }
  9355. /**
  9356. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  9357. * @param string $content 片段内容
  9358. * @param int $counter 当前已编号数量(引用传递,整集累计)
  9359. * @return string
  9360. */
  9361. private function renumberSegmentBlocks($content, &$counter) {
  9362. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  9363. $counter++;
  9364. return '【' . $match[1] . $counter . '】';
  9365. }, $content);
  9366. }
  9367. }