AnimeService.php 475 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Exceptions\ApiException;
  6. use App\Facade\Site;
  7. use App\Libs\Utils;
  8. use App\Models\MpGeneratePicTask;
  9. use App\Models\MpTaskCenter;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use App\Services\AIGeneration\AIVideoGenerationService;
  12. use App\Services\DeepSeek\DeepSeekService;
  13. use App\Services\PointsService;
  14. use App\Services\TaskCenterService;
  15. use Dflydev\DotAccessData\Util;
  16. use GuzzleHttp\Client;
  17. use Illuminate\Support\Facades\DB;
  18. use Illuminate\Support\Facades\Log;
  19. use Illuminate\Support\Facades\Redis;
  20. use OSS\Core\OssException;
  21. use OSS\OssClient;
  22. class AnimeService
  23. {
  24. protected $aiImageGenerationService;
  25. protected $aiVideoGenerationService;
  26. protected $DeepSeekService;
  27. protected $pointsService;
  28. protected $taskCenterService;
  29. private $url;
  30. private $api_key;
  31. private $headers;
  32. public function __construct(
  33. AIImageGenerationService $aiImageGenerationService,
  34. AIVideoGenerationService $aiVideoGenerationService,
  35. DeepSeekService $DeepSeekService,
  36. PointsService $pointsService,
  37. TaskCenterService $taskCenterService
  38. ) {
  39. $this->aiImageGenerationService = $aiImageGenerationService;
  40. $this->aiVideoGenerationService = $aiVideoGenerationService;
  41. $this->DeepSeekService = $DeepSeekService;
  42. $this->pointsService = $pointsService;
  43. $this->taskCenterService = $taskCenterService;
  44. $this->url = 'https://api.deepseek.com/chat/completions';
  45. $this->api_key = env('DEEPSEEK_API_KEY');
  46. $this->headers = [
  47. 'Authorization' => 'Bearer '.$this->api_key,
  48. 'Content-Type' => 'application/json; charset=UTF-8'
  49. ];
  50. }
  51. /**
  52. * 构建统一的分镜数据结构(episodeInfo格式)
  53. * @param array $segments 分镜数据数组
  54. * @return array 返回包含acts和total_duration的数组
  55. */
  56. public function buildEpisodeSegmentsStructure($segments) {
  57. $acts = [];
  58. $totalDuration = 0; // 初始化总时长
  59. foreach($segments as $segment) {
  60. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  61. $videoDuration = getProp($segment, 'video_duration');
  62. $audioDuration = getProp($segment, 'audio_duration');
  63. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  64. $totalDuration += floatval($videoDuration);
  65. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  66. $totalDuration += floatval($audioDuration);
  67. } else {
  68. $totalDuration += 5; // 默认5秒
  69. }
  70. $segment_content = getProp($segment, 'segment_content');
  71. // 判断是否有尾帧描述,如果有则去掉这部分内容
  72. if (strpos($segment_content, '尾帧') !== false) {
  73. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  74. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  75. }
  76. // 构建分镜信息
  77. $segmentInfo = [
  78. 'segment_id' => getProp($segment, 'segment_id'),
  79. 'segment_number' => getProp($segment, 'segment_number'),
  80. 'segment_content' => $segment_content,
  81. 'description' => getProp($segment, 'description'),
  82. 'composition' => getProp($segment, 'composition'),
  83. 'camera_movement' => getProp($segment, 'camera_movement'),
  84. 'voice_actor' => getProp($segment, 'voice_actor'),
  85. 'dialogue' => getProp($segment, 'dialogue'),
  86. 'frame_type' => getProp($segment, 'frame_type'),
  87. 'scene' => getProp($segment, 'scene'),
  88. 'characters' => getProp($segment, 'characters'),
  89. 'tail_frame' => getProp($segment, 'tail_frame'),
  90. 'emotion' => getProp($segment, 'emotion'),
  91. 'emotion_type' => getProp($segment, 'emotion_type'),
  92. 'gender' => getProp($segment, 'gender'),
  93. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  94. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  95. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  96. 'pitch' => getProp($segment, 'pitch'),
  97. 'voice_name' => getProp($segment, 'voice_name'),
  98. 'voice_type' => getProp($segment, 'voice_type'),
  99. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  100. 'img_url' => getProp($segment, 'img_url'),
  101. 'audio_url' => getProp($segment, 'audio_url'),
  102. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  103. 'video_url' => getProp($segment, 'video_url'),
  104. 'video_duration' => getProp($segment, 'video_duration', 0),
  105. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  106. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  107. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  108. 'current_type' => getProp($segment, 'current_type'),
  109. ];
  110. $actNumber = getProp($segment, 'act_number');
  111. if (isset($acts[$actNumber])) {
  112. $acts[$actNumber]['segments'][] = $segmentInfo;
  113. } else {
  114. $acts[$actNumber] = [
  115. 'act_number' => $actNumber,
  116. 'act_title' => getProp($segment, 'act_title'),
  117. 'act_duration' => getProp($segment, 'act_duration'),
  118. 'segments' => [$segmentInfo]
  119. ];
  120. }
  121. }
  122. return [
  123. 'acts' => array_values($acts),
  124. 'total_duration' => intval(round($totalDuration))
  125. ];
  126. }
  127. /**
  128. * 构建统一的分段数据结构(episodeInfoForAce格式)
  129. * @param array $segments 分段数据数组
  130. * @return array 返回包含acts和total_duration的数组
  131. */
  132. public function buildEpisodeActsStructureForAce($segments) {
  133. $acts = [];
  134. $totalDuration = 0; // 初始化总时长
  135. foreach($segments as $segment) {
  136. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  137. $videoDuration = getProp($segment, 'video_duration');
  138. $actDuration = getProp($segment, 'act_duration');
  139. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  140. $totalDuration += floatval($videoDuration);
  141. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  142. $totalDuration += floatval($actDuration);
  143. } else {
  144. $totalDuration += 5; // 默认5秒
  145. }
  146. // 构建分镜信息
  147. $segmentInfo = [
  148. 'act_id' => getProp($segment, 'id'),
  149. 'act_number' => getProp($segment, 'act_number'),
  150. 'act_title' => getProp($segment, 'act_title'),
  151. 'act_duration' => getProp($segment, 'act_duration'),
  152. 'act_content' => getProp($segment, 'act_content'),
  153. 'video_url' => getProp($segment, 'video_url'),
  154. 'video_duration' => getProp($segment, 'video_duration', 0),
  155. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  156. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  157. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  158. 'current_type' => getProp($segment, 'current_type'),
  159. ];
  160. $acts[] = $segmentInfo;
  161. }
  162. return [
  163. 'acts' => array_values($acts),
  164. 'total_duration' => intval(round($totalDuration))
  165. ];
  166. }
  167. /**
  168. * 验证画面比例是否有效
  169. * @param string $ratio 画面比例
  170. * @return bool
  171. */
  172. public function validateRatio($ratio) {
  173. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  174. }
  175. /**
  176. * 获取画面比例对应的宽高
  177. * @param string $ratio 画面比例
  178. * @return array ['width' => int, 'height' => int]
  179. * @throws \Exception
  180. */
  181. private function getRatioDimensions($ratio) {
  182. if ($ratio && !$this->validateRatio($ratio)) {
  183. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  184. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  185. }
  186. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  187. }
  188. public function createAnime($data) {
  189. $uid = Site::getUid();
  190. $cpid = Site::getCpid();
  191. $input_art_style = getProp($data, 'art_style');
  192. $file = getProp($data, 'file');
  193. $content = getProp($data, 'content', '');
  194. $bid = getProp($data, 'bid', 0);
  195. $script_id = getProp($data, 'script_id', 0);
  196. $ace_mode = getProp($data, 'ace_mode', 0);
  197. $extra_products = getProp($data, 'products', []);
  198. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  199. if (!is_array($extra_products)) {
  200. Utils::throwError('20003:传入的资产格式不正确');
  201. }
  202. // 替换美术风格
  203. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  204. // 提取文件内容
  205. if ($file) {
  206. $content = $this->DeepSeekService->extractFileContent($file);
  207. if (!$content) {
  208. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  209. }
  210. } elseif ($script_id) {
  211. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  212. if (!$content) {
  213. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  214. }
  215. } elseif ($bid) {
  216. $content = $this->DeepSeekService->getContentByBid($bid);
  217. if (!$content) {
  218. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  219. }
  220. } elseif ($content) {
  221. $content = filterContent($content);
  222. }else {
  223. $content = '';
  224. }
  225. $anime_data = [
  226. 'user_id' => $uid,
  227. 'cpid' => $cpid,
  228. 'anime_name' => '新剧本策划',
  229. 'is_multi' => getProp($data, 'is_multi', 1),
  230. 'content' => $content,
  231. 'art_style_type' => $input_art_style,
  232. 'ace_mode' => $ace_mode,
  233. 'script_id' => $script_id,
  234. 'extra_products' => json_encode($extra_products, 256),
  235. 'created_at' => date('Y-m-d H:i:s'),
  236. 'updated_at' => date('Y-m-d H:i:s'),
  237. ];
  238. // 处理文本模型
  239. $model = getProp($data, 'model');
  240. if (!$model) {
  241. // 用户没有输入,使用默认值
  242. $model = 'deepseek-v4-pro';
  243. }
  244. // 验证模型是否在可用模型表中
  245. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  246. $model = 'deepseek-v4-pro';
  247. }
  248. $anime_data['model'] = $model;
  249. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  250. return DB::table('mp_animes')->insertGetId($anime_data);
  251. }
  252. public function chatList($data) {
  253. $uid = Site::getUid();
  254. $anime_name = getProp($data, 'anime_name');
  255. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  256. if ($anime_name) {
  257. $query->where('anime_name', 'like', "%$anime_name%");
  258. }
  259. return $query->orderBy('id', 'desc')->paginate();
  260. }
  261. public function chatHistory($data) {
  262. $anime_id = getProp($data, 'anime_id');
  263. $sequence = getProp($data, 'sequence', 0);
  264. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  265. $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)
  266. ->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');
  267. return $query->orderBy('ar.id')->get()->map(function ($value) {
  268. $value = (array)$value;
  269. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  270. $value['created_at'] = transDate($value['created_at']);
  271. $value['episode_created_at'] = transDate($value['episode_created_at']);
  272. return $value;
  273. })->toArray();
  274. }
  275. public function batchSetRoleImg($data) {
  276. $episode_id = getProp($data, 'episode_id');
  277. if (!$episode_id) Utils::throwError('1002:请选择分集');
  278. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  279. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  280. $art_style = getProp($episode, 'art_style');
  281. $anime_id = getProp($episode, 'anime_id');
  282. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  283. $art_style_type = getProp($anime, 'art_style_type');
  284. $character_prefix = '';
  285. $scene_prefix = '';
  286. if ($art_style_type) {
  287. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  288. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  289. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  290. }
  291. foreach ($roles as &$role) {
  292. $role_name = getProp($role, 'role');
  293. if ($role_name == '旁白') continue;
  294. // 优先使用 pic_prompt,如果没有则使用 description
  295. $pic_prompt = getProp($role, 'pic_prompt');
  296. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  297. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  298. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  299. // 参考图地址
  300. $ref_img_url = getProp($role, 'url');
  301. if ($ref_img_url) continue; // 已有图片则跳过
  302. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  303. try {
  304. $params = [
  305. 'prompt' => $description,
  306. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  307. ];
  308. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  309. $task_id = $task->id;
  310. if (!$task_id) {
  311. Utils::throwError("20003:角色({$role_name})生成图片失败");
  312. }
  313. $role['task_id'] = $task_id;
  314. $role['task_status'] = 'processing';
  315. } catch (\Exception $e) {
  316. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  317. Utils::throwError("20003:" . $e->getMessage());
  318. }
  319. }
  320. // 保存角色信息
  321. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  322. 'roles' => json_encode($roles, 256),
  323. 'generate_status' => '执行中',
  324. 'generate_at' => date('Y-m-d H:i:s'),
  325. 'updated_at' => date('Y-m-d H:i:s')
  326. ]);
  327. if (!$boolen) {
  328. Utils::throwError('20003:保存角色信息失败');
  329. }
  330. return $boolen;
  331. }
  332. public function batchSetSceneImg($data) {
  333. $episode_id = getProp($data, 'episode_id');
  334. if (!$episode_id) Utils::throwError('1002:请选择分集');
  335. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  336. $scenes = json_decode(getProp($episode, 'scenes'), true);
  337. $art_style = getProp($episode, 'art_style');
  338. $target_scene = getProp($data, 'target_scene');
  339. $anime_id = getProp($episode, 'anime_id');
  340. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  341. $art_style_type = getProp($anime, 'art_style_type');
  342. $character_prefix = '';
  343. $scene_prefix = '';
  344. if ($art_style_type) {
  345. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  346. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  347. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  348. }
  349. foreach ($scenes as &$scene) {
  350. $scene_name = getProp($scene, 'scene');
  351. if ($scene_name != $target_scene) continue;
  352. // 优先使用 pic_prompt,如果没有则使用 description
  353. $pic_prompt = getProp($scene, 'pic_prompt');
  354. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  355. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  356. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  357. // 参考图地址
  358. $ref_img_url = getProp($scene, 'url');
  359. if ($ref_img_url) continue; // 已有图片则跳过
  360. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  361. try {
  362. $params = [
  363. 'prompt' => $description,
  364. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  365. ];
  366. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  367. $task_id = $task->id;
  368. if (!$task_id) {
  369. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  370. }
  371. $scene['task_id'] = $task_id;
  372. $scene['task_status'] = 'processing';
  373. } catch (\Exception $e) {
  374. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  375. Utils::throwError("20003:" . $e->getMessage());
  376. }
  377. }
  378. // 保存场景信息
  379. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  380. 'scenes' => json_encode($scenes, 256),
  381. 'generate_status' => '执行中',
  382. 'generate_at' => date('Y-m-d H:i:s'),
  383. 'updated_at' => date('Y-m-d H:i:s')
  384. ]);
  385. if (!$boolen) {
  386. Utils::throwError('20003:保存角色信息失败');
  387. }
  388. return $boolen;
  389. }
  390. public function editAnime($data) {
  391. $anime_id = getProp($data, 'anime_id');
  392. $anime_name = trim(getProp($data, 'anime_name'));
  393. // 确认对话名称唯一性
  394. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  395. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  396. }
  397. if (!$anime_id || !$anime_name) {
  398. Utils::throwError('20003:参数异常');
  399. }
  400. return DB::table('mp_animes')->where('id', $anime_id)->update([
  401. 'anime_name' => $anime_name,
  402. 'updated_at' => date('Y-m-d H:i:s')
  403. ]);
  404. // $script_arr =getProp($data, 'script', []);
  405. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  406. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  407. // $anime_id = getProp($data, 'anime_id');
  408. // try {
  409. // DB::beginTransaction();
  410. // $table_data = [
  411. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  412. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  413. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  414. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  415. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  416. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  417. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  418. // 'status' => 3,
  419. // 'start_episode_sequence' => $start_episode_sequence,
  420. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  421. // 'episode_num' => count($script_arr['episodes']),
  422. // 'updated_at' => date('Y-m-d H:i:s')
  423. // ];
  424. // // 保存剧本内容
  425. // if (!empty($anime_id)) {
  426. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  427. // if (!$boolen) {
  428. // dLog('anime')->info('对话保存失败', $table_data);
  429. // Utils::throwError('20003:对话保存失败');
  430. // }
  431. // }else {
  432. // $table['created_at'] = $table_data['updated_at'];
  433. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  434. // if (!$anime_id) {
  435. // dLog('anime')->info('对话保存失败', $table_data);
  436. // Utils::throwError('20003:对话保存失败');
  437. // }
  438. // }
  439. // // 保存分集内容
  440. // // 删除历史分集内容
  441. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  442. // $episodes = [];
  443. // $sequence = 1;
  444. // foreach ($script_arr['episodes'] as $episode) {
  445. // $segment_number = 1;
  446. // foreach($episode['segments'] as $segment) {
  447. // $episodes[] = [
  448. // 'anime_id' => $anime_id,
  449. // 'episode_number' => $episode['episode_number'],
  450. // 'title' => $episode['title'],
  451. // // 'content' => $episode['content'],
  452. // 'content' => '',
  453. // 'segment_number' => $segment_number,
  454. // 'segment_content' => $segment['segment_content'],
  455. // 'sequence' => $sequence,
  456. // 'created_at' => date('Y-m-d H:i:s'),
  457. // 'updated_at' => date('Y-m-d H:i:s')
  458. // ];
  459. // $sequence++;
  460. // $segment_number++;
  461. // }
  462. // }
  463. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  464. // if (!$boolen2) {
  465. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  466. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  467. // Utils::throwError('20003:分集内容保存失败');
  468. // }
  469. // } catch (\Exception $e) {
  470. // DB::rollBack();
  471. // Utils::throwError('20003:'.$e->getMessage());
  472. // }
  473. // DB::commit();
  474. // return true;
  475. }
  476. public function delAnime($data) {
  477. $anime_id = getProp($data, 'anime_id');
  478. if (!$anime_id) {
  479. Utils::throwError('20003:请选择剧本');
  480. }
  481. return DB::table('mp_animes')->where('id', $anime_id)->update([
  482. 'is_deleted' => 1,
  483. 'updated_at' => date('Y-m-d H:i:s')
  484. ]);
  485. }
  486. public function animeDetail($data) {
  487. $uid = Site::getUid();
  488. $anime_id = getProp($data, 'anime_id');
  489. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  490. ->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();
  491. if (!$anime) Utils::throwError('20003:权限不足');
  492. $anime = (array)$anime;
  493. $anime['roles'] = json_decode($anime['roles']);
  494. $anime['scenes'] = json_decode($anime['scenes']);
  495. // 获取分集信息
  496. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  497. ->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"))
  498. ->orderBy('episode_number')->get()->map(function ($value) {
  499. return (array)$value;
  500. })->toArray();
  501. $anime['episodes'] = $episodes;
  502. // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
  503. $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
  504. $episodeTasks = DB::table('mp_batch_episode_generation_details')
  505. ->where('anime_id', $anime_id)
  506. ->whereIn('status', ['pending', 'processing', 'failed']) // 只获取待生成/生成中任务,已完成或失败的不显示
  507. ->orderBy('episode_number')
  508. ->get()
  509. ->map(function ($task) use ($episodeNumbers) {
  510. if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
  511. return null;
  512. }
  513. return [
  514. 'episode_number' => (int)$task->episode_number,
  515. 'status' => $task->status,
  516. 'error_message' => $task->status == 'failed' ? $task->error_message : '',
  517. ];
  518. })
  519. ->filter()
  520. ->values()
  521. ->toArray();
  522. $anime['episode_tasks'] = $episodeTasks;
  523. return $anime;
  524. }
  525. public function episodeInfo($data) {
  526. $uid = Site::getUid();
  527. $anime_id = getProp($data, 'anime_id');
  528. $episode_id = getProp($data, 'episode_id');
  529. if (!$anime_id || !$episode_id) {
  530. Utils::throwError('1002:请选择剧集');
  531. }
  532. // 验证用户权限
  533. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  534. if (!$anime) Utils::throwError('20003:权限不足');
  535. $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();
  536. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  537. $episode = (array)$episode;
  538. $episode['roles'] = json_decode($episode['roles'], true);
  539. // foreach($episode['roles'] as &$item) {
  540. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  541. // }
  542. $episode['scenes'] = json_decode($episode['scenes'], true);
  543. // foreach($episode['scenes'] as &$item) {
  544. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  545. // }
  546. // 获取分镜信息
  547. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  548. ->select('*')->get()->map(function ($value) {
  549. return (array)$value;
  550. })->toArray();
  551. // 使用公共方法构建分镜结构
  552. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  553. $episode['acts'] = $segmentsStructure['acts'];
  554. $episode['total_duration'] = $segmentsStructure['total_duration'];
  555. return $episode;
  556. }
  557. public function episodeInfoForAce($data) {
  558. $anime_id = getProp($data, 'anime_id');
  559. $episode_id = getProp($data, 'episode_id');
  560. if (!$anime_id || !$episode_id) {
  561. Utils::throwError('1002:请选择剧集');
  562. }
  563. $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();
  564. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  565. $episode = (array)$episode;
  566. $episode['roles'] = json_decode($episode['roles'], true);
  567. // foreach($episode['roles'] as &$item) {
  568. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  569. // }
  570. $episode['scenes'] = json_decode($episode['scenes'], true);
  571. // foreach($episode['scenes'] as &$item) {
  572. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  573. // }
  574. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  575. // 获取分镜信息
  576. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  577. ->select('*')->get()->map(function ($value) {
  578. return (array)$value;
  579. })->toArray();
  580. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  581. $episode['acts'] = $segmentsStructure['acts'];
  582. $episode['total_duration'] = $segmentsStructure['total_duration'];
  583. // 获取mp_animes表中的视频参数
  584. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  585. $episode['video_params'] = [
  586. 'video_model' => getProp($anime, 'video_model'),
  587. 'video_resolution' => getProp($anime, 'video_resolution'),
  588. 'ratio' => getProp($anime, 'video_ratio'),
  589. ];
  590. return $episode;
  591. }
  592. public function segmentInfo($data) {
  593. $uid = Site::getUid();
  594. $segment_id = getProp($data, 'segment_id');
  595. if (!$segment_id) {
  596. Utils::throwError('1002:请选择分镜');
  597. }
  598. // 获取分镜信息
  599. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  600. // 验证用户权限
  601. if ($segment) {
  602. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  603. if (!$anime) Utils::throwError('20003:权限不足');
  604. }
  605. $result = [
  606. 'segment_id' => getProp($segment, 'segment_id'),
  607. 'segment_number' => getProp($segment, 'segment_number'),
  608. 'segment_content' => getProp($segment, 'segment_content'),
  609. 'description' => getProp($segment, 'description'),
  610. 'composition' => getProp($segment, 'composition'),
  611. 'camera_movement' => getProp($segment, 'camera_movement'),
  612. 'voice_actor' => getProp($segment, 'voice_actor'),
  613. 'dialogue' => getProp($segment, 'dialogue'),
  614. 'frame_type' => getProp($segment, 'frame_type'),
  615. 'scene' => getProp($segment, 'scene'),
  616. 'characters' => getProp($segment, 'characters'),
  617. 'tail_frame' => getProp($segment, 'tail_frame'),
  618. 'emotion' => getProp($segment, 'emotion'),
  619. 'emotion_type' => getProp($segment, 'emotion_type'),
  620. 'gender' => getProp($segment, 'gender'),
  621. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  622. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  623. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  624. 'pitch' => getProp($segment, 'pitch'),
  625. 'voice_name' => getProp($segment, 'voice_name'),
  626. 'voice_type' => getProp($segment, 'voice_type'),
  627. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  628. 'img_url' => getProp($segment, 'img_url'),
  629. 'video_url' => getProp($segment, 'video_url'),
  630. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  631. ];
  632. return $result;
  633. }
  634. public function copyEpisodeVersion($data) {
  635. $episode_id = getProp($data, 'episode_id');
  636. $uid = Site::getUid();
  637. $cpid = Site::getCpid();
  638. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  639. if (!$episode) Utils::throwError('20003:该剧集不存在');
  640. $episode = (array)$episode;
  641. $anime_id = $episode['anime_id'];
  642. $episode_number = $episode['episode_number'];
  643. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  644. $sequence = $count + 1;
  645. unset($episode['id']);
  646. $now = date('Y-m-d H:i:s');
  647. $episode['created_at'] = $now;
  648. $episode['updated_at'] = $now;
  649. $episode['is_default'] = 1;
  650. // 获取版本中含有"(副本"字样的个数
  651. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  652. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  653. $episode['sequence'] = $sequence;
  654. $episode['is_generated'] = 0;
  655. $episode['cpid'] = $cpid;
  656. // 获取ace_mode
  657. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  658. try {
  659. DB::beginTransaction();
  660. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  661. // 新增副本
  662. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  663. if (!$new_episode_id) {
  664. Utils::throwError('20003:创建副本失败!');
  665. }
  666. // 获取分镜数据并准备插入
  667. $segments_for_insert = DB::table('mp_episode_segments')
  668. ->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')
  669. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  670. $item = (array)$item;
  671. $item['episode_id'] = $new_episode_id;
  672. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  673. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  674. return $item;
  675. })->toArray();
  676. // 写入分镜数据
  677. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  678. if (!$boolen2) {
  679. Utils::throwError('20003:写入分镜数据失败!');
  680. }
  681. // 写入对话历史
  682. $records = [
  683. [
  684. 'uid' => $uid,
  685. 'anime_id' => $anime_id,
  686. 'role' => 'user',
  687. 'content' => '创建副本',
  688. 'sequence' => $episode_number,
  689. 'episode_id' => $new_episode_id,
  690. 'created_at' => $now,
  691. 'updated_at' => $now
  692. ],
  693. [
  694. 'uid' => $uid,
  695. 'anime_id' => $anime_id,
  696. 'role' => 'assistant',
  697. 'content' => '好的,已为您创建副本',
  698. 'sequence' => $episode_number,
  699. 'episode_id' => $new_episode_id,
  700. 'created_at' => $now,
  701. 'updated_at' => $now
  702. ]
  703. ];
  704. $boolen3 = DB::table('mp_anime_records')->insert($records);
  705. if (!$boolen3) {
  706. Utils::throwError('20003:对话记录保存失败');
  707. }
  708. }catch (\Exception $e) {
  709. DB::rollBack();
  710. Utils::throwError('20003:'.$e->getMessage());
  711. }
  712. DB::commit();
  713. // 构建与 episodeInfo 方法一致的返回数据结构
  714. $result = [
  715. 'episode_id' => $new_episode_id,
  716. 'anime_id' => $anime_id,
  717. 'episode_number' => $episode_number,
  718. 'title' => $episode['title'],
  719. 'intro' => $episode['intro'],
  720. 'art_style' => $episode['art_style'],
  721. 'roles' => json_decode($episode['roles'], true),
  722. 'scenes' => json_decode($episode['scenes'], true),
  723. 'is_generated' => (int)$episode['is_generated']
  724. ];
  725. if ((int)$ace_mode === 1) {
  726. // 获取分镜信息
  727. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  728. ->select('*')->get()->map(function ($value) {
  729. return (array)$value;
  730. })->toArray();
  731. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  732. }else {
  733. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  734. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  735. }
  736. $result['acts'] = $segmentsStructure['acts'];
  737. $result['total_duration'] = $segmentsStructure['total_duration'];
  738. return $result;
  739. }
  740. public function episodeVersions($data) {
  741. $anime_id = getProp($data, 'anime_id');
  742. $episode_id = getProp($data, 'episode_id');
  743. if (!$anime_id || !$episode_id) {
  744. Utils::throwError('1002:请选择剧集');
  745. }
  746. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  747. $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) {
  748. return (array)$value;
  749. })->toArray();
  750. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  751. foreach($episodes as &$episode) {
  752. $episode['version'] = 'V'.$episode['sequence'];
  753. $episode['roles'] = json_decode($episode['roles'], true);
  754. $episode['scenes'] = json_decode($episode['scenes'], true);
  755. // 获取分镜信息
  756. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  757. ->select('*')->get()->map(function ($value) {
  758. return (array)$value;
  759. })->toArray();
  760. // 使用公共方法构建分镜结构
  761. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  762. $episode['acts'] = $segmentsStructure['acts'];
  763. $episode['total_duration'] = $segmentsStructure['total_duration'];
  764. }
  765. return $episodes;
  766. }
  767. public function bindEpisodeVersion($data) {
  768. $episode_id = getProp($data, 'episode_id');
  769. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  770. if (!$episode) Utils::throwError('20003:该剧集不存在');
  771. $episode = (array)$episode;
  772. if ((int)$episode['is_default'] === 1) return true;
  773. try {
  774. DB::beginTransaction();
  775. // 移除is_default标志
  776. $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')]);
  777. if (!$boolen) {
  778. Utils::throwError('20003:更新失败!');
  779. }
  780. // 绑定副本
  781. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  782. if (!$boolen2) {
  783. Utils::throwError('20003:绑定失败!');
  784. }
  785. }catch (\Exception $e) {
  786. DB::rollBack();
  787. Utils::throwError('20003:'.$e->getMessage());
  788. }
  789. DB::commit();
  790. return true;
  791. }
  792. public function chatChangeImg($data) {
  793. $segment_id = getProp($data, 'segment_id');
  794. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  795. $prompt = getProp($data, 'prompt');
  796. if (!$prompt || !$segment_id) {
  797. Utils::throwError('1002:请输入提示词,并且选择分镜');
  798. }
  799. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  800. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  801. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  802. else $ref_img_url = '';
  803. // $ref_img_url = '';
  804. if (empty($prompt)) {
  805. if (empty($ref_img_url)) {
  806. $prompt = getProp($segment, 'segment_content');
  807. }else {
  808. $prompt = '请根据图片生成';
  809. }
  810. }
  811. $anime_id = getProp($segment, 'anime_id');
  812. $episode_id = getProp($segment, 'episode_id');
  813. $episode_number = getProp($segment, 'episode_number');
  814. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  815. $ratio = getProp($data, 'ratio');
  816. if (!$ratio) {
  817. $ratio = getProp($episode, 'ratio');
  818. if (!$ratio) $ratio = '9:16';
  819. }
  820. $art_style = getProp($episode, 'art_style');
  821. if ($art_style) {
  822. $prompt = "美术风格:{$art_style}\n{$prompt}";
  823. }
  824. $dimensions = $this->getRatioDimensions($ratio);
  825. $width = $dimensions['width'];
  826. $height = $dimensions['height'];
  827. try {
  828. $params = [
  829. 'alias_segment_id' => $segment_id,
  830. 'prompt' => $prompt,
  831. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  832. 'width' => $width,
  833. 'height' => $height
  834. ];
  835. // 优化提示词(不要生成字幕)
  836. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  837. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  838. $task_id = $task->id;
  839. if (!$task_id) {
  840. Utils::throwError("20003:生成图片失败");
  841. }
  842. // 更新任务ID
  843. $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')]);
  844. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  845. } catch (\Exception $e) {
  846. Utils::throwError("20003:" . $e->getMessage());
  847. }
  848. // 创建任务之后先暂停10s等待异步任务完成
  849. sleep(10);
  850. $img_url = $this->loopGetPicTaskResult($task_id);
  851. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  852. // 图片生成后新增对话记录
  853. try {
  854. $uid = Site::getUid();
  855. $now = date('Y-m-d H:i:s');
  856. // 使用AI反推图片提示词
  857. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  858. // 保存对话记录
  859. $records = [
  860. [
  861. 'uid' => $uid,
  862. 'anime_id' => $anime_id,
  863. 'sequence' => $episode_number,
  864. 'role' => 'user',
  865. 'content' => $prompt,
  866. 'segment_id' => $segment_id,
  867. 'pic_task_id' => $task_id,
  868. 'image_url' => '',
  869. 'created_at' => $now,
  870. 'updated_at' => $now
  871. ],
  872. [
  873. 'uid' => $uid,
  874. 'anime_id' => $anime_id,
  875. 'sequence' => $episode_number,
  876. 'role' => 'assistant',
  877. 'content' => $pic_prompt,
  878. 'segment_id' => $segment_id,
  879. 'pic_task_id' => $task_id,
  880. 'image_url' => $img_url,
  881. 'created_at' => $now,
  882. 'updated_at' => $now
  883. ]
  884. ];
  885. DB::table('mp_anime_records')->insert($records);
  886. } catch (\Exception $e) {
  887. // 记录日志但不影响主流程
  888. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  889. 'segment_id' => $segment_id,
  890. 'img_url' => $img_url
  891. ]);
  892. logDB('anime', 'error', '保存对话记录失败', [
  893. 'segment_id' => $segment_id,
  894. 'img_url' => $img_url,
  895. 'error' => $e->getMessage()
  896. ]);
  897. }
  898. return $img_url;
  899. }
  900. public function segmentChatHistory($data) {
  901. $segment_id = getProp($data, 'segment_id');
  902. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  903. $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');
  904. $chat = $query->orderBy('id')->get()->map(function ($value) {
  905. $value = (array)$value;
  906. $value['created_at'] = transDate($value['created_at']);
  907. return $value;
  908. })->toArray();
  909. // 获取历史图片
  910. $url = [];
  911. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  912. foreach($pic_history as $task) {
  913. $result_url = getProp($task, 'result_url');
  914. if (is_json($result_url)) {
  915. $url = array_merge($url, json_decode($result_url, true));
  916. }else {
  917. $url[] = $result_url;
  918. }
  919. }
  920. // 获取历史视频
  921. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  922. foreach($video_history as $task) {
  923. $result_url = getProp($task, 'compressed_url');
  924. if (is_json($result_url)) {
  925. $url = array_merge($url, json_decode($result_url, true));
  926. }else {
  927. $url[] = $result_url;
  928. }
  929. }
  930. return compact('chat', 'url');
  931. }
  932. public function changeEpisodeRoles($data) {
  933. $anime_id = getProp($data, 'anime_id');
  934. $episode_id = getProp($data, 'episode_id');
  935. $target_roles = getProp($data, 'roles');
  936. // 删除标志位于角色对象内部(roles.is_deleted),不在最外层
  937. $is_deleted = getProp($target_roles, 'is_deleted', 0);
  938. // 控制字段不随角色内容写入分集roles存储
  939. if (is_array($target_roles)) {
  940. unset($target_roles['is_deleted']);
  941. }
  942. // 参数验证
  943. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  944. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  945. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  946. // 验证剧集是否存在
  947. $episode = DB::table('mp_anime_episodes')
  948. ->where('anime_id', $anime_id)
  949. ->where('id', $episode_id)
  950. ->first();
  951. if (!$episode) Utils::throwError('20003:该剧集不存在');
  952. $roles = json_decode(getProp($episode, 'roles'), true);
  953. // 获取anime信息,检查是否有关联的script_id
  954. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  955. if (!$anime) Utils::throwError('20003:动漫不存在');
  956. $script_id = getProp($anime, 'script_id');
  957. $episode_number = getProp($episode, 'episode_number', 1);
  958. $uid = Site::getUid();
  959. $cpid = Site::getCpid();
  960. try {
  961. $target_role_name = getProp($target_roles, 'role');
  962. if (empty($target_role_name)) {
  963. Utils::throwError('20003:角色名称不能为空');
  964. }
  965. // 如果是删除操作
  966. if ($is_deleted == 1) {
  967. // 从角色列表中移除该角色
  968. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  969. return getProp($role, 'role') !== $target_role_name;
  970. }));
  971. // 更新角色列表
  972. $result = DB::table('mp_anime_episodes')
  973. ->where('anime_id', $anime_id)
  974. ->where('id', $episode_id)
  975. ->update([
  976. 'roles' => json_encode($roles, 256),
  977. 'updated_at' => date('Y-m-d H:i:s')
  978. ]);
  979. if ($result === false) {
  980. Utils::throwError('20003:删除角色失败');
  981. }
  982. } else {
  983. // 新增或更新操作
  984. $role_found = false;
  985. $is_new_role = false;
  986. // 查找并更新已存在的角色
  987. foreach($roles as &$role) {
  988. if (getProp($role, 'role') === $target_role_name) {
  989. $role = $target_roles;
  990. $role_found = true;
  991. break;
  992. }
  993. }
  994. // 如果角色不存在,则新增
  995. if (!$role_found) {
  996. $roles[] = $target_roles;
  997. $is_new_role = true;
  998. }
  999. // 更新角色列表
  1000. $result = DB::table('mp_anime_episodes')
  1001. ->where('anime_id', $anime_id)
  1002. ->where('id', $episode_id)
  1003. ->update([
  1004. 'roles' => json_encode($roles, 256),
  1005. 'updated_at' => date('Y-m-d H:i:s')
  1006. ]);
  1007. if ($result === false) {
  1008. Utils::throwError('20003:更新角色列表失败');
  1009. }
  1010. // 同步更新分镜表中对应主体的音色信息
  1011. $voice_name = getProp($target_roles, 'voice_name');
  1012. $voice_type = getProp($target_roles, 'voice_type');
  1013. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  1014. DB::table('mp_episode_segments')
  1015. ->where('anime_id', $anime_id)
  1016. ->where('episode_id', $episode_id)
  1017. ->where('voice_actor', $target_role_name)
  1018. ->update([
  1019. 'voice_name' => $voice_name,
  1020. 'voice_type' => $voice_type,
  1021. 'voice_audio_url' => $voice_audio_url,
  1022. 'updated_at' => date('Y-m-d H:i:s')
  1023. ]);
  1024. // 如果有关联的script_id,则同步到mp_products表
  1025. if ($script_id) {
  1026. // 查询剧本信息
  1027. $script = DB::table('mp_scripts')
  1028. ->where('id', $script_id)
  1029. ->where('is_deleted', 0)
  1030. ->first();
  1031. if ($script) {
  1032. $script_name = $script->script_name ?? 'script_' . $script_id;
  1033. $product_name = getProp($target_roles, 'role');
  1034. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1035. $url = getProp($target_roles, 'url', '');
  1036. $product_type = 1; // 1=角色
  1037. // 查找或创建以script_name命名的文件夹
  1038. $folder = DB::table('mp_products')
  1039. ->where('cpid', $cpid)
  1040. ->where('type', 2) // 文件夹类型
  1041. ->where('product', $product_type) // 角色类型
  1042. ->where('product_name', $script_name)
  1043. ->where('parent_id', 0)
  1044. ->where('is_deleted', 0)
  1045. ->first();
  1046. if (!$folder) {
  1047. // 创建文件夹
  1048. $folder_id = DB::table('mp_products')->insertGetId([
  1049. 'user_id' => $uid,
  1050. 'cpid' => $cpid,
  1051. 'type' => 2, // 文件夹
  1052. 'product' => $product_type, // 角色类型
  1053. 'parent_id' => 0,
  1054. 'level' => 1,
  1055. 'product_name' => $script_name,
  1056. 'sort_order' => time(),
  1057. 'is_deleted' => 0,
  1058. 'created_at' => date('Y-m-d H:i:s'),
  1059. 'updated_at' => date('Y-m-d H:i:s')
  1060. ]);
  1061. } else {
  1062. $folder_id = $folder->id;
  1063. }
  1064. // 查找该文件夹下是否已存在同名资产
  1065. $existing_product = DB::table('mp_products')
  1066. ->where('cpid', $cpid)
  1067. ->where('type', 1) // 资产类型
  1068. ->where('product', $product_type)
  1069. ->where('parent_id', $folder_id)
  1070. ->where('product_name', $product_name)
  1071. ->where('is_deleted', 0)
  1072. ->first();
  1073. if ($existing_product) {
  1074. // 更新已存在的资产
  1075. $updateData = [
  1076. 'pic_task_status' => '生成成功',
  1077. ];
  1078. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1079. if ($url) $updateData['url'] = $url;
  1080. // 处理versions字段
  1081. $versions = getProp($target_roles, 'versions', []);
  1082. if ($versions && is_array($versions)) {
  1083. $updateData['versions'] = json_encode($versions, 256);
  1084. }
  1085. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1086. DB::table('mp_products')
  1087. ->where('id', $existing_product->id)
  1088. ->update($updateData);
  1089. $product_id = $existing_product->id;
  1090. } else {
  1091. // 创建新资产
  1092. $versions = getProp($target_roles, 'versions', []);
  1093. $product_id = DB::table('mp_products')->insertGetId([
  1094. 'user_id' => $uid,
  1095. 'cpid' => $cpid,
  1096. 'type' => 1, // 资产
  1097. 'product' => $product_type, // 角色
  1098. 'parent_id' => $folder_id,
  1099. 'level' => 2,
  1100. 'product_name' => $product_name,
  1101. 'url' => $url,
  1102. 'pic_prompt' => $pic_prompt,
  1103. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1104. 'sort_order' => time(),
  1105. 'is_deleted' => 0,
  1106. 'pic_task_status' => '生成成功',
  1107. 'created_at' => date('Y-m-d H:i:s'),
  1108. 'updated_at' => date('Y-m-d H:i:s')
  1109. ]);
  1110. }
  1111. // 建立或更新绑定关系
  1112. $existing_mapping = DB::table('mp_script_product_mappings')
  1113. ->where('script_id', $script_id)
  1114. ->where('product_id', $product_id)
  1115. ->where('episode_number', $episode_number)
  1116. ->first();
  1117. if (!$existing_mapping) {
  1118. // 创建绑定关系
  1119. DB::table('mp_script_product_mappings')->insert([
  1120. 'script_id' => $script_id,
  1121. 'product_id' => $product_id,
  1122. 'episode_number' => $episode_number,
  1123. 'created_at' => date('Y-m-d H:i:s'),
  1124. 'updated_at' => date('Y-m-d H:i:s')
  1125. ]);
  1126. }
  1127. }
  1128. }
  1129. }
  1130. } catch (\Exception $e) {
  1131. dLog('anime')->error('更新剧集角色失败', [
  1132. 'anime_id' => $anime_id,
  1133. 'episode_id' => $episode_id,
  1134. 'error' => $e->getMessage()
  1135. ]);
  1136. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1137. }
  1138. return true;
  1139. }
  1140. public function changeEpisodeScenes($data) {
  1141. $anime_id = getProp($data, 'anime_id');
  1142. $episode_id = getProp($data, 'episode_id');
  1143. $target_scenes = getProp($data, 'scenes');
  1144. // 删除标志位于场景对象内部(scenes.is_deleted),不在最外层
  1145. $is_deleted = getProp($target_scenes, 'is_deleted', 0);
  1146. // 控制字段不随场景内容写入分集scenes存储
  1147. if (is_array($target_scenes)) {
  1148. unset($target_scenes['is_deleted']);
  1149. }
  1150. // 参数验证
  1151. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1152. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1153. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1154. // 验证剧集是否存在
  1155. $episode = DB::table('mp_anime_episodes')
  1156. ->where('anime_id', $anime_id)
  1157. ->where('id', $episode_id)
  1158. ->first();
  1159. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1160. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1161. // 获取anime信息,检查是否有关联的script_id
  1162. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1163. if (!$anime) Utils::throwError('20003:动漫不存在');
  1164. $script_id = getProp($anime, 'script_id');
  1165. $episode_number = getProp($episode, 'episode_number', 1);
  1166. $uid = Site::getUid();
  1167. $cpid = Site::getCpid();
  1168. try {
  1169. $target_scene_name = getProp($target_scenes, 'scene');
  1170. if (empty($target_scene_name)) {
  1171. Utils::throwError('20003:场景名称不能为空');
  1172. }
  1173. // 如果是删除操作
  1174. if ($is_deleted == 1) {
  1175. // 从场景列表中移除该场景
  1176. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1177. return getProp($scene, 'scene') !== $target_scene_name;
  1178. }));
  1179. // 更新场景列表
  1180. $result = DB::table('mp_anime_episodes')
  1181. ->where('anime_id', $anime_id)
  1182. ->where('id', $episode_id)
  1183. ->update([
  1184. 'scenes' => json_encode($scenes, 256),
  1185. 'updated_at' => date('Y-m-d H:i:s')
  1186. ]);
  1187. if ($result === false) {
  1188. Utils::throwError('20003:删除场景失败');
  1189. }
  1190. } else {
  1191. // 新增或更新操作
  1192. $scene_found = false;
  1193. $is_new_scene = false;
  1194. // 查找并更新已存在的场景
  1195. foreach($scenes as &$scene) {
  1196. if (getProp($scene, 'scene') === $target_scene_name) {
  1197. $scene = $target_scenes;
  1198. $scene_found = true;
  1199. break;
  1200. }
  1201. }
  1202. // 如果场景不存在,则新增
  1203. if (!$scene_found) {
  1204. $scenes[] = $target_scenes;
  1205. $is_new_scene = true;
  1206. }
  1207. // 更新场景列表
  1208. $result = DB::table('mp_anime_episodes')
  1209. ->where('anime_id', $anime_id)
  1210. ->where('id', $episode_id)
  1211. ->update([
  1212. 'scenes' => json_encode($scenes, 256),
  1213. 'updated_at' => date('Y-m-d H:i:s')
  1214. ]);
  1215. if ($result === false) {
  1216. Utils::throwError('20003:更新场景列表失败');
  1217. }
  1218. // 如果有关联的script_id,则同步到mp_products表
  1219. if ($script_id) {
  1220. // 查询剧本信息
  1221. $script = DB::table('mp_scripts')
  1222. ->where('id', $script_id)
  1223. ->where('is_deleted', 0)
  1224. ->first();
  1225. if ($script) {
  1226. $script_name = $script->script_name ?? 'script_' . $script_id;
  1227. $product_name = getProp($target_scenes, 'scene');
  1228. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1229. $url = getProp($target_scenes, 'url', '');
  1230. $product_type = 2; // 2=场景
  1231. // 查找或创建以script_name命名的文件夹
  1232. $folder = DB::table('mp_products')
  1233. ->where('cpid', $cpid)
  1234. ->where('type', 2) // 文件夹类型
  1235. ->where('product', $product_type) // 场景类型
  1236. ->where('product_name', $script_name)
  1237. ->where('parent_id', 0)
  1238. ->where('is_deleted', 0)
  1239. ->first();
  1240. if (!$folder) {
  1241. // 创建文件夹
  1242. $folder_id = DB::table('mp_products')->insertGetId([
  1243. 'user_id' => $uid,
  1244. 'cpid' => $cpid,
  1245. 'type' => 2, // 文件夹
  1246. 'product' => $product_type, // 场景类型
  1247. 'parent_id' => 0,
  1248. 'level' => 1,
  1249. 'product_name' => $script_name,
  1250. 'sort_order' => time(),
  1251. 'is_deleted' => 0,
  1252. 'created_at' => date('Y-m-d H:i:s'),
  1253. 'updated_at' => date('Y-m-d H:i:s')
  1254. ]);
  1255. } else {
  1256. $folder_id = $folder->id;
  1257. }
  1258. // 查找该文件夹下是否已存在同名资产
  1259. $existing_product = DB::table('mp_products')
  1260. ->where('cpid', $cpid)
  1261. ->where('type', 1) // 资产类型
  1262. ->where('product', $product_type)
  1263. ->where('parent_id', $folder_id)
  1264. ->where('product_name', $product_name)
  1265. ->where('is_deleted', 0)
  1266. ->first();
  1267. if ($existing_product) {
  1268. // 更新已存在的资产
  1269. $updateData = [
  1270. 'pic_task_status' => '生成成功'
  1271. ];
  1272. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1273. if ($url) $updateData['url'] = $url;
  1274. // 处理versions字段
  1275. $versions = getProp($target_scenes, 'versions', []);
  1276. if ($versions && is_array($versions)) {
  1277. $updateData['versions'] = json_encode($versions, 256);
  1278. }
  1279. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1280. DB::table('mp_products')
  1281. ->where('id', $existing_product->id)
  1282. ->update($updateData);
  1283. $product_id = $existing_product->id;
  1284. } else {
  1285. // 创建新资产
  1286. $versions = getProp($target_scenes, 'versions', []);
  1287. $product_id = DB::table('mp_products')->insertGetId([
  1288. 'user_id' => $uid,
  1289. 'cpid' => $cpid,
  1290. 'type' => 1, // 资产
  1291. 'product' => $product_type, // 场景
  1292. 'parent_id' => $folder_id,
  1293. 'level' => 2,
  1294. 'product_name' => $product_name,
  1295. 'url' => $url,
  1296. 'pic_prompt' => $pic_prompt,
  1297. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1298. 'sort_order' => time(),
  1299. 'is_deleted' => 0,
  1300. 'pic_task_status' => '生成成功',
  1301. 'created_at' => date('Y-m-d H:i:s'),
  1302. 'updated_at' => date('Y-m-d H:i:s')
  1303. ]);
  1304. }
  1305. // 建立或更新绑定关系
  1306. $existing_mapping = DB::table('mp_script_product_mappings')
  1307. ->where('script_id', $script_id)
  1308. ->where('product_id', $product_id)
  1309. ->where('episode_number', $episode_number)
  1310. ->first();
  1311. if (!$existing_mapping) {
  1312. // 创建绑定关系
  1313. DB::table('mp_script_product_mappings')->insert([
  1314. 'script_id' => $script_id,
  1315. 'product_id' => $product_id,
  1316. 'episode_number' => $episode_number,
  1317. 'created_at' => date('Y-m-d H:i:s'),
  1318. 'updated_at' => date('Y-m-d H:i:s')
  1319. ]);
  1320. }
  1321. }
  1322. }
  1323. }
  1324. } catch (\Exception $e) {
  1325. dLog('anime')->error('更新剧集场景失败', [
  1326. 'anime_id' => $anime_id,
  1327. 'episode_id' => $episode_id,
  1328. 'error' => $e->getMessage()
  1329. ]);
  1330. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1331. }
  1332. return true;
  1333. }
  1334. public function changeEpisodeProps($data) {
  1335. $anime_id = getProp($data, 'anime_id');
  1336. $episode_id = getProp($data, 'episode_id');
  1337. $target_props = getProp($data, 'props');
  1338. // 删除标志位于道具对象内部(props.is_deleted),不在最外层
  1339. $is_deleted = getProp($target_props, 'is_deleted', 0);
  1340. // 控制字段不随道具内容写入分集props存储
  1341. if (is_array($target_props)) {
  1342. unset($target_props['is_deleted']);
  1343. }
  1344. // 参数验证
  1345. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1346. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1347. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1348. // 验证剧集是否存在
  1349. $episode = DB::table('mp_anime_episodes')
  1350. ->where('anime_id', $anime_id)
  1351. ->where('id', $episode_id)
  1352. ->first();
  1353. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1354. $props = json_decode(getProp($episode, 'props'), true);
  1355. // 获取anime信息,检查是否有关联的script_id
  1356. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1357. if (!$anime) Utils::throwError('20003:动漫不存在');
  1358. $script_id = getProp($anime, 'script_id');
  1359. $episode_number = getProp($episode, 'episode_number', 1);
  1360. $uid = Site::getUid();
  1361. $cpid = Site::getCpid();
  1362. try {
  1363. $target_prop_name = getProp($target_props, 'prop');
  1364. if (empty($target_prop_name)) {
  1365. Utils::throwError('20003:道具名称不能为空');
  1366. }
  1367. // 如果是删除操作
  1368. if ($is_deleted == 1) {
  1369. // 从道具列表中移除该道具
  1370. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1371. return getProp($prop, 'prop') !== $target_prop_name;
  1372. }));
  1373. // 更新道具列表
  1374. $result = DB::table('mp_anime_episodes')
  1375. ->where('anime_id', $anime_id)
  1376. ->where('id', $episode_id)
  1377. ->update([
  1378. 'props' => json_encode($props, 256),
  1379. 'updated_at' => date('Y-m-d H:i:s')
  1380. ]);
  1381. if ($result === false) {
  1382. Utils::throwError('20003:删除道具失败');
  1383. }
  1384. } else {
  1385. // 新增或更新操作
  1386. $prop_found = false;
  1387. $is_new_prop = false;
  1388. // 查找并更新已存在的道具
  1389. foreach($props as &$prop) {
  1390. if (getProp($prop, 'prop') === $target_prop_name) {
  1391. $prop = $target_props;
  1392. $prop_found = true;
  1393. break;
  1394. }
  1395. }
  1396. // 如果道具不存在,则新增
  1397. if (!$prop_found) {
  1398. $props[] = $target_props;
  1399. $is_new_prop = true;
  1400. }
  1401. // 更新道具列表
  1402. $result = DB::table('mp_anime_episodes')
  1403. ->where('anime_id', $anime_id)
  1404. ->where('id', $episode_id)
  1405. ->update([
  1406. 'props' => json_encode($props, 256),
  1407. 'updated_at' => date('Y-m-d H:i:s')
  1408. ]);
  1409. if ($result === false) {
  1410. Utils::throwError('20003:更新道具列表失败');
  1411. }
  1412. // 如果有关联的script_id,则同步到mp_products表
  1413. if ($script_id) {
  1414. // 查询剧本信息
  1415. $script = DB::table('mp_scripts')
  1416. ->where('id', $script_id)
  1417. ->where('is_deleted', 0)
  1418. ->first();
  1419. if ($script) {
  1420. $script_name = $script->script_name ?? 'script_' . $script_id;
  1421. $product_name = getProp($target_props, 'prop');
  1422. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1423. $url = getProp($target_props, 'url', '');
  1424. $product_type = 3; // 3=道具
  1425. // 查找或创建以script_name命名的文件夹
  1426. $folder = DB::table('mp_products')
  1427. ->where('cpid', $cpid)
  1428. ->where('type', 2) // 文件夹类型
  1429. ->where('product', $product_type) // 道具类型
  1430. ->where('product_name', $script_name)
  1431. ->where('parent_id', 0)
  1432. ->where('is_deleted', 0)
  1433. ->first();
  1434. if (!$folder) {
  1435. // 创建文件夹
  1436. $folder_id = DB::table('mp_products')->insertGetId([
  1437. 'user_id' => $uid,
  1438. 'cpid' => $cpid,
  1439. 'type' => 2, // 文件夹
  1440. 'product' => $product_type, // 道具类型
  1441. 'parent_id' => 0,
  1442. 'level' => 1,
  1443. 'product_name' => $script_name,
  1444. 'sort_order' => time(),
  1445. 'is_deleted' => 0,
  1446. 'created_at' => date('Y-m-d H:i:s'),
  1447. 'updated_at' => date('Y-m-d H:i:s')
  1448. ]);
  1449. } else {
  1450. $folder_id = $folder->id;
  1451. }
  1452. // 查找该文件夹下是否已存在同名资产
  1453. $existing_product = DB::table('mp_products')
  1454. ->where('cpid', $cpid)
  1455. ->where('type', 1) // 资产类型
  1456. ->where('product', $product_type)
  1457. ->where('parent_id', $folder_id)
  1458. ->where('product_name', $product_name)
  1459. ->where('is_deleted', 0)
  1460. ->first();
  1461. if ($existing_product) {
  1462. // 更新已存在的资产
  1463. $updateData = [
  1464. 'pic_task_status' => '生成成功'
  1465. ];
  1466. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1467. if ($url) $updateData['url'] = $url;
  1468. // 处理versions字段
  1469. $versions = getProp($target_props, 'versions', []);
  1470. if ($versions && is_array($versions)) {
  1471. $updateData['versions'] = json_encode($versions, 256);
  1472. }
  1473. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1474. DB::table('mp_products')
  1475. ->where('id', $existing_product->id)
  1476. ->update($updateData);
  1477. $product_id = $existing_product->id;
  1478. } else {
  1479. // 创建新资产
  1480. $versions = getProp($target_props, 'versions', []);
  1481. $product_id = DB::table('mp_products')->insertGetId([
  1482. 'user_id' => $uid,
  1483. 'cpid' => $cpid,
  1484. 'type' => 1, // 资产
  1485. 'product' => $product_type, // 道具
  1486. 'parent_id' => $folder_id,
  1487. 'level' => 2,
  1488. 'product_name' => $product_name,
  1489. 'url' => $url,
  1490. 'pic_prompt' => $pic_prompt,
  1491. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1492. 'sort_order' => time(),
  1493. 'is_deleted' => 0,
  1494. 'pic_task_status' => '生成成功',
  1495. 'created_at' => date('Y-m-d H:i:s'),
  1496. 'updated_at' => date('Y-m-d H:i:s')
  1497. ]);
  1498. }
  1499. // 建立或更新绑定关系
  1500. $existing_mapping = DB::table('mp_script_product_mappings')
  1501. ->where('script_id', $script_id)
  1502. ->where('product_id', $product_id)
  1503. ->where('episode_number', $episode_number)
  1504. ->first();
  1505. if (!$existing_mapping) {
  1506. // 创建绑定关系
  1507. DB::table('mp_script_product_mappings')->insert([
  1508. 'script_id' => $script_id,
  1509. 'product_id' => $product_id,
  1510. 'episode_number' => $episode_number,
  1511. 'created_at' => date('Y-m-d H:i:s'),
  1512. 'updated_at' => date('Y-m-d H:i:s')
  1513. ]);
  1514. }
  1515. }
  1516. }
  1517. }
  1518. } catch (\Exception $e) {
  1519. dLog('anime')->error('更新剧集道具失败', [
  1520. 'anime_id' => $anime_id,
  1521. 'episode_id' => $episode_id,
  1522. 'error' => $e->getMessage()
  1523. ]);
  1524. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1525. }
  1526. return true;
  1527. }
  1528. public function editSegment($data) {
  1529. $segment_id = getProp($data, 'segment_id');
  1530. $segment_content = getProp($data, 'segment_content');
  1531. $image_url = getProp($data, 'image_url');
  1532. $video_url = getProp($data, 'video_url');
  1533. // 参数验证
  1534. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1535. // 验证分镜是否存在
  1536. $segment = DB::table('mp_episode_segments')
  1537. ->where('segment_id', $segment_id)
  1538. ->first();
  1539. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1540. $dubTaskId = 0;
  1541. try {
  1542. DB::beginTransaction();
  1543. // 准备更新数据
  1544. $update_data = [
  1545. 'updated_at' => date('Y-m-d H:i:s')
  1546. ];
  1547. if ($segment_content) {
  1548. // 先将segment_content赋值到update_data
  1549. $update_data['segment_content'] = $segment_content;
  1550. // 使用现有方法分析segment_content,提取各个字段
  1551. $this->handleSegmentContent($update_data);
  1552. // 如果有对话内容,创建视频配音合成任务
  1553. $dialogue = getProp($update_data, 'dialogue');
  1554. if (!empty($dialogue)) {
  1555. $now = date('Y-m-d H:i:s');
  1556. $generate_json = [
  1557. 'text' => $dialogue,
  1558. 'role' => getProp($update_data, 'voice_actor'),
  1559. 'voice_type' => getProp($update_data, 'voice_type'),
  1560. 'voice_name' => getProp($update_data, 'voice_name'),
  1561. 'emotion' => getProp($update_data, 'emotion'),
  1562. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1563. 'gender' => getProp($update_data, 'gender'),
  1564. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1565. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1566. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1567. 'pitch' => getProp($update_data, 'pitch', 0),
  1568. ];
  1569. // 插入视频配音合成任务
  1570. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1571. 'alias_segment_id' => $segment_id,
  1572. 'generate_status' => '执行中',
  1573. 'audio_url' => '',
  1574. 'generate_json' => json_encode($generate_json, 256),
  1575. 'created_at' => $now,
  1576. 'updated_at' => $now,
  1577. ]);
  1578. if (!$dubTaskId) {
  1579. Utils::throwError('20003:创建配音任务失败!');
  1580. }
  1581. $update_data['audio_url'] = '';
  1582. } else {
  1583. // dialogue为空时,直接写入默认音频信息
  1584. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1585. $update_data['audio_duration'] = 2.0;
  1586. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1587. }
  1588. }
  1589. if ($image_url) {
  1590. $update_data['img_url'] = $image_url;
  1591. // 同时写入一个简单的图片生成任务
  1592. $pic_task = [
  1593. 'alias_segment_id' => $segment_id,
  1594. 'ref_img_url' => json_encode([]),
  1595. 'status' => 'success',
  1596. 'result_url' => json_encode([$image_url], 256),
  1597. 'model' => '',
  1598. 'created_at' => date('Y-m-d H:i:s'),
  1599. 'updated_at' => date('Y-m-d H:i:s'),
  1600. ];
  1601. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1602. }
  1603. if ($video_url) {
  1604. $update_data['origin_video_url'] = $video_url;
  1605. $compressed_video_url = compressVideo($video_url);
  1606. $update_data['current_type'] = 2;
  1607. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1608. // 同时写入一个简单的视频生成任务
  1609. $video_task = [
  1610. 'alias_segment_id' => $segment_id,
  1611. 'status' => 'success',
  1612. 'result_url' => $update_data['origin_video_url'],
  1613. 'compressed_url' => $update_data['video_url'],
  1614. 'created_at' => date('Y-m-d H:i:s'),
  1615. 'updated_at' => date('Y-m-d H:i:s'),
  1616. ];
  1617. DB::table('mp_generate_video_tasks')->insert($video_task);
  1618. }
  1619. // 更新分镜信息
  1620. $result = DB::table('mp_episode_segments')
  1621. ->where('segment_id', $segment_id)
  1622. ->update($update_data);
  1623. if ($result === false) {
  1624. Utils::throwError('20003:更新分镜剧本失败');
  1625. }
  1626. DB::commit();
  1627. // 如果有创建音频生成任务则调用API
  1628. if ($dubTaskId) {
  1629. // 请求远程服务器执行生成
  1630. $client = new Client(['timeout' => 300, 'verify' => false]);
  1631. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1632. $response = $result->getBody()->getContents();
  1633. $response_arr = json_decode($response, true);
  1634. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1635. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1636. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1637. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1638. Utils::throwError('20003:火山生成音频失败');
  1639. }
  1640. }
  1641. return true;
  1642. } catch (\Exception $e) {
  1643. DB::rollBack();
  1644. dLog('anime')->error('更新分镜剧本失败', [
  1645. 'segment_id' => $segment_id,
  1646. 'error' => $e->getMessage()
  1647. ]);
  1648. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1649. }
  1650. }
  1651. public function batchSetSegmentPics($data) {
  1652. $anime_id = getProp($data, 'anime_id');
  1653. $episode_id = getProp($data, 'episode_id');
  1654. $ratio = getProp($data, 'ratio');
  1655. $dimensions = $this->getRatioDimensions($ratio);
  1656. $width = $dimensions['width'];
  1657. $height = $dimensions['height'];
  1658. if (!$anime_id || !$episode_id) {
  1659. Utils::throwError('1002:请选择剧集');
  1660. }
  1661. // 获取剧集信息
  1662. $episode = DB::table('mp_anime_episodes')
  1663. ->where('anime_id', $anime_id)
  1664. ->where('id', $episode_id)
  1665. ->where('is_default', 1)
  1666. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1667. ->first();
  1668. if (!$episode) {
  1669. Utils::throwError('20003:该剧集不存在');
  1670. }
  1671. $model = getProp($data, 'model');
  1672. if (!$model) {
  1673. $model = getProp($episode, 'image_model');
  1674. if (!$model) {
  1675. // episode表也没有,使用默认值
  1676. $model = 'doubao-seedream-5-0-lite-260128';
  1677. }
  1678. }
  1679. // 验证模型是否在可用模型表中
  1680. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1681. $model = 'doubao-seedream-5-0-lite-260128';
  1682. }
  1683. $roles = json_decode(getProp($episode, 'roles'), true);
  1684. if (!$roles) {
  1685. Utils::throwError('20003:角色信息格式错误');
  1686. }
  1687. // 构建角色名称到参考图的映射
  1688. $role_map = [];
  1689. foreach ($roles as $role) {
  1690. $role_name = getProp($role, 'role');
  1691. $role_url = getProp($role, 'url');
  1692. if (!empty($role_name) && !empty($role_url)) {
  1693. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1694. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1695. // $role_map[$base_name] = $role_url;
  1696. // 同时保存完整名称的映射
  1697. $role_map[$role_name] = $role_url;
  1698. }
  1699. }
  1700. $scenes = json_decode(getProp($episode, 'roles'), true);
  1701. if (!$scenes) {
  1702. Utils::throwError('20003:场景信息格式错误');
  1703. }
  1704. // 构建角色名称到参考图的映射
  1705. $scene_map = [];
  1706. foreach ($scenes as $scene) {
  1707. $scene_name = getProp($scene, 'scene');
  1708. $scene_url = getProp($scene, 'url');
  1709. if (!empty($scene_name) && !empty($scene_url)) {
  1710. $scene_map[$scene_name] = $scene_url;
  1711. }
  1712. }
  1713. // 获取所有分镜信息
  1714. $segments = DB::table('mp_episode_segments')
  1715. ->where('anime_id', $anime_id)
  1716. ->where('episode_id', $episode_id)
  1717. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1718. ->orderBy('segment_number')
  1719. ->get()
  1720. ->toArray();
  1721. if (empty($segments)) {
  1722. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1723. }
  1724. // 保存图片比例
  1725. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1726. $updated_segments = [];
  1727. $failed_segments = [];
  1728. // 批量为每个分镜生成图片任务
  1729. foreach ($segments as $segment) {
  1730. $segment_id = $segment->segment_id;
  1731. $segment_content = $segment->segment_content;
  1732. if (empty($segment_content)) {
  1733. $failed_segments[] = [
  1734. 'segment_id' => $segment_id,
  1735. 'error' => '分镜内容为空'
  1736. ];
  1737. continue;
  1738. }
  1739. try {
  1740. $dubTaskId = 0;
  1741. // 解析分镜内容,提取画面描述作为主要提示词
  1742. $prompt = $segment_content;
  1743. $ref_img_urls = [];
  1744. // 分镜场景
  1745. $scene = getProp($segment, 'scene');
  1746. $matched_scene = '';
  1747. if (isset($scene_map[$scene])) {
  1748. $img_index = count($ref_img_urls) + 1;
  1749. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1750. $ref_img_urls[] = $scene_map[$scene];
  1751. $matched_scene = $scene;
  1752. }
  1753. // 分镜角色
  1754. $characters = getProp($segment, 'characters');
  1755. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1756. $roles = explode(',', $characters);
  1757. // 从分镜内容中提取涉及的角色
  1758. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1759. // 获取匹配角色的参考图
  1760. foreach ($segment_characters as $character) {
  1761. if (isset($role_map[$character])) {
  1762. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1763. $img_index = count($ref_img_urls) + 1;
  1764. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1765. $ref_img_urls[] = $role_map[$character];
  1766. }
  1767. }
  1768. // 如果没有找到匹配的角色参考图,不使用参考图
  1769. if (empty($ref_img_urls)) {
  1770. $ref_img_urls = [];
  1771. }
  1772. // 准备生成任务参数
  1773. $params = [
  1774. 'model' => $model,
  1775. 'alias_segment_id' => $segment_id,
  1776. 'prompt' => $prompt,
  1777. 'ref_img_urls' => $ref_img_urls,
  1778. 'width' => $width,
  1779. 'height' => $height,
  1780. ];
  1781. // 优化提示词(不要生成字幕)
  1782. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1783. // $task_id = mt_rand(100000, 999999);
  1784. // 调用AI图片生成服务
  1785. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1786. $task_id = $task->id;
  1787. if (!$task_id) {
  1788. $failed_segments[] = [
  1789. 'segment_id' => $segment_id,
  1790. 'error' => '创建生成任务失败'
  1791. ];
  1792. continue;
  1793. }
  1794. $update_data = [
  1795. 'pic_task_id' => $task_id,
  1796. 'pic_task_status' => '生成中',
  1797. 'audio_url' => '',
  1798. 'updated_at' => date('Y-m-d H:i:s')
  1799. ];
  1800. // 如果有对话内容,创建视频配音合成任务
  1801. $dialogue = getProp($segment, 'dialogue');
  1802. if (!empty($dialogue)) {
  1803. $now = date('Y-m-d H:i:s');
  1804. $generate_json = [
  1805. 'text' => $dialogue,
  1806. 'role' => getProp($segment, 'voice_actor'),
  1807. 'voice_type' => getProp($segment, 'voice_type'),
  1808. 'voice_name' => getProp($segment, 'voice_name'),
  1809. 'emotion' => getProp($segment, 'emotion'),
  1810. 'emotion_type' => getProp($segment, 'emotion_type'),
  1811. 'gender' => getProp($segment, 'gender'),
  1812. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1813. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1814. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1815. 'pitch' => getProp($segment, 'pitch', 0),
  1816. ];
  1817. // 插入视频配音合成任务
  1818. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1819. 'alias_segment_id' => $segment_id,
  1820. 'generate_status' => '执行中',
  1821. 'audio_url' => '',
  1822. 'generate_json' => json_encode($generate_json, 256),
  1823. 'created_at' => $now,
  1824. 'updated_at' => $now,
  1825. ]);
  1826. if (!$dubTaskId) {
  1827. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1828. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1829. // Utils::throwError('20003:创建配音任务失败!');
  1830. }
  1831. } else {
  1832. // dialogue为空时,直接写入默认音频信息到分镜表
  1833. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1834. $update_data['audio_duration'] = 2.0;
  1835. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1836. }
  1837. // 更新分镜的任务信息
  1838. $update_result = DB::table('mp_episode_segments')
  1839. ->where('segment_id', $segment_id)
  1840. ->update($update_data);
  1841. // 如果是第一集的首帧图片,则存入待更新数组
  1842. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1843. Redis::sadd('anime_first_frame_urls', $segment_id);
  1844. }
  1845. if ($update_result) {
  1846. $updated_segments[] = [
  1847. 'segment_id' => $segment_id,
  1848. 'task_id' => $task_id,
  1849. 'status' => '生成中',
  1850. 'matched_scenes' => $matched_scene,
  1851. 'matched_roles' => $segment_characters,
  1852. 'ref_urls_count' => count($ref_img_urls)
  1853. ];
  1854. } else {
  1855. $failed_segments[] = [
  1856. 'segment_id' => $segment_id,
  1857. 'error' => '更新分镜任务状态失败'
  1858. ];
  1859. }
  1860. if ($dubTaskId) {
  1861. sleep(1);
  1862. // 请求远程服务器执行生成
  1863. $client = new Client(['timeout' => 300, 'verify' => false]);
  1864. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1865. $response = $result->getBody()->getContents();
  1866. $response_arr = json_decode($response, true);
  1867. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1868. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1869. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1870. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1871. }
  1872. }
  1873. } catch (\Exception $e) {
  1874. $failed_segments[] = [
  1875. 'segment_id' => $segment_id,
  1876. 'error' => $e->getMessage()
  1877. ];
  1878. }
  1879. }
  1880. // 更新剧集生成状态
  1881. if (!empty($updated_segments)) {
  1882. DB::table('mp_anime_episodes')
  1883. ->where('id', $episode_id)
  1884. ->update([
  1885. 'is_generated' => 1,
  1886. 'updated_at' => date('Y-m-d H:i:s')
  1887. ]);
  1888. }
  1889. return [
  1890. 'success_count' => count($updated_segments),
  1891. 'failed_count' => count($failed_segments),
  1892. 'success_segments' => $updated_segments,
  1893. 'failed_segments' => $failed_segments,
  1894. 'total_segments' => count($segments)
  1895. ];
  1896. }
  1897. public function reGenerateSegment($data) {
  1898. $segment_id = getProp($data, 'segment_id');
  1899. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1900. $anime_id = getProp($segment, 'anime_id');
  1901. $episode_id = getProp($segment, 'episode_id');
  1902. $episode_number = getProp($segment, 'episode_number');
  1903. $segment_content = getProp($data, 'segment_content');
  1904. $ratio = getProp($data, 'ratio');
  1905. if (!$ratio) {
  1906. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1907. if (!$ratio) $ratio = '9:16';
  1908. }
  1909. $dimensions = $this->getRatioDimensions($ratio);
  1910. $width = $dimensions['width'];
  1911. $height = $dimensions['height'];
  1912. if (!$anime_id || !$episode_id) {
  1913. Utils::throwError('1002:请选择分镜');
  1914. }
  1915. // 使用文生文模型重新解析segment_content
  1916. if (!empty($segment_content)) {
  1917. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1918. }
  1919. // 获取动漫的角色信息(包含参考图)
  1920. $anime = DB::table('mp_animes')
  1921. ->where('id', $anime_id)
  1922. ->select('roles', 'scenes')
  1923. ->first();
  1924. if (!$anime || !$anime->roles) {
  1925. Utils::throwError('20003:未找到角色信息');
  1926. }
  1927. $roles = json_decode($anime->roles, true);
  1928. if (!$roles) {
  1929. Utils::throwError('20003:角色信息格式错误');
  1930. }
  1931. // 构建角色名称到参考图的映射
  1932. $role_map = [];
  1933. foreach ($roles as $role) {
  1934. $role_name = getProp($role, 'role');
  1935. $role_url = getProp($role, 'url');
  1936. if (!empty($role_name) && !empty($role_url)) {
  1937. $role_map[$role_name] = $role_url;
  1938. }
  1939. }
  1940. $scenes = json_decode($anime->scenes, true);
  1941. if (!$scenes) {
  1942. Utils::throwError('20003:角色信息格式错误');
  1943. }
  1944. // 构建角色名称到参考图的映射
  1945. $scene_map = [];
  1946. foreach ($scenes as $scene) {
  1947. $scene_name = getProp($scene, 'scene');
  1948. $scene_url = getProp($scene, 'url');
  1949. if (!empty($scene_name) && !empty($scene_url)) {
  1950. $scene_map[$scene_name] = $scene_url;
  1951. }
  1952. }
  1953. $segment_id = $segment->segment_id;
  1954. $original_segment_content = $segment->segment_content;
  1955. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1956. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1957. if (empty($final_segment_content)) {
  1958. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1959. }
  1960. try {
  1961. $dubTaskId = 0;
  1962. // 分镜剧本数组
  1963. $update_data = [
  1964. 'segment_content' => $final_segment_content,
  1965. 'pic_task_status' => '生成中',
  1966. 'updated_at' => date('Y-m-d H:i:s')
  1967. ];
  1968. // 解析分镜内容,提取画面描述作为主要提示词
  1969. $prompt = $final_segment_content;
  1970. $ref_img_urls = [];
  1971. // 分镜场景
  1972. $scene = getProp($data, 'scene');
  1973. if ($scene) {
  1974. $matched_scene = '';
  1975. if (isset($scene_map[$scene])) {
  1976. $img_index = count($ref_img_urls) + 1;
  1977. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1978. $ref_img_urls[] = $scene_map[$scene];
  1979. $matched_scene = $scene;
  1980. }
  1981. $update_data['scene'] = $scene;
  1982. }
  1983. // 分镜角色
  1984. $characters = getProp($data, 'characters');
  1985. if ($characters) {
  1986. $update_data['characters'] = $characters;
  1987. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1988. $characters = explode(',', $characters);
  1989. // 从分镜内容中提取涉及的角色
  1990. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1991. // 获取匹配角色的参考图
  1992. foreach ($segment_characters as $character) {
  1993. if (isset($role_map[$character])) {
  1994. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1995. $img_index = count($ref_img_urls) + 1;
  1996. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1997. $ref_img_urls[] = $role_map[$character];
  1998. }
  1999. }
  2000. }
  2001. // 如果没有找到匹配的角色参考图,不使用参考图
  2002. if (empty($ref_img_urls)) {
  2003. $ref_img_urls = [];
  2004. }
  2005. // 准备生成任务参数
  2006. $params = [
  2007. 'alias_segment_id' => $segment_id,
  2008. 'prompt' => $prompt,
  2009. 'ref_img_urls' => $ref_img_urls,
  2010. 'width' => $width,
  2011. 'height' => $height,
  2012. ];
  2013. // 优化提示词(不要生成字幕)
  2014. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  2015. // 调用AI图片生成服务
  2016. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2017. $task_id = $task->id;
  2018. if (!$task_id) {
  2019. Utils::throwError('20003:创建生成任务失败!');
  2020. }
  2021. $update_data['pic_task_id'] = $task_id;
  2022. // 更新分镜剧本信息
  2023. $this->handleSegmentContent($update_data);
  2024. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2025. if ($segment_content) {
  2026. $dialogue = getProp($update_data, 'dialogue');
  2027. if (!empty($dialogue)) {
  2028. $now = date('Y-m-d H:i:s');
  2029. $generate_json = [
  2030. 'text' => $dialogue,
  2031. 'role' => getProp($update_data, 'voice_actor'),
  2032. 'voice_type' => getProp($update_data, 'voice_type'),
  2033. 'voice_name' => getProp($update_data, 'voice_name'),
  2034. 'emotion' => getProp($update_data, 'emotion'),
  2035. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2036. 'gender' => getProp($update_data, 'gender'),
  2037. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2038. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2039. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2040. 'pitch' => getProp($update_data, 'pitch', 0),
  2041. ];
  2042. // 插入视频配音合成任务
  2043. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2044. 'alias_segment_id' => $segment_id,
  2045. 'generate_status' => '执行中',
  2046. 'audio_url' => '',
  2047. 'generate_json' => json_encode($generate_json, 256),
  2048. 'created_at' => date('Y-m-d H:i:s'),
  2049. 'updated_at' => date('Y-m-d H:i:s'),
  2050. ]);
  2051. if (!$dubTaskId) {
  2052. Utils::throwError('20003:创建配音任务失败!');
  2053. }
  2054. $update_data['audio_url'] = '';
  2055. } else {
  2056. // dialogue为空时,直接写入默认音频信息
  2057. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2058. $update_data['audio_duration'] = 2.0;
  2059. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2060. }
  2061. }
  2062. $boolen = DB::table('mp_episode_segments')
  2063. ->where('segment_id', $segment_id)
  2064. ->update($update_data);
  2065. // 如果是第一集的首帧图片,则存入待更新数组
  2066. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2067. Redis::sadd('anime_first_frame_urls', $segment_id);
  2068. }
  2069. if ($dubTaskId) {
  2070. // 请求远程服务器执行生成
  2071. $client = new Client(['timeout' => 300, 'verify' => false]);
  2072. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2073. $response = $result->getBody()->getContents();
  2074. $response_arr = json_decode($response, true);
  2075. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2076. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2077. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2078. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2079. Utils::throwError('20003:火山生成音频失败');
  2080. }
  2081. }
  2082. } catch (\Exception $e) {
  2083. $failed_segments[] = [
  2084. 'segment_id' => $segment_id,
  2085. 'error' => $e->getMessage()
  2086. ];
  2087. }
  2088. // 创建任务之后先暂停10s等待异步任务完成
  2089. sleep(10);
  2090. $img_url = $this->loopGetPicTaskResult($task_id);
  2091. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2092. // 图片生成后新增对话记录
  2093. try {
  2094. $uid = Site::getUid();
  2095. $now = date('Y-m-d H:i:s');
  2096. // 使用AI反推图片提示词
  2097. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2098. // 保存对话记录
  2099. $records = [
  2100. [
  2101. 'uid' => $uid,
  2102. 'anime_id' => $anime_id,
  2103. 'sequence' => $episode_number,
  2104. 'role' => 'user',
  2105. 'content' => '重新生成',
  2106. 'segment_id' => $segment_id,
  2107. 'pic_task_id' => $task_id,
  2108. 'image_url' => '',
  2109. 'created_at' => $now,
  2110. 'updated_at' => $now
  2111. ],
  2112. [
  2113. 'uid' => $uid,
  2114. 'anime_id' => $anime_id,
  2115. 'sequence' => $episode_number,
  2116. 'role' => 'assistant',
  2117. 'content' => $pic_prompt,
  2118. 'segment_id' => $segment_id,
  2119. 'pic_task_id' => $task_id,
  2120. 'image_url' => $img_url,
  2121. 'created_at' => $now,
  2122. 'updated_at' => $now
  2123. ]
  2124. ];
  2125. DB::table('mp_anime_records')->insert($records);
  2126. } catch (\Exception $e) {
  2127. // 记录日志但不影响主流程
  2128. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2129. 'segment_id' => $segment_id,
  2130. 'img_url' => $img_url
  2131. ]);
  2132. }
  2133. return $img_url;
  2134. }
  2135. public function addSegment($data) {
  2136. $prev_segment_id = getProp($data, 'prev_segment_id');
  2137. $img_url = getProp($data, 'img_url');
  2138. $video_url = getProp($data, 'video_url');
  2139. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2140. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2141. $anime_id = getProp($segment, 'anime_id');
  2142. $episode_id = getProp($segment, 'episode_id');
  2143. $episode_number = getProp($segment, 'episode_number');
  2144. $segment_number = getProp($segment, 'segment_number');
  2145. $new_segment_number = $segment_number + 1;
  2146. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2147. // 分镜剧本数组
  2148. $insert_data = [
  2149. 'anime_id' => $anime_id,
  2150. 'episode_id' => $episode_id,
  2151. 'episode_number' => $episode_number,
  2152. 'act_number' => getProp($segment, 'act_number'),
  2153. 'act_title' => getProp($segment, 'act_title'),
  2154. 'segment_id' => $segment_id,
  2155. 'segment_number' => $new_segment_number,
  2156. 'segment_content' => '',
  2157. 'img_url' => '',
  2158. 'video_url' => '',
  2159. 'created_at' => date('Y-m-d H:i:s'),
  2160. 'updated_at' => date('Y-m-d H:i:s')
  2161. ];
  2162. if ($img_url) $insert_data['img_url'] = $img_url;
  2163. if ($video_url) {
  2164. $insert_data['origin_video_url'] = $video_url;
  2165. $insert_data['current_type'] = 2;
  2166. $compressed_video_url = compressVideo($video_url);
  2167. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2168. }
  2169. try {
  2170. DB::beginTransaction();
  2171. // 先更新序号
  2172. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2173. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2174. if (!$id) {
  2175. Utils::throwError('20003:新增分镜失败!');
  2176. }
  2177. }catch (\Exception $e) {
  2178. DB::rollBack();
  2179. Utils::throwError('20003:'.$e->getMessage());
  2180. }
  2181. DB::commit();
  2182. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2183. $segment = $segment ? (array)$segment : [];
  2184. return $segment;
  2185. // 以下代码暂弃用
  2186. $anime_id = getProp($segment, 'anime_id');
  2187. $episode_id = getProp($segment, 'episode_id');
  2188. $episode_number = getProp($segment, 'episode_number');
  2189. $segment_number = getProp($segment, 'segment_number');
  2190. $segment_content = getProp($data, 'segment_content');
  2191. $img_url = getProp($data, 'img_url');
  2192. $video_url = getProp($data, 'video_url');
  2193. $ratio = getProp($data, 'ratio');
  2194. $dimensions = $this->getRatioDimensions($ratio);
  2195. $width = $dimensions['width'];
  2196. $height = $dimensions['height'];
  2197. if (!$anime_id || !$episode_id) {
  2198. Utils::throwError('1002:请选择分镜');
  2199. }
  2200. // 使用文生文模型重新解析segment_content
  2201. if (!empty($segment_content)) {
  2202. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2203. }
  2204. // 获取动漫的角色信息(包含参考图)
  2205. $anime = DB::table('mp_animes')
  2206. ->where('id', $anime_id)
  2207. ->select('roles', 'scenes')
  2208. ->first();
  2209. if (!$anime || !$anime->roles) {
  2210. Utils::throwError('20003:未找到角色信息');
  2211. }
  2212. $roles = json_decode($anime->roles, true);
  2213. if (!$roles) {
  2214. Utils::throwError('20003:角色信息格式错误');
  2215. }
  2216. // 构建角色名称到参考图的映射
  2217. $role_map = [];
  2218. foreach ($roles as $role) {
  2219. $role_name = getProp($role, 'role');
  2220. $role_url = getProp($role, 'url');
  2221. if (!empty($role_name) && !empty($role_url)) {
  2222. $role_map[$role_name] = $role_url;
  2223. }
  2224. }
  2225. $scenes = json_decode($anime->scenes, true);
  2226. if (!$scenes) {
  2227. Utils::throwError('20003:角色信息格式错误');
  2228. }
  2229. // 构建角色名称到参考图的映射
  2230. $scene_map = [];
  2231. foreach ($scenes as $scene) {
  2232. $scene_name = getProp($scene, 'scene');
  2233. $scene_url = getProp($scene, 'url');
  2234. if (!empty($scene_name) && !empty($scene_url)) {
  2235. $scene_map[$scene_name] = $scene_url;
  2236. }
  2237. }
  2238. $segment_id = $segment->segment_id;
  2239. $original_segment_content = $segment->segment_content;
  2240. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2241. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2242. if (empty($final_segment_content)) {
  2243. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2244. }
  2245. try {
  2246. $dubTaskId = 0;
  2247. DB::beginTransaction();
  2248. $new_segment_number = $segment_number + 1;
  2249. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2250. // 分镜剧本数组
  2251. $insert_data = [
  2252. 'anime_id' => $anime_id,
  2253. 'episode_id' => $episode_id,
  2254. 'episode_number' => $episode_number,
  2255. 'act_number' => getProp($segment, 'act_number'),
  2256. 'act_title' => getProp($segment, 'act_title'),
  2257. 'segment_id' => $segment_id,
  2258. 'segment_number' => $new_segment_number,
  2259. 'segment_content' => $final_segment_content,
  2260. 'img_url' => $img_url,
  2261. 'video_url' => $video_url,
  2262. 'created_at' => date('Y-m-d H:i:s'),
  2263. 'updated_at' => date('Y-m-d H:i:s')
  2264. ];
  2265. // 更新分镜剧本信息
  2266. $this->handleSegmentContent($insert_data);
  2267. // 如果有对话内容,创建视频配音合成任务
  2268. $dialogue = getProp($insert_data, 'dialogue');
  2269. if (!empty($dialogue)) {
  2270. $now = date('Y-m-d H:i:s');
  2271. $generate_json = [
  2272. 'text' => $dialogue,
  2273. 'role' => getProp($insert_data, 'voice_actor'),
  2274. 'voice_type' => getProp($insert_data, 'voice_type'),
  2275. 'voice_name' => getProp($insert_data, 'voice_name'),
  2276. 'emotion' => getProp($insert_data, 'emotion'),
  2277. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2278. 'gender' => getProp($insert_data, 'gender'),
  2279. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2280. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2281. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2282. 'pitch' => getProp($insert_data, 'pitch', 0),
  2283. ];
  2284. // 插入视频配音合成任务
  2285. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2286. 'alias_segment_id' => $segment_id,
  2287. 'generate_status' => '执行中',
  2288. 'audio_url' => '',
  2289. 'generate_json' => json_encode($generate_json, 256),
  2290. 'created_at' => $now,
  2291. 'updated_at' => $now,
  2292. ]);
  2293. if (!$dubTaskId) {
  2294. Utils::throwError('20003:创建配音任务失败!');
  2295. }
  2296. $insert_data['audio_url'] = '';
  2297. } else {
  2298. // dialogue为空时,直接写入默认音频信息
  2299. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2300. $insert_data['audio_duration'] = 2.0;
  2301. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2302. }
  2303. // 如果没有上传图片则使用当前描述进行生成
  2304. if (!$img_url) {
  2305. // 解析分镜内容,提取画面描述作为主要提示词
  2306. $prompt = $final_segment_content;
  2307. $ref_img_urls = [];
  2308. // 分镜场景
  2309. $scene = getProp($insert_data, 'scene');
  2310. if ($scene) {
  2311. $matched_scene = '';
  2312. if (isset($scene_map[$scene])) {
  2313. $img_index = count($ref_img_urls) + 1;
  2314. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2315. $ref_img_urls[] = $scene_map[$scene];
  2316. $matched_scene = $scene;
  2317. }
  2318. $update_data['scene'] = $scene;
  2319. }
  2320. // 分镜角色
  2321. $characters = getProp($insert_data, 'characters');
  2322. if ($characters) {
  2323. $update_data['characters'] = $characters;
  2324. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2325. $characters = explode(',', $characters);
  2326. // 从分镜内容中提取涉及的角色
  2327. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2328. // 获取匹配角色的参考图
  2329. foreach ($segment_characters as $character) {
  2330. if (isset($role_map[$character])) {
  2331. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2332. $img_index = count($ref_img_urls) + 1;
  2333. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2334. $ref_img_urls[] = $role_map[$character];
  2335. }
  2336. }
  2337. }
  2338. // 如果没有找到匹配的角色参考图,不使用参考图
  2339. if (empty($ref_img_urls)) {
  2340. $ref_img_urls = [];
  2341. }
  2342. // 准备生成任务参数
  2343. $params = [
  2344. 'alias_segment_id' => $segment_id,
  2345. 'prompt' => $prompt,
  2346. 'ref_img_urls' => $ref_img_urls,
  2347. 'width' => $width,
  2348. 'height' => $height,
  2349. ];
  2350. // 调用AI图片生成服务
  2351. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2352. $task_id = $task->id;
  2353. // $task_id = 'whatever';
  2354. if (!$task_id) {
  2355. Utils::throwError('20003:创建生成任务失败!');
  2356. }
  2357. $insert_data['pic_task_status'] = '生成中';
  2358. $insert_data['pic_task_id'] = $task_id;
  2359. }
  2360. // 先更新序号
  2361. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2362. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2363. if (!$boolen) {
  2364. Utils::throwError('20003:新增分镜失败!');
  2365. }
  2366. // 如果是第一集的首帧图片,则存入待更新数组
  2367. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2368. Redis::sadd('anime_first_frame_urls', $segment_id);
  2369. }
  2370. if ($dubTaskId) {
  2371. // 请求远程服务器执行生成
  2372. $client = new Client(['timeout' => 300, 'verify' => false]);
  2373. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2374. $response = $result->getBody()->getContents();
  2375. $response_arr = json_decode($response, true);
  2376. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2377. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2378. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2379. Utils::throwError('20003:火山生成音频失败');
  2380. }
  2381. }
  2382. } catch (\Exception $e) {
  2383. DB::rollBack();
  2384. Utils::throwError('20003:'.$e->getMessage());
  2385. }
  2386. DB::commit();
  2387. // 创建任务之后先暂停10s等待异步任务完成
  2388. sleep(10);
  2389. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2390. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2391. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2392. $segment = $segment ? (array)$segment : [];
  2393. return $segment;
  2394. }
  2395. public function copySegment($data) {
  2396. $segment_id = getProp($data, 'segment_id');
  2397. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2398. if (!$segment) Utils::throwError('20003:请选择分镜');
  2399. $anime_id = getProp($segment, 'anime_id');
  2400. $episode_id = getProp($segment, 'episode_id');
  2401. $episode_number = getProp($segment, 'episode_number');
  2402. $segment_number = getProp($segment, 'segment_number');
  2403. $new_segment_id = 0;
  2404. try {
  2405. DB::beginTransaction();
  2406. $segment = (array)$segment;
  2407. unset($segment['id']);
  2408. $segment['segment_number'] += 1;
  2409. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2410. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2411. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2412. // 更新其他分镜序号
  2413. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2414. // 复制分镜
  2415. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2416. if (!$id) {
  2417. Utils::throwError('20003:复制分镜失败');
  2418. }
  2419. }catch (\Exception $e) {
  2420. DB::rollBack();
  2421. Utils::throwError('20003:'.$e->getMessage());
  2422. }
  2423. DB::commit();
  2424. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2425. $segment = $segment ? (array)$segment : [];
  2426. return $segment;
  2427. }
  2428. public function moveSegment($data) {
  2429. $segment_id = getProp($data, 'segment_id');
  2430. $target_segment_id = getProp($data, 'target_segment_id');
  2431. // 获取源分镜信息
  2432. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2433. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2434. // 获取目标分镜信息
  2435. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2436. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2437. $anime_id = getProp($source_segment, 'anime_id');
  2438. $episode_id = getProp($source_segment, 'episode_id');
  2439. $episode_number = getProp($source_segment, 'episode_number');
  2440. $source_segment_number = getProp($source_segment, 'segment_number');
  2441. $target_segment_number = getProp($target_segment, 'segment_number');
  2442. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2443. $target_anime_id = getProp($target_segment, 'anime_id');
  2444. $target_episode_number = getProp($target_segment, 'episode_number');
  2445. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2446. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2447. }
  2448. // 如果源分镜和目标分镜相同,无需移动
  2449. if ($source_segment_number == $target_segment_number) {
  2450. return true;
  2451. }
  2452. try {
  2453. DB::beginTransaction();
  2454. if ($source_segment_number < $target_segment_number) {
  2455. // 向后移动:源分镜移动到目标分镜之后
  2456. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2457. DB::table('mp_episode_segments')
  2458. ->where('anime_id', $anime_id)
  2459. ->where('episode_id', $episode_id)
  2460. ->where('segment_number', '>', $source_segment_number)
  2461. ->where('segment_number', '<=', $target_segment_number)
  2462. ->decrement('segment_number');
  2463. // 2. 将源分镜移动到目标分镜之后
  2464. $new_segment_number = $target_segment_number;
  2465. } else {
  2466. // 向前移动:源分镜移动到目标分镜之后
  2467. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2468. DB::table('mp_episode_segments')
  2469. ->where('anime_id', $anime_id)
  2470. ->where('episode_id', $episode_id)
  2471. ->where('segment_number', '>', $target_segment_number)
  2472. ->where('segment_number', '<', $source_segment_number)
  2473. ->increment('segment_number');
  2474. // 2. 将源分镜移动到目标分镜之后
  2475. $new_segment_number = $target_segment_number + 1;
  2476. }
  2477. // 3. 更新源分镜的序号
  2478. $update_result = DB::table('mp_episode_segments')
  2479. ->where('segment_id', $segment_id)
  2480. ->update([
  2481. 'segment_number' => $new_segment_number,
  2482. 'updated_at' => date('Y-m-d H:i:s')
  2483. ]);
  2484. if (!$update_result) {
  2485. Utils::throwError('20003:更新分镜序号失败');
  2486. }
  2487. DB::commit();
  2488. return true;
  2489. } catch (\Exception $e) {
  2490. DB::rollBack();
  2491. Utils::throwError('20003:' . $e->getMessage());
  2492. }
  2493. }
  2494. public function delSegment($data) {
  2495. $segment_id = getProp($data, 'segment_id');
  2496. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2497. if (!$segment) Utils::throwError('20003:请选择分镜');
  2498. $anime_id = getProp($segment, 'anime_id');
  2499. $episode_id = getProp($segment, 'episode_id');
  2500. $episode_number = getProp($segment, 'episode_number');
  2501. $segment_number = getProp($segment, 'segment_number');
  2502. try {
  2503. DB::beginTransaction();
  2504. // 删除分镜
  2505. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2506. if (!$boolen) {
  2507. Utils::throwError('20003:删除分镜失败');
  2508. }
  2509. // 更新其他分镜序号
  2510. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2511. }catch (\Exception $e) {
  2512. DB::rollBack();
  2513. Utils::throwError('20003:'.$e->getMessage());
  2514. }
  2515. DB::commit();
  2516. return true;
  2517. }
  2518. public function applySegment($data) {
  2519. $segment_id = getProp($data, 'segment_id');
  2520. $url = getProp($data, 'url');
  2521. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2522. if (!$url) Utils::throwError('20003:URL不能为空');
  2523. // 获取URL的文件扩展名
  2524. $urlPath = parse_url($url, PHP_URL_PATH);
  2525. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2526. // 定义图片和视频的扩展名
  2527. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2528. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2529. // 判断是图片还是视频
  2530. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2531. if (in_array($extension, $imageExtensions)) {
  2532. // 图片类型
  2533. $updateData['img_url'] = $url;
  2534. $updateData['current_type'] = 1;
  2535. } elseif (in_array($extension, $videoExtensions)) {
  2536. // 视频类型
  2537. $updateData['video_url'] = $url;
  2538. $updateData['current_type'] = 2;
  2539. } else {
  2540. Utils::throwError('20003:不支持的文件类型');
  2541. }
  2542. // 更新分镜表
  2543. $result = DB::table('mp_episode_segments')
  2544. ->where('segment_id', $segment_id)
  2545. ->update($updateData);
  2546. if (!$result) {
  2547. Utils::throwError('20003:更新分镜失败');
  2548. }
  2549. return true;
  2550. }
  2551. public function segmentHistory($data) {
  2552. $segment_id = getProp($data, 'segment_id');
  2553. // 获取历史图片
  2554. $pics = [];
  2555. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2556. foreach($pic_history as $task) {
  2557. $result_url = getProp($task, 'result_url');
  2558. if (is_json($result_url)) {
  2559. $pics = array_merge($pics, json_decode($result_url, true));
  2560. }else {
  2561. $pics[] = $result_url;
  2562. }
  2563. }
  2564. // 获取历史视频
  2565. $videos = [];
  2566. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2567. foreach($video_history as $task) {
  2568. $result_url = getProp($task, 'result_url');
  2569. if (is_json($result_url)) {
  2570. $videos = array_merge($videos, json_decode($result_url, true));
  2571. }else {
  2572. $videos[] = $result_url;
  2573. }
  2574. }
  2575. return compact('pics', 'videos');
  2576. }
  2577. public function addAct($data) {
  2578. $prev_act_id = getProp($data, 'prev_act_id');
  2579. $act_title = getProp($data, 'act_title', '');
  2580. $act_content = getProp($data, 'act_content', '');
  2581. $act_duration = getProp($data, 'act_duration', 5);
  2582. $video_url = getProp($data, 'video_url');
  2583. // 根据prev_act_id获取记录
  2584. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2585. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2586. $anime_id = getProp($prev_segment, 'anime_id');
  2587. $episode_id = getProp($prev_segment, 'episode_id');
  2588. $episode_number = getProp($prev_segment, 'episode_number');
  2589. $prev_act_number = getProp($prev_segment, 'act_number');
  2590. // 获取新的act_number
  2591. $new_act_number = $prev_act_number + 1;
  2592. try {
  2593. DB::beginTransaction();
  2594. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2595. DB::table('mp_episode_segments')
  2596. ->where('anime_id', $anime_id)
  2597. ->where('episode_id', $episode_id)
  2598. ->where('act_number', '>', $prev_act_number)
  2599. ->increment('act_number');
  2600. // 插入新片段记录
  2601. $insert_data = [
  2602. 'anime_id' => $anime_id,
  2603. 'episode_id' => $episode_id,
  2604. 'episode_number' => $episode_number,
  2605. 'act_number' => $new_act_number,
  2606. 'created_at' => date('Y-m-d H:i:s'),
  2607. 'updated_at' => date('Y-m-d H:i:s')
  2608. ];
  2609. if ($act_title) {
  2610. $insert_data['act_title'] = $act_title;
  2611. }
  2612. if ($act_content) {
  2613. $insert_data['act_content'] = $act_content;
  2614. }
  2615. if ($act_duration) {
  2616. $insert_data['act_duration'] = $act_duration;
  2617. }
  2618. if ($video_url) {
  2619. $insert_data['origin_video_url'] = $video_url;
  2620. $insert_data['current_type'] = 2;
  2621. $compressed_video_url = compressVideo($video_url);
  2622. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2623. }
  2624. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2625. if (!$id) {
  2626. Utils::throwError('20003:新增片段失败!');
  2627. }
  2628. DB::commit();
  2629. }catch (\Exception $e) {
  2630. DB::rollBack();
  2631. Utils::throwError('20003:'.$e->getMessage());
  2632. }
  2633. $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();
  2634. $segment = $segment ? (array)$segment : [];
  2635. return $segment;
  2636. }
  2637. public function editAct($data) {
  2638. $act_id = getProp($data, 'act_id');
  2639. $act_content = getProp($data, 'act_content');
  2640. $act_duration = getProp($data, 'act_duration');
  2641. $act_title = getProp($data, 'act_title');
  2642. $image_url = getProp($data, 'image_url');
  2643. $video_url = getProp($data, 'video_url');
  2644. // 参数验证
  2645. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2646. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2647. $segment = DB::table('mp_episode_segments')
  2648. ->where('id', $act_id)
  2649. ->first();
  2650. if (!$segment) Utils::throwError('20003:该片段不存在');
  2651. try {
  2652. DB::beginTransaction();
  2653. // 准备更新数据
  2654. $update_data = [
  2655. 'updated_at' => date('Y-m-d H:i:s')
  2656. ];
  2657. // 更新act相关字段
  2658. if (!empty($act_content)) {
  2659. $update_data['act_show_content'] = $act_content;
  2660. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2661. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2662. $shot_counter = 0;
  2663. $update_data['act_show_content'] = preg_replace_callback(
  2664. '/【(?:镜头|分镜)(\d+)】/u',
  2665. function($matches) use (&$shot_counter) {
  2666. $shot_counter++;
  2667. return '【镜头' . $shot_counter . '】';
  2668. },
  2669. $update_data['act_show_content']
  2670. );
  2671. }
  2672. if (!empty($act_duration)) {
  2673. $update_data['act_duration'] = $act_duration;
  2674. }
  2675. if (!empty($act_title)) {
  2676. $update_data['act_title'] = $act_title;
  2677. }
  2678. // 处理图片上传
  2679. if ($image_url) {
  2680. $update_data['img_url'] = $image_url;
  2681. $update_data['current_type'] = 1;
  2682. // 同时写入一个图片生成任务记录
  2683. if ($act_id) {
  2684. $pic_task = [
  2685. 'alias_act_id' => $act_id,
  2686. 'ref_img_url' => json_encode([]),
  2687. 'status' => 'success',
  2688. 'result_url' => json_encode([$image_url], 256),
  2689. 'model' => '',
  2690. 'created_at' => date('Y-m-d H:i:s'),
  2691. 'updated_at' => date('Y-m-d H:i:s'),
  2692. ];
  2693. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2694. }
  2695. }
  2696. // 处理视频上传
  2697. if ($video_url) {
  2698. $update_data['origin_video_url'] = $video_url;
  2699. $compressed_video_url = compressVideo($video_url);
  2700. $update_data['current_type'] = 2;
  2701. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2702. // 同时写入一个视频生成任务记录
  2703. if ($act_id) {
  2704. $video_task = [
  2705. 'alias_act_id' => $act_id,
  2706. 'status' => 'success',
  2707. 'result_url' => $update_data['origin_video_url'],
  2708. 'compressed_url' => $update_data['video_url'],
  2709. 'created_at' => date('Y-m-d H:i:s'),
  2710. 'updated_at' => date('Y-m-d H:i:s'),
  2711. ];
  2712. DB::table('mp_generate_video_tasks')->insert($video_task);
  2713. }
  2714. }
  2715. // 更新片段信息
  2716. $result = DB::table('mp_episode_segments')
  2717. ->where('id', $act_id)
  2718. ->update($update_data);
  2719. if ($result === false) {
  2720. Utils::throwError('20003:更新片段失败');
  2721. }
  2722. DB::commit();
  2723. // 返回新复制的记录
  2724. $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();
  2725. $new_segment = (array)$new_segment;
  2726. return $new_segment;
  2727. } catch (\Exception $e) {
  2728. DB::rollBack();
  2729. dLog('anime')->error('更新片段失败', [
  2730. 'act_id' => $act_id,
  2731. 'error' => $e->getMessage()
  2732. ]);
  2733. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2734. }
  2735. }
  2736. public function copyAct($data) {
  2737. $act_id = getProp($data, 'act_id');
  2738. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2739. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2740. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2741. $anime_id = getProp($source_segment, 'anime_id');
  2742. $episode_id = getProp($source_segment, 'episode_id');
  2743. $episode_number = getProp($source_segment, 'episode_number');
  2744. $act_number = getProp($source_segment, 'act_number');
  2745. try {
  2746. DB::beginTransaction();
  2747. // 新act的编号
  2748. $new_act_number = $act_number + 1;
  2749. // 更新后续所有act的act_number
  2750. DB::table('mp_episode_segments')
  2751. ->where('anime_id', $anime_id)
  2752. ->where('episode_id', $episode_id)
  2753. ->where('act_number', '>', $act_number)
  2754. ->increment('act_number');
  2755. // 复制该片段记录
  2756. $segment_data = (array)$source_segment;
  2757. unset($segment_data['id']);
  2758. $segment_data['video_url'] = '';
  2759. $segment_data['video_task_id'] = '';
  2760. $segment_data['video_task_status'] = '';
  2761. $segment_data['act_number'] = $new_act_number;
  2762. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2763. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2764. if (!$id) {
  2765. Utils::throwError('20003:复制片段失败');
  2766. }
  2767. DB::commit();
  2768. }catch (\Exception $e) {
  2769. DB::rollBack();
  2770. Utils::throwError('20003:'.$e->getMessage());
  2771. }
  2772. // 返回新复制的记录
  2773. $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();
  2774. $new_segment = $new_segment ? (array)$new_segment : [];
  2775. $new_segment['act_id'] = $id;
  2776. return $new_segment;
  2777. }
  2778. public function moveAct($data) {
  2779. $act_id = getProp($data, 'act_id');
  2780. $target_act_id = getProp($data, 'target_act_id');
  2781. // 获取源片段信息
  2782. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2783. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2784. // 获取目标片段信息
  2785. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2786. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2787. $anime_id = getProp($source_segment, 'anime_id');
  2788. $episode_id = getProp($source_segment, 'episode_id');
  2789. $source_act_number = getProp($source_segment, 'act_number');
  2790. $target_act_number = getProp($target_segment, 'act_number');
  2791. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2792. $target_anime_id = getProp($target_segment, 'anime_id');
  2793. $target_episode_id = getProp($target_segment, 'episode_id');
  2794. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2795. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2796. }
  2797. // 如果源片段和目标片段相同,无需移动
  2798. if ($source_act_number == $target_act_number) {
  2799. return true;
  2800. }
  2801. try {
  2802. DB::beginTransaction();
  2803. if ($source_act_number < $target_act_number) {
  2804. // 向后移动:源片段移动到目标片段之后
  2805. // 1. 将源片段和目标片段之间的所有片段编号减1
  2806. DB::table('mp_episode_segments')
  2807. ->where('anime_id', $anime_id)
  2808. ->where('episode_id', $episode_id)
  2809. ->where('act_number', '>', $source_act_number)
  2810. ->where('act_number', '<=', $target_act_number)
  2811. ->decrement('act_number');
  2812. // 2. 将源片段移动到目标片段之后
  2813. $new_act_number = $target_act_number;
  2814. } else {
  2815. // 向前移动:源片段移动到目标片段之后
  2816. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2817. DB::table('mp_episode_segments')
  2818. ->where('anime_id', $anime_id)
  2819. ->where('episode_id', $episode_id)
  2820. ->where('act_number', '>', $target_act_number)
  2821. ->where('act_number', '<', $source_act_number)
  2822. ->increment('act_number');
  2823. // 2. 将源片段移动到目标片段之后
  2824. $new_act_number = $target_act_number + 1;
  2825. }
  2826. // 3. 更新源片段的编号
  2827. $update_result = DB::table('mp_episode_segments')
  2828. ->where('id', $act_id)
  2829. ->update([
  2830. 'act_number' => $new_act_number,
  2831. 'updated_at' => date('Y-m-d H:i:s')
  2832. ]);
  2833. if (!$update_result) {
  2834. Utils::throwError('20003:更新片段编号失败');
  2835. }
  2836. DB::commit();
  2837. return true;
  2838. } catch (\Exception $e) {
  2839. DB::rollBack();
  2840. Utils::throwError('20003:' . $e->getMessage());
  2841. }
  2842. }
  2843. public function delAct($data) {
  2844. $act_id = getProp($data, 'act_id');
  2845. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2846. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2847. if (!$segment) Utils::throwError('20003:请选择片段');
  2848. $anime_id = getProp($segment, 'anime_id');
  2849. $episode_id = getProp($segment, 'episode_id');
  2850. $act_number = getProp($segment, 'act_number');
  2851. try {
  2852. DB::beginTransaction();
  2853. // 删除该片段记录
  2854. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2855. if (!$deleted) {
  2856. Utils::throwError('20003:删除片段失败');
  2857. }
  2858. // 更新后续act的编号
  2859. DB::table('mp_episode_segments')
  2860. ->where('anime_id', $anime_id)
  2861. ->where('episode_id', $episode_id)
  2862. ->where('act_number', '>', $act_number)
  2863. ->decrement('act_number');
  2864. DB::commit();
  2865. }catch (\Exception $e) {
  2866. DB::rollBack();
  2867. Utils::throwError('20003:'.$e->getMessage());
  2868. }
  2869. return true;
  2870. }
  2871. public function applyAct($data) {
  2872. $act_id = getProp($data, 'act_id');
  2873. $url = getProp($data, 'url');
  2874. if (!$act_id) Utils::throwError('20003:请选择片段');
  2875. if (!$url) Utils::throwError('20003:URL不能为空');
  2876. // 获取URL的文件扩展名
  2877. $urlPath = parse_url($url, PHP_URL_PATH);
  2878. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2879. // 定义图片和视频的扩展名
  2880. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2881. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2882. // 判断是图片还是视频
  2883. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2884. if (in_array($extension, $imageExtensions)) {
  2885. // 图片类型
  2886. $updateData['img_url'] = $url;
  2887. $updateData['current_type'] = 1;
  2888. } elseif (in_array($extension, $videoExtensions)) {
  2889. // 视频类型
  2890. $updateData['video_url'] = $url;
  2891. $updateData['current_type'] = 2;
  2892. } else {
  2893. Utils::throwError('20003:不支持的文件类型');
  2894. }
  2895. // 更新片段记录(全能模式下每个act只有一条记录)
  2896. $result = DB::table('mp_episode_segments')
  2897. ->where('id', $act_id)
  2898. ->update($updateData);
  2899. if (!$result) {
  2900. Utils::throwError('20003:更新片段失败');
  2901. }
  2902. return true;
  2903. }
  2904. public function actChatHistory($data) {
  2905. $act_id = getProp($data, 'act_id');
  2906. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2907. $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');
  2908. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2909. $value = (array)$value;
  2910. $value['created_at'] = transDate($value['created_at']);
  2911. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2912. else $value['reference_images'] = [];
  2913. return $value;
  2914. })->toArray();
  2915. // 获取历史图片
  2916. $url = [];
  2917. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2918. foreach($pic_history as $task) {
  2919. $result_url = getProp($task, 'result_url');
  2920. if (is_json($result_url)) {
  2921. $url = array_merge($url, json_decode($result_url, true));
  2922. }else {
  2923. $url[] = $result_url;
  2924. }
  2925. }
  2926. // 获取历史视频
  2927. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2928. foreach($video_history as $task) {
  2929. $result_url = getProp($task, 'result_url');
  2930. if (is_json($result_url)) {
  2931. $url = array_merge($url, json_decode($result_url, true));
  2932. }else {
  2933. $url[] = $result_url;
  2934. }
  2935. }
  2936. // 获取资产库
  2937. $products = [];
  2938. // 通过act_id查询片段信息获取episode_id
  2939. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2940. if ($segment) {
  2941. $episode_id = getProp($segment, 'episode_id');
  2942. // 查询剧集信息获取roles、scenes和extra_products
  2943. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2944. if ($episode) {
  2945. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2946. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2947. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2948. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2949. // 先合并roles、scenes和props
  2950. // 处理角色数组
  2951. foreach ($roles as $role) {
  2952. $product = $role;
  2953. // 将role字段重命名为product_name
  2954. if (is_array($product) && !empty($product['role'] ?? null)) {
  2955. $product['product_name'] = $product['role'];
  2956. unset($product['role']);
  2957. $product['product'] = 1; // 标记类型为角色
  2958. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2959. }
  2960. }
  2961. // 处理场景数组
  2962. foreach ($scenes as $scene) {
  2963. $product = $scene;
  2964. // 将scene字段重命名为product_name
  2965. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2966. $product['product_name'] = $product['scene'];
  2967. unset($product['scene']);
  2968. $product['product'] = 2; // 标记类型为场景
  2969. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2970. }
  2971. }
  2972. // 处理道具数组
  2973. foreach ($props as $prop) {
  2974. $product = $prop;
  2975. // 将prop字段重命名为product_name
  2976. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2977. $product['product_name'] = $product['prop'];
  2978. unset($product['prop']);
  2979. $product['product'] = 3; // 标记类型为道具
  2980. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2981. }
  2982. }
  2983. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2984. foreach ($extra_products as $extra_product) {
  2985. $product_name = getProp($extra_product, 'product_name');
  2986. if ($product_name) {
  2987. $products[$product_name] = $extra_product; // 覆盖同名数据
  2988. }
  2989. }
  2990. // 重新索引数组(去除key)
  2991. $products = array_values($products);
  2992. }
  2993. }
  2994. // 获取执行中的任务
  2995. $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) {
  2996. $value = (array)$value;
  2997. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2998. else $value['ref_image_url'] = [];
  2999. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  3000. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  3001. if (!empty($value['prompt'])) {
  3002. $prompt = $value['prompt'];
  3003. // 查找第一个【镜头】的位置
  3004. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  3005. // 从【镜头】开始截取
  3006. $prompt = substr($prompt, $matches[0][1]);
  3007. }
  3008. // 去除所有<图片X>格式的标记(X可以是任意数字)
  3009. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  3010. $value['prompt'] = $prompt;
  3011. }
  3012. return $value;
  3013. })->toArray();
  3014. return compact('chat', 'url', 'products', 'tasks');
  3015. }
  3016. public function applyAudioData($data) {
  3017. $segment_id = getProp($data, 'segment_id');
  3018. $global_data = getProp($data, 'global_data');
  3019. $segment_data = getProp($data, 'segment_data');
  3020. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3021. $global_data = is_array($global_data) ? $global_data : [];
  3022. $segment_data = is_array($segment_data) ? $segment_data : [];
  3023. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3024. $dialogue_item = null;
  3025. foreach ($global_data as $key => $item) {
  3026. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3027. $dialogue_item = $item;
  3028. unset($global_data[$key]);
  3029. break;
  3030. }
  3031. }
  3032. if ($dialogue_item) {
  3033. $segment_data[] = $dialogue_item;
  3034. }
  3035. // 特殊参数: audio_url,audio_duration,subtitle_info
  3036. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3037. // 如果不是全部存在,则仍需创建音频任务
  3038. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3039. $special_update_data = [];
  3040. $has_all_special_params = false;
  3041. // 从segment_data中提取特殊参数
  3042. $filtered_segment_data = [];
  3043. foreach ($segment_data as $item) {
  3044. $field_name = trim((string)getProp($item, 'name'));
  3045. if (in_array($field_name, $special_fields)) {
  3046. $special_update_data[$field_name] = getProp($item, 'value');
  3047. } else {
  3048. // 非特殊参数保留,继续后续处理
  3049. $filtered_segment_data[] = $item;
  3050. }
  3051. }
  3052. // 检查是否三个特殊参数都存在
  3053. if (count($special_update_data) === 3 &&
  3054. isset($special_update_data['audio_url']) &&
  3055. isset($special_update_data['audio_duration']) &&
  3056. isset($special_update_data['subtitle_info'])) {
  3057. $has_all_special_params = true;
  3058. // 立即更新到当前分镜
  3059. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3060. DB::table('mp_episode_segments')
  3061. ->where('segment_id', $segment_id)
  3062. ->update($special_update_data);
  3063. }
  3064. // 使用过滤后的segment_data继续处理其他参数
  3065. $segment_data = $filtered_segment_data;
  3066. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3067. $global_update_data = [];
  3068. $segment_update_data = [];
  3069. $global_voice_type = '';
  3070. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3071. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3072. $episode_id = getProp($target_segment, 'episode_id');
  3073. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3074. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3075. if (!$episode) Utils::throwError('20003:分集不存在');
  3076. foreach ($global_data as $item) {
  3077. $field_name = trim((string)getProp($item, 'name'));
  3078. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3079. continue;
  3080. }
  3081. $global_update_data[$field_name] = getProp($item, 'value');
  3082. if ($field_name === 'voice_type') {
  3083. $global_voice_type = trim((string)getProp($item, 'value'));
  3084. }
  3085. }
  3086. foreach ($segment_data as $item) {
  3087. $field_name = trim((string)getProp($item, 'name'));
  3088. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3089. continue;
  3090. }
  3091. $segment_update_data[$field_name] = getProp($item, 'value');
  3092. }
  3093. if ($global_voice_type) {
  3094. $timbre_info = DB::table('mp_timbres')
  3095. ->where('timbre_type', $global_voice_type)
  3096. ->select('audio_url', 'timbre_name')
  3097. ->first();
  3098. if ($timbre_info) {
  3099. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3100. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3101. }
  3102. }
  3103. try {
  3104. DB::beginTransaction();
  3105. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3106. $segment_ids_to_create_task = [];
  3107. $segments_data = [];
  3108. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3109. if (!empty($global_update_data)) {
  3110. // 如果角色不存在,则只更新当前分镜
  3111. if (!$target_voice_actor) {
  3112. // 只处理当前分镜
  3113. $affected_segments = DB::table('mp_episode_segments')
  3114. ->where('segment_id', $segment_id)
  3115. ->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')
  3116. ->get();
  3117. } else {
  3118. // 获取该角色的所有分镜
  3119. $affected_segments = DB::table('mp_episode_segments')
  3120. ->where('episode_id', $episode_id)
  3121. ->where('voice_actor', $target_voice_actor)
  3122. ->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')
  3123. ->get();
  3124. }
  3125. foreach ($affected_segments as $seg) {
  3126. $seg = (array)$seg;
  3127. $sid = getProp($seg, 'segment_id');
  3128. // 检查参数是否发生变化
  3129. $has_changed = false;
  3130. foreach ($global_update_data as $field => $new_value) {
  3131. $old_value = getProp($seg, $field);
  3132. if ($old_value != $new_value) {
  3133. $has_changed = true;
  3134. break;
  3135. }
  3136. }
  3137. if ($has_changed) {
  3138. $segment_ids_to_create_task[] = $sid;
  3139. $segments_data[$sid] = $seg;
  3140. }
  3141. }
  3142. // 只有在有变化的分镜时才更新
  3143. if (!empty($segment_ids_to_create_task)) {
  3144. $global_segment_update_data = $global_update_data;
  3145. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3146. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3147. DB::table('mp_episode_segments')
  3148. ->where('episode_id', $episode_id)
  3149. ->where('voice_actor', $target_voice_actor)
  3150. ->whereIn('segment_id', $segment_ids_to_create_task)
  3151. ->update($global_segment_update_data);
  3152. }
  3153. if ($global_voice_type) {
  3154. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3155. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3156. $roles_updated = false;
  3157. foreach ($episode_roles as &$role) {
  3158. // 通过 role 字段匹配角色名,而不是 voice_name
  3159. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3160. continue;
  3161. }
  3162. $role['voice_type'] = $global_voice_type;
  3163. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3164. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3165. $roles_updated = true;
  3166. }
  3167. unset($role);
  3168. if ($roles_updated) {
  3169. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3170. 'roles' => json_encode($episode_roles, 256),
  3171. 'updated_at' => date('Y-m-d H:i:s'),
  3172. ]);
  3173. }
  3174. }
  3175. }
  3176. // 如果有单个分镜更新,检查是否有变化
  3177. if (!empty($segment_update_data)) {
  3178. // 获取当前分镜数据
  3179. $current_segment = DB::table('mp_episode_segments')
  3180. ->where('segment_id', $segment_id)
  3181. ->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')
  3182. ->first();
  3183. if ($current_segment) {
  3184. $current_segment = (array)$current_segment;
  3185. // 检查参数是否发生变化
  3186. $has_changed = false;
  3187. foreach ($segment_update_data as $field => $new_value) {
  3188. $old_value = getProp($current_segment, $field);
  3189. if ($old_value != $new_value) {
  3190. $has_changed = true;
  3191. break;
  3192. }
  3193. }
  3194. if ($has_changed) {
  3195. // 如果该分镜还未在列表中,添加进去
  3196. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3197. $segment_ids_to_create_task[] = $segment_id;
  3198. $segments_data[$segment_id] = $current_segment;
  3199. }
  3200. // 更新分镜数据并清空音频URL
  3201. $segment_update_data['audio_url'] = '';
  3202. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3203. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3204. }
  3205. }
  3206. }
  3207. // 为所有有变化的分镜创建音频合成任务
  3208. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3209. if (!empty($segment_ids_to_create_task)) {
  3210. foreach ($segment_ids_to_create_task as $sid) {
  3211. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3212. if ($sid === $segment_id && $has_all_special_params) {
  3213. continue;
  3214. }
  3215. // 重新获取更新后的分镜数据
  3216. $updated_segment = DB::table('mp_episode_segments')
  3217. ->where('segment_id', $sid)
  3218. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3219. ->first();
  3220. if (!$updated_segment) continue;
  3221. $updated_segment = (array)$updated_segment;
  3222. // 检查dialogue是否为空
  3223. $dialogue = getProp($updated_segment, 'dialogue');
  3224. if (empty($dialogue)) {
  3225. // dialogue为空时,直接写入默认音频信息
  3226. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3227. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3228. 'audio_duration' => 2.0,
  3229. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3230. 'updated_at' => date('Y-m-d H:i:s')
  3231. ]);
  3232. continue;
  3233. }
  3234. $generate_json = [
  3235. 'text' => $dialogue,
  3236. 'role' => getProp($updated_segment, 'voice_actor'),
  3237. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3238. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3239. 'emotion' => getProp($updated_segment, 'emotion'),
  3240. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3241. 'gender' => getProp($updated_segment, 'gender'),
  3242. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3243. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3244. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3245. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3246. ];
  3247. // 插入视频配音合成任务
  3248. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3249. 'alias_segment_id' => $sid,
  3250. 'generate_status' => '执行中',
  3251. 'audio_url' => '',
  3252. 'generate_json' => json_encode($generate_json, 256),
  3253. 'created_at' => date('Y-m-d H:i:s'),
  3254. 'updated_at' => date('Y-m-d H:i:s'),
  3255. ]);
  3256. if (!$dubTaskId) {
  3257. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3258. continue;
  3259. }
  3260. // 将任务ID添加到Redis列表中
  3261. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3262. // 请求远程服务器执行生成
  3263. try {
  3264. sleep(1);
  3265. $client = new Client(['timeout' => 300, 'verify' => false]);
  3266. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3267. $response = $result->getBody()->getContents();
  3268. $response_arr = json_decode($response, true);
  3269. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3270. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3271. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3272. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3273. }
  3274. } catch (\Exception $e) {
  3275. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3276. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3277. }
  3278. }
  3279. }
  3280. DB::commit();
  3281. } catch (\Exception $e) {
  3282. DB::rollBack();
  3283. Utils::throwError('20003:'.$e->getMessage());
  3284. }
  3285. return true;
  3286. }
  3287. public function episodePicsInfo($data) {
  3288. $anime_id = getProp($data, 'anime_id');
  3289. $episode_id = getProp($data, 'episode_id');
  3290. // 参数验证
  3291. if (!$anime_id && !$episode_id) {
  3292. Utils::throwError('20003:请提供动漫ID或分集ID');
  3293. }
  3294. // 根据参数获取数据源
  3295. if ($episode_id) {
  3296. // 从剧集表获取
  3297. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3298. if (!$source) Utils::throwError('20003:该剧集不存在');
  3299. $table_name = 'mp_anime_episodes';
  3300. $id_field = 'id';
  3301. $id_value = $episode_id;
  3302. // 获取剧集的anime_id用于继承全局数据
  3303. $anime_id = getProp($source, 'anime_id');
  3304. } else {
  3305. // 从动漫表获取
  3306. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3307. if (!$source) Utils::throwError('20003:该动漫不存在');
  3308. $table_name = 'mp_animes';
  3309. $id_field = 'id';
  3310. $id_value = $anime_id;
  3311. }
  3312. $source = (array)$source;
  3313. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3314. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3315. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3316. // 如果是分集数据,需要处理继承和任务创建逻辑
  3317. if ($episode_id) {
  3318. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3319. }
  3320. // 返回生成器函数,用于 SSE 流式输出
  3321. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3322. $startTime = time();
  3323. $maxDuration = 600; // 10分钟超时
  3324. $checkInterval = 3; // 每3秒检查一次
  3325. // Redis 缓存键
  3326. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3327. // 生成当前数据的哈希值用于比较
  3328. $generateHash = function($roles, $scenes, $props) {
  3329. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3330. };
  3331. // 发送初始数据
  3332. $currentHash = $generateHash($roles, $scenes, $props);
  3333. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3334. echo "data: " . json_encode([
  3335. 'type' => 'init',
  3336. 'data' => [
  3337. 'roles' => $roles,
  3338. 'scenes' => $scenes,
  3339. 'props' => $props,
  3340. 'start_time' => $startTime
  3341. ]
  3342. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3343. if (ob_get_level() > 0) {
  3344. ob_flush();
  3345. }
  3346. flush();
  3347. // 持续轮询任务状态
  3348. while (time() - $startTime < $maxDuration) {
  3349. $hasProcessing = false;
  3350. $updated = false;
  3351. // 检查角色任务状态
  3352. foreach ($roles as $index => &$role) {
  3353. $task_id = getProp($role, 'task_id');
  3354. $task_status = getProp($role, 'task_status');
  3355. $existing_url = getProp($role, 'url');
  3356. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3357. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3358. $hasProcessing = ($task_status === 'processing');
  3359. // 查询任务状态
  3360. $task = DB::table('mp_generate_pic_tasks')
  3361. ->where('id', $task_id)
  3362. ->select('id', 'status', 'result_url', 'error_message')
  3363. ->first();
  3364. if ($task) {
  3365. $task = (array)$task;
  3366. $status = getProp($task, 'status');
  3367. // 如果任务完成或失败
  3368. if (in_array($status, ['success', 'failed'])) {
  3369. $role['task_status'] = $status;
  3370. if ($status === 'success') {
  3371. $result_url = getProp($task, 'result_url');
  3372. if ($result_url) {
  3373. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3374. if (is_array($result_urls) && !empty($result_urls[0])) {
  3375. $role['url'] = $result_urls[0];
  3376. }
  3377. }
  3378. }
  3379. $updated = true;
  3380. } else if ($status === 'processing') {
  3381. $hasProcessing = true;
  3382. }
  3383. }
  3384. }
  3385. }
  3386. // 检查场景任务状态
  3387. foreach ($scenes as $index => &$scene) {
  3388. $task_id = getProp($scene, 'task_id');
  3389. $task_status = getProp($scene, 'task_status');
  3390. $existing_url = getProp($scene, 'url');
  3391. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3392. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3393. $hasProcessing = ($task_status === 'processing');
  3394. // 查询任务状态
  3395. $task = DB::table('mp_generate_pic_tasks')
  3396. ->where('id', $task_id)
  3397. ->select('id', 'status', 'result_url', 'error_message')
  3398. ->first();
  3399. if ($task) {
  3400. $task = (array)$task;
  3401. $status = getProp($task, 'status');
  3402. // 如果任务完成或失败
  3403. if (in_array($status, ['success', 'failed'])) {
  3404. $scene['task_status'] = $status;
  3405. if ($status === 'success') {
  3406. $result_url = getProp($task, 'result_url');
  3407. if ($result_url) {
  3408. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3409. if (is_array($result_urls) && !empty($result_urls[0])) {
  3410. $scene['url'] = $result_urls[0];
  3411. }
  3412. }
  3413. }
  3414. $updated = true;
  3415. } else if ($status === 'processing') {
  3416. $hasProcessing = true;
  3417. }
  3418. }
  3419. }
  3420. }
  3421. // 检查道具任务状态
  3422. foreach ($props as $index => &$prop) {
  3423. $task_id = getProp($prop, 'task_id');
  3424. $task_status = getProp($prop, 'task_status');
  3425. $existing_url = getProp($prop, 'url');
  3426. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3427. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3428. $hasProcessing = ($task_status === 'processing');
  3429. // 查询任务状态
  3430. $task = DB::table('mp_generate_pic_tasks')
  3431. ->where('id', $task_id)
  3432. ->select('id', 'status', 'result_url', 'error_message')
  3433. ->first();
  3434. if ($task) {
  3435. $task = (array)$task;
  3436. $status = getProp($task, 'status');
  3437. // 如果任务完成或失败
  3438. if (in_array($status, ['success', 'failed'])) {
  3439. $prop['task_status'] = $status;
  3440. if ($status === 'success') {
  3441. $result_url = getProp($task, 'result_url');
  3442. if ($result_url) {
  3443. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3444. if (is_array($result_urls) && !empty($result_urls[0])) {
  3445. $prop['url'] = $result_urls[0];
  3446. }
  3447. }
  3448. }
  3449. $updated = true;
  3450. } else if ($status === 'processing') {
  3451. $hasProcessing = true;
  3452. }
  3453. }
  3454. }
  3455. }
  3456. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3457. if ($updated) {
  3458. $newHash = $generateHash($roles, $scenes, $props);
  3459. $cachedHash = Redis::get($cacheKey);
  3460. // 只有当数据真正变化时才更新数据库和发送事件
  3461. if ($newHash !== $cachedHash) {
  3462. try {
  3463. // 更新数据库
  3464. DB::table($table_name)->where($id_field, $id_value)->update([
  3465. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3466. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3467. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3468. 'updated_at' => date('Y-m-d H:i:s')
  3469. ]);
  3470. // 更新缓存
  3471. Redis::setex($cacheKey, 600, $newHash);
  3472. // 发送更新事件
  3473. echo "data: " . json_encode([
  3474. 'type' => 'update',
  3475. 'data' => [
  3476. 'roles' => $roles,
  3477. 'scenes' => $scenes,
  3478. 'props' => $props,
  3479. 'elapsed_time' => time() - $startTime
  3480. ]
  3481. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3482. if (ob_get_level() > 0) {
  3483. ob_flush();
  3484. }
  3485. flush();
  3486. } catch (\Exception $e) {
  3487. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3488. }
  3489. } else {
  3490. // 即使哈希相同,如果有URL更新也要发送事件
  3491. $hasUrlUpdate = false;
  3492. foreach ($roles as $role) {
  3493. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3494. $hasUrlUpdate = true;
  3495. break;
  3496. }
  3497. }
  3498. if (!$hasUrlUpdate) {
  3499. foreach ($scenes as $scene) {
  3500. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3501. $hasUrlUpdate = true;
  3502. break;
  3503. }
  3504. }
  3505. }
  3506. if (!$hasUrlUpdate) {
  3507. foreach ($props as $prop) {
  3508. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3509. $hasUrlUpdate = true;
  3510. break;
  3511. }
  3512. }
  3513. }
  3514. if ($hasUrlUpdate) {
  3515. // 强制更新数据库和发送事件
  3516. try {
  3517. DB::table($table_name)->where($id_field, $id_value)->update([
  3518. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3519. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3520. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3521. 'updated_at' => date('Y-m-d H:i:s')
  3522. ]);
  3523. // 更新缓存
  3524. Redis::setex($cacheKey, 600, $newHash);
  3525. // 发送更新事件
  3526. echo "data: " . json_encode([
  3527. 'type' => 'update',
  3528. 'data' => [
  3529. 'roles' => $roles,
  3530. 'scenes' => $scenes,
  3531. 'props' => $props,
  3532. 'elapsed_time' => time() - $startTime
  3533. ]
  3534. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3535. if (ob_get_level() > 0) {
  3536. ob_flush();
  3537. }
  3538. flush();
  3539. } catch (\Exception $e) {
  3540. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3541. }
  3542. }
  3543. }
  3544. }
  3545. // 如果所有任务都已完成,发送完成事件并退出
  3546. if (!$hasProcessing) {
  3547. // 查询数据库中的最终数据,确保返回最新的完整数据
  3548. try {
  3549. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3550. if ($finalSource) {
  3551. $finalSource = (array)$finalSource;
  3552. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3553. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3554. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3555. // 使用数据库中的最终数据
  3556. $roles = $finalRoles;
  3557. $scenes = $finalScenes;
  3558. $props = $finalProps;
  3559. }
  3560. } catch (\Exception $e) {
  3561. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3562. // 如果查询失败,继续使用内存中的数据
  3563. }
  3564. // 清理缓存
  3565. Redis::del($cacheKey);
  3566. echo "data: " . json_encode([
  3567. 'type' => 'completed',
  3568. 'data' => [
  3569. 'roles' => $roles,
  3570. 'scenes' => $scenes,
  3571. 'props' => $props,
  3572. 'total_time' => time() - $startTime
  3573. ]
  3574. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3575. if (ob_get_level() > 0) {
  3576. ob_flush();
  3577. }
  3578. flush();
  3579. break;
  3580. }
  3581. // 等待下次检查
  3582. sleep($checkInterval);
  3583. }
  3584. // 超时处理
  3585. if (time() - $startTime >= $maxDuration) {
  3586. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3587. try {
  3588. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3589. if ($finalSource) {
  3590. $finalSource = (array)$finalSource;
  3591. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3592. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3593. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3594. // 使用数据库中的最终数据
  3595. $roles = $finalRoles;
  3596. $scenes = $finalScenes;
  3597. $props = $finalProps;
  3598. }
  3599. } catch (\Exception $e) {
  3600. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3601. // 如果查询失败,继续使用内存中的数据
  3602. }
  3603. // 清理缓存
  3604. Redis::del($cacheKey);
  3605. echo "data: " . json_encode([
  3606. 'type' => 'timeout',
  3607. 'message' => '轮询超时,请刷新页面查看最新状态',
  3608. 'data' => [
  3609. 'roles' => $roles,
  3610. 'scenes' => $scenes,
  3611. 'props' => $props
  3612. ]
  3613. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3614. if (ob_get_level() > 0) {
  3615. ob_flush();
  3616. }
  3617. flush();
  3618. }
  3619. };
  3620. }
  3621. public function clipSegmentVideo($data) {
  3622. $segment_id = getProp($data, 'segment_id');
  3623. $video_time_point_start = getProp($data, 'video_time_point_start');
  3624. $video_time_point_end = getProp($data, 'video_time_point_end');
  3625. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3626. Utils::throwError('20003:参数异常');
  3627. }
  3628. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3629. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3630. }
  3631. $video_duration = $video_time_point_end - $video_time_point_start;
  3632. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3633. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3634. 'video_duration' => $video_duration,
  3635. 'video_time_point_start' => $video_time_point_start,
  3636. 'video_time_point_end' => $video_time_point_end,
  3637. 'updated_at' => date('Y-m-d H:i:s')
  3638. ]);
  3639. }
  3640. // 轮训获取图片任务结果
  3641. private function loopGetPicTaskResult($task_id) {
  3642. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3643. if (!$task) {
  3644. return '';
  3645. }
  3646. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3647. $model = getProp($task, 'model');
  3648. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3649. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3650. $isSyncModel = $isVolcModel || $isGptModel;
  3651. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3652. $start_count = 0;
  3653. $img_url = '';
  3654. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3655. sleep(3);
  3656. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3657. // 如果任务已经完成,直接返回结果
  3658. if ($task->status === 'success' && $task->result_url) {
  3659. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3660. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3661. }
  3662. // 如果任务已失败,返回空
  3663. if ($task->status === 'failed') {
  3664. return '';
  3665. }
  3666. if ($isSyncModel) continue;
  3667. // 查询任务状态
  3668. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3669. if ($statusInfo['status'] === 'success') {
  3670. $task->updateStatus('success', [
  3671. 'result_url' => $statusInfo['result_url'],
  3672. 'result_json' => $statusInfo['result_json'] ?? []
  3673. ]);
  3674. // 同步调整分镜图片状态和结果
  3675. if (getProp($task, 'alias_segment_id')) {
  3676. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3677. 'img_url' => $statusInfo['result_url'][0],
  3678. 'pic_task_status' => '已完成',
  3679. ]);
  3680. }
  3681. $img_url = $statusInfo['result_url'][0];
  3682. break;
  3683. } elseif ($statusInfo['status'] === 'failed') {
  3684. $task->updateStatus('failed', [
  3685. 'error_message' => $statusInfo['error_message'],
  3686. 'result_json' => $statusInfo['result_json'] ?? []
  3687. ]);
  3688. if (getProp($task, 'alias_segment_id')) {
  3689. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3690. 'pic_task_status' => '失败',
  3691. ]);
  3692. }
  3693. break;
  3694. }
  3695. $start_count++;
  3696. }
  3697. return $img_url;
  3698. }
  3699. /**
  3700. * 从分镜内容中提取涉及的角色
  3701. */
  3702. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3703. $found_characters = [];
  3704. foreach ($available_characters as $character) {
  3705. // 检查角色名称是否在分镜内容中出现
  3706. if (strpos($segment_content, $character) !== false) {
  3707. $found_characters[] = $character;
  3708. }
  3709. }
  3710. if (!$found_characters) {
  3711. foreach ($roles as $character) {
  3712. // 检查角色名称是否在分镜内容中出现
  3713. if (strpos($segment_content, $character) !== false) {
  3714. $found_characters[] = $character;
  3715. }
  3716. }
  3717. }
  3718. return array_unique($found_characters);
  3719. }
  3720. // 从分镜剧本中提取关键字段
  3721. private function handleSegmentContent(&$data) {
  3722. $segmentContent = getProp($data, 'segment_content');
  3723. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3724. $segmentData = [
  3725. 'description' => '',
  3726. 'composition' => '',
  3727. 'camera_movement' => '',
  3728. 'voice_actor' => '',
  3729. 'dialogue' => '',
  3730. 'frame_type' => '',
  3731. 'scene' => '', // 场景
  3732. 'characters' => '', // 出镜角色
  3733. 'tail_frame' => '', // 尾帧描述
  3734. 'emotion' => '中性', // 情感
  3735. 'gender' => '0', // 性别(0未知,1男,2女)
  3736. 'speed_ratio' => 0, // 语速
  3737. 'loudness_ratio' => 0, // 音量
  3738. 'emotion_scale' => 4, // 情感强度
  3739. 'pitch' => 0, // 音调
  3740. ];
  3741. // 用于存储需要从 segment_content 中移除的匹配项
  3742. $replaceEmptyArr = [];
  3743. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3744. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3745. $segmentData['description'] = trim($descMatch[1]);
  3746. $data['description'] = trim($descMatch[1]);
  3747. }
  3748. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3749. $segmentData['composition'] = trim($compMatch[1]);
  3750. $data['composition'] = trim($compMatch[1]);
  3751. }
  3752. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3753. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3754. $data['camera_movement'] = trim($cameraMatch[1]);
  3755. }
  3756. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3757. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3758. $data['voice_actor'] = trim($voiceMatch[1]);
  3759. }
  3760. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3761. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3762. $data['dialogue'] = trim($dialogueMatch[1]);
  3763. }
  3764. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3765. $segmentData['frame_type'] = trim($frameMatch[1]);
  3766. $data['frame_type'] = trim($frameMatch[1]);
  3767. }
  3768. // 场景字段
  3769. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3770. $segmentData['scene'] = trim($sceneMatch[1]);
  3771. $data['scene'] = trim($sceneMatch[1]);
  3772. }
  3773. // 出镜角色字段
  3774. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3775. $segmentData['characters'] = trim($charactersMatch[1]);
  3776. $data['characters'] = trim($charactersMatch[1]);
  3777. }
  3778. // 尾帧描述字段
  3779. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3780. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3781. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3782. }
  3783. // 情感字段
  3784. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3785. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3786. $segmentData['emotion'] = trim($emotionMatch[1]);
  3787. $data['emotion'] = trim($emotionMatch[1]);
  3788. }
  3789. // 性别字段
  3790. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3791. $replaceEmptyArr[] = trim($genderMatch[0]);
  3792. $genderStr = trim($genderMatch[1]);
  3793. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3794. $segmentData['gender'] = '1';
  3795. $data['gender'] = '1';
  3796. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3797. $segmentData['gender'] = '2';
  3798. $data['gender'] = '2';
  3799. } else {
  3800. $segmentData['gender'] = '0';
  3801. $data['gender'] = '0';
  3802. }
  3803. }
  3804. // 语速字段
  3805. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3806. $replaceEmptyArr[] = trim($speedMatch[0]);
  3807. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3808. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3809. }
  3810. // 音量字段
  3811. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3812. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3813. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3814. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3815. }
  3816. // 情感强度字段
  3817. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3818. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3819. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3820. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3821. }
  3822. // 音调字段
  3823. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3824. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3825. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3826. $data['pitch'] = (int)trim($pitchMatch[1]);
  3827. }
  3828. // 从 segment_content 中移除已提取的配音参数字段
  3829. if (!empty($replaceEmptyArr)) {
  3830. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3831. }
  3832. // 如果有配音角色,查询音色信息并验证情感
  3833. $voice_actor = $segmentData['voice_actor'];
  3834. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3835. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3836. $anime_id = getProp($data, 'anime_id');
  3837. $episode_id = getProp($data, 'episode_id');
  3838. // 优先从剧集的角色列表中查找
  3839. $roles = [];
  3840. if ($episode_id) {
  3841. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3842. if ($episode && getProp($episode, 'roles')) {
  3843. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3844. }
  3845. }
  3846. // 如果剧集中没有,从动漫的角色列表中查找
  3847. if (empty($roles) && $anime_id) {
  3848. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3849. if ($anime && getProp($anime, 'roles')) {
  3850. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3851. }
  3852. }
  3853. // 查找匹配的角色音色信息
  3854. $timbre_info = null;
  3855. foreach ($roles as $role) {
  3856. if (getProp($role, 'role') === $voice_actor) {
  3857. $timbre_info = $role;
  3858. break;
  3859. }
  3860. }
  3861. // 如果找到音色信息,添加到数据中
  3862. if ($timbre_info) {
  3863. $voice_type = getProp($timbre_info, 'voice_type');
  3864. $voice_name = getProp($timbre_info, 'voice_name');
  3865. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3866. if ($voice_type) {
  3867. $data['voice_type'] = $voice_type;
  3868. $segmentData['voice_type'] = $voice_type;
  3869. }
  3870. if ($voice_name) {
  3871. $data['voice_name'] = $voice_name;
  3872. $segmentData['voice_name'] = $voice_name;
  3873. }
  3874. if ($voice_audio_url) {
  3875. $data['voice_audio_url'] = $voice_audio_url;
  3876. $segmentData['voice_audio_url'] = $voice_audio_url;
  3877. }
  3878. // 验证情感是否在音色支持的情感列表中
  3879. if ($voice_type) {
  3880. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3881. if ($timbre_emotion) {
  3882. $timbre_emotion = explode(',', $timbre_emotion);
  3883. } else {
  3884. $timbre_emotion = [];
  3885. }
  3886. $emotion = getProp($segmentData, 'emotion', '中性');
  3887. if (!in_array($emotion, $timbre_emotion)) {
  3888. $emotion = '中性';
  3889. }
  3890. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3891. $emotion_list = array_flip($emotion_list);
  3892. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3893. $data['emotion_type'] = $emotion_type;
  3894. $segmentData['emotion_type'] = $emotion_type;
  3895. }
  3896. }
  3897. }
  3898. return $segmentData;
  3899. }
  3900. public function createSegmentVideoTask($data) {
  3901. $segment_id = getProp($data, 'segment_id');
  3902. $tail_frame = getProp($data, 'tail_frame');
  3903. $first_frame_url = getProp($data, 'first_frame_url');
  3904. $tail_frame_url = getProp($data, 'tail_frame_url');
  3905. $generate_audio = getProp($data, 'generate_audio', 0);
  3906. if (!$segment_id) {
  3907. Utils::throwError('1002:分镜ID不能为空');
  3908. }
  3909. // 获取分镜信息
  3910. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3911. if (!$segment) {
  3912. Utils::throwError('20003:分镜不存在');
  3913. }
  3914. $segment = (array)$segment;
  3915. $episode_id = getProp($segment, 'episode_id');
  3916. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3917. if (!$ratio) $ratio = '9:16';
  3918. // 获取分镜内容
  3919. $segmentContent = getProp($segment, 'segment_content', '');
  3920. // 检查 $segmentContent 中是否已有尾帧描述
  3921. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3922. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3923. $finalTailFrame = '';
  3924. if ($tail_frame) {
  3925. // 用户输入了尾帧描述,优先使用
  3926. $finalTailFrame = $tail_frame;
  3927. // 如果 segmentContent 中已有尾帧描述,需要替换
  3928. if ($contentHasTailFrame) {
  3929. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3930. }
  3931. } elseif ($contentHasTailFrame) {
  3932. // segmentContent 中有尾帧描述,使用它
  3933. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3934. } else {
  3935. // 两者都没有,使用分镜表中的尾帧描述
  3936. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3937. }
  3938. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3939. $hasDialogue = false;
  3940. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3941. $dialogue = trim($dialogueMatch[1]);
  3942. // 如果台词不为空且不是"无"
  3943. if (!empty($dialogue) && $dialogue !== '无') {
  3944. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3945. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3946. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3947. $hasDialogue = true;
  3948. }
  3949. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3950. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3951. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3952. if (!preg_match('/^[“]/', $dialogue)) {
  3953. $dialogue = '“' . $dialogue;
  3954. }
  3955. if (!preg_match('/[”]$/', $dialogue)) {
  3956. $dialogue .= '”';
  3957. }
  3958. // 将修改后的台词替换回 $segmentContent
  3959. $originalDialogue = $dialogueMatch[1];
  3960. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3961. }
  3962. }
  3963. // 构建完整的提示词
  3964. $fullPrompt = $segmentContent;
  3965. if ($finalTailFrame && !$contentHasTailFrame) {
  3966. // 只有当 segmentContent 中没有尾帧描述时才追加
  3967. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3968. }
  3969. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3970. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3971. $fullPrompt = trim($fullPrompt);
  3972. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3973. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3974. // 智能选择视频时长
  3975. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3976. $videoDuration = -1;
  3977. // 处理视频模型
  3978. $model = getProp($data, 'model');
  3979. if (!$model) {
  3980. // 用户没有输入,从episode表获取
  3981. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3982. $model = getProp($episode, 'video_model');
  3983. if (!$model) {
  3984. // episode表也没有,使用默认值
  3985. $model = 'doubao-seedance-1-5-pro-251215';
  3986. }
  3987. }
  3988. // 验证模型是否在可用模型表中
  3989. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3990. $model = 'doubao-seedance-1-5-pro-251215';
  3991. }
  3992. // 保存到episode表
  3993. $episode_id = getProp($segment, 'episode_id');
  3994. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3995. 'video_model' => $model,
  3996. 'updated_at' => date('Y-m-d H:i:s')
  3997. ]);
  3998. // 构建视频生成参数
  3999. $videoParams = [
  4000. 'model' => $model,
  4001. 'alias_segment_id' => $segment_id,
  4002. 'prompt' => trim($fullPrompt),
  4003. 'video_duration' => $videoDuration,
  4004. 'video_resolution' => '720P',
  4005. 'seed' => -1,
  4006. 'ratio' => $ratio,
  4007. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4008. 'draft' => false,
  4009. 'watermark' => false,
  4010. 'camera_fixed' => false,
  4011. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4012. ];
  4013. // 如果分镜有图片,作为首帧
  4014. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  4015. $hasVideo = !empty(getProp($segment, 'video_url'));
  4016. if ($hasImage) {
  4017. if ($first_frame_url) {
  4018. $videoParams['first_frame_url'] = $first_frame_url;
  4019. }else {
  4020. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4021. }
  4022. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4023. }
  4024. // 构建content数组
  4025. $videoParams['content'] = [
  4026. [
  4027. 'type' => 'text',
  4028. 'text' => $videoParams['prompt'],
  4029. ]
  4030. ];
  4031. // 如果有首帧图片,添加到content中
  4032. if ($hasImage) {
  4033. 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', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
  4034. $videoParams['content'][] = [
  4035. 'type' => 'image_url',
  4036. 'image_url' => [
  4037. 'url' => $videoParams['first_frame_url'],
  4038. ],
  4039. 'role' => 'reference_image',
  4040. ];
  4041. if (isset($videoParams['tail_frame_url'])) {
  4042. $videoParams['content'][] = [
  4043. 'type' => 'image_url',
  4044. 'image_url' => [
  4045. 'url' => $videoParams['tail_frame_url'],
  4046. ],
  4047. 'role' => 'reference_image',
  4048. ];
  4049. }
  4050. }else {
  4051. $videoParams['content'][] = [
  4052. 'type' => 'image_url',
  4053. 'image_url' => [
  4054. 'url' => $videoParams['first_frame_url'],
  4055. ],
  4056. 'role' => 'first_frame',
  4057. ];
  4058. if (isset($videoParams['tail_frame_url'])) {
  4059. $videoParams['content'][] = [
  4060. 'type' => 'image_url',
  4061. 'image_url' => [
  4062. 'url' => $videoParams['tail_frame_url'],
  4063. ],
  4064. 'role' => 'last_frame',
  4065. ];
  4066. }
  4067. }
  4068. }
  4069. // 获取配音音频URL
  4070. $audioUrl = getProp($segment, 'audio_url');
  4071. $audioDuration = getProp($segment, 'audio_duration');
  4072. // 音频传入的前提:必须有至少一张图片或一个视频
  4073. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4074. // 余额预检:按预估时长计算所需积分,不足直接报错
  4075. $chargeDuration = (int)ceil((float)$audioDuration);
  4076. if ($chargeDuration <= 0) {
  4077. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4078. }
  4079. $this->pointsService->checkUserPointsEnough(
  4080. $this->pointsService->getVideoChargePoints([
  4081. 'model' => $model,
  4082. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4083. 'video_duration' => $chargeDuration,
  4084. 'ratio' => $ratio,
  4085. 'generate_audio' => $current_generate_audio,
  4086. ])
  4087. );
  4088. // dd($videoParams);
  4089. // 根据模型选择不同的视频生成方法
  4090. if (strpos($model, 'jimeng') !== false) {
  4091. // 即梦模型参数调整
  4092. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4093. unset($videoParams['content']); // 即梦不使用content格式
  4094. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4095. } elseif (strpos($model, 'kling') !== false) {
  4096. // Keling模型参数调整
  4097. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4098. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4099. unset($videoParams['ratio']);
  4100. unset($videoParams['content']); // Keling不使用content格式
  4101. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4102. } elseif (strpos($model, 'zhizhen') !== false) {
  4103. // 智帧20等新模型使用统一API
  4104. // 构建统一API参数
  4105. $unifiedParams = [
  4106. 'model_code' => $model,
  4107. 'alias_segment_id' => $segment_id,
  4108. 'prompt' => trim($fullPrompt),
  4109. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4110. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4111. 'video_ratio' => $ratio,
  4112. 'seed' => -1,
  4113. ];
  4114. // 构建parameters参数
  4115. $parameters = [
  4116. 'seconds' => $unifiedParams['video_duration'],
  4117. 'resolution' => $unifiedParams['video_resolution'],
  4118. 'ratio' => $ratio,
  4119. // 'video_mode' => 'multi_image',
  4120. // 'mode' => 'multi_image',
  4121. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4122. ];
  4123. $hasImage = false;
  4124. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4125. if ($hasImage) {
  4126. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4127. if (isset($videoParams['tail_frame_url'])) {
  4128. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4129. }
  4130. // 只有在有图片的情况下才能添加参考音频
  4131. if ($audioUrl) {
  4132. // $parameters['reference_audios'] = [$audioUrl];
  4133. }
  4134. } else {
  4135. // 没有图片时,记录错误日志
  4136. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4137. 'segment_id' => $segment_id,
  4138. 'model' => $model
  4139. ]);
  4140. }
  4141. $unifiedParams['parameters'] = $parameters;
  4142. // 调用统一API创建任务
  4143. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4144. } else {
  4145. // Seedance模型(默认)
  4146. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4147. if ($this->isKuaikuaiSeedanceModel($model)) {
  4148. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4149. if ($canUseAudio && $audioUrl) {
  4150. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4151. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4152. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4153. // 优化提示词,增加音频相关描述
  4154. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4155. $videoParams['prompt'] = $audioPrompt;
  4156. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4157. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4158. }
  4159. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4160. } 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', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
  4161. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4162. // 添加配音音频到content中
  4163. $videoParams['content'][] = [
  4164. 'type' => 'audio_url',
  4165. 'audio_url' => [
  4166. 'url' => $audioUrl,
  4167. ],
  4168. 'role' => 'reference_audio',
  4169. ];
  4170. // 优化提示词,增加音频相关描述
  4171. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4172. $videoParams['prompt'] = $audioPrompt;
  4173. $videoParams['content'][0]['text'] = $audioPrompt;
  4174. } else {
  4175. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4176. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4177. }
  4178. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4179. }
  4180. }
  4181. // 更新分镜表的视频任务信息
  4182. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4183. 'video_task_id' => $task->id,
  4184. 'video_task_status' => '生成中',
  4185. 'generate_audio' => $generate_audio,
  4186. 'updated_at' => date('Y-m-d H:i:s')
  4187. ]);
  4188. return [
  4189. 'task_id' => $task->id,
  4190. 'status' => $task->status,
  4191. 'segment_id' => $segment_id,
  4192. 'video_duration' => $videoDuration
  4193. ];
  4194. }
  4195. /**
  4196. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4197. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4198. *
  4199. * @param string $model
  4200. * @return bool
  4201. */
  4202. public function isKuaikuaiSeedanceModel(string $model): bool
  4203. {
  4204. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4205. }
  4206. /**
  4207. * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
  4208. *
  4209. * @param string $model
  4210. * @return bool
  4211. */
  4212. public function isBaiduSeedanceModel(string $model): bool
  4213. {
  4214. return in_array($model, [
  4215. 'baidu-doubao-seedance-2-0-260128',
  4216. 'baidu-doubao-seedance-2-0-fast-260128',
  4217. 'baidu-doubao-seedance-2-0-mini-260615',
  4218. 'baidu-doubao-seedance-2-5-260628',
  4219. ], true);
  4220. }
  4221. /**
  4222. * 是否为海外百度Seedance(dreamina真人素材空间)模型
  4223. * 系统内使用 baidu-dreamina- 前缀名,请求网关时映射为 dreamina-* 原名
  4224. *
  4225. * @param string $model
  4226. * @return bool
  4227. */
  4228. public function isOverseasBaiduSeedanceModel(string $model): bool
  4229. {
  4230. return in_array($model, [
  4231. 'baidu-dreamina-seedance-2-0-260128',
  4232. 'baidu-dreamina-seedance-2-0-fast-260128',
  4233. 'baidu-dreamina-seedance-2-0-mini-260615',
  4234. 'baidu-dreamina-seedance-2-5-260628',
  4235. ], true);
  4236. }
  4237. /**
  4238. * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-doubao-* / baidu-dreamina-* / 快快AI seed-2 系列)
  4239. * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
  4240. *
  4241. * @param string $model
  4242. * @return bool
  4243. */
  4244. public function isSeedance20SeriesModel(string $model): bool
  4245. {
  4246. return strpos($model, 'doubao-seedance-2.0') !== false
  4247. || $this->isKuaikuaiSeedanceModel($model)
  4248. || $this->isBaiduSeedanceModel($model)
  4249. || $this->isOverseasBaiduSeedanceModel($model);
  4250. }
  4251. public function createActVideoTask($data) {
  4252. $act_id = getProp($data, 'act_id');
  4253. $first_frame_url = getProp($data, 'first_frame_url');
  4254. $tail_frame_url = getProp($data, 'tail_frame_url');
  4255. $generate_audio = getProp($data, 'generate_audio', 1);
  4256. $video_duration = getProp($data, 'video_duration');
  4257. $video_resolution = getProp($data, 'video_resolution');
  4258. $ratio = getProp($data, 'ratio');
  4259. $products = getProp($data, 'products', []);
  4260. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4261. if (!is_array($reference_images) || !is_array($products)) {
  4262. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4263. }
  4264. if (!$act_id) {
  4265. Utils::throwError('1002:片段ID不能为空');
  4266. }
  4267. // 获取片段信息
  4268. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4269. if (!$act) {
  4270. Utils::throwError('20003:片段不存在');
  4271. }
  4272. $act = (array)$act;
  4273. $anime_id = getProp($act, 'anime_id');
  4274. $episode_id = getProp($act, 'episode_id');
  4275. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4276. $ace_mode = getProp($anime, 'ace_mode');
  4277. $art_style_type = getProp($anime, 'art_style_type');
  4278. $art_style = getProp($anime, 'art_style');
  4279. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4280. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4281. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4282. // 将资产中新出现的资产放到extra_products中
  4283. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4284. if (!empty($products) && $episode) {
  4285. // 获取剧集中的角色、场景和道具列表
  4286. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4287. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4288. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4289. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4290. // 构建角色名称列表
  4291. $role_names = array_column($roles, 'role');
  4292. // 构建场景名称列表
  4293. $scene_names = array_column($scenes, 'scene');
  4294. // 构建道具名称列表
  4295. $prop_names = array_column($props, 'prop');
  4296. // 遍历传入的products
  4297. foreach ($products as $product) {
  4298. $product_name = getProp($product, 'product_name');
  4299. // 如果product_name不在roles、scenes和props中
  4300. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4301. // 查找是否在extra_products中存在同名的
  4302. $found = false;
  4303. foreach ($extra_products as $key => $extra_product) {
  4304. if (getProp($extra_product, 'product_name') === $product_name) {
  4305. // 有同名的则覆盖
  4306. $extra_products[$key] = $product;
  4307. $found = true;
  4308. break;
  4309. }
  4310. }
  4311. // 没有则新增
  4312. if (!$found) {
  4313. $extra_products[] = $product;
  4314. }
  4315. }
  4316. }
  4317. if ($extra_products) {
  4318. // 保存到数据库
  4319. DB::table('mp_anime_episodes')
  4320. ->where('id', $episode_id)
  4321. ->update([
  4322. 'extra_products' => json_encode($extra_products, 256),
  4323. 'updated_at' => date('Y-m-d H:i:s')
  4324. ]);
  4325. }
  4326. }
  4327. // 获取分镜内容
  4328. $actContent = getProp($act, 'act_show_content', '');
  4329. // 音效同出(默认使用)
  4330. $current_generate_audio = $generate_audio ? 1 : 0;
  4331. // 构建完整的提示词
  4332. $processResult = $this->processActContentWithProducts($actContent, $products);
  4333. $fullPrompt = $processResult['content'];
  4334. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4335. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4336. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4337. // 处理视频模型
  4338. $model = getProp($data, 'model');
  4339. if (!$model) {
  4340. $model = getProp($episode, 'video_model');
  4341. if (!$model) {
  4342. // episode表也没有,使用默认值
  4343. $model = 'seed-2';
  4344. }
  4345. }
  4346. // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
  4347. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  4348. if (!in_array($model, $valid_models)) {
  4349. $model = 'seed-2';
  4350. }
  4351. // 保存到episode表(仅在专用方法中更新模型)
  4352. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4353. // 'video_model' => $model,
  4354. // 'updated_at' => date('Y-m-d H:i:s')
  4355. // ]);
  4356. // 余额预检:按预估时长计算所需积分,不足直接报错
  4357. $chargeDuration = (int)$videoDuration;
  4358. if ($chargeDuration <= 0) {
  4359. $chargeDuration = 5; // 无时长时按默认5秒预估
  4360. }
  4361. $this->pointsService->checkUserPointsEnough(
  4362. $this->pointsService->getVideoChargePoints([
  4363. 'model' => $model,
  4364. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4365. 'video_duration' => $chargeDuration,
  4366. 'ratio' => $ratio,
  4367. 'generate_audio' => $current_generate_audio,
  4368. ])
  4369. );
  4370. // 构建视频生成参数
  4371. $videoParams = [
  4372. 'model' => $model,
  4373. 'alias_act_id' => $act_id,
  4374. 'prompt' => trim($fullPrompt),
  4375. 'video_duration' => $videoDuration,
  4376. 'video_resolution' => $video_resolution,
  4377. 'seed' => -1,
  4378. 'ratio' => $ratio,
  4379. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4380. 'draft' => false,
  4381. 'watermark' => false,
  4382. 'camera_fixed' => false,
  4383. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4384. ];
  4385. // 如果分镜有图片,作为首帧
  4386. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4387. $hasVideo = !empty(getProp($act, 'video_url'));
  4388. if ($hasImage) {
  4389. if ($first_frame_url) {
  4390. $videoParams['first_frame_url'] = $first_frame_url;
  4391. }else {
  4392. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4393. }
  4394. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4395. }
  4396. // 构建content数组
  4397. $videoParams['content'] = [
  4398. [
  4399. 'type' => 'text',
  4400. 'text' => $videoParams['prompt'],
  4401. ]
  4402. ];
  4403. // 如果有首帧图片,添加到content中
  4404. if ($hasImage) {
  4405. 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', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
  4406. $videoParams['content'][] = [
  4407. 'type' => 'image_url',
  4408. 'image_url' => [
  4409. 'url' => $videoParams['first_frame_url'],
  4410. ],
  4411. 'role' => 'reference_image',
  4412. ];
  4413. if (isset($videoParams['tail_frame_url'])) {
  4414. $videoParams['content'][] = [
  4415. 'type' => 'image_url',
  4416. 'image_url' => [
  4417. 'url' => $videoParams['tail_frame_url'],
  4418. ],
  4419. 'role' => 'reference_image',
  4420. ];
  4421. }
  4422. }else {
  4423. $videoParams['content'][] = [
  4424. 'type' => 'image_url',
  4425. 'image_url' => [
  4426. 'url' => $videoParams['first_frame_url'],
  4427. ],
  4428. 'role' => 'first_frame',
  4429. ];
  4430. if (isset($videoParams['tail_frame_url'])) {
  4431. $videoParams['content'][] = [
  4432. 'type' => 'image_url',
  4433. 'image_url' => [
  4434. 'url' => $videoParams['tail_frame_url'],
  4435. ],
  4436. 'role' => 'last_frame',
  4437. ];
  4438. }
  4439. }
  4440. }
  4441. // dd($videoParams);
  4442. // 根据模型选择不同的视频生成方法
  4443. try {
  4444. if (strpos($model, 'jimeng') !== false) {
  4445. // 即梦模型参数调整
  4446. unset($videoParams['content']); // 即梦不使用content格式
  4447. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4448. } elseif (strpos($model, 'kling') !== false) {
  4449. // Keling模型参数调整
  4450. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4451. unset($videoParams['ratio']);
  4452. unset($videoParams['content']); // Keling不使用content格式
  4453. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4454. } elseif (strpos($model, 'zhizhen') !== false) {
  4455. // 智帧20等新模型使用统一API
  4456. // 构建统一API参数
  4457. $unifiedParams = [
  4458. 'model_code' => $model,
  4459. 'alias_act_id' => $act_id,
  4460. 'prompt' => trim($fullPrompt),
  4461. 'video_duration' => $videoDuration,
  4462. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4463. 'video_ratio' => $ratio,
  4464. 'seed' => -1,
  4465. ];
  4466. // 构建parameters参数
  4467. $parameters = [
  4468. 'seconds' => $unifiedParams['video_duration'],
  4469. 'resolution' => $unifiedParams['video_resolution'],
  4470. 'ratio' => $ratio,
  4471. // 'video_mode' => 'multi_image',
  4472. // 'mode' => 'multi_image',
  4473. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4474. ];
  4475. $hasImage = false;
  4476. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4477. if ($hasImage) {
  4478. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4479. if (isset($videoParams['tail_frame_url'])) {
  4480. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4481. }
  4482. } else {
  4483. // 没有图片时,记录错误日志
  4484. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4485. 'act_id' => $act_id,
  4486. 'model' => $model
  4487. ]);
  4488. }
  4489. if ($reference_images) {
  4490. // 限制只传入9张参考图
  4491. $reference_images = array_slice($reference_images, 0, 9);
  4492. // 在处理之前先保存原始reference_images到任务参数中
  4493. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4494. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4495. $parameters['reference_images'] = $reference_images;
  4496. $parameters['video_mode'] = 'multi_image';
  4497. $parameters['mode'] = 'multi_image';
  4498. }
  4499. $unifiedParams['parameters'] = $parameters;
  4500. // 调用统一API创建任务
  4501. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4502. } elseif ($this->isSeedance20SeriesModel($model)) {
  4503. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4504. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4505. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4506. // 保存原始参考图用于任务记录
  4507. $videoParams['reference_images'] = $reference_images;
  4508. if ($reference_images) {
  4509. // 限制只传入9张参考图
  4510. $reference_images = array_slice($reference_images, 0, 9);
  4511. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4512. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4513. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4514. $reference_image_assets = $isKuaikuai
  4515. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4516. : ($isDreamina
  4517. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $fullPrompt)
  4518. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt));
  4519. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4520. $videoParams['prompt'] = trim($fullPrompt);
  4521. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4522. $videoParams['reference_image_assets'] = $reference_image_assets;
  4523. }
  4524. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4525. if ($isKuaikuai) {
  4526. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4527. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4528. } else {
  4529. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4530. }
  4531. } else {
  4532. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4533. }
  4534. } catch (ApiException $e) {
  4535. // 上游调用抛出的网关异常统一做友好化处理;本地业务错误(非1001)保持原提示不变
  4536. if ($e->getCode() === 1001) {
  4537. Utils::throwError('1001:' . mapErrorMessage($e->getMessage()));
  4538. }
  4539. throw $e;
  4540. } catch (\Exception $e) {
  4541. // 其他未包装的异常,同样只对报错信息做格式化,便于前端展示友好提示
  4542. Utils::throwError('20003:' . mapErrorMessage($e->getMessage()));
  4543. }
  4544. // 更新分镜表的视频任务信息
  4545. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4546. 'video_task_id' => $task->id,
  4547. 'video_task_status' => '生成中',
  4548. 'generate_audio' => $generate_audio,
  4549. 'updated_at' => date('Y-m-d H:i:s')
  4550. ]);
  4551. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4552. $episode_number = getProp($act, 'episode_number');
  4553. $act_number = getProp($act, 'act_number');
  4554. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4555. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4556. }
  4557. $result = [
  4558. 'task_id' => $task->id,
  4559. 'status' => $task->status,
  4560. 'act_id' => $act_id,
  4561. 'video_duration' => $videoDuration
  4562. ];
  4563. // 仅当任务提交阶段就已失败时,附带格式化后的错误信息;正常返回结构不受影响
  4564. if ($task->status === 'failed' && !empty($task->error_message)) {
  4565. $result['error_message'] = mapErrorMessage($task->error_message);
  4566. }
  4567. return $result;
  4568. }
  4569. /**
  4570. * 文生视频通用方法
  4571. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4572. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4573. *
  4574. * @param array $data 请求参数
  4575. * @return array
  4576. */
  4577. public function generateVideo($data) {
  4578. $prompt = getProp($data, 'prompt');
  4579. if (empty($prompt)) {
  4580. Utils::throwError('20003:提示词不能为空');
  4581. }
  4582. $model = getProp($data, 'model');
  4583. if (!$model) {
  4584. $model = 'seed-2';
  4585. }
  4586. // 验证模型是否在可用模型表中
  4587. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4588. Utils::throwError('20003:该模型已不可用,请更换!');
  4589. }
  4590. $video_duration = getProp($data, 'video_duration', 5);
  4591. // 默认超分720p档(按480p生成后本地超分到720p);480p为原始档需前端显式指定
  4592. $video_resolution = getProp($data, 'video_resolution', 'sr_720p');
  4593. $ratio = getProp($data, 'ratio', '9:16');
  4594. $generate_audio = getProp($data, 'generate_audio', 1);
  4595. $seed = getProp($data, 'seed', -1);
  4596. $first_frame_url = getProp($data, 'first_frame_url');
  4597. $tail_frame_url = getProp($data, 'tail_frame_url');
  4598. // 参考图(支持数组或JSON字符串,最多9张)
  4599. $reference_images = getProp($data, 'reference_images', []);
  4600. if (is_string($reference_images)) {
  4601. $reference_images = json_decode($reference_images, true) ?: [];
  4602. }
  4603. if (!is_array($reference_images)) {
  4604. Utils::throwError('20003:参考图格式不正确');
  4605. }
  4606. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4607. $reference_images = array_slice($reference_images, 0, 9);
  4608. // 参考视频(支持数组或JSON字符串,最多3个)
  4609. $reference_videos = getProp($data, 'reference_videos', []);
  4610. if (is_string($reference_videos)) {
  4611. $reference_videos = json_decode($reference_videos, true) ?: [];
  4612. }
  4613. if (!is_array($reference_videos)) {
  4614. Utils::throwError('20003:参考视频格式不正确');
  4615. }
  4616. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4617. if (count($reference_videos) > 3) {
  4618. Utils::throwError('20003:参考视频最多选择3个');
  4619. }
  4620. $reference_videos = array_slice($reference_videos, 0, 3);
  4621. // 参考音频(支持数组或JSON字符串,最多3个)
  4622. $reference_audios = getProp($data, 'reference_audios', []);
  4623. if (is_string($reference_audios)) {
  4624. $reference_audios = json_decode($reference_audios, true) ?: [];
  4625. }
  4626. if (!is_array($reference_audios)) {
  4627. Utils::throwError('20003:参考音频格式不正确');
  4628. }
  4629. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4630. if (count($reference_audios) > 3) {
  4631. Utils::throwError('20003:参考音频最多选择3个');
  4632. }
  4633. $reference_audios = array_slice($reference_audios, 0, 3);
  4634. // 余额预检:按预估时长计算所需积分,不足直接报错
  4635. $chargeDuration = (int)ceil((float)$video_duration);
  4636. if ($chargeDuration <= 0) {
  4637. $chargeDuration = 5; // 无时长时按默认5秒预估
  4638. }
  4639. $this->pointsService->checkUserPointsEnough(
  4640. $this->pointsService->getVideoChargePoints([
  4641. 'model' => $model,
  4642. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4643. 'video_duration' => $chargeDuration,
  4644. 'ratio' => $ratio,
  4645. 'generate_audio' => (int)$generate_audio,
  4646. ])
  4647. );
  4648. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4649. $videoParams = [
  4650. 'model' => $model,
  4651. 'prompt' => $prompt,
  4652. 'video_duration' => $video_duration,
  4653. 'video_resolution' => $video_resolution,
  4654. 'seed' => $seed,
  4655. 'ratio' => $ratio,
  4656. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4657. 'draft' => getProp($data, 'draft', false),
  4658. 'watermark' => getProp($data, 'watermark', false),
  4659. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4660. ];
  4661. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4662. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4663. // 构建content数组
  4664. $videoParams['content'] = [
  4665. [
  4666. 'type' => 'text',
  4667. 'text' => $prompt,
  4668. ]
  4669. ];
  4670. // 根据模型选择不同的视频生成方法
  4671. if (strpos($model, 'jimeng') !== false) {
  4672. // 即梦模型参数调整
  4673. unset($videoParams['content']); // 即梦不使用content格式
  4674. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4675. } elseif (strpos($model, 'kling') !== false) {
  4676. // 可灵模型参数调整
  4677. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4678. unset($videoParams['ratio']);
  4679. unset($videoParams['content']); // 可灵不使用content格式
  4680. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4681. } elseif (strpos($model, 'zhizhen') !== false) {
  4682. // 智帧等新模型使用统一API
  4683. $unifiedParams = [
  4684. 'model_code' => $model,
  4685. 'prompt' => $prompt,
  4686. 'video_duration' => $video_duration,
  4687. 'video_resolution' => strtolower($video_resolution),
  4688. 'video_ratio' => $ratio,
  4689. 'seed' => $seed,
  4690. ];
  4691. // 构建parameters参数
  4692. $parameters = [
  4693. 'seconds' => $unifiedParams['video_duration'],
  4694. 'resolution' => $unifiedParams['video_resolution'],
  4695. 'ratio' => $ratio,
  4696. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4697. ];
  4698. // 首帧和尾帧
  4699. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4700. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4701. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4702. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4703. if ($refImageUrls) {
  4704. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4705. }
  4706. // 参考图处理
  4707. if ($reference_images) {
  4708. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4709. $parameters['reference_images'] = $reference_images;
  4710. $parameters['video_mode'] = 'multi_image';
  4711. $parameters['mode'] = 'multi_image';
  4712. }
  4713. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4714. if ($reference_videos) {
  4715. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4716. $parameters['reference_videos'] = $reference_videos;
  4717. }
  4718. if ($reference_audios) {
  4719. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4720. $parameters['reference_audios'] = $reference_audios;
  4721. }
  4722. $unifiedParams['parameters'] = $parameters;
  4723. // 调用统一API创建任务
  4724. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4725. } elseif ($this->isSeedance20SeriesModel($model)) {
  4726. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4727. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4728. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4729. $videoParams['reference_images'] = $reference_images;
  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_images) {
  4736. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI)
  4737. $reference_image_assets = $isKuaikuai
  4738. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4739. : ($isDreamina
  4740. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $videoParams['prompt'])
  4741. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']));
  4742. $videoParams['reference_image_assets'] = $reference_image_assets;
  4743. }
  4744. // 参考视频上传为素材(国内百度/海外百度dreamina/快快AI)
  4745. if ($reference_videos) {
  4746. $reference_video_assets = $isKuaikuai
  4747. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4748. : ($isDreamina
  4749. ? $this->aiVideoGenerationService->processReferenceVideosToBaiduDreaminaAssets($reference_videos, $videoParams['prompt'])
  4750. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']));
  4751. $videoParams['reference_video_assets'] = $reference_video_assets;
  4752. }
  4753. // 参考音频上传为素材(国内百度/海外百度dreamina/快快AI)
  4754. if ($reference_audios) {
  4755. $reference_audio_assets = $isKuaikuai
  4756. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4757. : ($isDreamina
  4758. ? $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($reference_audios, $videoParams['prompt'])
  4759. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']));
  4760. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4761. }
  4762. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4763. if ($reference_images || $reference_videos || $reference_audios) {
  4764. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4765. }
  4766. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4767. if ($isKuaikuai) {
  4768. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4769. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4770. } else {
  4771. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4772. }
  4773. } else {
  4774. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4775. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4776. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4777. if ($refImageUrls) {
  4778. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4779. }
  4780. if ($reference_videos) {
  4781. foreach ($reference_videos as $videoUrl) {
  4782. $videoParams['content'][] = [
  4783. 'type' => 'video_url',
  4784. 'video_url' => [
  4785. 'url' => $videoUrl,
  4786. ],
  4787. 'role' => 'reference_video',
  4788. ];
  4789. }
  4790. }
  4791. if ($reference_audios) {
  4792. foreach ($reference_audios as $audioUrl) {
  4793. $videoParams['content'][] = [
  4794. 'type' => 'audio_url',
  4795. 'audio_url' => [
  4796. 'url' => $audioUrl,
  4797. ],
  4798. 'role' => 'reference_audio',
  4799. ];
  4800. }
  4801. }
  4802. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4803. }
  4804. return [
  4805. 'task_id' => $task->id,
  4806. 'status' => $task->status,
  4807. 'model' => $model,
  4808. 'video_duration' => $video_duration,
  4809. 'video_resolution' => $video_resolution,
  4810. 'ratio' => $ratio
  4811. ];
  4812. }
  4813. /**
  4814. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4815. *
  4816. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4817. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4818. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4819. *
  4820. * @param array $data
  4821. * @return array
  4822. */
  4823. public function previewCharge(array $data): array
  4824. {
  4825. $mode = (string)getProp($data, 'mode', '');
  4826. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4827. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4828. }
  4829. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4830. $scene = (string)getProp($data, 'scene', 'video_generation');
  4831. // 未显式传scene且带参考视频时,自动按video_to_video定价
  4832. if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
  4833. $scene = 'video_to_video';
  4834. }
  4835. $items = [];
  4836. $model = '';
  4837. $resolution = '';
  4838. if ($mode === 'video') {
  4839. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4840. $model = (string)getProp($data, 'model', '');
  4841. if (!$model) {
  4842. Utils::throwError('1002:model参数不能为空');
  4843. }
  4844. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4845. $duration = (int)getProp($data, 'video_duration', 5);
  4846. if ($duration <= 0) {
  4847. $duration = 5;
  4848. }
  4849. $count = max(1, (int)getProp($data, 'count', 1));
  4850. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4851. 'model' => $model,
  4852. 'video_resolution' => $resolution,
  4853. 'video_duration' => $duration,
  4854. 'mode' => $scene,
  4855. ]);
  4856. $points = $pointsPerVideo * $count;
  4857. $items[] = [
  4858. 'type' => 'video',
  4859. 'model' => $model,
  4860. 'video_resolution' => $resolution,
  4861. 'video_duration' => $duration,
  4862. 'count' => $count,
  4863. 'points' => $points,
  4864. ];
  4865. } elseif ($mode === 'image') {
  4866. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4867. $model = (string)getProp($data, 'model', '');
  4868. if (!$model) {
  4869. Utils::throwError('1002:model参数不能为空');
  4870. }
  4871. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4872. if (!$resolution) {
  4873. $width = (int)getProp($data, 'width', 0);
  4874. $height = (int)getProp($data, 'height', 0);
  4875. if ($width <= 0 || $height <= 0) {
  4876. $width = 1600;
  4877. $height = 2848;
  4878. }
  4879. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4880. }
  4881. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4882. $points = $this->pointsService->getImageChargePoints([
  4883. 'model' => $model,
  4884. 'resolution' => $resolution,
  4885. ]) * $imageNum;
  4886. $items[] = [
  4887. 'type' => 'image',
  4888. 'model' => $model,
  4889. 'resolution' => $resolution,
  4890. 'image_num' => $imageNum,
  4891. 'points' => $points,
  4892. ];
  4893. } else {
  4894. // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
  4895. // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
  4896. $priceType = (string)getProp($data, 'price_type', 'special');
  4897. if (!in_array($priceType, ['special', 'normal'], true)) {
  4898. Utils::throwError('1003:price_type参数仅支持special或normal');
  4899. }
  4900. $count = max(1, (int)getProp($data, 'count', 1));
  4901. $animeId = getProp($data, 'anime_id');
  4902. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4903. if ($animeId && $generateEpisodes > 0) {
  4904. // 批量生成分集按 special 档预估,与实际扣费口径一致
  4905. $priceType = 'special';
  4906. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4907. ->where('anime_id', $animeId)
  4908. ->where('is_default', 1)
  4909. ->max('episode_number');
  4910. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4911. $startEpisodeNumber = $currentMaxEpisode + 1;
  4912. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4913. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4914. ->where('anime_id', $animeId)
  4915. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4916. ->whereIn('status', ['pending', 'processing', 'completed'])
  4917. ->count();
  4918. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4919. if ($count < 0) {
  4920. $count = 0;
  4921. }
  4922. }
  4923. $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
  4924. $items[] = [
  4925. 'type' => 'chat',
  4926. 'count' => $count,
  4927. 'price_type' => $priceType,
  4928. 'points' => $points,
  4929. ];
  4930. }
  4931. $totalPoints = 0;
  4932. foreach ($items as $item) {
  4933. $totalPoints += $item['points'];
  4934. }
  4935. return [
  4936. 'mode' => $mode,
  4937. 'total_points' => $totalPoints,
  4938. 'items' => $items,
  4939. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4940. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4941. ];
  4942. }
  4943. /**
  4944. * 根据提示词内容智能计算最优视频时长
  4945. *
  4946. * @param string $segmentContent 分镜内容
  4947. * @param string $tailFrame 尾帧描述
  4948. * @return int 视频时长(2-12秒)
  4949. */
  4950. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4951. // 合并所有文本内容
  4952. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4953. // 如果没有内容,返回默认时长
  4954. if (empty($fullText)) {
  4955. return 5;
  4956. }
  4957. // 计算文本长度(中文字符按2个字符计算)
  4958. $textLength = mb_strlen($fullText, 'UTF-8');
  4959. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4960. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4961. // 分析内容复杂度
  4962. $complexityScore = $this->analyzeContentComplexity($fullText);
  4963. // 基础时长计算(根据文本长度)
  4964. $baseDuration = 3; // 默认2秒
  4965. // if ($adjustedLength <= 20) {
  4966. // $baseDuration = 3;
  4967. // } elseif ($adjustedLength <= 40) {
  4968. // $baseDuration = 4;
  4969. // } elseif ($adjustedLength <= 60) {
  4970. // $baseDuration = 5;
  4971. // } elseif ($adjustedLength <= 80) {
  4972. // $baseDuration = 6;
  4973. // } elseif ($adjustedLength <= 100) {
  4974. // $baseDuration = 7;
  4975. // } elseif ($adjustedLength <= 120) {
  4976. // $baseDuration = 8;
  4977. // } else {
  4978. // $baseDuration = 9;
  4979. // }
  4980. // 根据内容复杂度调整时长
  4981. $finalDuration = $baseDuration + $complexityScore;
  4982. // 确保时长在2-12秒范围内
  4983. return max(4, min(12, $finalDuration));
  4984. }
  4985. /**
  4986. * 分析内容复杂度,返回时长调整值
  4987. *
  4988. * @param string $text 文本内容
  4989. * @return int 调整值(-2到+3)
  4990. */
  4991. private function analyzeContentComplexity($text) {
  4992. $score = 0;
  4993. // 动作关键词(需要更长时间展现)
  4994. $actionKeywords = [
  4995. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4996. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4997. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4998. ];
  4999. // 静态关键词(可以用较短时间)
  5000. $staticKeywords = [
  5001. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  5002. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  5003. ];
  5004. // 复杂场景关键词(需要更长时间)
  5005. $complexSceneKeywords = [
  5006. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  5007. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  5008. ];
  5009. // 情感关键词(需要适中时间表现)
  5010. $emotionKeywords = [
  5011. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  5012. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  5013. ];
  5014. // 检查动作关键词
  5015. foreach ($actionKeywords as $keyword) {
  5016. if (strpos($text, $keyword) !== false) {
  5017. $score += 1;
  5018. break; // 避免重复加分
  5019. }
  5020. }
  5021. // 检查静态关键词
  5022. foreach ($staticKeywords as $keyword) {
  5023. if (strpos($text, $keyword) !== false) {
  5024. $score -= 1;
  5025. break;
  5026. }
  5027. }
  5028. // 检查复杂场景关键词
  5029. foreach ($complexSceneKeywords as $keyword) {
  5030. if (strpos($text, $keyword) !== false) {
  5031. $score += 1;
  5032. break;
  5033. }
  5034. }
  5035. // 检查情感关键词
  5036. foreach ($emotionKeywords as $keyword) {
  5037. if (strpos($text, $keyword) !== false) {
  5038. $score += 1;
  5039. break;
  5040. }
  5041. }
  5042. // 检查时间相关词汇
  5043. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  5044. $score += 1;
  5045. }
  5046. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  5047. $score -= 1;
  5048. }
  5049. // 检查转场词汇
  5050. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  5051. $score += 1;
  5052. }
  5053. // 检查环境描述(复杂环境需要更多时间)
  5054. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  5055. $score += 1;
  5056. }
  5057. // 检查对话内容(对话需要更多时间)
  5058. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  5059. $score += 1;
  5060. }
  5061. // 限制调整范围
  5062. return max(-1, min(4, $score));
  5063. }
  5064. /**
  5065. * 创建完整视频合成任务
  5066. *
  5067. * @param array $data
  5068. * @return array
  5069. */
  5070. public function createCompleteVideoTask($data)
  5071. {
  5072. $animeId = getProp($data, 'anime_id');
  5073. $episodeId = getProp($data, 'episode_id');
  5074. // 验证参数
  5075. if (!$animeId || !$episodeId) {
  5076. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  5077. }
  5078. // 检查是否已存在处理中的任务
  5079. $existingTask = DB::table('mp_complete_video_tasks')
  5080. ->where('anime_id', $animeId)
  5081. ->where('episode_id', $episodeId)
  5082. ->whereIn('generate_status', ['执行中'])
  5083. ->first();
  5084. if ($existingTask) {
  5085. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  5086. }
  5087. // 获取全能模式状态
  5088. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  5089. if ((int)$ace_mode === 1) {
  5090. // 获取所有片段的配音视频,按 act_number 排序
  5091. $segments = DB::table('mp_episode_segments')
  5092. ->where('anime_id', $animeId)
  5093. ->where('episode_id', $episodeId)
  5094. ->orderBy('segment_number')
  5095. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5096. ->get();
  5097. // 检查是否所有片段都有视频
  5098. $missingVideos = $segments->filter(function($segment) {
  5099. return empty($segment->video_url);
  5100. });
  5101. if ($missingVideos->isNotEmpty()) {
  5102. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  5103. }
  5104. }else {
  5105. // 获取所有分镜的配音视频,按 segment_number 排序
  5106. $segments = DB::table('mp_episode_segments')
  5107. ->where('anime_id', $animeId)
  5108. ->where('episode_id', $episodeId)
  5109. ->orderBy('segment_number')
  5110. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5111. ->get();
  5112. // 检查是否所有分镜都有配音和视频
  5113. $missingVideos = $segments->filter(function($segment) {
  5114. return empty($segment->audio_url) || empty($segment->video_url);
  5115. });
  5116. if ($missingVideos->isNotEmpty()) {
  5117. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5118. }
  5119. }
  5120. if ($segments->isEmpty()) {
  5121. Utils::throwError('20003:未找到该剧集的分镜数据');
  5122. }
  5123. // 获取当前完整视频url
  5124. $completeVideoUrl = DB::table('mp_anime_episodes')
  5125. ->where('anime_id', $animeId)
  5126. ->where('id', $episodeId)
  5127. ->value('complete_video_url');
  5128. // 构建 generate_json
  5129. $generateJson = [];
  5130. $sequence = 1;
  5131. foreach ($segments as $segment) {
  5132. if ((int)$ace_mode === 1) {
  5133. $generateJson[] = [
  5134. 'sequence' => $sequence++,
  5135. 'video_url' => $segment->video_url,
  5136. 'video_time_point_start' => $segment->video_time_point_start,
  5137. 'video_time_point_end' => $segment->video_time_point_end
  5138. ];
  5139. }else {
  5140. $generateJson[] = [
  5141. 'sequence' => $sequence++,
  5142. 'video_url' => $segment->video_url,
  5143. 'audio_url' => $segment->audio_url,
  5144. 'video_time_point_start' => $segment->video_time_point_start,
  5145. 'video_time_point_end' => $segment->video_time_point_end
  5146. ];
  5147. }
  5148. }
  5149. // 创建任务
  5150. $now = date('Y-m-d H:i:s');
  5151. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5152. 'anime_id' => $animeId,
  5153. 'episode_id' => $episodeId,
  5154. 'generate_json' => json_encode($generateJson, 256),
  5155. 'generate_status' => '执行中',
  5156. 'complete_video_url' => '',
  5157. 'created_at' => $now,
  5158. 'updated_at' => $now
  5159. ]);
  5160. if (!$taskId) {
  5161. Utils::throwError('20003:创建任务失败');
  5162. }
  5163. // 更新剧集表的任务ID和状态
  5164. $boolen = DB::table('mp_anime_episodes')
  5165. ->where('anime_id', $animeId)
  5166. ->where('id', $episodeId)
  5167. ->update([
  5168. 'complete_video_task_id' => $taskId,
  5169. 'complete_video_task_status' => '执行中',
  5170. 'updated_at' => $now
  5171. ]);
  5172. if (!$boolen) {
  5173. Utils::throwError('20003:更新剧集表失败');
  5174. }
  5175. dLog('anime')->info('创建完整视频合成任务', [
  5176. 'task_id' => $taskId,
  5177. 'anime_id' => $animeId,
  5178. 'episode_id' => $episodeId,
  5179. 'segment_count' => count($generateJson)
  5180. ]);
  5181. // 请求远程服务器执行生成
  5182. $client = new Client(['timeout' => 600, 'verify' => false]);
  5183. try {
  5184. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5185. $response = $result->getBody()->getContents();
  5186. $response_arr = json_decode($response, true);
  5187. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5188. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5189. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5190. // // 更新任务状态为失败
  5191. // DB::table('mp_complete_video_tasks')
  5192. // ->where('id', $taskId)
  5193. // ->update([
  5194. // 'generate_status' => '执行失败',
  5195. // 'error_message' => $error_msg,
  5196. // 'updated_at' => date('Y-m-d H:i:s')
  5197. // ]);
  5198. // // 同步更新剧集表状态
  5199. // DB::table('mp_anime_episodes')
  5200. // ->where('complete_video_task_id', $taskId)
  5201. // ->update([
  5202. // 'complete_video_task_status' => '执行失败',
  5203. // 'updated_at' => date('Y-m-d H:i:s')
  5204. // ]);
  5205. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5206. }
  5207. } catch (\Exception $e) {
  5208. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5209. // 更新任务状态为失败
  5210. DB::table('mp_complete_video_tasks')
  5211. ->where('id', $taskId)
  5212. ->update([
  5213. 'generate_status' => '执行失败',
  5214. 'error_message' => $e->getMessage(),
  5215. 'updated_at' => date('Y-m-d H:i:s')
  5216. ]);
  5217. // 同步更新剧集表状态
  5218. DB::table('mp_anime_episodes')
  5219. ->where('complete_video_task_id', $taskId)
  5220. ->update([
  5221. 'complete_video_task_status' => '执行失败',
  5222. 'updated_at' => date('Y-m-d H:i:s')
  5223. ]);
  5224. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5225. }
  5226. // 开始轮询任务状态
  5227. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5228. $pollInterval = 5; // 每5秒轮询一次
  5229. $attempt = 0;
  5230. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5231. while ($attempt < $maxAttempts) {
  5232. sleep($pollInterval);
  5233. $attempt++;
  5234. // 查询任务状态
  5235. $task = DB::table('mp_complete_video_tasks')
  5236. ->where('id', $taskId)
  5237. ->first();
  5238. if (!$task) {
  5239. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5240. Utils::throwError('20003:任务不存在');
  5241. }
  5242. dLog('anime')->info('轮询任务状态', [
  5243. 'task_id' => $taskId,
  5244. 'attempt' => $attempt,
  5245. 'status' => $task->generate_status
  5246. ]);
  5247. // 检查任务是否完成
  5248. if ($task->generate_status === '执行成功') {
  5249. // 同步更新剧集表状态
  5250. $boolen3 = DB::table('mp_anime_episodes')
  5251. ->where('anime_id', $animeId)
  5252. ->where('id', $episodeId)
  5253. ->update([
  5254. 'complete_video_url' => $task->complete_video_url,
  5255. 'complete_video_task_status' => '执行成功',
  5256. 'updated_at' => date('Y-m-d H:i:s')
  5257. ]);
  5258. dLog('anime')->info('视频合成任务完成', [
  5259. 'task_id' => $taskId,
  5260. 'video_url' => $task->complete_video_url,
  5261. 'attempts' => $attempt
  5262. ]);
  5263. // 如果更新成功则远程删除之前的文件
  5264. if ($boolen3 && $completeVideoUrl) {
  5265. $encode_url = urlencode($completeVideoUrl);
  5266. $client = new Client(['timeout' => 300, 'verify' => false]);
  5267. // 根据ID通过API通知合成音频
  5268. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5269. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5270. $response = $result->getBody()->getContents();
  5271. $response_arr = json_decode($response, true);
  5272. Log::info('火山删除音频返回: '.$response);
  5273. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5274. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5275. Log::info('火山删除音频失败: '.$error_msg);
  5276. // Utils::throwError('20003:火山删除音频失败');
  5277. }
  5278. }
  5279. return [
  5280. 'task_id' => $taskId,
  5281. 'anime_id' => $animeId,
  5282. 'episode_id' => $episodeId,
  5283. 'segment_count' => count($generateJson),
  5284. 'generate_status' => '执行成功',
  5285. 'complete_video_url' => $task->complete_video_url,
  5286. ];
  5287. }
  5288. // 检查任务是否失败
  5289. if ($task->generate_status === '执行失败') {
  5290. // 同步更新剧集表状态
  5291. DB::table('mp_anime_episodes')
  5292. ->where('anime_id', $animeId)
  5293. ->where('id', $episodeId)
  5294. ->update([
  5295. 'complete_video_task_status' => '执行失败',
  5296. 'updated_at' => date('Y-m-d H:i:s')
  5297. ]);
  5298. $errorMessage = $task->error_message ?? '未知错误';
  5299. dLog('anime')->error('视频合成任务失败', [
  5300. 'task_id' => $taskId,
  5301. 'error' => $errorMessage,
  5302. 'attempts' => $attempt
  5303. ]);
  5304. return [
  5305. 'task_id' => $taskId,
  5306. 'anime_id' => $animeId,
  5307. 'episode_id' => $episodeId,
  5308. 'segment_count' => count($generateJson),
  5309. 'generate_status' => '执行失败',
  5310. 'error_message' => $errorMessage
  5311. ];
  5312. }
  5313. }
  5314. // 超时处理
  5315. dLog('anime')->warning('视频合成任务超时', [
  5316. 'task_id' => $taskId,
  5317. 'max_attempts' => $maxAttempts,
  5318. 'timeout_seconds' => $maxAttempts * $pollInterval
  5319. ]);
  5320. // 更新任务状态为超时
  5321. DB::table('mp_complete_video_tasks')
  5322. ->where('id', $taskId)
  5323. ->update([
  5324. 'generate_status' => '超时',
  5325. 'error_message' => '任务执行超时(5分钟)',
  5326. 'updated_at' => date('Y-m-d H:i:s')
  5327. ]);
  5328. return [
  5329. 'task_id' => $taskId,
  5330. 'anime_id' => $animeId,
  5331. 'episode_id' => $episodeId,
  5332. 'segment_count' => count($generateJson),
  5333. 'generate_status' => '超时',
  5334. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5335. ];
  5336. }
  5337. /**
  5338. * 根据 inner_prompt_type 附加内置提示词
  5339. *
  5340. * @param string $prompt 用户提示词
  5341. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5342. * @return string 合并后的提示词
  5343. */
  5344. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5345. {
  5346. $innerPromptMap = [
  5347. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  5348. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5349. ];
  5350. if (!isset($innerPromptMap[$innerPromptType])) {
  5351. return $prompt;
  5352. }
  5353. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5354. }
  5355. /**
  5356. * 根据 inner_prompt_type 获取生成图片数量
  5357. *
  5358. * @param int $innerPromptType 内置提示词类型
  5359. * @param int $imageNum 传入的图片张数
  5360. * @return int 图片数量
  5361. */
  5362. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5363. {
  5364. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5365. }
  5366. /**
  5367. * 提取图片生成结果URL
  5368. *
  5369. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5370. * @param int $innerPromptType 内置提示词类型
  5371. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5372. */
  5373. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5374. {
  5375. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5376. if (is_array($resultUrls) && !empty($resultUrls)) {
  5377. $resultUrls = array_values($resultUrls);
  5378. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5379. }
  5380. if (!empty($resultUrl)) {
  5381. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5382. }
  5383. return (int)$innerPromptType === 2 ? [] : '';
  5384. }
  5385. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5386. $prompt = getProp($data, 'prompt');
  5387. $episode_id = getProp($data, 'episode_id');
  5388. $ref_img_urls = getProp($data, 'ref_img_urls');
  5389. $ratio = getProp($data, 'ratio', '9:16');
  5390. $resolution = getProp($data, 'resolution', '2k');
  5391. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5392. $imageNum = (int)getProp($data, 'image_num', 1);
  5393. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  5394. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  5395. // 参数验证
  5396. $resolution = strtolower($resolution);
  5397. if (!isset($sizeMap[$resolution])) {
  5398. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5399. }
  5400. if (!isset($sizeMap[$resolution][$ratio])) {
  5401. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5402. }
  5403. // 根据 ratio 和 resolution 确定宽高
  5404. $width = $sizeMap[$resolution][$ratio]['width'];
  5405. $height = $sizeMap[$resolution][$ratio]['height'];
  5406. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5407. if (is_json($ref_img_urls)) {
  5408. $ref_img_urls = json_decode($ref_img_urls, true);
  5409. }else {
  5410. $ref_img_urls = explode(',', $ref_img_urls);
  5411. }
  5412. }
  5413. // 处理图片模型
  5414. $model = getProp($data, 'model');
  5415. if (!$model) {
  5416. // 用户没有输入,从episode表获取
  5417. if ($episode_id) {
  5418. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5419. $model = getProp($episode, 'image_model');
  5420. }
  5421. if (!$model) {
  5422. // episode表也没有,使用默认值
  5423. $model = 'doubao-seedream-5-0-lite-260128';
  5424. }
  5425. }
  5426. // 验证模型是否在可用模型表中
  5427. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5428. // $model = 'doubao-seedream-5-0-lite-260128';
  5429. Utils::throwError('20003:该模型已不可用,请更换!');
  5430. }
  5431. // 保存到episode表
  5432. if ($episode_id) {
  5433. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5434. 'image_model' => $model,
  5435. 'updated_at' => date('Y-m-d H:i:s')
  5436. ]);
  5437. }
  5438. // 参数验证
  5439. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5440. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5441. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5442. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5443. try {
  5444. // 创建图片生成任务
  5445. $params = [
  5446. 'prompt' => $prompt,
  5447. 'model' => $model,
  5448. 'ref_img_urls' => '',
  5449. 'width' => $width,
  5450. 'height' => $height,
  5451. 'image_num' => $imageNum
  5452. ];
  5453. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5454. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5455. $task_id = $task->id;
  5456. if (!$task_id) {
  5457. Utils::throwError('20003:创建图片生成任务失败');
  5458. }
  5459. // 创建任务中心记录并关联图片任务ID
  5460. $taskCenter = $this->taskCenterService->createTask('image', [
  5461. 'title' => '文生图',
  5462. 'ref_task_id' => $task_id,
  5463. // 'prompt' => $prompt,
  5464. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5465. ]);
  5466. $taskCenterId = $taskCenter->id;
  5467. // 组装本次任务信息(用于init消息,类似generateVideo)
  5468. $taskInfo = [
  5469. 'task_id' => $task_id,
  5470. 'status' => getProp($task, 'status', 'processing'),
  5471. 'model' => $model,
  5472. 'ratio' => $ratio,
  5473. 'resolution' => $resolution,
  5474. 'image_num' => $imageNum,
  5475. ];
  5476. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5477. if (is_callable($onTaskCreated)) {
  5478. $onTaskCreated($taskCenterId, $taskInfo);
  5479. }
  5480. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5481. $model = getProp($task, 'model');
  5482. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5483. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5484. $isSyncModel = $isVolcModel || $isGptModel;
  5485. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5486. $start_time = time();
  5487. $timeout = 300; // 5分钟
  5488. $img_url = '';
  5489. $img_urls = [];
  5490. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5491. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5492. while (time() - $start_time < $timeout) {
  5493. sleep(3);
  5494. // 每分钟发送一次队列状态消息(仅流式模式)
  5495. if (is_callable($onPoll)) {
  5496. $currentTime = time();
  5497. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5498. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5499. $lastQueueMessageTime = $currentTime;
  5500. }
  5501. }
  5502. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5503. if ($isSyncModel) {
  5504. // 刷新任务状态
  5505. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5506. if ($task->status === 'success' && $task->result_url) {
  5507. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5508. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5509. if (!empty($resultUrls)) {
  5510. $img_urls = $resultUrls;
  5511. $img_url = $resultUrls[0];
  5512. } else {
  5513. $img_url = (string)$task->result_url;
  5514. }
  5515. break;
  5516. } elseif ($task->status === 'failed') {
  5517. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5518. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5519. }
  5520. // // 如果还在处理中,提示用户稍后查看
  5521. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5522. }else {
  5523. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5524. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5525. if ($statusInfo['status'] === 'success') {
  5526. $task->updateStatus('success', [
  5527. 'result_url' => $statusInfo['result_url'],
  5528. 'result_json' => $statusInfo['result_json'] ?? []
  5529. ]);
  5530. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5531. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5532. if (!empty($resultUrls)) {
  5533. $img_urls = $resultUrls;
  5534. $img_url = $resultUrls[0];
  5535. } else {
  5536. $img_url = (string)$statusInfo['result_url'];
  5537. }
  5538. break;
  5539. } elseif ($statusInfo['status'] === 'failed') {
  5540. $task->updateStatus('failed', [
  5541. 'error_message' => $statusInfo['error_message'],
  5542. 'result_json' => $statusInfo['result_json'] ?? []
  5543. ]);
  5544. dLog('anime')->error('图片生成失败,', [
  5545. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5546. ]);
  5547. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5548. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5549. }
  5550. }
  5551. }
  5552. if (empty($img_url)) {
  5553. Utils::throwError('20003:图片生成超时,请稍后重试');
  5554. }
  5555. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5556. if (count($img_urls) > 1) {
  5557. return [
  5558. 'img_url' => $img_url,
  5559. 'image_urls' => $img_urls,
  5560. 'task_id' => $taskCenterId,
  5561. ];
  5562. }
  5563. return [
  5564. 'img_url' => $img_url,
  5565. 'task_id' => $taskCenterId,
  5566. ];
  5567. } catch (\Exception $e) {
  5568. dLog('anime')->error('更新角色或场景失败', [
  5569. 'error' => $e->getMessage()
  5570. ]);
  5571. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5572. Utils::throwError('20003:' . $e->getMessage());
  5573. }
  5574. }
  5575. /**
  5576. * 使用文生文模型解析分镜内容
  5577. */
  5578. private function parseSegmentContentWithAI($segment_content) {
  5579. try {
  5580. // 使用DeepSeek服务的公开方法解析分镜内容
  5581. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5582. } catch (\Exception $e) {
  5583. // 如果AI解析失败,记录日志并返回原内容
  5584. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5585. return $segment_content;
  5586. }
  5587. }
  5588. /**
  5589. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5590. *
  5591. * @param int $episode_id 分集ID
  5592. * @param int $anime_id 动漫ID
  5593. * @param array $roles 分集角色数组(引用传递)
  5594. * @param array $scenes 分集场景数组(引用传递)
  5595. * @param array $episode 分集数据
  5596. */
  5597. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5598. // 获取全局动漫的角色和场景数据
  5599. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5600. if (!$anime) return;
  5601. $art_style_type = getProp($anime, 'art_style_type');
  5602. $character_prefix = '';
  5603. $scene_prefix = '';
  5604. if ($art_style_type) {
  5605. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5606. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5607. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5608. }
  5609. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5610. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5611. $roles_updated = false;
  5612. $scenes_updated = false;
  5613. // 处理角色
  5614. foreach ($roles as &$role) {
  5615. $role_name = getProp($role, 'role');
  5616. $role_description = getProp($role, 'description');
  5617. $role_pic_prompt = getProp($role, 'pic_prompt');
  5618. $role_url = getProp($role, 'url');
  5619. $role_task_id = getProp($role, 'task_id');
  5620. // 如果已有URL或已有任务ID,跳过
  5621. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5622. continue;
  5623. }
  5624. $url_inherited = false;
  5625. // 尝试从全局数据中继承
  5626. foreach ($global_roles as $global_role) {
  5627. $global_role_name = getProp($global_role, 'role');
  5628. $global_role_description = getProp($global_role, 'description');
  5629. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5630. $global_role_url = getProp($global_role, 'url');
  5631. $global_role_task_id = getProp($global_role, 'task_id');
  5632. $global_role_task_status = getProp($global_role, 'task_status');
  5633. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5634. if ($role_name === $global_role_name
  5635. && $role_description === $global_role_description
  5636. && $role_pic_prompt === $global_role_pic_prompt
  5637. && !empty($global_role_url)) {
  5638. // 继承 task_id、task_status 和 url
  5639. $role['task_id'] = $global_role_task_id;
  5640. $role['task_status'] = $global_role_task_status;
  5641. $role['url'] = $global_role_url;
  5642. $roles_updated = true;
  5643. $url_inherited = true;
  5644. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5645. break;
  5646. }
  5647. }
  5648. // 如果无法继承且没有任务ID,创建新任务
  5649. if (!$url_inherited && empty($role_task_id)) {
  5650. try {
  5651. $art_style = getProp($episode, 'art_style');
  5652. // 优先使用 pic_prompt,如果没有则使用 description
  5653. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5654. // if ($art_style) {
  5655. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5656. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5657. // }
  5658. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5659. $params = [
  5660. 'prompt' => $description,
  5661. 'ref_img_urls' => []
  5662. ];
  5663. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5664. $task_id = $task->id;
  5665. if ($task_id) {
  5666. $role['task_id'] = $task_id;
  5667. $role['task_status'] = 'processing';
  5668. $roles_updated = true;
  5669. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5670. }
  5671. } catch (\Exception $e) {
  5672. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5673. }
  5674. }
  5675. }
  5676. // 处理场景
  5677. foreach ($scenes as &$scene) {
  5678. $scene_name = getProp($scene, 'scene');
  5679. $scene_description = getProp($scene, 'description');
  5680. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5681. $scene_url = getProp($scene, 'url');
  5682. $scene_task_id = getProp($scene, 'task_id');
  5683. // 如果已有URL或已有任务ID,跳过
  5684. if (!empty($scene_url) || !empty($scene_task_id)) {
  5685. continue;
  5686. }
  5687. $url_inherited = false;
  5688. // 尝试从全局数据中继承
  5689. foreach ($global_scenes as $global_scene) {
  5690. $global_scene_name = getProp($global_scene, 'scene');
  5691. $global_scene_description = getProp($global_scene, 'description');
  5692. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5693. $global_scene_url = getProp($global_scene, 'url');
  5694. $global_scene_task_id = getProp($global_scene, 'task_id');
  5695. $global_scene_task_status = getProp($global_scene, 'task_status');
  5696. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5697. if ($scene_name === $global_scene_name
  5698. && $scene_description === $global_scene_description
  5699. && $scene_pic_prompt === $global_scene_pic_prompt
  5700. && !empty($global_scene_url)) {
  5701. // 继承 task_id、task_status 和 url
  5702. $scene['task_id'] = $global_scene_task_id;
  5703. $scene['task_status'] = $global_scene_task_status;
  5704. $scene['url'] = $global_scene_url;
  5705. $scenes_updated = true;
  5706. $url_inherited = true;
  5707. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5708. break;
  5709. }
  5710. }
  5711. // 如果无法继承且没有任务ID,创建新任务
  5712. if (!$url_inherited && empty($scene_task_id)) {
  5713. try {
  5714. $art_style = getProp($episode, 'art_style');
  5715. // 优先使用 pic_prompt,如果没有则使用 description
  5716. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5717. // if ($art_style) {
  5718. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5719. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5720. // }
  5721. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5722. $params = [
  5723. 'prompt' => $description,
  5724. 'ref_img_urls' => []
  5725. ];
  5726. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5727. $task_id = $task->id;
  5728. if ($task_id) {
  5729. $scene['task_id'] = $task_id;
  5730. $scene['task_status'] = 'processing';
  5731. $scenes_updated = true;
  5732. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5733. }
  5734. } catch (\Exception $e) {
  5735. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5736. }
  5737. }
  5738. }
  5739. // 如果有更新,保存到数据库
  5740. if ($roles_updated || $scenes_updated) {
  5741. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5742. if ($roles_updated) {
  5743. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5744. }
  5745. if ($scenes_updated) {
  5746. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5747. }
  5748. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5749. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5750. }
  5751. }
  5752. /**
  5753. * 根据图片URL使用AI反推图片提示词
  5754. *
  5755. * @param string $img_url 图片URL
  5756. * @return string 反推的提示词
  5757. */
  5758. private function generateImagePromptFromUrl($img_url) {
  5759. try {
  5760. // 获取默认模型
  5761. $model = 'doubao-seed-2-0-mini-260215';
  5762. // 构建messages参数
  5763. $messages = [
  5764. [
  5765. 'role' => 'user',
  5766. 'content' => [
  5767. [
  5768. 'type' => 'text',
  5769. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5770. ],
  5771. [
  5772. 'type' => 'image_url',
  5773. 'image_url' => [
  5774. 'url' => $img_url
  5775. ]
  5776. ]
  5777. ]
  5778. ]
  5779. ];
  5780. // 构建请求参数
  5781. $params = [
  5782. 'model' => $model,
  5783. 'messages' => $messages,
  5784. 'stream' => false,
  5785. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5786. ];
  5787. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5788. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5789. // 仅记录 token 使用明细(不扣积分)
  5790. $uid = 0;
  5791. try {
  5792. $uid = (int)Site::getUid();
  5793. } catch (\Throwable $e) {
  5794. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5795. }
  5796. $this->pointsService->recordTokenOnlyDetail(
  5797. $uid,
  5798. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5799. [
  5800. 'model' => $model,
  5801. 'img_url' => $img_url,
  5802. 'source' => 'generateImagePromptFromUrl',
  5803. ],
  5804. 'chat',
  5805. $model,
  5806. ''
  5807. );
  5808. // 返回生成的内容
  5809. return getProp($result, 'fullContent', '图片描述生成失败');
  5810. } catch (\Exception $e) {
  5811. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5812. 'img_url' => $img_url
  5813. ]);
  5814. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5815. 'error' => $e->getMessage(),
  5816. 'img_url' => $img_url
  5817. ]);
  5818. return '图片描述生成失败: ' . $e->getMessage();
  5819. }
  5820. }
  5821. /**
  5822. * 音频试听接口
  5823. * 创建音频任务并轮询获取结果
  5824. *
  5825. * @param array $data 参数数组
  5826. * @return array 返回音频URL或错误信息
  5827. */
  5828. public function previewAudio($data) {
  5829. $dialogue = getProp($data, 'dialogue');
  5830. // 必填参数验证
  5831. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5832. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5833. $voice_type = getProp($data, 'voice_type');
  5834. $voice_name = getProp($data, 'voice_name');
  5835. $voice_actor = getProp($data, 'voice_actor');
  5836. $emotion_type = getProp($data, 'emotion_type');
  5837. $gender = getProp($data, 'gender', 0);
  5838. $emotion = getProp($data, 'emotion');
  5839. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5840. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5841. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5842. $pitch = getProp($data, 'pitch', 0);
  5843. try {
  5844. $now = date('Y-m-d H:i:s');
  5845. // 构建生成参数
  5846. $generate_json = json_encode([
  5847. 'text' => $dialogue,
  5848. 'role' => $voice_actor,
  5849. 'voice_type' => $voice_type,
  5850. 'voice_name' => $voice_name,
  5851. 'emotion' => $emotion,
  5852. 'emotion_type' => $emotion_type,
  5853. 'gender' => $gender,
  5854. 'speed_ratio' => $speed_ratio,
  5855. 'loudness_ratio' => $loudness_ratio,
  5856. 'emotion_scale' => $emotion_scale,
  5857. 'pitch' => $pitch,
  5858. ], 256);
  5859. // 请求远程服务器执行生成
  5860. $client = new Client(['timeout' => 600, 'verify' => false]);
  5861. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5862. $response = $result->getBody()->getContents();
  5863. $response_arr = json_decode($response, true);
  5864. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5865. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5866. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5867. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5868. }
  5869. $arr = $response_arr['data'];
  5870. $subtitle_info = $arr['subtitle_info'];
  5871. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5872. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5873. return [
  5874. 'audio_url' => $arr['url'],
  5875. 'subtitle_info' => $subtitle_info,
  5876. 'audio_duration' => round($audio_duration, 2)
  5877. ];
  5878. } catch (\Exception $e) {
  5879. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5880. Utils::throwError('20003:' . $e->getMessage());
  5881. }
  5882. }
  5883. /**
  5884. * 获取角色库列表(支持文件夹递归查询)
  5885. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5886. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5887. */
  5888. public function globalProducts($data) {
  5889. $uid = Site::getUid();
  5890. $cpid = Site::getCpid();
  5891. $role = Site::getRole();
  5892. $id = getProp($data, 'id', 0);
  5893. $parent_id = getProp($data, 'parent_id', 0);
  5894. $product_name = getProp($data, 'product_name');
  5895. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5896. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5897. if (!$product) {
  5898. Utils::throwError('20003:请选择产品类型');
  5899. }
  5900. // 根据角色和is_public参数确定查询范围
  5901. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5902. // user角色:根据is_public参数筛选
  5903. $query_user_ids = [];
  5904. if ($role === 'admin') {
  5905. // admin获取所有个人库和公共库
  5906. $query_user_ids = [$uid, 0];
  5907. } else {
  5908. // user角色根据is_public参数筛选
  5909. if ($is_public == 2) {
  5910. // 个人库+公共库
  5911. $query_user_ids = [$uid, 0];
  5912. } elseif ($is_public == 0) {
  5913. // 仅个人库
  5914. $query_user_ids = [$uid];
  5915. } elseif ($is_public == 1) {
  5916. // 仅公共库
  5917. $query_user_ids = [0];
  5918. }
  5919. }
  5920. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5921. if ($id || $product_name) {
  5922. $query = DB::table('mp_products')
  5923. ->where('cpid', $cpid)
  5924. ->whereIn('user_id', $query_user_ids)
  5925. ->where('is_deleted', 0);
  5926. // 如果指定了 id,按 id 精确查询
  5927. if ($id) {
  5928. $query->where('id', $id);
  5929. }
  5930. // 如果指定了 product_name,按名称模糊查询
  5931. if ($product_name) {
  5932. $query->where('product_name', 'like', "%{$product_name}%");
  5933. }
  5934. // 如果指定了 product,添加筛选条件
  5935. if ($product) {
  5936. $query->where('product', $product);
  5937. }
  5938. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5939. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5940. ->get()
  5941. ->map(function($value) {
  5942. $value = (array)$value;
  5943. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5944. $value['type'] = (int)$value['type'];
  5945. $value['parent_id'] = (int)$value['parent_id'];
  5946. $value['level'] = (int)$value['level'];
  5947. $value['product'] = (int)($value['product'] ?? 1);
  5948. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5949. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5950. unset($value['user_id']);
  5951. return $value;
  5952. })
  5953. ->toArray();
  5954. return $result;
  5955. }
  5956. // 递归获取所有子目录和角色
  5957. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5958. }
  5959. /**
  5960. * 递归获取指定目录下的所有子目录和角色
  5961. * @param int $cpid 公司ID
  5962. * @param int $parent_id 父目录ID
  5963. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5964. * @param array $query_user_ids 用户ID数组(支持多个)
  5965. * @param int $current_uid 当前用户ID(用于排序)
  5966. * @return array
  5967. */
  5968. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5969. // 查询当前层级的所有项(文件夹和角色)
  5970. $query = DB::table('mp_products')
  5971. ->where('cpid', $cpid)
  5972. ->where('is_deleted', 0)
  5973. ->where('parent_id', $parent_id);
  5974. // 添加用户ID验证(支持多个user_id)
  5975. if (!empty($query_user_ids)) {
  5976. $query->whereIn('user_id', $query_user_ids);
  5977. }
  5978. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5979. if ($product) {
  5980. $query->where('product', $product);
  5981. }
  5982. // 排序规则:
  5983. // 1. 文件夹在前(type DESC)
  5984. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5985. // 3. 其他排序规则
  5986. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5987. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5988. ->get();
  5989. $result = [];
  5990. foreach ($items as $item) {
  5991. $itemArray = [
  5992. 'id' => $item->id,
  5993. 'type' => (int)$item->type,
  5994. 'parent_id' => (int)$item->parent_id,
  5995. 'level' => (int)$item->level,
  5996. 'product_name' => $item->product_name,
  5997. 'url' => $item->url,
  5998. 'pic_prompt' => $item->pic_prompt ?? '',
  5999. 'three_view_image_url' => $item->three_view_image_url,
  6000. 'product' => (int)($item->product ?? 1),
  6001. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  6002. 'created_at' => transDate($item->created_at, 'Y-m-d')
  6003. ];
  6004. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  6005. // 如果是文件夹,递归获取其子项
  6006. if ($item->type == 2) {
  6007. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  6008. if (!empty($children)) {
  6009. $itemArray['children'] = $children;
  6010. }
  6011. }
  6012. $result[] = $itemArray;
  6013. }
  6014. return $result;
  6015. }
  6016. /**
  6017. * 创建文件夹
  6018. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  6019. * @return int 返回新建文件夹ID
  6020. */
  6021. public function createFolder($data) {
  6022. $uid = Site::getUid();
  6023. $cpid = Site::getCpid();
  6024. $role = Site::getRole();
  6025. $parent_id = getProp($data, 'parent_id', 0);
  6026. $folder_name = getProp($data, 'product_name', '新建文件夹');
  6027. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6028. // 如果是公共库操作,需要admin权限
  6029. if ($is_public && $role !== 'admin') {
  6030. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6031. }
  6032. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6033. $store_uid = $is_public ? 0 : $uid;
  6034. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6035. $product = getProp($data, 'product');
  6036. if (!in_array($product, [1, 2, 3])) {
  6037. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  6038. }
  6039. // 验证父文件夹
  6040. $parent_level = 0;
  6041. if ($parent_id > 0) {
  6042. $parent = DB::table('mp_products')
  6043. ->where('id', $parent_id)
  6044. ->where('cpid', $cpid)
  6045. ->where('user_id', $store_uid)
  6046. ->where('type', 2)
  6047. ->where('is_deleted', 0)
  6048. ->first();
  6049. if (!$parent) {
  6050. Utils::throwError('20003:父文件夹不存在');
  6051. }
  6052. // 检查父文件夹的 product 类型是否一致
  6053. if ($parent->product != $product) {
  6054. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  6055. }
  6056. $parent_level = $parent->level;
  6057. // 检查层级限制(最多3层)
  6058. if ($parent_level >= 3) {
  6059. Utils::throwError('20003:文件夹层级不能超过3层');
  6060. }
  6061. }
  6062. // 检查当前目录下是否已存在空白文件夹
  6063. $empty_folder_exists = DB::table('mp_products')
  6064. ->where('parent_id', $parent_id)
  6065. ->where('cpid', $cpid)
  6066. ->where('user_id', $store_uid)
  6067. ->where('type', 2)
  6068. ->where('product', $product)
  6069. ->where('product_name', '新建文件夹')
  6070. ->where('is_deleted', 0)
  6071. ->exists();
  6072. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  6073. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  6074. }
  6075. // 创建文件夹
  6076. $folder_id = DB::table('mp_products')->insertGetId([
  6077. 'user_id' => $store_uid,
  6078. 'cpid' => $cpid,
  6079. 'type' => 2,
  6080. 'parent_id' => $parent_id,
  6081. 'level' => $parent_level + 1,
  6082. 'product_name' => $folder_name,
  6083. 'product' => $product,
  6084. 'sort_order' => time(), // 使用时间戳作为排序权重
  6085. 'is_deleted' => 0,
  6086. 'created_at' => date('Y-m-d H:i:s'),
  6087. 'updated_at' => date('Y-m-d H:i:s')
  6088. ]);
  6089. return [
  6090. 'id' => $folder_id,
  6091. 'type' => 2,
  6092. 'parent_id' => $parent_id,
  6093. 'level' => $parent_level + 1,
  6094. 'product_name' => $folder_name,
  6095. 'product' => $product,
  6096. ];
  6097. }
  6098. /**
  6099. * 重命名文件夹或角色
  6100. * @param array $data 包含 id、product_name(新名称)
  6101. * @return bool
  6102. */
  6103. public function renameFolder($data) {
  6104. $uid = Site::getUid();
  6105. $cpid = Site::getCpid();
  6106. $role = Site::getRole();
  6107. $id = getProp($data, 'id');
  6108. $new_name = getProp($data, 'product_name');
  6109. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6110. if (!$id || !$new_name) {
  6111. Utils::throwError('20003:参数不完整');
  6112. }
  6113. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6114. $query_uid = $is_public ? 0 : $uid;
  6115. // 如果是公共库操作,需要admin权限
  6116. if ($is_public && $role !== 'admin') {
  6117. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6118. }
  6119. // 检查是否存在
  6120. $item = DB::table('mp_products')
  6121. ->where('id', $id)
  6122. ->where('cpid', $cpid)
  6123. ->where('user_id', $query_uid)
  6124. ->where('is_deleted', 0)
  6125. ->first();
  6126. if (!$item) {
  6127. Utils::throwError('20003:项目不存在');
  6128. }
  6129. return DB::table('mp_products')
  6130. ->where('id', $id)
  6131. ->where('cpid', $cpid)
  6132. ->where('user_id', $query_uid)
  6133. ->update([
  6134. 'product_name' => $new_name,
  6135. 'updated_at' => date('Y-m-d H:i:s')
  6136. ]);
  6137. }
  6138. /**
  6139. * 移动角色或文件夹到指定文件夹
  6140. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6141. * @return bool
  6142. */
  6143. public function moveProductOrFolder($data) {
  6144. $uid = Site::getUid();
  6145. $cpid = Site::getCpid();
  6146. $role = Site::getRole();
  6147. $id = getProp($data, 'id');
  6148. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6149. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6150. if (!$id) {
  6151. Utils::throwError('20003:请选择要移动的项目');
  6152. }
  6153. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6154. $query_uid = $is_public ? 0 : $uid;
  6155. // 如果是公共库操作,需要admin权限
  6156. if ($is_public && $role !== 'admin') {
  6157. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6158. }
  6159. // 检查要移动的项目
  6160. $item = DB::table('mp_products')
  6161. ->where('id', $id)
  6162. ->where('cpid', $cpid)
  6163. ->where('user_id', $query_uid)
  6164. ->where('is_deleted', 0)
  6165. ->first();
  6166. if (!$item) {
  6167. Utils::throwError('20003:项目不存在');
  6168. }
  6169. // 验证目标文件夹
  6170. $target_level = 0;
  6171. $target_product = $item->product; // 默认使用当前项目的 product
  6172. if ($target_parent_id > 0) {
  6173. $target_parent = DB::table('mp_products')
  6174. ->where('id', $target_parent_id)
  6175. ->where('cpid', $cpid)
  6176. ->where('user_id', $query_uid)
  6177. ->where('type', 2)
  6178. ->where('is_deleted', 0)
  6179. ->first();
  6180. if (!$target_parent) {
  6181. Utils::throwError('20003:目标文件夹不存在');
  6182. }
  6183. // 检查 product 类型是否一致
  6184. if ($target_parent->product != $item->product) {
  6185. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6186. }
  6187. $target_level = $target_parent->level;
  6188. $target_product = $target_parent->product;
  6189. // 如果移动的是文件夹,需要检查层级
  6190. if ($item->type == 2) {
  6191. // 计算移动后的最大层级
  6192. $max_child_level = $this->getMaxChildLevel($id);
  6193. $depth = $max_child_level - $item->level;
  6194. if ($target_level + 1 + $depth > 3) {
  6195. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6196. }
  6197. // 不能移动到自己或自己的子文件夹下
  6198. if ($this->isDescendant($target_parent_id, $id)) {
  6199. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6200. }
  6201. }
  6202. }
  6203. // 更新父文件夹和层级
  6204. $new_level = $target_level + 1;
  6205. DB::table('mp_products')
  6206. ->where('id', $id)
  6207. ->update([
  6208. 'parent_id' => $target_parent_id,
  6209. 'level' => $new_level,
  6210. 'updated_at' => date('Y-m-d H:i:s')
  6211. ]);
  6212. // 如果是文件夹,需要递归更新所有子项的层级
  6213. if ($item->type == 2) {
  6214. $this->updateChildrenLevel($id, $new_level);
  6215. }
  6216. return true;
  6217. }
  6218. /**
  6219. * 获取文件夹下最大子层级
  6220. * @param int $folder_id
  6221. * @return int
  6222. */
  6223. private function getMaxChildLevel($folder_id) {
  6224. $max_level = DB::table('mp_products')
  6225. ->where('parent_id', $folder_id)
  6226. ->where('is_deleted', 0)
  6227. ->max('level');
  6228. if (!$max_level) {
  6229. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6230. }
  6231. // 递归查找子文件夹
  6232. $children = DB::table('mp_products')
  6233. ->where('parent_id', $folder_id)
  6234. ->where('type', 2)
  6235. ->where('is_deleted', 0)
  6236. ->pluck('id');
  6237. foreach ($children as $child_id) {
  6238. $child_max = $this->getMaxChildLevel($child_id);
  6239. if ($child_max > $max_level) {
  6240. $max_level = $child_max;
  6241. }
  6242. }
  6243. return $max_level;
  6244. }
  6245. /**
  6246. * 检查 target_id 是否是 folder_id 的后代
  6247. * @param int $target_id
  6248. * @param int $folder_id
  6249. * @return bool
  6250. */
  6251. private function isDescendant($target_id, $folder_id) {
  6252. if ($target_id == $folder_id) {
  6253. return true;
  6254. }
  6255. $parent = DB::table('mp_products')
  6256. ->where('id', $target_id)
  6257. ->where('is_deleted', 0)
  6258. ->first();
  6259. if (!$parent || $parent->parent_id == 0) {
  6260. return false;
  6261. }
  6262. return $this->isDescendant($parent->parent_id, $folder_id);
  6263. }
  6264. /**
  6265. * 递归更新子项层级
  6266. * @param int $parent_id
  6267. * @param int $parent_level
  6268. */
  6269. private function updateChildrenLevel($parent_id, $parent_level) {
  6270. $children = DB::table('mp_products')
  6271. ->where('parent_id', $parent_id)
  6272. ->where('is_deleted', 0)
  6273. ->get();
  6274. foreach ($children as $child) {
  6275. $new_level = $parent_level + 1;
  6276. DB::table('mp_products')
  6277. ->where('id', $child->id)
  6278. ->update([
  6279. 'level' => $new_level,
  6280. 'updated_at' => date('Y-m-d H:i:s')
  6281. ]);
  6282. // 如果是文件夹,继续递归
  6283. if ($child->type == 2) {
  6284. $this->updateChildrenLevel($child->id, $new_level);
  6285. }
  6286. }
  6287. }
  6288. /**
  6289. * 获取文件夹路径(面包屑导航)
  6290. * @param array $data 包含 folder_id
  6291. * @return array 返回路径数组
  6292. */
  6293. public function getFolderPath($data) {
  6294. $uid = Site::getUid();
  6295. $cpid = Site::getCpid();
  6296. $folder_id = getProp($data, 'id', 0);
  6297. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6298. if ($folder_id == 0) {
  6299. return [
  6300. ['id' => 0, 'name' => '根目录']
  6301. ];
  6302. }
  6303. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6304. $query_uid = $is_public ? 0 : $uid;
  6305. $path = [];
  6306. $current_id = $folder_id;
  6307. while ($current_id > 0) {
  6308. $folder = DB::table('mp_products')
  6309. ->where('id', $current_id)
  6310. ->where('cpid', $cpid)
  6311. ->where('user_id', $query_uid)
  6312. ->where('type', 2)
  6313. ->where('is_deleted', 0)
  6314. ->first();
  6315. if (!$folder) {
  6316. break;
  6317. }
  6318. array_unshift($path, [
  6319. 'id' => $folder->id,
  6320. 'name' => $folder->product_name
  6321. ]);
  6322. $current_id = $folder->parent_id;
  6323. }
  6324. // 添加根目录
  6325. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6326. return $path;
  6327. }
  6328. public function createProduct($data) {
  6329. $uid = Site::getUid();
  6330. $cpid = Site::getCpid();
  6331. $role = Site::getRole();
  6332. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6333. // 如果是公共库操作,需要admin权限
  6334. if ($is_public && $role !== 'admin') {
  6335. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6336. }
  6337. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6338. $store_uid = $is_public ? 0 : $uid;
  6339. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6340. $script_id = (int)getProp($data, 'script_id', 0);
  6341. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6342. if ($script_id && empty($episode_numbers)) {
  6343. Utils::throwError('20003:剧集序号不能为空');
  6344. }
  6345. if (!$script_id && !empty($episode_numbers)) {
  6346. Utils::throwError('20003:请提供剧本ID');
  6347. }
  6348. $product_name = trim(getProp($data, 'product_name'));
  6349. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6350. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6351. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6352. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6353. $url = trim(getProp($data, 'url'));
  6354. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6355. $versions = getProp($data, 'versions');
  6356. // 检查是否是正确的图片格式
  6357. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6358. $urlPath = parse_url($url, PHP_URL_PATH);
  6359. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6360. if (!in_array($extension, $allowedExtensions)) {
  6361. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6362. }
  6363. // 选填三视图图片地址,格式校验与 url 一致
  6364. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6365. if ($three_view_image_url) {
  6366. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6367. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6368. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6369. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6370. }
  6371. }
  6372. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6373. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6374. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6375. $product = getProp($data, 'product');
  6376. if (!in_array($product, [1, 2, 3])) {
  6377. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6378. }
  6379. // 获取父文件夹ID和层级
  6380. $parent_id = getProp($data, 'parent_id', 0);
  6381. $parent_level = 0;
  6382. if ($parent_id > 0) {
  6383. $parent = DB::table('mp_products')
  6384. ->where('id', $parent_id)
  6385. ->where('cpid', $cpid)
  6386. ->where('user_id', $store_uid)
  6387. ->where('type', 2)
  6388. ->where('is_deleted', 0)
  6389. ->first();
  6390. if (!$parent) {
  6391. Utils::throwError('20003:父文件夹不存在');
  6392. }
  6393. $parent_level = $parent->level;
  6394. }
  6395. // 创建资产并保存剧本资产关联关系(同一事务)
  6396. DB::beginTransaction();
  6397. try {
  6398. $id = DB::table('mp_products')->insertGetId([
  6399. 'user_id' => $store_uid,
  6400. 'cpid' => $cpid,
  6401. 'type' => 1, // 1=角色图片
  6402. 'parent_id' => $parent_id,
  6403. 'level' => $parent_level + 1,
  6404. 'product_name' => $product_name,
  6405. 'url' => $url,
  6406. 'three_view_image_url' => $three_view_image_url,
  6407. 'pic_prompt' => $pic_prompt,
  6408. 'product' => $product,
  6409. 'versions' => json_encode($versions, 256),
  6410. 'sort_order' => time(), // 使用时间戳作为排序权重
  6411. 'created_at' => date('Y-m-d H:i:s'),
  6412. 'updated_at' => date('Y-m-d H:i:s')
  6413. ]);
  6414. if (!$id) Utils::throwError('20003:创建失败');
  6415. // 保存剧本资产关联关系
  6416. if ($script_id) {
  6417. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6418. }
  6419. DB::commit();
  6420. } catch (\Exception $e) {
  6421. DB::rollback();
  6422. throw $e;
  6423. }
  6424. return [
  6425. 'id' => $id,
  6426. 'type' => 1,
  6427. 'parent_id' => $parent_id,
  6428. 'level' => $parent_level + 1,
  6429. 'product_name' => $product_name,
  6430. 'url' => $url,
  6431. 'three_view_image_url' => $three_view_image_url,
  6432. 'pic_prompt' => $pic_prompt,
  6433. 'product' => $product,
  6434. 'versions' => $versions
  6435. ];
  6436. }
  6437. public function editProduct($data) {
  6438. $uid = Site::getUid();
  6439. $cpid = Site::getCpid();
  6440. $role = Site::getRole();
  6441. $id = getProp($data, 'id');
  6442. if (!$id) Utils::throwError('20003:ID不能为空');
  6443. $versions = getProp($data, 'versions');
  6444. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6445. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6446. $script_id = (int)getProp($data, 'script_id', 0);
  6447. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6448. if ($script_id && empty($episode_numbers)) {
  6449. Utils::throwError('20003:剧集序号不能为空');
  6450. }
  6451. if (!$script_id && !empty($episode_numbers)) {
  6452. Utils::throwError('20003:请提供剧本ID');
  6453. }
  6454. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6455. $query_uid = $is_public ? 0 : $uid;
  6456. // 如果是公共库操作,需要admin权限
  6457. if ($is_public && $role !== 'admin') {
  6458. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6459. }
  6460. // 检查是否存在且属于当前用户或公共库
  6461. $role = DB::table('mp_products')
  6462. ->where('id', $id)
  6463. ->where('cpid', $cpid)
  6464. ->where('user_id', $query_uid)
  6465. ->where('type', 1)->first();
  6466. if (!$role) Utils::throwError('20003:记录不存在');
  6467. $updateData = [];
  6468. // $needVersionRecord = false; // 是否需要记录版本
  6469. // 名称
  6470. $product_name = trim(getProp($data, 'product_name'));
  6471. if ($product_name) {
  6472. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6473. $updateData['product_name'] = $product_name;
  6474. }
  6475. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6476. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6477. // 图片地址
  6478. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6479. $url = trim(getProp($data, 'url'));
  6480. if ($url) {
  6481. // 检查是否是正确的图片格式
  6482. $urlPath = parse_url($url, PHP_URL_PATH);
  6483. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6484. if (!in_array($extension, $allowedExtensions)) {
  6485. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6486. }
  6487. // // 如果 url 有变更,记录版本
  6488. // if ($url !== $role->url) {
  6489. // $needVersionRecord = true;
  6490. // }
  6491. $updateData['url'] = $url;
  6492. }
  6493. // 三视图图片地址(选填),格式校验与 url 一致
  6494. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6495. if ($three_view_image_url) {
  6496. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6497. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6498. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6499. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6500. }
  6501. $updateData['three_view_image_url'] = $three_view_image_url;
  6502. }
  6503. // 提示词
  6504. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6505. if ($pic_prompt) {
  6506. // // 如果 pic_prompt 有变更,记录版本
  6507. // if ($pic_prompt !== $role->pic_prompt) {
  6508. // $needVersionRecord = true;
  6509. // }
  6510. $updateData['pic_prompt'] = $pic_prompt;
  6511. }
  6512. if (empty($updateData) && !$script_id) {
  6513. Utils::throwError('20003:没有需要更新的数据');
  6514. }
  6515. // // 如果需要记录版本,将数据添加到 versions 数组
  6516. // if ($needVersionRecord) {
  6517. // // 获取现有的 versions 数据
  6518. // $versions = json_decode($role->versions, true) ?: [];
  6519. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6520. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6521. // if ($isFirstVersion) {
  6522. // $oldVersion = [
  6523. // 'url' => $role->url,
  6524. // 'description' => $role->pic_prompt,
  6525. // ];
  6526. // // 旧版本添加到数组末尾
  6527. // $versions[] = $oldVersion;
  6528. // }
  6529. // // 构建新版本(变更后)
  6530. // $newVersion = [
  6531. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6532. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6533. // ];
  6534. // // 检查新版本是否已存在于历史版本中
  6535. // $existingIndex = -1;
  6536. // foreach ($versions as $index => $version) {
  6537. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6538. // $existingIndex = $index;
  6539. // break;
  6540. // }
  6541. // }
  6542. // if ($existingIndex !== -1) {
  6543. // // 如果已存在,移除旧的位置
  6544. // array_splice($versions, $existingIndex, 1);
  6545. // }
  6546. // // 新版本添加到数组开头(最新的在前)
  6547. // array_unshift($versions, $newVersion);
  6548. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6549. // // if (count($versions) > 10) {
  6550. // // $versions = array_slice($versions, 0, 10);
  6551. // // }
  6552. // $updateData['versions'] = json_encode($versions, 256);
  6553. // }
  6554. if ($versions) {
  6555. $updateData['versions'] = json_encode($versions, 256);
  6556. }
  6557. if (!empty($updateData)) {
  6558. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6559. }
  6560. // 更新资产并保存剧本资产关联关系(同一事务)
  6561. DB::beginTransaction();
  6562. try {
  6563. $updated = true;
  6564. if (!empty($updateData)) {
  6565. $updated = DB::table('mp_products')
  6566. ->where('cpid', $cpid)
  6567. ->where('id', $id)
  6568. ->update($updateData);
  6569. }
  6570. // 保存剧本资产关联关系
  6571. if ($script_id) {
  6572. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6573. }
  6574. DB::commit();
  6575. } catch (\Exception $e) {
  6576. DB::rollback();
  6577. throw $e;
  6578. }
  6579. return $updated;
  6580. }
  6581. /**
  6582. * 保存单一资产与剧本剧集的关联关系
  6583. *
  6584. * @param int $product_id 资产ID
  6585. * @param int $script_id 剧本ID
  6586. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6587. * @return int 新增关联数量
  6588. */
  6589. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6590. $uid = Site::getUid();
  6591. // 验证剧本是否存在
  6592. $script = DB::table('mp_scripts')
  6593. ->where('id', $script_id)
  6594. ->where('is_deleted', 0)
  6595. ->first();
  6596. if (!$script) {
  6597. Utils::throwError('20003:剧本不存在');
  6598. }
  6599. // 验证剧本归属:只能关联自己的剧本
  6600. if ((int)$script->user_id !== (int)$uid) {
  6601. Utils::throwError('20003:只能添加到自己的剧本');
  6602. }
  6603. // 使用 splitContent 拆分剧本内容获取总集数
  6604. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6605. // 解析剧集序号(数组)
  6606. $episodes = [];
  6607. foreach ($episode_numbers as $item) {
  6608. if (is_array($item)) {
  6609. continue;
  6610. }
  6611. $item = trim((string)$item);
  6612. if ($item === '' || !is_numeric($item)) {
  6613. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6614. }
  6615. $episodes[] = (int)$item;
  6616. }
  6617. // 去重并校验序号范围(序号从1开始)
  6618. $episodes = array_values(array_unique($episodes));
  6619. if (empty($episodes)) {
  6620. Utils::throwError('20003:剧集序号不能为空');
  6621. }
  6622. foreach ($episodes as $episode) {
  6623. if ($episode < 1 || $episode > $totalEpisodes) {
  6624. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6625. }
  6626. }
  6627. $now = now();
  6628. // 过滤已存在的关联,避免重复
  6629. $existingEpisodes = DB::table('mp_script_product_mappings')
  6630. ->where('script_id', $script_id)
  6631. ->where('product_id', $product_id)
  6632. ->whereIn('episode_number', $episodes)
  6633. ->pluck('episode_number')
  6634. ->all();
  6635. $mappingRecords = [];
  6636. foreach ($episodes as $episode) {
  6637. if (in_array($episode, $existingEpisodes)) {
  6638. continue;
  6639. }
  6640. $mappingRecords[] = [
  6641. 'script_id' => $script_id,
  6642. 'product_id' => $product_id,
  6643. 'episode_number' => $episode,
  6644. 'created_at' => $now,
  6645. 'updated_at' => $now,
  6646. ];
  6647. }
  6648. $insertedCount = 0;
  6649. if (!empty($mappingRecords)) {
  6650. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6651. }
  6652. return $insertedCount;
  6653. }
  6654. /**
  6655. * 规范化剧集序号参数,统一为数组
  6656. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6657. *
  6658. * @param mixed $episode_number 剧集序号参数
  6659. * @return array
  6660. */
  6661. private function normalizeEpisodeNumbers($episode_number) {
  6662. if (!is_array($episode_number)) {
  6663. $episode_number = explode(',', (string)$episode_number);
  6664. }
  6665. $items = [];
  6666. foreach ($episode_number as $item) {
  6667. if (is_array($item)) {
  6668. continue;
  6669. }
  6670. foreach (explode(',', (string)$item) as $part) {
  6671. $part = trim($part);
  6672. if ($part !== '') {
  6673. $items[] = $part;
  6674. }
  6675. }
  6676. }
  6677. return $items;
  6678. }
  6679. /**
  6680. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6681. *
  6682. * @param object $script 剧本记录
  6683. * @return int 总集数
  6684. */
  6685. private function getScriptTotalEpisodeCount($script) {
  6686. if (empty($script->content)) {
  6687. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6688. }
  6689. $totalEpisodes = count(splitContent($script->content));
  6690. if ($totalEpisodes < 1) {
  6691. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6692. }
  6693. return $totalEpisodes;
  6694. }
  6695. /**
  6696. * 获取剧本总集数
  6697. *
  6698. * @param array $data 包含 script_id(剧本ID)
  6699. * @return array
  6700. */
  6701. public function getScriptTotalEpisodes($data) {
  6702. $script_id = (int)getProp($data, 'script_id', 0);
  6703. if (!$script_id) {
  6704. Utils::throwError('20003:请提供剧本ID');
  6705. }
  6706. // 验证剧本是否存在
  6707. $script = DB::table('mp_scripts')
  6708. ->where('id', $script_id)
  6709. ->where('is_deleted', 0)
  6710. ->first();
  6711. if (!$script) {
  6712. Utils::throwError('20003:剧本不存在');
  6713. }
  6714. return [
  6715. 'script_id' => $script_id,
  6716. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6717. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6718. ];
  6719. }
  6720. /**
  6721. * 获取角色版本历史
  6722. * @param array $data 包含 id(角色ID)
  6723. * @return array 返回版本历史列表
  6724. */
  6725. public function getProductVersions($data) {
  6726. $cpid = Site::getCpid();
  6727. $id = getProp($data, 'id');
  6728. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6729. $role = DB::table('mp_products')
  6730. ->where('id', $id)
  6731. ->where('cpid', $cpid)
  6732. ->where('type', 1)
  6733. ->first();
  6734. if (!$role) Utils::throwError('20003:角色不存在');
  6735. // 获取版本历史
  6736. $versions = json_decode($role->versions, true) ?: [];
  6737. // 添加当前版本作为最新版本
  6738. $currentVersion = [
  6739. 'version' => 0, // 0 表示当前版本
  6740. 'url' => $role->url,
  6741. 'pic_prompt' => $role->pic_prompt,
  6742. 'updated_at' => $role->updated_at,
  6743. 'is_current' => true
  6744. ];
  6745. array_unshift($versions, $currentVersion);
  6746. return $versions;
  6747. }
  6748. /**
  6749. * 恢复到指定版本
  6750. * @param array $data 包含 id(角色ID)、version(版本号)
  6751. * @return bool
  6752. */
  6753. public function restoreProductVersion($data) {
  6754. $uid = Site::getUid();
  6755. $cpid = Site::getCpid();
  6756. $id = getProp($data, 'id');
  6757. $version = getProp($data, 'version');
  6758. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6759. if (!$version) Utils::throwError('20003:版本号不能为空');
  6760. $role = DB::table('mp_products')
  6761. ->where('id', $id)
  6762. ->where('cpid', $cpid)
  6763. ->where('type', 1)
  6764. ->first();
  6765. if (!$role) Utils::throwError('20003:角色不存在');
  6766. // 获取版本历史
  6767. $versions = json_decode($role->versions, true) ?: [];
  6768. // 查找指定版本
  6769. $targetVersion = null;
  6770. foreach ($versions as $v) {
  6771. if ($v['version'] == $version) {
  6772. $targetVersion = $v;
  6773. break;
  6774. }
  6775. }
  6776. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6777. // 先将当前版本保存到历史
  6778. $newVersion = [
  6779. 'version' => count($versions) + 1,
  6780. 'url' => $role->url,
  6781. 'pic_prompt' => $role->pic_prompt,
  6782. 'updated_at' => date('Y-m-d H:i:s'),
  6783. 'updated_by' => $uid
  6784. ];
  6785. array_unshift($versions, $newVersion);
  6786. // 限制版本数量
  6787. if (count($versions) > 10) {
  6788. $versions = array_slice($versions, 0, 10);
  6789. }
  6790. // 恢复到指定版本
  6791. return DB::table('mp_products')
  6792. ->where('id', $id)
  6793. ->where('cpid', $cpid)
  6794. ->update([
  6795. 'url' => $targetVersion['url'],
  6796. 'pic_prompt' => $targetVersion['pic_prompt'],
  6797. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6798. 'updated_at' => date('Y-m-d H:i:s')
  6799. ]);
  6800. }
  6801. public function deleteProduct($data) {
  6802. $uid = Site::getUid();
  6803. $cpid = Site::getCpid();
  6804. $role = Site::getRole();
  6805. $id = getProp($data, 'id');
  6806. if (!$id) Utils::throwError('20003:ID不能为空');
  6807. $ids = explode(',', $id);
  6808. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6809. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6810. $query_uid = $is_public ? 0 : $uid;
  6811. // 如果是公共库操作,需要admin权限
  6812. if ($is_public && $role !== 'admin') {
  6813. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6814. }
  6815. // 检查是否存在且属于当前用户或公共库
  6816. $role = DB::table('mp_products')
  6817. ->whereIn('id', $ids)
  6818. ->where('cpid', $cpid)
  6819. ->where('user_id', $query_uid)
  6820. ->get();
  6821. if (!$role) Utils::throwError('20003:记录不存在');
  6822. return DB::table('mp_products')
  6823. ->where('cpid', $cpid)
  6824. ->where('user_id', $query_uid)
  6825. ->whereIn('id', $ids)
  6826. ->update([
  6827. 'is_deleted' => 1,
  6828. 'updated_at' => date('Y-m-d H:i:s')
  6829. ]);
  6830. }
  6831. public function generateThreeView($data) {
  6832. $uid = Site::getUid();
  6833. $cpid = Site::getCpid();
  6834. $role = Site::getRole();
  6835. $id = getProp($data, 'id');
  6836. if (!$id) Utils::throwError('20003:ID不能为空');
  6837. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6838. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6839. $query_uid = $is_public ? 0 : $uid;
  6840. // 如果是公共库操作,需要admin权限
  6841. if ($is_public && $role !== 'admin') {
  6842. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6843. }
  6844. // 检查是否存在且属于当前用户或公共库
  6845. $product = DB::table('mp_products')
  6846. ->where('id', $id)
  6847. ->where('cpid', $cpid)
  6848. ->where('user_id', $query_uid)
  6849. ->where('type', 1)->first();
  6850. if (!$product) Utils::throwError('20003:资产不存在');
  6851. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6852. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6853. if (!$ref_img_url) {
  6854. // 如果没有传入参考图,使用角色表中的图片
  6855. $ref_img_url = $product->url ?? '';
  6856. if (!$ref_img_url) {
  6857. Utils::throwError('20003:参考图不能为空');
  6858. }
  6859. }
  6860. $pic_prompt = getProp($product, 'pic_prompt');
  6861. if ($pic_prompt) {
  6862. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6863. }
  6864. // 检查参考图是否是正确的图片格式
  6865. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6866. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6867. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6868. if (!in_array($extension, $allowedExtensions)) {
  6869. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6870. }
  6871. // 处理图片模型
  6872. $model = getProp($data, 'model');
  6873. if (!$model) {
  6874. // 使用默认模型
  6875. $model = 'doubao-seedream-5-0-lite-260128';
  6876. }
  6877. // 验证模型是否在可用模型表中
  6878. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6879. Utils::throwError('20003:该模型已不可用,请更换!');
  6880. }
  6881. $ratio = getProp($data, 'ratio', '16:9');
  6882. $resolution = getProp($data, 'resolution', '2k');
  6883. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  6884. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  6885. // 参数验证
  6886. $resolution = strtolower($resolution);
  6887. if (!isset($sizeMap[$resolution])) {
  6888. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6889. }
  6890. if (!isset($sizeMap[$resolution][$ratio])) {
  6891. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6892. }
  6893. // 根据 ratio 和 resolution 确定宽高
  6894. $width = $sizeMap[$resolution][$ratio]['width'];
  6895. $height = $sizeMap[$resolution][$ratio]['height'];
  6896. try {
  6897. // 创建图片生成任务
  6898. $params = [
  6899. 'prompt' => $prompt,
  6900. 'model' => $model,
  6901. 'ref_img_urls' => [$ref_img_url],
  6902. 'width' => $width,
  6903. 'height' => $height
  6904. ];
  6905. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6906. $task_id = $task->id;
  6907. if (!$task_id) {
  6908. Utils::throwError('20003:创建图片生成任务失败');
  6909. }
  6910. // 轮询获取结果
  6911. // 只查询数据库,不调用API,不更新任务表
  6912. $start_time = time();
  6913. $timeout = 1800;
  6914. $img_url = '';
  6915. while (time() - $start_time < $timeout) {
  6916. sleep(5);
  6917. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6918. $task = DB::table('mp_generate_pic_tasks')
  6919. ->where('id', $task_id)
  6920. ->first();
  6921. if (!$task) {
  6922. Utils::throwError('20003:任务不存在');
  6923. }
  6924. if ($task->status === 'success' && $task->result_url) {
  6925. $result_urls = is_string($task->result_url)
  6926. ? json_decode($task->result_url, true)
  6927. : $task->result_url;
  6928. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6929. break;
  6930. } elseif ($task->status === 'failed') {
  6931. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6932. }
  6933. // 其他状态继续轮询
  6934. }
  6935. if (empty($img_url)) {
  6936. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6937. }
  6938. // 更新 mp_products 表(不是任务表)
  6939. DB::table('mp_products')
  6940. ->where('id', $id)
  6941. ->where('cpid', $cpid)
  6942. ->update([
  6943. 'three_view_image_url' => $img_url,
  6944. 'updated_at' => date('Y-m-d H:i:s')
  6945. ]);
  6946. return ['three_view_image_url' => $img_url];
  6947. } catch (\Exception $e) {
  6948. dLog('anime')->error('生成三视图失败', [
  6949. 'error' => $e->getMessage()
  6950. ]);
  6951. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6952. Utils::throwError('20003:' . $e->getMessage());
  6953. }
  6954. }
  6955. /**
  6956. * 推送(复制)资产或文件夹到目标位置
  6957. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6958. * @return array 返回推送结果
  6959. */
  6960. public function pushProductOrFolder($data) {
  6961. $uid = Site::getUid();
  6962. $cpid = Site::getCpid();
  6963. $role = Site::getRole();
  6964. $product_id = getProp($data, 'product_id');
  6965. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6966. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6967. if (!$product_id) {
  6968. Utils::throwError('20003:请选择要推送的项目');
  6969. }
  6970. // 查询源项目(只通过cpid查询,不限制user_id)
  6971. $sourceItem = DB::table('mp_products')
  6972. ->where('id', $product_id)
  6973. ->where('cpid', $cpid)
  6974. ->where('is_deleted', 0)
  6975. ->first();
  6976. if (!$sourceItem) {
  6977. Utils::throwError('20003:要推送的项目不存在');
  6978. }
  6979. // 通过user_id判断源是公共库还是个人库
  6980. $source_uid = $sourceItem->user_id;
  6981. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6982. // 验证目标文件夹并确定目标是公共库还是个人库
  6983. $target_level = 0;
  6984. $target_uid = $uid; // 默认推送到个人库
  6985. $target_is_public = 0;
  6986. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6987. if ($target_parent_id > 0) {
  6988. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6989. $targetParent = DB::table('mp_products')
  6990. ->where('id', $target_parent_id)
  6991. ->where('cpid', $cpid)
  6992. ->where('type', 2)
  6993. ->where('is_deleted', 0)
  6994. ->first();
  6995. if (!$targetParent) {
  6996. Utils::throwError('20003:目标文件夹不存在');
  6997. }
  6998. // 通过user_id判断目标是公共库还是个人库
  6999. $target_level = $targetParent->level;
  7000. $target_uid = $targetParent->user_id;
  7001. $target_is_public = ($target_uid == 0) ? 1 : 0;
  7002. // 使用目标文件夹的 product 类型
  7003. $final_product_type = $targetParent->product;
  7004. }
  7005. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  7006. else {
  7007. $push_to_public = getProp($data, 'push_to_public');
  7008. if ($push_to_public === '') {
  7009. Utils::throwError('20003:请选择是否推送到公共库');
  7010. }
  7011. if ($push_to_public) {
  7012. $target_uid = 0;
  7013. $target_is_public = 1;
  7014. }
  7015. // 推送到根目录时,必须指定 product 类型
  7016. if ($target_product === null || $target_product === '') {
  7017. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  7018. }
  7019. $final_product_type = $target_product;
  7020. }
  7021. // 如果目标是公共库,需要admin权限
  7022. if ($target_is_public && $role !== 'admin') {
  7023. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  7024. }
  7025. // 权限验证:验证是否符合允许的推送规则
  7026. $this->validatePushPermission($source_uid, $target_uid, $uid);
  7027. try {
  7028. DB::beginTransaction();
  7029. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  7030. if ($sourceItem->type == 1) {
  7031. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  7032. DB::commit();
  7033. return [
  7034. 'product_id' => $newId,
  7035. ];
  7036. }
  7037. // 如果是文件夹,递归复制(支持跨类型推送)
  7038. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  7039. DB::commit();
  7040. return [
  7041. 'product_id' => $newFolderId,
  7042. ];
  7043. } catch (\Exception $e) {
  7044. DB::rollBack();
  7045. dLog('anime')->error('推送失败', [
  7046. 'error' => $e->getMessage(),
  7047. 'product_id' => $product_id
  7048. ]);
  7049. Utils::throwError('20003:' . $e->getMessage());
  7050. }
  7051. }
  7052. /**
  7053. * 验证推送权限
  7054. * 允许的推送规则:
  7055. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7056. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  7057. * 3. 公共库推送给公共库(公共库 → 公共库)
  7058. *
  7059. * @param int $source_uid 源的user_id
  7060. * @param int $target_uid 目标的user_id
  7061. * @param int $current_uid 当前用户ID
  7062. * @throws \Exception
  7063. */
  7064. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  7065. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7066. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  7067. return; // 允许
  7068. }
  7069. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  7070. if ($source_uid == 0 && $target_uid == $current_uid) {
  7071. return; // 允许
  7072. }
  7073. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7074. if ($source_uid == 0 && $target_uid == 0) {
  7075. return; // 允许
  7076. }
  7077. // 其他情况都不允许
  7078. if ($source_uid != 0 && $source_uid != $current_uid) {
  7079. // 源是别人的个人库
  7080. Utils::throwError('20003:无权限访问该资产');
  7081. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7082. // 个人库推送给公共库(不允许)
  7083. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7084. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7085. // 不同用户的个人库之间推送(不允许)
  7086. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7087. } else {
  7088. // 其他未知情况
  7089. Utils::throwError('20003:不允许的推送操作');
  7090. }
  7091. }
  7092. /**
  7093. * 复制单个资产
  7094. * @param object $sourceProduct 源资产对象
  7095. * @param int $targetParentId 目标父文件夹ID
  7096. * @param int $targetLevel 目标层级
  7097. * @param int $cpid 公司ID
  7098. * @param int $targetUid 目标用户ID
  7099. * @return int 返回新资产ID
  7100. */
  7101. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7102. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7103. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7104. $newProductData = [
  7105. 'user_id' => $targetUid,
  7106. 'cpid' => $cpid,
  7107. 'type' => 1,
  7108. 'parent_id' => $targetParentId,
  7109. 'level' => $targetLevel,
  7110. 'product_name' => $sourceProduct->product_name,
  7111. 'url' => $sourceProduct->url,
  7112. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7113. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7114. 'product' => $finalProductType,
  7115. 'versions' => $sourceProduct->versions ?? '',
  7116. 'sort_order' => time(),
  7117. 'is_deleted' => 0,
  7118. 'created_at' => date('Y-m-d H:i:s'),
  7119. 'updated_at' => date('Y-m-d H:i:s')
  7120. ];
  7121. return DB::table('mp_products')->insertGetId($newProductData);
  7122. }
  7123. /**
  7124. * 递归复制文件夹及其子项
  7125. * @param object $sourceFolder 源文件夹对象
  7126. * @param int $targetParentId 目标父文件夹ID
  7127. * @param int $targetLevel 目标层级
  7128. * @param int $cpid 公司ID
  7129. * @param int $targetUid 目标用户ID
  7130. * @param int $sourceUid 源用户ID
  7131. * @return int 返回新文件夹ID
  7132. */
  7133. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7134. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7135. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7136. // 创建新文件夹
  7137. $newFolderData = [
  7138. 'user_id' => $targetUid,
  7139. 'cpid' => $cpid,
  7140. 'type' => 2,
  7141. 'parent_id' => $targetParentId,
  7142. 'level' => $targetLevel,
  7143. 'product_name' => $sourceFolder->product_name,
  7144. 'product' => $finalProductType,
  7145. 'sort_order' => time(),
  7146. 'is_deleted' => 0,
  7147. 'created_at' => date('Y-m-d H:i:s'),
  7148. 'updated_at' => date('Y-m-d H:i:s')
  7149. ];
  7150. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7151. // 获取源文件夹下的所有子项
  7152. $children = DB::table('mp_products')
  7153. ->where('parent_id', $sourceFolder->id)
  7154. ->where('cpid', $cpid)
  7155. ->where('user_id', $sourceUid)
  7156. ->where('is_deleted', 0)
  7157. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7158. ->get();
  7159. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7160. foreach ($children as $child) {
  7161. if ($child->type == 1) {
  7162. // 资产
  7163. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7164. } else {
  7165. // 文件夹
  7166. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7167. }
  7168. }
  7169. return $newFolderId;
  7170. }
  7171. /**
  7172. * 转让剧本归属(剧本及其关联资产)
  7173. *
  7174. * 仅调整 mp_scripts.user_id 与 mp_products.user_id,其他表保持不变。
  7175. * 权限:仅 admin / superadmin 可操作;目标用户必须是同组(cpid 相同)且角色为 user(组员)的用户,禁止跨组转让。
  7176. * 多个剧本逐个独立事务处理,单个剧本失败不影响其他剧本;
  7177. * 单个剧本内的剧本记录与关联资产必须全部更新成功,否则整体回滚。
  7178. *
  7179. * @param array $data 请求参数:script_ids(数组或英文逗号分隔,兼容单个 script_id)、target_user_id
  7180. * @return array
  7181. */
  7182. public function transferScriptOwner($data) {
  7183. $operatorRole = Site::getRole();
  7184. $operatorCpid = Site::getCpid();
  7185. // 1.权限校验:仅管理员和超管可操作
  7186. if (!in_array($operatorRole, ['admin', 'superadmin'], true)) {
  7187. Utils::throwError(ErrorConst::NOT_ACCESS);
  7188. }
  7189. // 2.目标用户校验:必须存在且角色为 user(组员)
  7190. $targetUserId = (int)getProp($data, 'target_user_id', 0);
  7191. if ($targetUserId < 1) {
  7192. Utils::throwError('1002:请选择转让的目标用户');
  7193. }
  7194. $targetUser = DB::table('mp_manage_users')
  7195. ->where('id', $targetUserId)
  7196. ->where('is_deleted', 0)
  7197. ->first();
  7198. if (!$targetUser) {
  7199. Utils::throwError('20003:目标用户不存在');
  7200. }
  7201. if ((string)getProp($targetUser, 'role') !== 'user') {
  7202. Utils::throwError('20003:只能转让给角色为组员(user)的用户');
  7203. }
  7204. $targetCpid = (int)getProp($targetUser, 'cpid');
  7205. // 3.规范化剧本ID列表(兼容数组、逗号分隔字符串、script_id 单值)
  7206. $rawScriptIds = getProp($data, 'script_ids');
  7207. if (empty($rawScriptIds)) {
  7208. $rawScriptIds = getProp($data, 'script_id');
  7209. }
  7210. $scriptIds = $this->normalizeIdList($rawScriptIds);
  7211. if (empty($scriptIds)) {
  7212. Utils::throwError('20003:请提供剧本ID');
  7213. }
  7214. // 预取剧本名称,便于失败结果中回显
  7215. $scriptNameMap = DB::table('mp_scripts')
  7216. ->whereIn('id', $scriptIds)
  7217. ->pluck('script_name', 'id')
  7218. ->all();
  7219. $successList = [];
  7220. $failedList = [];
  7221. // 4.逐个剧本独立事务处理,单个失败不影响其他剧本
  7222. foreach ($scriptIds as $scriptId) {
  7223. DB::beginTransaction();
  7224. try {
  7225. $successList[] = $this->transferSingleScriptOwner(
  7226. $scriptId,
  7227. $targetUserId,
  7228. $targetCpid,
  7229. $operatorRole,
  7230. $operatorCpid,
  7231. Site::getUid()
  7232. );
  7233. DB::commit();
  7234. } catch (\Throwable $e) {
  7235. DB::rollBack();
  7236. $failedList[] = [
  7237. 'script_id' => (int)$scriptId,
  7238. 'script_name' => (string)($scriptNameMap[$scriptId] ?? ''),
  7239. 'reason' => $e->getMessage() !== '' ? $e->getMessage() : '转让失败',
  7240. ];
  7241. dLog('anime')->error('剧本归属转让失败', [
  7242. 'script_id' => $scriptId,
  7243. 'target_user_id' => $targetUserId,
  7244. 'operator_uid' => Site::getUid(),
  7245. 'error' => $e->getMessage(),
  7246. ]);
  7247. }
  7248. }
  7249. return [
  7250. 'target_user_id' => $targetUserId,
  7251. 'success_count' => count($successList),
  7252. 'failed_count' => count($failedList),
  7253. 'success_list' => $successList,
  7254. 'failed_list' => $failedList,
  7255. ];
  7256. }
  7257. /**
  7258. * 单个剧本的归属转让(需在事务中调用)
  7259. *
  7260. * @param int $scriptId 剧本ID
  7261. * @param int $targetUserId 目标用户ID
  7262. * @param int $targetCpid 目标用户所属公司ID
  7263. * @param string $operatorRole 操作人角色
  7264. * @param int $operatorCpid 操作人所属公司ID
  7265. * @param int $operatorUid 操作人用户ID
  7266. * @return array
  7267. */
  7268. private function transferSingleScriptOwner($scriptId, $targetUserId, $targetCpid, $operatorRole, $operatorCpid, $operatorUid) {
  7269. $script = DB::table('mp_scripts')
  7270. ->where('id', $scriptId)
  7271. ->where('is_deleted', 0)
  7272. ->first();
  7273. if (!$script) {
  7274. Utils::throwError('20003:剧本不存在');
  7275. }
  7276. $scriptCpid = (int)getProp($script, 'cpid');
  7277. $fromUserId = (int)getProp($script, 'user_id');
  7278. // 管理员仅可操作本组剧本
  7279. if ($operatorRole !== 'superadmin' && $scriptCpid !== $operatorCpid) {
  7280. Utils::throwError(ErrorConst::NOT_ACCESS);
  7281. }
  7282. // 管理员仅可转让自己创建的剧本(超管不做此验证)
  7283. if ($operatorRole !== 'superadmin' && $fromUserId !== (int)$operatorUid) {
  7284. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7285. }
  7286. // 禁止跨组转让:目标用户必须与剧本同组
  7287. if ($targetCpid !== $scriptCpid) {
  7288. Utils::throwError('20003:不能跨组转让,目标用户与剧本不在同一组');
  7289. }
  7290. // 关联资产ID(同一资产可能关联多个剧集序号,需去重)
  7291. $productIds = $this->normalizeIdList(
  7292. DB::table('mp_script_product_mappings')
  7293. ->where('script_id', $scriptId)
  7294. ->pluck('product_id')
  7295. ->all()
  7296. );
  7297. $folderIds = [];
  7298. if (!empty($productIds)) {
  7299. $products = DB::table('mp_products')
  7300. ->whereIn('id', $productIds)
  7301. ->select('id', 'cpid', 'parent_id', 'user_id')
  7302. ->get();
  7303. // 关联资产必须全部存在,否则视为数据异常,不提交
  7304. if ($products->count() !== count($productIds)) {
  7305. Utils::throwError('20003:剧本存在已丢失的关联资产,无法完成转让');
  7306. }
  7307. foreach ($products as $product) {
  7308. // 关联资产必须与剧本同组,避免误转让跨组资产
  7309. if ((int)getProp($product, 'cpid') !== $scriptCpid) {
  7310. Utils::throwError('20003:剧本存在跨组关联资产,无法完成转让');
  7311. }
  7312. $parentId = (int)getProp($product, 'parent_id', 0);
  7313. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7314. $folderIds[] = $parentId;
  7315. }
  7316. }
  7317. // 仅转让归属于原剧本所有者的资产
  7318. $folderIds = DB::table('mp_products')
  7319. ->whereIn('id', $folderIds)
  7320. ->where('type', 2)
  7321. ->where('cpid', $scriptCpid)
  7322. ->where('user_id', $fromUserId)
  7323. ->pluck('id')
  7324. ->map('intval')
  7325. ->all();
  7326. // 管理员仅可转让自己创建的资产及其所属文件夹(超管不做此验证)
  7327. if ($operatorRole !== 'superadmin') {
  7328. foreach ($products as $product) {
  7329. if ((int)getProp($product, 'user_id') !== (int)$operatorUid) {
  7330. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7331. }
  7332. }
  7333. foreach ($products as $product) {
  7334. $parentId = (int)getProp($product, 'parent_id', 0);
  7335. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7336. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7337. }
  7338. }
  7339. }
  7340. }
  7341. $now = now();
  7342. // 5.更新剧本归属
  7343. DB::table('mp_scripts')
  7344. ->where('id', $scriptId)
  7345. ->update([
  7346. 'user_id' => $targetUserId,
  7347. 'updated_at' => $now,
  7348. ]);
  7349. // 6.更新关联资产归属
  7350. if (!empty($productIds)) {
  7351. DB::table('mp_products')
  7352. ->whereIn('id', $productIds)
  7353. ->update([
  7354. 'user_id' => $targetUserId,
  7355. 'updated_at' => $now,
  7356. ]);
  7357. }
  7358. // 7.更新资产所属的类型根文件夹归属(文件夹属于 mp_products,随资产一并转让)
  7359. if (!empty($folderIds)) {
  7360. DB::table('mp_products')
  7361. ->whereIn('id', $folderIds)
  7362. ->update([
  7363. 'user_id' => $targetUserId,
  7364. 'updated_at' => $now,
  7365. ]);
  7366. }
  7367. // 8.校验剧本与资产是否全部更新成功,任一未成功则回滚
  7368. $scriptOwner = (int)DB::table('mp_scripts')->where('id', $scriptId)->value('user_id');
  7369. if ($scriptOwner !== $targetUserId) {
  7370. Utils::throwError('20003:剧本归属更新失败');
  7371. }
  7372. if (!empty($productIds)) {
  7373. $updatedProductCount = DB::table('mp_products')
  7374. ->whereIn('id', $productIds)
  7375. ->where('user_id', $targetUserId)
  7376. ->count();
  7377. if ($updatedProductCount !== count($productIds)) {
  7378. Utils::throwError('20003:部分剧本资产转让失败,已回滚');
  7379. }
  7380. }
  7381. if (!empty($folderIds)) {
  7382. $updatedFolderCount = DB::table('mp_products')
  7383. ->whereIn('id', $folderIds)
  7384. ->where('user_id', $targetUserId)
  7385. ->count();
  7386. if ($updatedFolderCount !== count($folderIds)) {
  7387. Utils::throwError('20003:部分资产文件夹转让失败,已回滚');
  7388. }
  7389. }
  7390. return [
  7391. 'script_id' => (int)$scriptId,
  7392. 'script_name' => (string)getProp($script, 'script_name', ''),
  7393. 'from_user_id' => $fromUserId,
  7394. 'to_user_id' => $targetUserId,
  7395. 'product_count' => count($productIds),
  7396. 'folder_count' => count($folderIds),
  7397. ];
  7398. }
  7399. /**
  7400. * 规范化ID列表,兼容数组、逗号分隔字符串以及字符串数组
  7401. *
  7402. * @param mixed $ids 待处理的ID集合
  7403. * @return array 去重后的正整数ID数组
  7404. */
  7405. private function normalizeIdList($ids) {
  7406. if (!is_array($ids)) {
  7407. $ids = explode(',', (string)$ids);
  7408. }
  7409. $result = [];
  7410. foreach ($ids as $item) {
  7411. if (is_array($item)) {
  7412. continue;
  7413. }
  7414. foreach (explode(',', (string)$item) as $part) {
  7415. $part = trim($part);
  7416. if ($part !== '' && is_numeric($part) && (int)$part > 0) {
  7417. $result[] = (int)$part;
  7418. }
  7419. }
  7420. }
  7421. return array_values(array_unique($result));
  7422. }
  7423. /**
  7424. * 保存剧本资产关联关系
  7425. * @param array $data 请求参数
  7426. * @return bool
  7427. */
  7428. public function saveScriptProducts($data) {
  7429. $uid = Site::getUid();
  7430. $cpid = Site::getCpid();
  7431. $script_id = getProp($data, 'script_id');
  7432. $products = getProp($data, 'products', []);
  7433. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  7434. if (!$script_id) {
  7435. Utils::throwError('20003:请提供剧本ID');
  7436. }
  7437. // 验证剧本是否存在
  7438. $script = DB::table('mp_scripts')
  7439. ->where('id', $script_id)
  7440. ->where('is_deleted', 0)
  7441. ->first();
  7442. if (!$script) {
  7443. Utils::throwError('20003:剧本不存在');
  7444. }
  7445. // 处理图片模型
  7446. $model = getProp($data, 'model');
  7447. if (!$model) {
  7448. // 使用默认模型
  7449. $model = 'doubao-seedream-5-0-lite-260128';
  7450. }
  7451. // 验证模型是否在可用模型表中
  7452. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7453. Utils::throwError('20003:该模型已不可用,请更换!');
  7454. }
  7455. $ratio = getProp($data, 'ratio', '9:16');
  7456. $resolution = getProp($data, 'resolution', '2k');
  7457. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  7458. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7459. // 参数验证
  7460. $resolution = strtolower($resolution);
  7461. if (!isset($sizeMap[$resolution])) {
  7462. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7463. }
  7464. if (!isset($sizeMap[$resolution][$ratio])) {
  7465. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7466. }
  7467. // 根据 ratio 和 resolution 确定宽高
  7468. $width = $sizeMap[$resolution][$ratio]['width'];
  7469. $height = $sizeMap[$resolution][$ratio]['height'];
  7470. $script_name = $script->script_name ?? 'script_' . $script_id;
  7471. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  7472. $taskCenterId = $this->createScriptProductTaskCenter(
  7473. $uid,
  7474. $cpid,
  7475. $script_id,
  7476. $products,
  7477. $model,
  7478. $ratio,
  7479. $resolution,
  7480. $auto_generate_images
  7481. );
  7482. // 检查是否已经有该剧本的资产数据
  7483. $existingMappings = DB::table('mp_script_product_mappings')
  7484. ->where('script_id', $script_id)
  7485. ->get();
  7486. if ($existingMappings->isNotEmpty()) {
  7487. // 已存在资产映射,检查是否所有资产都有图片生成任务
  7488. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  7489. // 查询这些资产的图片生成任务状态
  7490. $productsWithTasks = DB::table('mp_products')
  7491. ->whereIn('id', $productIds)
  7492. ->where('is_deleted', 0)
  7493. ->get();
  7494. $productTaskMap = [];
  7495. $typeFolderIds = [];
  7496. $hasAllTasks = true;
  7497. foreach ($productsWithTasks as $product) {
  7498. // 收集类型文件夹ID
  7499. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  7500. $parentFolder = DB::table('mp_products')
  7501. ->where('id', $product->parent_id)
  7502. ->where('type', 2)
  7503. ->first();
  7504. if ($parentFolder) {
  7505. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  7506. }
  7507. }
  7508. // 检查是否有图片生成任务
  7509. if (!empty($product->pic_task_id)) {
  7510. $productTaskMap[$product->id] = $product->pic_task_id;
  7511. } else if($product->url && $product->pic_task_status == '生成成功') {
  7512. continue;
  7513. } else {
  7514. // 有资产没有图片任务
  7515. $hasAllTasks = false;
  7516. }
  7517. }
  7518. // 如果所有资产都有任务ID,直接轮询返回结果
  7519. if ($hasAllTasks && !empty($productTaskMap)) {
  7520. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  7521. 'script_id' => $script_id,
  7522. 'script_name' => $script_name,
  7523. 'product_count' => count($productTaskMap)
  7524. ]);
  7525. // 直接返回 SSE 流轮询结果
  7526. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7527. }
  7528. // 如果部分资产没有任务ID,只为这些资产创建任务
  7529. if (!$hasAllTasks && $auto_generate_images) {
  7530. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  7531. 'script_id' => $script_id,
  7532. 'script_name' => $script_name
  7533. ]);
  7534. // 开启事务
  7535. DB::beginTransaction();
  7536. try {
  7537. foreach ($productsWithTasks as $product) {
  7538. // 跳过已有任务的资产
  7539. if (!empty($product->pic_task_id)) {
  7540. continue;
  7541. }
  7542. // 跳过没有提示词的资产
  7543. if (empty($product->pic_prompt)) {
  7544. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7545. 'product_id' => $product->id,
  7546. 'product_name' => $product->product_name
  7547. ]);
  7548. continue;
  7549. }
  7550. try {
  7551. // 创建图片生成任务
  7552. $params = [
  7553. 'prompt' => $product->pic_prompt,
  7554. 'model' => $model,
  7555. 'ref_img_urls' => [],
  7556. 'width' => $width,
  7557. 'height' => $height
  7558. ];
  7559. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7560. $task_id = $task->id;
  7561. if ($task_id) {
  7562. $productTaskMap[$product->id] = $task_id;
  7563. // 在事务中更新资产表的任务ID和状态
  7564. DB::table('mp_products')
  7565. ->where('id', $product->id)
  7566. ->update([
  7567. 'pic_task_id' => $task_id,
  7568. 'pic_task_status' => '生成中',
  7569. 'updated_at' => now()
  7570. ]);
  7571. dLog('anime')->info('为已存在资产创建图片生成任务', [
  7572. 'product_id' => $product->id,
  7573. 'task_id' => $task_id
  7574. ]);
  7575. }
  7576. } catch (\Exception $e) {
  7577. dLog('anime')->error('创建资产图片生成任务失败', [
  7578. 'product_id' => $product->id,
  7579. 'error' => $e->getMessage()
  7580. ]);
  7581. // 标记为失败(仍在事务中)
  7582. DB::table('mp_products')
  7583. ->where('id', $product->id)
  7584. ->update([
  7585. 'pic_task_status' => '生成失败',
  7586. 'updated_at' => now()
  7587. ]);
  7588. }
  7589. }
  7590. // 提交事务
  7591. DB::commit();
  7592. // 如果有新创建的任务,返回 SSE 流
  7593. if (!empty($productTaskMap)) {
  7594. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7595. }
  7596. } catch (\Exception $e) {
  7597. // 回滚事务
  7598. DB::rollback();
  7599. dLog('anime')->error('为已存在资产创建图片任务失败', [
  7600. 'script_id' => $script_id,
  7601. 'error' => $e->getMessage()
  7602. ]);
  7603. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  7604. }
  7605. }
  7606. // 如果不需要生成图片,返回已存在的信息
  7607. $resultData = [
  7608. 'success' => true,
  7609. 'message' => '剧本资产已存在',
  7610. 'script_id' => $script_id,
  7611. 'script_name' => $script_name,
  7612. 'type_folder_ids' => $typeFolderIds,
  7613. 'existing_products' => count($productIds),
  7614. 'tasks_count' => count($productTaskMap),
  7615. 'task_center_id' => $taskCenterId
  7616. ];
  7617. // 接口已正常完成,更新任务中心状态和结果
  7618. if ($taskCenterId) {
  7619. $this->taskCenterService->updateTask($taskCenterId, [
  7620. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7621. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7622. 'error_message' => null
  7623. ]);
  7624. }
  7625. return $resultData;
  7626. }
  7627. // 解析 products(可能是 JSON 字符串或数组)
  7628. if (is_string($products)) {
  7629. $products = json_decode($products, true);
  7630. if (json_last_error() !== JSON_ERROR_NONE) {
  7631. Utils::throwError('20003:产品数据格式错误');
  7632. }
  7633. }
  7634. if (!is_array($products) || empty($products)) {
  7635. Utils::throwError('20003:产品数据不能为空');
  7636. }
  7637. // 以下是原有的创建逻辑...
  7638. // 开启事务
  7639. DB::beginTransaction();
  7640. try {
  7641. $now = now();
  7642. $mappingRecords = [];
  7643. $createdProductIds = []; // 记录所有创建的资产ID
  7644. // 获取剧本名称
  7645. $script_name = $script->script_name ?? 'script_' . $script_id;
  7646. // 存储每个类型的根文件夹ID
  7647. $typeFolderIds = [];
  7648. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  7649. foreach ($products as $productGroup) {
  7650. $type = getProp($productGroup, 'type');
  7651. $title = getProp($productGroup, 'title', '');
  7652. $content = getProp($productGroup, 'content', []);
  7653. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  7654. continue;
  7655. }
  7656. // 为当前类型创建根文件夹(如果还未创建)
  7657. if (!isset($typeFolderIds[$type])) {
  7658. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7659. 'user_id' => $uid,
  7660. 'cpid' => $cpid,
  7661. 'type' => 2, // 1.资产 2文件夹
  7662. 'product' => $type, // 1.主体 2.场景 3.道具
  7663. 'parent_id' => 0, // 根文件夹,parent_id=0
  7664. 'level' => 1, // 第一层级
  7665. 'product_name' => $script_name,
  7666. 'sort_order' => time() + $type,
  7667. 'is_deleted' => 0,
  7668. 'created_at' => $now,
  7669. 'updated_at' => $now
  7670. ]);
  7671. }
  7672. $folder_id = $typeFolderIds[$type];
  7673. // 获取表头(第一行)并查找关键列的位置
  7674. $headers = $content[0];
  7675. $nameColumnIndex = -1; // 资产名称列索引
  7676. $sequenceColumnIndex = -1; // 使用范围列索引
  7677. $promptColumnIndex = -1; // 参考提示词列索引
  7678. foreach ($headers as $index => $header) {
  7679. // 查找"资产名称"列
  7680. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  7681. $nameColumnIndex = $index;
  7682. }
  7683. // 查找"使用范围"列
  7684. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  7685. $sequenceColumnIndex = $index;
  7686. }
  7687. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  7688. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  7689. $promptColumnIndex = $index;
  7690. }
  7691. }
  7692. // 验证必要的列是否都找到了
  7693. if ($nameColumnIndex === -1) {
  7694. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  7695. continue;
  7696. }
  7697. if ($sequenceColumnIndex === -1) {
  7698. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  7699. continue;
  7700. }
  7701. // 跳过表头,解析每一行数据
  7702. for ($i = 1; $i < count($content); $i++) {
  7703. $row = $content[$i];
  7704. // 确保行数据有效
  7705. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  7706. continue;
  7707. }
  7708. // 根据动态查找的列索引提取数据
  7709. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  7710. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  7711. $pic_prompt = '';
  7712. // 提取参考提示词(如果找到了该列)
  7713. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  7714. $pic_prompt = trim($row[$promptColumnIndex]);
  7715. }
  7716. // 解析使用范围(逗号分隔的序号)
  7717. $sequences = [];
  7718. if (!empty($sequence_str)) {
  7719. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  7720. foreach ($sequenceParts as $part) {
  7721. if (is_numeric($part)) {
  7722. $sequences[] = (int)$part;
  7723. }
  7724. }
  7725. }
  7726. if (empty($product_name)) {
  7727. continue;
  7728. }
  7729. // 处理product_name两边的符号
  7730. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7731. // 如果名称不存在或仅剩占位符号,则跳过
  7732. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  7733. dLog('anime')->warning('资产名称无效,跳过保存', [
  7734. 'script_id' => $script_id,
  7735. 'type' => $type,
  7736. 'product_name' => $product_name
  7737. ]);
  7738. continue;
  7739. }
  7740. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  7741. $product_id = DB::table('mp_products')->insertGetId([
  7742. 'product_name' => $product_name,
  7743. 'type' => 1, // 1=资产 2.文件夹
  7744. 'product' => $type, // 1=角色, 2=场景, 3=道具
  7745. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  7746. 'level' => 2, // 第二层级
  7747. 'pic_prompt' => $pic_prompt,
  7748. 'user_id' => $uid,
  7749. 'cpid' => $cpid,
  7750. 'sort_order' => time(),
  7751. 'is_deleted' => 0,
  7752. 'created_at' => $now,
  7753. 'updated_at' => $now,
  7754. ]);
  7755. // 记录创建的资产ID
  7756. $createdProductIds[] = $product_id;
  7757. // 为每个序号创建映射记录
  7758. if (!empty($sequences)) {
  7759. foreach ($sequences as $sequence) {
  7760. $mappingRecords[] = [
  7761. 'script_id' => $script_id,
  7762. 'product_id' => $product_id,
  7763. 'episode_number' => $sequence,
  7764. 'created_at' => $now,
  7765. 'updated_at' => $now,
  7766. ];
  7767. }
  7768. } else {
  7769. // 如果没有指定序号,创建一个默认映射(序号为0)
  7770. $mappingRecords[] = [
  7771. 'script_id' => $script_id,
  7772. 'product_id' => $product_id,
  7773. 'episode_number' => 0,
  7774. 'created_at' => $now,
  7775. 'updated_at' => $now,
  7776. ];
  7777. }
  7778. }
  7779. }
  7780. if (empty($mappingRecords)) {
  7781. Utils::throwError('20003:没有有效的产品数据');
  7782. }
  7783. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7784. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7785. // 剧本已有资产,同步更新is_products标记
  7786. DB::table('mp_scripts')->where('id', $script_id)->update([
  7787. 'is_products' => 1,
  7788. 'updated_at' => $now
  7789. ]);
  7790. // 如果需要自动生成图片,在事务中创建图片生成任务
  7791. $productTaskMap = [];
  7792. if ($auto_generate_images && !empty($createdProductIds)) {
  7793. // 查询所有创建的资产
  7794. $productsToGenerate = DB::table('mp_products')
  7795. ->whereIn('id', $createdProductIds)
  7796. ->where('is_deleted', 0)
  7797. ->get();
  7798. foreach ($productsToGenerate as $product) {
  7799. if (empty($product->pic_prompt)) {
  7800. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7801. 'product_id' => $product->id,
  7802. 'product_name' => $product->product_name
  7803. ]);
  7804. continue;
  7805. }
  7806. try {
  7807. // 创建图片生成任务
  7808. $params = [
  7809. 'prompt' => $product->pic_prompt,
  7810. 'model' => $model,
  7811. 'ref_img_urls' => [],
  7812. 'width' => $width,
  7813. 'height' => $height
  7814. ];
  7815. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7816. $task_id = $task->id;
  7817. if ($task_id) {
  7818. $productTaskMap[$product->id] = $task_id;
  7819. // 在事务中更新资产表的任务ID和状态
  7820. DB::table('mp_products')
  7821. ->where('id', $product->id)
  7822. ->update([
  7823. 'pic_task_id' => $task_id,
  7824. 'pic_task_status' => '生成中',
  7825. 'updated_at' => now()
  7826. ]);
  7827. dLog('anime')->info('创建资产图片生成任务', [
  7828. 'product_id' => $product->id,
  7829. 'task_id' => $task_id
  7830. ]);
  7831. }
  7832. } catch (\Exception $e) {
  7833. dLog('anime')->error('创建资产图片生成任务失败', [
  7834. 'product_id' => $product->id,
  7835. 'error' => $e->getMessage()
  7836. ]);
  7837. // 标记为失败(仍在事务中)
  7838. DB::table('mp_products')
  7839. ->where('id', $product->id)
  7840. ->update([
  7841. 'pic_task_status' => '生成失败',
  7842. 'updated_at' => now()
  7843. ]);
  7844. }
  7845. }
  7846. }
  7847. // 提交事务
  7848. DB::commit();
  7849. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  7850. if ($auto_generate_images && !empty($productTaskMap)) {
  7851. // 返回 SSE 流(事务外轮询)
  7852. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7853. }
  7854. // 如果不需要生成图片,返回普通结果
  7855. $resultData = [
  7856. 'success' => true,
  7857. 'type_folder_ids' => $typeFolderIds,
  7858. 'inserted_count' => $insertedCount,
  7859. 'total_records' => count($mappingRecords),
  7860. 'created_products' => count($createdProductIds),
  7861. 'image_tasks_created' => count($productTaskMap),
  7862. 'task_center_id' => $taskCenterId
  7863. ];
  7864. // 接口已正常完成,更新任务中心状态和结果
  7865. if ($taskCenterId) {
  7866. $this->taskCenterService->updateTask($taskCenterId, [
  7867. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7868. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7869. 'error_message' => null
  7870. ]);
  7871. }
  7872. return $resultData;
  7873. } catch (\Exception $e) {
  7874. // 回滚事务
  7875. DB::rollback();
  7876. // 更新任务中心状态为失败
  7877. if (!empty($taskCenterId)) {
  7878. $this->taskCenterService->updateTask($taskCenterId, [
  7879. 'status' => MpTaskCenter::STATUS_FAILED,
  7880. 'error_message' => $e->getMessage()
  7881. ]);
  7882. }
  7883. // 记录错误日志
  7884. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  7885. 'script_id' => $script_id,
  7886. 'error' => $e->getMessage(),
  7887. 'trace' => $e->getTraceAsString()
  7888. ]);
  7889. // 统一使用 Utils::throwError 抛出错误
  7890. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  7891. }
  7892. }
  7893. /**
  7894. * 根据入参创建或复用任务中心记录
  7895. *
  7896. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  7897. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  7898. * 避免生成重复任务。
  7899. *
  7900. * @param int|string $uid
  7901. * @param int|string $cpid
  7902. * @param int|string $script_id
  7903. * @param mixed $products
  7904. * @param string $model
  7905. * @param string $ratio
  7906. * @param string $resolution
  7907. * @param mixed $auto_generate_images
  7908. * @return int 任务中心ID
  7909. */
  7910. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  7911. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  7912. if (is_string($products)) {
  7913. $decoded = json_decode($products, true);
  7914. if (json_last_error() === JSON_ERROR_NONE) {
  7915. $products = $decoded;
  7916. }
  7917. }
  7918. $params = [
  7919. 'script_id' => (int)$script_id,
  7920. 'products' => $products,
  7921. 'model' => $model,
  7922. 'ratio' => $ratio,
  7923. 'resolution' => $resolution,
  7924. 'auto_generate_images' => (bool)$auto_generate_images,
  7925. ];
  7926. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  7927. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  7928. $existing = DB::table('mp_task_center')
  7929. ->where('uid', (int)$uid)
  7930. ->where('cpid', (int)$cpid)
  7931. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  7932. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  7933. ->where('params_md5', $paramsMd5)
  7934. ->orderBy('id', 'desc')
  7935. ->first();
  7936. if ($existing) {
  7937. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  7938. 'script_id' => $script_id,
  7939. 'task_center_id' => $existing->id,
  7940. 'params_md5' => $paramsMd5,
  7941. ]);
  7942. return (int)$existing->id;
  7943. }
  7944. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  7945. $now = date('Y-m-d H:i:s');
  7946. DB::table('mp_task_center')->insertOrIgnore([
  7947. 'uid' => (int)$uid,
  7948. 'cpid' => (int)$cpid,
  7949. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  7950. 'title' => '剧本资产图片生成',
  7951. 'ref_task_id' => 0,
  7952. 'status' => MpTaskCenter::STATUS_PROCESSING,
  7953. 'result' => null,
  7954. 'error_message' => null,
  7955. 'prompt' => null,
  7956. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  7957. 'params_md5' => $paramsMd5,
  7958. 'created_at' => $now,
  7959. 'updated_at' => $now,
  7960. ]);
  7961. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  7962. $taskId = (int)DB::table('mp_task_center')
  7963. ->where('uid', (int)$uid)
  7964. ->where('cpid', (int)$cpid)
  7965. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  7966. ->where('params_md5', $paramsMd5)
  7967. ->orderBy('id', 'desc')
  7968. ->value('id');
  7969. dLog('anime')->info('创建任务中心记录', [
  7970. 'script_id' => $script_id,
  7971. 'task_center_id' => $taskId,
  7972. 'params_md5' => $paramsMd5,
  7973. ]);
  7974. return $taskId;
  7975. }
  7976. /**
  7977. * 任务结束时更新任务中心记录的状态和结果
  7978. *
  7979. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  7980. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  7981. *
  7982. * @param int|null $taskCenterId
  7983. * @param array $resultData 接口返回结果数组
  7984. * @param bool $timeout 是否超时未完成
  7985. */
  7986. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  7987. if (!$taskCenterId) {
  7988. return;
  7989. }
  7990. $stats = $resultData['stats'] ?? [];
  7991. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  7992. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  7993. $failedCount = $completedCount - $successCount;
  7994. // 与接口返回给客户端的结果保持一致
  7995. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  7996. if ($timeout) {
  7997. $this->taskCenterService->updateTask((int)$taskCenterId, [
  7998. 'status' => MpTaskCenter::STATUS_FAILED,
  7999. 'result' => $result,
  8000. 'error_message' => '部分任务超时,请稍后查看结果',
  8001. ]);
  8002. return;
  8003. }
  8004. $this->taskCenterService->updateTask((int)$taskCenterId, [
  8005. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  8006. 'result' => $result,
  8007. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  8008. ]);
  8009. }
  8010. /**
  8011. * 批量为剧本资产生成图片
  8012. *
  8013. * @param array $data 请求参数
  8014. * @return \Generator 返回 SSE 流
  8015. */
  8016. public function batchGenerateProductImages($data) {
  8017. $script_id = getProp($data, 'script_id');
  8018. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  8019. if (!$script_id) {
  8020. Utils::throwError('20003:请提供剧本ID');
  8021. }
  8022. // 验证剧本是否存在
  8023. $script = DB::table('mp_scripts')
  8024. ->where('id', $script_id)
  8025. ->where('is_deleted', 0)
  8026. ->first();
  8027. if (!$script) {
  8028. Utils::throwError('20003:剧本不存在');
  8029. }
  8030. $script_name = $script->script_name ?? 'script_' . $script_id;
  8031. // 获取需要生成图片的所有资产
  8032. $products = DB::table('mp_products')
  8033. ->whereIn('parent_id', array_values($type_folder_ids))
  8034. ->where('is_deleted', 0)
  8035. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  8036. ->get();
  8037. if ($products->isEmpty()) {
  8038. Utils::throwError('20003:没有找到需要生成图片的资产');
  8039. }
  8040. // 默认参数
  8041. $model = 'doubao-seedream-5-0-lite-260128';
  8042. $width = 1600;
  8043. $height = 2848;
  8044. // 开始为每个资产创建图片生成任务
  8045. $taskIds = [];
  8046. $productTaskMap = []; // 资产ID到任务ID的映射
  8047. foreach ($products as $product) {
  8048. if (empty($product->pic_prompt)) {
  8049. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  8050. continue;
  8051. }
  8052. try {
  8053. // 创建图片生成任务
  8054. $params = [
  8055. 'prompt' => $product->pic_prompt,
  8056. 'model' => $model,
  8057. 'ref_img_urls' => [],
  8058. 'width' => $width,
  8059. 'height' => $height
  8060. ];
  8061. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8062. $task_id = $task->id;
  8063. if ($task_id) {
  8064. $taskIds[] = $task_id;
  8065. $productTaskMap[$product->id] = $task_id;
  8066. // 更新资产表的任务ID和状态
  8067. DB::table('mp_products')
  8068. ->where('id', $product->id)
  8069. ->update([
  8070. 'pic_task_id' => $task_id,
  8071. 'pic_task_status' => '生成中',
  8072. 'updated_at' => now()
  8073. ]);
  8074. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  8075. }
  8076. } catch (\Exception $e) {
  8077. dLog('anime')->error('创建资产图片生成任务失败', [
  8078. 'product_id' => $product->id,
  8079. 'error' => $e->getMessage()
  8080. ]);
  8081. // 标记为失败
  8082. DB::table('mp_products')
  8083. ->where('id', $product->id)
  8084. ->update([
  8085. 'pic_task_status' => '生成失败',
  8086. 'updated_at' => now()
  8087. ]);
  8088. }
  8089. }
  8090. if (empty($taskIds)) {
  8091. Utils::throwError('20003:没有成功创建任何图片生成任务');
  8092. }
  8093. // 返回 SSE 流
  8094. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  8095. }
  8096. /**
  8097. * 轮询资产图片生成任务状态(SSE流式返回)
  8098. * 只通过查询数据库获取任务状态,不主动调用API
  8099. *
  8100. * @param int $script_id 剧本ID
  8101. * @param string $script_name 剧本名称
  8102. * @param array $productTaskMap 资产ID到任务ID的映射
  8103. * @param array $type_folder_ids 类型文件夹ID映射
  8104. * @return \Generator
  8105. */
  8106. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null) {
  8107. $startTime = time();
  8108. $timeout = 1800; // 30分钟超时
  8109. $pollInterval = 10; // 10秒轮询一次
  8110. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  8111. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  8112. if ($taskCenterId) {
  8113. $initResponse = [
  8114. 'type' => 'init',
  8115. 'script_id' => $script_id,
  8116. 'script_name' => $script_name,
  8117. 'timestamp' => date('Y-m-d H:i:s'),
  8118. 'task_center_id' => (int)$taskCenterId,
  8119. ];
  8120. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  8121. }
  8122. // 定义类型名称映射
  8123. $typeNames = [
  8124. 1 => 'roles', // 角色
  8125. 2 => 'scenes', // 场景
  8126. 3 => 'props' // 道具
  8127. ];
  8128. while (time() - $startTime < $timeout) {
  8129. sleep($pollInterval);
  8130. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  8131. $mappings = DB::table('mp_script_product_mappings')
  8132. ->where('script_id', $script_id)
  8133. ->pluck('product_id')
  8134. ->unique()
  8135. ->toArray();
  8136. if (empty($mappings)) {
  8137. dLog('anime')->warning('该剧本没有关联的资产', [
  8138. 'script_id' => $script_id,
  8139. 'script_name' => $script_name
  8140. ]);
  8141. break;
  8142. }
  8143. // 查询所有资产的当前状态
  8144. $products = DB::table('mp_products')
  8145. ->whereIn('id', $mappings)
  8146. ->where('is_deleted', 0)
  8147. ->get();
  8148. // 统计各类型的状态(使用类型名称作为键名)
  8149. $stats = [
  8150. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  8151. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  8152. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  8153. ];
  8154. $allCompleted = true;
  8155. $hasStatusChange = false;
  8156. foreach ($products as $product) {
  8157. $type = $product->product;
  8158. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  8159. // 如果类型名称不在 stats 中,初始化
  8160. if (!isset($stats[$typeName])) {
  8161. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  8162. }
  8163. $stats[$typeName]['total']++;
  8164. $task_id = $product->pic_task_id;
  8165. $currentStatus = $product->pic_task_status;
  8166. // 检查状态是否有变化
  8167. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  8168. $hasStatusChange = true;
  8169. $lastStatus[$product->id] = $currentStatus;
  8170. }
  8171. // 如果是生成中,查询任务表状态
  8172. if ($currentStatus === '生成中' && $task_id) {
  8173. // 只查询数据库,不调用API
  8174. $task = DB::table('mp_generate_pic_tasks')
  8175. ->where('id', $task_id)
  8176. ->first();
  8177. if ($task) {
  8178. // 检查任务状态
  8179. if ($task->status === 'success' && $task->result_url) {
  8180. // 解析图片URL
  8181. $result_urls = $task->result_url;
  8182. if (is_string($result_urls)) {
  8183. $result_urls = json_decode($result_urls, true);
  8184. }
  8185. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  8186. // 更新资产表状态
  8187. DB::table('mp_products')
  8188. ->where('id', $product->id)
  8189. ->update([
  8190. 'pic_task_status' => '生成成功',
  8191. 'url' => $img_url,
  8192. 'updated_at' => now()
  8193. ]);
  8194. $stats[$typeName]['success']++;
  8195. $stats[$typeName]['completed']++;
  8196. $hasStatusChange = true;
  8197. dLog('anime')->info('资产图片生成成功', [
  8198. 'product_id' => $product->id,
  8199. 'task_id' => $task_id,
  8200. 'img_url' => $img_url
  8201. ]);
  8202. } elseif ($task->status === 'failed') {
  8203. // 更新资产表状态
  8204. DB::table('mp_products')
  8205. ->where('id', $product->id)
  8206. ->update([
  8207. 'pic_task_status' => '生成失败',
  8208. 'updated_at' => now()
  8209. ]);
  8210. $stats[$typeName]['completed']++;
  8211. $hasStatusChange = true;
  8212. dLog('anime')->warning('资产图片生成失败', [
  8213. 'product_id' => $product->id,
  8214. 'task_id' => $task_id,
  8215. 'error' => $task->error_message ?? '未知错误'
  8216. ]);
  8217. } else {
  8218. // 任务还在处理中
  8219. $allCompleted = false;
  8220. }
  8221. } else {
  8222. // 任务不存在,标记为失败
  8223. DB::table('mp_products')
  8224. ->where('id', $product->id)
  8225. ->update([
  8226. 'pic_task_status' => '生成失败',
  8227. 'updated_at' => now()
  8228. ]);
  8229. $stats[$type]['completed']++;
  8230. $hasStatusChange = true;
  8231. dLog('anime')->error('图片生成任务不存在', [
  8232. 'product_id' => $product->id,
  8233. 'task_id' => $task_id
  8234. ]);
  8235. }
  8236. } elseif ($currentStatus === '生成成功') {
  8237. $stats[$typeName]['success']++;
  8238. $stats[$typeName]['completed']++;
  8239. } elseif ($currentStatus === '生成失败') {
  8240. $stats[$typeName]['completed']++;
  8241. } else {
  8242. // 其他状态也认为未完成
  8243. $allCompleted = false;
  8244. }
  8245. }
  8246. // 移除没有数据的类型(total=0)
  8247. foreach ($stats as $typeName => $stat) {
  8248. if ($stat['total'] === 0) {
  8249. unset($stats[$typeName]);
  8250. }
  8251. }
  8252. // 如果有状态变化,发送 SSE 更新
  8253. if ($hasStatusChange) {
  8254. $eventType = $allCompleted ? 'complete' : 'update';
  8255. $response = [
  8256. 'type' => $eventType,
  8257. 'script_id' => $script_id,
  8258. 'script_name' => $script_name,
  8259. 'stats' => $stats,
  8260. 'timestamp' => date('Y-m-d H:i:s')
  8261. ];
  8262. if ($taskCenterId) {
  8263. $response['task_center_id'] = $taskCenterId;
  8264. }
  8265. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  8266. dLog('anime')->info('SSE更新', [
  8267. 'event_type' => $eventType,
  8268. 'script_id' => $script_id,
  8269. 'script_name' => $script_name,
  8270. 'stats' => $stats
  8271. ]);
  8272. if ($allCompleted) {
  8273. dLog('anime')->info('所有资产图片生成任务已完成', [
  8274. 'script_id' => $script_id,
  8275. 'script_name' => $script_name,
  8276. 'stats' => $stats
  8277. ]);
  8278. // 全部任务完成,更新任务中心状态和结果
  8279. $this->finishScriptProductTask($taskCenterId, $response);
  8280. break;
  8281. }
  8282. }
  8283. }
  8284. // 超时处理
  8285. if (time() - $startTime >= $timeout && !$allCompleted) {
  8286. $response = [
  8287. 'type' => 'timeout',
  8288. 'message' => '部分任务超时,请稍后查看结果',
  8289. 'script_id' => $script_id,
  8290. 'script_name' => $script_name,
  8291. 'timestamp' => date('Y-m-d H:i:s')
  8292. ];
  8293. if ($taskCenterId) {
  8294. $response['task_center_id'] = $taskCenterId;
  8295. }
  8296. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  8297. dLog('anime')->warning('资产图片生成任务超时', [
  8298. 'script_id' => $script_id,
  8299. 'script_name' => $script_name,
  8300. 'timeout' => $timeout
  8301. ]);
  8302. // 超时未完成,更新任务中心状态和结果
  8303. $this->finishScriptProductTask($taskCenterId, $response, true);
  8304. }
  8305. }
  8306. /**
  8307. * 定时任务:检查产品图片生成任务状态并更新产品记录
  8308. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  8309. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  8310. *
  8311. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  8312. */
  8313. public function checkProductPicTasks() {
  8314. // 查询所有生成中的产品图片任务
  8315. $products = DB::table('mp_products')
  8316. ->whereNotNull('pic_task_id')
  8317. ->where('pic_task_status', '生成中')
  8318. ->where('is_deleted', 0)
  8319. ->get();
  8320. $stats = [
  8321. 'total' => $products->count(),
  8322. 'success' => 0,
  8323. 'failed' => 0,
  8324. 'pending' => 0,
  8325. ];
  8326. foreach ($products as $product) {
  8327. try {
  8328. $task_id = $product->pic_task_id;
  8329. // 通过 pic_task_id 查询图片生成任务结果
  8330. $task = DB::table('mp_generate_pic_tasks')
  8331. ->where('id', $task_id)
  8332. ->first();
  8333. if ($task) {
  8334. if ($task->status === 'success' && $task->result_url) {
  8335. // 解析图片URL
  8336. $result_urls = $task->result_url;
  8337. if (is_string($result_urls)) {
  8338. $result_urls = json_decode($result_urls, true);
  8339. }
  8340. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  8341. // 更新资产表状态
  8342. DB::table('mp_products')
  8343. ->where('id', $product->id)
  8344. ->update([
  8345. 'pic_task_status' => '生成成功',
  8346. 'url' => $img_url,
  8347. 'updated_at' => now()
  8348. ]);
  8349. $stats['success']++;
  8350. dLog('anime')->info('资产图片生成成功', [
  8351. 'product_id' => $product->id,
  8352. 'task_id' => $task_id,
  8353. 'img_url' => $img_url
  8354. ]);
  8355. } elseif ($task->status === 'failed') {
  8356. // 更新资产表状态
  8357. DB::table('mp_products')
  8358. ->where('id', $product->id)
  8359. ->update([
  8360. 'pic_task_status' => '生成失败',
  8361. 'updated_at' => now()
  8362. ]);
  8363. $stats['failed']++;
  8364. dLog('anime')->warning('资产图片生成失败', [
  8365. 'product_id' => $product->id,
  8366. 'task_id' => $task_id,
  8367. 'error' => $task->error_message ?? '未知错误'
  8368. ]);
  8369. } else {
  8370. // 任务还在处理中
  8371. $stats['pending']++;
  8372. }
  8373. } else {
  8374. // 任务不存在,标记为失败
  8375. DB::table('mp_products')
  8376. ->where('id', $product->id)
  8377. ->update([
  8378. 'pic_task_status' => '生成失败',
  8379. 'updated_at' => now()
  8380. ]);
  8381. $stats['failed']++;
  8382. dLog('anime')->error('图片生成任务不存在', [
  8383. 'product_id' => $product->id,
  8384. 'task_id' => $task_id
  8385. ]);
  8386. }
  8387. } catch (\Exception $e) {
  8388. dLog('anime')->error('检查产品图片生成任务异常', [
  8389. 'product_id' => $product->id,
  8390. 'task_id' => $product->pic_task_id ?? null,
  8391. 'error' => $e->getMessage()
  8392. ]);
  8393. }
  8394. }
  8395. return $stats;
  8396. }
  8397. /**
  8398. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  8399. *
  8400. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  8401. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  8402. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  8403. *
  8404. * @return int 更新的任务中心记录数
  8405. */
  8406. public function checkSaveScriptProductTaskCenters() {
  8407. $updated = 0;
  8408. // 只扫描尚未结束的 saveScriptProducts 任务
  8409. $tasks = DB::table('mp_task_center')
  8410. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8411. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  8412. ->orderBy('id', 'desc')
  8413. ->limit(500)
  8414. ->get();
  8415. // 与 pollProductImageTasks 保持一致的类型名称映射
  8416. $typeNames = [
  8417. 1 => 'roles', // 角色
  8418. 2 => 'scenes', // 场景
  8419. 3 => 'props', // 道具
  8420. ];
  8421. foreach ($tasks as $task) {
  8422. try {
  8423. $taskParams = json_decode((string)$task->params, true);
  8424. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  8425. if (!$script_id) {
  8426. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  8427. 'task_center_id' => $task->id,
  8428. ]);
  8429. continue;
  8430. }
  8431. // 获取该剧本关联的全部资产ID
  8432. $productIds = DB::table('mp_script_product_mappings')
  8433. ->where('script_id', $script_id)
  8434. ->pluck('product_id')
  8435. ->unique()
  8436. ->toArray();
  8437. if (empty($productIds)) {
  8438. // 剧本没有关联资产,不视为完成,等待下一次检查
  8439. continue;
  8440. }
  8441. $products = DB::table('mp_products')
  8442. ->whereIn('id', $productIds)
  8443. ->where('is_deleted', 0)
  8444. ->get();
  8445. $stats = [];
  8446. $allCompleted = true;
  8447. foreach ($products as $product) {
  8448. $typeName = $typeNames[$product->product] ?? 'unknown';
  8449. if (!isset($stats[$typeName])) {
  8450. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  8451. }
  8452. $stats[$typeName]['total']++;
  8453. if ($product->pic_task_status === '生成成功') {
  8454. $stats[$typeName]['success']++;
  8455. $stats[$typeName]['completed']++;
  8456. } elseif ($product->pic_task_status === '生成失败') {
  8457. $stats[$typeName]['completed']++;
  8458. } else {
  8459. // 仍有资产在生成中或未生成,任务未完成
  8460. $allCompleted = false;
  8461. }
  8462. }
  8463. if (!$allCompleted) {
  8464. continue;
  8465. }
  8466. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  8467. $script = DB::table('mp_scripts')
  8468. ->where('id', $script_id)
  8469. ->where('is_deleted', 0)
  8470. ->first();
  8471. $script_name = $script->script_name ?? 'script_' . $script_id;
  8472. $this->finishScriptProductTask($task->id, [
  8473. 'type' => 'complete',
  8474. 'script_id' => $script_id,
  8475. 'script_name' => $script_name,
  8476. 'stats' => $stats,
  8477. 'timestamp' => date('Y-m-d H:i:s'),
  8478. 'task_center_id' => (int)$task->id,
  8479. ]);
  8480. $updated++;
  8481. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  8482. 'task_center_id' => $task->id,
  8483. 'script_id' => $script_id,
  8484. 'stats' => $stats,
  8485. ]);
  8486. } catch (\Exception $e) {
  8487. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  8488. 'task_center_id' => $task->id,
  8489. 'error' => $e->getMessage(),
  8490. ]);
  8491. }
  8492. }
  8493. return $updated;
  8494. }
  8495. /**
  8496. * 获取剧本关联的资产列表
  8497. * @param array $data 请求参数
  8498. * @return array
  8499. */
  8500. public function getScriptProducts($data) {
  8501. $uid = Site::getUid();
  8502. $cpid = Site::getCpid();
  8503. $script_id = getProp($data, 'script_id');
  8504. $episode_number = getProp($data, 'episode_number');
  8505. if (!$script_id) {
  8506. Utils::throwError('20003:请提供剧本ID');
  8507. }
  8508. // 验证剧本是否存在
  8509. $script = DB::table('mp_scripts')
  8510. ->where('id', $script_id)
  8511. ->where('is_deleted', 0)
  8512. ->first();
  8513. if (!$script) {
  8514. Utils::throwError('20003:剧本不存在');
  8515. }
  8516. // 联表查询资产信息
  8517. $query = DB::table('mp_script_product_mappings as mapping')
  8518. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8519. ->where('mapping.script_id', $script_id)
  8520. ->where('product.cpid', $cpid)
  8521. ->where('product.is_deleted', 0);
  8522. // 如果提供了 episode_number,则过滤指定集数
  8523. if ($episode_number !== null && $episode_number !== '') {
  8524. $query->where('mapping.episode_number', $episode_number);
  8525. }
  8526. $mappings = $query->select(
  8527. 'mapping.script_id',
  8528. 'mapping.product_id',
  8529. 'mapping.episode_number',
  8530. 'product.product_name',
  8531. 'product.type',
  8532. 'product.product',
  8533. 'product.pic_prompt',
  8534. 'product.url',
  8535. 'product.pic_task_id',
  8536. 'product.pic_task_status',
  8537. 'product.three_view_image_url',
  8538. 'mapping.created_at'
  8539. )
  8540. ->orderBy('mapping.product_id', 'asc')
  8541. ->orderBy('mapping.episode_number', 'asc')
  8542. ->get();
  8543. // 按 product_id 分组,合并 episode_number
  8544. $productMap = [];
  8545. foreach ($mappings as $item) {
  8546. $product_id = $item->product_id;
  8547. if (!isset($productMap[$product_id])) {
  8548. $productMap[$product_id] = [
  8549. 'product_id' => $product_id,
  8550. 'product_name' => $item->product_name,
  8551. 'type' => (int)$item->type,
  8552. 'product' => (int)$item->product,
  8553. 'pic_prompt' => $item->pic_prompt,
  8554. 'url' => $item->url,
  8555. 'pic_task_id' => $item->pic_task_id,
  8556. 'pic_task_status' => $item->pic_task_status,
  8557. 'episode_numbers' => [],
  8558. 'created_at' => $item->created_at,
  8559. ];
  8560. }
  8561. // 添加 episode_number(去重)
  8562. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8563. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8564. }
  8565. }
  8566. // 按类型分组
  8567. $roles = []; // type=1 角色/主体
  8568. $scenes = []; // type=2 场景
  8569. $props = []; // type=3 道具
  8570. foreach ($productMap as $product) {
  8571. // 将 episode_numbers 数组转换为逗号分隔的字符串
  8572. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  8573. // 构造返回数据
  8574. $productData = [
  8575. 'product_id' => $product['product_id'],
  8576. 'product_name' => $product['product_name'],
  8577. 'product' => $product['product'],
  8578. 'pic_prompt' => $product['pic_prompt'],
  8579. 'url' => $product['url'],
  8580. 'pic_task_id' => $product['pic_task_id'],
  8581. 'pic_task_status' => $product['pic_task_status'],
  8582. 'episode_numbers' => $episodeNumbersStr,
  8583. 'created_at' => $product['created_at'],
  8584. ];
  8585. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  8586. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  8587. switch ($product['product']) {
  8588. case 1:
  8589. $roles[] = $productData;
  8590. break;
  8591. case 2:
  8592. $scenes[] = $productData;
  8593. break;
  8594. case 3:
  8595. $props[] = $productData;
  8596. break;
  8597. }
  8598. }
  8599. return [
  8600. 'script_id' => $script_id,
  8601. 'script_name' => $script->script_name ?? '',
  8602. 'roles' => $roles, // 主体
  8603. 'scenes' => $scenes, // 场景
  8604. 'props' => $props, // 道具
  8605. ];
  8606. }
  8607. /**
  8608. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  8609. * @param string $actContent 原始内容
  8610. * @param array $products 产品数组(包含product_name和url)
  8611. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  8612. */
  8613. public function processActContentWithProducts($actContent, $products) {
  8614. if (empty($actContent) || empty($products)) {
  8615. return [
  8616. 'content' => $actContent,
  8617. 'reference_images' => []
  8618. ];
  8619. }
  8620. // 构建产品名称到产品信息的映射
  8621. $product_dict = [];
  8622. foreach ($products as $product) {
  8623. $product_name = getProp($product, 'product_name');
  8624. if ($product_name) {
  8625. $product_dict[$product_name] = [
  8626. // 优先使用三视图图片作为素材/参考图,否则使用原图 url
  8627. 'url' => getProp($product, 'three_view_image_url') ?: getProp($product, 'url'),
  8628. 'voice_prompt' => getProp($product, 'voice_prompt')
  8629. ];
  8630. }
  8631. }
  8632. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  8633. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  8634. $reference_images = [];
  8635. $product_index_map = []; // 产品名称 => 图片序号的映射
  8636. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  8637. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  8638. $current_index = 1;
  8639. if (!empty($matches[1])) {
  8640. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  8641. $seen_products = []; // 用于去重
  8642. foreach ($matches[1] as $product_name) {
  8643. // 跳过已处理的产品
  8644. if (isset($seen_products[$product_name])) {
  8645. continue;
  8646. }
  8647. $seen_products[$product_name] = true;
  8648. // 检查产品是否在字典中
  8649. if (isset($product_dict[$product_name])) {
  8650. $url = $product_dict[$product_name]['url'];
  8651. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  8652. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  8653. if (!empty($voice_prompt) && $product_name !== '旁白') {
  8654. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  8655. }
  8656. // 只有URL非空才分配序号和添加到参考图片
  8657. if (!empty($url)) {
  8658. // 检查URL是否已经在reference_images中(去重)
  8659. if (!in_array($url, $reference_images)) {
  8660. $reference_images[] = $url;
  8661. $product_index_map[$product_name] = $current_index;
  8662. $current_index++;
  8663. } else {
  8664. // URL重复,找到已有的序号
  8665. $existing_index = array_search($url, $reference_images) + 1;
  8666. $product_index_map[$product_name] = $existing_index;
  8667. }
  8668. } else {
  8669. // URL为空,不分配序号(后续直接去掉{})
  8670. $product_index_map[$product_name] = 0;
  8671. }
  8672. } else {
  8673. // 产品不在字典中,不分配序号
  8674. $product_index_map[$product_name] = 0;
  8675. }
  8676. }
  8677. }
  8678. // 第二步:替换内容中的 {产品名称}
  8679. $processedContent = $actContent;
  8680. foreach ($product_index_map as $product_name => $index) {
  8681. $escaped_name = preg_quote($product_name, '/');
  8682. if ($index > 0) {
  8683. // 有图片,替换为:产品名称(图X)
  8684. $replacement = $product_name . '<图片' . $index . '>';
  8685. } else {
  8686. // 无图片,只保留产品名称
  8687. $replacement = $product_name;
  8688. }
  8689. // 替换所有 {产品名称} 为处理后的格式
  8690. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  8691. }
  8692. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  8693. foreach ($products as $product) {
  8694. $product_name = getProp($product, 'product_name');
  8695. $voice_prompt = getProp($product, 'voice_prompt');
  8696. if ($product_name === '旁白' && !empty($voice_prompt)) {
  8697. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  8698. break; // 找到旁白后退出循环
  8699. }
  8700. }
  8701. // 第四步:将voice_prompt信息添加到内容最前面
  8702. $voice_prompt_prefix = '';
  8703. if (!empty($voice_prompts)) {
  8704. $voice_prompt_prefix .= implode('', $voice_prompts);
  8705. }
  8706. // 旁白的voice_prompt放在最后
  8707. if (!empty($narrator_voice_prompt)) {
  8708. $voice_prompt_prefix .= $narrator_voice_prompt;
  8709. }
  8710. // 如果有voice_prompt信息,添加到内容开头
  8711. if (!empty($voice_prompt_prefix)) {
  8712. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  8713. }
  8714. return [
  8715. 'content' => $processedContent,
  8716. 'reference_images' => $reference_images
  8717. ];
  8718. }
  8719. public function saveActVideoGenerateParams($data) {
  8720. $episode_id = getProp($data, 'episode_id');
  8721. $model = getProp($data, 'video_model');
  8722. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  8723. if (!in_array($model, $valid_models)) {
  8724. Utils::throwError('20003:该模型不可用');
  8725. }
  8726. // 验证模型是否在可用模型表中
  8727. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8728. Utils::throwError('20003:该模型已不可用,请更换!');
  8729. }
  8730. $video_resolution = getProp($data, 'video_resolution', '720p');
  8731. $ratio = getProp($data, 'ratio');
  8732. if (!$ratio) $ratio = '9:16';
  8733. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  8734. if (!$episode) {
  8735. Utils::throwError('20003:分集不存在');
  8736. }
  8737. dLog('anime')->info('保存分集视频参数', $data);
  8738. try {
  8739. DB::beginTransaction();
  8740. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8741. 'video_model' => $model,
  8742. 'video_resolution' => $video_resolution,
  8743. 'ratio' => $ratio,
  8744. 'updated_at' => date('Y-m-d H:i:s')
  8745. ]);
  8746. if ($result === false) {
  8747. Utils::throwError('20003:分集视频参数保存失败');
  8748. }
  8749. // 同步更新mp_animes表
  8750. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  8751. 'video_model' => $model,
  8752. 'video_resolution' => $video_resolution,
  8753. 'video_ratio' => $ratio,
  8754. 'updated_at' => date('Y-m-d H:i:s')
  8755. ]);
  8756. if ($anime_result === false) {
  8757. Utils::throwError('20003:动漫视频参数保存失败');
  8758. }
  8759. } catch (\Exception $e) {
  8760. DB::rollBack();
  8761. Utils::throwError('20003:'.$e->getMessage());
  8762. }
  8763. DB::commit();
  8764. return $result;
  8765. }
  8766. public function confirmActs($data) {
  8767. $episode_id = getProp($data, 'episode_id');
  8768. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  8769. if (!$episode) {
  8770. Utils::throwError('20003:分集不存在');
  8771. }
  8772. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  8773. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  8774. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  8775. // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
  8776. $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
  8777. // 获取所有片段数据
  8778. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8779. // 先构建完整的 products(角色、场景、道具、extra_products,并用资产库映射覆盖),
  8780. // 再处理每个片段的 act_content,避免 extra_products 等资产名未被格式化为 {资产名}
  8781. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  8782. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  8783. $products = [];
  8784. // 先处理角色数组
  8785. foreach ($roles as $role) {
  8786. $product = $role;
  8787. // 将role字段重命名为product_name
  8788. if (isset($product['role'])) {
  8789. $product['product_name'] = $product['role'];
  8790. unset($product['role']);
  8791. $product['product'] = 1; // 标记类型为角色
  8792. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8793. }
  8794. }
  8795. // 处理场景数组
  8796. foreach ($scenes as $scene) {
  8797. $product = $scene;
  8798. // 将scene字段重命名为product_name
  8799. if (isset($product['scene'])) {
  8800. $product['product_name'] = $product['scene'];
  8801. unset($product['scene']);
  8802. $product['product'] = 2; // 标记类型为场景
  8803. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8804. }
  8805. }
  8806. // 处理道具数组(逻辑与场景一致)
  8807. foreach ($props as $prop) {
  8808. $product = $prop;
  8809. // 将prop字段重命名为product_name
  8810. if (isset($product['prop'])) {
  8811. $product['product_name'] = $product['prop'];
  8812. unset($product['prop']);
  8813. $product['product'] = 3; // 标记类型为道具
  8814. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8815. }
  8816. }
  8817. // extra_products优先级更高,直接覆盖同名的roles和scenes
  8818. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  8819. foreach ($extra_products as $extra_product) {
  8820. $product_name = getProp($extra_product, 'product_name');
  8821. if ($product_name) {
  8822. $products[$product_name] = $extra_product; // 覆盖同名数据
  8823. }
  8824. }
  8825. // mp_script_product_mappings 信息优先级更高:
  8826. // 获取当前剧集所属动漫剧本下、与本集资产同名的资产库最新数据(url/三视图/提示词等),
  8827. // 覆盖分集 JSON 中保存的同名旧快照;分集内独有的 description、voice_prompt 等字段保留
  8828. $anime = DB::table('mp_animes')->where('id', getProp($episode, 'anime_id'))->first();
  8829. $script_id = $anime ? (int)getProp($anime, 'script_id', 0) : 0;
  8830. if ($script_id && !empty($products)) {
  8831. $currentProductNames = array_keys($products);
  8832. $normalizeName = function($name) {
  8833. return trim(preg_replace(
  8834. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  8835. '',
  8836. trim((string)$name)
  8837. ));
  8838. };
  8839. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  8840. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8841. ->where('mapping.script_id', $script_id)
  8842. ->where('product.is_deleted', 0)
  8843. ->whereIn('product.product_name', $currentProductNames)
  8844. ->select(
  8845. 'mapping.product_id',
  8846. 'product.product_name',
  8847. 'product.product',
  8848. 'product.pic_prompt',
  8849. 'product.url',
  8850. 'product.three_view_image_url',
  8851. )
  8852. ->get();
  8853. $mappingByName = [];
  8854. foreach ($mappingItems as $mappingItem) {
  8855. $normalizedName = $normalizeName($mappingItem->product_name);
  8856. if (!$normalizedName) continue;
  8857. $mappingByName[$normalizedName] = [
  8858. 'product_id' => (int)$mappingItem->product_id,
  8859. 'product_name' => $mappingItem->product_name,
  8860. 'product' => (int)$mappingItem->product,
  8861. 'pic_prompt' => $mappingItem->pic_prompt ?? '',
  8862. 'url' => $mappingItem->url ?? '',
  8863. 'three_view_image_url' => $mappingItem->three_view_image_url ?? '',
  8864. ];
  8865. }
  8866. foreach ($products as $key => &$product) {
  8867. $normalizedKey = $normalizeName($key);
  8868. if ($normalizedKey && isset($mappingByName[$normalizedKey])) {
  8869. $product = array_merge($product, $mappingByName[$normalizedKey]);
  8870. }
  8871. }
  8872. unset($product);
  8873. }
  8874. // 兼容返回 three_view_image_url 字段(旧数据可能没有该键,统一补空值)
  8875. foreach ($products as &$product) {
  8876. if (!isset($product['three_view_image_url'])) {
  8877. $product['three_view_image_url'] = '';
  8878. }
  8879. }
  8880. unset($product);
  8881. // 重新索引数组(去除key)
  8882. $products = array_values($products);
  8883. // 基于构建完成的 products 收集所有资产名称(含 extra_products 中的资产)
  8884. $product_names = [];
  8885. foreach ($products as $product) {
  8886. $product_name = getProp($product, 'product_name');
  8887. if ($product_name && $product_name !== '旁白') {
  8888. $product_names[] = $product_name;
  8889. }
  8890. }
  8891. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8892. $product_names = array_unique($product_names);
  8893. usort($product_names, function($a, $b) {
  8894. return mb_strlen($b) - mb_strlen($a);
  8895. });
  8896. try {
  8897. DB::beginTransaction();
  8898. // 处理每个片段
  8899. foreach ($acts as $act) {
  8900. $act_content = getProp($act, 'act_content');
  8901. if (!$act_content) continue;
  8902. $processed_content = $act_content;
  8903. // 统一替换所有资产名称为 {资产名} 格式
  8904. // 使用占位符避免嵌套替换问题
  8905. $placeholder_map = [];
  8906. $placeholder_index = 0;
  8907. foreach ($product_names as $product_name) {
  8908. // 转义特殊字符
  8909. $escaped_product = preg_quote($product_name, '/');
  8910. // 检查是否匹配且未被 {} 包裹
  8911. $processed_content = preg_replace_callback(
  8912. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8913. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8914. // 使用唯一占位符
  8915. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8916. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8917. $placeholder_index++;
  8918. return $placeholder;
  8919. },
  8920. $processed_content
  8921. );
  8922. }
  8923. // 将所有占位符替换回实际内容
  8924. foreach ($placeholder_map as $placeholder => $replacement) {
  8925. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8926. }
  8927. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8928. $shot_counter = 0;
  8929. $processed_content = preg_replace_callback(
  8930. '/【(?:镜头|分镜)(\d+)】/u',
  8931. function($matches) use (&$shot_counter) {
  8932. $shot_counter++;
  8933. return '【镜头' . $shot_counter . '】';
  8934. },
  8935. $processed_content
  8936. );
  8937. // 更新数据库
  8938. $boolen = DB::table('mp_episode_segments')
  8939. ->where('id', $act->id)
  8940. ->update([
  8941. 'act_show_content' => $processed_content,
  8942. 'updated_at' => date('Y-m-d H:i:s')
  8943. ]);
  8944. if (!$boolen) {
  8945. Utils::throwError('20003:片段处理失败');
  8946. }
  8947. }
  8948. }catch (\Exception $e) {
  8949. DB::rollBack();
  8950. Utils::throwError('20003:'.$e->getMessage());
  8951. }
  8952. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8953. 'is_generated' => 1,
  8954. 'updated_at' => date('Y-m-d H:i:s')
  8955. ]);
  8956. if (!$boolen1) {
  8957. DB::rollBack();
  8958. Utils::throwError('20003:分集处理失败!');
  8959. }
  8960. DB::commit();
  8961. // 重新查询更新后的片段数据
  8962. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8963. // 构建返回的acts数组
  8964. $return_acts = [];
  8965. foreach ($acts as $act) {
  8966. $return_acts[] = [
  8967. 'act_id' => getProp($act, 'id'),
  8968. 'act_number' => getProp($act, 'act_number'),
  8969. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  8970. 'act_show_content' => getProp($act, 'act_show_content'),
  8971. 'video_url' => getProp($act, 'video_url'),
  8972. 'video_duration' => getProp($act, 'video_duration'),
  8973. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  8974. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  8975. ];
  8976. }
  8977. return [
  8978. 'anime_id' => getProp($episode, 'anime_id'),
  8979. 'episode_id' => $episode_id,
  8980. 'title' => getProp($episode, 'title'),
  8981. 'episode_number' => getProp($episode, 'episode_number'),
  8982. 'is_generated' => getProp($episode, 'is_generated'),
  8983. 'video_params' => [
  8984. 'video_model' => getProp($episode, 'video_model'),
  8985. 'video_resolution' => getProp($episode, 'video_resolution'),
  8986. 'ratio' => getProp($episode, 'ratio'),
  8987. ],
  8988. 'products' => $products,
  8989. 'acts' => $return_acts
  8990. ];
  8991. }
  8992. /**
  8993. * 参照 episodePicsInfo 的更新与监控逻辑:
  8994. * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
  8995. * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
  8996. */
  8997. private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
  8998. $pollInterval = 5; // 每5秒查询一次
  8999. $maxWaitSeconds = 60; // 最多持续1分钟
  9000. $startTime = time();
  9001. while (true) {
  9002. // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
  9003. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  9004. if (!$episode) {
  9005. Utils::throwError('20003:分集不存在');
  9006. }
  9007. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9008. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9009. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  9010. $updated = false;
  9011. $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
  9012. $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
  9013. $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
  9014. $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
  9015. $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
  9016. // 有图片任务结果更新时写回分集表
  9017. if ($updated) {
  9018. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  9019. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  9020. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  9021. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  9022. 'updated_at' => date('Y-m-d H:i:s')
  9023. ]);
  9024. }
  9025. // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
  9026. if (empty($waitingAssets) && empty($missingAssets)) {
  9027. return;
  9028. }
  9029. // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
  9030. if (empty($waitingAssets)) {
  9031. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  9032. }
  9033. // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
  9034. if (time() - $startTime >= $maxWaitSeconds) {
  9035. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  9036. }
  9037. sleep($pollInterval);
  9038. }
  9039. }
  9040. /**
  9041. * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
  9042. * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
  9043. * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
  9044. */
  9045. private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
  9046. foreach ($assets as &$asset) {
  9047. $assetName = getProp($asset, $nameKey);
  9048. if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
  9049. continue;
  9050. }
  9051. // 已有图片URL的资产视为已生成
  9052. if (getProp($asset, 'url')) {
  9053. continue;
  9054. }
  9055. $task_id = getProp($asset, 'task_id');
  9056. // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
  9057. if (!$task_id) {
  9058. $missingAssets[] = $assetName;
  9059. continue;
  9060. }
  9061. $task = DB::table('mp_generate_pic_tasks')
  9062. ->where('id', $task_id)
  9063. ->select('status', 'result_url')
  9064. ->first();
  9065. // 任务不存在:同样记录为缺失项,不在此处直接报错
  9066. if (!$task) {
  9067. $missingAssets[] = $assetName;
  9068. continue;
  9069. }
  9070. if ($task->status === 'success') {
  9071. $result_url = getProp($task, 'result_url');
  9072. if ($result_url) {
  9073. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  9074. if (is_array($result_urls) && !empty($result_urls[0])) {
  9075. $asset['url'] = $result_urls[0];
  9076. $asset['task_status'] = 'success';
  9077. $updated = true;
  9078. continue;
  9079. }
  9080. }
  9081. // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
  9082. $waitingAssets[] = $assetName;
  9083. } elseif ($task->status === 'failed') {
  9084. // 生成失败:记录为缺失项,待其他任务处理完后统一报错
  9085. $missingAssets[] = $assetName;
  9086. } else {
  9087. // 任务仍在生成中,等待下一次轮询
  9088. $waitingAssets[] = $assetName;
  9089. }
  9090. }
  9091. unset($asset);
  9092. }
  9093. /**
  9094. * 导出动漫剧本为PDF(参照示例PDF版式)
  9095. * @param int $animeId 动漫ID
  9096. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  9097. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  9098. * @return string|null
  9099. */
  9100. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  9101. // 图片下载与转换可能占用较多内存
  9102. ini_set('memory_limit', '512M');
  9103. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  9104. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  9105. $anime = (array)$anime;
  9106. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  9107. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  9108. // 获取分集(默认展示版本,按集数升序)
  9109. $episodeQuery = DB::table('mp_anime_episodes')
  9110. ->where('anime_id', $animeId)
  9111. ->where('is_default', 1)
  9112. ->orderBy('episode_number')
  9113. ->orderBy('id');
  9114. if ($episodeCount > 0) {
  9115. $episodeQuery->limit($episodeCount);
  9116. }
  9117. $episodes = $episodeQuery->get()->map(function ($value) {
  9118. return (array)$value;
  9119. })->toArray();
  9120. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  9121. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  9122. $roles = $this->mergeEpisodeItems($episodes, 'role');
  9123. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  9124. $props = $this->mergeEpisodeItems($episodes, 'prop');
  9125. // 组装分集剧本数据
  9126. $episodeScripts = [];
  9127. foreach ($episodes as $episode) {
  9128. $segments = DB::table('mp_episode_segments')
  9129. ->where('anime_id', $animeId)
  9130. ->where('episode_id', $episode['id'])
  9131. ->get();
  9132. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  9133. $acts = [];
  9134. foreach ($segments as $segment) {
  9135. $segment = (array)$segment;
  9136. $actNumber = (int)getProp($segment, 'act_number', 0);
  9137. if ($actNumber <= 0) continue;
  9138. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  9139. $acts[$actNumber] = [
  9140. 'id' => (int)$segment['id'],
  9141. 'act_number' => $actNumber,
  9142. 'duration' => getProp($segment, 'act_duration', ''),
  9143. 'content' => getProp($segment, 'act_content', ''),
  9144. ];
  9145. }
  9146. }
  9147. ksort($acts);
  9148. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  9149. $segmentCounter = 0;
  9150. foreach ($acts as &$act) {
  9151. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  9152. }
  9153. unset($act);
  9154. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  9155. $narratorVoice = '';
  9156. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  9157. foreach ($episodeRoles as $role) {
  9158. if (getProp($role, 'role') === '旁白') {
  9159. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  9160. break;
  9161. }
  9162. }
  9163. if ($narratorVoice === '') {
  9164. foreach ($acts as $act) {
  9165. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  9166. $narratorVoice = trim($match[1]);
  9167. break;
  9168. }
  9169. }
  9170. }
  9171. $episodeScripts[] = [
  9172. 'episode_number' => getProp($episode, 'episode_number'),
  9173. 'title' => getProp($episode, 'title', ''),
  9174. 'act_count' => count($acts),
  9175. 'narrator_voice' => $narratorVoice,
  9176. 'acts' => array_values($acts),
  9177. ];
  9178. }
  9179. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  9180. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  9181. // 构建PDF
  9182. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  9183. // 图片已嵌入PDF,清理临时文件
  9184. foreach ($imageCache as $imgFile) {
  9185. @unlink($imgFile);
  9186. }
  9187. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  9188. if ($savePath) {
  9189. $pdf->Output($savePath, 'F');
  9190. return $savePath;
  9191. }
  9192. // 直接下载输出
  9193. header('Content-Type: application/pdf');
  9194. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  9195. $pdf->Output($filename . '.pdf', 'D');
  9196. exit();
  9197. }
  9198. /**
  9199. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  9200. * @param array $episodes 分集数据
  9201. * @param string $nameKey role|scene|prop
  9202. * @return array
  9203. */
  9204. private function mergeEpisodeItems(array $episodes, $nameKey) {
  9205. $fieldMap = [
  9206. 'role' => 'roles',
  9207. 'scene' => 'scenes',
  9208. 'prop' => 'props',
  9209. ];
  9210. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  9211. $items = [];
  9212. foreach ($episodes as $episode) {
  9213. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  9214. foreach ($list as $item) {
  9215. if (!is_array($item)) continue;
  9216. $name = trim((string)getProp($item, $nameKey, ''));
  9217. if ($name === '') continue;
  9218. // 旁白不进入主体列表(仅作为旁白音色来源)
  9219. if ($nameKey === 'role' && $name === '旁白') continue;
  9220. if (!isset($items[$name])) {
  9221. $items[$name] = $item;
  9222. }
  9223. }
  9224. }
  9225. return array_values($items);
  9226. }
  9227. /**
  9228. * 构建动漫剧本PDF
  9229. * @param array $anime 动漫信息
  9230. * @param array $roles 主体列表
  9231. * @param array $scenes 场景列表
  9232. * @param array $props 道具列表
  9233. * @param array $episodeScripts 分集剧本数据
  9234. * @param array $imageCache 图片缓存(url => 临时文件路径)
  9235. * @return \TCPDF
  9236. */
  9237. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  9238. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  9239. $pdf->SetCreator('动漫剧本导出系统');
  9240. $pdf->SetAuthor('系统');
  9241. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  9242. $pdf->SetSubject('动漫剧本导出');
  9243. $pdf->SetMargins(15, 15, 15);
  9244. $pdf->SetAutoPageBreak(true, 15);
  9245. // 剧本名
  9246. $pdf->AddPage();
  9247. $pdf->SetFont('simsun', 'B', 20);
  9248. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  9249. $pdf->Ln(5);
  9250. // 故事梗概
  9251. $intro = trim((string)getProp($anime, 'intro', ''));
  9252. if ($intro !== '') {
  9253. $this->pdfSectionTitle($pdf, '故事梗概');
  9254. $this->pdfBody($pdf, $intro);
  9255. }
  9256. // 美术风格
  9257. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  9258. if ($artStyle !== '') {
  9259. $this->pdfSectionTitle($pdf, '美术风格');
  9260. $this->pdfBody($pdf, $artStyle);
  9261. }
  9262. // 主体列表(文字+图片)
  9263. $this->pdfSectionTitle($pdf, '主体列表');
  9264. foreach ($roles as $index => $role) {
  9265. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  9266. }
  9267. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  9268. // 场景列表(文字+图片)
  9269. $this->pdfSectionTitle($pdf, '场景列表');
  9270. foreach ($scenes as $index => $scene) {
  9271. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  9272. }
  9273. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  9274. // 道具列表(文字+图片)
  9275. $this->pdfSectionTitle($pdf, '道具列表');
  9276. foreach ($props as $index => $prop) {
  9277. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  9278. }
  9279. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  9280. // 分镜剧本
  9281. $this->pdfSectionTitle($pdf, '分镜剧本');
  9282. foreach ($episodeScripts as $episodeScript) {
  9283. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  9284. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  9285. if ($episodeTitleRaw !== '') {
  9286. // title 字段可能已带"第N集"前缀,避免重复
  9287. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  9288. $episodeTitle = $episodeTitleRaw;
  9289. } else {
  9290. $episodeTitle .= ':' . $episodeTitleRaw;
  9291. }
  9292. }
  9293. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  9294. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  9295. if (getProp($episodeScript, 'narrator_voice') !== '') {
  9296. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  9297. }
  9298. foreach (getProp($episodeScript, 'acts', []) as $act) {
  9299. $actTitle = '片段' . getProp($act, 'act_number');
  9300. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  9301. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  9302. }
  9303. $this->pdfSubTitle($pdf, $actTitle, 12);
  9304. if (getProp($act, 'content') !== '') {
  9305. $this->pdfBody($pdf, getProp($act, 'content'));
  9306. }
  9307. }
  9308. }
  9309. return $pdf;
  9310. }
  9311. /**
  9312. * PDF章节标题(带分隔线)
  9313. */
  9314. private function pdfSectionTitle($pdf, $title) {
  9315. if ($pdf->GetY() > 230) {
  9316. $pdf->AddPage();
  9317. }
  9318. $pdf->SetFont('simsun', 'B', 15);
  9319. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  9320. $y = $pdf->GetY();
  9321. $pdf->SetLineWidth(0.4);
  9322. $pdf->Line(15, $y, 195, $y);
  9323. $pdf->Ln(4);
  9324. }
  9325. /**
  9326. * PDF子标题(集数/片段标题)
  9327. */
  9328. private function pdfSubTitle($pdf, $title, $size = 13) {
  9329. if ($pdf->GetY() > 240) {
  9330. $pdf->AddPage();
  9331. }
  9332. $pdf->SetFont('simsun', 'B', $size);
  9333. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  9334. $pdf->Ln(1);
  9335. }
  9336. /**
  9337. * PDF正文段落
  9338. */
  9339. private function pdfBody($pdf, $text) {
  9340. $pdf->SetFont('simsun', '', 11);
  9341. $pdf->MultiCell(0, 6, $text, 0, 'L');
  9342. $pdf->Ln(2);
  9343. }
  9344. /**
  9345. * 输出列表项图片(每张图单独一页,图下标注名称)
  9346. * @param \TCPDF $pdf
  9347. * @param array $items 列表项
  9348. * @param string $nameKey role|scene|prop
  9349. * @param array $imageCache 图片缓存(url => 临时文件路径)
  9350. */
  9351. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  9352. foreach ($items as $item) {
  9353. $url = trim((string)getProp($item, 'url', ''));
  9354. $name = trim((string)getProp($item, $nameKey, ''));
  9355. if ($url === '' || !isset($imageCache[$url])) continue;
  9356. $imgPath = $imageCache[$url];
  9357. $size = @getimagesize($imgPath);
  9358. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  9359. continue;
  9360. }
  9361. $pdf->AddPage();
  9362. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  9363. $maxW = 160;
  9364. $maxH = 170;
  9365. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  9366. $drawW = $size[0] * $ratio;
  9367. $drawH = $size[1] * $ratio;
  9368. $x = (210 - $drawW) / 2;
  9369. $y = max(15, (297 - $drawH) / 2 - 10);
  9370. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  9371. // 图下标注名称
  9372. $pdf->SetFont('simsun', 'B', 13);
  9373. $pdf->SetY(297 - 28);
  9374. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  9375. }
  9376. }
  9377. /**
  9378. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  9379. * @param array $items 包含url字段的列表项
  9380. * @return array url => 临时文件路径
  9381. */
  9382. private function downloadImagesConcurrently(array $items) {
  9383. // 收集唯一的图片URL
  9384. $urls = [];
  9385. foreach ($items as $item) {
  9386. $url = trim((string)getProp($item, 'url', ''));
  9387. if ($url !== '') $urls[$url] = true;
  9388. }
  9389. if (!$urls) return [];
  9390. $urls = array_keys($urls);
  9391. $tmpDir = sys_get_temp_dir();
  9392. $rawFiles = [];
  9393. foreach ($urls as $url) {
  9394. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  9395. $rawFiles[$url] = $rawFile;
  9396. }
  9397. $client = new Client(['timeout' => 180, 'verify' => false]);
  9398. // 低并发下载,sink写入文件避免大图占用内存
  9399. $generator = (function () use ($urls, $client, $rawFiles) {
  9400. foreach ($urls as $url) {
  9401. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  9402. }
  9403. })();
  9404. $errors = [];
  9405. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  9406. 'concurrency' => 4,
  9407. 'rejected' => function ($reason, $url) use (&$errors) {
  9408. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  9409. },
  9410. ]);
  9411. $each->promise()->wait();
  9412. // 失败的图片串行重试一次(独占带宽,提高成功率)
  9413. foreach ($urls as $url) {
  9414. if (!isset($errors[$url])) continue;
  9415. try {
  9416. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  9417. unset($errors[$url]);
  9418. } catch (\Throwable $e) {
  9419. // 重试仍失败
  9420. }
  9421. }
  9422. $cache = [];
  9423. foreach ($urls as $url) {
  9424. $rawFile = $rawFiles[$url];
  9425. if (isset($errors[$url])) {
  9426. dLog('anime')->error('导出PDF图片下载失败', [
  9427. 'url' => $url,
  9428. 'error' => $errors[$url],
  9429. ]);
  9430. @unlink($rawFile);
  9431. continue;
  9432. }
  9433. $converted = $this->convertImageFile($rawFile, $url);
  9434. if ($converted !== null) {
  9435. $cache[$url] = $converted;
  9436. } else {
  9437. @unlink($rawFile);
  9438. }
  9439. }
  9440. return $cache;
  9441. }
  9442. /**
  9443. * 将已下载的图片文件缩放并转为JPEG
  9444. * @param string $rawFile 原始图片临时文件
  9445. * @param string $url 图片地址(用于命名)
  9446. * @return string|null 转换后的文件路径,转换失败返回null
  9447. */
  9448. private function convertImageFile($rawFile, $url) {
  9449. $content = @file_get_contents($rawFile);
  9450. if ($content === false || $content === '') return null;
  9451. if (!function_exists('imagecreatefromstring')) return null;
  9452. $image = @imagecreatefromstring($content);
  9453. if ($image === false) return null;
  9454. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  9455. imagedestroy($image);
  9456. if ($jpeg !== null) {
  9457. @unlink($rawFile);
  9458. }
  9459. return $jpeg;
  9460. }
  9461. /**
  9462. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  9463. * @param resource $srcImage GD图片资源
  9464. * @param string $rawFile 原始图片临时文件
  9465. * @param string $url 图片地址(用于命名)
  9466. * @return string|null 压缩后的JPEG文件路径
  9467. */
  9468. private function compressImageForPdf($srcImage, $rawFile, $url) {
  9469. $maxBytes = 2 * 1024 * 1024; // 2MB
  9470. $sizes = [2048, 1600, 1280, 1024, 800];
  9471. $qualities = [85, 70, 55, 40];
  9472. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  9473. foreach ($sizes as $size) {
  9474. $resized = $this->copyAndResize($srcImage, $size);
  9475. $flat = $this->flattenToWhite($resized);
  9476. imagedestroy($resized);
  9477. foreach ($qualities as $quality) {
  9478. ob_start();
  9479. $saved = imagejpeg($flat, null, $quality);
  9480. $data = ob_get_clean();
  9481. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  9482. file_put_contents($jpeg, $data);
  9483. imagedestroy($flat);
  9484. dLog('anime')->info('导出PDF图片压缩完成', [
  9485. 'url' => $url,
  9486. 'size' => filesize($jpeg),
  9487. 'edge' => $size,
  9488. 'quality' => $quality,
  9489. ]);
  9490. return $jpeg;
  9491. }
  9492. }
  9493. imagedestroy($flat);
  9494. }
  9495. // 兜底:最小尺寸、最低质量强制输出
  9496. $resized = $this->copyAndResize($srcImage, 800);
  9497. $flat = $this->flattenToWhite($resized);
  9498. imagedestroy($resized);
  9499. $saved = imagejpeg($flat, $jpeg, 30);
  9500. imagedestroy($flat);
  9501. if (!$saved) return null;
  9502. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  9503. 'url' => $url,
  9504. 'size' => filesize($jpeg),
  9505. ]);
  9506. return $jpeg;
  9507. }
  9508. /**
  9509. * 等比缩放图片副本(不销毁原图)
  9510. * @param resource $srcImage GD图片资源
  9511. * @param int $maxEdge 最大边长
  9512. * @return resource
  9513. */
  9514. private function copyAndResize($srcImage, $maxEdge) {
  9515. $width = imagesx($srcImage);
  9516. $height = imagesy($srcImage);
  9517. $max = max($width, $height);
  9518. if ($max <= $maxEdge) {
  9519. $copy = imagecreatetruecolor($width, $height);
  9520. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  9521. return $copy;
  9522. }
  9523. $ratio = $maxEdge / $max;
  9524. $newWidth = max(1, (int)round($width * $ratio));
  9525. $newHeight = max(1, (int)round($height * $ratio));
  9526. $resized = imagecreatetruecolor($newWidth, $newHeight);
  9527. imagealphablending($resized, false);
  9528. imagesavealpha($resized, true);
  9529. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  9530. return $resized;
  9531. }
  9532. /**
  9533. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  9534. * @param resource $image GD图片资源
  9535. * @return resource
  9536. */
  9537. private function flattenToWhite($image) {
  9538. $width = imagesx($image);
  9539. $height = imagesy($image);
  9540. $flat = imagecreatetruecolor($width, $height);
  9541. $white = imagecolorallocate($flat, 255, 255, 255);
  9542. imagefill($flat, 0, 0, $white);
  9543. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  9544. return $flat;
  9545. }
  9546. /**
  9547. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  9548. * @param string $content 片段内容
  9549. * @param int $counter 当前已编号数量(引用传递,整集累计)
  9550. * @return string
  9551. */
  9552. private function renumberSegmentBlocks($content, &$counter) {
  9553. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  9554. $counter++;
  9555. return '【' . $match[1] . $counter . '】';
  9556. }, $content);
  9557. }
  9558. }