AnimeService.php 564 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177
  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. use PhpOffice\PhpSpreadsheet\IOFactory;
  23. class AnimeService
  24. {
  25. protected $aiImageGenerationService;
  26. protected $aiVideoGenerationService;
  27. protected $DeepSeekService;
  28. protected $pointsService;
  29. protected $taskCenterService;
  30. private $url;
  31. private $api_key;
  32. private $headers;
  33. public function __construct(
  34. AIImageGenerationService $aiImageGenerationService,
  35. AIVideoGenerationService $aiVideoGenerationService,
  36. DeepSeekService $DeepSeekService,
  37. PointsService $pointsService,
  38. TaskCenterService $taskCenterService
  39. ) {
  40. $this->aiImageGenerationService = $aiImageGenerationService;
  41. $this->aiVideoGenerationService = $aiVideoGenerationService;
  42. $this->DeepSeekService = $DeepSeekService;
  43. $this->pointsService = $pointsService;
  44. $this->taskCenterService = $taskCenterService;
  45. $this->url = 'https://api.deepseek.com/chat/completions';
  46. $this->api_key = env('DEEPSEEK_API_KEY');
  47. $this->headers = [
  48. 'Authorization' => 'Bearer '.$this->api_key,
  49. 'Content-Type' => 'application/json; charset=UTF-8'
  50. ];
  51. }
  52. /**
  53. * 构建统一的分镜数据结构(episodeInfo格式)
  54. * @param array $segments 分镜数据数组
  55. * @return array 返回包含acts和total_duration的数组
  56. */
  57. public function buildEpisodeSegmentsStructure($segments) {
  58. $acts = [];
  59. $totalDuration = 0; // 初始化总时长
  60. foreach($segments as $segment) {
  61. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  62. $videoDuration = getProp($segment, 'video_duration');
  63. $audioDuration = getProp($segment, 'audio_duration');
  64. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  65. $totalDuration += floatval($videoDuration);
  66. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  67. $totalDuration += floatval($audioDuration);
  68. } else {
  69. $totalDuration += 5; // 默认5秒
  70. }
  71. $segment_content = getProp($segment, 'segment_content');
  72. // 判断是否有尾帧描述,如果有则去掉这部分内容
  73. if (strpos($segment_content, '尾帧') !== false) {
  74. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  75. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  76. }
  77. // 构建分镜信息
  78. $segmentInfo = [
  79. 'segment_id' => getProp($segment, 'segment_id'),
  80. 'segment_number' => getProp($segment, 'segment_number'),
  81. 'segment_content' => $segment_content,
  82. 'description' => getProp($segment, 'description'),
  83. 'composition' => getProp($segment, 'composition'),
  84. 'camera_movement' => getProp($segment, 'camera_movement'),
  85. 'voice_actor' => getProp($segment, 'voice_actor'),
  86. 'dialogue' => getProp($segment, 'dialogue'),
  87. 'frame_type' => getProp($segment, 'frame_type'),
  88. 'scene' => getProp($segment, 'scene'),
  89. 'characters' => getProp($segment, 'characters'),
  90. 'tail_frame' => getProp($segment, 'tail_frame'),
  91. 'emotion' => getProp($segment, 'emotion'),
  92. 'emotion_type' => getProp($segment, 'emotion_type'),
  93. 'gender' => getProp($segment, 'gender'),
  94. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  95. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  96. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  97. 'pitch' => getProp($segment, 'pitch'),
  98. 'voice_name' => getProp($segment, 'voice_name'),
  99. 'voice_type' => getProp($segment, 'voice_type'),
  100. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  101. 'img_url' => getProp($segment, 'img_url'),
  102. 'audio_url' => getProp($segment, 'audio_url'),
  103. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  104. 'video_url' => getProp($segment, 'video_url'),
  105. 'video_duration' => getProp($segment, 'video_duration', 0),
  106. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  107. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  108. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  109. 'current_type' => getProp($segment, 'current_type'),
  110. ];
  111. $actNumber = getProp($segment, 'act_number');
  112. if (isset($acts[$actNumber])) {
  113. $acts[$actNumber]['segments'][] = $segmentInfo;
  114. } else {
  115. $acts[$actNumber] = [
  116. 'act_number' => $actNumber,
  117. 'act_title' => getProp($segment, 'act_title'),
  118. 'act_duration' => getProp($segment, 'act_duration'),
  119. 'segments' => [$segmentInfo]
  120. ];
  121. }
  122. }
  123. return [
  124. 'acts' => array_values($acts),
  125. 'total_duration' => intval(round($totalDuration))
  126. ];
  127. }
  128. /**
  129. * 构建统一的分段数据结构(episodeInfoForAce格式)
  130. * @param array $segments 分段数据数组
  131. * @return array 返回包含acts和total_duration的数组
  132. */
  133. public function buildEpisodeActsStructureForAce($segments) {
  134. $acts = [];
  135. $totalDuration = 0; // 初始化总时长
  136. foreach($segments as $segment) {
  137. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  138. $videoDuration = getProp($segment, 'video_duration');
  139. $actDuration = getProp($segment, 'act_duration');
  140. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  141. $totalDuration += floatval($videoDuration);
  142. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  143. $totalDuration += floatval($actDuration);
  144. } else {
  145. $totalDuration += 5; // 默认5秒
  146. }
  147. // 构建分镜信息
  148. $segmentInfo = [
  149. 'act_id' => getProp($segment, 'id'),
  150. 'act_number' => getProp($segment, 'act_number'),
  151. 'act_title' => getProp($segment, 'act_title'),
  152. 'act_duration' => getProp($segment, 'act_duration'),
  153. 'act_content' => getProp($segment, 'act_content'),
  154. 'video_url' => getProp($segment, 'video_url'),
  155. 'video_duration' => getProp($segment, 'video_duration', 0),
  156. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  157. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  158. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  159. 'current_type' => getProp($segment, 'current_type'),
  160. ];
  161. $acts[] = $segmentInfo;
  162. }
  163. return [
  164. 'acts' => array_values($acts),
  165. 'total_duration' => intval(round($totalDuration))
  166. ];
  167. }
  168. /**
  169. * 验证画面比例是否有效
  170. * @param string $ratio 画面比例
  171. * @return bool
  172. */
  173. public function validateRatio($ratio) {
  174. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  175. }
  176. /**
  177. * 获取画面比例对应的宽高
  178. * @param string $ratio 画面比例
  179. * @return array ['width' => int, 'height' => int]
  180. * @throws \Exception
  181. */
  182. private function getRatioDimensions($ratio) {
  183. if ($ratio && !$this->validateRatio($ratio)) {
  184. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  185. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  186. }
  187. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  188. }
  189. public function createAnime($data) {
  190. $uid = Site::getUid();
  191. $cpid = Site::getCpid();
  192. $input_art_style = getProp($data, 'art_style');
  193. $file = getProp($data, 'file');
  194. $content = getProp($data, 'content', '');
  195. $bid = getProp($data, 'bid', 0);
  196. $script_id = getProp($data, 'script_id', 0);
  197. $ace_mode = getProp($data, 'ace_mode', 0);
  198. $extra_products = getProp($data, 'products', []);
  199. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  200. if (!is_array($extra_products)) {
  201. Utils::throwError('20003:传入的资产格式不正确');
  202. }
  203. // 替换美术风格
  204. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  205. // 提取文件内容
  206. if ($file) {
  207. $content = $this->DeepSeekService->extractFileContent($file);
  208. if (!$content) {
  209. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  210. }
  211. } elseif ($script_id) {
  212. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  213. if (!$content) {
  214. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  215. }
  216. } elseif ($bid) {
  217. $content = $this->DeepSeekService->getContentByBid($bid);
  218. if (!$content) {
  219. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  220. }
  221. } elseif ($content) {
  222. $content = filterContent($content);
  223. }else {
  224. $content = '';
  225. }
  226. $anime_data = [
  227. 'user_id' => $uid,
  228. 'cpid' => $cpid,
  229. 'anime_name' => '新剧本策划',
  230. 'is_multi' => getProp($data, 'is_multi', 1),
  231. 'content' => $content,
  232. 'art_style_type' => $input_art_style,
  233. 'ace_mode' => $ace_mode,
  234. 'script_id' => $script_id,
  235. 'extra_products' => json_encode($extra_products, 256),
  236. 'created_at' => date('Y-m-d H:i:s'),
  237. 'updated_at' => date('Y-m-d H:i:s'),
  238. ];
  239. // 处理文本模型
  240. $model = getProp($data, 'model');
  241. if (!$model) {
  242. // 用户没有输入,使用默认值
  243. $model = 'deepseek-v4-pro';
  244. }
  245. // 验证模型是否在可用模型表中
  246. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  247. $model = 'deepseek-v4-pro';
  248. }
  249. $anime_data['model'] = $model;
  250. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  251. return DB::table('mp_animes')->insertGetId($anime_data);
  252. }
  253. public function chatList($data) {
  254. $uid = Site::getUid();
  255. $anime_name = getProp($data, 'anime_name');
  256. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  257. if ($anime_name) {
  258. $query->where('anime_name', 'like', "%$anime_name%");
  259. }
  260. return $query->orderBy('id', 'desc')->paginate();
  261. }
  262. public function chatHistory($data) {
  263. $anime_id = getProp($data, 'anime_id');
  264. $sequence = getProp($data, 'sequence', 0);
  265. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  266. $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)
  267. ->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');
  268. return $query->orderBy('ar.id')->get()->map(function ($value) {
  269. $value = (array)$value;
  270. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  271. $value['created_at'] = transDate($value['created_at']);
  272. $value['episode_created_at'] = transDate($value['episode_created_at']);
  273. return $value;
  274. })->toArray();
  275. }
  276. public function batchSetRoleImg($data) {
  277. $episode_id = getProp($data, 'episode_id');
  278. if (!$episode_id) Utils::throwError('1002:请选择分集');
  279. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  280. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  281. $art_style = getProp($episode, 'art_style');
  282. $anime_id = getProp($episode, 'anime_id');
  283. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  284. $art_style_type = getProp($anime, 'art_style_type');
  285. $character_prefix = '';
  286. $scene_prefix = '';
  287. if ($art_style_type) {
  288. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  289. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  290. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  291. }
  292. foreach ($roles as &$role) {
  293. $role_name = getProp($role, 'role');
  294. if ($role_name == '旁白') continue;
  295. // 优先使用 pic_prompt,如果没有则使用 description
  296. $pic_prompt = getProp($role, 'pic_prompt');
  297. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  298. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  299. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  300. // 参考图地址
  301. $ref_img_url = getProp($role, 'url');
  302. if ($ref_img_url) continue; // 已有图片则跳过
  303. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  304. try {
  305. $params = [
  306. 'prompt' => $description,
  307. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  308. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  309. 'anime_id' => $anime_id,
  310. 'episode_id' => $episode_id,
  311. 'episode_number' => getProp($episode, 'episode_number'),
  312. ];
  313. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  314. $task_id = $task->id;
  315. if (!$task_id) {
  316. Utils::throwError("20003:角色({$role_name})生成图片失败");
  317. }
  318. $role['task_id'] = $task_id;
  319. $role['task_status'] = 'processing';
  320. } catch (\Exception $e) {
  321. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  322. Utils::throwError("20003:" . $e->getMessage());
  323. }
  324. }
  325. // 保存角色信息
  326. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  327. 'roles' => json_encode($roles, 256),
  328. 'generate_status' => '执行中',
  329. 'generate_at' => date('Y-m-d H:i:s'),
  330. 'updated_at' => date('Y-m-d H:i:s')
  331. ]);
  332. if (!$boolen) {
  333. Utils::throwError('20003:保存角色信息失败');
  334. }
  335. return $boolen;
  336. }
  337. public function batchSetSceneImg($data) {
  338. $episode_id = getProp($data, 'episode_id');
  339. if (!$episode_id) Utils::throwError('1002:请选择分集');
  340. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  341. $scenes = json_decode(getProp($episode, 'scenes'), true);
  342. $art_style = getProp($episode, 'art_style');
  343. $target_scene = getProp($data, 'target_scene');
  344. $anime_id = getProp($episode, 'anime_id');
  345. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  346. $art_style_type = getProp($anime, 'art_style_type');
  347. $character_prefix = '';
  348. $scene_prefix = '';
  349. if ($art_style_type) {
  350. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  351. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  352. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  353. }
  354. foreach ($scenes as &$scene) {
  355. $scene_name = getProp($scene, 'scene');
  356. if ($scene_name != $target_scene) continue;
  357. // 优先使用 pic_prompt,如果没有则使用 description
  358. $pic_prompt = getProp($scene, 'pic_prompt');
  359. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  360. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  361. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  362. // 参考图地址
  363. $ref_img_url = getProp($scene, 'url');
  364. if ($ref_img_url) continue; // 已有图片则跳过
  365. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  366. try {
  367. $params = [
  368. 'prompt' => $description,
  369. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  370. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  371. 'anime_id' => $anime_id,
  372. 'episode_id' => $episode_id,
  373. 'episode_number' => getProp($episode, 'episode_number'),
  374. ];
  375. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  376. $task_id = $task->id;
  377. if (!$task_id) {
  378. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  379. }
  380. $scene['task_id'] = $task_id;
  381. $scene['task_status'] = 'processing';
  382. } catch (\Exception $e) {
  383. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  384. Utils::throwError("20003:" . $e->getMessage());
  385. }
  386. }
  387. // 保存场景信息
  388. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  389. 'scenes' => json_encode($scenes, 256),
  390. 'generate_status' => '执行中',
  391. 'generate_at' => date('Y-m-d H:i:s'),
  392. 'updated_at' => date('Y-m-d H:i:s')
  393. ]);
  394. if (!$boolen) {
  395. Utils::throwError('20003:保存角色信息失败');
  396. }
  397. return $boolen;
  398. }
  399. public function editAnime($data) {
  400. $anime_id = getProp($data, 'anime_id');
  401. $anime_name = trim(getProp($data, 'anime_name'));
  402. // 确认对话名称唯一性
  403. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  404. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  405. }
  406. if (!$anime_id || !$anime_name) {
  407. Utils::throwError('20003:参数异常');
  408. }
  409. return DB::table('mp_animes')->where('id', $anime_id)->update([
  410. 'anime_name' => $anime_name,
  411. 'updated_at' => date('Y-m-d H:i:s')
  412. ]);
  413. // $script_arr =getProp($data, 'script', []);
  414. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  415. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  416. // $anime_id = getProp($data, 'anime_id');
  417. // try {
  418. // DB::beginTransaction();
  419. // $table_data = [
  420. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  421. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  422. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  423. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  424. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  425. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  426. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  427. // 'status' => 3,
  428. // 'start_episode_sequence' => $start_episode_sequence,
  429. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  430. // 'episode_num' => count($script_arr['episodes']),
  431. // 'updated_at' => date('Y-m-d H:i:s')
  432. // ];
  433. // // 保存剧本内容
  434. // if (!empty($anime_id)) {
  435. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  436. // if (!$boolen) {
  437. // dLog('anime')->info('对话保存失败', $table_data);
  438. // Utils::throwError('20003:对话保存失败');
  439. // }
  440. // }else {
  441. // $table['created_at'] = $table_data['updated_at'];
  442. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  443. // if (!$anime_id) {
  444. // dLog('anime')->info('对话保存失败', $table_data);
  445. // Utils::throwError('20003:对话保存失败');
  446. // }
  447. // }
  448. // // 保存分集内容
  449. // // 删除历史分集内容
  450. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  451. // $episodes = [];
  452. // $sequence = 1;
  453. // foreach ($script_arr['episodes'] as $episode) {
  454. // $segment_number = 1;
  455. // foreach($episode['segments'] as $segment) {
  456. // $episodes[] = [
  457. // 'anime_id' => $anime_id,
  458. // 'episode_number' => $episode['episode_number'],
  459. // 'title' => $episode['title'],
  460. // // 'content' => $episode['content'],
  461. // 'content' => '',
  462. // 'segment_number' => $segment_number,
  463. // 'segment_content' => $segment['segment_content'],
  464. // 'sequence' => $sequence,
  465. // 'created_at' => date('Y-m-d H:i:s'),
  466. // 'updated_at' => date('Y-m-d H:i:s')
  467. // ];
  468. // $sequence++;
  469. // $segment_number++;
  470. // }
  471. // }
  472. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  473. // if (!$boolen2) {
  474. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  475. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  476. // Utils::throwError('20003:分集内容保存失败');
  477. // }
  478. // } catch (\Exception $e) {
  479. // DB::rollBack();
  480. // Utils::throwError('20003:'.$e->getMessage());
  481. // }
  482. // DB::commit();
  483. // return true;
  484. }
  485. public function delAnime($data) {
  486. $anime_id = getProp($data, 'anime_id');
  487. if (!$anime_id) {
  488. Utils::throwError('20003:请选择剧本');
  489. }
  490. return DB::table('mp_animes')->where('id', $anime_id)->update([
  491. 'is_deleted' => 1,
  492. 'updated_at' => date('Y-m-d H:i:s')
  493. ]);
  494. }
  495. public function animeDetail($data) {
  496. $uid = Site::getUid();
  497. $anime_id = getProp($data, 'anime_id');
  498. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  499. ->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();
  500. if (!$anime) Utils::throwError('20003:权限不足');
  501. $anime = (array)$anime;
  502. $anime['roles'] = json_decode($anime['roles']);
  503. $anime['scenes'] = json_decode($anime['scenes']);
  504. // 获取分集信息
  505. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  506. ->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"))
  507. ->orderBy('episode_number')->get()->map(function ($value) {
  508. return (array)$value;
  509. })->toArray();
  510. $anime['episodes'] = $episodes;
  511. // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
  512. $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
  513. $episodeTasks = DB::table('mp_batch_episode_generation_details')
  514. ->where('anime_id', $anime_id)
  515. ->whereIn('status', ['pending', 'processing', 'failed']) // 只获取待生成/生成中任务,已完成或失败的不显示
  516. ->orderBy('episode_number')
  517. ->get()
  518. ->map(function ($task) use ($episodeNumbers) {
  519. if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
  520. return null;
  521. }
  522. return [
  523. 'episode_number' => (int)$task->episode_number,
  524. 'status' => $task->status,
  525. 'error_message' => $task->status == 'failed' ? $task->error_message : '',
  526. ];
  527. })
  528. ->filter()
  529. ->values()
  530. ->toArray();
  531. $anime['episode_tasks'] = $episodeTasks;
  532. return $anime;
  533. }
  534. public function episodeInfo($data) {
  535. $uid = Site::getUid();
  536. $anime_id = getProp($data, 'anime_id');
  537. $episode_id = getProp($data, 'episode_id');
  538. if (!$anime_id || !$episode_id) {
  539. Utils::throwError('1002:请选择剧集');
  540. }
  541. // 验证用户权限
  542. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  543. if (!$anime) Utils::throwError('20003:权限不足');
  544. $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();
  545. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  546. $episode = (array)$episode;
  547. $episode['roles'] = json_decode($episode['roles'], true);
  548. // foreach($episode['roles'] as &$item) {
  549. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  550. // }
  551. $episode['scenes'] = json_decode($episode['scenes'], true);
  552. // foreach($episode['scenes'] as &$item) {
  553. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  554. // }
  555. // 获取分镜信息
  556. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  557. ->select('*')->get()->map(function ($value) {
  558. return (array)$value;
  559. })->toArray();
  560. // 使用公共方法构建分镜结构
  561. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  562. $episode['acts'] = $segmentsStructure['acts'];
  563. $episode['total_duration'] = $segmentsStructure['total_duration'];
  564. return $episode;
  565. }
  566. public function episodeInfoForAce($data) {
  567. $anime_id = getProp($data, 'anime_id');
  568. $episode_id = getProp($data, 'episode_id');
  569. if (!$anime_id || !$episode_id) {
  570. Utils::throwError('1002:请选择剧集');
  571. }
  572. $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();
  573. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  574. $episode = (array)$episode;
  575. $episode['roles'] = json_decode($episode['roles'], true);
  576. // foreach($episode['roles'] as &$item) {
  577. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  578. // }
  579. $episode['scenes'] = json_decode($episode['scenes'], true);
  580. // foreach($episode['scenes'] as &$item) {
  581. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  582. // }
  583. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  584. // 获取分镜信息
  585. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  586. ->select('*')->get()->map(function ($value) {
  587. return (array)$value;
  588. })->toArray();
  589. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  590. $episode['acts'] = $segmentsStructure['acts'];
  591. $episode['total_duration'] = $segmentsStructure['total_duration'];
  592. // 获取mp_animes表中的视频参数
  593. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  594. $episode['video_params'] = [
  595. 'video_model' => getProp($anime, 'video_model'),
  596. 'video_resolution' => getProp($anime, 'video_resolution'),
  597. 'ratio' => getProp($anime, 'video_ratio'),
  598. ];
  599. return $episode;
  600. }
  601. public function segmentInfo($data) {
  602. $uid = Site::getUid();
  603. $segment_id = getProp($data, 'segment_id');
  604. if (!$segment_id) {
  605. Utils::throwError('1002:请选择分镜');
  606. }
  607. // 获取分镜信息
  608. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  609. // 验证用户权限
  610. if ($segment) {
  611. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  612. if (!$anime) Utils::throwError('20003:权限不足');
  613. }
  614. $result = [
  615. 'segment_id' => getProp($segment, 'segment_id'),
  616. 'segment_number' => getProp($segment, 'segment_number'),
  617. 'segment_content' => getProp($segment, 'segment_content'),
  618. 'description' => getProp($segment, 'description'),
  619. 'composition' => getProp($segment, 'composition'),
  620. 'camera_movement' => getProp($segment, 'camera_movement'),
  621. 'voice_actor' => getProp($segment, 'voice_actor'),
  622. 'dialogue' => getProp($segment, 'dialogue'),
  623. 'frame_type' => getProp($segment, 'frame_type'),
  624. 'scene' => getProp($segment, 'scene'),
  625. 'characters' => getProp($segment, 'characters'),
  626. 'tail_frame' => getProp($segment, 'tail_frame'),
  627. 'emotion' => getProp($segment, 'emotion'),
  628. 'emotion_type' => getProp($segment, 'emotion_type'),
  629. 'gender' => getProp($segment, 'gender'),
  630. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  631. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  632. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  633. 'pitch' => getProp($segment, 'pitch'),
  634. 'voice_name' => getProp($segment, 'voice_name'),
  635. 'voice_type' => getProp($segment, 'voice_type'),
  636. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  637. 'img_url' => getProp($segment, 'img_url'),
  638. 'video_url' => getProp($segment, 'video_url'),
  639. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  640. ];
  641. return $result;
  642. }
  643. public function copyEpisodeVersion($data) {
  644. $episode_id = getProp($data, 'episode_id');
  645. $uid = Site::getUid();
  646. $cpid = Site::getCpid();
  647. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  648. if (!$episode) Utils::throwError('20003:该剧集不存在');
  649. $episode = (array)$episode;
  650. $anime_id = $episode['anime_id'];
  651. $episode_number = $episode['episode_number'];
  652. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  653. $sequence = $count + 1;
  654. unset($episode['id']);
  655. $now = date('Y-m-d H:i:s');
  656. $episode['created_at'] = $now;
  657. $episode['updated_at'] = $now;
  658. $episode['is_default'] = 1;
  659. // 获取版本中含有"(副本"字样的个数
  660. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  661. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  662. $episode['sequence'] = $sequence;
  663. $episode['is_generated'] = 0;
  664. $episode['cpid'] = $cpid;
  665. // 获取ace_mode
  666. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  667. try {
  668. DB::beginTransaction();
  669. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  670. // 新增副本
  671. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  672. if (!$new_episode_id) {
  673. Utils::throwError('20003:创建副本失败!');
  674. }
  675. // 获取分镜数据并准备插入
  676. $segments_for_insert = DB::table('mp_episode_segments')
  677. ->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')
  678. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  679. $item = (array)$item;
  680. $item['episode_id'] = $new_episode_id;
  681. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  682. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  683. return $item;
  684. })->toArray();
  685. // 写入分镜数据
  686. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  687. if (!$boolen2) {
  688. Utils::throwError('20003:写入分镜数据失败!');
  689. }
  690. // 写入对话历史
  691. $records = [
  692. [
  693. 'uid' => $uid,
  694. 'anime_id' => $anime_id,
  695. 'role' => 'user',
  696. 'content' => '创建副本',
  697. 'sequence' => $episode_number,
  698. 'episode_id' => $new_episode_id,
  699. 'created_at' => $now,
  700. 'updated_at' => $now
  701. ],
  702. [
  703. 'uid' => $uid,
  704. 'anime_id' => $anime_id,
  705. 'role' => 'assistant',
  706. 'content' => '好的,已为您创建副本',
  707. 'sequence' => $episode_number,
  708. 'episode_id' => $new_episode_id,
  709. 'created_at' => $now,
  710. 'updated_at' => $now
  711. ]
  712. ];
  713. $boolen3 = DB::table('mp_anime_records')->insert($records);
  714. if (!$boolen3) {
  715. Utils::throwError('20003:对话记录保存失败');
  716. }
  717. }catch (\Exception $e) {
  718. DB::rollBack();
  719. Utils::throwError('20003:'.$e->getMessage());
  720. }
  721. DB::commit();
  722. // 构建与 episodeInfo 方法一致的返回数据结构
  723. $result = [
  724. 'episode_id' => $new_episode_id,
  725. 'anime_id' => $anime_id,
  726. 'episode_number' => $episode_number,
  727. 'title' => $episode['title'],
  728. 'intro' => $episode['intro'],
  729. 'art_style' => $episode['art_style'],
  730. 'roles' => json_decode($episode['roles'], true),
  731. 'scenes' => json_decode($episode['scenes'], true),
  732. 'is_generated' => (int)$episode['is_generated']
  733. ];
  734. if ((int)$ace_mode === 1) {
  735. // 获取分镜信息
  736. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  737. ->select('*')->get()->map(function ($value) {
  738. return (array)$value;
  739. })->toArray();
  740. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  741. }else {
  742. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  743. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  744. }
  745. $result['acts'] = $segmentsStructure['acts'];
  746. $result['total_duration'] = $segmentsStructure['total_duration'];
  747. return $result;
  748. }
  749. public function episodeVersions($data) {
  750. $anime_id = getProp($data, 'anime_id');
  751. $episode_id = getProp($data, 'episode_id');
  752. if (!$anime_id || !$episode_id) {
  753. Utils::throwError('1002:请选择剧集');
  754. }
  755. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  756. $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) {
  757. return (array)$value;
  758. })->toArray();
  759. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  760. foreach($episodes as &$episode) {
  761. $episode['version'] = 'V'.$episode['sequence'];
  762. $episode['roles'] = json_decode($episode['roles'], true);
  763. $episode['scenes'] = json_decode($episode['scenes'], true);
  764. // 获取分镜信息
  765. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  766. ->select('*')->get()->map(function ($value) {
  767. return (array)$value;
  768. })->toArray();
  769. // 使用公共方法构建分镜结构
  770. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  771. $episode['acts'] = $segmentsStructure['acts'];
  772. $episode['total_duration'] = $segmentsStructure['total_duration'];
  773. }
  774. return $episodes;
  775. }
  776. public function bindEpisodeVersion($data) {
  777. $episode_id = getProp($data, 'episode_id');
  778. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  779. if (!$episode) Utils::throwError('20003:该剧集不存在');
  780. $episode = (array)$episode;
  781. if ((int)$episode['is_default'] === 1) return true;
  782. try {
  783. DB::beginTransaction();
  784. // 移除is_default标志
  785. $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')]);
  786. if (!$boolen) {
  787. Utils::throwError('20003:更新失败!');
  788. }
  789. // 绑定副本
  790. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  791. if (!$boolen2) {
  792. Utils::throwError('20003:绑定失败!');
  793. }
  794. }catch (\Exception $e) {
  795. DB::rollBack();
  796. Utils::throwError('20003:'.$e->getMessage());
  797. }
  798. DB::commit();
  799. return true;
  800. }
  801. public function chatChangeImg($data) {
  802. $segment_id = getProp($data, 'segment_id');
  803. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  804. $prompt = getProp($data, 'prompt');
  805. if (!$prompt || !$segment_id) {
  806. Utils::throwError('1002:请输入提示词,并且选择分镜');
  807. }
  808. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  809. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  810. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  811. else $ref_img_url = '';
  812. // $ref_img_url = '';
  813. if (empty($prompt)) {
  814. if (empty($ref_img_url)) {
  815. $prompt = getProp($segment, 'segment_content');
  816. }else {
  817. $prompt = '请根据图片生成';
  818. }
  819. }
  820. $anime_id = getProp($segment, 'anime_id');
  821. $episode_id = getProp($segment, 'episode_id');
  822. $episode_number = getProp($segment, 'episode_number');
  823. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  824. $ratio = getProp($data, 'ratio');
  825. if (!$ratio) {
  826. $ratio = getProp($episode, 'ratio');
  827. if (!$ratio) $ratio = '9:16';
  828. }
  829. $art_style = getProp($episode, 'art_style');
  830. if ($art_style) {
  831. $prompt = "美术风格:{$art_style}\n{$prompt}";
  832. }
  833. $dimensions = $this->getRatioDimensions($ratio);
  834. $width = $dimensions['width'];
  835. $height = $dimensions['height'];
  836. try {
  837. $params = [
  838. 'alias_segment_id' => $segment_id,
  839. 'prompt' => $prompt,
  840. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  841. 'width' => $width,
  842. 'height' => $height
  843. ];
  844. // 优化提示词(不要生成字幕)
  845. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  846. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  847. $task_id = $task->id;
  848. if (!$task_id) {
  849. Utils::throwError("20003:生成图片失败");
  850. }
  851. // 更新任务ID
  852. $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')]);
  853. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  854. } catch (\Exception $e) {
  855. Utils::throwError("20003:" . $e->getMessage());
  856. }
  857. // 创建任务之后先暂停10s等待异步任务完成
  858. sleep(10);
  859. $img_url = $this->loopGetPicTaskResult($task_id);
  860. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  861. // 图片生成后新增对话记录
  862. try {
  863. $uid = Site::getUid();
  864. $now = date('Y-m-d H:i:s');
  865. // 使用AI反推图片提示词
  866. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  867. // 保存对话记录
  868. $records = [
  869. [
  870. 'uid' => $uid,
  871. 'anime_id' => $anime_id,
  872. 'sequence' => $episode_number,
  873. 'role' => 'user',
  874. 'content' => $prompt,
  875. 'segment_id' => $segment_id,
  876. 'pic_task_id' => $task_id,
  877. 'image_url' => '',
  878. 'created_at' => $now,
  879. 'updated_at' => $now
  880. ],
  881. [
  882. 'uid' => $uid,
  883. 'anime_id' => $anime_id,
  884. 'sequence' => $episode_number,
  885. 'role' => 'assistant',
  886. 'content' => $pic_prompt,
  887. 'segment_id' => $segment_id,
  888. 'pic_task_id' => $task_id,
  889. 'image_url' => $img_url,
  890. 'created_at' => $now,
  891. 'updated_at' => $now
  892. ]
  893. ];
  894. DB::table('mp_anime_records')->insert($records);
  895. } catch (\Exception $e) {
  896. // 记录日志但不影响主流程
  897. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  898. 'segment_id' => $segment_id,
  899. 'img_url' => $img_url
  900. ]);
  901. logDB('anime', 'error', '保存对话记录失败', [
  902. 'segment_id' => $segment_id,
  903. 'img_url' => $img_url,
  904. 'error' => $e->getMessage()
  905. ]);
  906. }
  907. return $img_url;
  908. }
  909. public function segmentChatHistory($data) {
  910. $segment_id = getProp($data, 'segment_id');
  911. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  912. $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');
  913. $chat = $query->orderBy('id')->get()->map(function ($value) {
  914. $value = (array)$value;
  915. $value['created_at'] = transDate($value['created_at']);
  916. return $value;
  917. })->toArray();
  918. // 获取历史图片
  919. $url = [];
  920. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  921. foreach($pic_history as $task) {
  922. $result_url = getProp($task, 'result_url');
  923. if (is_json($result_url)) {
  924. $url = array_merge($url, json_decode($result_url, true));
  925. }else {
  926. $url[] = $result_url;
  927. }
  928. }
  929. // 获取历史视频
  930. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  931. foreach($video_history as $task) {
  932. $result_url = getProp($task, 'compressed_url');
  933. if (is_json($result_url)) {
  934. $url = array_merge($url, json_decode($result_url, true));
  935. }else {
  936. $url[] = $result_url;
  937. }
  938. }
  939. return compact('chat', 'url');
  940. }
  941. public function changeEpisodeRoles($data) {
  942. $anime_id = getProp($data, 'anime_id');
  943. $episode_id = getProp($data, 'episode_id');
  944. $target_roles = getProp($data, 'roles');
  945. // 删除标志优先取最外层入参 is_deleted,兼容角色对象内部(roles.is_deleted)的传参
  946. $is_deleted = getProp($data, 'is_deleted', getProp($target_roles, 'is_deleted', 0));
  947. // 控制字段不随角色内容写入分集roles存储
  948. if (is_array($target_roles)) {
  949. unset($target_roles['is_deleted']);
  950. }
  951. // 参数验证
  952. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  953. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  954. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  955. // 验证剧集是否存在
  956. $episode = DB::table('mp_anime_episodes')
  957. ->where('anime_id', $anime_id)
  958. ->where('id', $episode_id)
  959. ->first();
  960. if (!$episode) Utils::throwError('20003:该剧集不存在');
  961. $roles = json_decode(getProp($episode, 'roles'), true);
  962. // 获取anime信息,检查是否有关联的script_id
  963. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  964. if (!$anime) Utils::throwError('20003:动漫不存在');
  965. $script_id = getProp($anime, 'script_id');
  966. $episode_number = getProp($episode, 'episode_number', 1);
  967. $uid = Site::getUid();
  968. $cpid = Site::getCpid();
  969. try {
  970. $target_role_name = getProp($target_roles, 'role');
  971. if (empty($target_role_name)) {
  972. Utils::throwError('20003:角色名称不能为空');
  973. }
  974. // 如果是删除操作
  975. if ($is_deleted == 1) {
  976. // 从角色列表中移除该角色
  977. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  978. return getProp($role, 'role') !== $target_role_name;
  979. }));
  980. // 更新角色列表
  981. $result = DB::table('mp_anime_episodes')
  982. ->where('anime_id', $anime_id)
  983. ->where('id', $episode_id)
  984. ->update([
  985. 'roles' => json_encode($roles, 256),
  986. 'updated_at' => date('Y-m-d H:i:s')
  987. ]);
  988. if ($result === false) {
  989. Utils::throwError('20003:删除角色失败');
  990. }
  991. } else {
  992. // 新增或更新操作
  993. $role_found = false;
  994. $is_new_role = false;
  995. // 查找并更新已存在的角色
  996. foreach($roles as &$role) {
  997. if (getProp($role, 'role') === $target_role_name) {
  998. $role = $target_roles;
  999. $role_found = true;
  1000. break;
  1001. }
  1002. }
  1003. // 如果角色不存在,则新增
  1004. if (!$role_found) {
  1005. $roles[] = $target_roles;
  1006. $is_new_role = true;
  1007. }
  1008. // 更新角色列表
  1009. $result = DB::table('mp_anime_episodes')
  1010. ->where('anime_id', $anime_id)
  1011. ->where('id', $episode_id)
  1012. ->update([
  1013. 'roles' => json_encode($roles, 256),
  1014. 'updated_at' => date('Y-m-d H:i:s')
  1015. ]);
  1016. if ($result === false) {
  1017. Utils::throwError('20003:更新角色列表失败');
  1018. }
  1019. // 同步更新分镜表中对应主体的音色信息
  1020. $voice_name = getProp($target_roles, 'voice_name');
  1021. $voice_type = getProp($target_roles, 'voice_type');
  1022. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  1023. DB::table('mp_episode_segments')
  1024. ->where('anime_id', $anime_id)
  1025. ->where('episode_id', $episode_id)
  1026. ->where('voice_actor', $target_role_name)
  1027. ->update([
  1028. 'voice_name' => $voice_name,
  1029. 'voice_type' => $voice_type,
  1030. 'voice_audio_url' => $voice_audio_url,
  1031. 'updated_at' => date('Y-m-d H:i:s')
  1032. ]);
  1033. // 如果有关联的script_id,则同步到mp_products表
  1034. if ($script_id) {
  1035. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1036. $script = DB::table('mp_scripts')
  1037. ->where('id', $script_id)
  1038. ->where('user_id', $uid)
  1039. ->where('is_deleted', 0)
  1040. ->first();
  1041. if ($script) {
  1042. $script_name = $script->script_name ?? 'script_' . $script_id;
  1043. $product_name = getProp($target_roles, 'role');
  1044. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1045. $url = getProp($target_roles, 'url', '');
  1046. $three_view_image_url = trim(getProp($target_roles, 'three_view_image_url', ''));
  1047. $timbre_url = trim(getProp($target_roles, 'timbre_url', ''));
  1048. // 兼容 versions 传入数组或 JSON 字符串
  1049. $versions = getProp($target_roles, 'versions', null);
  1050. if (is_string($versions) && $versions !== '') {
  1051. $decoded_versions = json_decode($versions, true);
  1052. if (is_array($decoded_versions)) {
  1053. $versions = $decoded_versions;
  1054. }
  1055. }
  1056. $product_type = 1; // 1=角色
  1057. // 查找或创建以script_name命名的文件夹
  1058. $folder = DB::table('mp_products')
  1059. ->where('cpid', $cpid)
  1060. ->where('type', 2) // 文件夹类型
  1061. ->where('product', $product_type) // 角色类型
  1062. ->where('product_name', $script_name)
  1063. ->where('parent_id', 0)
  1064. ->where('is_deleted', 0)
  1065. ->first();
  1066. if (!$folder) {
  1067. // 创建文件夹
  1068. $folder_id = DB::table('mp_products')->insertGetId([
  1069. 'user_id' => $uid,
  1070. 'cpid' => $cpid,
  1071. 'type' => 2, // 文件夹
  1072. 'product' => $product_type, // 角色类型
  1073. 'parent_id' => 0,
  1074. 'level' => 1,
  1075. 'product_name' => $script_name,
  1076. 'sort_order' => time(),
  1077. 'is_deleted' => 0,
  1078. 'created_at' => date('Y-m-d H:i:s'),
  1079. 'updated_at' => date('Y-m-d H:i:s')
  1080. ]);
  1081. } else {
  1082. $folder_id = $folder->id;
  1083. }
  1084. // 查找该文件夹下是否已存在同名资产
  1085. $existing_product = DB::table('mp_products')
  1086. ->where('cpid', $cpid)
  1087. ->where('type', 1) // 资产类型
  1088. ->where('product', $product_type)
  1089. ->where('parent_id', $folder_id)
  1090. ->where('product_name', $product_name)
  1091. ->where('is_deleted', 0)
  1092. ->first();
  1093. if ($existing_product) {
  1094. // 更新已存在的资产
  1095. $updateData = [
  1096. 'pic_task_status' => '生成成功',
  1097. ];
  1098. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1099. if ($url) $updateData['url'] = $url;
  1100. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1101. if (is_array($target_roles) && array_key_exists('three_view_image_url', $target_roles)) {
  1102. $updateData['three_view_image_url'] = trim(getProp($target_roles, 'three_view_image_url', ''));
  1103. }
  1104. // 显式传入音色(含空值)时同步写入,空值表示清除该资产的音色
  1105. if (is_array($target_roles) && array_key_exists('timbre_url', $target_roles)) {
  1106. $updateData['timbre_url'] = trim(getProp($target_roles, 'timbre_url', ''));
  1107. }
  1108. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1109. if (is_array($versions)) {
  1110. $updateData['versions'] = json_encode($versions, 256);
  1111. }
  1112. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1113. DB::table('mp_products')
  1114. ->where('id', $existing_product->id)
  1115. ->update($updateData);
  1116. $product_id = $existing_product->id;
  1117. } else {
  1118. // 创建新资产
  1119. $product_id = DB::table('mp_products')->insertGetId([
  1120. 'user_id' => $uid,
  1121. 'cpid' => $cpid,
  1122. 'type' => 1, // 资产
  1123. 'product' => $product_type, // 角色
  1124. 'parent_id' => $folder_id,
  1125. 'level' => 2,
  1126. 'product_name' => $product_name,
  1127. 'url' => $url,
  1128. 'three_view_image_url' => $three_view_image_url,
  1129. 'timbre_url' => $timbre_url,
  1130. 'pic_prompt' => $pic_prompt,
  1131. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1132. 'sort_order' => time(),
  1133. 'is_deleted' => 0,
  1134. 'pic_task_status' => '生成成功',
  1135. 'created_at' => date('Y-m-d H:i:s'),
  1136. 'updated_at' => date('Y-m-d H:i:s')
  1137. ]);
  1138. }
  1139. // 建立或更新绑定关系
  1140. $existing_mapping = DB::table('mp_script_product_mappings')
  1141. ->where('script_id', $script_id)
  1142. ->where('product_id', $product_id)
  1143. ->where('episode_number', $episode_number)
  1144. ->first();
  1145. if (!$existing_mapping) {
  1146. // 创建绑定关系
  1147. DB::table('mp_script_product_mappings')->insert([
  1148. 'script_id' => $script_id,
  1149. 'product_id' => $product_id,
  1150. 'episode_number' => $episode_number,
  1151. 'created_at' => date('Y-m-d H:i:s'),
  1152. 'updated_at' => date('Y-m-d H:i:s')
  1153. ]);
  1154. }
  1155. }
  1156. }
  1157. }
  1158. } catch (\Exception $e) {
  1159. dLog('anime')->error('更新剧集角色失败', [
  1160. 'anime_id' => $anime_id,
  1161. 'episode_id' => $episode_id,
  1162. 'error' => $e->getMessage()
  1163. ]);
  1164. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1165. }
  1166. return true;
  1167. }
  1168. public function changeEpisodeScenes($data) {
  1169. $anime_id = getProp($data, 'anime_id');
  1170. $episode_id = getProp($data, 'episode_id');
  1171. $target_scenes = getProp($data, 'scenes');
  1172. // 删除标志优先取最外层入参 is_deleted,兼容场景对象内部(scenes.is_deleted)的传参
  1173. $is_deleted = getProp($data, 'is_deleted', getProp($target_scenes, 'is_deleted', 0));
  1174. // 控制字段不随场景内容写入分集scenes存储
  1175. if (is_array($target_scenes)) {
  1176. unset($target_scenes['is_deleted']);
  1177. }
  1178. // 参数验证
  1179. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1180. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1181. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1182. // 验证剧集是否存在
  1183. $episode = DB::table('mp_anime_episodes')
  1184. ->where('anime_id', $anime_id)
  1185. ->where('id', $episode_id)
  1186. ->first();
  1187. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1188. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1189. // 获取anime信息,检查是否有关联的script_id
  1190. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1191. if (!$anime) Utils::throwError('20003:动漫不存在');
  1192. $script_id = getProp($anime, 'script_id');
  1193. $episode_number = getProp($episode, 'episode_number', 1);
  1194. $uid = Site::getUid();
  1195. $cpid = Site::getCpid();
  1196. try {
  1197. $target_scene_name = getProp($target_scenes, 'scene');
  1198. if (empty($target_scene_name)) {
  1199. Utils::throwError('20003:场景名称不能为空');
  1200. }
  1201. // 如果是删除操作
  1202. if ($is_deleted == 1) {
  1203. // 从场景列表中移除该场景
  1204. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1205. return getProp($scene, 'scene') !== $target_scene_name;
  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. } else {
  1219. // 新增或更新操作
  1220. $scene_found = false;
  1221. $is_new_scene = false;
  1222. // 查找并更新已存在的场景
  1223. foreach($scenes as &$scene) {
  1224. if (getProp($scene, 'scene') === $target_scene_name) {
  1225. $scene = $target_scenes;
  1226. $scene_found = true;
  1227. break;
  1228. }
  1229. }
  1230. // 如果场景不存在,则新增
  1231. if (!$scene_found) {
  1232. $scenes[] = $target_scenes;
  1233. $is_new_scene = true;
  1234. }
  1235. // 更新场景列表
  1236. $result = DB::table('mp_anime_episodes')
  1237. ->where('anime_id', $anime_id)
  1238. ->where('id', $episode_id)
  1239. ->update([
  1240. 'scenes' => json_encode($scenes, 256),
  1241. 'updated_at' => date('Y-m-d H:i:s')
  1242. ]);
  1243. if ($result === false) {
  1244. Utils::throwError('20003:更新场景列表失败');
  1245. }
  1246. // 如果有关联的script_id,则同步到mp_products表
  1247. if ($script_id) {
  1248. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1249. $script = DB::table('mp_scripts')
  1250. ->where('id', $script_id)
  1251. ->where('user_id', $uid)
  1252. ->where('is_deleted', 0)
  1253. ->first();
  1254. if ($script) {
  1255. $script_name = $script->script_name ?? 'script_' . $script_id;
  1256. $product_name = getProp($target_scenes, 'scene');
  1257. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1258. $url = getProp($target_scenes, 'url', '');
  1259. $three_view_image_url = trim(getProp($target_scenes, 'three_view_image_url', ''));
  1260. $timbre_url = trim(getProp($target_scenes, 'timbre_url', ''));
  1261. // 兼容 versions 传入数组或 JSON 字符串
  1262. $versions = getProp($target_scenes, 'versions', null);
  1263. if (is_string($versions) && $versions !== '') {
  1264. $decoded_versions = json_decode($versions, true);
  1265. if (is_array($decoded_versions)) {
  1266. $versions = $decoded_versions;
  1267. }
  1268. }
  1269. $product_type = 2; // 2=场景
  1270. // 查找或创建以script_name命名的文件夹
  1271. $folder = DB::table('mp_products')
  1272. ->where('cpid', $cpid)
  1273. ->where('type', 2) // 文件夹类型
  1274. ->where('product', $product_type) // 场景类型
  1275. ->where('product_name', $script_name)
  1276. ->where('parent_id', 0)
  1277. ->where('is_deleted', 0)
  1278. ->first();
  1279. if (!$folder) {
  1280. // 创建文件夹
  1281. $folder_id = DB::table('mp_products')->insertGetId([
  1282. 'user_id' => $uid,
  1283. 'cpid' => $cpid,
  1284. 'type' => 2, // 文件夹
  1285. 'product' => $product_type, // 场景类型
  1286. 'parent_id' => 0,
  1287. 'level' => 1,
  1288. 'product_name' => $script_name,
  1289. 'sort_order' => time(),
  1290. 'is_deleted' => 0,
  1291. 'created_at' => date('Y-m-d H:i:s'),
  1292. 'updated_at' => date('Y-m-d H:i:s')
  1293. ]);
  1294. } else {
  1295. $folder_id = $folder->id;
  1296. }
  1297. // 查找该文件夹下是否已存在同名资产
  1298. $existing_product = DB::table('mp_products')
  1299. ->where('cpid', $cpid)
  1300. ->where('type', 1) // 资产类型
  1301. ->where('product', $product_type)
  1302. ->where('parent_id', $folder_id)
  1303. ->where('product_name', $product_name)
  1304. ->where('is_deleted', 0)
  1305. ->first();
  1306. if ($existing_product) {
  1307. // 更新已存在的资产
  1308. $updateData = [
  1309. 'pic_task_status' => '生成成功'
  1310. ];
  1311. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1312. if ($url) $updateData['url'] = $url;
  1313. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1314. if (is_array($target_scenes) && array_key_exists('three_view_image_url', $target_scenes)) {
  1315. $updateData['three_view_image_url'] = trim(getProp($target_scenes, 'three_view_image_url', ''));
  1316. }
  1317. // 显式传入音色(含空值)时同步写入,空值表示清除该资产的音色
  1318. if (is_array($target_scenes) && array_key_exists('timbre_url', $target_scenes)) {
  1319. $updateData['timbre_url'] = trim(getProp($target_scenes, 'timbre_url', ''));
  1320. }
  1321. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1322. if (is_array($versions)) {
  1323. $updateData['versions'] = json_encode($versions, 256);
  1324. }
  1325. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1326. DB::table('mp_products')
  1327. ->where('id', $existing_product->id)
  1328. ->update($updateData);
  1329. $product_id = $existing_product->id;
  1330. } else {
  1331. // 创建新资产
  1332. $product_id = DB::table('mp_products')->insertGetId([
  1333. 'user_id' => $uid,
  1334. 'cpid' => $cpid,
  1335. 'type' => 1, // 资产
  1336. 'product' => $product_type, // 场景
  1337. 'parent_id' => $folder_id,
  1338. 'level' => 2,
  1339. 'product_name' => $product_name,
  1340. 'url' => $url,
  1341. 'three_view_image_url' => $three_view_image_url,
  1342. 'timbre_url' => $timbre_url,
  1343. 'pic_prompt' => $pic_prompt,
  1344. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1345. 'sort_order' => time(),
  1346. 'is_deleted' => 0,
  1347. 'pic_task_status' => '生成成功',
  1348. 'created_at' => date('Y-m-d H:i:s'),
  1349. 'updated_at' => date('Y-m-d H:i:s')
  1350. ]);
  1351. }
  1352. // 建立或更新绑定关系
  1353. $existing_mapping = DB::table('mp_script_product_mappings')
  1354. ->where('script_id', $script_id)
  1355. ->where('product_id', $product_id)
  1356. ->where('episode_number', $episode_number)
  1357. ->first();
  1358. if (!$existing_mapping) {
  1359. // 创建绑定关系
  1360. DB::table('mp_script_product_mappings')->insert([
  1361. 'script_id' => $script_id,
  1362. 'product_id' => $product_id,
  1363. 'episode_number' => $episode_number,
  1364. 'created_at' => date('Y-m-d H:i:s'),
  1365. 'updated_at' => date('Y-m-d H:i:s')
  1366. ]);
  1367. }
  1368. }
  1369. }
  1370. }
  1371. } catch (\Exception $e) {
  1372. dLog('anime')->error('更新剧集场景失败', [
  1373. 'anime_id' => $anime_id,
  1374. 'episode_id' => $episode_id,
  1375. 'error' => $e->getMessage()
  1376. ]);
  1377. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1378. }
  1379. return true;
  1380. }
  1381. public function changeEpisodeProps($data) {
  1382. $anime_id = getProp($data, 'anime_id');
  1383. $episode_id = getProp($data, 'episode_id');
  1384. $target_props = getProp($data, 'props');
  1385. // 删除标志优先取最外层入参 is_deleted,兼容道具对象内部(props.is_deleted)的传参
  1386. $is_deleted = getProp($data, 'is_deleted', getProp($target_props, 'is_deleted', 0));
  1387. // 控制字段不随道具内容写入分集props存储
  1388. if (is_array($target_props)) {
  1389. unset($target_props['is_deleted']);
  1390. }
  1391. // 参数验证
  1392. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1393. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1394. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1395. // 验证剧集是否存在
  1396. $episode = DB::table('mp_anime_episodes')
  1397. ->where('anime_id', $anime_id)
  1398. ->where('id', $episode_id)
  1399. ->first();
  1400. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1401. $props = json_decode(getProp($episode, 'props'), true);
  1402. // 获取anime信息,检查是否有关联的script_id
  1403. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1404. if (!$anime) Utils::throwError('20003:动漫不存在');
  1405. $script_id = getProp($anime, 'script_id');
  1406. $episode_number = getProp($episode, 'episode_number', 1);
  1407. $uid = Site::getUid();
  1408. $cpid = Site::getCpid();
  1409. try {
  1410. $target_prop_name = getProp($target_props, 'prop');
  1411. if (empty($target_prop_name)) {
  1412. Utils::throwError('20003:道具名称不能为空');
  1413. }
  1414. // 如果是删除操作
  1415. if ($is_deleted == 1) {
  1416. // 从道具列表中移除该道具
  1417. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1418. return getProp($prop, 'prop') !== $target_prop_name;
  1419. }));
  1420. // 更新道具列表
  1421. $result = DB::table('mp_anime_episodes')
  1422. ->where('anime_id', $anime_id)
  1423. ->where('id', $episode_id)
  1424. ->update([
  1425. 'props' => json_encode($props, 256),
  1426. 'updated_at' => date('Y-m-d H:i:s')
  1427. ]);
  1428. if ($result === false) {
  1429. Utils::throwError('20003:删除道具失败');
  1430. }
  1431. } else {
  1432. // 新增或更新操作
  1433. $prop_found = false;
  1434. $is_new_prop = false;
  1435. // 查找并更新已存在的道具
  1436. foreach($props as &$prop) {
  1437. if (getProp($prop, 'prop') === $target_prop_name) {
  1438. $prop = $target_props;
  1439. $prop_found = true;
  1440. break;
  1441. }
  1442. }
  1443. // 如果道具不存在,则新增
  1444. if (!$prop_found) {
  1445. $props[] = $target_props;
  1446. $is_new_prop = true;
  1447. }
  1448. // 更新道具列表
  1449. $result = DB::table('mp_anime_episodes')
  1450. ->where('anime_id', $anime_id)
  1451. ->where('id', $episode_id)
  1452. ->update([
  1453. 'props' => json_encode($props, 256),
  1454. 'updated_at' => date('Y-m-d H:i:s')
  1455. ]);
  1456. if ($result === false) {
  1457. Utils::throwError('20003:更新道具列表失败');
  1458. }
  1459. // 如果有关联的script_id,则同步到mp_products表
  1460. if ($script_id) {
  1461. // 查询剧本信息(仅同步属于当前用户的剧本,不属于则跳过后续资产同步)
  1462. $script = DB::table('mp_scripts')
  1463. ->where('id', $script_id)
  1464. ->where('user_id', $uid)
  1465. ->where('is_deleted', 0)
  1466. ->first();
  1467. if ($script) {
  1468. $script_name = $script->script_name ?? 'script_' . $script_id;
  1469. $product_name = getProp($target_props, 'prop');
  1470. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1471. $url = getProp($target_props, 'url', '');
  1472. $three_view_image_url = trim(getProp($target_props, 'three_view_image_url', ''));
  1473. $timbre_url = trim(getProp($target_props, 'timbre_url', ''));
  1474. // 兼容 versions 传入数组或 JSON 字符串
  1475. $versions = getProp($target_props, 'versions', null);
  1476. if (is_string($versions) && $versions !== '') {
  1477. $decoded_versions = json_decode($versions, true);
  1478. if (is_array($decoded_versions)) {
  1479. $versions = $decoded_versions;
  1480. }
  1481. }
  1482. $product_type = 3; // 3=道具
  1483. // 查找或创建以script_name命名的文件夹
  1484. $folder = DB::table('mp_products')
  1485. ->where('cpid', $cpid)
  1486. ->where('type', 2) // 文件夹类型
  1487. ->where('product', $product_type) // 道具类型
  1488. ->where('product_name', $script_name)
  1489. ->where('parent_id', 0)
  1490. ->where('is_deleted', 0)
  1491. ->first();
  1492. if (!$folder) {
  1493. // 创建文件夹
  1494. $folder_id = DB::table('mp_products')->insertGetId([
  1495. 'user_id' => $uid,
  1496. 'cpid' => $cpid,
  1497. 'type' => 2, // 文件夹
  1498. 'product' => $product_type, // 道具类型
  1499. 'parent_id' => 0,
  1500. 'level' => 1,
  1501. 'product_name' => $script_name,
  1502. 'sort_order' => time(),
  1503. 'is_deleted' => 0,
  1504. 'created_at' => date('Y-m-d H:i:s'),
  1505. 'updated_at' => date('Y-m-d H:i:s')
  1506. ]);
  1507. } else {
  1508. $folder_id = $folder->id;
  1509. }
  1510. // 查找该文件夹下是否已存在同名资产
  1511. $existing_product = DB::table('mp_products')
  1512. ->where('cpid', $cpid)
  1513. ->where('type', 1) // 资产类型
  1514. ->where('product', $product_type)
  1515. ->where('parent_id', $folder_id)
  1516. ->where('product_name', $product_name)
  1517. ->where('is_deleted', 0)
  1518. ->first();
  1519. if ($existing_product) {
  1520. // 更新已存在的资产
  1521. $updateData = [
  1522. 'pic_task_status' => '生成成功'
  1523. ];
  1524. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1525. if ($url) $updateData['url'] = $url;
  1526. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  1527. if (is_array($target_props) && array_key_exists('three_view_image_url', $target_props)) {
  1528. $updateData['three_view_image_url'] = trim(getProp($target_props, 'three_view_image_url', ''));
  1529. }
  1530. // 显式传入音色(含空值)时同步写入,空值表示清除该资产的音色
  1531. if (is_array($target_props) && array_key_exists('timbre_url', $target_props)) {
  1532. $updateData['timbre_url'] = trim(getProp($target_props, 'timbre_url', ''));
  1533. }
  1534. // 处理versions字段,显式传入数组(含空数组)时覆盖
  1535. if (is_array($versions)) {
  1536. $updateData['versions'] = json_encode($versions, 256);
  1537. }
  1538. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1539. DB::table('mp_products')
  1540. ->where('id', $existing_product->id)
  1541. ->update($updateData);
  1542. $product_id = $existing_product->id;
  1543. } else {
  1544. // 创建新资产
  1545. $product_id = DB::table('mp_products')->insertGetId([
  1546. 'user_id' => $uid,
  1547. 'cpid' => $cpid,
  1548. 'type' => 1, // 资产
  1549. 'product' => $product_type, // 道具
  1550. 'parent_id' => $folder_id,
  1551. 'level' => 2,
  1552. 'product_name' => $product_name,
  1553. 'url' => $url,
  1554. 'three_view_image_url' => $three_view_image_url,
  1555. 'timbre_url' => $timbre_url,
  1556. 'pic_prompt' => $pic_prompt,
  1557. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1558. 'sort_order' => time(),
  1559. 'is_deleted' => 0,
  1560. 'pic_task_status' => '生成成功',
  1561. 'created_at' => date('Y-m-d H:i:s'),
  1562. 'updated_at' => date('Y-m-d H:i:s')
  1563. ]);
  1564. }
  1565. // 建立或更新绑定关系
  1566. $existing_mapping = DB::table('mp_script_product_mappings')
  1567. ->where('script_id', $script_id)
  1568. ->where('product_id', $product_id)
  1569. ->where('episode_number', $episode_number)
  1570. ->first();
  1571. if (!$existing_mapping) {
  1572. // 创建绑定关系
  1573. DB::table('mp_script_product_mappings')->insert([
  1574. 'script_id' => $script_id,
  1575. 'product_id' => $product_id,
  1576. 'episode_number' => $episode_number,
  1577. 'created_at' => date('Y-m-d H:i:s'),
  1578. 'updated_at' => date('Y-m-d H:i:s')
  1579. ]);
  1580. }
  1581. }
  1582. }
  1583. }
  1584. } catch (\Exception $e) {
  1585. dLog('anime')->error('更新剧集道具失败', [
  1586. 'anime_id' => $anime_id,
  1587. 'episode_id' => $episode_id,
  1588. 'error' => $e->getMessage()
  1589. ]);
  1590. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1591. }
  1592. return true;
  1593. }
  1594. public function editSegment($data) {
  1595. $segment_id = getProp($data, 'segment_id');
  1596. $segment_content = getProp($data, 'segment_content');
  1597. $image_url = getProp($data, 'image_url');
  1598. $video_url = getProp($data, 'video_url');
  1599. // 参数验证
  1600. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1601. // 验证分镜是否存在
  1602. $segment = DB::table('mp_episode_segments')
  1603. ->where('segment_id', $segment_id)
  1604. ->first();
  1605. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1606. $dubTaskId = 0;
  1607. try {
  1608. DB::beginTransaction();
  1609. // 准备更新数据
  1610. $update_data = [
  1611. 'updated_at' => date('Y-m-d H:i:s')
  1612. ];
  1613. if ($segment_content) {
  1614. // 先将segment_content赋值到update_data
  1615. $update_data['segment_content'] = $segment_content;
  1616. // 使用现有方法分析segment_content,提取各个字段
  1617. $this->handleSegmentContent($update_data);
  1618. // 如果有对话内容,创建视频配音合成任务
  1619. $dialogue = getProp($update_data, 'dialogue');
  1620. if (!empty($dialogue)) {
  1621. $now = date('Y-m-d H:i:s');
  1622. $generate_json = [
  1623. 'text' => $dialogue,
  1624. 'role' => getProp($update_data, 'voice_actor'),
  1625. 'voice_type' => getProp($update_data, 'voice_type'),
  1626. 'voice_name' => getProp($update_data, 'voice_name'),
  1627. 'emotion' => getProp($update_data, 'emotion'),
  1628. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1629. 'gender' => getProp($update_data, 'gender'),
  1630. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1631. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1632. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1633. 'pitch' => getProp($update_data, 'pitch', 0),
  1634. ];
  1635. // 插入视频配音合成任务
  1636. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1637. 'alias_segment_id' => $segment_id,
  1638. 'generate_status' => '执行中',
  1639. 'audio_url' => '',
  1640. 'generate_json' => json_encode($generate_json, 256),
  1641. 'created_at' => $now,
  1642. 'updated_at' => $now,
  1643. ]);
  1644. if (!$dubTaskId) {
  1645. Utils::throwError('20003:创建配音任务失败!');
  1646. }
  1647. $update_data['audio_url'] = '';
  1648. } else {
  1649. // dialogue为空时,直接写入默认音频信息
  1650. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1651. $update_data['audio_duration'] = 2.0;
  1652. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1653. }
  1654. }
  1655. if ($image_url) {
  1656. $update_data['img_url'] = $image_url;
  1657. // 同时写入一个简单的图片生成任务
  1658. $pic_task = [
  1659. 'alias_segment_id' => $segment_id,
  1660. 'ref_img_url' => json_encode([]),
  1661. 'status' => 'success',
  1662. 'result_url' => json_encode([$image_url], 256),
  1663. 'model' => '',
  1664. 'created_at' => date('Y-m-d H:i:s'),
  1665. 'updated_at' => date('Y-m-d H:i:s'),
  1666. ];
  1667. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1668. }
  1669. if ($video_url) {
  1670. $update_data['origin_video_url'] = $video_url;
  1671. $compressed_video_url = compressVideo($video_url);
  1672. $update_data['current_type'] = 2;
  1673. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1674. // 同时写入一个简单的视频生成任务
  1675. $video_task = [
  1676. 'alias_segment_id' => $segment_id,
  1677. 'status' => 'success',
  1678. 'result_url' => $update_data['origin_video_url'],
  1679. 'compressed_url' => $update_data['video_url'],
  1680. 'created_at' => date('Y-m-d H:i:s'),
  1681. 'updated_at' => date('Y-m-d H:i:s'),
  1682. ];
  1683. DB::table('mp_generate_video_tasks')->insert($video_task);
  1684. }
  1685. // 更新分镜信息
  1686. $result = DB::table('mp_episode_segments')
  1687. ->where('segment_id', $segment_id)
  1688. ->update($update_data);
  1689. if ($result === false) {
  1690. Utils::throwError('20003:更新分镜剧本失败');
  1691. }
  1692. DB::commit();
  1693. // 如果有创建音频生成任务则调用API
  1694. if ($dubTaskId) {
  1695. // 请求远程服务器执行生成
  1696. $client = new Client(['timeout' => 300, 'verify' => false]);
  1697. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1698. $response = $result->getBody()->getContents();
  1699. $response_arr = json_decode($response, true);
  1700. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1701. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1702. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1703. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1704. Utils::throwError('20003:火山生成音频失败');
  1705. }
  1706. }
  1707. return true;
  1708. } catch (\Exception $e) {
  1709. DB::rollBack();
  1710. dLog('anime')->error('更新分镜剧本失败', [
  1711. 'segment_id' => $segment_id,
  1712. 'error' => $e->getMessage()
  1713. ]);
  1714. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1715. }
  1716. }
  1717. public function batchSetSegmentPics($data) {
  1718. $anime_id = getProp($data, 'anime_id');
  1719. $episode_id = getProp($data, 'episode_id');
  1720. $ratio = getProp($data, 'ratio');
  1721. $dimensions = $this->getRatioDimensions($ratio);
  1722. $width = $dimensions['width'];
  1723. $height = $dimensions['height'];
  1724. if (!$anime_id || !$episode_id) {
  1725. Utils::throwError('1002:请选择剧集');
  1726. }
  1727. // 获取剧集信息
  1728. $episode = DB::table('mp_anime_episodes')
  1729. ->where('anime_id', $anime_id)
  1730. ->where('id', $episode_id)
  1731. ->where('is_default', 1)
  1732. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1733. ->first();
  1734. if (!$episode) {
  1735. Utils::throwError('20003:该剧集不存在');
  1736. }
  1737. $model = getProp($data, 'model');
  1738. if (!$model) {
  1739. $model = getProp($episode, 'image_model');
  1740. if (!$model) {
  1741. // episode表也没有,使用默认值
  1742. $model = 'gpt-image-2';
  1743. }
  1744. }
  1745. // 验证模型是否在可用模型表中
  1746. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1747. $model = 'gpt-image-2';
  1748. }
  1749. $roles = json_decode(getProp($episode, 'roles'), true);
  1750. if (!$roles) {
  1751. Utils::throwError('20003:角色信息格式错误');
  1752. }
  1753. // 构建角色名称到参考图的映射
  1754. $role_map = [];
  1755. foreach ($roles as $role) {
  1756. $role_name = getProp($role, 'role');
  1757. $role_url = getProp($role, 'url');
  1758. if (!empty($role_name) && !empty($role_url)) {
  1759. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1760. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1761. // $role_map[$base_name] = $role_url;
  1762. // 同时保存完整名称的映射
  1763. $role_map[$role_name] = $role_url;
  1764. }
  1765. }
  1766. $scenes = json_decode(getProp($episode, 'roles'), true);
  1767. if (!$scenes) {
  1768. Utils::throwError('20003:场景信息格式错误');
  1769. }
  1770. // 构建角色名称到参考图的映射
  1771. $scene_map = [];
  1772. foreach ($scenes as $scene) {
  1773. $scene_name = getProp($scene, 'scene');
  1774. $scene_url = getProp($scene, 'url');
  1775. if (!empty($scene_name) && !empty($scene_url)) {
  1776. $scene_map[$scene_name] = $scene_url;
  1777. }
  1778. }
  1779. // 获取所有分镜信息
  1780. $segments = DB::table('mp_episode_segments')
  1781. ->where('anime_id', $anime_id)
  1782. ->where('episode_id', $episode_id)
  1783. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1784. ->orderBy('segment_number')
  1785. ->get()
  1786. ->toArray();
  1787. if (empty($segments)) {
  1788. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1789. }
  1790. // 保存图片比例
  1791. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1792. $updated_segments = [];
  1793. $failed_segments = [];
  1794. // 批量为每个分镜生成图片任务
  1795. foreach ($segments as $segment) {
  1796. $segment_id = $segment->segment_id;
  1797. $segment_content = $segment->segment_content;
  1798. if (empty($segment_content)) {
  1799. $failed_segments[] = [
  1800. 'segment_id' => $segment_id,
  1801. 'error' => '分镜内容为空'
  1802. ];
  1803. continue;
  1804. }
  1805. try {
  1806. $dubTaskId = 0;
  1807. // 解析分镜内容,提取画面描述作为主要提示词
  1808. $prompt = $segment_content;
  1809. $ref_img_urls = [];
  1810. // 分镜场景
  1811. $scene = getProp($segment, 'scene');
  1812. $matched_scene = '';
  1813. if (isset($scene_map[$scene])) {
  1814. $img_index = count($ref_img_urls) + 1;
  1815. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1816. $ref_img_urls[] = $scene_map[$scene];
  1817. $matched_scene = $scene;
  1818. }
  1819. // 分镜角色
  1820. $characters = getProp($segment, 'characters');
  1821. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1822. $roles = explode(',', $characters);
  1823. // 从分镜内容中提取涉及的角色
  1824. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1825. // 获取匹配角色的参考图
  1826. foreach ($segment_characters as $character) {
  1827. if (isset($role_map[$character])) {
  1828. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1829. $img_index = count($ref_img_urls) + 1;
  1830. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1831. $ref_img_urls[] = $role_map[$character];
  1832. }
  1833. }
  1834. // 如果没有找到匹配的角色参考图,不使用参考图
  1835. if (empty($ref_img_urls)) {
  1836. $ref_img_urls = [];
  1837. }
  1838. // 准备生成任务参数
  1839. $params = [
  1840. 'model' => $model,
  1841. 'alias_segment_id' => $segment_id,
  1842. 'prompt' => $prompt,
  1843. 'ref_img_urls' => $ref_img_urls,
  1844. 'width' => $width,
  1845. 'height' => $height,
  1846. ];
  1847. // 优化提示词(不要生成字幕)
  1848. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1849. // $task_id = mt_rand(100000, 999999);
  1850. // 调用AI图片生成服务
  1851. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1852. $task_id = $task->id;
  1853. if (!$task_id) {
  1854. $failed_segments[] = [
  1855. 'segment_id' => $segment_id,
  1856. 'error' => '创建生成任务失败'
  1857. ];
  1858. continue;
  1859. }
  1860. $update_data = [
  1861. 'pic_task_id' => $task_id,
  1862. 'pic_task_status' => '生成中',
  1863. 'audio_url' => '',
  1864. 'updated_at' => date('Y-m-d H:i:s')
  1865. ];
  1866. // 如果有对话内容,创建视频配音合成任务
  1867. $dialogue = getProp($segment, 'dialogue');
  1868. if (!empty($dialogue)) {
  1869. $now = date('Y-m-d H:i:s');
  1870. $generate_json = [
  1871. 'text' => $dialogue,
  1872. 'role' => getProp($segment, 'voice_actor'),
  1873. 'voice_type' => getProp($segment, 'voice_type'),
  1874. 'voice_name' => getProp($segment, 'voice_name'),
  1875. 'emotion' => getProp($segment, 'emotion'),
  1876. 'emotion_type' => getProp($segment, 'emotion_type'),
  1877. 'gender' => getProp($segment, 'gender'),
  1878. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1879. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1880. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1881. 'pitch' => getProp($segment, 'pitch', 0),
  1882. ];
  1883. // 插入视频配音合成任务
  1884. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1885. 'alias_segment_id' => $segment_id,
  1886. 'generate_status' => '执行中',
  1887. 'audio_url' => '',
  1888. 'generate_json' => json_encode($generate_json, 256),
  1889. 'created_at' => $now,
  1890. 'updated_at' => $now,
  1891. ]);
  1892. if (!$dubTaskId) {
  1893. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1894. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1895. // Utils::throwError('20003:创建配音任务失败!');
  1896. }
  1897. } else {
  1898. // dialogue为空时,直接写入默认音频信息到分镜表
  1899. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1900. $update_data['audio_duration'] = 2.0;
  1901. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1902. }
  1903. // 更新分镜的任务信息
  1904. $update_result = DB::table('mp_episode_segments')
  1905. ->where('segment_id', $segment_id)
  1906. ->update($update_data);
  1907. // 如果是第一集的首帧图片,则存入待更新数组
  1908. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1909. Redis::sadd('anime_first_frame_urls', $segment_id);
  1910. }
  1911. if ($update_result) {
  1912. $updated_segments[] = [
  1913. 'segment_id' => $segment_id,
  1914. 'task_id' => $task_id,
  1915. 'status' => '生成中',
  1916. 'matched_scenes' => $matched_scene,
  1917. 'matched_roles' => $segment_characters,
  1918. 'ref_urls_count' => count($ref_img_urls)
  1919. ];
  1920. } else {
  1921. $failed_segments[] = [
  1922. 'segment_id' => $segment_id,
  1923. 'error' => '更新分镜任务状态失败'
  1924. ];
  1925. }
  1926. if ($dubTaskId) {
  1927. sleep(1);
  1928. // 请求远程服务器执行生成
  1929. $client = new Client(['timeout' => 300, 'verify' => false]);
  1930. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1931. $response = $result->getBody()->getContents();
  1932. $response_arr = json_decode($response, true);
  1933. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1934. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1935. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1936. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1937. }
  1938. }
  1939. } catch (\Exception $e) {
  1940. $failed_segments[] = [
  1941. 'segment_id' => $segment_id,
  1942. 'error' => $e->getMessage()
  1943. ];
  1944. }
  1945. }
  1946. // 更新剧集生成状态
  1947. if (!empty($updated_segments)) {
  1948. DB::table('mp_anime_episodes')
  1949. ->where('id', $episode_id)
  1950. ->update([
  1951. 'is_generated' => 1,
  1952. 'updated_at' => date('Y-m-d H:i:s')
  1953. ]);
  1954. }
  1955. return [
  1956. 'success_count' => count($updated_segments),
  1957. 'failed_count' => count($failed_segments),
  1958. 'success_segments' => $updated_segments,
  1959. 'failed_segments' => $failed_segments,
  1960. 'total_segments' => count($segments)
  1961. ];
  1962. }
  1963. public function reGenerateSegment($data) {
  1964. $segment_id = getProp($data, 'segment_id');
  1965. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1966. $anime_id = getProp($segment, 'anime_id');
  1967. $episode_id = getProp($segment, 'episode_id');
  1968. $episode_number = getProp($segment, 'episode_number');
  1969. $segment_content = getProp($data, 'segment_content');
  1970. $ratio = getProp($data, 'ratio');
  1971. if (!$ratio) {
  1972. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1973. if (!$ratio) $ratio = '9:16';
  1974. }
  1975. $dimensions = $this->getRatioDimensions($ratio);
  1976. $width = $dimensions['width'];
  1977. $height = $dimensions['height'];
  1978. if (!$anime_id || !$episode_id) {
  1979. Utils::throwError('1002:请选择分镜');
  1980. }
  1981. // 使用文生文模型重新解析segment_content
  1982. if (!empty($segment_content)) {
  1983. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1984. }
  1985. // 获取动漫的角色信息(包含参考图)
  1986. $anime = DB::table('mp_animes')
  1987. ->where('id', $anime_id)
  1988. ->select('roles', 'scenes')
  1989. ->first();
  1990. if (!$anime || !$anime->roles) {
  1991. Utils::throwError('20003:未找到角色信息');
  1992. }
  1993. $roles = json_decode($anime->roles, true);
  1994. if (!$roles) {
  1995. Utils::throwError('20003:角色信息格式错误');
  1996. }
  1997. // 构建角色名称到参考图的映射
  1998. $role_map = [];
  1999. foreach ($roles as $role) {
  2000. $role_name = getProp($role, 'role');
  2001. $role_url = getProp($role, 'url');
  2002. if (!empty($role_name) && !empty($role_url)) {
  2003. $role_map[$role_name] = $role_url;
  2004. }
  2005. }
  2006. $scenes = json_decode($anime->scenes, true);
  2007. if (!$scenes) {
  2008. Utils::throwError('20003:角色信息格式错误');
  2009. }
  2010. // 构建角色名称到参考图的映射
  2011. $scene_map = [];
  2012. foreach ($scenes as $scene) {
  2013. $scene_name = getProp($scene, 'scene');
  2014. $scene_url = getProp($scene, 'url');
  2015. if (!empty($scene_name) && !empty($scene_url)) {
  2016. $scene_map[$scene_name] = $scene_url;
  2017. }
  2018. }
  2019. $segment_id = $segment->segment_id;
  2020. $original_segment_content = $segment->segment_content;
  2021. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2022. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2023. if (empty($final_segment_content)) {
  2024. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2025. }
  2026. try {
  2027. $dubTaskId = 0;
  2028. // 分镜剧本数组
  2029. $update_data = [
  2030. 'segment_content' => $final_segment_content,
  2031. 'pic_task_status' => '生成中',
  2032. 'updated_at' => date('Y-m-d H:i:s')
  2033. ];
  2034. // 解析分镜内容,提取画面描述作为主要提示词
  2035. $prompt = $final_segment_content;
  2036. $ref_img_urls = [];
  2037. // 分镜场景
  2038. $scene = getProp($data, 'scene');
  2039. if ($scene) {
  2040. $matched_scene = '';
  2041. if (isset($scene_map[$scene])) {
  2042. $img_index = count($ref_img_urls) + 1;
  2043. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2044. $ref_img_urls[] = $scene_map[$scene];
  2045. $matched_scene = $scene;
  2046. }
  2047. $update_data['scene'] = $scene;
  2048. }
  2049. // 分镜角色
  2050. $characters = getProp($data, 'characters');
  2051. if ($characters) {
  2052. $update_data['characters'] = $characters;
  2053. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2054. $characters = explode(',', $characters);
  2055. // 从分镜内容中提取涉及的角色
  2056. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2057. // 获取匹配角色的参考图
  2058. foreach ($segment_characters as $character) {
  2059. if (isset($role_map[$character])) {
  2060. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2061. $img_index = count($ref_img_urls) + 1;
  2062. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2063. $ref_img_urls[] = $role_map[$character];
  2064. }
  2065. }
  2066. }
  2067. // 如果没有找到匹配的角色参考图,不使用参考图
  2068. if (empty($ref_img_urls)) {
  2069. $ref_img_urls = [];
  2070. }
  2071. // 准备生成任务参数
  2072. $params = [
  2073. 'alias_segment_id' => $segment_id,
  2074. 'prompt' => $prompt,
  2075. 'ref_img_urls' => $ref_img_urls,
  2076. 'width' => $width,
  2077. 'height' => $height,
  2078. ];
  2079. // 优化提示词(不要生成字幕)
  2080. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  2081. // 调用AI图片生成服务
  2082. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2083. $task_id = $task->id;
  2084. if (!$task_id) {
  2085. Utils::throwError('20003:创建生成任务失败!');
  2086. }
  2087. $update_data['pic_task_id'] = $task_id;
  2088. // 更新分镜剧本信息
  2089. $this->handleSegmentContent($update_data);
  2090. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2091. if ($segment_content) {
  2092. $dialogue = getProp($update_data, 'dialogue');
  2093. if (!empty($dialogue)) {
  2094. $now = date('Y-m-d H:i:s');
  2095. $generate_json = [
  2096. 'text' => $dialogue,
  2097. 'role' => getProp($update_data, 'voice_actor'),
  2098. 'voice_type' => getProp($update_data, 'voice_type'),
  2099. 'voice_name' => getProp($update_data, 'voice_name'),
  2100. 'emotion' => getProp($update_data, 'emotion'),
  2101. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2102. 'gender' => getProp($update_data, 'gender'),
  2103. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2104. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2105. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2106. 'pitch' => getProp($update_data, 'pitch', 0),
  2107. ];
  2108. // 插入视频配音合成任务
  2109. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2110. 'alias_segment_id' => $segment_id,
  2111. 'generate_status' => '执行中',
  2112. 'audio_url' => '',
  2113. 'generate_json' => json_encode($generate_json, 256),
  2114. 'created_at' => date('Y-m-d H:i:s'),
  2115. 'updated_at' => date('Y-m-d H:i:s'),
  2116. ]);
  2117. if (!$dubTaskId) {
  2118. Utils::throwError('20003:创建配音任务失败!');
  2119. }
  2120. $update_data['audio_url'] = '';
  2121. } else {
  2122. // dialogue为空时,直接写入默认音频信息
  2123. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2124. $update_data['audio_duration'] = 2.0;
  2125. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2126. }
  2127. }
  2128. $boolen = DB::table('mp_episode_segments')
  2129. ->where('segment_id', $segment_id)
  2130. ->update($update_data);
  2131. // 如果是第一集的首帧图片,则存入待更新数组
  2132. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2133. Redis::sadd('anime_first_frame_urls', $segment_id);
  2134. }
  2135. if ($dubTaskId) {
  2136. // 请求远程服务器执行生成
  2137. $client = new Client(['timeout' => 300, 'verify' => false]);
  2138. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2139. $response = $result->getBody()->getContents();
  2140. $response_arr = json_decode($response, true);
  2141. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2142. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2143. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2144. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2145. Utils::throwError('20003:火山生成音频失败');
  2146. }
  2147. }
  2148. } catch (\Exception $e) {
  2149. $failed_segments[] = [
  2150. 'segment_id' => $segment_id,
  2151. 'error' => $e->getMessage()
  2152. ];
  2153. }
  2154. // 创建任务之后先暂停10s等待异步任务完成
  2155. sleep(10);
  2156. $img_url = $this->loopGetPicTaskResult($task_id);
  2157. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2158. // 图片生成后新增对话记录
  2159. try {
  2160. $uid = Site::getUid();
  2161. $now = date('Y-m-d H:i:s');
  2162. // 使用AI反推图片提示词
  2163. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2164. // 保存对话记录
  2165. $records = [
  2166. [
  2167. 'uid' => $uid,
  2168. 'anime_id' => $anime_id,
  2169. 'sequence' => $episode_number,
  2170. 'role' => 'user',
  2171. 'content' => '重新生成',
  2172. 'segment_id' => $segment_id,
  2173. 'pic_task_id' => $task_id,
  2174. 'image_url' => '',
  2175. 'created_at' => $now,
  2176. 'updated_at' => $now
  2177. ],
  2178. [
  2179. 'uid' => $uid,
  2180. 'anime_id' => $anime_id,
  2181. 'sequence' => $episode_number,
  2182. 'role' => 'assistant',
  2183. 'content' => $pic_prompt,
  2184. 'segment_id' => $segment_id,
  2185. 'pic_task_id' => $task_id,
  2186. 'image_url' => $img_url,
  2187. 'created_at' => $now,
  2188. 'updated_at' => $now
  2189. ]
  2190. ];
  2191. DB::table('mp_anime_records')->insert($records);
  2192. } catch (\Exception $e) {
  2193. // 记录日志但不影响主流程
  2194. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2195. 'segment_id' => $segment_id,
  2196. 'img_url' => $img_url
  2197. ]);
  2198. }
  2199. return $img_url;
  2200. }
  2201. public function addSegment($data) {
  2202. $prev_segment_id = getProp($data, 'prev_segment_id');
  2203. $img_url = getProp($data, 'img_url');
  2204. $video_url = getProp($data, 'video_url');
  2205. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2206. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2207. $anime_id = getProp($segment, 'anime_id');
  2208. $episode_id = getProp($segment, 'episode_id');
  2209. $episode_number = getProp($segment, 'episode_number');
  2210. $segment_number = getProp($segment, 'segment_number');
  2211. $new_segment_number = $segment_number + 1;
  2212. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2213. // 分镜剧本数组
  2214. $insert_data = [
  2215. 'anime_id' => $anime_id,
  2216. 'episode_id' => $episode_id,
  2217. 'episode_number' => $episode_number,
  2218. 'act_number' => getProp($segment, 'act_number'),
  2219. 'act_title' => getProp($segment, 'act_title'),
  2220. 'segment_id' => $segment_id,
  2221. 'segment_number' => $new_segment_number,
  2222. 'segment_content' => '',
  2223. 'img_url' => '',
  2224. 'video_url' => '',
  2225. 'created_at' => date('Y-m-d H:i:s'),
  2226. 'updated_at' => date('Y-m-d H:i:s')
  2227. ];
  2228. if ($img_url) $insert_data['img_url'] = $img_url;
  2229. if ($video_url) {
  2230. $insert_data['origin_video_url'] = $video_url;
  2231. $insert_data['current_type'] = 2;
  2232. $compressed_video_url = compressVideo($video_url);
  2233. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2234. }
  2235. try {
  2236. DB::beginTransaction();
  2237. // 先更新序号
  2238. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2239. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2240. if (!$id) {
  2241. Utils::throwError('20003:新增分镜失败!');
  2242. }
  2243. }catch (\Exception $e) {
  2244. DB::rollBack();
  2245. Utils::throwError('20003:'.$e->getMessage());
  2246. }
  2247. DB::commit();
  2248. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2249. $segment = $segment ? (array)$segment : [];
  2250. return $segment;
  2251. // 以下代码暂弃用
  2252. $anime_id = getProp($segment, 'anime_id');
  2253. $episode_id = getProp($segment, 'episode_id');
  2254. $episode_number = getProp($segment, 'episode_number');
  2255. $segment_number = getProp($segment, 'segment_number');
  2256. $segment_content = getProp($data, 'segment_content');
  2257. $img_url = getProp($data, 'img_url');
  2258. $video_url = getProp($data, 'video_url');
  2259. $ratio = getProp($data, 'ratio');
  2260. $dimensions = $this->getRatioDimensions($ratio);
  2261. $width = $dimensions['width'];
  2262. $height = $dimensions['height'];
  2263. if (!$anime_id || !$episode_id) {
  2264. Utils::throwError('1002:请选择分镜');
  2265. }
  2266. // 使用文生文模型重新解析segment_content
  2267. if (!empty($segment_content)) {
  2268. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2269. }
  2270. // 获取动漫的角色信息(包含参考图)
  2271. $anime = DB::table('mp_animes')
  2272. ->where('id', $anime_id)
  2273. ->select('roles', 'scenes')
  2274. ->first();
  2275. if (!$anime || !$anime->roles) {
  2276. Utils::throwError('20003:未找到角色信息');
  2277. }
  2278. $roles = json_decode($anime->roles, true);
  2279. if (!$roles) {
  2280. Utils::throwError('20003:角色信息格式错误');
  2281. }
  2282. // 构建角色名称到参考图的映射
  2283. $role_map = [];
  2284. foreach ($roles as $role) {
  2285. $role_name = getProp($role, 'role');
  2286. $role_url = getProp($role, 'url');
  2287. if (!empty($role_name) && !empty($role_url)) {
  2288. $role_map[$role_name] = $role_url;
  2289. }
  2290. }
  2291. $scenes = json_decode($anime->scenes, true);
  2292. if (!$scenes) {
  2293. Utils::throwError('20003:角色信息格式错误');
  2294. }
  2295. // 构建角色名称到参考图的映射
  2296. $scene_map = [];
  2297. foreach ($scenes as $scene) {
  2298. $scene_name = getProp($scene, 'scene');
  2299. $scene_url = getProp($scene, 'url');
  2300. if (!empty($scene_name) && !empty($scene_url)) {
  2301. $scene_map[$scene_name] = $scene_url;
  2302. }
  2303. }
  2304. $segment_id = $segment->segment_id;
  2305. $original_segment_content = $segment->segment_content;
  2306. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2307. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2308. if (empty($final_segment_content)) {
  2309. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2310. }
  2311. try {
  2312. $dubTaskId = 0;
  2313. DB::beginTransaction();
  2314. $new_segment_number = $segment_number + 1;
  2315. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2316. // 分镜剧本数组
  2317. $insert_data = [
  2318. 'anime_id' => $anime_id,
  2319. 'episode_id' => $episode_id,
  2320. 'episode_number' => $episode_number,
  2321. 'act_number' => getProp($segment, 'act_number'),
  2322. 'act_title' => getProp($segment, 'act_title'),
  2323. 'segment_id' => $segment_id,
  2324. 'segment_number' => $new_segment_number,
  2325. 'segment_content' => $final_segment_content,
  2326. 'img_url' => $img_url,
  2327. 'video_url' => $video_url,
  2328. 'created_at' => date('Y-m-d H:i:s'),
  2329. 'updated_at' => date('Y-m-d H:i:s')
  2330. ];
  2331. // 更新分镜剧本信息
  2332. $this->handleSegmentContent($insert_data);
  2333. // 如果有对话内容,创建视频配音合成任务
  2334. $dialogue = getProp($insert_data, 'dialogue');
  2335. if (!empty($dialogue)) {
  2336. $now = date('Y-m-d H:i:s');
  2337. $generate_json = [
  2338. 'text' => $dialogue,
  2339. 'role' => getProp($insert_data, 'voice_actor'),
  2340. 'voice_type' => getProp($insert_data, 'voice_type'),
  2341. 'voice_name' => getProp($insert_data, 'voice_name'),
  2342. 'emotion' => getProp($insert_data, 'emotion'),
  2343. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2344. 'gender' => getProp($insert_data, 'gender'),
  2345. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2346. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2347. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2348. 'pitch' => getProp($insert_data, 'pitch', 0),
  2349. ];
  2350. // 插入视频配音合成任务
  2351. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2352. 'alias_segment_id' => $segment_id,
  2353. 'generate_status' => '执行中',
  2354. 'audio_url' => '',
  2355. 'generate_json' => json_encode($generate_json, 256),
  2356. 'created_at' => $now,
  2357. 'updated_at' => $now,
  2358. ]);
  2359. if (!$dubTaskId) {
  2360. Utils::throwError('20003:创建配音任务失败!');
  2361. }
  2362. $insert_data['audio_url'] = '';
  2363. } else {
  2364. // dialogue为空时,直接写入默认音频信息
  2365. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2366. $insert_data['audio_duration'] = 2.0;
  2367. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2368. }
  2369. // 如果没有上传图片则使用当前描述进行生成
  2370. if (!$img_url) {
  2371. // 解析分镜内容,提取画面描述作为主要提示词
  2372. $prompt = $final_segment_content;
  2373. $ref_img_urls = [];
  2374. // 分镜场景
  2375. $scene = getProp($insert_data, 'scene');
  2376. if ($scene) {
  2377. $matched_scene = '';
  2378. if (isset($scene_map[$scene])) {
  2379. $img_index = count($ref_img_urls) + 1;
  2380. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2381. $ref_img_urls[] = $scene_map[$scene];
  2382. $matched_scene = $scene;
  2383. }
  2384. $update_data['scene'] = $scene;
  2385. }
  2386. // 分镜角色
  2387. $characters = getProp($insert_data, 'characters');
  2388. if ($characters) {
  2389. $update_data['characters'] = $characters;
  2390. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2391. $characters = explode(',', $characters);
  2392. // 从分镜内容中提取涉及的角色
  2393. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2394. // 获取匹配角色的参考图
  2395. foreach ($segment_characters as $character) {
  2396. if (isset($role_map[$character])) {
  2397. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2398. $img_index = count($ref_img_urls) + 1;
  2399. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2400. $ref_img_urls[] = $role_map[$character];
  2401. }
  2402. }
  2403. }
  2404. // 如果没有找到匹配的角色参考图,不使用参考图
  2405. if (empty($ref_img_urls)) {
  2406. $ref_img_urls = [];
  2407. }
  2408. // 准备生成任务参数
  2409. $params = [
  2410. 'alias_segment_id' => $segment_id,
  2411. 'prompt' => $prompt,
  2412. 'ref_img_urls' => $ref_img_urls,
  2413. 'width' => $width,
  2414. 'height' => $height,
  2415. ];
  2416. // 调用AI图片生成服务
  2417. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2418. $task_id = $task->id;
  2419. // $task_id = 'whatever';
  2420. if (!$task_id) {
  2421. Utils::throwError('20003:创建生成任务失败!');
  2422. }
  2423. $insert_data['pic_task_status'] = '生成中';
  2424. $insert_data['pic_task_id'] = $task_id;
  2425. }
  2426. // 先更新序号
  2427. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2428. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2429. if (!$boolen) {
  2430. Utils::throwError('20003:新增分镜失败!');
  2431. }
  2432. // 如果是第一集的首帧图片,则存入待更新数组
  2433. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2434. Redis::sadd('anime_first_frame_urls', $segment_id);
  2435. }
  2436. if ($dubTaskId) {
  2437. // 请求远程服务器执行生成
  2438. $client = new Client(['timeout' => 300, 'verify' => false]);
  2439. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2440. $response = $result->getBody()->getContents();
  2441. $response_arr = json_decode($response, true);
  2442. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2443. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2444. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2445. Utils::throwError('20003:火山生成音频失败');
  2446. }
  2447. }
  2448. } catch (\Exception $e) {
  2449. DB::rollBack();
  2450. Utils::throwError('20003:'.$e->getMessage());
  2451. }
  2452. DB::commit();
  2453. // 创建任务之后先暂停10s等待异步任务完成
  2454. sleep(10);
  2455. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2456. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2457. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2458. $segment = $segment ? (array)$segment : [];
  2459. return $segment;
  2460. }
  2461. public function copySegment($data) {
  2462. $segment_id = getProp($data, 'segment_id');
  2463. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2464. if (!$segment) Utils::throwError('20003:请选择分镜');
  2465. $anime_id = getProp($segment, 'anime_id');
  2466. $episode_id = getProp($segment, 'episode_id');
  2467. $episode_number = getProp($segment, 'episode_number');
  2468. $segment_number = getProp($segment, 'segment_number');
  2469. $new_segment_id = 0;
  2470. try {
  2471. DB::beginTransaction();
  2472. $segment = (array)$segment;
  2473. unset($segment['id']);
  2474. $segment['segment_number'] += 1;
  2475. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2476. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2477. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2478. // 更新其他分镜序号
  2479. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2480. // 复制分镜
  2481. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2482. if (!$id) {
  2483. Utils::throwError('20003:复制分镜失败');
  2484. }
  2485. }catch (\Exception $e) {
  2486. DB::rollBack();
  2487. Utils::throwError('20003:'.$e->getMessage());
  2488. }
  2489. DB::commit();
  2490. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2491. $segment = $segment ? (array)$segment : [];
  2492. return $segment;
  2493. }
  2494. public function moveSegment($data) {
  2495. $segment_id = getProp($data, 'segment_id');
  2496. $target_segment_id = getProp($data, 'target_segment_id');
  2497. // 获取源分镜信息
  2498. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2499. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2500. // 获取目标分镜信息
  2501. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2502. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2503. $anime_id = getProp($source_segment, 'anime_id');
  2504. $episode_id = getProp($source_segment, 'episode_id');
  2505. $episode_number = getProp($source_segment, 'episode_number');
  2506. $source_segment_number = getProp($source_segment, 'segment_number');
  2507. $target_segment_number = getProp($target_segment, 'segment_number');
  2508. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2509. $target_anime_id = getProp($target_segment, 'anime_id');
  2510. $target_episode_number = getProp($target_segment, 'episode_number');
  2511. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2512. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2513. }
  2514. // 如果源分镜和目标分镜相同,无需移动
  2515. if ($source_segment_number == $target_segment_number) {
  2516. return true;
  2517. }
  2518. try {
  2519. DB::beginTransaction();
  2520. if ($source_segment_number < $target_segment_number) {
  2521. // 向后移动:源分镜移动到目标分镜之后
  2522. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2523. DB::table('mp_episode_segments')
  2524. ->where('anime_id', $anime_id)
  2525. ->where('episode_id', $episode_id)
  2526. ->where('segment_number', '>', $source_segment_number)
  2527. ->where('segment_number', '<=', $target_segment_number)
  2528. ->decrement('segment_number');
  2529. // 2. 将源分镜移动到目标分镜之后
  2530. $new_segment_number = $target_segment_number;
  2531. } else {
  2532. // 向前移动:源分镜移动到目标分镜之后
  2533. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2534. DB::table('mp_episode_segments')
  2535. ->where('anime_id', $anime_id)
  2536. ->where('episode_id', $episode_id)
  2537. ->where('segment_number', '>', $target_segment_number)
  2538. ->where('segment_number', '<', $source_segment_number)
  2539. ->increment('segment_number');
  2540. // 2. 将源分镜移动到目标分镜之后
  2541. $new_segment_number = $target_segment_number + 1;
  2542. }
  2543. // 3. 更新源分镜的序号
  2544. $update_result = DB::table('mp_episode_segments')
  2545. ->where('segment_id', $segment_id)
  2546. ->update([
  2547. 'segment_number' => $new_segment_number,
  2548. 'updated_at' => date('Y-m-d H:i:s')
  2549. ]);
  2550. if (!$update_result) {
  2551. Utils::throwError('20003:更新分镜序号失败');
  2552. }
  2553. DB::commit();
  2554. return true;
  2555. } catch (\Exception $e) {
  2556. DB::rollBack();
  2557. Utils::throwError('20003:' . $e->getMessage());
  2558. }
  2559. }
  2560. public function delSegment($data) {
  2561. $segment_id = getProp($data, 'segment_id');
  2562. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2563. if (!$segment) Utils::throwError('20003:请选择分镜');
  2564. $anime_id = getProp($segment, 'anime_id');
  2565. $episode_id = getProp($segment, 'episode_id');
  2566. $episode_number = getProp($segment, 'episode_number');
  2567. $segment_number = getProp($segment, 'segment_number');
  2568. try {
  2569. DB::beginTransaction();
  2570. // 删除分镜
  2571. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2572. if (!$boolen) {
  2573. Utils::throwError('20003:删除分镜失败');
  2574. }
  2575. // 更新其他分镜序号
  2576. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2577. }catch (\Exception $e) {
  2578. DB::rollBack();
  2579. Utils::throwError('20003:'.$e->getMessage());
  2580. }
  2581. DB::commit();
  2582. return true;
  2583. }
  2584. public function applySegment($data) {
  2585. $segment_id = getProp($data, 'segment_id');
  2586. $url = getProp($data, 'url');
  2587. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2588. if (!$url) Utils::throwError('20003:URL不能为空');
  2589. // 获取URL的文件扩展名
  2590. $urlPath = parse_url($url, PHP_URL_PATH);
  2591. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2592. // 定义图片和视频的扩展名
  2593. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2594. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2595. // 判断是图片还是视频
  2596. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2597. if (in_array($extension, $imageExtensions)) {
  2598. // 图片类型
  2599. $updateData['img_url'] = $url;
  2600. $updateData['current_type'] = 1;
  2601. } elseif (in_array($extension, $videoExtensions)) {
  2602. // 视频类型
  2603. $updateData['video_url'] = $url;
  2604. $updateData['current_type'] = 2;
  2605. } else {
  2606. Utils::throwError('20003:不支持的文件类型');
  2607. }
  2608. // 更新分镜表
  2609. $result = DB::table('mp_episode_segments')
  2610. ->where('segment_id', $segment_id)
  2611. ->update($updateData);
  2612. if (!$result) {
  2613. Utils::throwError('20003:更新分镜失败');
  2614. }
  2615. return true;
  2616. }
  2617. public function segmentHistory($data) {
  2618. $segment_id = getProp($data, 'segment_id');
  2619. // 获取历史图片
  2620. $pics = [];
  2621. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2622. foreach($pic_history as $task) {
  2623. $result_url = getProp($task, 'result_url');
  2624. if (is_json($result_url)) {
  2625. $pics = array_merge($pics, json_decode($result_url, true));
  2626. }else {
  2627. $pics[] = $result_url;
  2628. }
  2629. }
  2630. // 获取历史视频
  2631. $videos = [];
  2632. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2633. foreach($video_history as $task) {
  2634. $result_url = getProp($task, 'result_url');
  2635. if (is_json($result_url)) {
  2636. $videos = array_merge($videos, json_decode($result_url, true));
  2637. }else {
  2638. $videos[] = $result_url;
  2639. }
  2640. }
  2641. return compact('pics', 'videos');
  2642. }
  2643. public function addAct($data) {
  2644. $prev_act_id = getProp($data, 'prev_act_id');
  2645. $act_title = getProp($data, 'act_title', '');
  2646. $act_content = getProp($data, 'act_content', '');
  2647. $act_duration = getProp($data, 'act_duration', 5);
  2648. $video_url = getProp($data, 'video_url');
  2649. // 根据prev_act_id获取记录
  2650. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2651. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2652. $anime_id = getProp($prev_segment, 'anime_id');
  2653. $episode_id = getProp($prev_segment, 'episode_id');
  2654. $episode_number = getProp($prev_segment, 'episode_number');
  2655. $prev_act_number = getProp($prev_segment, 'act_number');
  2656. // 获取新的act_number
  2657. $new_act_number = $prev_act_number + 1;
  2658. try {
  2659. DB::beginTransaction();
  2660. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2661. DB::table('mp_episode_segments')
  2662. ->where('anime_id', $anime_id)
  2663. ->where('episode_id', $episode_id)
  2664. ->where('act_number', '>', $prev_act_number)
  2665. ->increment('act_number');
  2666. // 插入新片段记录
  2667. $insert_data = [
  2668. 'anime_id' => $anime_id,
  2669. 'episode_id' => $episode_id,
  2670. 'episode_number' => $episode_number,
  2671. 'act_number' => $new_act_number,
  2672. 'created_at' => date('Y-m-d H:i:s'),
  2673. 'updated_at' => date('Y-m-d H:i:s')
  2674. ];
  2675. if ($act_title) {
  2676. $insert_data['act_title'] = $act_title;
  2677. }
  2678. if ($act_content) {
  2679. $insert_data['act_content'] = $act_content;
  2680. }
  2681. if ($act_duration) {
  2682. $insert_data['act_duration'] = $act_duration;
  2683. }
  2684. if ($video_url) {
  2685. $insert_data['origin_video_url'] = $video_url;
  2686. $insert_data['current_type'] = 2;
  2687. $compressed_video_url = compressVideo($video_url);
  2688. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2689. }
  2690. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2691. if (!$id) {
  2692. Utils::throwError('20003:新增片段失败!');
  2693. }
  2694. DB::commit();
  2695. }catch (\Exception $e) {
  2696. DB::rollBack();
  2697. Utils::throwError('20003:'.$e->getMessage());
  2698. }
  2699. $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();
  2700. $segment = $segment ? (array)$segment : [];
  2701. return $segment;
  2702. }
  2703. public function editAct($data) {
  2704. $act_id = getProp($data, 'act_id');
  2705. $act_content = getProp($data, 'act_content');
  2706. $act_duration = getProp($data, 'act_duration');
  2707. $act_title = getProp($data, 'act_title');
  2708. $image_url = getProp($data, 'image_url');
  2709. $video_url = getProp($data, 'video_url');
  2710. // 参数验证
  2711. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2712. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2713. $segment = DB::table('mp_episode_segments')
  2714. ->where('id', $act_id)
  2715. ->first();
  2716. if (!$segment) Utils::throwError('20003:该片段不存在');
  2717. try {
  2718. DB::beginTransaction();
  2719. // 准备更新数据
  2720. $update_data = [
  2721. 'updated_at' => date('Y-m-d H:i:s')
  2722. ];
  2723. // 更新act相关字段
  2724. if (!empty($act_content)) {
  2725. $update_data['act_show_content'] = $act_content;
  2726. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2727. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2728. $shot_counter = 0;
  2729. $update_data['act_show_content'] = preg_replace_callback(
  2730. '/【(?:镜头|分镜)(\d+)】/u',
  2731. function($matches) use (&$shot_counter) {
  2732. $shot_counter++;
  2733. return '【镜头' . $shot_counter . '】';
  2734. },
  2735. $update_data['act_show_content']
  2736. );
  2737. }
  2738. if (!empty($act_duration)) {
  2739. $update_data['act_duration'] = $act_duration;
  2740. }
  2741. if (!empty($act_title)) {
  2742. $update_data['act_title'] = $act_title;
  2743. }
  2744. // 处理图片上传
  2745. if ($image_url) {
  2746. $update_data['img_url'] = $image_url;
  2747. $update_data['current_type'] = 1;
  2748. // 同时写入一个图片生成任务记录
  2749. if ($act_id) {
  2750. $pic_task = [
  2751. 'alias_act_id' => $act_id,
  2752. 'ref_img_url' => json_encode([]),
  2753. 'status' => 'success',
  2754. 'result_url' => json_encode([$image_url], 256),
  2755. 'model' => '',
  2756. 'created_at' => date('Y-m-d H:i:s'),
  2757. 'updated_at' => date('Y-m-d H:i:s'),
  2758. ];
  2759. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2760. }
  2761. }
  2762. // 处理视频上传
  2763. if ($video_url) {
  2764. $update_data['origin_video_url'] = $video_url;
  2765. $compressed_video_url = compressVideo($video_url);
  2766. $update_data['current_type'] = 2;
  2767. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2768. // 同时写入一个视频生成任务记录
  2769. if ($act_id) {
  2770. $video_task = [
  2771. 'alias_act_id' => $act_id,
  2772. 'status' => 'success',
  2773. 'result_url' => $update_data['origin_video_url'],
  2774. 'compressed_url' => $update_data['video_url'],
  2775. 'created_at' => date('Y-m-d H:i:s'),
  2776. 'updated_at' => date('Y-m-d H:i:s'),
  2777. ];
  2778. DB::table('mp_generate_video_tasks')->insert($video_task);
  2779. }
  2780. }
  2781. // 更新片段信息
  2782. $result = DB::table('mp_episode_segments')
  2783. ->where('id', $act_id)
  2784. ->update($update_data);
  2785. if ($result === false) {
  2786. Utils::throwError('20003:更新片段失败');
  2787. }
  2788. DB::commit();
  2789. // 返回新复制的记录
  2790. $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();
  2791. $new_segment = (array)$new_segment;
  2792. return $new_segment;
  2793. } catch (\Exception $e) {
  2794. DB::rollBack();
  2795. dLog('anime')->error('更新片段失败', [
  2796. 'act_id' => $act_id,
  2797. 'error' => $e->getMessage()
  2798. ]);
  2799. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2800. }
  2801. }
  2802. public function copyAct($data) {
  2803. $act_id = getProp($data, 'act_id');
  2804. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2805. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2806. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2807. $anime_id = getProp($source_segment, 'anime_id');
  2808. $episode_id = getProp($source_segment, 'episode_id');
  2809. $episode_number = getProp($source_segment, 'episode_number');
  2810. $act_number = getProp($source_segment, 'act_number');
  2811. try {
  2812. DB::beginTransaction();
  2813. // 新act的编号
  2814. $new_act_number = $act_number + 1;
  2815. // 更新后续所有act的act_number
  2816. DB::table('mp_episode_segments')
  2817. ->where('anime_id', $anime_id)
  2818. ->where('episode_id', $episode_id)
  2819. ->where('act_number', '>', $act_number)
  2820. ->increment('act_number');
  2821. // 复制该片段记录
  2822. $segment_data = (array)$source_segment;
  2823. unset($segment_data['id']);
  2824. $segment_data['video_url'] = '';
  2825. $segment_data['video_task_id'] = '';
  2826. $segment_data['video_task_status'] = '';
  2827. $segment_data['act_number'] = $new_act_number;
  2828. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2829. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2830. if (!$id) {
  2831. Utils::throwError('20003:复制片段失败');
  2832. }
  2833. DB::commit();
  2834. }catch (\Exception $e) {
  2835. DB::rollBack();
  2836. Utils::throwError('20003:'.$e->getMessage());
  2837. }
  2838. // 返回新复制的记录
  2839. $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();
  2840. $new_segment = $new_segment ? (array)$new_segment : [];
  2841. $new_segment['act_id'] = $id;
  2842. return $new_segment;
  2843. }
  2844. public function moveAct($data) {
  2845. $act_id = getProp($data, 'act_id');
  2846. $target_act_id = getProp($data, 'target_act_id');
  2847. // 获取源片段信息
  2848. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2849. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2850. // 获取目标片段信息
  2851. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2852. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2853. $anime_id = getProp($source_segment, 'anime_id');
  2854. $episode_id = getProp($source_segment, 'episode_id');
  2855. $source_act_number = getProp($source_segment, 'act_number');
  2856. $target_act_number = getProp($target_segment, 'act_number');
  2857. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2858. $target_anime_id = getProp($target_segment, 'anime_id');
  2859. $target_episode_id = getProp($target_segment, 'episode_id');
  2860. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2861. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2862. }
  2863. // 如果源片段和目标片段相同,无需移动
  2864. if ($source_act_number == $target_act_number) {
  2865. return true;
  2866. }
  2867. try {
  2868. DB::beginTransaction();
  2869. if ($source_act_number < $target_act_number) {
  2870. // 向后移动:源片段移动到目标片段之后
  2871. // 1. 将源片段和目标片段之间的所有片段编号减1
  2872. DB::table('mp_episode_segments')
  2873. ->where('anime_id', $anime_id)
  2874. ->where('episode_id', $episode_id)
  2875. ->where('act_number', '>', $source_act_number)
  2876. ->where('act_number', '<=', $target_act_number)
  2877. ->decrement('act_number');
  2878. // 2. 将源片段移动到目标片段之后
  2879. $new_act_number = $target_act_number;
  2880. } else {
  2881. // 向前移动:源片段移动到目标片段之后
  2882. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2883. DB::table('mp_episode_segments')
  2884. ->where('anime_id', $anime_id)
  2885. ->where('episode_id', $episode_id)
  2886. ->where('act_number', '>', $target_act_number)
  2887. ->where('act_number', '<', $source_act_number)
  2888. ->increment('act_number');
  2889. // 2. 将源片段移动到目标片段之后
  2890. $new_act_number = $target_act_number + 1;
  2891. }
  2892. // 3. 更新源片段的编号
  2893. $update_result = DB::table('mp_episode_segments')
  2894. ->where('id', $act_id)
  2895. ->update([
  2896. 'act_number' => $new_act_number,
  2897. 'updated_at' => date('Y-m-d H:i:s')
  2898. ]);
  2899. if (!$update_result) {
  2900. Utils::throwError('20003:更新片段编号失败');
  2901. }
  2902. DB::commit();
  2903. return true;
  2904. } catch (\Exception $e) {
  2905. DB::rollBack();
  2906. Utils::throwError('20003:' . $e->getMessage());
  2907. }
  2908. }
  2909. public function delAct($data) {
  2910. $act_id = getProp($data, 'act_id');
  2911. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2912. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2913. if (!$segment) Utils::throwError('20003:请选择片段');
  2914. $anime_id = getProp($segment, 'anime_id');
  2915. $episode_id = getProp($segment, 'episode_id');
  2916. $act_number = getProp($segment, 'act_number');
  2917. try {
  2918. DB::beginTransaction();
  2919. // 删除该片段记录
  2920. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2921. if (!$deleted) {
  2922. Utils::throwError('20003:删除片段失败');
  2923. }
  2924. // 更新后续act的编号
  2925. DB::table('mp_episode_segments')
  2926. ->where('anime_id', $anime_id)
  2927. ->where('episode_id', $episode_id)
  2928. ->where('act_number', '>', $act_number)
  2929. ->decrement('act_number');
  2930. DB::commit();
  2931. }catch (\Exception $e) {
  2932. DB::rollBack();
  2933. Utils::throwError('20003:'.$e->getMessage());
  2934. }
  2935. return true;
  2936. }
  2937. public function applyAct($data) {
  2938. $act_id = getProp($data, 'act_id');
  2939. $url = getProp($data, 'url');
  2940. if (!$act_id) Utils::throwError('20003:请选择片段');
  2941. if (!$url) Utils::throwError('20003:URL不能为空');
  2942. // 获取URL的文件扩展名
  2943. $urlPath = parse_url($url, PHP_URL_PATH);
  2944. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2945. // 定义图片和视频的扩展名
  2946. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2947. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2948. // 判断是图片还是视频
  2949. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2950. if (in_array($extension, $imageExtensions)) {
  2951. // 图片类型
  2952. $updateData['img_url'] = $url;
  2953. $updateData['current_type'] = 1;
  2954. } elseif (in_array($extension, $videoExtensions)) {
  2955. // 视频类型
  2956. $updateData['video_url'] = $url;
  2957. $updateData['current_type'] = 2;
  2958. } else {
  2959. Utils::throwError('20003:不支持的文件类型');
  2960. }
  2961. // 更新片段记录(全能模式下每个act只有一条记录)
  2962. $result = DB::table('mp_episode_segments')
  2963. ->where('id', $act_id)
  2964. ->update($updateData);
  2965. if (!$result) {
  2966. Utils::throwError('20003:更新片段失败');
  2967. }
  2968. return true;
  2969. }
  2970. public function actChatHistory($data) {
  2971. $act_id = getProp($data, 'act_id');
  2972. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2973. $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');
  2974. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2975. $value = (array)$value;
  2976. $value['created_at'] = transDate($value['created_at']);
  2977. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2978. else $value['reference_images'] = [];
  2979. return $value;
  2980. })->toArray();
  2981. // 获取历史图片
  2982. $url = [];
  2983. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2984. foreach($pic_history as $task) {
  2985. $result_url = getProp($task, 'result_url');
  2986. if (is_json($result_url)) {
  2987. $url = array_merge($url, json_decode($result_url, true));
  2988. }else {
  2989. $url[] = $result_url;
  2990. }
  2991. }
  2992. // 获取历史视频
  2993. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2994. foreach($video_history as $task) {
  2995. $result_url = getProp($task, 'result_url');
  2996. if (is_json($result_url)) {
  2997. $url = array_merge($url, json_decode($result_url, true));
  2998. }else {
  2999. $url[] = $result_url;
  3000. }
  3001. }
  3002. // 获取资产库
  3003. $products = [];
  3004. // 通过act_id查询片段信息获取episode_id
  3005. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  3006. if ($segment) {
  3007. $episode_id = getProp($segment, 'episode_id');
  3008. // 查询剧集信息获取roles、scenes和extra_products
  3009. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3010. if ($episode) {
  3011. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  3012. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  3013. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  3014. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  3015. // 先合并roles、scenes和props
  3016. // 处理角色数组
  3017. foreach ($roles as $role) {
  3018. $product = $role;
  3019. // 将role字段重命名为product_name
  3020. if (is_array($product) && !empty($product['role'] ?? null)) {
  3021. $product['product_name'] = $product['role'];
  3022. unset($product['role']);
  3023. $product['product'] = 1; // 标记类型为角色
  3024. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3025. }
  3026. }
  3027. // 处理场景数组
  3028. foreach ($scenes as $scene) {
  3029. $product = $scene;
  3030. // 将scene字段重命名为product_name
  3031. if (is_array($product) && !empty($product['scene'] ?? null)) {
  3032. $product['product_name'] = $product['scene'];
  3033. unset($product['scene']);
  3034. $product['product'] = 2; // 标记类型为场景
  3035. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3036. }
  3037. }
  3038. // 处理道具数组
  3039. foreach ($props as $prop) {
  3040. $product = $prop;
  3041. // 将prop字段重命名为product_name
  3042. if (is_array($product) && !empty($product['prop'] ?? null)) {
  3043. $product['product_name'] = $product['prop'];
  3044. unset($product['prop']);
  3045. $product['product'] = 3; // 标记类型为道具
  3046. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  3047. }
  3048. }
  3049. // extra_products优先级更高,直接覆盖同名的roles和scenes
  3050. foreach ($extra_products as $extra_product) {
  3051. $product_name = getProp($extra_product, 'product_name');
  3052. if ($product_name) {
  3053. $products[$product_name] = $extra_product; // 覆盖同名数据
  3054. }
  3055. }
  3056. // 重新索引数组(去除key)
  3057. $products = array_values($products);
  3058. }
  3059. }
  3060. // 获取执行中的任务
  3061. $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) {
  3062. $value = (array)$value;
  3063. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  3064. else $value['ref_image_url'] = [];
  3065. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  3066. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  3067. if (!empty($value['prompt'])) {
  3068. $prompt = $value['prompt'];
  3069. // 查找第一个【镜头】的位置
  3070. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  3071. // 从【镜头】开始截取
  3072. $prompt = substr($prompt, $matches[0][1]);
  3073. }
  3074. // 去除所有<图片X>格式的标记(X可以是任意数字)
  3075. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  3076. $value['prompt'] = $prompt;
  3077. }
  3078. return $value;
  3079. })->toArray();
  3080. return compact('chat', 'url', 'products', 'tasks');
  3081. }
  3082. public function applyAudioData($data) {
  3083. $segment_id = getProp($data, 'segment_id');
  3084. $global_data = getProp($data, 'global_data');
  3085. $segment_data = getProp($data, 'segment_data');
  3086. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3087. $global_data = is_array($global_data) ? $global_data : [];
  3088. $segment_data = is_array($segment_data) ? $segment_data : [];
  3089. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3090. $dialogue_item = null;
  3091. foreach ($global_data as $key => $item) {
  3092. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3093. $dialogue_item = $item;
  3094. unset($global_data[$key]);
  3095. break;
  3096. }
  3097. }
  3098. if ($dialogue_item) {
  3099. $segment_data[] = $dialogue_item;
  3100. }
  3101. // 特殊参数: audio_url,audio_duration,subtitle_info
  3102. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3103. // 如果不是全部存在,则仍需创建音频任务
  3104. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3105. $special_update_data = [];
  3106. $has_all_special_params = false;
  3107. // 从segment_data中提取特殊参数
  3108. $filtered_segment_data = [];
  3109. foreach ($segment_data as $item) {
  3110. $field_name = trim((string)getProp($item, 'name'));
  3111. if (in_array($field_name, $special_fields)) {
  3112. $special_update_data[$field_name] = getProp($item, 'value');
  3113. } else {
  3114. // 非特殊参数保留,继续后续处理
  3115. $filtered_segment_data[] = $item;
  3116. }
  3117. }
  3118. // 检查是否三个特殊参数都存在
  3119. if (count($special_update_data) === 3 &&
  3120. isset($special_update_data['audio_url']) &&
  3121. isset($special_update_data['audio_duration']) &&
  3122. isset($special_update_data['subtitle_info'])) {
  3123. $has_all_special_params = true;
  3124. // 立即更新到当前分镜
  3125. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3126. DB::table('mp_episode_segments')
  3127. ->where('segment_id', $segment_id)
  3128. ->update($special_update_data);
  3129. }
  3130. // 使用过滤后的segment_data继续处理其他参数
  3131. $segment_data = $filtered_segment_data;
  3132. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3133. $global_update_data = [];
  3134. $segment_update_data = [];
  3135. $global_voice_type = '';
  3136. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3137. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3138. $episode_id = getProp($target_segment, 'episode_id');
  3139. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3140. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3141. if (!$episode) Utils::throwError('20003:分集不存在');
  3142. foreach ($global_data as $item) {
  3143. $field_name = trim((string)getProp($item, 'name'));
  3144. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3145. continue;
  3146. }
  3147. $global_update_data[$field_name] = getProp($item, 'value');
  3148. if ($field_name === 'voice_type') {
  3149. $global_voice_type = trim((string)getProp($item, 'value'));
  3150. }
  3151. }
  3152. foreach ($segment_data as $item) {
  3153. $field_name = trim((string)getProp($item, 'name'));
  3154. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3155. continue;
  3156. }
  3157. $segment_update_data[$field_name] = getProp($item, 'value');
  3158. }
  3159. if ($global_voice_type) {
  3160. $timbre_info = DB::table('mp_timbres')
  3161. ->where('timbre_type', $global_voice_type)
  3162. ->select('audio_url', 'timbre_name')
  3163. ->first();
  3164. if ($timbre_info) {
  3165. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3166. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3167. }
  3168. }
  3169. try {
  3170. DB::beginTransaction();
  3171. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3172. $segment_ids_to_create_task = [];
  3173. $segments_data = [];
  3174. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3175. if (!empty($global_update_data)) {
  3176. // 如果角色不存在,则只更新当前分镜
  3177. if (!$target_voice_actor) {
  3178. // 只处理当前分镜
  3179. $affected_segments = 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. ->get();
  3183. } else {
  3184. // 获取该角色的所有分镜
  3185. $affected_segments = DB::table('mp_episode_segments')
  3186. ->where('episode_id', $episode_id)
  3187. ->where('voice_actor', $target_voice_actor)
  3188. ->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')
  3189. ->get();
  3190. }
  3191. foreach ($affected_segments as $seg) {
  3192. $seg = (array)$seg;
  3193. $sid = getProp($seg, 'segment_id');
  3194. // 检查参数是否发生变化
  3195. $has_changed = false;
  3196. foreach ($global_update_data as $field => $new_value) {
  3197. $old_value = getProp($seg, $field);
  3198. if ($old_value != $new_value) {
  3199. $has_changed = true;
  3200. break;
  3201. }
  3202. }
  3203. if ($has_changed) {
  3204. $segment_ids_to_create_task[] = $sid;
  3205. $segments_data[$sid] = $seg;
  3206. }
  3207. }
  3208. // 只有在有变化的分镜时才更新
  3209. if (!empty($segment_ids_to_create_task)) {
  3210. $global_segment_update_data = $global_update_data;
  3211. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3212. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3213. DB::table('mp_episode_segments')
  3214. ->where('episode_id', $episode_id)
  3215. ->where('voice_actor', $target_voice_actor)
  3216. ->whereIn('segment_id', $segment_ids_to_create_task)
  3217. ->update($global_segment_update_data);
  3218. }
  3219. if ($global_voice_type) {
  3220. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3221. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3222. $roles_updated = false;
  3223. foreach ($episode_roles as &$role) {
  3224. // 通过 role 字段匹配角色名,而不是 voice_name
  3225. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3226. continue;
  3227. }
  3228. $role['voice_type'] = $global_voice_type;
  3229. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3230. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3231. $roles_updated = true;
  3232. }
  3233. unset($role);
  3234. if ($roles_updated) {
  3235. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3236. 'roles' => json_encode($episode_roles, 256),
  3237. 'updated_at' => date('Y-m-d H:i:s'),
  3238. ]);
  3239. }
  3240. }
  3241. }
  3242. // 如果有单个分镜更新,检查是否有变化
  3243. if (!empty($segment_update_data)) {
  3244. // 获取当前分镜数据
  3245. $current_segment = DB::table('mp_episode_segments')
  3246. ->where('segment_id', $segment_id)
  3247. ->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')
  3248. ->first();
  3249. if ($current_segment) {
  3250. $current_segment = (array)$current_segment;
  3251. // 检查参数是否发生变化
  3252. $has_changed = false;
  3253. foreach ($segment_update_data as $field => $new_value) {
  3254. $old_value = getProp($current_segment, $field);
  3255. if ($old_value != $new_value) {
  3256. $has_changed = true;
  3257. break;
  3258. }
  3259. }
  3260. if ($has_changed) {
  3261. // 如果该分镜还未在列表中,添加进去
  3262. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3263. $segment_ids_to_create_task[] = $segment_id;
  3264. $segments_data[$segment_id] = $current_segment;
  3265. }
  3266. // 更新分镜数据并清空音频URL
  3267. $segment_update_data['audio_url'] = '';
  3268. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3269. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3270. }
  3271. }
  3272. }
  3273. // 为所有有变化的分镜创建音频合成任务
  3274. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3275. if (!empty($segment_ids_to_create_task)) {
  3276. foreach ($segment_ids_to_create_task as $sid) {
  3277. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3278. if ($sid === $segment_id && $has_all_special_params) {
  3279. continue;
  3280. }
  3281. // 重新获取更新后的分镜数据
  3282. $updated_segment = DB::table('mp_episode_segments')
  3283. ->where('segment_id', $sid)
  3284. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3285. ->first();
  3286. if (!$updated_segment) continue;
  3287. $updated_segment = (array)$updated_segment;
  3288. // 检查dialogue是否为空
  3289. $dialogue = getProp($updated_segment, 'dialogue');
  3290. if (empty($dialogue)) {
  3291. // dialogue为空时,直接写入默认音频信息
  3292. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3293. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3294. 'audio_duration' => 2.0,
  3295. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3296. 'updated_at' => date('Y-m-d H:i:s')
  3297. ]);
  3298. continue;
  3299. }
  3300. $generate_json = [
  3301. 'text' => $dialogue,
  3302. 'role' => getProp($updated_segment, 'voice_actor'),
  3303. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3304. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3305. 'emotion' => getProp($updated_segment, 'emotion'),
  3306. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3307. 'gender' => getProp($updated_segment, 'gender'),
  3308. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3309. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3310. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3311. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3312. ];
  3313. // 插入视频配音合成任务
  3314. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3315. 'alias_segment_id' => $sid,
  3316. 'generate_status' => '执行中',
  3317. 'audio_url' => '',
  3318. 'generate_json' => json_encode($generate_json, 256),
  3319. 'created_at' => date('Y-m-d H:i:s'),
  3320. 'updated_at' => date('Y-m-d H:i:s'),
  3321. ]);
  3322. if (!$dubTaskId) {
  3323. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3324. continue;
  3325. }
  3326. // 将任务ID添加到Redis列表中
  3327. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3328. // 请求远程服务器执行生成
  3329. try {
  3330. sleep(1);
  3331. $client = new Client(['timeout' => 300, 'verify' => false]);
  3332. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3333. $response = $result->getBody()->getContents();
  3334. $response_arr = json_decode($response, true);
  3335. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3336. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3337. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3338. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3339. }
  3340. } catch (\Exception $e) {
  3341. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3342. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3343. }
  3344. }
  3345. }
  3346. DB::commit();
  3347. } catch (\Exception $e) {
  3348. DB::rollBack();
  3349. Utils::throwError('20003:'.$e->getMessage());
  3350. }
  3351. return true;
  3352. }
  3353. public function episodePicsInfo($data) {
  3354. $anime_id = getProp($data, 'anime_id');
  3355. $episode_id = getProp($data, 'episode_id');
  3356. // 参数验证
  3357. if (!$anime_id && !$episode_id) {
  3358. Utils::throwError('20003:请提供动漫ID或分集ID');
  3359. }
  3360. // 根据参数获取数据源
  3361. if ($episode_id) {
  3362. // 从剧集表获取
  3363. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3364. if (!$source) Utils::throwError('20003:该剧集不存在');
  3365. $table_name = 'mp_anime_episodes';
  3366. $id_field = 'id';
  3367. $id_value = $episode_id;
  3368. // 获取剧集的anime_id用于继承全局数据
  3369. $anime_id = getProp($source, 'anime_id');
  3370. } else {
  3371. // 从动漫表获取
  3372. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3373. if (!$source) Utils::throwError('20003:该动漫不存在');
  3374. $table_name = 'mp_animes';
  3375. $id_field = 'id';
  3376. $id_value = $anime_id;
  3377. }
  3378. $source = (array)$source;
  3379. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3380. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3381. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3382. // 如果是分集数据,需要处理继承和任务创建逻辑
  3383. if ($episode_id) {
  3384. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3385. }
  3386. // 返回生成器函数,用于 SSE 流式输出
  3387. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3388. $startTime = time();
  3389. $maxDuration = 600; // 10分钟超时
  3390. $checkInterval = 3; // 每3秒检查一次
  3391. // Redis 缓存键
  3392. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3393. // 生成当前数据的哈希值用于比较
  3394. $generateHash = function($roles, $scenes, $props) {
  3395. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3396. };
  3397. // 发送初始数据
  3398. $currentHash = $generateHash($roles, $scenes, $props);
  3399. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3400. echo "data: " . json_encode([
  3401. 'type' => 'init',
  3402. 'data' => [
  3403. 'roles' => $roles,
  3404. 'scenes' => $scenes,
  3405. 'props' => $props,
  3406. 'start_time' => $startTime
  3407. ]
  3408. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3409. if (ob_get_level() > 0) {
  3410. ob_flush();
  3411. }
  3412. flush();
  3413. // 持续轮询任务状态
  3414. while (time() - $startTime < $maxDuration) {
  3415. $hasProcessing = false;
  3416. $updated = false;
  3417. // 检查角色任务状态
  3418. foreach ($roles as $index => &$role) {
  3419. $task_id = getProp($role, 'task_id');
  3420. $task_status = getProp($role, 'task_status');
  3421. $existing_url = getProp($role, 'url');
  3422. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3423. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3424. $hasProcessing = ($task_status === 'processing');
  3425. // 查询任务状态
  3426. $task = DB::table('mp_generate_pic_tasks')
  3427. ->where('id', $task_id)
  3428. ->select('id', 'status', 'result_url', 'error_message')
  3429. ->first();
  3430. if ($task) {
  3431. $task = (array)$task;
  3432. $status = getProp($task, 'status');
  3433. // 如果任务完成或失败
  3434. if (in_array($status, ['success', 'failed'])) {
  3435. $role['task_status'] = $status;
  3436. if ($status === 'success') {
  3437. $result_url = getProp($task, 'result_url');
  3438. if ($result_url) {
  3439. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3440. if (is_array($result_urls) && !empty($result_urls[0])) {
  3441. $role['url'] = $result_urls[0];
  3442. }
  3443. }
  3444. }
  3445. $updated = true;
  3446. } else if ($status === 'processing') {
  3447. $hasProcessing = true;
  3448. }
  3449. }
  3450. }
  3451. }
  3452. // 检查场景任务状态
  3453. foreach ($scenes as $index => &$scene) {
  3454. $task_id = getProp($scene, 'task_id');
  3455. $task_status = getProp($scene, 'task_status');
  3456. $existing_url = getProp($scene, 'url');
  3457. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3458. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3459. $hasProcessing = ($task_status === 'processing');
  3460. // 查询任务状态
  3461. $task = DB::table('mp_generate_pic_tasks')
  3462. ->where('id', $task_id)
  3463. ->select('id', 'status', 'result_url', 'error_message')
  3464. ->first();
  3465. if ($task) {
  3466. $task = (array)$task;
  3467. $status = getProp($task, 'status');
  3468. // 如果任务完成或失败
  3469. if (in_array($status, ['success', 'failed'])) {
  3470. $scene['task_status'] = $status;
  3471. if ($status === 'success') {
  3472. $result_url = getProp($task, 'result_url');
  3473. if ($result_url) {
  3474. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3475. if (is_array($result_urls) && !empty($result_urls[0])) {
  3476. $scene['url'] = $result_urls[0];
  3477. }
  3478. }
  3479. }
  3480. $updated = true;
  3481. } else if ($status === 'processing') {
  3482. $hasProcessing = true;
  3483. }
  3484. }
  3485. }
  3486. }
  3487. // 检查道具任务状态
  3488. foreach ($props as $index => &$prop) {
  3489. $task_id = getProp($prop, 'task_id');
  3490. $task_status = getProp($prop, 'task_status');
  3491. $existing_url = getProp($prop, 'url');
  3492. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3493. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3494. $hasProcessing = ($task_status === 'processing');
  3495. // 查询任务状态
  3496. $task = DB::table('mp_generate_pic_tasks')
  3497. ->where('id', $task_id)
  3498. ->select('id', 'status', 'result_url', 'error_message')
  3499. ->first();
  3500. if ($task) {
  3501. $task = (array)$task;
  3502. $status = getProp($task, 'status');
  3503. // 如果任务完成或失败
  3504. if (in_array($status, ['success', 'failed'])) {
  3505. $prop['task_status'] = $status;
  3506. if ($status === 'success') {
  3507. $result_url = getProp($task, 'result_url');
  3508. if ($result_url) {
  3509. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3510. if (is_array($result_urls) && !empty($result_urls[0])) {
  3511. $prop['url'] = $result_urls[0];
  3512. }
  3513. }
  3514. }
  3515. $updated = true;
  3516. } else if ($status === 'processing') {
  3517. $hasProcessing = true;
  3518. }
  3519. }
  3520. }
  3521. }
  3522. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3523. if ($updated) {
  3524. $newHash = $generateHash($roles, $scenes, $props);
  3525. $cachedHash = Redis::get($cacheKey);
  3526. // 只有当数据真正变化时才更新数据库和发送事件
  3527. if ($newHash !== $cachedHash) {
  3528. try {
  3529. // 更新数据库
  3530. DB::table($table_name)->where($id_field, $id_value)->update([
  3531. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3532. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3533. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3534. 'updated_at' => date('Y-m-d H:i:s')
  3535. ]);
  3536. // 更新缓存
  3537. Redis::setex($cacheKey, 600, $newHash);
  3538. // 发送更新事件
  3539. echo "data: " . json_encode([
  3540. 'type' => 'update',
  3541. 'data' => [
  3542. 'roles' => $roles,
  3543. 'scenes' => $scenes,
  3544. 'props' => $props,
  3545. 'elapsed_time' => time() - $startTime
  3546. ]
  3547. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3548. if (ob_get_level() > 0) {
  3549. ob_flush();
  3550. }
  3551. flush();
  3552. } catch (\Exception $e) {
  3553. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3554. }
  3555. } else {
  3556. // 即使哈希相同,如果有URL更新也要发送事件
  3557. $hasUrlUpdate = false;
  3558. foreach ($roles as $role) {
  3559. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3560. $hasUrlUpdate = true;
  3561. break;
  3562. }
  3563. }
  3564. if (!$hasUrlUpdate) {
  3565. foreach ($scenes as $scene) {
  3566. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3567. $hasUrlUpdate = true;
  3568. break;
  3569. }
  3570. }
  3571. }
  3572. if (!$hasUrlUpdate) {
  3573. foreach ($props as $prop) {
  3574. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3575. $hasUrlUpdate = true;
  3576. break;
  3577. }
  3578. }
  3579. }
  3580. if ($hasUrlUpdate) {
  3581. // 强制更新数据库和发送事件
  3582. try {
  3583. DB::table($table_name)->where($id_field, $id_value)->update([
  3584. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3585. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3586. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3587. 'updated_at' => date('Y-m-d H:i:s')
  3588. ]);
  3589. // 更新缓存
  3590. Redis::setex($cacheKey, 600, $newHash);
  3591. // 发送更新事件
  3592. echo "data: " . json_encode([
  3593. 'type' => 'update',
  3594. 'data' => [
  3595. 'roles' => $roles,
  3596. 'scenes' => $scenes,
  3597. 'props' => $props,
  3598. 'elapsed_time' => time() - $startTime
  3599. ]
  3600. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3601. if (ob_get_level() > 0) {
  3602. ob_flush();
  3603. }
  3604. flush();
  3605. } catch (\Exception $e) {
  3606. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3607. }
  3608. }
  3609. }
  3610. }
  3611. // 如果所有任务都已完成,发送完成事件并退出
  3612. if (!$hasProcessing) {
  3613. // 查询数据库中的最终数据,确保返回最新的完整数据
  3614. try {
  3615. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3616. if ($finalSource) {
  3617. $finalSource = (array)$finalSource;
  3618. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3619. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3620. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3621. // 使用数据库中的最终数据
  3622. $roles = $finalRoles;
  3623. $scenes = $finalScenes;
  3624. $props = $finalProps;
  3625. }
  3626. } catch (\Exception $e) {
  3627. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3628. // 如果查询失败,继续使用内存中的数据
  3629. }
  3630. // 清理缓存
  3631. Redis::del($cacheKey);
  3632. echo "data: " . json_encode([
  3633. 'type' => 'completed',
  3634. 'data' => [
  3635. 'roles' => $roles,
  3636. 'scenes' => $scenes,
  3637. 'props' => $props,
  3638. 'total_time' => time() - $startTime
  3639. ]
  3640. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3641. if (ob_get_level() > 0) {
  3642. ob_flush();
  3643. }
  3644. flush();
  3645. break;
  3646. }
  3647. // 等待下次检查
  3648. sleep($checkInterval);
  3649. }
  3650. // 超时处理
  3651. if (time() - $startTime >= $maxDuration) {
  3652. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3653. try {
  3654. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3655. if ($finalSource) {
  3656. $finalSource = (array)$finalSource;
  3657. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3658. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3659. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3660. // 使用数据库中的最终数据
  3661. $roles = $finalRoles;
  3662. $scenes = $finalScenes;
  3663. $props = $finalProps;
  3664. }
  3665. } catch (\Exception $e) {
  3666. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3667. // 如果查询失败,继续使用内存中的数据
  3668. }
  3669. // 清理缓存
  3670. Redis::del($cacheKey);
  3671. echo "data: " . json_encode([
  3672. 'type' => 'timeout',
  3673. 'message' => '轮询超时,请刷新页面查看最新状态',
  3674. 'data' => [
  3675. 'roles' => $roles,
  3676. 'scenes' => $scenes,
  3677. 'props' => $props
  3678. ]
  3679. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3680. if (ob_get_level() > 0) {
  3681. ob_flush();
  3682. }
  3683. flush();
  3684. }
  3685. };
  3686. }
  3687. public function clipSegmentVideo($data) {
  3688. $segment_id = getProp($data, 'segment_id');
  3689. $video_time_point_start = getProp($data, 'video_time_point_start');
  3690. $video_time_point_end = getProp($data, 'video_time_point_end');
  3691. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3692. Utils::throwError('20003:参数异常');
  3693. }
  3694. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3695. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3696. }
  3697. $video_duration = $video_time_point_end - $video_time_point_start;
  3698. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3699. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3700. 'video_duration' => $video_duration,
  3701. 'video_time_point_start' => $video_time_point_start,
  3702. 'video_time_point_end' => $video_time_point_end,
  3703. 'updated_at' => date('Y-m-d H:i:s')
  3704. ]);
  3705. }
  3706. // 轮训获取图片任务结果
  3707. private function loopGetPicTaskResult($task_id) {
  3708. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3709. if (!$task) {
  3710. return '';
  3711. }
  3712. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3713. $model = getProp($task, 'model');
  3714. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3715. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3716. $isSyncModel = $isVolcModel || $isGptModel;
  3717. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3718. $start_count = 0;
  3719. $img_url = '';
  3720. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3721. sleep(3);
  3722. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3723. // 如果任务已经完成,直接返回结果
  3724. if ($task->status === 'success' && $task->result_url) {
  3725. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3726. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3727. }
  3728. // 如果任务已失败,返回空
  3729. if ($task->status === 'failed') {
  3730. return '';
  3731. }
  3732. if ($isSyncModel) continue;
  3733. // 查询任务状态
  3734. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3735. if ($statusInfo['status'] === 'success') {
  3736. $task->updateStatus('success', [
  3737. 'result_url' => $statusInfo['result_url'],
  3738. 'result_json' => $statusInfo['result_json'] ?? []
  3739. ]);
  3740. // 同步调整分镜图片状态和结果
  3741. if (getProp($task, 'alias_segment_id')) {
  3742. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3743. 'img_url' => $statusInfo['result_url'][0],
  3744. 'pic_task_status' => '已完成',
  3745. ]);
  3746. }
  3747. $img_url = $statusInfo['result_url'][0];
  3748. break;
  3749. } elseif ($statusInfo['status'] === 'failed') {
  3750. $task->updateStatus('failed', [
  3751. 'error_message' => $statusInfo['error_message'],
  3752. 'result_json' => $statusInfo['result_json'] ?? []
  3753. ]);
  3754. if (getProp($task, 'alias_segment_id')) {
  3755. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3756. 'pic_task_status' => '失败',
  3757. ]);
  3758. }
  3759. break;
  3760. }
  3761. $start_count++;
  3762. }
  3763. return $img_url;
  3764. }
  3765. /**
  3766. * 从分镜内容中提取涉及的角色
  3767. */
  3768. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3769. $found_characters = [];
  3770. foreach ($available_characters as $character) {
  3771. // 检查角色名称是否在分镜内容中出现
  3772. if (strpos($segment_content, $character) !== false) {
  3773. $found_characters[] = $character;
  3774. }
  3775. }
  3776. if (!$found_characters) {
  3777. foreach ($roles as $character) {
  3778. // 检查角色名称是否在分镜内容中出现
  3779. if (strpos($segment_content, $character) !== false) {
  3780. $found_characters[] = $character;
  3781. }
  3782. }
  3783. }
  3784. return array_unique($found_characters);
  3785. }
  3786. // 从分镜剧本中提取关键字段
  3787. private function handleSegmentContent(&$data) {
  3788. $segmentContent = getProp($data, 'segment_content');
  3789. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3790. $segmentData = [
  3791. 'description' => '',
  3792. 'composition' => '',
  3793. 'camera_movement' => '',
  3794. 'voice_actor' => '',
  3795. 'dialogue' => '',
  3796. 'frame_type' => '',
  3797. 'scene' => '', // 场景
  3798. 'characters' => '', // 出镜角色
  3799. 'tail_frame' => '', // 尾帧描述
  3800. 'emotion' => '中性', // 情感
  3801. 'gender' => '0', // 性别(0未知,1男,2女)
  3802. 'speed_ratio' => 0, // 语速
  3803. 'loudness_ratio' => 0, // 音量
  3804. 'emotion_scale' => 4, // 情感强度
  3805. 'pitch' => 0, // 音调
  3806. ];
  3807. // 用于存储需要从 segment_content 中移除的匹配项
  3808. $replaceEmptyArr = [];
  3809. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3810. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3811. $segmentData['description'] = trim($descMatch[1]);
  3812. $data['description'] = trim($descMatch[1]);
  3813. }
  3814. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3815. $segmentData['composition'] = trim($compMatch[1]);
  3816. $data['composition'] = trim($compMatch[1]);
  3817. }
  3818. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3819. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3820. $data['camera_movement'] = trim($cameraMatch[1]);
  3821. }
  3822. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3823. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3824. $data['voice_actor'] = trim($voiceMatch[1]);
  3825. }
  3826. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3827. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3828. $data['dialogue'] = trim($dialogueMatch[1]);
  3829. }
  3830. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3831. $segmentData['frame_type'] = trim($frameMatch[1]);
  3832. $data['frame_type'] = trim($frameMatch[1]);
  3833. }
  3834. // 场景字段
  3835. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3836. $segmentData['scene'] = trim($sceneMatch[1]);
  3837. $data['scene'] = trim($sceneMatch[1]);
  3838. }
  3839. // 出镜角色字段
  3840. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3841. $segmentData['characters'] = trim($charactersMatch[1]);
  3842. $data['characters'] = trim($charactersMatch[1]);
  3843. }
  3844. // 尾帧描述字段
  3845. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3846. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3847. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3848. }
  3849. // 情感字段
  3850. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3851. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3852. $segmentData['emotion'] = trim($emotionMatch[1]);
  3853. $data['emotion'] = trim($emotionMatch[1]);
  3854. }
  3855. // 性别字段
  3856. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3857. $replaceEmptyArr[] = trim($genderMatch[0]);
  3858. $genderStr = trim($genderMatch[1]);
  3859. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3860. $segmentData['gender'] = '1';
  3861. $data['gender'] = '1';
  3862. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3863. $segmentData['gender'] = '2';
  3864. $data['gender'] = '2';
  3865. } else {
  3866. $segmentData['gender'] = '0';
  3867. $data['gender'] = '0';
  3868. }
  3869. }
  3870. // 语速字段
  3871. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3872. $replaceEmptyArr[] = trim($speedMatch[0]);
  3873. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3874. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3875. }
  3876. // 音量字段
  3877. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3878. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3879. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3880. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3881. }
  3882. // 情感强度字段
  3883. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3884. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3885. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3886. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3887. }
  3888. // 音调字段
  3889. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3890. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3891. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3892. $data['pitch'] = (int)trim($pitchMatch[1]);
  3893. }
  3894. // 从 segment_content 中移除已提取的配音参数字段
  3895. if (!empty($replaceEmptyArr)) {
  3896. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3897. }
  3898. // 如果有配音角色,查询音色信息并验证情感
  3899. $voice_actor = $segmentData['voice_actor'];
  3900. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3901. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3902. $anime_id = getProp($data, 'anime_id');
  3903. $episode_id = getProp($data, 'episode_id');
  3904. // 优先从剧集的角色列表中查找
  3905. $roles = [];
  3906. if ($episode_id) {
  3907. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3908. if ($episode && getProp($episode, 'roles')) {
  3909. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3910. }
  3911. }
  3912. // 如果剧集中没有,从动漫的角色列表中查找
  3913. if (empty($roles) && $anime_id) {
  3914. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3915. if ($anime && getProp($anime, 'roles')) {
  3916. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3917. }
  3918. }
  3919. // 查找匹配的角色音色信息
  3920. $timbre_info = null;
  3921. foreach ($roles as $role) {
  3922. if (getProp($role, 'role') === $voice_actor) {
  3923. $timbre_info = $role;
  3924. break;
  3925. }
  3926. }
  3927. // 如果找到音色信息,添加到数据中
  3928. if ($timbre_info) {
  3929. $voice_type = getProp($timbre_info, 'voice_type');
  3930. $voice_name = getProp($timbre_info, 'voice_name');
  3931. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3932. if ($voice_type) {
  3933. $data['voice_type'] = $voice_type;
  3934. $segmentData['voice_type'] = $voice_type;
  3935. }
  3936. if ($voice_name) {
  3937. $data['voice_name'] = $voice_name;
  3938. $segmentData['voice_name'] = $voice_name;
  3939. }
  3940. if ($voice_audio_url) {
  3941. $data['voice_audio_url'] = $voice_audio_url;
  3942. $segmentData['voice_audio_url'] = $voice_audio_url;
  3943. }
  3944. // 验证情感是否在音色支持的情感列表中
  3945. if ($voice_type) {
  3946. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3947. if ($timbre_emotion) {
  3948. $timbre_emotion = explode(',', $timbre_emotion);
  3949. } else {
  3950. $timbre_emotion = [];
  3951. }
  3952. $emotion = getProp($segmentData, 'emotion', '中性');
  3953. if (!in_array($emotion, $timbre_emotion)) {
  3954. $emotion = '中性';
  3955. }
  3956. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3957. $emotion_list = array_flip($emotion_list);
  3958. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3959. $data['emotion_type'] = $emotion_type;
  3960. $segmentData['emotion_type'] = $emotion_type;
  3961. }
  3962. }
  3963. }
  3964. return $segmentData;
  3965. }
  3966. public function createSegmentVideoTask($data) {
  3967. $segment_id = getProp($data, 'segment_id');
  3968. $tail_frame = getProp($data, 'tail_frame');
  3969. $first_frame_url = getProp($data, 'first_frame_url');
  3970. $tail_frame_url = getProp($data, 'tail_frame_url');
  3971. $generate_audio = getProp($data, 'generate_audio', 0);
  3972. if (!$segment_id) {
  3973. Utils::throwError('1002:分镜ID不能为空');
  3974. }
  3975. // 获取分镜信息
  3976. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3977. if (!$segment) {
  3978. Utils::throwError('20003:分镜不存在');
  3979. }
  3980. $segment = (array)$segment;
  3981. $episode_id = getProp($segment, 'episode_id');
  3982. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3983. if (!$ratio) $ratio = '9:16';
  3984. // 获取分镜内容
  3985. $segmentContent = getProp($segment, 'segment_content', '');
  3986. // 检查 $segmentContent 中是否已有尾帧描述
  3987. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3988. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3989. $finalTailFrame = '';
  3990. if ($tail_frame) {
  3991. // 用户输入了尾帧描述,优先使用
  3992. $finalTailFrame = $tail_frame;
  3993. // 如果 segmentContent 中已有尾帧描述,需要替换
  3994. if ($contentHasTailFrame) {
  3995. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3996. }
  3997. } elseif ($contentHasTailFrame) {
  3998. // segmentContent 中有尾帧描述,使用它
  3999. $finalTailFrame = trim($contentTailFrameMatch[1]);
  4000. } else {
  4001. // 两者都没有,使用分镜表中的尾帧描述
  4002. $finalTailFrame = getProp($segment, 'tail_frame', '');
  4003. }
  4004. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  4005. $hasDialogue = false;
  4006. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  4007. $dialogue = trim($dialogueMatch[1]);
  4008. // 如果台词不为空且不是"无"
  4009. if (!empty($dialogue) && $dialogue !== '无') {
  4010. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  4011. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  4012. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  4013. $hasDialogue = true;
  4014. }
  4015. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  4016. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  4017. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  4018. if (!preg_match('/^[“]/', $dialogue)) {
  4019. $dialogue = '“' . $dialogue;
  4020. }
  4021. if (!preg_match('/[”]$/', $dialogue)) {
  4022. $dialogue .= '”';
  4023. }
  4024. // 将修改后的台词替换回 $segmentContent
  4025. $originalDialogue = $dialogueMatch[1];
  4026. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  4027. }
  4028. }
  4029. // 构建完整的提示词
  4030. $fullPrompt = $segmentContent;
  4031. if ($finalTailFrame && !$contentHasTailFrame) {
  4032. // 只有当 segmentContent 中没有尾帧描述时才追加
  4033. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  4034. }
  4035. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  4036. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  4037. $fullPrompt = trim($fullPrompt);
  4038. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  4039. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  4040. // 智能选择视频时长
  4041. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  4042. $videoDuration = -1;
  4043. // 处理视频模型
  4044. $model = getProp($data, 'model');
  4045. if (!$model) {
  4046. // 用户没有输入,从episode表获取
  4047. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  4048. $model = getProp($episode, 'video_model');
  4049. if (!$model) {
  4050. // episode表也没有,使用默认值
  4051. $model = 'doubao-seedance-1-5-pro-251215';
  4052. }
  4053. }
  4054. // 验证模型是否在可用模型表中
  4055. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4056. $model = 'doubao-seedance-1-5-pro-251215';
  4057. }
  4058. // 保存到episode表
  4059. $episode_id = getProp($segment, 'episode_id');
  4060. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4061. 'video_model' => $model,
  4062. 'updated_at' => date('Y-m-d H:i:s')
  4063. ]);
  4064. // 构建视频生成参数
  4065. $videoParams = [
  4066. 'model' => $model,
  4067. 'alias_segment_id' => $segment_id,
  4068. 'prompt' => trim($fullPrompt),
  4069. 'video_duration' => $videoDuration,
  4070. 'video_resolution' => '720P',
  4071. 'seed' => -1,
  4072. 'ratio' => $ratio,
  4073. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4074. 'draft' => false,
  4075. 'watermark' => false,
  4076. 'camera_fixed' => false,
  4077. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4078. ];
  4079. // 如果分镜有图片,作为首帧
  4080. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  4081. $hasVideo = !empty(getProp($segment, 'video_url'));
  4082. if ($hasImage) {
  4083. if ($first_frame_url) {
  4084. $videoParams['first_frame_url'] = $first_frame_url;
  4085. }else {
  4086. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4087. }
  4088. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4089. }
  4090. // 构建content数组
  4091. $videoParams['content'] = [
  4092. [
  4093. 'type' => 'text',
  4094. 'text' => $videoParams['prompt'],
  4095. ]
  4096. ];
  4097. // 如果有首帧图片,添加到content中
  4098. if ($hasImage) {
  4099. 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'])) {
  4100. $videoParams['content'][] = [
  4101. 'type' => 'image_url',
  4102. 'image_url' => [
  4103. 'url' => $videoParams['first_frame_url'],
  4104. ],
  4105. 'role' => 'reference_image',
  4106. ];
  4107. if (isset($videoParams['tail_frame_url'])) {
  4108. $videoParams['content'][] = [
  4109. 'type' => 'image_url',
  4110. 'image_url' => [
  4111. 'url' => $videoParams['tail_frame_url'],
  4112. ],
  4113. 'role' => 'reference_image',
  4114. ];
  4115. }
  4116. }else {
  4117. $videoParams['content'][] = [
  4118. 'type' => 'image_url',
  4119. 'image_url' => [
  4120. 'url' => $videoParams['first_frame_url'],
  4121. ],
  4122. 'role' => 'first_frame',
  4123. ];
  4124. if (isset($videoParams['tail_frame_url'])) {
  4125. $videoParams['content'][] = [
  4126. 'type' => 'image_url',
  4127. 'image_url' => [
  4128. 'url' => $videoParams['tail_frame_url'],
  4129. ],
  4130. 'role' => 'last_frame',
  4131. ];
  4132. }
  4133. }
  4134. }
  4135. // 获取配音音频URL
  4136. $audioUrl = getProp($segment, 'audio_url');
  4137. $audioDuration = getProp($segment, 'audio_duration');
  4138. // 音频传入的前提:必须有至少一张图片或一个视频
  4139. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4140. // 余额预检:按预估时长计算所需积分,不足直接报错
  4141. $chargeDuration = (int)ceil((float)$audioDuration);
  4142. if ($chargeDuration <= 0) {
  4143. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4144. }
  4145. $this->pointsService->checkUserPointsEnough(
  4146. $this->pointsService->getVideoChargePoints([
  4147. 'model' => $model,
  4148. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4149. 'video_duration' => $chargeDuration,
  4150. 'ratio' => $ratio,
  4151. 'generate_audio' => $current_generate_audio,
  4152. ])
  4153. );
  4154. // dd($videoParams);
  4155. // 根据模型选择不同的视频生成方法
  4156. if (strpos($model, 'jimeng') !== false) {
  4157. // 即梦模型参数调整
  4158. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4159. unset($videoParams['content']); // 即梦不使用content格式
  4160. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4161. } elseif (strpos($model, 'kling') !== false) {
  4162. // Keling模型参数调整
  4163. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4164. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4165. unset($videoParams['ratio']);
  4166. unset($videoParams['content']); // Keling不使用content格式
  4167. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4168. } elseif (strpos($model, 'zhizhen') !== false) {
  4169. // 智帧20等新模型使用统一API
  4170. // 构建统一API参数
  4171. $unifiedParams = [
  4172. 'model_code' => $model,
  4173. 'alias_segment_id' => $segment_id,
  4174. 'prompt' => trim($fullPrompt),
  4175. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4176. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4177. 'video_ratio' => $ratio,
  4178. 'seed' => -1,
  4179. ];
  4180. // 构建parameters参数
  4181. $parameters = [
  4182. 'seconds' => $unifiedParams['video_duration'],
  4183. 'resolution' => $unifiedParams['video_resolution'],
  4184. 'ratio' => $ratio,
  4185. // 'video_mode' => 'multi_image',
  4186. // 'mode' => 'multi_image',
  4187. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4188. ];
  4189. $hasImage = false;
  4190. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4191. if ($hasImage) {
  4192. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4193. if (isset($videoParams['tail_frame_url'])) {
  4194. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4195. }
  4196. // 只有在有图片的情况下才能添加参考音频
  4197. if ($audioUrl) {
  4198. // $parameters['reference_audios'] = [$audioUrl];
  4199. }
  4200. } else {
  4201. // 没有图片时,记录错误日志
  4202. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4203. 'segment_id' => $segment_id,
  4204. 'model' => $model
  4205. ]);
  4206. }
  4207. $unifiedParams['parameters'] = $parameters;
  4208. // 调用统一API创建任务
  4209. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4210. } else {
  4211. // Seedance模型(默认)
  4212. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4213. if ($this->isKuaikuaiSeedanceModel($model)) {
  4214. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4215. if ($canUseAudio && $audioUrl) {
  4216. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4217. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4218. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4219. // 优化提示词,增加音频相关描述
  4220. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4221. $videoParams['prompt'] = $audioPrompt;
  4222. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4223. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4224. }
  4225. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4226. } 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'])) {
  4227. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4228. // 添加配音音频到content中
  4229. $videoParams['content'][] = [
  4230. 'type' => 'audio_url',
  4231. 'audio_url' => [
  4232. 'url' => $audioUrl,
  4233. ],
  4234. 'role' => 'reference_audio',
  4235. ];
  4236. // 优化提示词,增加音频相关描述
  4237. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4238. $videoParams['prompt'] = $audioPrompt;
  4239. $videoParams['content'][0]['text'] = $audioPrompt;
  4240. } else {
  4241. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4242. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4243. }
  4244. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4245. }
  4246. }
  4247. // 更新分镜表的视频任务信息
  4248. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4249. 'video_task_id' => $task->id,
  4250. 'video_task_status' => '生成中',
  4251. 'generate_audio' => $generate_audio,
  4252. 'updated_at' => date('Y-m-d H:i:s')
  4253. ]);
  4254. return [
  4255. 'task_id' => $task->id,
  4256. 'status' => $task->status,
  4257. 'segment_id' => $segment_id,
  4258. 'video_duration' => $videoDuration
  4259. ];
  4260. }
  4261. /**
  4262. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4263. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4264. *
  4265. * @param string $model
  4266. * @return bool
  4267. */
  4268. public function isKuaikuaiSeedanceModel(string $model): bool
  4269. {
  4270. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4271. }
  4272. /**
  4273. * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
  4274. *
  4275. * @param string $model
  4276. * @return bool
  4277. */
  4278. public function isBaiduSeedanceModel(string $model): bool
  4279. {
  4280. return in_array($model, [
  4281. 'baidu-doubao-seedance-2-0-260128',
  4282. 'baidu-doubao-seedance-2-0-fast-260128',
  4283. 'baidu-doubao-seedance-2-0-mini-260615',
  4284. 'baidu-doubao-seedance-2-5-260628',
  4285. ], true);
  4286. }
  4287. /**
  4288. * 是否为海外百度Seedance(dreamina真人素材空间)模型
  4289. * 系统内使用 baidu-dreamina- 前缀名,请求网关时映射为 dreamina-* 原名
  4290. *
  4291. * @param string $model
  4292. * @return bool
  4293. */
  4294. public function isOverseasBaiduSeedanceModel(string $model): bool
  4295. {
  4296. return in_array($model, [
  4297. 'baidu-dreamina-seedance-2-0-260128',
  4298. 'baidu-dreamina-seedance-2-0-fast-260128',
  4299. 'baidu-dreamina-seedance-2-0-mini-260615',
  4300. 'baidu-dreamina-seedance-2-5-260628',
  4301. ], true);
  4302. }
  4303. /**
  4304. * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-doubao-* / baidu-dreamina-* / 快快AI seed-2 系列)
  4305. * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
  4306. *
  4307. * @param string $model
  4308. * @return bool
  4309. */
  4310. public function isSeedance20SeriesModel(string $model): bool
  4311. {
  4312. return strpos($model, 'doubao-seedance-2.0') !== false
  4313. || $this->isKuaikuaiSeedanceModel($model)
  4314. || $this->isBaiduSeedanceModel($model)
  4315. || $this->isOverseasBaiduSeedanceModel($model);
  4316. }
  4317. public function createActVideoTask($data) {
  4318. $act_id = getProp($data, 'act_id');
  4319. $first_frame_url = getProp($data, 'first_frame_url');
  4320. $tail_frame_url = getProp($data, 'tail_frame_url');
  4321. $generate_audio = getProp($data, 'generate_audio', 1);
  4322. $video_duration = getProp($data, 'video_duration');
  4323. $video_resolution = getProp($data, 'video_resolution');
  4324. $ratio = getProp($data, 'ratio');
  4325. $products = getProp($data, 'products', []);
  4326. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4327. if (!is_array($reference_images) || !is_array($products)) {
  4328. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4329. }
  4330. if (!$act_id) {
  4331. Utils::throwError('1002:片段ID不能为空');
  4332. }
  4333. // 获取片段信息
  4334. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4335. if (!$act) {
  4336. Utils::throwError('20003:片段不存在');
  4337. }
  4338. $act = (array)$act;
  4339. $anime_id = getProp($act, 'anime_id');
  4340. $episode_id = getProp($act, 'episode_id');
  4341. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4342. $ace_mode = getProp($anime, 'ace_mode');
  4343. $art_style_type = getProp($anime, 'art_style_type');
  4344. $art_style = getProp($anime, 'art_style');
  4345. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4346. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4347. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4348. // 将资产中新出现的资产放到extra_products中
  4349. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4350. if (!empty($products) && $episode) {
  4351. // 获取剧集中的角色、场景和道具列表
  4352. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4353. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4354. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4355. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4356. // 构建角色名称列表
  4357. $role_names = array_column($roles, 'role');
  4358. // 构建场景名称列表
  4359. $scene_names = array_column($scenes, 'scene');
  4360. // 构建道具名称列表
  4361. $prop_names = array_column($props, 'prop');
  4362. // 遍历传入的products
  4363. foreach ($products as $product) {
  4364. $product_name = getProp($product, 'product_name');
  4365. // 如果product_name不在roles、scenes和props中
  4366. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4367. // 查找是否在extra_products中存在同名的
  4368. $found = false;
  4369. foreach ($extra_products as $key => $extra_product) {
  4370. if (getProp($extra_product, 'product_name') === $product_name) {
  4371. // 有同名的则覆盖
  4372. $extra_products[$key] = $product;
  4373. $found = true;
  4374. break;
  4375. }
  4376. }
  4377. // 没有则新增
  4378. if (!$found) {
  4379. $extra_products[] = $product;
  4380. }
  4381. }
  4382. }
  4383. if ($extra_products) {
  4384. // 保存到数据库
  4385. DB::table('mp_anime_episodes')
  4386. ->where('id', $episode_id)
  4387. ->update([
  4388. 'extra_products' => json_encode($extra_products, 256),
  4389. 'updated_at' => date('Y-m-d H:i:s')
  4390. ]);
  4391. }
  4392. }
  4393. // 获取分镜内容
  4394. $actContent = getProp($act, 'act_show_content', '');
  4395. // 音效同出(默认使用)
  4396. $current_generate_audio = $generate_audio ? 1 : 0;
  4397. // 处理视频模型(需在构建提示词之前解析:决定角色音色是否使用参考音频)
  4398. $model = getProp($data, 'model');
  4399. if (!$model) {
  4400. $model = getProp($episode, 'video_model');
  4401. if (!$model) {
  4402. // episode表也没有,使用默认值
  4403. $model = 'seed-2';
  4404. }
  4405. }
  4406. // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
  4407. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  4408. if (!in_array($model, $valid_models)) {
  4409. $model = 'seed-2';
  4410. }
  4411. // 构建完整的提示词
  4412. // 参考音频开关:调用方传 enable_reference_audio 优先,未传则读 ENABLE_REFERENCE_AUDIO(默认开启)
  4413. $supportAudioReference = $this->isReferenceAudioEnabled($data) && $this->isActReferenceAudioSupported($model);
  4414. // 先在提示词转换之前完成参考音频校验与截断(超出模型段数/时长上限的角色回退使用音色提示词)
  4415. $audioPlan = $supportAudioReference
  4416. ? $this->resolveActReferenceAudios($actContent, $products, $model)
  4417. : ['allowed' => [], 'excluded' => [], 'total_duration' => 0];
  4418. // 资产参考图同样先按模型上限(2.0=9张、2.5=30张)截断,保证提示词中的<图片N>与实际素材一一对应
  4419. $imagePlan = $this->resolveActReferenceImages($actContent, $products, $model);
  4420. $processResult = $this->processActContentWithProducts($actContent, $products, $supportAudioReference, $audioPlan['allowed'], $imagePlan['allowed']);
  4421. $fullPrompt = $processResult['content'];
  4422. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4423. // 参考图合并:资产参考图(已按模型上限截断)优先,调用方显式传入的参考图按剩余额度补充,超出时优先截断调用方传入的图
  4424. $asset_reference_images = $processResult['reference_images'];
  4425. $frontend_reference_images_all = array_values(array_unique(array_filter($reference_images)));
  4426. $frontend_reference_images = $frontend_reference_images_all;
  4427. if (!empty($imagePlan['limit'])) {
  4428. $remaining = max(0, $imagePlan['limit'] - count($asset_reference_images));
  4429. $frontend_reference_images = array_slice($frontend_reference_images, 0, $remaining);
  4430. }
  4431. $reference_images = array_values(array_unique(array_filter(array_merge($asset_reference_images, $frontend_reference_images))));
  4432. // 任务记录用:截断前的完整合并数组(正文内出现的资产图 + 调用方传入的参考图),便于追溯前端入参
  4433. $reference_images_all = array_values(array_unique(array_filter(array_merge(
  4434. $processResult['reference_images_all'] ?? $asset_reference_images,
  4435. $frontend_reference_images_all
  4436. ))));
  4437. // 角色音色参考音频(顺序与提示词中的<音频N>标记一一对应)
  4438. $reference_audios = $supportAudioReference ? ($processResult['reference_audios'] ?? []) : [];
  4439. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4440. // 保存到episode表(仅在专用方法中更新模型)
  4441. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4442. // 'video_model' => $model,
  4443. // 'updated_at' => date('Y-m-d H:i:s')
  4444. // ]);
  4445. // 余额预检:按预估时长计算所需积分,不足直接报错
  4446. $chargeDuration = (int)$videoDuration;
  4447. if ($chargeDuration <= 0) {
  4448. $chargeDuration = 5; // 无时长时按默认5秒预估
  4449. }
  4450. $this->pointsService->checkUserPointsEnough(
  4451. $this->pointsService->getVideoChargePoints([
  4452. 'model' => $model,
  4453. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4454. 'video_duration' => $chargeDuration,
  4455. 'ratio' => $ratio,
  4456. 'generate_audio' => $current_generate_audio,
  4457. ])
  4458. );
  4459. // 构建视频生成参数
  4460. $videoParams = [
  4461. 'model' => $model,
  4462. 'alias_act_id' => $act_id,
  4463. 'prompt' => trim($fullPrompt),
  4464. 'video_duration' => $videoDuration,
  4465. 'video_resolution' => $video_resolution,
  4466. 'seed' => -1,
  4467. 'ratio' => $ratio,
  4468. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4469. 'draft' => false,
  4470. 'watermark' => false,
  4471. 'camera_fixed' => false,
  4472. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4473. ];
  4474. // 如果分镜有图片,作为首帧
  4475. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4476. $hasVideo = !empty(getProp($act, 'video_url'));
  4477. if ($hasImage) {
  4478. if ($first_frame_url) {
  4479. $videoParams['first_frame_url'] = $first_frame_url;
  4480. }else {
  4481. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4482. }
  4483. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4484. }
  4485. // 构建content数组
  4486. $videoParams['content'] = [
  4487. [
  4488. 'type' => 'text',
  4489. 'text' => $videoParams['prompt'],
  4490. ]
  4491. ];
  4492. // 如果有首帧图片,添加到content中
  4493. if ($hasImage) {
  4494. 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'])) {
  4495. $videoParams['content'][] = [
  4496. 'type' => 'image_url',
  4497. 'image_url' => [
  4498. 'url' => $videoParams['first_frame_url'],
  4499. ],
  4500. 'role' => 'reference_image',
  4501. ];
  4502. if (isset($videoParams['tail_frame_url'])) {
  4503. $videoParams['content'][] = [
  4504. 'type' => 'image_url',
  4505. 'image_url' => [
  4506. 'url' => $videoParams['tail_frame_url'],
  4507. ],
  4508. 'role' => 'reference_image',
  4509. ];
  4510. }
  4511. }else {
  4512. $videoParams['content'][] = [
  4513. 'type' => 'image_url',
  4514. 'image_url' => [
  4515. 'url' => $videoParams['first_frame_url'],
  4516. ],
  4517. 'role' => 'first_frame',
  4518. ];
  4519. if (isset($videoParams['tail_frame_url'])) {
  4520. $videoParams['content'][] = [
  4521. 'type' => 'image_url',
  4522. 'image_url' => [
  4523. 'url' => $videoParams['tail_frame_url'],
  4524. ],
  4525. 'role' => 'last_frame',
  4526. ];
  4527. }
  4528. }
  4529. }
  4530. // dd($videoParams);
  4531. // 根据模型选择不同的视频生成方法
  4532. try {
  4533. if (strpos($model, 'jimeng') !== false) {
  4534. // 即梦模型参数调整
  4535. unset($videoParams['content']); // 即梦不使用content格式
  4536. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4537. } elseif (strpos($model, 'kling') !== false) {
  4538. // Keling模型参数调整
  4539. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4540. unset($videoParams['ratio']);
  4541. unset($videoParams['content']); // Keling不使用content格式
  4542. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4543. } elseif (strpos($model, 'zhizhen') !== false) {
  4544. // 智帧20等新模型使用统一API
  4545. // 构建统一API参数
  4546. $unifiedParams = [
  4547. 'model_code' => $model,
  4548. 'alias_act_id' => $act_id,
  4549. 'prompt' => trim($fullPrompt),
  4550. 'video_duration' => $videoDuration,
  4551. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4552. 'video_ratio' => $ratio,
  4553. 'seed' => -1,
  4554. ];
  4555. // 构建parameters参数
  4556. $parameters = [
  4557. 'seconds' => $unifiedParams['video_duration'],
  4558. 'resolution' => $unifiedParams['video_resolution'],
  4559. 'ratio' => $ratio,
  4560. // 'video_mode' => 'multi_image',
  4561. // 'mode' => 'multi_image',
  4562. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4563. ];
  4564. $hasImage = false;
  4565. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4566. if ($hasImage) {
  4567. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4568. if (isset($videoParams['tail_frame_url'])) {
  4569. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4570. }
  4571. } else {
  4572. // 没有图片时,记录错误日志
  4573. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4574. 'act_id' => $act_id,
  4575. 'model' => $model
  4576. ]);
  4577. }
  4578. if ($reference_images) {
  4579. // 参考图按模型上限截断(Seedance 2.0 系列=9张,2.5=30张)
  4580. $imageLimit = $this->getActReferenceImageLimit($model);
  4581. if ($imageLimit > 0) {
  4582. $reference_images = array_slice($reference_images, 0, $imageLimit);
  4583. }
  4584. // 任务记录用:保存截断前的完整参考图(含调用方传入),便于追溯前端入参
  4585. $unifiedParams['reference_images'] = $reference_images_all;
  4586. // 实际提交给大模型的参考图(截断后)
  4587. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4588. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4589. $parameters['reference_images'] = $reference_images;
  4590. $parameters['video_mode'] = 'multi_image';
  4591. $parameters['mode'] = 'multi_image';
  4592. }
  4593. // 角色音色参考音频:上传为素材并传入统一API(上传失败时清理提示词中的<音频N>标记)
  4594. if ($reference_audios) {
  4595. $unifiedParams['ref_audio_url'] = json_encode($reference_audios, 256);
  4596. // 任务记录:参考图与参考音频一起存入 ref_image_url
  4597. $unifiedParams['ref_image_url'] = $this->mergeReferenceAudiosIntoRefImageUrl($unifiedParams['ref_image_url'] ?? '', $reference_audios);
  4598. $reference_audio_assets = $this->processActReferenceAudiosToAssets($reference_audios, $model, $unifiedParams['prompt']);
  4599. $parameters['reference_audios'] = $reference_audio_assets;
  4600. // 音频素材上传失败的角色回退到音色提示词
  4601. $unifiedParams['prompt'] = $this->applyAudioVoiceFallbacks($unifiedParams['prompt'], $processResult['audio_voice_fallbacks'] ?? []);
  4602. $unifiedParams['prompt'] = trim($unifiedParams['prompt']);
  4603. }
  4604. $unifiedParams['parameters'] = $parameters;
  4605. // 调用统一API创建任务
  4606. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4607. } elseif ($this->isSeedance20SeriesModel($model)) {
  4608. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4609. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4610. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4611. // 任务记录用:保存截断前的完整合并数组(正文内资产图 + 调用方传入的参考图),便于追溯前端入参
  4612. $videoParams['reference_images'] = $reference_images_all;
  4613. if ($reference_images) {
  4614. // 参考图按模型上限截断(Seedance 2.0 系列=9张,2.5=30张)
  4615. $imageLimit = $this->getActReferenceImageLimit($model);
  4616. if ($imageLimit > 0) {
  4617. $reference_images = array_slice($reference_images, 0, $imageLimit);
  4618. }
  4619. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4620. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4621. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4622. $reference_image_assets = $isKuaikuai
  4623. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4624. : ($isDreamina
  4625. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $fullPrompt)
  4626. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt));
  4627. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4628. $videoParams['prompt'] = trim($fullPrompt);
  4629. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4630. $videoParams['reference_image_assets'] = $reference_image_assets;
  4631. }
  4632. // 角色音色参考音频:上传为素材并传入网关(上传失败时清理提示词中的<音频N>标记)
  4633. if ($reference_audios) {
  4634. $videoParams['ref_audio_url'] = json_encode($reference_audios, 256);
  4635. // 任务记录:参考图与参考音频一起存入 ref_image_url
  4636. $videoParams['ref_image_url'] = $this->mergeReferenceAudiosIntoRefImageUrl($videoParams['ref_image_url'] ?? '', $reference_audios);
  4637. $reference_audio_assets = $this->processActReferenceAudiosToAssets($reference_audios, $model, $fullPrompt);
  4638. // 音频素材上传失败的角色回退到音色提示词
  4639. $fullPrompt = $this->applyAudioVoiceFallbacks($fullPrompt, $processResult['audio_voice_fallbacks'] ?? []);
  4640. $videoParams['prompt'] = trim($fullPrompt);
  4641. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4642. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4643. }
  4644. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4645. if ($isKuaikuai) {
  4646. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4647. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4648. } else {
  4649. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4650. }
  4651. } else {
  4652. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4653. }
  4654. } catch (ApiException $e) {
  4655. // 上游调用抛出的网关异常统一做友好化处理;本地业务错误(非1001)保持原提示不变
  4656. if ($e->getCode() === 1001) {
  4657. Utils::throwError('1001:' . mapErrorMessage($e->getMessage()));
  4658. }
  4659. throw $e;
  4660. } catch (\Exception $e) {
  4661. // 其他未包装的异常,同样只对报错信息做格式化,便于前端展示友好提示
  4662. Utils::throwError('20003:' . mapErrorMessage($e->getMessage()));
  4663. }
  4664. // 更新分镜表的视频任务信息
  4665. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4666. 'video_task_id' => $task->id,
  4667. 'video_task_status' => '生成中',
  4668. 'generate_audio' => $generate_audio,
  4669. 'updated_at' => date('Y-m-d H:i:s')
  4670. ]);
  4671. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4672. $episode_number = getProp($act, 'episode_number');
  4673. $act_number = getProp($act, 'act_number');
  4674. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4675. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4676. }
  4677. $result = [
  4678. 'task_id' => $task->id,
  4679. 'status' => $task->status,
  4680. 'act_id' => $act_id,
  4681. 'video_duration' => $videoDuration
  4682. ];
  4683. // 仅当任务提交阶段就已失败时,附带格式化后的错误信息;正常返回结构不受影响
  4684. if ($task->status === 'failed' && !empty($task->error_message)) {
  4685. $result['error_message'] = mapErrorMessage($task->error_message);
  4686. }
  4687. return $result;
  4688. }
  4689. /**
  4690. * 文生视频通用方法
  4691. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4692. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4693. *
  4694. * @param array $data 请求参数
  4695. * @return array
  4696. */
  4697. public function generateVideo($data) {
  4698. $prompt = getProp($data, 'prompt');
  4699. if (empty($prompt)) {
  4700. Utils::throwError('20003:提示词不能为空');
  4701. }
  4702. $model = getProp($data, 'model');
  4703. if (!$model) {
  4704. $model = 'seed-2';
  4705. }
  4706. // 验证模型是否在可用模型表中
  4707. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4708. Utils::throwError('20003:该模型已不可用,请更换!');
  4709. }
  4710. $video_duration = getProp($data, 'video_duration', 5);
  4711. // 默认超分720p档(按480p生成后本地超分到720p);480p为原始档需前端显式指定
  4712. $video_resolution = getProp($data, 'video_resolution', 'sr_720p');
  4713. $ratio = getProp($data, 'ratio', '9:16');
  4714. $generate_audio = getProp($data, 'generate_audio', 1);
  4715. $seed = getProp($data, 'seed', -1);
  4716. $first_frame_url = getProp($data, 'first_frame_url');
  4717. $tail_frame_url = getProp($data, 'tail_frame_url');
  4718. // 参考图(支持数组或JSON字符串,最多9张)
  4719. $reference_images = getProp($data, 'reference_images', []);
  4720. if (is_string($reference_images)) {
  4721. $reference_images = json_decode($reference_images, true) ?: [];
  4722. }
  4723. if (!is_array($reference_images)) {
  4724. Utils::throwError('20003:参考图格式不正确');
  4725. }
  4726. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4727. $reference_images = array_slice($reference_images, 0, 9);
  4728. // 参考视频(支持数组或JSON字符串,最多3个)
  4729. $reference_videos = getProp($data, 'reference_videos', []);
  4730. if (is_string($reference_videos)) {
  4731. $reference_videos = json_decode($reference_videos, true) ?: [];
  4732. }
  4733. if (!is_array($reference_videos)) {
  4734. Utils::throwError('20003:参考视频格式不正确');
  4735. }
  4736. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4737. if (count($reference_videos) > 3) {
  4738. Utils::throwError('20003:参考视频最多选择3个');
  4739. }
  4740. $reference_videos = array_slice($reference_videos, 0, 3);
  4741. // 参考音频(支持数组或JSON字符串,最多3个)
  4742. $reference_audios = getProp($data, 'reference_audios', []);
  4743. if (is_string($reference_audios)) {
  4744. $reference_audios = json_decode($reference_audios, true) ?: [];
  4745. }
  4746. if (!is_array($reference_audios)) {
  4747. Utils::throwError('20003:参考音频格式不正确');
  4748. }
  4749. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4750. if (count($reference_audios) > 3) {
  4751. Utils::throwError('20003:参考音频最多选择3个');
  4752. }
  4753. $reference_audios = array_slice($reference_audios, 0, 3);
  4754. // 余额预检:按预估时长计算所需积分,不足直接报错
  4755. $chargeDuration = (int)ceil((float)$video_duration);
  4756. if ($chargeDuration <= 0) {
  4757. $chargeDuration = 5; // 无时长时按默认5秒预估
  4758. }
  4759. $this->pointsService->checkUserPointsEnough(
  4760. $this->pointsService->getVideoChargePoints([
  4761. 'model' => $model,
  4762. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4763. 'video_duration' => $chargeDuration,
  4764. 'ratio' => $ratio,
  4765. 'generate_audio' => (int)$generate_audio,
  4766. ])
  4767. );
  4768. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4769. $videoParams = [
  4770. 'model' => $model,
  4771. 'prompt' => $prompt,
  4772. 'video_duration' => $video_duration,
  4773. 'video_resolution' => $video_resolution,
  4774. 'seed' => $seed,
  4775. 'ratio' => $ratio,
  4776. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4777. 'draft' => getProp($data, 'draft', false),
  4778. 'watermark' => getProp($data, 'watermark', false),
  4779. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4780. ];
  4781. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4782. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4783. // 构建content数组
  4784. $videoParams['content'] = [
  4785. [
  4786. 'type' => 'text',
  4787. 'text' => $prompt,
  4788. ]
  4789. ];
  4790. // 根据模型选择不同的视频生成方法
  4791. if (strpos($model, 'jimeng') !== false) {
  4792. // 即梦模型参数调整
  4793. unset($videoParams['content']); // 即梦不使用content格式
  4794. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4795. } elseif (strpos($model, 'kling') !== false) {
  4796. // 可灵模型参数调整
  4797. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4798. unset($videoParams['ratio']);
  4799. unset($videoParams['content']); // 可灵不使用content格式
  4800. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4801. } elseif (strpos($model, 'zhizhen') !== false) {
  4802. // 智帧等新模型使用统一API
  4803. $unifiedParams = [
  4804. 'model_code' => $model,
  4805. 'prompt' => $prompt,
  4806. 'video_duration' => $video_duration,
  4807. 'video_resolution' => strtolower($video_resolution),
  4808. 'video_ratio' => $ratio,
  4809. 'seed' => $seed,
  4810. ];
  4811. // 构建parameters参数
  4812. $parameters = [
  4813. 'seconds' => $unifiedParams['video_duration'],
  4814. 'resolution' => $unifiedParams['video_resolution'],
  4815. 'ratio' => $ratio,
  4816. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4817. ];
  4818. // 首帧和尾帧
  4819. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4820. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4821. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4822. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4823. if ($refImageUrls) {
  4824. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4825. }
  4826. // 参考图处理
  4827. if ($reference_images) {
  4828. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4829. $parameters['reference_images'] = $reference_images;
  4830. $parameters['video_mode'] = 'multi_image';
  4831. $parameters['mode'] = 'multi_image';
  4832. }
  4833. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4834. if ($reference_videos) {
  4835. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4836. $parameters['reference_videos'] = $reference_videos;
  4837. }
  4838. if ($reference_audios) {
  4839. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4840. $parameters['reference_audios'] = $reference_audios;
  4841. }
  4842. $unifiedParams['parameters'] = $parameters;
  4843. // 调用统一API创建任务
  4844. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4845. } elseif ($this->isSeedance20SeriesModel($model)) {
  4846. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4847. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4848. $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
  4849. $videoParams['reference_images'] = $reference_images;
  4850. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4851. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4852. if ($refImageUrls) {
  4853. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4854. }
  4855. if ($reference_images) {
  4856. // 参考图上传为素材(国内百度/海外百度dreamina/快快AI)
  4857. $reference_image_assets = $isKuaikuai
  4858. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4859. : ($isDreamina
  4860. ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $videoParams['prompt'])
  4861. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']));
  4862. $videoParams['reference_image_assets'] = $reference_image_assets;
  4863. }
  4864. // 参考视频上传为素材(国内百度/海外百度dreamina/快快AI)
  4865. if ($reference_videos) {
  4866. $reference_video_assets = $isKuaikuai
  4867. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4868. : ($isDreamina
  4869. ? $this->aiVideoGenerationService->processReferenceVideosToBaiduDreaminaAssets($reference_videos, $videoParams['prompt'])
  4870. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']));
  4871. $videoParams['reference_video_assets'] = $reference_video_assets;
  4872. }
  4873. // 参考音频上传为素材(国内百度/海外百度dreamina/快快AI)
  4874. if ($reference_audios) {
  4875. $reference_audio_assets = $isKuaikuai
  4876. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4877. : ($isDreamina
  4878. ? $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($reference_audios, $videoParams['prompt'])
  4879. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']));
  4880. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4881. }
  4882. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4883. if ($reference_images || $reference_videos || $reference_audios) {
  4884. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4885. }
  4886. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4887. if ($isKuaikuai) {
  4888. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4889. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4890. } else {
  4891. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4892. }
  4893. } else {
  4894. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4895. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4896. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4897. if ($refImageUrls) {
  4898. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4899. }
  4900. if ($reference_videos) {
  4901. foreach ($reference_videos as $videoUrl) {
  4902. $videoParams['content'][] = [
  4903. 'type' => 'video_url',
  4904. 'video_url' => [
  4905. 'url' => $videoUrl,
  4906. ],
  4907. 'role' => 'reference_video',
  4908. ];
  4909. }
  4910. }
  4911. if ($reference_audios) {
  4912. foreach ($reference_audios as $audioUrl) {
  4913. $videoParams['content'][] = [
  4914. 'type' => 'audio_url',
  4915. 'audio_url' => [
  4916. 'url' => $audioUrl,
  4917. ],
  4918. 'role' => 'reference_audio',
  4919. ];
  4920. }
  4921. }
  4922. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4923. }
  4924. return [
  4925. 'task_id' => $task->id,
  4926. 'status' => $task->status,
  4927. 'model' => $model,
  4928. 'video_duration' => $video_duration,
  4929. 'video_resolution' => $video_resolution,
  4930. 'ratio' => $ratio
  4931. ];
  4932. }
  4933. /**
  4934. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4935. *
  4936. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4937. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4938. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4939. *
  4940. * @param array $data
  4941. * @return array
  4942. */
  4943. public function previewCharge(array $data): array
  4944. {
  4945. $mode = (string)getProp($data, 'mode', '');
  4946. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4947. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4948. }
  4949. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4950. $scene = (string)getProp($data, 'scene', 'video_generation');
  4951. // 未显式传scene且带参考视频时,自动按video_to_video定价
  4952. if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
  4953. $scene = 'video_to_video';
  4954. }
  4955. $items = [];
  4956. $model = '';
  4957. $resolution = '';
  4958. if ($mode === 'video') {
  4959. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4960. $model = (string)getProp($data, 'model', '');
  4961. if (!$model) {
  4962. Utils::throwError('1002:model参数不能为空');
  4963. }
  4964. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4965. $duration = (int)getProp($data, 'video_duration', 5);
  4966. if ($duration <= 0) {
  4967. $duration = 5;
  4968. }
  4969. $count = max(1, (int)getProp($data, 'count', 1));
  4970. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4971. 'model' => $model,
  4972. 'video_resolution' => $resolution,
  4973. 'video_duration' => $duration,
  4974. 'mode' => $scene,
  4975. ]);
  4976. $points = $pointsPerVideo * $count;
  4977. $items[] = [
  4978. 'type' => 'video',
  4979. 'model' => $model,
  4980. 'video_resolution' => $resolution,
  4981. 'video_duration' => $duration,
  4982. 'count' => $count,
  4983. 'points' => $points,
  4984. ];
  4985. } elseif ($mode === 'image') {
  4986. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4987. $model = (string)getProp($data, 'model', '');
  4988. if (!$model) {
  4989. Utils::throwError('1002:model参数不能为空');
  4990. }
  4991. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4992. if (!$resolution) {
  4993. $width = (int)getProp($data, 'width', 0);
  4994. $height = (int)getProp($data, 'height', 0);
  4995. if ($width <= 0 || $height <= 0) {
  4996. $width = 1600;
  4997. $height = 2848;
  4998. }
  4999. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  5000. }
  5001. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  5002. $points = $this->pointsService->getImageChargePoints([
  5003. 'model' => $model,
  5004. 'resolution' => $resolution,
  5005. ]) * $imageNum;
  5006. $items[] = [
  5007. 'type' => 'image',
  5008. 'model' => $model,
  5009. 'resolution' => $resolution,
  5010. 'image_num' => $imageNum,
  5011. 'points' => $points,
  5012. ];
  5013. } else {
  5014. // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
  5015. // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
  5016. $priceType = (string)getProp($data, 'price_type', 'special');
  5017. if (!in_array($priceType, ['special', 'normal'], true)) {
  5018. Utils::throwError('1003:price_type参数仅支持special或normal');
  5019. }
  5020. $count = max(1, (int)getProp($data, 'count', 1));
  5021. $animeId = getProp($data, 'anime_id');
  5022. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  5023. if ($animeId && $generateEpisodes > 0) {
  5024. // 批量生成分集按 special 档预估,与实际扣费口径一致
  5025. $priceType = 'special';
  5026. $currentMaxEpisode = DB::table('mp_anime_episodes')
  5027. ->where('anime_id', $animeId)
  5028. ->where('is_default', 1)
  5029. ->max('episode_number');
  5030. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  5031. $startEpisodeNumber = $currentMaxEpisode + 1;
  5032. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  5033. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  5034. ->where('anime_id', $animeId)
  5035. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  5036. ->whereIn('status', ['pending', 'processing', 'completed'])
  5037. ->count();
  5038. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  5039. if ($count < 0) {
  5040. $count = 0;
  5041. }
  5042. }
  5043. $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
  5044. $items[] = [
  5045. 'type' => 'chat',
  5046. 'count' => $count,
  5047. 'price_type' => $priceType,
  5048. 'points' => $points,
  5049. ];
  5050. }
  5051. $totalPoints = 0;
  5052. foreach ($items as $item) {
  5053. $totalPoints += $item['points'];
  5054. }
  5055. return [
  5056. 'mode' => $mode,
  5057. 'total_points' => $totalPoints,
  5058. 'items' => $items,
  5059. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  5060. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  5061. ];
  5062. }
  5063. /**
  5064. * 根据提示词内容智能计算最优视频时长
  5065. *
  5066. * @param string $segmentContent 分镜内容
  5067. * @param string $tailFrame 尾帧描述
  5068. * @return int 视频时长(2-12秒)
  5069. */
  5070. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  5071. // 合并所有文本内容
  5072. $fullText = trim($segmentContent . ' ' . $tailFrame);
  5073. // 如果没有内容,返回默认时长
  5074. if (empty($fullText)) {
  5075. return 5;
  5076. }
  5077. // 计算文本长度(中文字符按2个字符计算)
  5078. $textLength = mb_strlen($fullText, 'UTF-8');
  5079. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  5080. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  5081. // 分析内容复杂度
  5082. $complexityScore = $this->analyzeContentComplexity($fullText);
  5083. // 基础时长计算(根据文本长度)
  5084. $baseDuration = 3; // 默认2秒
  5085. // if ($adjustedLength <= 20) {
  5086. // $baseDuration = 3;
  5087. // } elseif ($adjustedLength <= 40) {
  5088. // $baseDuration = 4;
  5089. // } elseif ($adjustedLength <= 60) {
  5090. // $baseDuration = 5;
  5091. // } elseif ($adjustedLength <= 80) {
  5092. // $baseDuration = 6;
  5093. // } elseif ($adjustedLength <= 100) {
  5094. // $baseDuration = 7;
  5095. // } elseif ($adjustedLength <= 120) {
  5096. // $baseDuration = 8;
  5097. // } else {
  5098. // $baseDuration = 9;
  5099. // }
  5100. // 根据内容复杂度调整时长
  5101. $finalDuration = $baseDuration + $complexityScore;
  5102. // 确保时长在2-12秒范围内
  5103. return max(4, min(12, $finalDuration));
  5104. }
  5105. /**
  5106. * 分析内容复杂度,返回时长调整值
  5107. *
  5108. * @param string $text 文本内容
  5109. * @return int 调整值(-2到+3)
  5110. */
  5111. private function analyzeContentComplexity($text) {
  5112. $score = 0;
  5113. // 动作关键词(需要更长时间展现)
  5114. $actionKeywords = [
  5115. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  5116. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  5117. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  5118. ];
  5119. // 静态关键词(可以用较短时间)
  5120. $staticKeywords = [
  5121. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  5122. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  5123. ];
  5124. // 复杂场景关键词(需要更长时间)
  5125. $complexSceneKeywords = [
  5126. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  5127. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  5128. ];
  5129. // 情感关键词(需要适中时间表现)
  5130. $emotionKeywords = [
  5131. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  5132. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  5133. ];
  5134. // 检查动作关键词
  5135. foreach ($actionKeywords as $keyword) {
  5136. if (strpos($text, $keyword) !== false) {
  5137. $score += 1;
  5138. break; // 避免重复加分
  5139. }
  5140. }
  5141. // 检查静态关键词
  5142. foreach ($staticKeywords as $keyword) {
  5143. if (strpos($text, $keyword) !== false) {
  5144. $score -= 1;
  5145. break;
  5146. }
  5147. }
  5148. // 检查复杂场景关键词
  5149. foreach ($complexSceneKeywords as $keyword) {
  5150. if (strpos($text, $keyword) !== false) {
  5151. $score += 1;
  5152. break;
  5153. }
  5154. }
  5155. // 检查情感关键词
  5156. foreach ($emotionKeywords as $keyword) {
  5157. if (strpos($text, $keyword) !== false) {
  5158. $score += 1;
  5159. break;
  5160. }
  5161. }
  5162. // 检查时间相关词汇
  5163. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  5164. $score += 1;
  5165. }
  5166. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  5167. $score -= 1;
  5168. }
  5169. // 检查转场词汇
  5170. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  5171. $score += 1;
  5172. }
  5173. // 检查环境描述(复杂环境需要更多时间)
  5174. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  5175. $score += 1;
  5176. }
  5177. // 检查对话内容(对话需要更多时间)
  5178. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  5179. $score += 1;
  5180. }
  5181. // 限制调整范围
  5182. return max(-1, min(4, $score));
  5183. }
  5184. /**
  5185. * 创建完整视频合成任务
  5186. *
  5187. * @param array $data
  5188. * @return array
  5189. */
  5190. public function createCompleteVideoTask($data)
  5191. {
  5192. $animeId = getProp($data, 'anime_id');
  5193. $episodeId = getProp($data, 'episode_id');
  5194. // 验证参数
  5195. if (!$animeId || !$episodeId) {
  5196. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  5197. }
  5198. // 检查是否已存在处理中的任务
  5199. $existingTask = DB::table('mp_complete_video_tasks')
  5200. ->where('anime_id', $animeId)
  5201. ->where('episode_id', $episodeId)
  5202. ->whereIn('generate_status', ['执行中'])
  5203. ->first();
  5204. if ($existingTask) {
  5205. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  5206. }
  5207. // 获取全能模式状态
  5208. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  5209. if ((int)$ace_mode === 1) {
  5210. // 获取所有片段的配音视频,按 act_number 排序
  5211. $segments = DB::table('mp_episode_segments')
  5212. ->where('anime_id', $animeId)
  5213. ->where('episode_id', $episodeId)
  5214. ->orderBy('segment_number')
  5215. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5216. ->get();
  5217. // 检查是否所有片段都有视频
  5218. $missingVideos = $segments->filter(function($segment) {
  5219. return empty($segment->video_url);
  5220. });
  5221. if ($missingVideos->isNotEmpty()) {
  5222. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  5223. }
  5224. }else {
  5225. // 获取所有分镜的配音视频,按 segment_number 排序
  5226. $segments = DB::table('mp_episode_segments')
  5227. ->where('anime_id', $animeId)
  5228. ->where('episode_id', $episodeId)
  5229. ->orderBy('segment_number')
  5230. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5231. ->get();
  5232. // 检查是否所有分镜都有配音和视频
  5233. $missingVideos = $segments->filter(function($segment) {
  5234. return empty($segment->audio_url) || empty($segment->video_url);
  5235. });
  5236. if ($missingVideos->isNotEmpty()) {
  5237. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5238. }
  5239. }
  5240. if ($segments->isEmpty()) {
  5241. Utils::throwError('20003:未找到该剧集的分镜数据');
  5242. }
  5243. // 获取当前完整视频url
  5244. $completeVideoUrl = DB::table('mp_anime_episodes')
  5245. ->where('anime_id', $animeId)
  5246. ->where('id', $episodeId)
  5247. ->value('complete_video_url');
  5248. // 构建 generate_json
  5249. $generateJson = [];
  5250. $sequence = 1;
  5251. foreach ($segments as $segment) {
  5252. if ((int)$ace_mode === 1) {
  5253. $generateJson[] = [
  5254. 'sequence' => $sequence++,
  5255. 'video_url' => $segment->video_url,
  5256. 'video_time_point_start' => $segment->video_time_point_start,
  5257. 'video_time_point_end' => $segment->video_time_point_end
  5258. ];
  5259. }else {
  5260. $generateJson[] = [
  5261. 'sequence' => $sequence++,
  5262. 'video_url' => $segment->video_url,
  5263. 'audio_url' => $segment->audio_url,
  5264. 'video_time_point_start' => $segment->video_time_point_start,
  5265. 'video_time_point_end' => $segment->video_time_point_end
  5266. ];
  5267. }
  5268. }
  5269. // 创建任务
  5270. $now = date('Y-m-d H:i:s');
  5271. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5272. 'anime_id' => $animeId,
  5273. 'episode_id' => $episodeId,
  5274. 'generate_json' => json_encode($generateJson, 256),
  5275. 'generate_status' => '执行中',
  5276. 'complete_video_url' => '',
  5277. 'created_at' => $now,
  5278. 'updated_at' => $now
  5279. ]);
  5280. if (!$taskId) {
  5281. Utils::throwError('20003:创建任务失败');
  5282. }
  5283. // 更新剧集表的任务ID和状态
  5284. $boolen = DB::table('mp_anime_episodes')
  5285. ->where('anime_id', $animeId)
  5286. ->where('id', $episodeId)
  5287. ->update([
  5288. 'complete_video_task_id' => $taskId,
  5289. 'complete_video_task_status' => '执行中',
  5290. 'updated_at' => $now
  5291. ]);
  5292. if (!$boolen) {
  5293. Utils::throwError('20003:更新剧集表失败');
  5294. }
  5295. dLog('anime')->info('创建完整视频合成任务', [
  5296. 'task_id' => $taskId,
  5297. 'anime_id' => $animeId,
  5298. 'episode_id' => $episodeId,
  5299. 'segment_count' => count($generateJson)
  5300. ]);
  5301. // 请求远程服务器执行生成
  5302. $client = new Client(['timeout' => 600, 'verify' => false]);
  5303. try {
  5304. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5305. $response = $result->getBody()->getContents();
  5306. $response_arr = json_decode($response, true);
  5307. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5308. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5309. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5310. // // 更新任务状态为失败
  5311. // DB::table('mp_complete_video_tasks')
  5312. // ->where('id', $taskId)
  5313. // ->update([
  5314. // 'generate_status' => '执行失败',
  5315. // 'error_message' => $error_msg,
  5316. // 'updated_at' => date('Y-m-d H:i:s')
  5317. // ]);
  5318. // // 同步更新剧集表状态
  5319. // DB::table('mp_anime_episodes')
  5320. // ->where('complete_video_task_id', $taskId)
  5321. // ->update([
  5322. // 'complete_video_task_status' => '执行失败',
  5323. // 'updated_at' => date('Y-m-d H:i:s')
  5324. // ]);
  5325. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5326. }
  5327. } catch (\Exception $e) {
  5328. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5329. // 更新任务状态为失败
  5330. DB::table('mp_complete_video_tasks')
  5331. ->where('id', $taskId)
  5332. ->update([
  5333. 'generate_status' => '执行失败',
  5334. 'error_message' => $e->getMessage(),
  5335. 'updated_at' => date('Y-m-d H:i:s')
  5336. ]);
  5337. // 同步更新剧集表状态
  5338. DB::table('mp_anime_episodes')
  5339. ->where('complete_video_task_id', $taskId)
  5340. ->update([
  5341. 'complete_video_task_status' => '执行失败',
  5342. 'updated_at' => date('Y-m-d H:i:s')
  5343. ]);
  5344. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5345. }
  5346. // 开始轮询任务状态
  5347. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5348. $pollInterval = 5; // 每5秒轮询一次
  5349. $attempt = 0;
  5350. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5351. while ($attempt < $maxAttempts) {
  5352. sleep($pollInterval);
  5353. $attempt++;
  5354. // 查询任务状态
  5355. $task = DB::table('mp_complete_video_tasks')
  5356. ->where('id', $taskId)
  5357. ->first();
  5358. if (!$task) {
  5359. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5360. Utils::throwError('20003:任务不存在');
  5361. }
  5362. dLog('anime')->info('轮询任务状态', [
  5363. 'task_id' => $taskId,
  5364. 'attempt' => $attempt,
  5365. 'status' => $task->generate_status
  5366. ]);
  5367. // 检查任务是否完成
  5368. if ($task->generate_status === '执行成功') {
  5369. // 同步更新剧集表状态
  5370. $boolen3 = DB::table('mp_anime_episodes')
  5371. ->where('anime_id', $animeId)
  5372. ->where('id', $episodeId)
  5373. ->update([
  5374. 'complete_video_url' => $task->complete_video_url,
  5375. 'complete_video_task_status' => '执行成功',
  5376. 'updated_at' => date('Y-m-d H:i:s')
  5377. ]);
  5378. dLog('anime')->info('视频合成任务完成', [
  5379. 'task_id' => $taskId,
  5380. 'video_url' => $task->complete_video_url,
  5381. 'attempts' => $attempt
  5382. ]);
  5383. // 如果更新成功则远程删除之前的文件
  5384. if ($boolen3 && $completeVideoUrl) {
  5385. $encode_url = urlencode($completeVideoUrl);
  5386. $client = new Client(['timeout' => 300, 'verify' => false]);
  5387. // 根据ID通过API通知合成音频
  5388. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5389. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5390. $response = $result->getBody()->getContents();
  5391. $response_arr = json_decode($response, true);
  5392. Log::info('火山删除音频返回: '.$response);
  5393. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5394. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5395. Log::info('火山删除音频失败: '.$error_msg);
  5396. // Utils::throwError('20003:火山删除音频失败');
  5397. }
  5398. }
  5399. return [
  5400. 'task_id' => $taskId,
  5401. 'anime_id' => $animeId,
  5402. 'episode_id' => $episodeId,
  5403. 'segment_count' => count($generateJson),
  5404. 'generate_status' => '执行成功',
  5405. 'complete_video_url' => $task->complete_video_url,
  5406. ];
  5407. }
  5408. // 检查任务是否失败
  5409. if ($task->generate_status === '执行失败') {
  5410. // 同步更新剧集表状态
  5411. DB::table('mp_anime_episodes')
  5412. ->where('anime_id', $animeId)
  5413. ->where('id', $episodeId)
  5414. ->update([
  5415. 'complete_video_task_status' => '执行失败',
  5416. 'updated_at' => date('Y-m-d H:i:s')
  5417. ]);
  5418. $errorMessage = $task->error_message ?? '未知错误';
  5419. dLog('anime')->error('视频合成任务失败', [
  5420. 'task_id' => $taskId,
  5421. 'error' => $errorMessage,
  5422. 'attempts' => $attempt
  5423. ]);
  5424. return [
  5425. 'task_id' => $taskId,
  5426. 'anime_id' => $animeId,
  5427. 'episode_id' => $episodeId,
  5428. 'segment_count' => count($generateJson),
  5429. 'generate_status' => '执行失败',
  5430. 'error_message' => $errorMessage
  5431. ];
  5432. }
  5433. }
  5434. // 超时处理
  5435. dLog('anime')->warning('视频合成任务超时', [
  5436. 'task_id' => $taskId,
  5437. 'max_attempts' => $maxAttempts,
  5438. 'timeout_seconds' => $maxAttempts * $pollInterval
  5439. ]);
  5440. // 更新任务状态为超时
  5441. DB::table('mp_complete_video_tasks')
  5442. ->where('id', $taskId)
  5443. ->update([
  5444. 'generate_status' => '超时',
  5445. 'error_message' => '任务执行超时(5分钟)',
  5446. 'updated_at' => date('Y-m-d H:i:s')
  5447. ]);
  5448. return [
  5449. 'task_id' => $taskId,
  5450. 'anime_id' => $animeId,
  5451. 'episode_id' => $episodeId,
  5452. 'segment_count' => count($generateJson),
  5453. 'generate_status' => '超时',
  5454. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5455. ];
  5456. }
  5457. /**
  5458. * 根据 inner_prompt_type 附加内置提示词
  5459. *
  5460. * @param string $prompt 用户提示词
  5461. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5462. * @return string 合并后的提示词
  5463. */
  5464. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5465. {
  5466. $innerPromptMap = [
  5467. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。',
  5468. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5469. ];
  5470. if (!isset($innerPromptMap[$innerPromptType])) {
  5471. return $prompt;
  5472. }
  5473. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5474. }
  5475. /**
  5476. * 根据 inner_prompt_type 获取生成图片数量
  5477. *
  5478. * @param int $innerPromptType 内置提示词类型
  5479. * @param int $imageNum 传入的图片张数
  5480. * @return int 图片数量
  5481. */
  5482. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5483. {
  5484. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5485. }
  5486. /**
  5487. * 提取图片生成结果URL
  5488. *
  5489. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5490. * @param int $innerPromptType 内置提示词类型
  5491. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5492. */
  5493. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5494. {
  5495. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5496. if (is_array($resultUrls) && !empty($resultUrls)) {
  5497. $resultUrls = array_values($resultUrls);
  5498. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5499. }
  5500. if (!empty($resultUrl)) {
  5501. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5502. }
  5503. return (int)$innerPromptType === 2 ? [] : '';
  5504. }
  5505. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5506. $prompt = getProp($data, 'prompt');
  5507. $episode_id = getProp($data, 'episode_id');
  5508. $ref_img_urls = getProp($data, 'ref_img_urls');
  5509. $ratio = getProp($data, 'ratio', '9:16');
  5510. $resolution = getProp($data, 'resolution', '2k');
  5511. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5512. $imageNum = (int)getProp($data, 'image_num', 1);
  5513. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  5514. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  5515. // 参数验证
  5516. $resolution = strtolower($resolution);
  5517. if (!isset($sizeMap[$resolution])) {
  5518. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5519. }
  5520. if (!isset($sizeMap[$resolution][$ratio])) {
  5521. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5522. }
  5523. // 根据 ratio 和 resolution 确定宽高
  5524. $width = $sizeMap[$resolution][$ratio]['width'];
  5525. $height = $sizeMap[$resolution][$ratio]['height'];
  5526. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5527. if (is_json($ref_img_urls)) {
  5528. $ref_img_urls = json_decode($ref_img_urls, true);
  5529. }else {
  5530. $ref_img_urls = explode(',', $ref_img_urls);
  5531. }
  5532. }
  5533. // 处理图片模型
  5534. $model = getProp($data, 'model');
  5535. if (!$model) {
  5536. // 用户没有输入,从episode表获取
  5537. if ($episode_id) {
  5538. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5539. $model = getProp($episode, 'image_model');
  5540. }
  5541. if (!$model) {
  5542. // episode表也没有,使用默认值
  5543. $model = 'gpt-image-2';
  5544. }
  5545. }
  5546. // 验证模型是否在可用模型表中
  5547. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5548. // $model = 'gpt-image-2';
  5549. Utils::throwError('20003:该模型已不可用,请更换!');
  5550. }
  5551. // 保存到episode表
  5552. if ($episode_id) {
  5553. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5554. 'image_model' => $model,
  5555. 'updated_at' => date('Y-m-d H:i:s')
  5556. ]);
  5557. }
  5558. // 参数验证
  5559. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5560. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5561. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5562. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5563. try {
  5564. // 创建图片生成任务
  5565. $params = [
  5566. 'prompt' => $prompt,
  5567. 'model' => $model,
  5568. 'ref_img_urls' => '',
  5569. 'width' => $width,
  5570. 'height' => $height,
  5571. 'image_num' => $imageNum,
  5572. // 计费锚点(动漫/剧集/剧本),上下文没有时不记录
  5573. 'anime_id' => getProp($data, 'anime_id'),
  5574. 'episode_id' => $episode_id,
  5575. ];
  5576. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5577. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5578. $task_id = $task->id;
  5579. if (!$task_id) {
  5580. Utils::throwError('20003:创建图片生成任务失败');
  5581. }
  5582. // 创建任务中心记录并关联图片任务ID
  5583. $taskCenter = $this->taskCenterService->createTask('image', [
  5584. 'title' => '文生图',
  5585. 'ref_task_id' => $task_id,
  5586. // 'prompt' => $prompt,
  5587. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5588. ]);
  5589. $taskCenterId = $taskCenter->id;
  5590. // 组装本次任务信息(用于init消息,类似generateVideo)
  5591. $taskInfo = [
  5592. 'task_id' => $task_id,
  5593. 'status' => getProp($task, 'status', 'processing'),
  5594. 'model' => $model,
  5595. 'ratio' => $ratio,
  5596. 'resolution' => $resolution,
  5597. 'image_num' => $imageNum,
  5598. ];
  5599. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5600. if (is_callable($onTaskCreated)) {
  5601. $onTaskCreated($taskCenterId, $taskInfo);
  5602. }
  5603. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5604. $model = getProp($task, 'model');
  5605. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5606. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5607. $isSyncModel = $isVolcModel || $isGptModel;
  5608. // 任务需要轮询获取结果(15分钟超时,每3秒查询一次)
  5609. $start_time = time();
  5610. $timeout = 900; // 15分钟
  5611. $img_url = '';
  5612. $img_urls = [];
  5613. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5614. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5615. while (time() - $start_time < $timeout) {
  5616. sleep(3);
  5617. // 每分钟发送一次队列状态消息(仅流式模式)
  5618. if (is_callable($onPoll)) {
  5619. $currentTime = time();
  5620. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5621. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5622. $lastQueueMessageTime = $currentTime;
  5623. }
  5624. }
  5625. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5626. if ($isSyncModel) {
  5627. // 刷新任务状态
  5628. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5629. if ($task->status === 'success' && $task->result_url) {
  5630. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5631. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5632. if (!empty($resultUrls)) {
  5633. $img_urls = $resultUrls;
  5634. $img_url = $resultUrls[0];
  5635. } else {
  5636. $img_url = (string)$task->result_url;
  5637. }
  5638. break;
  5639. } elseif ($task->status === 'failed') {
  5640. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5641. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5642. }
  5643. // // 如果还在处理中,提示用户稍后查看
  5644. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5645. }else {
  5646. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5647. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5648. if ($statusInfo['status'] === 'success') {
  5649. $task->updateStatus('success', [
  5650. 'result_url' => $statusInfo['result_url'],
  5651. 'result_json' => $statusInfo['result_json'] ?? []
  5652. ]);
  5653. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5654. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5655. if (!empty($resultUrls)) {
  5656. $img_urls = $resultUrls;
  5657. $img_url = $resultUrls[0];
  5658. } else {
  5659. $img_url = (string)$statusInfo['result_url'];
  5660. }
  5661. break;
  5662. } elseif ($statusInfo['status'] === 'failed') {
  5663. $task->updateStatus('failed', [
  5664. 'error_message' => $statusInfo['error_message'],
  5665. 'result_json' => $statusInfo['result_json'] ?? []
  5666. ]);
  5667. dLog('anime')->error('图片生成失败,', [
  5668. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5669. ]);
  5670. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5671. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5672. }
  5673. }
  5674. }
  5675. if (empty($img_url)) {
  5676. Utils::throwError('20003:图片生成超时,请稍后重试');
  5677. }
  5678. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5679. if (count($img_urls) > 1) {
  5680. return [
  5681. 'img_url' => $img_url,
  5682. 'image_urls' => $img_urls,
  5683. 'task_id' => $taskCenterId,
  5684. ];
  5685. }
  5686. return [
  5687. 'img_url' => $img_url,
  5688. 'task_id' => $taskCenterId,
  5689. ];
  5690. } catch (\Exception $e) {
  5691. dLog('anime')->error('更新角色或场景失败', [
  5692. 'error' => $e->getMessage()
  5693. ]);
  5694. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5695. Utils::throwError('20003:' . $e->getMessage());
  5696. }
  5697. }
  5698. /**
  5699. * 使用文生文模型解析分镜内容
  5700. */
  5701. private function parseSegmentContentWithAI($segment_content) {
  5702. try {
  5703. // 使用DeepSeek服务的公开方法解析分镜内容
  5704. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5705. } catch (\Exception $e) {
  5706. // 如果AI解析失败,记录日志并返回原内容
  5707. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5708. return $segment_content;
  5709. }
  5710. }
  5711. /**
  5712. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5713. *
  5714. * @param int $episode_id 分集ID
  5715. * @param int $anime_id 动漫ID
  5716. * @param array $roles 分集角色数组(引用传递)
  5717. * @param array $scenes 分集场景数组(引用传递)
  5718. * @param array $episode 分集数据
  5719. */
  5720. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5721. // 获取全局动漫的角色和场景数据
  5722. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5723. if (!$anime) return;
  5724. $art_style_type = getProp($anime, 'art_style_type');
  5725. $character_prefix = '';
  5726. $scene_prefix = '';
  5727. if ($art_style_type) {
  5728. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5729. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5730. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5731. }
  5732. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5733. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5734. $roles_updated = false;
  5735. $scenes_updated = false;
  5736. // 处理角色
  5737. foreach ($roles as &$role) {
  5738. $role_name = getProp($role, 'role');
  5739. $role_description = getProp($role, 'description');
  5740. $role_pic_prompt = getProp($role, 'pic_prompt');
  5741. $role_url = getProp($role, 'url');
  5742. $role_task_id = getProp($role, 'task_id');
  5743. // 如果已有URL或已有任务ID,跳过
  5744. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5745. continue;
  5746. }
  5747. $url_inherited = false;
  5748. // 尝试从全局数据中继承
  5749. foreach ($global_roles as $global_role) {
  5750. $global_role_name = getProp($global_role, 'role');
  5751. $global_role_description = getProp($global_role, 'description');
  5752. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5753. $global_role_url = getProp($global_role, 'url');
  5754. $global_role_task_id = getProp($global_role, 'task_id');
  5755. $global_role_task_status = getProp($global_role, 'task_status');
  5756. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5757. if ($role_name === $global_role_name
  5758. && $role_description === $global_role_description
  5759. && $role_pic_prompt === $global_role_pic_prompt
  5760. && !empty($global_role_url)) {
  5761. // 继承 task_id、task_status 和 url
  5762. $role['task_id'] = $global_role_task_id;
  5763. $role['task_status'] = $global_role_task_status;
  5764. $role['url'] = $global_role_url;
  5765. $roles_updated = true;
  5766. $url_inherited = true;
  5767. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5768. break;
  5769. }
  5770. }
  5771. // 如果无法继承且没有任务ID,创建新任务
  5772. if (!$url_inherited && empty($role_task_id)) {
  5773. try {
  5774. $art_style = getProp($episode, 'art_style');
  5775. // 优先使用 pic_prompt,如果没有则使用 description
  5776. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5777. // if ($art_style) {
  5778. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5779. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5780. // }
  5781. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5782. $params = [
  5783. 'prompt' => $description,
  5784. 'ref_img_urls' => [],
  5785. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  5786. 'anime_id' => $anime_id,
  5787. 'episode_id' => $episode_id,
  5788. 'episode_number' => getProp($episode, 'episode_number'),
  5789. ];
  5790. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5791. $task_id = $task->id;
  5792. if ($task_id) {
  5793. $role['task_id'] = $task_id;
  5794. $role['task_status'] = 'processing';
  5795. $roles_updated = true;
  5796. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5797. }
  5798. } catch (\Exception $e) {
  5799. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5800. }
  5801. }
  5802. }
  5803. // 处理场景
  5804. foreach ($scenes as &$scene) {
  5805. $scene_name = getProp($scene, 'scene');
  5806. $scene_description = getProp($scene, 'description');
  5807. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5808. $scene_url = getProp($scene, 'url');
  5809. $scene_task_id = getProp($scene, 'task_id');
  5810. // 如果已有URL或已有任务ID,跳过
  5811. if (!empty($scene_url) || !empty($scene_task_id)) {
  5812. continue;
  5813. }
  5814. $url_inherited = false;
  5815. // 尝试从全局数据中继承
  5816. foreach ($global_scenes as $global_scene) {
  5817. $global_scene_name = getProp($global_scene, 'scene');
  5818. $global_scene_description = getProp($global_scene, 'description');
  5819. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5820. $global_scene_url = getProp($global_scene, 'url');
  5821. $global_scene_task_id = getProp($global_scene, 'task_id');
  5822. $global_scene_task_status = getProp($global_scene, 'task_status');
  5823. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5824. if ($scene_name === $global_scene_name
  5825. && $scene_description === $global_scene_description
  5826. && $scene_pic_prompt === $global_scene_pic_prompt
  5827. && !empty($global_scene_url)) {
  5828. // 继承 task_id、task_status 和 url
  5829. $scene['task_id'] = $global_scene_task_id;
  5830. $scene['task_status'] = $global_scene_task_status;
  5831. $scene['url'] = $global_scene_url;
  5832. $scenes_updated = true;
  5833. $url_inherited = true;
  5834. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5835. break;
  5836. }
  5837. }
  5838. // 如果无法继承且没有任务ID,创建新任务
  5839. if (!$url_inherited && empty($scene_task_id)) {
  5840. try {
  5841. $art_style = getProp($episode, 'art_style');
  5842. // 优先使用 pic_prompt,如果没有则使用 description
  5843. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5844. // if ($art_style) {
  5845. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5846. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5847. // }
  5848. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5849. $params = [
  5850. 'prompt' => $description,
  5851. 'ref_img_urls' => [],
  5852. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  5853. 'anime_id' => $anime_id,
  5854. 'episode_id' => $episode_id,
  5855. 'episode_number' => getProp($episode, 'episode_number'),
  5856. ];
  5857. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5858. $task_id = $task->id;
  5859. if ($task_id) {
  5860. $scene['task_id'] = $task_id;
  5861. $scene['task_status'] = 'processing';
  5862. $scenes_updated = true;
  5863. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5864. }
  5865. } catch (\Exception $e) {
  5866. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5867. }
  5868. }
  5869. }
  5870. // 如果有更新,保存到数据库
  5871. if ($roles_updated || $scenes_updated) {
  5872. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5873. if ($roles_updated) {
  5874. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5875. }
  5876. if ($scenes_updated) {
  5877. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5878. }
  5879. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5880. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5881. }
  5882. }
  5883. /**
  5884. * 根据图片URL使用AI反推图片提示词
  5885. *
  5886. * @param string $img_url 图片URL
  5887. * @return string 反推的提示词
  5888. */
  5889. private function generateImagePromptFromUrl($img_url) {
  5890. try {
  5891. // 获取默认模型
  5892. $model = 'doubao-seed-2-0-mini-260215';
  5893. // 构建messages参数
  5894. $messages = [
  5895. [
  5896. 'role' => 'user',
  5897. 'content' => [
  5898. [
  5899. 'type' => 'text',
  5900. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5901. ],
  5902. [
  5903. 'type' => 'image_url',
  5904. 'image_url' => [
  5905. 'url' => $img_url
  5906. ]
  5907. ]
  5908. ]
  5909. ]
  5910. ];
  5911. // 构建请求参数
  5912. $params = [
  5913. 'model' => $model,
  5914. 'messages' => $messages,
  5915. 'stream' => false,
  5916. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5917. ];
  5918. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5919. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5920. // 仅记录 token 使用明细(不扣积分)
  5921. $uid = 0;
  5922. try {
  5923. $uid = (int)Site::getUid();
  5924. } catch (\Throwable $e) {
  5925. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5926. }
  5927. $this->pointsService->recordTokenOnlyDetail(
  5928. $uid,
  5929. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5930. [
  5931. 'model' => $model,
  5932. 'img_url' => $img_url,
  5933. 'source' => 'generateImagePromptFromUrl',
  5934. ],
  5935. 'chat',
  5936. $model,
  5937. ''
  5938. );
  5939. // 返回生成的内容
  5940. return getProp($result, 'fullContent', '图片描述生成失败');
  5941. } catch (\Exception $e) {
  5942. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5943. 'img_url' => $img_url
  5944. ]);
  5945. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5946. 'error' => $e->getMessage(),
  5947. 'img_url' => $img_url
  5948. ]);
  5949. return '图片描述生成失败: ' . $e->getMessage();
  5950. }
  5951. }
  5952. /**
  5953. * 音频试听接口
  5954. * 创建音频任务并轮询获取结果
  5955. *
  5956. * @param array $data 参数数组
  5957. * @return array 返回音频URL或错误信息
  5958. */
  5959. public function previewAudio($data) {
  5960. $dialogue = getProp($data, 'dialogue');
  5961. // 必填参数验证
  5962. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5963. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5964. $voice_type = getProp($data, 'voice_type');
  5965. $voice_name = getProp($data, 'voice_name');
  5966. $voice_actor = getProp($data, 'voice_actor');
  5967. $emotion_type = getProp($data, 'emotion_type');
  5968. $gender = getProp($data, 'gender', 0);
  5969. $emotion = getProp($data, 'emotion');
  5970. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5971. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5972. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5973. $pitch = getProp($data, 'pitch', 0);
  5974. try {
  5975. $now = date('Y-m-d H:i:s');
  5976. // 构建生成参数
  5977. $generate_json = json_encode([
  5978. 'text' => $dialogue,
  5979. 'role' => $voice_actor,
  5980. 'voice_type' => $voice_type,
  5981. 'voice_name' => $voice_name,
  5982. 'emotion' => $emotion,
  5983. 'emotion_type' => $emotion_type,
  5984. 'gender' => $gender,
  5985. 'speed_ratio' => $speed_ratio,
  5986. 'loudness_ratio' => $loudness_ratio,
  5987. 'emotion_scale' => $emotion_scale,
  5988. 'pitch' => $pitch,
  5989. ], 256);
  5990. // 请求远程服务器执行生成
  5991. $client = new Client(['timeout' => 600, 'verify' => false]);
  5992. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5993. $response = $result->getBody()->getContents();
  5994. $response_arr = json_decode($response, true);
  5995. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5996. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5997. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5998. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5999. }
  6000. $arr = $response_arr['data'];
  6001. $subtitle_info = $arr['subtitle_info'];
  6002. $audio_duration = json_decode($subtitle_info, true)['duration'];
  6003. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  6004. return [
  6005. 'audio_url' => $arr['url'],
  6006. 'subtitle_info' => $subtitle_info,
  6007. 'audio_duration' => round($audio_duration, 2)
  6008. ];
  6009. } catch (\Exception $e) {
  6010. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  6011. Utils::throwError('20003:' . $e->getMessage());
  6012. }
  6013. }
  6014. /**
  6015. * 获取角色库列表(支持文件夹递归查询)
  6016. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  6017. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  6018. */
  6019. public function globalProducts($data) {
  6020. $uid = Site::getUid();
  6021. $cpid = Site::getCpid();
  6022. $role = Site::getRole();
  6023. $id = getProp($data, 'id', 0);
  6024. $parent_id = getProp($data, 'parent_id', 0);
  6025. $product_name = getProp($data, 'product_name');
  6026. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  6027. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  6028. if (!$product) {
  6029. Utils::throwError('20003:请选择产品类型');
  6030. }
  6031. // 根据角色和is_public参数确定查询范围
  6032. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  6033. // user角色:根据is_public参数筛选
  6034. $query_user_ids = [];
  6035. if ($role === 'admin') {
  6036. // admin获取所有个人库和公共库
  6037. $query_user_ids = [$uid, 0];
  6038. } else {
  6039. // user角色根据is_public参数筛选
  6040. if ($is_public == 2) {
  6041. // 个人库+公共库
  6042. $query_user_ids = [$uid, 0];
  6043. } elseif ($is_public == 0) {
  6044. // 仅个人库
  6045. $query_user_ids = [$uid];
  6046. } elseif ($is_public == 1) {
  6047. // 仅公共库
  6048. $query_user_ids = [0];
  6049. }
  6050. }
  6051. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  6052. if ($id || $product_name) {
  6053. $query = DB::table('mp_products')
  6054. ->where('cpid', $cpid)
  6055. ->whereIn('user_id', $query_user_ids)
  6056. ->where('is_deleted', 0);
  6057. // 如果指定了 id,按 id 精确查询
  6058. if ($id) {
  6059. $query->where('id', $id);
  6060. }
  6061. // 如果指定了 product_name,按名称模糊查询
  6062. if ($product_name) {
  6063. $query->where('product_name', 'like', "%{$product_name}%");
  6064. }
  6065. // 如果指定了 product,添加筛选条件
  6066. if ($product) {
  6067. $query->where('product', $product);
  6068. }
  6069. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'timbre_url', 'versions', 'product', 'user_id', 'created_at')
  6070. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  6071. ->get()
  6072. ->map(function($value) {
  6073. $value = (array)$value;
  6074. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  6075. $value['type'] = (int)$value['type'];
  6076. $value['parent_id'] = (int)$value['parent_id'];
  6077. $value['level'] = (int)$value['level'];
  6078. $value['product'] = (int)($value['product'] ?? 1);
  6079. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  6080. $value['timbre_url'] = $value['timbre_url'] ?? '';
  6081. $value['versions'] = json_decode($value['versions'], true) ?: [];
  6082. unset($value['user_id']);
  6083. return $value;
  6084. })
  6085. ->toArray();
  6086. return $result;
  6087. }
  6088. // 递归获取所有子目录和角色
  6089. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  6090. }
  6091. /**
  6092. * 递归获取指定目录下的所有子目录和角色
  6093. * @param int $cpid 公司ID
  6094. * @param int $parent_id 父目录ID
  6095. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  6096. * @param array $query_user_ids 用户ID数组(支持多个)
  6097. * @param int $current_uid 当前用户ID(用于排序)
  6098. * @return array
  6099. */
  6100. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  6101. // 查询当前层级的所有项(文件夹和角色)
  6102. $query = DB::table('mp_products')
  6103. ->where('cpid', $cpid)
  6104. ->where('is_deleted', 0)
  6105. ->where('parent_id', $parent_id);
  6106. // 添加用户ID验证(支持多个user_id)
  6107. if (!empty($query_user_ids)) {
  6108. $query->whereIn('user_id', $query_user_ids);
  6109. }
  6110. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  6111. if ($product) {
  6112. $query->where('product', $product);
  6113. }
  6114. // 排序规则:
  6115. // 1. 文件夹在前(type DESC)
  6116. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  6117. // 3. 其他排序规则
  6118. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'timbre_url', 'versions', 'product', 'user_id', 'created_at')
  6119. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  6120. ->get();
  6121. $result = [];
  6122. foreach ($items as $item) {
  6123. $itemArray = [
  6124. 'id' => $item->id,
  6125. 'type' => (int)$item->type,
  6126. 'parent_id' => (int)$item->parent_id,
  6127. 'level' => (int)$item->level,
  6128. 'product_name' => $item->product_name,
  6129. 'url' => $item->url,
  6130. 'pic_prompt' => $item->pic_prompt ?? '',
  6131. 'three_view_image_url' => $item->three_view_image_url,
  6132. 'timbre_url' => $item->timbre_url ?? '',
  6133. 'product' => (int)($item->product ?? 1),
  6134. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  6135. 'created_at' => transDate($item->created_at, 'Y-m-d')
  6136. ];
  6137. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  6138. // 如果是文件夹,递归获取其子项
  6139. if ($item->type == 2) {
  6140. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  6141. if (!empty($children)) {
  6142. $itemArray['children'] = $children;
  6143. }
  6144. }
  6145. $result[] = $itemArray;
  6146. }
  6147. return $result;
  6148. }
  6149. /**
  6150. * 创建文件夹
  6151. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  6152. * @return int 返回新建文件夹ID
  6153. */
  6154. public function createFolder($data) {
  6155. $uid = Site::getUid();
  6156. $cpid = Site::getCpid();
  6157. $role = Site::getRole();
  6158. $parent_id = getProp($data, 'parent_id', 0);
  6159. $folder_name = getProp($data, 'product_name', '新建文件夹');
  6160. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6161. // 如果是公共库操作,需要admin权限
  6162. if ($is_public && $role !== 'admin') {
  6163. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6164. }
  6165. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6166. $store_uid = $is_public ? 0 : $uid;
  6167. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6168. $product = getProp($data, 'product');
  6169. if (!in_array($product, [1, 2, 3])) {
  6170. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  6171. }
  6172. // 验证父文件夹
  6173. $parent_level = 0;
  6174. if ($parent_id > 0) {
  6175. $parent = DB::table('mp_products')
  6176. ->where('id', $parent_id)
  6177. ->where('cpid', $cpid)
  6178. ->where('user_id', $store_uid)
  6179. ->where('type', 2)
  6180. ->where('is_deleted', 0)
  6181. ->first();
  6182. if (!$parent) {
  6183. Utils::throwError('20003:父文件夹不存在');
  6184. }
  6185. // 检查父文件夹的 product 类型是否一致
  6186. if ($parent->product != $product) {
  6187. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  6188. }
  6189. $parent_level = $parent->level;
  6190. // 检查层级限制(最多3层)
  6191. if ($parent_level >= 3) {
  6192. Utils::throwError('20003:文件夹层级不能超过3层');
  6193. }
  6194. }
  6195. // 检查当前目录下是否已存在空白文件夹
  6196. $empty_folder_exists = DB::table('mp_products')
  6197. ->where('parent_id', $parent_id)
  6198. ->where('cpid', $cpid)
  6199. ->where('user_id', $store_uid)
  6200. ->where('type', 2)
  6201. ->where('product', $product)
  6202. ->where('product_name', '新建文件夹')
  6203. ->where('is_deleted', 0)
  6204. ->exists();
  6205. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  6206. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  6207. }
  6208. // 创建文件夹
  6209. $folder_id = DB::table('mp_products')->insertGetId([
  6210. 'user_id' => $store_uid,
  6211. 'cpid' => $cpid,
  6212. 'type' => 2,
  6213. 'parent_id' => $parent_id,
  6214. 'level' => $parent_level + 1,
  6215. 'product_name' => $folder_name,
  6216. 'product' => $product,
  6217. 'sort_order' => time(), // 使用时间戳作为排序权重
  6218. 'is_deleted' => 0,
  6219. 'created_at' => date('Y-m-d H:i:s'),
  6220. 'updated_at' => date('Y-m-d H:i:s')
  6221. ]);
  6222. return [
  6223. 'id' => $folder_id,
  6224. 'type' => 2,
  6225. 'parent_id' => $parent_id,
  6226. 'level' => $parent_level + 1,
  6227. 'product_name' => $folder_name,
  6228. 'product' => $product,
  6229. ];
  6230. }
  6231. /**
  6232. * 重命名文件夹或角色
  6233. * @param array $data 包含 id、product_name(新名称)
  6234. * @return bool
  6235. */
  6236. public function renameFolder($data) {
  6237. $uid = Site::getUid();
  6238. $cpid = Site::getCpid();
  6239. $role = Site::getRole();
  6240. $id = getProp($data, 'id');
  6241. $new_name = getProp($data, 'product_name');
  6242. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6243. if (!$id || !$new_name) {
  6244. Utils::throwError('20003:参数不完整');
  6245. }
  6246. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6247. $query_uid = $is_public ? 0 : $uid;
  6248. // 如果是公共库操作,需要admin权限
  6249. if ($is_public && $role !== 'admin') {
  6250. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6251. }
  6252. // 检查是否存在
  6253. $item = DB::table('mp_products')
  6254. ->where('id', $id)
  6255. ->where('cpid', $cpid)
  6256. ->where('user_id', $query_uid)
  6257. ->where('is_deleted', 0)
  6258. ->first();
  6259. if (!$item) {
  6260. Utils::throwError('20003:项目不存在');
  6261. }
  6262. return DB::table('mp_products')
  6263. ->where('id', $id)
  6264. ->where('cpid', $cpid)
  6265. ->where('user_id', $query_uid)
  6266. ->update([
  6267. 'product_name' => $new_name,
  6268. 'updated_at' => date('Y-m-d H:i:s')
  6269. ]);
  6270. }
  6271. /**
  6272. * 移动角色或文件夹到指定文件夹
  6273. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6274. * @return bool
  6275. */
  6276. public function moveProductOrFolder($data) {
  6277. $uid = Site::getUid();
  6278. $cpid = Site::getCpid();
  6279. $role = Site::getRole();
  6280. $id = getProp($data, 'id');
  6281. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6282. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6283. if (!$id) {
  6284. Utils::throwError('20003:请选择要移动的项目');
  6285. }
  6286. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6287. $query_uid = $is_public ? 0 : $uid;
  6288. // 如果是公共库操作,需要admin权限
  6289. if ($is_public && $role !== 'admin') {
  6290. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6291. }
  6292. // 检查要移动的项目
  6293. $item = DB::table('mp_products')
  6294. ->where('id', $id)
  6295. ->where('cpid', $cpid)
  6296. ->where('user_id', $query_uid)
  6297. ->where('is_deleted', 0)
  6298. ->first();
  6299. if (!$item) {
  6300. Utils::throwError('20003:项目不存在');
  6301. }
  6302. // 验证目标文件夹
  6303. $target_level = 0;
  6304. $target_product = $item->product; // 默认使用当前项目的 product
  6305. if ($target_parent_id > 0) {
  6306. $target_parent = DB::table('mp_products')
  6307. ->where('id', $target_parent_id)
  6308. ->where('cpid', $cpid)
  6309. ->where('user_id', $query_uid)
  6310. ->where('type', 2)
  6311. ->where('is_deleted', 0)
  6312. ->first();
  6313. if (!$target_parent) {
  6314. Utils::throwError('20003:目标文件夹不存在');
  6315. }
  6316. // 检查 product 类型是否一致
  6317. if ($target_parent->product != $item->product) {
  6318. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6319. }
  6320. $target_level = $target_parent->level;
  6321. $target_product = $target_parent->product;
  6322. // 如果移动的是文件夹,需要检查层级
  6323. if ($item->type == 2) {
  6324. // 计算移动后的最大层级
  6325. $max_child_level = $this->getMaxChildLevel($id);
  6326. $depth = $max_child_level - $item->level;
  6327. if ($target_level + 1 + $depth > 3) {
  6328. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6329. }
  6330. // 不能移动到自己或自己的子文件夹下
  6331. if ($this->isDescendant($target_parent_id, $id)) {
  6332. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6333. }
  6334. }
  6335. }
  6336. // 更新父文件夹和层级
  6337. $new_level = $target_level + 1;
  6338. DB::table('mp_products')
  6339. ->where('id', $id)
  6340. ->update([
  6341. 'parent_id' => $target_parent_id,
  6342. 'level' => $new_level,
  6343. 'updated_at' => date('Y-m-d H:i:s')
  6344. ]);
  6345. // 如果是文件夹,需要递归更新所有子项的层级
  6346. if ($item->type == 2) {
  6347. $this->updateChildrenLevel($id, $new_level);
  6348. }
  6349. return true;
  6350. }
  6351. /**
  6352. * 获取文件夹下最大子层级
  6353. * @param int $folder_id
  6354. * @return int
  6355. */
  6356. private function getMaxChildLevel($folder_id) {
  6357. $max_level = DB::table('mp_products')
  6358. ->where('parent_id', $folder_id)
  6359. ->where('is_deleted', 0)
  6360. ->max('level');
  6361. if (!$max_level) {
  6362. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6363. }
  6364. // 递归查找子文件夹
  6365. $children = DB::table('mp_products')
  6366. ->where('parent_id', $folder_id)
  6367. ->where('type', 2)
  6368. ->where('is_deleted', 0)
  6369. ->pluck('id');
  6370. foreach ($children as $child_id) {
  6371. $child_max = $this->getMaxChildLevel($child_id);
  6372. if ($child_max > $max_level) {
  6373. $max_level = $child_max;
  6374. }
  6375. }
  6376. return $max_level;
  6377. }
  6378. /**
  6379. * 检查 target_id 是否是 folder_id 的后代
  6380. * @param int $target_id
  6381. * @param int $folder_id
  6382. * @return bool
  6383. */
  6384. private function isDescendant($target_id, $folder_id) {
  6385. if ($target_id == $folder_id) {
  6386. return true;
  6387. }
  6388. $parent = DB::table('mp_products')
  6389. ->where('id', $target_id)
  6390. ->where('is_deleted', 0)
  6391. ->first();
  6392. if (!$parent || $parent->parent_id == 0) {
  6393. return false;
  6394. }
  6395. return $this->isDescendant($parent->parent_id, $folder_id);
  6396. }
  6397. /**
  6398. * 递归更新子项层级
  6399. * @param int $parent_id
  6400. * @param int $parent_level
  6401. */
  6402. private function updateChildrenLevel($parent_id, $parent_level) {
  6403. $children = DB::table('mp_products')
  6404. ->where('parent_id', $parent_id)
  6405. ->where('is_deleted', 0)
  6406. ->get();
  6407. foreach ($children as $child) {
  6408. $new_level = $parent_level + 1;
  6409. DB::table('mp_products')
  6410. ->where('id', $child->id)
  6411. ->update([
  6412. 'level' => $new_level,
  6413. 'updated_at' => date('Y-m-d H:i:s')
  6414. ]);
  6415. // 如果是文件夹,继续递归
  6416. if ($child->type == 2) {
  6417. $this->updateChildrenLevel($child->id, $new_level);
  6418. }
  6419. }
  6420. }
  6421. /**
  6422. * 获取文件夹路径(面包屑导航)
  6423. * @param array $data 包含 folder_id
  6424. * @return array 返回路径数组
  6425. */
  6426. public function getFolderPath($data) {
  6427. $uid = Site::getUid();
  6428. $cpid = Site::getCpid();
  6429. $folder_id = getProp($data, 'id', 0);
  6430. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6431. if ($folder_id == 0) {
  6432. return [
  6433. ['id' => 0, 'name' => '根目录']
  6434. ];
  6435. }
  6436. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6437. $query_uid = $is_public ? 0 : $uid;
  6438. $path = [];
  6439. $current_id = $folder_id;
  6440. while ($current_id > 0) {
  6441. $folder = DB::table('mp_products')
  6442. ->where('id', $current_id)
  6443. ->where('cpid', $cpid)
  6444. ->where('user_id', $query_uid)
  6445. ->where('type', 2)
  6446. ->where('is_deleted', 0)
  6447. ->first();
  6448. if (!$folder) {
  6449. break;
  6450. }
  6451. array_unshift($path, [
  6452. 'id' => $folder->id,
  6453. 'name' => $folder->product_name
  6454. ]);
  6455. $current_id = $folder->parent_id;
  6456. }
  6457. // 添加根目录
  6458. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6459. return $path;
  6460. }
  6461. public function createProduct($data) {
  6462. $uid = Site::getUid();
  6463. $cpid = Site::getCpid();
  6464. $role = Site::getRole();
  6465. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6466. // 如果是公共库操作,需要admin权限
  6467. if ($is_public && $role !== 'admin') {
  6468. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6469. }
  6470. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6471. $store_uid = $is_public ? 0 : $uid;
  6472. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6473. $script_id = (int)getProp($data, 'script_id', 0);
  6474. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6475. if ($script_id && empty($episode_numbers)) {
  6476. Utils::throwError('20003:剧集序号不能为空');
  6477. }
  6478. if (!$script_id && !empty($episode_numbers)) {
  6479. Utils::throwError('20003:请提供剧本ID');
  6480. }
  6481. $product_name = trim(getProp($data, 'product_name'));
  6482. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6483. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6484. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6485. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6486. $url = trim(getProp($data, 'url'));
  6487. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6488. $versions = getProp($data, 'versions');
  6489. // 检查是否是正确的图片格式
  6490. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6491. $urlPath = parse_url($url, PHP_URL_PATH);
  6492. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6493. if (!in_array($extension, $allowedExtensions)) {
  6494. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6495. }
  6496. // 选填三视图图片地址,格式校验与 url 一致
  6497. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6498. if ($three_view_image_url) {
  6499. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6500. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6501. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6502. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6503. }
  6504. }
  6505. // 选填音色音频地址(兼容 timbre_url/audio_url/timbre 传参)
  6506. $timbre_url = $this->getProductTimbreUrl($data);
  6507. if ($timbre_url) {
  6508. $this->validateProductAudioUrl($timbre_url);
  6509. }
  6510. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6511. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6512. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6513. $product = getProp($data, 'product');
  6514. if (!in_array($product, [1, 2, 3])) {
  6515. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6516. }
  6517. // 获取父文件夹ID和层级
  6518. $parent_id = getProp($data, 'parent_id', 0);
  6519. $parent_level = 0;
  6520. if ($parent_id > 0) {
  6521. $parent = DB::table('mp_products')
  6522. ->where('id', $parent_id)
  6523. ->where('cpid', $cpid)
  6524. ->where('user_id', $store_uid)
  6525. ->where('type', 2)
  6526. ->where('is_deleted', 0)
  6527. ->first();
  6528. if (!$parent) {
  6529. Utils::throwError('20003:父文件夹不存在');
  6530. }
  6531. $parent_level = $parent->level;
  6532. }
  6533. // 创建资产并保存剧本资产关联关系(同一事务)
  6534. DB::beginTransaction();
  6535. try {
  6536. $id = DB::table('mp_products')->insertGetId([
  6537. 'user_id' => $store_uid,
  6538. 'cpid' => $cpid,
  6539. 'type' => 1, // 1=角色图片
  6540. 'parent_id' => $parent_id,
  6541. 'level' => $parent_level + 1,
  6542. 'product_name' => $product_name,
  6543. 'url' => $url,
  6544. 'three_view_image_url' => $three_view_image_url,
  6545. 'timbre_url' => $timbre_url,
  6546. 'pic_prompt' => $pic_prompt,
  6547. 'product' => $product,
  6548. 'versions' => json_encode($versions, 256),
  6549. 'sort_order' => time(), // 使用时间戳作为排序权重
  6550. 'created_at' => date('Y-m-d H:i:s'),
  6551. 'updated_at' => date('Y-m-d H:i:s')
  6552. ]);
  6553. if (!$id) Utils::throwError('20003:创建失败');
  6554. // 保存剧本资产关联关系
  6555. if ($script_id) {
  6556. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6557. }
  6558. DB::commit();
  6559. } catch (\Exception $e) {
  6560. DB::rollback();
  6561. throw $e;
  6562. }
  6563. return [
  6564. 'id' => $id,
  6565. 'type' => 1,
  6566. 'parent_id' => $parent_id,
  6567. 'level' => $parent_level + 1,
  6568. 'product_name' => $product_name,
  6569. 'url' => $url,
  6570. 'three_view_image_url' => $three_view_image_url,
  6571. 'timbre_url' => $timbre_url,
  6572. 'pic_prompt' => $pic_prompt,
  6573. 'product' => $product,
  6574. 'versions' => $versions
  6575. ];
  6576. }
  6577. public function editProduct($data) {
  6578. $uid = Site::getUid();
  6579. $cpid = Site::getCpid();
  6580. $role = Site::getRole();
  6581. $id = getProp($data, 'id');
  6582. if (!$id) Utils::throwError('20003:ID不能为空');
  6583. $versions = getProp($data, 'versions');
  6584. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6585. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6586. $script_id = (int)getProp($data, 'script_id', 0);
  6587. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6588. if ($script_id && empty($episode_numbers)) {
  6589. Utils::throwError('20003:剧集序号不能为空');
  6590. }
  6591. if (!$script_id && !empty($episode_numbers)) {
  6592. Utils::throwError('20003:请提供剧本ID');
  6593. }
  6594. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6595. $query_uid = $is_public ? 0 : $uid;
  6596. // 如果是公共库操作,需要admin权限
  6597. if ($is_public && $role !== 'admin') {
  6598. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6599. }
  6600. // 检查是否存在且属于当前用户或公共库
  6601. $role = DB::table('mp_products')
  6602. ->where('id', $id)
  6603. ->where('cpid', $cpid)
  6604. ->where('user_id', $query_uid)
  6605. ->where('type', 1)->first();
  6606. if (!$role) Utils::throwError('20003:记录不存在');
  6607. $updateData = [];
  6608. // $needVersionRecord = false; // 是否需要记录版本
  6609. // 名称
  6610. $product_name = trim(getProp($data, 'product_name'));
  6611. if ($product_name) {
  6612. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6613. $updateData['product_name'] = $product_name;
  6614. }
  6615. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6616. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6617. // 图片地址
  6618. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6619. $url = trim(getProp($data, 'url'));
  6620. if ($url) {
  6621. // 检查是否是正确的图片格式
  6622. $urlPath = parse_url($url, PHP_URL_PATH);
  6623. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6624. if (!in_array($extension, $allowedExtensions)) {
  6625. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6626. }
  6627. // // 如果 url 有变更,记录版本
  6628. // if ($url !== $role->url) {
  6629. // $needVersionRecord = true;
  6630. // }
  6631. $updateData['url'] = $url;
  6632. }
  6633. // 三视图图片地址(选填),格式校验与 url 一致;显式传空表示当前版本没有三视图
  6634. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6635. if ($three_view_image_url) {
  6636. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6637. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6638. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6639. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6640. }
  6641. }
  6642. // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
  6643. if (array_key_exists('three_view_image_url', $data)) {
  6644. $updateData['three_view_image_url'] = $three_view_image_url;
  6645. }
  6646. // 音色音频地址(选填,显式传空字符串可清除已有音色)
  6647. if (array_key_exists('timbre_url', $data) || array_key_exists('audio_url', $data) || array_key_exists('timbre', $data)) {
  6648. $timbre_url = $this->getProductTimbreUrl($data);
  6649. if ($timbre_url) {
  6650. $this->validateProductAudioUrl($timbre_url);
  6651. }
  6652. $updateData['timbre_url'] = $timbre_url;
  6653. }
  6654. // 提示词
  6655. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6656. if ($pic_prompt) {
  6657. // // 如果 pic_prompt 有变更,记录版本
  6658. // if ($pic_prompt !== $role->pic_prompt) {
  6659. // $needVersionRecord = true;
  6660. // }
  6661. $updateData['pic_prompt'] = $pic_prompt;
  6662. }else {
  6663. Utils::throwError('20003:请输入提示词');
  6664. }
  6665. if (empty($updateData) && !$script_id) {
  6666. Utils::throwError('20003:没有需要更新的数据');
  6667. }
  6668. // // 如果需要记录版本,将数据添加到 versions 数组
  6669. // if ($needVersionRecord) {
  6670. // // 获取现有的 versions 数据
  6671. // $versions = json_decode($role->versions, true) ?: [];
  6672. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6673. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6674. // if ($isFirstVersion) {
  6675. // $oldVersion = [
  6676. // 'url' => $role->url,
  6677. // 'description' => $role->pic_prompt,
  6678. // ];
  6679. // // 旧版本添加到数组末尾
  6680. // $versions[] = $oldVersion;
  6681. // }
  6682. // // 构建新版本(变更后)
  6683. // $newVersion = [
  6684. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6685. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6686. // ];
  6687. // // 检查新版本是否已存在于历史版本中
  6688. // $existingIndex = -1;
  6689. // foreach ($versions as $index => $version) {
  6690. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6691. // $existingIndex = $index;
  6692. // break;
  6693. // }
  6694. // }
  6695. // if ($existingIndex !== -1) {
  6696. // // 如果已存在,移除旧的位置
  6697. // array_splice($versions, $existingIndex, 1);
  6698. // }
  6699. // // 新版本添加到数组开头(最新的在前)
  6700. // array_unshift($versions, $newVersion);
  6701. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6702. // // if (count($versions) > 10) {
  6703. // // $versions = array_slice($versions, 0, 10);
  6704. // // }
  6705. // $updateData['versions'] = json_encode($versions, 256);
  6706. // }
  6707. if ($versions) {
  6708. $updateData['versions'] = json_encode($versions, 256);
  6709. }
  6710. if (!empty($updateData)) {
  6711. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6712. }
  6713. // 更新资产并保存剧本资产关联关系(同一事务)
  6714. DB::beginTransaction();
  6715. try {
  6716. $updated = true;
  6717. if (!empty($updateData)) {
  6718. $updated = DB::table('mp_products')
  6719. ->where('cpid', $cpid)
  6720. ->where('id', $id)
  6721. ->update($updateData);
  6722. }
  6723. // 保存剧本资产关联关系
  6724. if ($script_id) {
  6725. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6726. }
  6727. DB::commit();
  6728. } catch (\Exception $e) {
  6729. DB::rollback();
  6730. throw $e;
  6731. }
  6732. return $updated;
  6733. }
  6734. /**
  6735. * 获取资产音色音频地址
  6736. * 兼容 timbre_url/audio_url/timbre 三种传参,timbre 支持字符串或 {"url":"..."} 结构
  6737. *
  6738. * @param array $data
  6739. * @return string
  6740. */
  6741. private function getProductTimbreUrl($data) {
  6742. foreach (['timbre_url', 'audio_url', 'timbre'] as $key) {
  6743. if (!array_key_exists($key, $data)) {
  6744. continue;
  6745. }
  6746. $value = $data[$key];
  6747. if (is_array($value)) {
  6748. $value = getProp($value, 'url', $value[0] ?? '');
  6749. }
  6750. if (!is_string($value)) {
  6751. continue;
  6752. }
  6753. return trim($value);
  6754. }
  6755. return '';
  6756. }
  6757. /**
  6758. * 校验资产音色音频地址格式
  6759. *
  6760. * @param string $url 音频地址
  6761. * @return void
  6762. */
  6763. private function validateProductAudioUrl($url) {
  6764. $allowedExtensions = ['mp3', 'wav', 'm4a', 'aac', 'ogg', 'oga', 'flac', 'amr', 'wma', 'weba'];
  6765. $urlPath = parse_url($url, PHP_URL_PATH);
  6766. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6767. if (!in_array($extension, $allowedExtensions)) {
  6768. Utils::throwError('20003:音色音频格式不正确,仅支持 mp3、wav、m4a、aac、ogg、flac、amr、wma 格式');
  6769. }
  6770. }
  6771. /**
  6772. * 保存单一资产与剧本剧集的关联关系
  6773. *
  6774. * @param int $product_id 资产ID
  6775. * @param int $script_id 剧本ID
  6776. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6777. * @return int 新增关联数量
  6778. */
  6779. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6780. $uid = Site::getUid();
  6781. // 验证剧本是否存在
  6782. $script = DB::table('mp_scripts')
  6783. ->where('id', $script_id)
  6784. ->where('is_deleted', 0)
  6785. ->first();
  6786. if (!$script) {
  6787. Utils::throwError('20003:剧本不存在');
  6788. }
  6789. // 验证剧本归属:只能关联自己的剧本
  6790. if ((int)$script->user_id !== (int)$uid) {
  6791. Utils::throwError('20003:只能添加到自己的剧本');
  6792. }
  6793. // 使用 splitContent 拆分剧本内容获取总集数
  6794. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6795. // 解析剧集序号(数组)
  6796. $episodes = [];
  6797. foreach ($episode_numbers as $item) {
  6798. if (is_array($item)) {
  6799. continue;
  6800. }
  6801. $item = trim((string)$item);
  6802. if ($item === '' || !is_numeric($item)) {
  6803. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6804. }
  6805. $episodes[] = (int)$item;
  6806. }
  6807. // 去重并校验序号范围(序号从1开始)
  6808. $episodes = array_values(array_unique($episodes));
  6809. if (empty($episodes)) {
  6810. Utils::throwError('20003:剧集序号不能为空');
  6811. }
  6812. foreach ($episodes as $episode) {
  6813. if ($episode < 1 || $episode > $totalEpisodes) {
  6814. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6815. }
  6816. }
  6817. $now = now();
  6818. // 过滤已存在的关联,避免重复
  6819. $existingEpisodes = DB::table('mp_script_product_mappings')
  6820. ->where('script_id', $script_id)
  6821. ->where('product_id', $product_id)
  6822. ->whereIn('episode_number', $episodes)
  6823. ->pluck('episode_number')
  6824. ->all();
  6825. $mappingRecords = [];
  6826. foreach ($episodes as $episode) {
  6827. if (in_array($episode, $existingEpisodes)) {
  6828. continue;
  6829. }
  6830. $mappingRecords[] = [
  6831. 'script_id' => $script_id,
  6832. 'product_id' => $product_id,
  6833. 'episode_number' => $episode,
  6834. 'created_at' => $now,
  6835. 'updated_at' => $now,
  6836. ];
  6837. }
  6838. $insertedCount = 0;
  6839. if (!empty($mappingRecords)) {
  6840. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6841. }
  6842. return $insertedCount;
  6843. }
  6844. /**
  6845. * 规范化剧集序号参数,统一为数组
  6846. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6847. *
  6848. * @param mixed $episode_number 剧集序号参数
  6849. * @return array
  6850. */
  6851. private function normalizeEpisodeNumbers($episode_number) {
  6852. if (!is_array($episode_number)) {
  6853. $episode_number = explode(',', (string)$episode_number);
  6854. }
  6855. $items = [];
  6856. foreach ($episode_number as $item) {
  6857. if (is_array($item)) {
  6858. continue;
  6859. }
  6860. foreach (explode(',', (string)$item) as $part) {
  6861. $part = trim($part);
  6862. if ($part !== '') {
  6863. $items[] = $part;
  6864. }
  6865. }
  6866. }
  6867. return $items;
  6868. }
  6869. /**
  6870. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6871. *
  6872. * @param object $script 剧本记录
  6873. * @return int 总集数
  6874. */
  6875. private function getScriptTotalEpisodeCount($script) {
  6876. if (empty($script->content)) {
  6877. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6878. }
  6879. $totalEpisodes = count(splitContent($script->content));
  6880. if ($totalEpisodes < 1) {
  6881. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6882. }
  6883. return $totalEpisodes;
  6884. }
  6885. /**
  6886. * 获取剧本总集数
  6887. *
  6888. * @param array $data 包含 script_id(剧本ID)
  6889. * @return array
  6890. */
  6891. public function getScriptTotalEpisodes($data) {
  6892. $script_id = (int)getProp($data, 'script_id', 0);
  6893. if (!$script_id) {
  6894. Utils::throwError('20003:请提供剧本ID');
  6895. }
  6896. // 验证剧本是否存在
  6897. $script = DB::table('mp_scripts')
  6898. ->where('id', $script_id)
  6899. ->where('is_deleted', 0)
  6900. ->first();
  6901. if (!$script) {
  6902. Utils::throwError('20003:剧本不存在');
  6903. }
  6904. return [
  6905. 'script_id' => $script_id,
  6906. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6907. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6908. ];
  6909. }
  6910. /**
  6911. * 获取角色版本历史
  6912. * @param array $data 包含 id(角色ID)
  6913. * @return array 返回版本历史列表
  6914. */
  6915. public function getProductVersions($data) {
  6916. $cpid = Site::getCpid();
  6917. $id = getProp($data, 'id');
  6918. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6919. $role = DB::table('mp_products')
  6920. ->where('id', $id)
  6921. ->where('cpid', $cpid)
  6922. ->where('type', 1)
  6923. ->first();
  6924. if (!$role) Utils::throwError('20003:角色不存在');
  6925. // 获取版本历史
  6926. $versions = json_decode($role->versions, true) ?: [];
  6927. // 添加当前版本作为最新版本
  6928. $currentVersion = [
  6929. 'version' => 0, // 0 表示当前版本
  6930. 'url' => $role->url,
  6931. 'pic_prompt' => $role->pic_prompt,
  6932. 'updated_at' => $role->updated_at,
  6933. 'is_current' => true
  6934. ];
  6935. array_unshift($versions, $currentVersion);
  6936. return $versions;
  6937. }
  6938. /**
  6939. * 恢复到指定版本
  6940. * @param array $data 包含 id(角色ID)、version(版本号)
  6941. * @return bool
  6942. */
  6943. public function restoreProductVersion($data) {
  6944. $uid = Site::getUid();
  6945. $cpid = Site::getCpid();
  6946. $id = getProp($data, 'id');
  6947. $version = getProp($data, 'version');
  6948. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6949. if (!$version) Utils::throwError('20003:版本号不能为空');
  6950. $role = DB::table('mp_products')
  6951. ->where('id', $id)
  6952. ->where('cpid', $cpid)
  6953. ->where('type', 1)
  6954. ->first();
  6955. if (!$role) Utils::throwError('20003:角色不存在');
  6956. // 获取版本历史
  6957. $versions = json_decode($role->versions, true) ?: [];
  6958. // 查找指定版本
  6959. $targetVersion = null;
  6960. foreach ($versions as $v) {
  6961. if ($v['version'] == $version) {
  6962. $targetVersion = $v;
  6963. break;
  6964. }
  6965. }
  6966. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6967. // 先将当前版本保存到历史
  6968. $newVersion = [
  6969. 'version' => count($versions) + 1,
  6970. 'url' => $role->url,
  6971. 'pic_prompt' => $role->pic_prompt,
  6972. 'updated_at' => date('Y-m-d H:i:s'),
  6973. 'updated_by' => $uid
  6974. ];
  6975. array_unshift($versions, $newVersion);
  6976. // 限制版本数量
  6977. if (count($versions) > 10) {
  6978. $versions = array_slice($versions, 0, 10);
  6979. }
  6980. // 恢复到指定版本
  6981. return DB::table('mp_products')
  6982. ->where('id', $id)
  6983. ->where('cpid', $cpid)
  6984. ->update([
  6985. 'url' => $targetVersion['url'],
  6986. 'pic_prompt' => $targetVersion['pic_prompt'],
  6987. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6988. 'updated_at' => date('Y-m-d H:i:s')
  6989. ]);
  6990. }
  6991. public function deleteProduct($data) {
  6992. $uid = Site::getUid();
  6993. $cpid = Site::getCpid();
  6994. $role = Site::getRole();
  6995. $id = getProp($data, 'id');
  6996. if (!$id) Utils::throwError('20003:ID不能为空');
  6997. $ids = explode(',', $id);
  6998. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6999. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  7000. $query_uid = $is_public ? 0 : $uid;
  7001. // 如果是公共库操作,需要admin权限
  7002. if ($is_public && $role !== 'admin') {
  7003. Utils::throwError('20003:只有管理员才能操作公共资产库');
  7004. }
  7005. // 检查是否存在且属于当前用户或公共库
  7006. $role = DB::table('mp_products')
  7007. ->whereIn('id', $ids)
  7008. ->where('cpid', $cpid)
  7009. ->where('user_id', $query_uid)
  7010. ->get();
  7011. if (!$role) Utils::throwError('20003:记录不存在');
  7012. return DB::table('mp_products')
  7013. ->where('cpid', $cpid)
  7014. ->where('user_id', $query_uid)
  7015. ->whereIn('id', $ids)
  7016. ->update([
  7017. 'is_deleted' => 1,
  7018. 'updated_at' => date('Y-m-d H:i:s')
  7019. ]);
  7020. }
  7021. public function generateThreeView($data) {
  7022. $uid = Site::getUid();
  7023. $cpid = Site::getCpid();
  7024. $role = Site::getRole();
  7025. $id = getProp($data, 'id');
  7026. if (!$id) Utils::throwError('20003:ID不能为空');
  7027. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  7028. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  7029. $query_uid = $is_public ? 0 : $uid;
  7030. // 如果是公共库操作,需要admin权限
  7031. if ($is_public && $role !== 'admin') {
  7032. Utils::throwError('20003:只有管理员才能操作公共资产库');
  7033. }
  7034. // 检查是否存在且属于当前用户或公共库
  7035. $product = DB::table('mp_products')
  7036. ->where('id', $id)
  7037. ->where('cpid', $cpid)
  7038. ->where('user_id', $query_uid)
  7039. ->where('type', 1)->first();
  7040. if (!$product) Utils::throwError('20003:资产不存在');
  7041. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。'));
  7042. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  7043. if (!$ref_img_url) {
  7044. // 如果没有传入参考图,使用角色表中的图片
  7045. $ref_img_url = $product->url ?? '';
  7046. if (!$ref_img_url) {
  7047. Utils::throwError('20003:参考图不能为空');
  7048. }
  7049. }
  7050. $pic_prompt = getProp($product, 'pic_prompt');
  7051. if ($pic_prompt) {
  7052. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  7053. }
  7054. // 检查参考图是否是正确的图片格式
  7055. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  7056. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  7057. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  7058. if (!in_array($extension, $allowedExtensions)) {
  7059. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  7060. }
  7061. // 处理图片模型
  7062. $model = getProp($data, 'model');
  7063. if (!$model) {
  7064. // 使用默认模型
  7065. $model = 'gpt-image-2';
  7066. }
  7067. // 验证模型是否在可用模型表中
  7068. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7069. Utils::throwError('20003:该模型已不可用,请更换!');
  7070. }
  7071. $ratio = getProp($data, 'ratio', '16:9');
  7072. $resolution = getProp($data, 'resolution', '2k');
  7073. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  7074. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7075. // 参数验证
  7076. $resolution = strtolower($resolution);
  7077. if (!isset($sizeMap[$resolution])) {
  7078. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7079. }
  7080. if (!isset($sizeMap[$resolution][$ratio])) {
  7081. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7082. }
  7083. // 根据 ratio 和 resolution 确定宽高
  7084. $width = $sizeMap[$resolution][$ratio]['width'];
  7085. $height = $sizeMap[$resolution][$ratio]['height'];
  7086. try {
  7087. // 创建图片生成任务
  7088. $params = [
  7089. 'prompt' => $prompt,
  7090. 'model' => $model,
  7091. 'ref_img_urls' => [$ref_img_url],
  7092. 'width' => $width,
  7093. 'height' => $height
  7094. ];
  7095. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7096. $task_id = $task->id;
  7097. if (!$task_id) {
  7098. Utils::throwError('20003:创建图片生成任务失败');
  7099. }
  7100. // 轮询获取结果
  7101. // 只查询数据库,不调用API,不更新任务表
  7102. $start_time = time();
  7103. $timeout = 1800;
  7104. $img_url = '';
  7105. while (time() - $start_time < $timeout) {
  7106. sleep(5);
  7107. // 只查询数据库中的任务状态,不调用API,不更新任务表
  7108. $task = DB::table('mp_generate_pic_tasks')
  7109. ->where('id', $task_id)
  7110. ->first();
  7111. if (!$task) {
  7112. Utils::throwError('20003:任务不存在');
  7113. }
  7114. if ($task->status === 'success' && $task->result_url) {
  7115. $result_urls = is_string($task->result_url)
  7116. ? json_decode($task->result_url, true)
  7117. : $task->result_url;
  7118. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7119. break;
  7120. } elseif ($task->status === 'failed') {
  7121. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  7122. }
  7123. // 其他状态继续轮询
  7124. }
  7125. if (empty($img_url)) {
  7126. Utils::throwError('20003:三视图生成超时,请稍后重试');
  7127. }
  7128. // 更新 mp_products 表(不是任务表)
  7129. DB::table('mp_products')
  7130. ->where('id', $id)
  7131. ->where('cpid', $cpid)
  7132. ->update([
  7133. 'three_view_image_url' => $img_url,
  7134. 'updated_at' => date('Y-m-d H:i:s')
  7135. ]);
  7136. return ['three_view_image_url' => $img_url];
  7137. } catch (\Exception $e) {
  7138. dLog('anime')->error('生成三视图失败', [
  7139. 'error' => $e->getMessage()
  7140. ]);
  7141. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  7142. Utils::throwError('20003:' . $e->getMessage());
  7143. }
  7144. }
  7145. /**
  7146. * 推送(复制)资产或文件夹到目标位置
  7147. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  7148. * @return array 返回推送结果
  7149. */
  7150. public function pushProductOrFolder($data) {
  7151. $uid = Site::getUid();
  7152. $cpid = Site::getCpid();
  7153. $role = Site::getRole();
  7154. $product_id = getProp($data, 'product_id');
  7155. $target_parent_id = getProp($data, 'target_parent_id', 0);
  7156. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  7157. if (!$product_id) {
  7158. Utils::throwError('20003:请选择要推送的项目');
  7159. }
  7160. // 查询源项目(只通过cpid查询,不限制user_id)
  7161. $sourceItem = DB::table('mp_products')
  7162. ->where('id', $product_id)
  7163. ->where('cpid', $cpid)
  7164. ->where('is_deleted', 0)
  7165. ->first();
  7166. if (!$sourceItem) {
  7167. Utils::throwError('20003:要推送的项目不存在');
  7168. }
  7169. // 通过user_id判断源是公共库还是个人库
  7170. $source_uid = $sourceItem->user_id;
  7171. $source_is_public = ($source_uid == 0) ? 1 : 0;
  7172. // 验证目标文件夹并确定目标是公共库还是个人库
  7173. $target_level = 0;
  7174. $target_uid = $uid; // 默认推送到个人库
  7175. $target_is_public = 0;
  7176. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  7177. if ($target_parent_id > 0) {
  7178. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  7179. $targetParent = DB::table('mp_products')
  7180. ->where('id', $target_parent_id)
  7181. ->where('cpid', $cpid)
  7182. ->where('type', 2)
  7183. ->where('is_deleted', 0)
  7184. ->first();
  7185. if (!$targetParent) {
  7186. Utils::throwError('20003:目标文件夹不存在');
  7187. }
  7188. // 通过user_id判断目标是公共库还是个人库
  7189. $target_level = $targetParent->level;
  7190. $target_uid = $targetParent->user_id;
  7191. $target_is_public = ($target_uid == 0) ? 1 : 0;
  7192. // 使用目标文件夹的 product 类型
  7193. $final_product_type = $targetParent->product;
  7194. }
  7195. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  7196. else {
  7197. $push_to_public = getProp($data, 'push_to_public');
  7198. if ($push_to_public === '') {
  7199. Utils::throwError('20003:请选择是否推送到公共库');
  7200. }
  7201. if ($push_to_public) {
  7202. $target_uid = 0;
  7203. $target_is_public = 1;
  7204. }
  7205. // 推送到根目录时,必须指定 product 类型
  7206. if ($target_product === null || $target_product === '') {
  7207. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  7208. }
  7209. $final_product_type = $target_product;
  7210. }
  7211. // 如果目标是公共库,需要admin权限
  7212. if ($target_is_public && $role !== 'admin') {
  7213. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  7214. }
  7215. // 权限验证:验证是否符合允许的推送规则
  7216. $this->validatePushPermission($source_uid, $target_uid, $uid);
  7217. try {
  7218. DB::beginTransaction();
  7219. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  7220. if ($sourceItem->type == 1) {
  7221. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  7222. DB::commit();
  7223. return [
  7224. 'product_id' => $newId,
  7225. ];
  7226. }
  7227. // 如果是文件夹,递归复制(支持跨类型推送)
  7228. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  7229. DB::commit();
  7230. return [
  7231. 'product_id' => $newFolderId,
  7232. ];
  7233. } catch (\Exception $e) {
  7234. DB::rollBack();
  7235. dLog('anime')->error('推送失败', [
  7236. 'error' => $e->getMessage(),
  7237. 'product_id' => $product_id
  7238. ]);
  7239. Utils::throwError('20003:' . $e->getMessage());
  7240. }
  7241. }
  7242. /**
  7243. * 验证推送权限
  7244. * 允许的推送规则:
  7245. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7246. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  7247. * 3. 公共库推送给公共库(公共库 → 公共库)
  7248. *
  7249. * @param int $source_uid 源的user_id
  7250. * @param int $target_uid 目标的user_id
  7251. * @param int $current_uid 当前用户ID
  7252. * @throws \Exception
  7253. */
  7254. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  7255. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7256. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  7257. return; // 允许
  7258. }
  7259. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  7260. if ($source_uid == 0 && $target_uid == $current_uid) {
  7261. return; // 允许
  7262. }
  7263. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7264. if ($source_uid == 0 && $target_uid == 0) {
  7265. return; // 允许
  7266. }
  7267. // 其他情况都不允许
  7268. if ($source_uid != 0 && $source_uid != $current_uid) {
  7269. // 源是别人的个人库
  7270. Utils::throwError('20003:无权限访问该资产');
  7271. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7272. // 个人库推送给公共库(不允许)
  7273. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7274. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7275. // 不同用户的个人库之间推送(不允许)
  7276. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7277. } else {
  7278. // 其他未知情况
  7279. Utils::throwError('20003:不允许的推送操作');
  7280. }
  7281. }
  7282. /**
  7283. * 复制单个资产
  7284. * @param object $sourceProduct 源资产对象
  7285. * @param int $targetParentId 目标父文件夹ID
  7286. * @param int $targetLevel 目标层级
  7287. * @param int $cpid 公司ID
  7288. * @param int $targetUid 目标用户ID
  7289. * @return int 返回新资产ID
  7290. */
  7291. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7292. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7293. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7294. $newProductData = [
  7295. 'user_id' => $targetUid,
  7296. 'cpid' => $cpid,
  7297. 'type' => 1,
  7298. 'parent_id' => $targetParentId,
  7299. 'level' => $targetLevel,
  7300. 'product_name' => $sourceProduct->product_name,
  7301. 'url' => $sourceProduct->url,
  7302. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7303. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7304. 'timbre_url' => $sourceProduct->timbre_url ?? '',
  7305. 'product' => $finalProductType,
  7306. 'versions' => $sourceProduct->versions ?? '',
  7307. 'sort_order' => time(),
  7308. 'is_deleted' => 0,
  7309. 'created_at' => date('Y-m-d H:i:s'),
  7310. 'updated_at' => date('Y-m-d H:i:s')
  7311. ];
  7312. return DB::table('mp_products')->insertGetId($newProductData);
  7313. }
  7314. /**
  7315. * 递归复制文件夹及其子项
  7316. * @param object $sourceFolder 源文件夹对象
  7317. * @param int $targetParentId 目标父文件夹ID
  7318. * @param int $targetLevel 目标层级
  7319. * @param int $cpid 公司ID
  7320. * @param int $targetUid 目标用户ID
  7321. * @param int $sourceUid 源用户ID
  7322. * @return int 返回新文件夹ID
  7323. */
  7324. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7325. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7326. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7327. // 创建新文件夹
  7328. $newFolderData = [
  7329. 'user_id' => $targetUid,
  7330. 'cpid' => $cpid,
  7331. 'type' => 2,
  7332. 'parent_id' => $targetParentId,
  7333. 'level' => $targetLevel,
  7334. 'product_name' => $sourceFolder->product_name,
  7335. 'product' => $finalProductType,
  7336. 'sort_order' => time(),
  7337. 'is_deleted' => 0,
  7338. 'created_at' => date('Y-m-d H:i:s'),
  7339. 'updated_at' => date('Y-m-d H:i:s')
  7340. ];
  7341. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7342. // 获取源文件夹下的所有子项
  7343. $children = DB::table('mp_products')
  7344. ->where('parent_id', $sourceFolder->id)
  7345. ->where('cpid', $cpid)
  7346. ->where('user_id', $sourceUid)
  7347. ->where('is_deleted', 0)
  7348. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7349. ->get();
  7350. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7351. foreach ($children as $child) {
  7352. if ($child->type == 1) {
  7353. // 资产
  7354. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7355. } else {
  7356. // 文件夹
  7357. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7358. }
  7359. }
  7360. return $newFolderId;
  7361. }
  7362. /**
  7363. * 转让剧本归属(剧本及其关联资产)
  7364. *
  7365. * 仅调整 mp_scripts.user_id 与 mp_products.user_id,其他表保持不变。
  7366. * 权限:仅 admin / superadmin 可操作;目标用户必须是同组(cpid 相同)且角色为 user(组员)的用户,禁止跨组转让。
  7367. * 多个剧本逐个独立事务处理,单个剧本失败不影响其他剧本;
  7368. * 单个剧本内的剧本记录与关联资产必须全部更新成功,否则整体回滚。
  7369. *
  7370. * @param array $data 请求参数:script_ids(数组或英文逗号分隔,兼容单个 script_id)、target_user_id
  7371. * @return array
  7372. */
  7373. public function transferScriptOwner($data) {
  7374. $operatorRole = Site::getRole();
  7375. $operatorCpid = Site::getCpid();
  7376. // 1.权限校验:仅管理员和超管可操作
  7377. if (!in_array($operatorRole, ['admin', 'superadmin'], true)) {
  7378. Utils::throwError(ErrorConst::NOT_ACCESS);
  7379. }
  7380. // 2.目标用户校验:必须存在且角色为 user(组员)
  7381. $targetUserId = (int)getProp($data, 'target_user_id', 0);
  7382. if ($targetUserId < 1) {
  7383. Utils::throwError('1002:请选择转让的目标用户');
  7384. }
  7385. $targetUser = DB::table('mp_manage_users')
  7386. ->where('id', $targetUserId)
  7387. ->where('is_deleted', 0)
  7388. ->first();
  7389. if (!$targetUser) {
  7390. Utils::throwError('20003:目标用户不存在');
  7391. }
  7392. if ((string)getProp($targetUser, 'role') !== 'user') {
  7393. Utils::throwError('20003:只能转让给角色为组员(user)的用户');
  7394. }
  7395. $targetCpid = (int)getProp($targetUser, 'cpid');
  7396. // 3.规范化剧本ID列表(兼容数组、逗号分隔字符串、script_id 单值)
  7397. $rawScriptIds = getProp($data, 'script_ids');
  7398. if (empty($rawScriptIds)) {
  7399. $rawScriptIds = getProp($data, 'script_id');
  7400. }
  7401. $scriptIds = $this->normalizeIdList($rawScriptIds);
  7402. if (empty($scriptIds)) {
  7403. Utils::throwError('20003:请提供剧本ID');
  7404. }
  7405. // 预取剧本名称,便于失败结果中回显
  7406. $scriptNameMap = DB::table('mp_scripts')
  7407. ->whereIn('id', $scriptIds)
  7408. ->pluck('script_name', 'id')
  7409. ->all();
  7410. $successList = [];
  7411. $failedList = [];
  7412. // 4.逐个剧本独立事务处理,单个失败不影响其他剧本
  7413. foreach ($scriptIds as $scriptId) {
  7414. DB::beginTransaction();
  7415. try {
  7416. $successList[] = $this->transferSingleScriptOwner(
  7417. $scriptId,
  7418. $targetUserId,
  7419. $targetCpid,
  7420. $operatorRole,
  7421. $operatorCpid,
  7422. Site::getUid()
  7423. );
  7424. DB::commit();
  7425. } catch (\Throwable $e) {
  7426. DB::rollBack();
  7427. $failedList[] = [
  7428. 'script_id' => (int)$scriptId,
  7429. 'script_name' => (string)($scriptNameMap[$scriptId] ?? ''),
  7430. 'reason' => $e->getMessage() !== '' ? $e->getMessage() : '转让失败',
  7431. ];
  7432. dLog('anime')->error('剧本归属转让失败', [
  7433. 'script_id' => $scriptId,
  7434. 'target_user_id' => $targetUserId,
  7435. 'operator_uid' => Site::getUid(),
  7436. 'error' => $e->getMessage(),
  7437. ]);
  7438. }
  7439. }
  7440. return [
  7441. 'target_user_id' => $targetUserId,
  7442. 'success_count' => count($successList),
  7443. 'failed_count' => count($failedList),
  7444. 'success_list' => $successList,
  7445. 'failed_list' => $failedList,
  7446. ];
  7447. }
  7448. /**
  7449. * 单个剧本的归属转让(需在事务中调用)
  7450. *
  7451. * @param int $scriptId 剧本ID
  7452. * @param int $targetUserId 目标用户ID
  7453. * @param int $targetCpid 目标用户所属公司ID
  7454. * @param string $operatorRole 操作人角色
  7455. * @param int $operatorCpid 操作人所属公司ID
  7456. * @param int $operatorUid 操作人用户ID
  7457. * @return array
  7458. */
  7459. private function transferSingleScriptOwner($scriptId, $targetUserId, $targetCpid, $operatorRole, $operatorCpid, $operatorUid) {
  7460. $script = DB::table('mp_scripts')
  7461. ->where('id', $scriptId)
  7462. ->where('is_deleted', 0)
  7463. ->first();
  7464. if (!$script) {
  7465. Utils::throwError('20003:剧本不存在');
  7466. }
  7467. $scriptCpid = (int)getProp($script, 'cpid');
  7468. $fromUserId = (int)getProp($script, 'user_id');
  7469. // 管理员仅可操作本组剧本
  7470. if ($operatorRole !== 'superadmin' && $scriptCpid !== $operatorCpid) {
  7471. Utils::throwError(ErrorConst::NOT_ACCESS);
  7472. }
  7473. // 管理员仅可转让自己创建的剧本(超管不做此验证)
  7474. if ($operatorRole !== 'superadmin' && $fromUserId !== (int)$operatorUid) {
  7475. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7476. }
  7477. // 禁止跨组转让:目标用户必须与剧本同组
  7478. if ($targetCpid !== $scriptCpid) {
  7479. Utils::throwError('20003:不能跨组转让,目标用户与剧本不在同一组');
  7480. }
  7481. // 关联资产ID(同一资产可能关联多个剧集序号,需去重)
  7482. $productIds = $this->normalizeIdList(
  7483. DB::table('mp_script_product_mappings')
  7484. ->where('script_id', $scriptId)
  7485. ->pluck('product_id')
  7486. ->all()
  7487. );
  7488. $folderIds = [];
  7489. if (!empty($productIds)) {
  7490. $products = DB::table('mp_products')
  7491. ->whereIn('id', $productIds)
  7492. ->select('id', 'cpid', 'parent_id', 'user_id')
  7493. ->get();
  7494. // 关联资产必须全部存在,否则视为数据异常,不提交
  7495. if ($products->count() !== count($productIds)) {
  7496. Utils::throwError('20003:剧本存在已丢失的关联资产,无法完成转让');
  7497. }
  7498. foreach ($products as $product) {
  7499. // 关联资产必须与剧本同组,避免误转让跨组资产
  7500. if ((int)getProp($product, 'cpid') !== $scriptCpid) {
  7501. Utils::throwError('20003:剧本存在跨组关联资产,无法完成转让');
  7502. }
  7503. $parentId = (int)getProp($product, 'parent_id', 0);
  7504. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7505. $folderIds[] = $parentId;
  7506. }
  7507. }
  7508. // 仅转让归属于原剧本所有者的资产
  7509. $folderIds = DB::table('mp_products')
  7510. ->whereIn('id', $folderIds)
  7511. ->where('type', 2)
  7512. ->where('cpid', $scriptCpid)
  7513. ->where('user_id', $fromUserId)
  7514. ->pluck('id')
  7515. ->map('intval')
  7516. ->all();
  7517. // 管理员仅可转让自己创建的资产及其所属文件夹(超管不做此验证)
  7518. if ($operatorRole !== 'superadmin') {
  7519. foreach ($products as $product) {
  7520. if ((int)getProp($product, 'user_id') !== (int)$operatorUid) {
  7521. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7522. }
  7523. }
  7524. foreach ($products as $product) {
  7525. $parentId = (int)getProp($product, 'parent_id', 0);
  7526. if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
  7527. Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
  7528. }
  7529. }
  7530. }
  7531. }
  7532. $now = now();
  7533. // 5.更新剧本归属
  7534. DB::table('mp_scripts')
  7535. ->where('id', $scriptId)
  7536. ->update([
  7537. 'user_id' => $targetUserId,
  7538. 'updated_at' => $now,
  7539. ]);
  7540. // 6.更新关联资产归属
  7541. if (!empty($productIds)) {
  7542. DB::table('mp_products')
  7543. ->whereIn('id', $productIds)
  7544. ->update([
  7545. 'user_id' => $targetUserId,
  7546. 'updated_at' => $now,
  7547. ]);
  7548. }
  7549. // 7.更新资产所属的类型根文件夹归属(文件夹属于 mp_products,随资产一并转让)
  7550. if (!empty($folderIds)) {
  7551. DB::table('mp_products')
  7552. ->whereIn('id', $folderIds)
  7553. ->update([
  7554. 'user_id' => $targetUserId,
  7555. 'updated_at' => $now,
  7556. ]);
  7557. }
  7558. // 8.校验剧本与资产是否全部更新成功,任一未成功则回滚
  7559. $scriptOwner = (int)DB::table('mp_scripts')->where('id', $scriptId)->value('user_id');
  7560. if ($scriptOwner !== $targetUserId) {
  7561. Utils::throwError('20003:剧本归属更新失败');
  7562. }
  7563. if (!empty($productIds)) {
  7564. $updatedProductCount = DB::table('mp_products')
  7565. ->whereIn('id', $productIds)
  7566. ->where('user_id', $targetUserId)
  7567. ->count();
  7568. if ($updatedProductCount !== count($productIds)) {
  7569. Utils::throwError('20003:部分剧本资产转让失败,已回滚');
  7570. }
  7571. }
  7572. if (!empty($folderIds)) {
  7573. $updatedFolderCount = DB::table('mp_products')
  7574. ->whereIn('id', $folderIds)
  7575. ->where('user_id', $targetUserId)
  7576. ->count();
  7577. if ($updatedFolderCount !== count($folderIds)) {
  7578. Utils::throwError('20003:部分资产文件夹转让失败,已回滚');
  7579. }
  7580. }
  7581. return [
  7582. 'script_id' => (int)$scriptId,
  7583. 'script_name' => (string)getProp($script, 'script_name', ''),
  7584. 'from_user_id' => $fromUserId,
  7585. 'to_user_id' => $targetUserId,
  7586. 'product_count' => count($productIds),
  7587. 'folder_count' => count($folderIds),
  7588. ];
  7589. }
  7590. /**
  7591. * 规范化ID列表,兼容数组、逗号分隔字符串以及字符串数组
  7592. *
  7593. * @param mixed $ids 待处理的ID集合
  7594. * @return array 去重后的正整数ID数组
  7595. */
  7596. private function normalizeIdList($ids) {
  7597. if (!is_array($ids)) {
  7598. $ids = explode(',', (string)$ids);
  7599. }
  7600. $result = [];
  7601. foreach ($ids as $item) {
  7602. if (is_array($item)) {
  7603. continue;
  7604. }
  7605. foreach (explode(',', (string)$item) as $part) {
  7606. $part = trim($part);
  7607. if ($part !== '' && is_numeric($part) && (int)$part > 0) {
  7608. $result[] = (int)$part;
  7609. }
  7610. }
  7611. }
  7612. return array_values(array_unique($result));
  7613. }
  7614. /**
  7615. * 通过 Excel 批量导入剧本资产(独立实现,不依赖 saveScriptProducts)
  7616. *
  7617. * 流程:
  7618. * 1. 校验剧本存在且属于当前用户
  7619. * 2. 解析 Excel 并校验强制列与数据完整性(资产类型/资产名称/使用范围/参考提示词)
  7620. * 3. 名称去重(与 Excel 内及该剧本已有关联资产比对)
  7621. * 4. 事务内创建类型文件夹、资产与剧本映射
  7622. * 5. 为没有图片的资产创建图片生成任务,生成中返回 SSE 轮询
  7623. *
  7624. * @param array $data 请求参数
  7625. * @param \Illuminate\Http\UploadedFile $file 上传的 Excel 文件
  7626. * @return array|\Generator
  7627. */
  7628. public function importScriptProductsByExcel($data, $file) {
  7629. $uid = Site::getUid();
  7630. $cpid = Site::getCpid();
  7631. $script_id = (int)getProp($data, 'script_id', 0);
  7632. if (!$script_id) {
  7633. Utils::throwError('20003:请提供剧本ID');
  7634. }
  7635. // 验证剧本是否存在,且只能导入自己创建的剧本
  7636. $script = DB::table('mp_scripts')
  7637. ->where('id', $script_id)
  7638. ->where('is_deleted', 0)
  7639. ->where('user_id', $uid)
  7640. ->first();
  7641. if (!$script) {
  7642. Utils::throwError('20003:剧本不存在或无权限操作');
  7643. }
  7644. $script_name = $script->script_name ?? 'script_' . $script_id;
  7645. // 校验上传文件
  7646. if (!$file) {
  7647. Utils::throwError('20003:请上传Excel文件');
  7648. }
  7649. $extension = strtolower($file->getClientOriginalExtension());
  7650. if (!in_array($extension, ['xlsx', 'xls'])) {
  7651. Utils::throwError('20003:文件格式错误,仅支持 xlsx、xls 格式');
  7652. }
  7653. if ($file->getSize() > 10 * 1024 * 1024) {
  7654. Utils::throwError('20003:文件大小不能超过10M');
  7655. }
  7656. // 解析 Excel(第一行为表头)
  7657. $rows = $this->readImportExcelRows($file);
  7658. if (empty($rows)) {
  7659. Utils::throwError('20003:Excel内容为空');
  7660. }
  7661. $headers = array_shift($rows);
  7662. // 定位强制列
  7663. $typeColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产类型'], ['资产类型', '类型']);
  7664. $nameColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产名称'], ['资产名称', '名称']);
  7665. $rangeColumnIndex = $this->findImportExcelColumnIndex($headers, ['使用范围'], ['使用范围', '范围']);
  7666. $promptColumnIndex = $this->findImportExcelColumnIndex($headers, ['参考提示词', '提示词'], ['提示词']);
  7667. $missingColumns = [];
  7668. if ($typeColumnIndex < 0) {
  7669. $missingColumns[] = '资产类型';
  7670. }
  7671. if ($nameColumnIndex < 0) {
  7672. $missingColumns[] = '资产名称';
  7673. }
  7674. if ($rangeColumnIndex < 0) {
  7675. $missingColumns[] = '使用范围';
  7676. }
  7677. if ($promptColumnIndex < 0) {
  7678. $missingColumns[] = '参考提示词';
  7679. }
  7680. if (!empty($missingColumns)) {
  7681. Utils::throwError('20003:Excel缺少必填列:' . implode('、', $missingColumns));
  7682. }
  7683. // 先整体校验 Excel 数据,所有异常行一次性返回
  7684. $validation = $this->validateImportExcelRows(
  7685. $rows,
  7686. $typeColumnIndex,
  7687. $nameColumnIndex,
  7688. $rangeColumnIndex,
  7689. $promptColumnIndex
  7690. );
  7691. $errors = $validation['errors'];
  7692. $checkedRows = $validation['checked_rows'];
  7693. if (empty($checkedRows)) {
  7694. $errors[] = 'Excel中没有有效的数据行';
  7695. }
  7696. if (!empty($errors)) {
  7697. Utils::throwError('20003:Excel数据校验失败:' . implode(';', $errors));
  7698. }
  7699. // 名称去重:Excel 内部 + 该剧本已关联资产(按 createProduct 的名称判断逻辑)
  7700. $existingNames = $this->getScriptProductNames($script_id, $cpid);
  7701. $dedupResult = $this->deduplicateImportRows($checkedRows, $existingNames);
  7702. $validRows = $dedupResult['valid_rows'];
  7703. $skipped = $dedupResult['skipped'];
  7704. // 图片生成参数(与 saveScriptProducts 保持一致的校验规则)
  7705. $model = getProp($data, 'model');
  7706. if (!$model) {
  7707. $model = 'gpt-image-2';
  7708. }
  7709. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7710. Utils::throwError('20003:该模型已不可用,请更换!');
  7711. }
  7712. $ratio = getProp($data, 'ratio', '9:16');
  7713. $resolution = strtolower(getProp($data, 'resolution', '2k'));
  7714. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  7715. if (!isset($sizeMap[$resolution])) {
  7716. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7717. }
  7718. if (!isset($sizeMap[$resolution][$ratio])) {
  7719. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7720. }
  7721. $width = $sizeMap[$resolution][$ratio]['width'];
  7722. $height = $sizeMap[$resolution][$ratio]['height'];
  7723. $autoRaw = getProp($data, 'auto_generate_images', true);
  7724. $auto_generate_images = !in_array($autoRaw, [false, 0, '0', 'false', 'False'], true);
  7725. // 创建/复用任务中心记录(md5 验重,避免重复任务)
  7726. $taskCenterId = $this->createScriptProductTaskCenter(
  7727. $uid,
  7728. $cpid,
  7729. $script_id,
  7730. $validRows,
  7731. $model,
  7732. $ratio,
  7733. $resolution,
  7734. $auto_generate_images
  7735. );
  7736. // 全部为重复项:参照 saveScriptProducts,检查已存在资产的图片状态,缺图的补建任务
  7737. if (empty($validRows)) {
  7738. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7739. $script_id,
  7740. $model,
  7741. $width,
  7742. $height,
  7743. $auto_generate_images
  7744. );
  7745. $productTaskMap = $existingTaskInfo['product_task_map'];
  7746. $typeFolderIds = $existingTaskInfo['type_folder_ids'];
  7747. if (!empty($productTaskMap)) {
  7748. $message = 'Excel中的资产均已存在,正在为缺少图片的资产生成图片';
  7749. } elseif (!$existingTaskInfo['has_all_tasks']) {
  7750. $message = 'Excel中的资产均已存在,部分资产没有参考提示词,无法生成图片';
  7751. } else {
  7752. $message = 'Excel中的资产均已存在,且图片已全部生成完成';
  7753. }
  7754. $resultData = [
  7755. 'success' => true,
  7756. 'message' => $message,
  7757. 'script_id' => $script_id,
  7758. 'script_name' => $script_name,
  7759. 'imported_count' => 0,
  7760. 'existing_products' => $existingTaskInfo['product_count'],
  7761. 'skipped_count' => count($skipped),
  7762. 'skipped' => $skipped,
  7763. 'created_products' => [],
  7764. 'type_folder_ids' => $typeFolderIds,
  7765. 'pending_tasks_count' => count($productTaskMap),
  7766. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7767. 'task_center_id' => $taskCenterId,
  7768. ];
  7769. // 有需要轮询的任务(已有任务或本次补建):走 SSE 轮询
  7770. if (!empty($productTaskMap)) {
  7771. return $this->pollProductImageTasks(
  7772. $script_id,
  7773. $script_name,
  7774. $productTaskMap,
  7775. $typeFolderIds,
  7776. $taskCenterId,
  7777. ['import_result' => $resultData],
  7778. ['import_result' => $resultData]
  7779. );
  7780. }
  7781. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7782. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7783. }
  7784. // 事务内创建资产、类型文件夹与剧本映射
  7785. $typeFolderIds = [];
  7786. $createdProducts = [];
  7787. $mappingRecords = [];
  7788. $now = now();
  7789. DB::beginTransaction();
  7790. try {
  7791. foreach ($validRows as $row) {
  7792. $type = $row['type'];
  7793. if (!isset($typeFolderIds[$type])) {
  7794. // 与 createProduct 一致:先查找该剧本已存在的类型文件夹,没有则创建
  7795. $folder = DB::table('mp_products')
  7796. ->where('cpid', $cpid)
  7797. ->where('type', 2)
  7798. ->where('product', $type)
  7799. ->where('product_name', $script_name)
  7800. ->where('parent_id', 0)
  7801. ->where('is_deleted', 0)
  7802. ->first();
  7803. if ($folder) {
  7804. $typeFolderIds[$type] = $folder->id;
  7805. } else {
  7806. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7807. 'user_id' => $uid,
  7808. 'cpid' => $cpid,
  7809. 'type' => 2, // 文件夹
  7810. 'product' => $type, // 1=角色 2=场景 3=道具
  7811. 'parent_id' => 0,
  7812. 'level' => 1,
  7813. 'product_name' => $script_name,
  7814. 'sort_order' => time() + $type,
  7815. 'is_deleted' => 0,
  7816. 'created_at' => $now,
  7817. 'updated_at' => $now,
  7818. ]);
  7819. }
  7820. }
  7821. $folder_id = $typeFolderIds[$type];
  7822. $product_id = DB::table('mp_products')->insertGetId([
  7823. 'user_id' => $uid,
  7824. 'cpid' => $cpid,
  7825. 'type' => 1, // 资产
  7826. 'product' => $type,
  7827. 'parent_id' => $folder_id,
  7828. 'level' => 2,
  7829. 'product_name' => $row['product_name'],
  7830. 'pic_prompt' => $row['pic_prompt'],
  7831. 'sort_order' => time(),
  7832. 'is_deleted' => 0,
  7833. 'created_at' => $now,
  7834. 'updated_at' => $now,
  7835. ]);
  7836. $createdProducts[] = [
  7837. 'id' => $product_id,
  7838. 'type' => $type,
  7839. 'product_name' => $row['product_name'],
  7840. 'pic_prompt' => $row['pic_prompt'],
  7841. ];
  7842. // 为每个使用范围(集数)创建映射记录
  7843. foreach ($row['episode_numbers'] as $episodeNumber) {
  7844. $mappingRecords[] = [
  7845. 'script_id' => $script_id,
  7846. 'product_id' => $product_id,
  7847. 'episode_number' => $episodeNumber,
  7848. 'created_at' => $now,
  7849. 'updated_at' => $now,
  7850. ];
  7851. }
  7852. }
  7853. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7854. DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7855. // 剧本已有资产,同步更新is_products标记
  7856. DB::table('mp_scripts')->where('id', $script_id)->update([
  7857. 'is_products' => 1,
  7858. 'updated_at' => $now,
  7859. ]);
  7860. DB::commit();
  7861. } catch (\Exception $e) {
  7862. DB::rollback();
  7863. if ($taskCenterId) {
  7864. $this->taskCenterService->updateTask($taskCenterId, [
  7865. 'status' => MpTaskCenter::STATUS_FAILED,
  7866. 'error_message' => $e->getMessage(),
  7867. ]);
  7868. }
  7869. dLog('anime')->error('Excel导入剧本资产失败: ' . $e->getMessage(), [
  7870. 'script_id' => $script_id,
  7871. 'error' => $e->getMessage(),
  7872. 'trace' => $e->getTraceAsString(),
  7873. ]);
  7874. Utils::throwError('20003:Excel导入剧本资产失败:' . $e->getMessage());
  7875. }
  7876. // 参照 saveScriptProducts:为新建资产以及已存在但缺图的资产统一补建图片生成任务
  7877. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  7878. $script_id,
  7879. $model,
  7880. $width,
  7881. $height,
  7882. $auto_generate_images
  7883. );
  7884. $productTaskMap = $existingTaskInfo['product_task_map'];
  7885. $resultData = [
  7886. 'success' => true,
  7887. 'message' => '导入完成',
  7888. 'script_id' => $script_id,
  7889. 'script_name' => $script_name,
  7890. 'imported_count' => count($createdProducts),
  7891. 'skipped_count' => count($skipped),
  7892. 'skipped' => $skipped,
  7893. 'created_products' => array_map(function ($item) {
  7894. return [
  7895. 'id' => $item['id'],
  7896. 'type' => $item['type'],
  7897. 'product_name' => $item['product_name'],
  7898. ];
  7899. }, $createdProducts),
  7900. 'type_folder_ids' => $typeFolderIds,
  7901. 'pending_tasks_count' => count($productTaskMap),
  7902. 'image_tasks_created' => $existingTaskInfo['created_count'],
  7903. 'task_center_id' => $taskCenterId,
  7904. ];
  7905. // 有待生成的图片任务:返回 SSE 轮询结果(导入统计在 init 与 complete 事件中)
  7906. if (!empty($productTaskMap)) {
  7907. return $this->pollProductImageTasks(
  7908. $script_id,
  7909. $script_name,
  7910. $productTaskMap,
  7911. $typeFolderIds,
  7912. $taskCenterId,
  7913. ['import_result' => $resultData],
  7914. ['import_result' => $resultData]
  7915. );
  7916. }
  7917. // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
  7918. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  7919. }
  7920. /**
  7921. * 校验 Excel 数据行(先校验完毕,再进行后续逻辑)
  7922. *
  7923. * @param array $rows
  7924. * @param int $typeColumnIndex
  7925. * @param int $nameColumnIndex
  7926. * @param int $rangeColumnIndex
  7927. * @param int $promptColumnIndex
  7928. * @return array ['errors' => [], 'checked_rows' => []]
  7929. */
  7930. private function validateImportExcelRows(array $rows, $typeColumnIndex, $nameColumnIndex, $rangeColumnIndex, $promptColumnIndex) {
  7931. $errors = [];
  7932. $checkedRows = [];
  7933. foreach ($rows as $rowIndex => $row) {
  7934. // 数据从第2行开始(表头占第1行)
  7935. $excelRowNo = $rowIndex + 2;
  7936. if (!is_array($row) || $this->isImportExcelRowEmpty($row)) {
  7937. continue;
  7938. }
  7939. $typeRaw = trim((string)($row[$typeColumnIndex] ?? ''));
  7940. $nameRaw = trim((string)($row[$nameColumnIndex] ?? ''));
  7941. $rangeRaw = trim((string)($row[$rangeColumnIndex] ?? ''));
  7942. $promptRaw = trim((string)($row[$promptColumnIndex] ?? ''));
  7943. $missingFields = [];
  7944. if ($typeRaw === '') {
  7945. $missingFields[] = '资产类型';
  7946. }
  7947. if ($nameRaw === '') {
  7948. $missingFields[] = '资产名称';
  7949. }
  7950. if ($rangeRaw === '') {
  7951. $missingFields[] = '使用范围';
  7952. }
  7953. if ($promptRaw === '') {
  7954. $missingFields[] = '参考提示词';
  7955. }
  7956. if (!empty($missingFields)) {
  7957. $errors[] = "第{$excelRowNo}行:" . implode('、', $missingFields) . '不能为空';
  7958. continue;
  7959. }
  7960. // 资产类型校验
  7961. $productType = $this->resolveImportProductType($typeRaw);
  7962. if (!$productType) {
  7963. $errors[] = "第{$excelRowNo}行:资产类型「{$typeRaw}」不正确,仅支持 角色/场景/道具";
  7964. continue;
  7965. }
  7966. // 资产名称去除两边特殊符号
  7967. $productName = $this->normalizeImportProductName($nameRaw);
  7968. if ($productName === '') {
  7969. $errors[] = "第{$excelRowNo}行:资产名称「{$nameRaw}」去除特殊符号后为空";
  7970. continue;
  7971. }
  7972. if (mb_strlen($productName, 'UTF-8') > 64) {
  7973. $errors[] = "第{$excelRowNo}行:资产名称「{$productName}」超过64个字符";
  7974. continue;
  7975. }
  7976. // 解析使用范围(逗号分隔的集数)
  7977. $episodeNumbers = $this->parseImportEpisodeNumbers($rangeRaw);
  7978. if (empty($episodeNumbers)) {
  7979. $errors[] = "第{$excelRowNo}行:使用范围「{$rangeRaw}」格式错误,仅支持数字或逗号分隔的数字";
  7980. continue;
  7981. }
  7982. $checkedRows[] = [
  7983. 'row' => $excelRowNo,
  7984. 'type' => $productType,
  7985. 'product_name' => $productName,
  7986. 'episode_numbers' => $episodeNumbers,
  7987. 'pic_prompt' => $promptRaw,
  7988. ];
  7989. }
  7990. return [
  7991. 'errors' => $errors,
  7992. 'checked_rows' => $checkedRows,
  7993. ];
  7994. }
  7995. /**
  7996. * Excel 资产名称去重:Excel 内部 + 剧本已有关联资产
  7997. *
  7998. * @param array $checkedRows
  7999. * @param array $existingNames 剧本已有关联资产名称集合(name => true)
  8000. * @return array ['valid_rows' => [], 'skipped' => []]
  8001. */
  8002. private function deduplicateImportRows(array $checkedRows, array $existingNames) {
  8003. $seenNames = [];
  8004. $validRows = [];
  8005. $skipped = [];
  8006. foreach ($checkedRows as $row) {
  8007. $nameKey = $row['product_name'];
  8008. $typeText = $this->getImportProductTypeText($row['type']);
  8009. if (isset($seenNames[$nameKey])) {
  8010. $skipped[] = [
  8011. 'row' => $row['row'],
  8012. 'type' => $typeText,
  8013. 'product_name' => $row['product_name'],
  8014. 'reason' => 'Excel中资产名称重复',
  8015. ];
  8016. continue;
  8017. }
  8018. if (isset($existingNames[$nameKey])) {
  8019. $skipped[] = [
  8020. 'row' => $row['row'],
  8021. 'type' => $typeText,
  8022. 'product_name' => $row['product_name'],
  8023. 'reason' => '剧本中已存在同名资产',
  8024. ];
  8025. continue;
  8026. }
  8027. $seenNames[$nameKey] = true;
  8028. $validRows[] = $row;
  8029. }
  8030. return [
  8031. 'valid_rows' => $validRows,
  8032. 'skipped' => $skipped,
  8033. ];
  8034. }
  8035. /**
  8036. * 读取 Excel 文件为二维数组(第一行为表头)
  8037. *
  8038. * @param \Illuminate\Http\UploadedFile $file
  8039. * @return array
  8040. */
  8041. private function readImportExcelRows($file) {
  8042. try {
  8043. $reader = IOFactory::createReaderForFile($file->getRealPath());
  8044. $reader->setReadDataOnly(true);
  8045. $spreadsheet = $reader->load($file->getRealPath());
  8046. $sheet = $spreadsheet->getSheet(0);
  8047. $rows = $sheet->toArray(null, true, true, false);
  8048. $spreadsheet->disconnectWorksheets();
  8049. unset($spreadsheet);
  8050. return $rows;
  8051. } catch (\Exception $e) {
  8052. dLog('anime')->error('Excel文件解析失败', [
  8053. 'error' => $e->getMessage(),
  8054. ]);
  8055. Utils::throwError('20003:Excel文件解析失败,请确认文件格式正确');
  8056. }
  8057. }
  8058. /**
  8059. * 查找 Excel 表头列索引(先精确匹配,再模糊匹配)
  8060. *
  8061. * @param array $headers
  8062. * @param array $exactKeywords
  8063. * @param array $fuzzyKeywords
  8064. * @return int
  8065. */
  8066. private function findImportExcelColumnIndex(array $headers, array $exactKeywords, array $fuzzyKeywords) {
  8067. foreach ($headers as $index => $header) {
  8068. $header = trim((string)$header);
  8069. if ($header === '') {
  8070. continue;
  8071. }
  8072. foreach ($exactKeywords as $keyword) {
  8073. if ($header === $keyword) {
  8074. return $index;
  8075. }
  8076. }
  8077. }
  8078. foreach ($headers as $index => $header) {
  8079. $header = trim((string)$header);
  8080. if ($header === '') {
  8081. continue;
  8082. }
  8083. foreach ($fuzzyKeywords as $keyword) {
  8084. if (mb_strpos($header, $keyword) !== false) {
  8085. return $index;
  8086. }
  8087. }
  8088. }
  8089. return -1;
  8090. }
  8091. /**
  8092. * 判断 Excel 行是否为空行
  8093. *
  8094. * @param array $row
  8095. * @return bool
  8096. */
  8097. private function isImportExcelRowEmpty(array $row) {
  8098. foreach ($row as $cell) {
  8099. if (trim((string)$cell) !== '') {
  8100. return false;
  8101. }
  8102. }
  8103. return true;
  8104. }
  8105. /**
  8106. * 资产名称去除两边特殊符号(与 createProduct 保持一致)
  8107. *
  8108. * @param string $name
  8109. * @return string
  8110. */
  8111. private function normalizeImportProductName($name) {
  8112. $name = trim((string)$name);
  8113. $name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $name);
  8114. if (!$name || preg_match('/^[-—_]+$/u', $name)) {
  8115. return '';
  8116. }
  8117. return $name;
  8118. }
  8119. /**
  8120. * 解析 Excel 中的资产类型
  8121. *
  8122. * @param string $value
  8123. * @return int|null 1=角色 2=场景 3=道具
  8124. */
  8125. private function resolveImportProductType($value) {
  8126. $value = trim((string)$value);
  8127. $map = [
  8128. '角色' => 1,
  8129. '主体' => 1,
  8130. '人物' => 1,
  8131. '1' => 1,
  8132. '场景' => 2,
  8133. '2' => 2,
  8134. '道具' => 3,
  8135. '3' => 3,
  8136. ];
  8137. return isset($map[$value]) ? $map[$value] : null;
  8138. }
  8139. /**
  8140. * 资产类型文案
  8141. *
  8142. * @param int $type
  8143. * @return string
  8144. */
  8145. private function getImportProductTypeText($type) {
  8146. $map = [1 => '角色', 2 => '场景', 3 => '道具'];
  8147. return isset($map[$type]) ? $map[$type] : (string)$type;
  8148. }
  8149. /**
  8150. * 解析使用范围(逗号分隔的集数)
  8151. *
  8152. * @param string $value
  8153. * @return array
  8154. */
  8155. private function parseImportEpisodeNumbers($value) {
  8156. $parts = preg_split('/[,,、\s]+/u', trim((string)$value));
  8157. $episodeNumbers = [];
  8158. foreach ($parts as $part) {
  8159. if ($part === '') {
  8160. continue;
  8161. }
  8162. if (!is_numeric($part)) {
  8163. return [];
  8164. }
  8165. $episodeNumbers[] = (int)$part;
  8166. }
  8167. $episodeNumbers = array_values(array_unique($episodeNumbers));
  8168. sort($episodeNumbers);
  8169. return $episodeNumbers;
  8170. }
  8171. /**
  8172. * 获取剧本已关联资产名称集合(按 createProduct 的名称判断逻辑)
  8173. *
  8174. * @param int $script_id
  8175. * @param int $cpid
  8176. * @return array
  8177. */
  8178. private function getScriptProductNames($script_id, $cpid) {
  8179. $products = DB::table('mp_script_product_mappings as m')
  8180. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8181. ->where('m.script_id', $script_id)
  8182. ->where('p.cpid', $cpid)
  8183. ->where('p.type', 1)
  8184. ->where('p.is_deleted', 0)
  8185. ->get(['p.product_name']);
  8186. $names = [];
  8187. foreach ($products as $product) {
  8188. $name = $this->normalizeImportProductName($product->product_name);
  8189. if ($name !== '') {
  8190. $names[$name] = true;
  8191. }
  8192. }
  8193. return $names;
  8194. }
  8195. /**
  8196. * 获取剧本已关联的资产名称(仅按剧本判重,不区分资产类型)
  8197. *
  8198. * @param int $script_id
  8199. * @return array ['资产名称' => true]
  8200. */
  8201. private function getScriptAssetNames($script_id) {
  8202. $products = DB::table('mp_script_product_mappings as m')
  8203. ->join('mp_products as p', 'm.product_id', '=', 'p.id')
  8204. ->where('m.script_id', $script_id)
  8205. ->where('p.type', 1)
  8206. ->where('p.is_deleted', 0)
  8207. ->get(['p.product_name']);
  8208. $names = [];
  8209. foreach ($products as $product) {
  8210. $name = $this->normalizeImportProductName($product->product_name);
  8211. if ($name !== '') {
  8212. $names[$name] = true;
  8213. }
  8214. }
  8215. return $names;
  8216. }
  8217. /**
  8218. * 校验并提取本次入参中的新增资产行
  8219. *
  8220. * 规则:
  8221. * - 资产名称为空(或仅剩占位符):跳过
  8222. * - 同一份入参内重名(跨类型):保留最后一条
  8223. * - 与剧本已关联资产同名(跨类型判重,仅限当前剧本):不算新增
  8224. * - 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8225. *
  8226. * @param int $script_id
  8227. * @param mixed $products 入参(数组或 JSON 字符串)
  8228. * @return array [['type' => int, 'product_name' => string, 'pic_prompt' => string, 'episode_numbers' => []]]
  8229. */
  8230. private function extractNewScriptProductRows($script_id, $products) {
  8231. // 兼容 JSON 字符串;无法解析时按"没有新增行"处理,由后续创建逻辑给出原有报错
  8232. if (is_string($products)) {
  8233. $decoded = json_decode($products, true);
  8234. $products = (json_last_error() === JSON_ERROR_NONE) ? $decoded : [];
  8235. }
  8236. if (!is_array($products) || empty($products)) {
  8237. return [];
  8238. }
  8239. $rowMap = [];
  8240. foreach ($products as $productGroup) {
  8241. $type = getProp($productGroup, 'type');
  8242. $content = getProp($productGroup, 'content', []);
  8243. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8244. continue;
  8245. }
  8246. // 获取表头(第一行)并查找关键列的位置
  8247. $headers = $content[0];
  8248. $nameColumnIndex = -1;
  8249. $sequenceColumnIndex = -1;
  8250. $promptColumnIndex = -1;
  8251. $fallbackPromptColumnIndex = -1;
  8252. foreach ($headers as $index => $header) {
  8253. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8254. $nameColumnIndex = $index;
  8255. }
  8256. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8257. $sequenceColumnIndex = $index;
  8258. }
  8259. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8260. $promptColumnIndex = $index;
  8261. } elseif (strpos($header, '提示词') !== false && $fallbackPromptColumnIndex === -1) {
  8262. // 与 Excel 导入保持一致:优先"参考提示词",否则兼容"提示词"列
  8263. $fallbackPromptColumnIndex = $index;
  8264. }
  8265. }
  8266. if ($promptColumnIndex === -1) {
  8267. $promptColumnIndex = $fallbackPromptColumnIndex;
  8268. }
  8269. if ($nameColumnIndex === -1) {
  8270. continue;
  8271. }
  8272. for ($i = 1; $i < count($content); $i++) {
  8273. $row = $content[$i];
  8274. if (empty($row) || !isset($row[$nameColumnIndex])) {
  8275. continue;
  8276. }
  8277. // 处理product_name两边的符号;名称为空或仅剩占位符号则跳过
  8278. $product_name = $this->normalizeImportProductName($row[$nameColumnIndex]);
  8279. if ($product_name === '') {
  8280. continue;
  8281. }
  8282. $pic_prompt = '';
  8283. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8284. $pic_prompt = trim((string)$row[$promptColumnIndex]);
  8285. }
  8286. // 解析使用范围(逗号分隔的序号),为空时由创建逻辑写入默认映射(序号0)
  8287. $sequences = [];
  8288. $sequence_str = ($sequenceColumnIndex >= 0 && isset($row[$sequenceColumnIndex]))
  8289. ? trim((string)$row[$sequenceColumnIndex])
  8290. : '';
  8291. if ($sequence_str !== '') {
  8292. foreach (array_map('trim', explode(',', $sequence_str)) as $part) {
  8293. if (is_numeric($part)) {
  8294. $sequences[] = (int)$part;
  8295. }
  8296. }
  8297. }
  8298. // 跨类型判重,同一份入参内重名保留最后一条
  8299. $rowMap[$product_name] = [
  8300. 'type' => (int)$type,
  8301. 'product_name' => $product_name,
  8302. 'pic_prompt' => $pic_prompt,
  8303. 'episode_numbers' => $sequences,
  8304. ];
  8305. }
  8306. }
  8307. // 与剧本已关联资产判重(仅限当前剧本,跨类型)
  8308. $existingNames = $this->getScriptAssetNames($script_id);
  8309. $newRows = [];
  8310. $emptyPromptNames = [];
  8311. foreach ($rowMap as $name => $row) {
  8312. if (isset($existingNames[$name])) {
  8313. continue;
  8314. }
  8315. if ($row['pic_prompt'] === '') {
  8316. $emptyPromptNames[] = $name;
  8317. continue;
  8318. }
  8319. $newRows[] = $row;
  8320. }
  8321. // 新增行的参考提示词为空:直接报错,不进行任何后续处理
  8322. if (!empty($emptyPromptNames)) {
  8323. Utils::throwError('20003:以下新增资产的参考提示词不能为空:' . implode('、', $emptyPromptNames));
  8324. }
  8325. return $newRows;
  8326. }
  8327. /**
  8328. * 已有关联资产的图片任务处理(参照 saveScriptProducts 的处理方式)
  8329. *
  8330. * - 已有图片任务的资产:收集任务ID,交给轮询
  8331. * - 已有图片且生成成功的资产:跳过
  8332. * - 没有图片的资产:允许自动生成时补建图片任务(需要提示词)
  8333. *
  8334. * @param int $script_id
  8335. * @param string $model
  8336. * @param int $width
  8337. * @param int $height
  8338. * @param bool $auto_generate_images
  8339. * @return array ['product_task_map' => [], 'type_folder_ids' => [], 'has_all_tasks' => bool, 'product_count' => int, 'created_count' => int]
  8340. */
  8341. private function prepareExistingScriptProductTasks($script_id, $model, $width, $height, $auto_generate_images) {
  8342. $productTaskMap = [];
  8343. $typeFolderIds = [];
  8344. $hasAllTasks = true;
  8345. $createdCount = 0;
  8346. $existingMappings = DB::table('mp_script_product_mappings')
  8347. ->where('script_id', $script_id)
  8348. ->get();
  8349. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8350. $productsWithTasks = DB::table('mp_products')
  8351. ->whereIn('id', $productIds)
  8352. ->where('is_deleted', 0)
  8353. ->get();
  8354. foreach ($productsWithTasks as $product) {
  8355. // 收集类型文件夹ID
  8356. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8357. $parentFolder = DB::table('mp_products')
  8358. ->where('id', $product->parent_id)
  8359. ->where('type', 2)
  8360. ->first();
  8361. if ($parentFolder) {
  8362. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8363. }
  8364. }
  8365. // 检查是否有图片生成任务
  8366. if (!empty($product->pic_task_id)) {
  8367. $productTaskMap[$product->id] = $product->pic_task_id;
  8368. } elseif ($product->url && $product->pic_task_status == '生成成功') {
  8369. continue;
  8370. } else {
  8371. // 有资产没有图片
  8372. $hasAllTasks = false;
  8373. }
  8374. }
  8375. // 为没有图片的资产补建图片生成任务
  8376. if (!$hasAllTasks && $auto_generate_images && $productsWithTasks->isNotEmpty()) {
  8377. DB::beginTransaction();
  8378. try {
  8379. foreach ($productsWithTasks as $product) {
  8380. // 跳过已有任务的资产
  8381. if (!empty($product->pic_task_id)) {
  8382. continue;
  8383. }
  8384. // 跳过没有提示词的资产
  8385. if (empty($product->pic_prompt)) {
  8386. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8387. 'product_id' => $product->id,
  8388. 'product_name' => $product->product_name,
  8389. ]);
  8390. continue;
  8391. }
  8392. try {
  8393. $task = $this->aiImageGenerationService->createImageGenerationTask([
  8394. 'prompt' => $product->pic_prompt,
  8395. 'model' => $model,
  8396. 'ref_img_urls' => [],
  8397. 'width' => $width,
  8398. 'height' => $height,
  8399. // 计费锚点(剧本),用于积分明细归属统计
  8400. 'script_id' => $script_id,
  8401. ]);
  8402. $task_id = $task->id;
  8403. if ($task_id) {
  8404. $productTaskMap[$product->id] = $task_id;
  8405. $createdCount++;
  8406. DB::table('mp_products')
  8407. ->where('id', $product->id)
  8408. ->update([
  8409. 'pic_task_id' => $task_id,
  8410. 'pic_task_status' => '生成中',
  8411. 'updated_at' => now(),
  8412. ]);
  8413. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8414. 'product_id' => $product->id,
  8415. 'task_id' => $task_id,
  8416. ]);
  8417. }
  8418. } catch (\Exception $e) {
  8419. dLog('anime')->error('创建资产图片生成任务失败', [
  8420. 'product_id' => $product->id,
  8421. 'error' => $e->getMessage(),
  8422. ]);
  8423. DB::table('mp_products')
  8424. ->where('id', $product->id)
  8425. ->update([
  8426. 'pic_task_status' => '生成失败',
  8427. 'updated_at' => now(),
  8428. ]);
  8429. }
  8430. }
  8431. DB::commit();
  8432. } catch (\Exception $e) {
  8433. DB::rollback();
  8434. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8435. 'script_id' => $script_id,
  8436. 'error' => $e->getMessage(),
  8437. ]);
  8438. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8439. }
  8440. }
  8441. return [
  8442. 'product_task_map' => $productTaskMap,
  8443. 'type_folder_ids' => $typeFolderIds,
  8444. 'has_all_tasks' => $hasAllTasks,
  8445. 'product_count' => count($productIds),
  8446. 'created_count' => $createdCount,
  8447. ];
  8448. }
  8449. /**
  8450. * 保存剧本资产关联关系
  8451. * @param array $data 请求参数
  8452. * @return bool
  8453. */
  8454. public function saveScriptProducts($data) {
  8455. $uid = Site::getUid();
  8456. $cpid = Site::getCpid();
  8457. $script_id = getProp($data, 'script_id');
  8458. $products = getProp($data, 'products', []);
  8459. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  8460. if (!$script_id) {
  8461. Utils::throwError('20003:请提供剧本ID');
  8462. }
  8463. // 验证剧本是否存在
  8464. $script = DB::table('mp_scripts')
  8465. ->where('id', $script_id)
  8466. ->where('is_deleted', 0)
  8467. ->first();
  8468. if (!$script) {
  8469. Utils::throwError('20003:剧本不存在');
  8470. }
  8471. // 处理图片模型
  8472. $model = getProp($data, 'model');
  8473. if (!$model) {
  8474. // 使用默认模型
  8475. $model = 'gpt-image-2';
  8476. }
  8477. // 验证模型是否在可用模型表中
  8478. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8479. Utils::throwError('20003:该模型已不可用,请更换!');
  8480. }
  8481. $ratio = getProp($data, 'ratio', '9:16');
  8482. $resolution = getProp($data, 'resolution', '2k');
  8483. // 分辨率档位与尺寸映射统一从 BaseConst 获取
  8484. $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
  8485. // 参数验证
  8486. $resolution = strtolower($resolution);
  8487. if (!isset($sizeMap[$resolution])) {
  8488. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  8489. }
  8490. if (!isset($sizeMap[$resolution][$ratio])) {
  8491. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  8492. }
  8493. // 根据 ratio 和 resolution 确定宽高
  8494. $width = $sizeMap[$resolution][$ratio]['width'];
  8495. $height = $sizeMap[$resolution][$ratio]['height'];
  8496. $script_name = $script->script_name ?? 'script_' . $script_id;
  8497. // 先校验并提取本次入参中的新增资产行:
  8498. // 新增行的参考提示词为空时直接报错,不写任何数据、不创建任务中心记录
  8499. $newRows = $this->extractNewScriptProductRows($script_id, $products);
  8500. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  8501. $taskCenterId = $this->createScriptProductTaskCenter(
  8502. $uid,
  8503. $cpid,
  8504. $script_id,
  8505. $products,
  8506. $model,
  8507. $ratio,
  8508. $resolution,
  8509. $auto_generate_images
  8510. );
  8511. // 检查是否已经有该剧本的资产数据
  8512. $existingMappings = DB::table('mp_script_product_mappings')
  8513. ->where('script_id', $script_id)
  8514. ->get();
  8515. // 已有资产且本次没有新增行时,走原有的"已存在"处理;否则走下方创建逻辑
  8516. if ($existingMappings->isNotEmpty() && empty($newRows)) {
  8517. // 已存在资产映射,检查是否所有资产都有图片生成任务
  8518. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  8519. // 查询这些资产的图片生成任务状态
  8520. $productsWithTasks = DB::table('mp_products')
  8521. ->whereIn('id', $productIds)
  8522. ->where('is_deleted', 0)
  8523. ->get();
  8524. $productTaskMap = [];
  8525. $typeFolderIds = [];
  8526. $hasAllTasks = true;
  8527. foreach ($productsWithTasks as $product) {
  8528. // 收集类型文件夹ID
  8529. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  8530. $parentFolder = DB::table('mp_products')
  8531. ->where('id', $product->parent_id)
  8532. ->where('type', 2)
  8533. ->first();
  8534. if ($parentFolder) {
  8535. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  8536. }
  8537. }
  8538. // 检查是否有图片生成任务
  8539. if (!empty($product->pic_task_id)) {
  8540. $productTaskMap[$product->id] = $product->pic_task_id;
  8541. } else if($product->url && $product->pic_task_status == '生成成功') {
  8542. continue;
  8543. } else {
  8544. // 有资产没有图片任务
  8545. $hasAllTasks = false;
  8546. }
  8547. }
  8548. // 如果所有资产都有任务ID,直接轮询返回结果
  8549. if ($hasAllTasks && !empty($productTaskMap)) {
  8550. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  8551. 'script_id' => $script_id,
  8552. 'script_name' => $script_name,
  8553. 'product_count' => count($productTaskMap)
  8554. ]);
  8555. // 直接返回 SSE 流轮询结果
  8556. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8557. }
  8558. // 如果部分资产没有任务ID,只为这些资产创建任务
  8559. if (!$hasAllTasks && $auto_generate_images) {
  8560. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  8561. 'script_id' => $script_id,
  8562. 'script_name' => $script_name
  8563. ]);
  8564. // 开启事务
  8565. DB::beginTransaction();
  8566. try {
  8567. foreach ($productsWithTasks as $product) {
  8568. // 跳过已有任务的资产
  8569. if (!empty($product->pic_task_id)) {
  8570. continue;
  8571. }
  8572. // 跳过没有提示词的资产
  8573. if (empty($product->pic_prompt)) {
  8574. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8575. 'product_id' => $product->id,
  8576. 'product_name' => $product->product_name
  8577. ]);
  8578. continue;
  8579. }
  8580. try {
  8581. // 创建图片生成任务
  8582. $params = [
  8583. 'prompt' => $product->pic_prompt,
  8584. 'model' => $model,
  8585. 'ref_img_urls' => [],
  8586. 'width' => $width,
  8587. 'height' => $height,
  8588. // 计费锚点(剧本),用于积分明细归属统计
  8589. 'script_id' => $script_id,
  8590. ];
  8591. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8592. $task_id = $task->id;
  8593. if ($task_id) {
  8594. $productTaskMap[$product->id] = $task_id;
  8595. // 在事务中更新资产表的任务ID和状态
  8596. DB::table('mp_products')
  8597. ->where('id', $product->id)
  8598. ->update([
  8599. 'pic_task_id' => $task_id,
  8600. 'pic_task_status' => '生成中',
  8601. 'updated_at' => now()
  8602. ]);
  8603. dLog('anime')->info('为已存在资产创建图片生成任务', [
  8604. 'product_id' => $product->id,
  8605. 'task_id' => $task_id
  8606. ]);
  8607. }
  8608. } catch (\Exception $e) {
  8609. dLog('anime')->error('创建资产图片生成任务失败', [
  8610. 'product_id' => $product->id,
  8611. 'error' => $e->getMessage()
  8612. ]);
  8613. // 标记为失败(仍在事务中)
  8614. DB::table('mp_products')
  8615. ->where('id', $product->id)
  8616. ->update([
  8617. 'pic_task_status' => '生成失败',
  8618. 'updated_at' => now()
  8619. ]);
  8620. }
  8621. }
  8622. // 提交事务
  8623. DB::commit();
  8624. // 如果有新创建的任务,返回 SSE 流
  8625. if (!empty($productTaskMap)) {
  8626. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  8627. }
  8628. } catch (\Exception $e) {
  8629. // 回滚事务
  8630. DB::rollback();
  8631. dLog('anime')->error('为已存在资产创建图片任务失败', [
  8632. 'script_id' => $script_id,
  8633. 'error' => $e->getMessage()
  8634. ]);
  8635. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  8636. }
  8637. }
  8638. // 如果不需要生成图片,返回已存在的信息
  8639. $resultData = [
  8640. 'success' => true,
  8641. 'message' => '剧本资产已存在',
  8642. 'script_id' => $script_id,
  8643. 'script_name' => $script_name,
  8644. 'type_folder_ids' => $typeFolderIds,
  8645. 'existing_products' => count($productIds),
  8646. 'tasks_count' => count($productTaskMap),
  8647. 'task_center_id' => $taskCenterId
  8648. ];
  8649. // 接口已正常完成,更新任务中心状态和结果
  8650. if ($taskCenterId) {
  8651. $this->taskCenterService->updateTask($taskCenterId, [
  8652. 'status' => MpTaskCenter::STATUS_SUCCESS,
  8653. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  8654. 'error_message' => null
  8655. ]);
  8656. }
  8657. return $resultData;
  8658. }
  8659. // 走到这里说明有新行需要创建(或剧本还没有任何资产),保留原有的入参校验报错
  8660. if (empty($newRows)) {
  8661. $decodedProducts = $products;
  8662. if (is_string($decodedProducts)) {
  8663. $decodedProducts = json_decode($decodedProducts, true);
  8664. if (json_last_error() !== JSON_ERROR_NONE) {
  8665. Utils::throwError('20003:产品数据格式错误');
  8666. }
  8667. }
  8668. if (!is_array($decodedProducts) || empty($decodedProducts)) {
  8669. Utils::throwError('20003:产品数据不能为空');
  8670. }
  8671. Utils::throwError('20003:没有有效的产品数据');
  8672. }
  8673. // 仅保留本次新增的资产行,复用下方原有的创建逻辑
  8674. $products = [];
  8675. foreach ($newRows as $newRow) {
  8676. if (!isset($products[$newRow['type']])) {
  8677. $products[$newRow['type']] = [
  8678. 'type' => $newRow['type'],
  8679. 'content' => [['资产名称', '使用范围', '参考提示词']],
  8680. ];
  8681. }
  8682. $products[$newRow['type']]['content'][] = [
  8683. $newRow['product_name'],
  8684. implode(',', $newRow['episode_numbers']),
  8685. $newRow['pic_prompt'],
  8686. ];
  8687. }
  8688. $products = array_values($products);
  8689. // 以下是原有的创建逻辑...
  8690. // 开启事务
  8691. DB::beginTransaction();
  8692. try {
  8693. $now = now();
  8694. $mappingRecords = [];
  8695. $createdProductIds = []; // 记录所有创建的资产ID
  8696. // 获取剧本名称
  8697. $script_name = $script->script_name ?? 'script_' . $script_id;
  8698. // 存储每个类型的根文件夹ID
  8699. $typeFolderIds = [];
  8700. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  8701. foreach ($products as $productGroup) {
  8702. $type = getProp($productGroup, 'type');
  8703. $title = getProp($productGroup, 'title', '');
  8704. $content = getProp($productGroup, 'content', []);
  8705. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  8706. continue;
  8707. }
  8708. // 为当前类型获取根文件夹:该剧本已存在则复用,避免重复创建根文件夹
  8709. if (!isset($typeFolderIds[$type])) {
  8710. $folder = DB::table('mp_products')
  8711. ->where('cpid', $cpid)
  8712. ->where('type', 2)
  8713. ->where('product', $type)
  8714. ->where('product_name', $script_name)
  8715. ->where('parent_id', 0)
  8716. ->where('is_deleted', 0)
  8717. ->first();
  8718. if ($folder) {
  8719. $typeFolderIds[$type] = $folder->id;
  8720. } else {
  8721. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  8722. 'user_id' => $uid,
  8723. 'cpid' => $cpid,
  8724. 'type' => 2, // 1.资产 2文件夹
  8725. 'product' => $type, // 1.主体 2.场景 3.道具
  8726. 'parent_id' => 0, // 根文件夹,parent_id=0
  8727. 'level' => 1, // 第一层级
  8728. 'product_name' => $script_name,
  8729. 'sort_order' => time() + $type,
  8730. 'is_deleted' => 0,
  8731. 'created_at' => $now,
  8732. 'updated_at' => $now
  8733. ]);
  8734. }
  8735. }
  8736. $folder_id = $typeFolderIds[$type];
  8737. // 获取表头(第一行)并查找关键列的位置
  8738. $headers = $content[0];
  8739. $nameColumnIndex = -1; // 资产名称列索引
  8740. $sequenceColumnIndex = -1; // 使用范围列索引
  8741. $promptColumnIndex = -1; // 参考提示词列索引
  8742. foreach ($headers as $index => $header) {
  8743. // 查找"资产名称"列
  8744. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  8745. $nameColumnIndex = $index;
  8746. }
  8747. // 查找"使用范围"列
  8748. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  8749. $sequenceColumnIndex = $index;
  8750. }
  8751. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  8752. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  8753. $promptColumnIndex = $index;
  8754. }
  8755. }
  8756. // 验证必要的列是否都找到了
  8757. if ($nameColumnIndex === -1) {
  8758. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  8759. continue;
  8760. }
  8761. if ($sequenceColumnIndex === -1) {
  8762. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  8763. continue;
  8764. }
  8765. // 跳过表头,解析每一行数据
  8766. for ($i = 1; $i < count($content); $i++) {
  8767. $row = $content[$i];
  8768. // 确保行数据有效
  8769. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  8770. continue;
  8771. }
  8772. // 根据动态查找的列索引提取数据
  8773. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  8774. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  8775. $pic_prompt = '';
  8776. // 提取参考提示词(如果找到了该列)
  8777. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  8778. $pic_prompt = trim($row[$promptColumnIndex]);
  8779. }
  8780. // 解析使用范围(逗号分隔的序号)
  8781. $sequences = [];
  8782. if (!empty($sequence_str)) {
  8783. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  8784. foreach ($sequenceParts as $part) {
  8785. if (is_numeric($part)) {
  8786. $sequences[] = (int)$part;
  8787. }
  8788. }
  8789. }
  8790. if (empty($product_name)) {
  8791. continue;
  8792. }
  8793. // 处理product_name两边的符号
  8794. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8795. // 如果名称不存在或仅剩占位符号,则跳过
  8796. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  8797. dLog('anime')->warning('资产名称无效,跳过保存', [
  8798. 'script_id' => $script_id,
  8799. 'type' => $type,
  8800. 'product_name' => $product_name
  8801. ]);
  8802. continue;
  8803. }
  8804. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  8805. $product_id = DB::table('mp_products')->insertGetId([
  8806. 'product_name' => $product_name,
  8807. 'type' => 1, // 1=资产 2.文件夹
  8808. 'product' => $type, // 1=角色, 2=场景, 3=道具
  8809. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  8810. 'level' => 2, // 第二层级
  8811. 'pic_prompt' => $pic_prompt,
  8812. 'user_id' => $uid,
  8813. 'cpid' => $cpid,
  8814. 'sort_order' => time(),
  8815. 'is_deleted' => 0,
  8816. 'created_at' => $now,
  8817. 'updated_at' => $now,
  8818. ]);
  8819. // 记录创建的资产ID
  8820. $createdProductIds[] = $product_id;
  8821. // 为每个序号创建映射记录
  8822. if (!empty($sequences)) {
  8823. foreach ($sequences as $sequence) {
  8824. $mappingRecords[] = [
  8825. 'script_id' => $script_id,
  8826. 'product_id' => $product_id,
  8827. 'episode_number' => $sequence,
  8828. 'created_at' => $now,
  8829. 'updated_at' => $now,
  8830. ];
  8831. }
  8832. } else {
  8833. // 如果没有指定序号,创建一个默认映射(序号为0)
  8834. $mappingRecords[] = [
  8835. 'script_id' => $script_id,
  8836. 'product_id' => $product_id,
  8837. 'episode_number' => 0,
  8838. 'created_at' => $now,
  8839. 'updated_at' => $now,
  8840. ];
  8841. }
  8842. }
  8843. }
  8844. if (empty($mappingRecords)) {
  8845. Utils::throwError('20003:没有有效的产品数据');
  8846. }
  8847. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  8848. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  8849. // 剧本已有资产,同步更新is_products标记
  8850. DB::table('mp_scripts')->where('id', $script_id)->update([
  8851. 'is_products' => 1,
  8852. 'updated_at' => $now
  8853. ]);
  8854. // 如果需要自动生成图片,在事务中创建图片生成任务
  8855. $productTaskMap = [];
  8856. if ($auto_generate_images && !empty($createdProductIds)) {
  8857. // 查询所有创建的资产
  8858. $productsToGenerate = DB::table('mp_products')
  8859. ->whereIn('id', $createdProductIds)
  8860. ->where('is_deleted', 0)
  8861. ->get();
  8862. foreach ($productsToGenerate as $product) {
  8863. if (empty($product->pic_prompt)) {
  8864. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  8865. 'product_id' => $product->id,
  8866. 'product_name' => $product->product_name
  8867. ]);
  8868. continue;
  8869. }
  8870. try {
  8871. // 创建图片生成任务
  8872. $params = [
  8873. 'prompt' => $product->pic_prompt,
  8874. 'model' => $model,
  8875. 'ref_img_urls' => [],
  8876. 'width' => $width,
  8877. 'height' => $height,
  8878. // 计费锚点(剧本),用于积分明细归属统计
  8879. 'script_id' => $script_id,
  8880. ];
  8881. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8882. $task_id = $task->id;
  8883. if ($task_id) {
  8884. $productTaskMap[$product->id] = $task_id;
  8885. // 在事务中更新资产表的任务ID和状态
  8886. DB::table('mp_products')
  8887. ->where('id', $product->id)
  8888. ->update([
  8889. 'pic_task_id' => $task_id,
  8890. 'pic_task_status' => '生成中',
  8891. 'updated_at' => now()
  8892. ]);
  8893. dLog('anime')->info('创建资产图片生成任务', [
  8894. 'product_id' => $product->id,
  8895. 'task_id' => $task_id
  8896. ]);
  8897. }
  8898. } catch (\Exception $e) {
  8899. dLog('anime')->error('创建资产图片生成任务失败', [
  8900. 'product_id' => $product->id,
  8901. 'error' => $e->getMessage()
  8902. ]);
  8903. // 标记为失败(仍在事务中)
  8904. DB::table('mp_products')
  8905. ->where('id', $product->id)
  8906. ->update([
  8907. 'pic_task_status' => '生成失败',
  8908. 'updated_at' => now()
  8909. ]);
  8910. }
  8911. }
  8912. }
  8913. // 提交事务
  8914. DB::commit();
  8915. // 本次新增资产创建的图片任务
  8916. $createdTaskMap = $productTaskMap;
  8917. } catch (\Exception $e) {
  8918. // 回滚事务
  8919. DB::rollback();
  8920. // 更新任务中心状态为失败
  8921. if (!empty($taskCenterId)) {
  8922. $this->taskCenterService->updateTask($taskCenterId, [
  8923. 'status' => MpTaskCenter::STATUS_FAILED,
  8924. 'error_message' => $e->getMessage()
  8925. ]);
  8926. }
  8927. // 记录错误日志
  8928. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  8929. 'script_id' => $script_id,
  8930. 'error' => $e->getMessage(),
  8931. 'trace' => $e->getTraceAsString()
  8932. ]);
  8933. // 统一使用 Utils::throwError 抛出错误
  8934. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  8935. }
  8936. // 落库成功后统一处理图片任务:
  8937. // 1) 本次新增资产的图片任务已在上方事务中创建
  8938. // 2) 剧本内已存在但缺图的资产在此补建,并与新增资产的任务一并收集为待轮询任务
  8939. $existingTaskInfo = $this->prepareExistingScriptProductTasks(
  8940. $script_id,
  8941. $model,
  8942. $width,
  8943. $height,
  8944. $auto_generate_images
  8945. );
  8946. $productTaskMap = $existingTaskInfo['product_task_map'];
  8947. // 创建阶段解析到的类型根文件夹优先
  8948. $typeFolderIds = $typeFolderIds + $existingTaskInfo['type_folder_ids'];
  8949. // 保存结果(SSE 的 init / complete 事件会携带该结构)
  8950. $resultData = [
  8951. 'success' => true,
  8952. 'message' => '保存完成',
  8953. 'script_id' => $script_id,
  8954. 'script_name' => $script_name,
  8955. 'type_folder_ids' => $typeFolderIds,
  8956. 'inserted_count' => $insertedCount,
  8957. 'total_records' => count($mappingRecords),
  8958. 'created_products' => count($createdProductIds),
  8959. 'pending_tasks_count' => count($productTaskMap),
  8960. 'image_tasks_created' => count($createdTaskMap) + $existingTaskInfo['created_count'],
  8961. 'task_center_id' => $taskCenterId,
  8962. ];
  8963. // 有待完成的图片任务:返回 SSE 轮询流(事务外轮询)
  8964. if ($auto_generate_images && !empty($productTaskMap)) {
  8965. return $this->pollProductImageTasks(
  8966. $script_id,
  8967. $script_name,
  8968. $productTaskMap,
  8969. $typeFolderIds,
  8970. $taskCenterId,
  8971. ['import_result' => $resultData],
  8972. ['import_result' => $resultData]
  8973. );
  8974. }
  8975. // 没有需要轮询的任务:通过 SSE complete 事件返回保存结果
  8976. return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
  8977. }
  8978. /**
  8979. * 根据入参创建或复用任务中心记录
  8980. *
  8981. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  8982. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  8983. * 避免生成重复任务。
  8984. *
  8985. * @param int|string $uid
  8986. * @param int|string $cpid
  8987. * @param int|string $script_id
  8988. * @param mixed $products
  8989. * @param string $model
  8990. * @param string $ratio
  8991. * @param string $resolution
  8992. * @param mixed $auto_generate_images
  8993. * @return int 任务中心ID
  8994. */
  8995. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  8996. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  8997. if (is_string($products)) {
  8998. $decoded = json_decode($products, true);
  8999. if (json_last_error() === JSON_ERROR_NONE) {
  9000. $products = $decoded;
  9001. }
  9002. }
  9003. $params = [
  9004. 'script_id' => (int)$script_id,
  9005. 'products' => $products,
  9006. 'model' => $model,
  9007. 'ratio' => $ratio,
  9008. 'resolution' => $resolution,
  9009. 'auto_generate_images' => (bool)$auto_generate_images,
  9010. ];
  9011. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  9012. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  9013. $existing = DB::table('mp_task_center')
  9014. ->where('uid', (int)$uid)
  9015. ->where('cpid', (int)$cpid)
  9016. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9017. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  9018. ->where('params_md5', $paramsMd5)
  9019. ->orderBy('id', 'desc')
  9020. ->first();
  9021. if ($existing) {
  9022. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  9023. 'script_id' => $script_id,
  9024. 'task_center_id' => $existing->id,
  9025. 'params_md5' => $paramsMd5,
  9026. ]);
  9027. return (int)$existing->id;
  9028. }
  9029. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  9030. $now = date('Y-m-d H:i:s');
  9031. DB::table('mp_task_center')->insertOrIgnore([
  9032. 'uid' => (int)$uid,
  9033. 'cpid' => (int)$cpid,
  9034. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  9035. 'title' => '剧本资产图片生成',
  9036. 'ref_task_id' => 0,
  9037. 'status' => MpTaskCenter::STATUS_PROCESSING,
  9038. 'result' => null,
  9039. 'error_message' => null,
  9040. 'prompt' => null,
  9041. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  9042. 'params_md5' => $paramsMd5,
  9043. 'created_at' => $now,
  9044. 'updated_at' => $now,
  9045. ]);
  9046. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  9047. $taskId = (int)DB::table('mp_task_center')
  9048. ->where('uid', (int)$uid)
  9049. ->where('cpid', (int)$cpid)
  9050. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9051. ->where('params_md5', $paramsMd5)
  9052. ->orderBy('id', 'desc')
  9053. ->value('id');
  9054. dLog('anime')->info('创建任务中心记录', [
  9055. 'script_id' => $script_id,
  9056. 'task_center_id' => $taskId,
  9057. 'params_md5' => $paramsMd5,
  9058. ]);
  9059. return $taskId;
  9060. }
  9061. /**
  9062. * 任务结束时更新任务中心记录的状态和结果
  9063. *
  9064. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  9065. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  9066. *
  9067. * @param int|null $taskCenterId
  9068. * @param array $resultData 接口返回结果数组
  9069. * @param bool $timeout 是否超时未完成
  9070. */
  9071. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  9072. if (!$taskCenterId) {
  9073. return;
  9074. }
  9075. $stats = $resultData['stats'] ?? [];
  9076. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  9077. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  9078. $failedCount = $completedCount - $successCount;
  9079. // 与接口返回给客户端的结果保持一致
  9080. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  9081. if ($timeout) {
  9082. $this->taskCenterService->updateTask((int)$taskCenterId, [
  9083. 'status' => MpTaskCenter::STATUS_FAILED,
  9084. 'result' => $result,
  9085. 'error_message' => '部分任务超时,请稍后查看结果',
  9086. ]);
  9087. return;
  9088. }
  9089. $this->taskCenterService->updateTask((int)$taskCenterId, [
  9090. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  9091. 'result' => $result,
  9092. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  9093. ]);
  9094. }
  9095. /**
  9096. * 批量为剧本资产生成图片
  9097. *
  9098. * @param array $data 请求参数
  9099. * @return \Generator 返回 SSE 流
  9100. */
  9101. public function batchGenerateProductImages($data) {
  9102. $script_id = getProp($data, 'script_id');
  9103. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  9104. if (!$script_id) {
  9105. Utils::throwError('20003:请提供剧本ID');
  9106. }
  9107. // 验证剧本是否存在
  9108. $script = DB::table('mp_scripts')
  9109. ->where('id', $script_id)
  9110. ->where('is_deleted', 0)
  9111. ->first();
  9112. if (!$script) {
  9113. Utils::throwError('20003:剧本不存在');
  9114. }
  9115. $script_name = $script->script_name ?? 'script_' . $script_id;
  9116. // 获取需要生成图片的所有资产
  9117. $products = DB::table('mp_products')
  9118. ->whereIn('parent_id', array_values($type_folder_ids))
  9119. ->where('is_deleted', 0)
  9120. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  9121. ->get();
  9122. if ($products->isEmpty()) {
  9123. Utils::throwError('20003:没有找到需要生成图片的资产');
  9124. }
  9125. // 默认参数
  9126. $model = 'gpt-image-2';
  9127. $width = 1600;
  9128. $height = 2848;
  9129. // 开始为每个资产创建图片生成任务
  9130. $taskIds = [];
  9131. $productTaskMap = []; // 资产ID到任务ID的映射
  9132. foreach ($products as $product) {
  9133. if (empty($product->pic_prompt)) {
  9134. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  9135. continue;
  9136. }
  9137. try {
  9138. // 创建图片生成任务
  9139. $params = [
  9140. 'prompt' => $product->pic_prompt,
  9141. 'model' => $model,
  9142. 'ref_img_urls' => [],
  9143. 'width' => $width,
  9144. 'height' => $height,
  9145. // 计费锚点(剧本),用于积分明细归属统计
  9146. 'script_id' => $script_id,
  9147. ];
  9148. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9149. $task_id = $task->id;
  9150. if ($task_id) {
  9151. $taskIds[] = $task_id;
  9152. $productTaskMap[$product->id] = $task_id;
  9153. // 更新资产表的任务ID和状态
  9154. DB::table('mp_products')
  9155. ->where('id', $product->id)
  9156. ->update([
  9157. 'pic_task_id' => $task_id,
  9158. 'pic_task_status' => '生成中',
  9159. 'updated_at' => now()
  9160. ]);
  9161. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  9162. }
  9163. } catch (\Exception $e) {
  9164. dLog('anime')->error('创建资产图片生成任务失败', [
  9165. 'product_id' => $product->id,
  9166. 'error' => $e->getMessage()
  9167. ]);
  9168. // 标记为失败
  9169. DB::table('mp_products')
  9170. ->where('id', $product->id)
  9171. ->update([
  9172. 'pic_task_status' => '生成失败',
  9173. 'updated_at' => now()
  9174. ]);
  9175. }
  9176. }
  9177. if (empty($taskIds)) {
  9178. Utils::throwError('20003:没有成功创建任何图片生成任务');
  9179. }
  9180. // 返回 SSE 流
  9181. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  9182. }
  9183. /**
  9184. * 无需轮询时的 SSE 返回:直接通过 complete 事件返回导入结果
  9185. *
  9186. * @param int $script_id
  9187. * @param string $script_name
  9188. * @param array $resultData 导入结果(原普通 JSON 的 data 内容)
  9189. * @param array $type_folder_ids
  9190. * @param int|null $taskCenterId
  9191. * @return \Generator
  9192. */
  9193. private function streamImportComplete($script_id, $script_name, array $resultData, $type_folder_ids, $taskCenterId = null) {
  9194. if ($taskCenterId) {
  9195. $initResponse = [
  9196. 'type' => 'init',
  9197. 'script_id' => $script_id,
  9198. 'script_name' => $script_name,
  9199. 'timestamp' => date('Y-m-d H:i:s'),
  9200. 'task_center_id' => (int)$taskCenterId,
  9201. 'import_result' => $resultData,
  9202. ];
  9203. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9204. }
  9205. $stats = $this->collectScriptProductStats($script_id);
  9206. $response = [
  9207. 'type' => 'complete',
  9208. 'script_id' => $script_id,
  9209. 'script_name' => $script_name,
  9210. 'stats' => $stats,
  9211. 'timestamp' => date('Y-m-d H:i:s'),
  9212. 'import_result' => $resultData,
  9213. ];
  9214. if ($taskCenterId) {
  9215. $response['task_center_id'] = (int)$taskCenterId;
  9216. }
  9217. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9218. // 更新任务中心状态和结果
  9219. $this->finishScriptProductTask($taskCenterId, $response);
  9220. }
  9221. /**
  9222. * 统计剧本资产的图片生成状态(仅按 mp_products 当前状态统计,不驱动任务)
  9223. *
  9224. * @param int $script_id
  9225. * @return array
  9226. */
  9227. private function collectScriptProductStats($script_id) {
  9228. $stats = [
  9229. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9230. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9231. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0],
  9232. ];
  9233. $typeNames = [1 => 'roles', 2 => 'scenes', 3 => 'props'];
  9234. $productIds = DB::table('mp_script_product_mappings')
  9235. ->where('script_id', $script_id)
  9236. ->pluck('product_id')
  9237. ->unique()
  9238. ->toArray();
  9239. if (empty($productIds)) {
  9240. return [];
  9241. }
  9242. $products = DB::table('mp_products')
  9243. ->whereIn('id', $productIds)
  9244. ->where('is_deleted', 0)
  9245. ->get();
  9246. foreach ($products as $product) {
  9247. $typeName = $typeNames[$product->product] ?? 'unknown';
  9248. if (!isset($stats[$typeName])) {
  9249. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9250. }
  9251. $stats[$typeName]['total']++;
  9252. if ($product->pic_task_status === '生成成功') {
  9253. $stats[$typeName]['success']++;
  9254. $stats[$typeName]['completed']++;
  9255. } elseif ($product->pic_task_status === '生成失败') {
  9256. $stats[$typeName]['completed']++;
  9257. }
  9258. }
  9259. foreach ($stats as $typeName => $stat) {
  9260. if ($stat['total'] === 0) {
  9261. unset($stats[$typeName]);
  9262. }
  9263. }
  9264. return $stats;
  9265. }
  9266. /**
  9267. * 轮询资产图片生成任务状态(SSE流式返回)
  9268. * 只通过查询数据库获取任务状态,不主动调用API
  9269. *
  9270. * @param int $script_id 剧本ID
  9271. * @param string $script_name 剧本名称
  9272. * @param array $productTaskMap 资产ID到任务ID的映射
  9273. * @param array $type_folder_ids 类型文件夹ID映射
  9274. * @param int|null $taskCenterId 任务中心ID
  9275. * @param array $initExtra 追加到 init 事件中的额外数据
  9276. * @param array $completeExtra 追加到 complete、timeout 事件中的额外数据
  9277. * @return \Generator
  9278. */
  9279. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null, array $initExtra = [], array $completeExtra = []) {
  9280. $startTime = time();
  9281. $timeout = 1800; // 30分钟超时
  9282. $pollInterval = 10; // 10秒轮询一次
  9283. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  9284. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  9285. if ($taskCenterId) {
  9286. $initResponse = array_merge([
  9287. 'type' => 'init',
  9288. 'script_id' => $script_id,
  9289. 'script_name' => $script_name,
  9290. 'timestamp' => date('Y-m-d H:i:s'),
  9291. 'task_center_id' => (int)$taskCenterId,
  9292. ], $initExtra);
  9293. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  9294. }
  9295. // 定义类型名称映射
  9296. $typeNames = [
  9297. 1 => 'roles', // 角色
  9298. 2 => 'scenes', // 场景
  9299. 3 => 'props' // 道具
  9300. ];
  9301. while (time() - $startTime < $timeout) {
  9302. sleep($pollInterval);
  9303. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  9304. $mappings = DB::table('mp_script_product_mappings')
  9305. ->where('script_id', $script_id)
  9306. ->pluck('product_id')
  9307. ->unique()
  9308. ->toArray();
  9309. if (empty($mappings)) {
  9310. dLog('anime')->warning('该剧本没有关联的资产', [
  9311. 'script_id' => $script_id,
  9312. 'script_name' => $script_name
  9313. ]);
  9314. break;
  9315. }
  9316. // 查询所有资产的当前状态
  9317. $products = DB::table('mp_products')
  9318. ->whereIn('id', $mappings)
  9319. ->where('is_deleted', 0)
  9320. ->get();
  9321. // 统计各类型的状态(使用类型名称作为键名)
  9322. $stats = [
  9323. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  9324. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  9325. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  9326. ];
  9327. $allCompleted = true;
  9328. $hasStatusChange = false;
  9329. foreach ($products as $product) {
  9330. $type = $product->product;
  9331. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  9332. // 如果类型名称不在 stats 中,初始化
  9333. if (!isset($stats[$typeName])) {
  9334. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9335. }
  9336. $stats[$typeName]['total']++;
  9337. $task_id = $product->pic_task_id;
  9338. $currentStatus = $product->pic_task_status;
  9339. // 检查状态是否有变化
  9340. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  9341. $hasStatusChange = true;
  9342. $lastStatus[$product->id] = $currentStatus;
  9343. }
  9344. // 如果是生成中,查询任务表状态
  9345. if ($currentStatus === '生成中' && $task_id) {
  9346. // 只查询数据库,不调用API
  9347. $task = DB::table('mp_generate_pic_tasks')
  9348. ->where('id', $task_id)
  9349. ->first();
  9350. if ($task) {
  9351. // 检查任务状态
  9352. if ($task->status === 'success' && $task->result_url) {
  9353. // 解析图片URL
  9354. $result_urls = $task->result_url;
  9355. if (is_string($result_urls)) {
  9356. $result_urls = json_decode($result_urls, true);
  9357. }
  9358. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  9359. // 更新资产表状态
  9360. DB::table('mp_products')
  9361. ->where('id', $product->id)
  9362. ->update([
  9363. 'pic_task_status' => '生成成功',
  9364. 'url' => $img_url,
  9365. 'updated_at' => now()
  9366. ]);
  9367. $stats[$typeName]['success']++;
  9368. $stats[$typeName]['completed']++;
  9369. $hasStatusChange = true;
  9370. dLog('anime')->info('资产图片生成成功', [
  9371. 'product_id' => $product->id,
  9372. 'task_id' => $task_id,
  9373. 'img_url' => $img_url
  9374. ]);
  9375. } elseif ($task->status === 'failed') {
  9376. // 更新资产表状态
  9377. DB::table('mp_products')
  9378. ->where('id', $product->id)
  9379. ->update([
  9380. 'pic_task_status' => '生成失败',
  9381. 'updated_at' => now()
  9382. ]);
  9383. $stats[$typeName]['completed']++;
  9384. $hasStatusChange = true;
  9385. dLog('anime')->warning('资产图片生成失败', [
  9386. 'product_id' => $product->id,
  9387. 'task_id' => $task_id,
  9388. 'error' => $task->error_message ?? '未知错误'
  9389. ]);
  9390. } else {
  9391. // 任务还在处理中
  9392. $allCompleted = false;
  9393. }
  9394. } else {
  9395. // 任务不存在,标记为失败
  9396. DB::table('mp_products')
  9397. ->where('id', $product->id)
  9398. ->update([
  9399. 'pic_task_status' => '生成失败',
  9400. 'updated_at' => now()
  9401. ]);
  9402. $stats[$typeName]['completed']++;
  9403. $hasStatusChange = true;
  9404. dLog('anime')->error('图片生成任务不存在', [
  9405. 'product_id' => $product->id,
  9406. 'task_id' => $task_id
  9407. ]);
  9408. }
  9409. } elseif ($currentStatus === '生成成功') {
  9410. $stats[$typeName]['success']++;
  9411. $stats[$typeName]['completed']++;
  9412. } elseif ($currentStatus === '生成失败') {
  9413. $stats[$typeName]['completed']++;
  9414. } else {
  9415. // 其他状态也认为未完成
  9416. $allCompleted = false;
  9417. }
  9418. }
  9419. // 移除没有数据的类型(total=0)
  9420. foreach ($stats as $typeName => $stat) {
  9421. if ($stat['total'] === 0) {
  9422. unset($stats[$typeName]);
  9423. }
  9424. }
  9425. // 如果有状态变化,发送 SSE 更新
  9426. if ($hasStatusChange) {
  9427. $eventType = $allCompleted ? 'complete' : 'update';
  9428. $response = [
  9429. 'type' => $eventType,
  9430. 'script_id' => $script_id,
  9431. 'script_name' => $script_name,
  9432. 'stats' => $stats,
  9433. 'timestamp' => date('Y-m-d H:i:s')
  9434. ];
  9435. if ($taskCenterId) {
  9436. $response['task_center_id'] = $taskCenterId;
  9437. }
  9438. if ($eventType === 'complete') {
  9439. $response = array_merge($response, $completeExtra);
  9440. }
  9441. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9442. dLog('anime')->info('SSE更新', [
  9443. 'event_type' => $eventType,
  9444. 'script_id' => $script_id,
  9445. 'script_name' => $script_name,
  9446. 'stats' => $stats
  9447. ]);
  9448. if ($allCompleted) {
  9449. dLog('anime')->info('所有资产图片生成任务已完成', [
  9450. 'script_id' => $script_id,
  9451. 'script_name' => $script_name,
  9452. 'stats' => $stats
  9453. ]);
  9454. // 全部任务完成,更新任务中心状态和结果
  9455. $this->finishScriptProductTask($taskCenterId, $response);
  9456. break;
  9457. }
  9458. }
  9459. }
  9460. // 超时处理
  9461. if (time() - $startTime >= $timeout && !$allCompleted) {
  9462. $response = [
  9463. 'type' => 'timeout',
  9464. 'message' => '部分任务超时,请稍后查看结果',
  9465. 'script_id' => $script_id,
  9466. 'script_name' => $script_name,
  9467. 'timestamp' => date('Y-m-d H:i:s')
  9468. ];
  9469. if ($taskCenterId) {
  9470. $response['task_center_id'] = $taskCenterId;
  9471. }
  9472. $response = array_merge($response, $completeExtra);
  9473. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  9474. dLog('anime')->warning('资产图片生成任务超时', [
  9475. 'script_id' => $script_id,
  9476. 'script_name' => $script_name,
  9477. 'timeout' => $timeout
  9478. ]);
  9479. // 超时未完成,更新任务中心状态和结果
  9480. $this->finishScriptProductTask($taskCenterId, $response, true);
  9481. }
  9482. }
  9483. /**
  9484. * 定时任务:检查产品图片生成任务状态并更新产品记录
  9485. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  9486. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  9487. *
  9488. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  9489. */
  9490. public function checkProductPicTasks() {
  9491. // 查询所有生成中的产品图片任务
  9492. $products = DB::table('mp_products')
  9493. ->whereNotNull('pic_task_id')
  9494. ->where('pic_task_status', '生成中')
  9495. ->where('is_deleted', 0)
  9496. ->get();
  9497. $stats = [
  9498. 'total' => $products->count(),
  9499. 'success' => 0,
  9500. 'failed' => 0,
  9501. 'pending' => 0,
  9502. ];
  9503. foreach ($products as $product) {
  9504. try {
  9505. $task_id = $product->pic_task_id;
  9506. // 通过 pic_task_id 查询图片生成任务结果
  9507. $task = DB::table('mp_generate_pic_tasks')
  9508. ->where('id', $task_id)
  9509. ->first();
  9510. if ($task) {
  9511. if ($task->status === 'success' && $task->result_url) {
  9512. // 解析图片URL
  9513. $result_urls = $task->result_url;
  9514. if (is_string($result_urls)) {
  9515. $result_urls = json_decode($result_urls, true);
  9516. }
  9517. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  9518. // 更新资产表状态
  9519. DB::table('mp_products')
  9520. ->where('id', $product->id)
  9521. ->update([
  9522. 'pic_task_status' => '生成成功',
  9523. 'url' => $img_url,
  9524. 'updated_at' => now()
  9525. ]);
  9526. $stats['success']++;
  9527. dLog('anime')->info('资产图片生成成功', [
  9528. 'product_id' => $product->id,
  9529. 'task_id' => $task_id,
  9530. 'img_url' => $img_url
  9531. ]);
  9532. } elseif ($task->status === 'failed') {
  9533. // 更新资产表状态
  9534. DB::table('mp_products')
  9535. ->where('id', $product->id)
  9536. ->update([
  9537. 'pic_task_status' => '生成失败',
  9538. 'updated_at' => now()
  9539. ]);
  9540. $stats['failed']++;
  9541. dLog('anime')->warning('资产图片生成失败', [
  9542. 'product_id' => $product->id,
  9543. 'task_id' => $task_id,
  9544. 'error' => $task->error_message ?? '未知错误'
  9545. ]);
  9546. } else {
  9547. // 任务还在处理中
  9548. $stats['pending']++;
  9549. }
  9550. } else {
  9551. // 任务不存在,标记为失败
  9552. DB::table('mp_products')
  9553. ->where('id', $product->id)
  9554. ->update([
  9555. 'pic_task_status' => '生成失败',
  9556. 'updated_at' => now()
  9557. ]);
  9558. $stats['failed']++;
  9559. dLog('anime')->error('图片生成任务不存在', [
  9560. 'product_id' => $product->id,
  9561. 'task_id' => $task_id
  9562. ]);
  9563. }
  9564. } catch (\Exception $e) {
  9565. dLog('anime')->error('检查产品图片生成任务异常', [
  9566. 'product_id' => $product->id,
  9567. 'task_id' => $product->pic_task_id ?? null,
  9568. 'error' => $e->getMessage()
  9569. ]);
  9570. }
  9571. }
  9572. return $stats;
  9573. }
  9574. /**
  9575. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  9576. *
  9577. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  9578. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  9579. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  9580. *
  9581. * @return int 更新的任务中心记录数
  9582. */
  9583. public function checkSaveScriptProductTaskCenters() {
  9584. $updated = 0;
  9585. // 只扫描尚未结束的 saveScriptProducts 任务
  9586. $tasks = DB::table('mp_task_center')
  9587. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  9588. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  9589. ->orderBy('id', 'desc')
  9590. ->limit(500)
  9591. ->get();
  9592. // 与 pollProductImageTasks 保持一致的类型名称映射
  9593. $typeNames = [
  9594. 1 => 'roles', // 角色
  9595. 2 => 'scenes', // 场景
  9596. 3 => 'props', // 道具
  9597. ];
  9598. foreach ($tasks as $task) {
  9599. try {
  9600. $taskParams = json_decode((string)$task->params, true);
  9601. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  9602. if (!$script_id) {
  9603. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  9604. 'task_center_id' => $task->id,
  9605. ]);
  9606. continue;
  9607. }
  9608. // 获取该剧本关联的全部资产ID
  9609. $productIds = DB::table('mp_script_product_mappings')
  9610. ->where('script_id', $script_id)
  9611. ->pluck('product_id')
  9612. ->unique()
  9613. ->toArray();
  9614. if (empty($productIds)) {
  9615. // 剧本没有关联资产,不视为完成,等待下一次检查
  9616. continue;
  9617. }
  9618. $products = DB::table('mp_products')
  9619. ->whereIn('id', $productIds)
  9620. ->where('is_deleted', 0)
  9621. ->get();
  9622. $stats = [];
  9623. $allCompleted = true;
  9624. foreach ($products as $product) {
  9625. $typeName = $typeNames[$product->product] ?? 'unknown';
  9626. if (!isset($stats[$typeName])) {
  9627. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  9628. }
  9629. $stats[$typeName]['total']++;
  9630. if ($product->pic_task_status === '生成成功') {
  9631. $stats[$typeName]['success']++;
  9632. $stats[$typeName]['completed']++;
  9633. } elseif ($product->pic_task_status === '生成失败') {
  9634. $stats[$typeName]['completed']++;
  9635. } else {
  9636. // 仍有资产在生成中或未生成,任务未完成
  9637. $allCompleted = false;
  9638. }
  9639. }
  9640. if (!$allCompleted) {
  9641. continue;
  9642. }
  9643. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  9644. $script = DB::table('mp_scripts')
  9645. ->where('id', $script_id)
  9646. ->where('is_deleted', 0)
  9647. ->first();
  9648. $script_name = $script->script_name ?? 'script_' . $script_id;
  9649. $this->finishScriptProductTask($task->id, [
  9650. 'type' => 'complete',
  9651. 'script_id' => $script_id,
  9652. 'script_name' => $script_name,
  9653. 'stats' => $stats,
  9654. 'timestamp' => date('Y-m-d H:i:s'),
  9655. 'task_center_id' => (int)$task->id,
  9656. ]);
  9657. $updated++;
  9658. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  9659. 'task_center_id' => $task->id,
  9660. 'script_id' => $script_id,
  9661. 'stats' => $stats,
  9662. ]);
  9663. } catch (\Exception $e) {
  9664. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  9665. 'task_center_id' => $task->id,
  9666. 'error' => $e->getMessage(),
  9667. ]);
  9668. }
  9669. }
  9670. return $updated;
  9671. }
  9672. /**
  9673. * 获取剧本关联的资产列表
  9674. * @param array $data 请求参数
  9675. * @return array
  9676. */
  9677. public function getScriptProducts($data) {
  9678. $uid = Site::getUid();
  9679. $cpid = Site::getCpid();
  9680. $script_id = getProp($data, 'script_id');
  9681. $episode_number = getProp($data, 'episode_number');
  9682. if (!$script_id) {
  9683. Utils::throwError('20003:请提供剧本ID');
  9684. }
  9685. // 验证剧本是否存在
  9686. $script = DB::table('mp_scripts')
  9687. ->where('id', $script_id)
  9688. ->where('is_deleted', 0)
  9689. ->first();
  9690. if (!$script) {
  9691. Utils::throwError('20003:剧本不存在');
  9692. }
  9693. // 联表查询资产信息
  9694. $query = DB::table('mp_script_product_mappings as mapping')
  9695. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9696. ->where('mapping.script_id', $script_id)
  9697. ->where('product.cpid', $cpid)
  9698. ->where('product.is_deleted', 0);
  9699. // 如果提供了 episode_number,则过滤指定集数
  9700. if ($episode_number !== null && $episode_number !== '') {
  9701. $query->where('mapping.episode_number', $episode_number);
  9702. }
  9703. $mappings = $query->select(
  9704. 'mapping.script_id',
  9705. 'mapping.product_id',
  9706. 'mapping.episode_number',
  9707. 'product.product_name',
  9708. 'product.type',
  9709. 'product.product',
  9710. 'product.pic_prompt',
  9711. 'product.url',
  9712. 'product.pic_task_id',
  9713. 'product.pic_task_status',
  9714. 'product.three_view_image_url',
  9715. 'product.timbre_url',
  9716. 'mapping.created_at'
  9717. )
  9718. ->orderBy('mapping.product_id', 'asc')
  9719. ->orderBy('mapping.episode_number', 'asc')
  9720. ->get();
  9721. // 按 product_id 分组,合并 episode_number
  9722. $productMap = [];
  9723. foreach ($mappings as $item) {
  9724. $product_id = $item->product_id;
  9725. if (!isset($productMap[$product_id])) {
  9726. $productMap[$product_id] = [
  9727. 'product_id' => $product_id,
  9728. 'product_name' => $item->product_name,
  9729. 'type' => (int)$item->type,
  9730. 'product' => (int)$item->product,
  9731. 'pic_prompt' => $item->pic_prompt,
  9732. 'url' => $item->url,
  9733. 'timbre_url' => $item->timbre_url,
  9734. 'pic_task_id' => $item->pic_task_id,
  9735. 'pic_task_status' => $item->pic_task_status,
  9736. 'episode_numbers' => [],
  9737. 'created_at' => $item->created_at,
  9738. ];
  9739. }
  9740. // 添加 episode_number(去重)
  9741. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  9742. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  9743. }
  9744. }
  9745. // 按类型分组
  9746. $roles = []; // type=1 角色/主体
  9747. $scenes = []; // type=2 场景
  9748. $props = []; // type=3 道具
  9749. foreach ($productMap as $product) {
  9750. // 将 episode_numbers 数组转换为逗号分隔的字符串
  9751. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  9752. // 构造返回数据
  9753. $productData = [
  9754. 'product_id' => $product['product_id'],
  9755. 'product_name' => $product['product_name'],
  9756. 'product' => $product['product'],
  9757. 'pic_prompt' => $product['pic_prompt'],
  9758. 'url' => $product['url'],
  9759. 'timbre_url' => $product['timbre_url'] ?? '',
  9760. 'pic_task_id' => $product['pic_task_id'],
  9761. 'pic_task_status' => $product['pic_task_status'],
  9762. 'episode_numbers' => $episodeNumbersStr,
  9763. 'created_at' => $product['created_at'],
  9764. ];
  9765. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  9766. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  9767. switch ($product['product']) {
  9768. case 1:
  9769. $roles[] = $productData;
  9770. break;
  9771. case 2:
  9772. $scenes[] = $productData;
  9773. break;
  9774. case 3:
  9775. $props[] = $productData;
  9776. break;
  9777. }
  9778. }
  9779. return [
  9780. 'script_id' => $script_id,
  9781. 'script_name' => $script->script_name ?? '',
  9782. 'roles' => $roles, // 主体
  9783. 'scenes' => $scenes, // 场景
  9784. 'props' => $props, // 道具
  9785. ];
  9786. }
  9787. /**
  9788. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  9789. * @param string $actContent 原始内容
  9790. * @param array $products 产品数组(包含product_name和url)
  9791. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  9792. */
  9793. /**
  9794. * 根据片段内容与资产构建提示词、参考图、参考音频
  9795. *
  9796. * @param string $actContent 片段内容
  9797. * @param array $products 资产数组(角色/场景/道具)
  9798. * @param bool $supportAudioReference 模型是否支持参考音频;支持时角色音色优先使用 timbre_url
  9799. * @return array
  9800. */
  9801. public function processActContentWithProducts($actContent, $products, $supportAudioReference = false, $allowedAudioProducts = null, $allowedImageProducts = null) {
  9802. if (empty($actContent) || empty($products)) {
  9803. return [
  9804. 'content' => $actContent,
  9805. 'reference_images' => [],
  9806. 'reference_images_all' => [],
  9807. 'reference_audios' => [],
  9808. 'audio_voice_fallbacks' => []
  9809. ];
  9810. }
  9811. // 构建产品名称到产品信息的映射
  9812. $product_dict = [];
  9813. foreach ($products as $product) {
  9814. $product_name = getProp($product, 'product_name');
  9815. if ($product_name) {
  9816. $product_dict[$product_name] = [
  9817. // 优先使用三视图图片作为素材/参考图,否则使用原图 url
  9818. 'url' => getProp($product, 'three_view_image_url') ?: getProp($product, 'url'),
  9819. 'voice_prompt' => getProp($product, 'voice_prompt'),
  9820. // 角色音色参考音频(选填),有值时优先于 voice_prompt
  9821. 'timbre_url' => trim((string)getProp($product, 'timbre_url', '')),
  9822. 'product' => (int)getProp($product, 'product', 1)
  9823. ];
  9824. }
  9825. }
  9826. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  9827. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  9828. $reference_images = [];
  9829. $reference_images_all = []; // 正文中出现且有图的资产图(不受模型上限影响,用于任务记录)
  9830. $product_index_map = []; // 产品名称 => 图片序号的映射
  9831. $reference_audios = [];
  9832. $product_audio_index_map = []; // 产品名称 => 音频序号的映射(与图片序号互相独立)
  9833. $audio_voice_fallbacks = []; // 产品名称 => voice_prompt(参考音频素材不可用时兜底使用)
  9834. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  9835. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  9836. $current_index = 1;
  9837. $current_audio_index = 1;
  9838. if (!empty($matches[1])) {
  9839. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  9840. $seen_products = []; // 用于去重
  9841. foreach ($matches[1] as $product_name) {
  9842. // 跳过已处理的产品
  9843. if (isset($seen_products[$product_name])) {
  9844. continue;
  9845. }
  9846. $seen_products[$product_name] = true;
  9847. // 检查产品是否在字典中
  9848. if (isset($product_dict[$product_name])) {
  9849. $url = $product_dict[$product_name]['url'];
  9850. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  9851. $timbre_url = $product_dict[$product_name]['timbre_url'];
  9852. // 判断该角色的参考音频是否可用(模型支持 + 配置了音色 + 未超出模型段数/时长限制)
  9853. $audio_allowed = $supportAudioReference && !empty($timbre_url);
  9854. if ($audio_allowed && is_array($allowedAudioProducts)) {
  9855. $audio_allowed = isset($allowedAudioProducts[$product_name])
  9856. && $allowedAudioProducts[$product_name] === $timbre_url;
  9857. }
  9858. // 分配音频序号(与图片序号互相独立;相同音频URL复用同一序号,保证角色与音频一一对应)
  9859. if ($audio_allowed) {
  9860. if (!in_array($timbre_url, $reference_audios)) {
  9861. $reference_audios[] = $timbre_url;
  9862. $product_audio_index_map[$product_name] = $current_audio_index;
  9863. $current_audio_index++;
  9864. } else {
  9865. $existing_audio_index = array_search($timbre_url, $reference_audios) + 1;
  9866. $product_audio_index_map[$product_name] = $existing_audio_index;
  9867. }
  9868. // 记录该角色的音色提示词:参考音频素材不可用时用它兜底(无提示词时记录空串,用于清理残留说明行)
  9869. $audio_voice_fallbacks[$product_name] = $voice_prompt ?? '';
  9870. }
  9871. // 处理voice_prompt:有可用参考音频的角色优先使用音频,不再输出音色提示词(旁白是公共的在后面单独处理)
  9872. if (!$audio_allowed && !empty($voice_prompt) && $product_name !== '旁白') {
  9873. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  9874. }
  9875. // 只有URL非空且未被模型参考图上限截断,才分配序号并加入参考图片
  9876. if (!empty($url)) {
  9877. // 任务记录用:正文中出现且有图的资产图全部记录(不受模型上限影响)
  9878. if (!in_array($url, $reference_images_all)) {
  9879. $reference_images_all[] = $url;
  9880. }
  9881. $image_allowed = true;
  9882. if (is_array($allowedImageProducts)) {
  9883. $image_allowed = isset($allowedImageProducts[$product_name])
  9884. && $allowedImageProducts[$product_name] === $url;
  9885. }
  9886. if (!$image_allowed) {
  9887. // 超出模型参考图上限的资产不分配序号,提示词中不会出现<图片N>
  9888. $product_index_map[$product_name] = 0;
  9889. } elseif (!in_array($url, $reference_images)) {
  9890. $reference_images[] = $url;
  9891. $product_index_map[$product_name] = $current_index;
  9892. $current_index++;
  9893. } else {
  9894. // URL重复,找到已有的序号
  9895. $existing_index = array_search($url, $reference_images) + 1;
  9896. $product_index_map[$product_name] = $existing_index;
  9897. }
  9898. } else {
  9899. // URL为空,不分配序号(后续直接去掉{})
  9900. $product_index_map[$product_name] = 0;
  9901. }
  9902. } else {
  9903. // 产品不在字典中,不分配序号
  9904. $product_index_map[$product_name] = 0;
  9905. }
  9906. }
  9907. }
  9908. // 第二步:替换内容中的 {产品名称}
  9909. $processedContent = $actContent;
  9910. foreach ($product_index_map as $product_name => $index) {
  9911. $escaped_name = preg_quote($product_name, '/');
  9912. if ($index > 0) {
  9913. // 有图片,替换为:产品名称<图片X>
  9914. $replacement = $product_name . '<图片' . $index . '>';
  9915. } else {
  9916. // 无图片,只保留产品名称
  9917. $replacement = $product_name;
  9918. }
  9919. // 有参考音频的角色追加音频标记(如 角色A<图片1><音频1>),保证角色与音频一一对应
  9920. $audio_index = $product_audio_index_map[$product_name] ?? 0;
  9921. if ($audio_index > 0) {
  9922. $replacement .= '<音频' . $audio_index . '>';
  9923. }
  9924. // 替换所有 {产品名称} 为处理后的格式
  9925. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  9926. }
  9927. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  9928. foreach ($products as $product) {
  9929. $product_name = getProp($product, 'product_name');
  9930. $voice_prompt = getProp($product, 'voice_prompt');
  9931. if ($product_name === '旁白' && !empty($voice_prompt) && empty($product_audio_index_map['旁白'])) {
  9932. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  9933. break; // 找到旁白后退出循环
  9934. }
  9935. }
  9936. // 第四步:将参考音频音色信息和voice_prompt信息添加到内容最前面
  9937. $voice_prompt_prefix = '';
  9938. // 有参考音频的角色:按官方推荐句式"参考<音频N>中的音色"声明对应关系,
  9939. // 素材上传失败时与正文标记一起被清理/重排,保证角色与音频始终对应
  9940. foreach ($product_audio_index_map as $product_name => $audio_index) {
  9941. $voice_prompt_prefix .= '参考<音频' . $audio_index . '>中的音色,为' . $product_name . '配音' . "\n";
  9942. }
  9943. if (!empty($voice_prompts)) {
  9944. $voice_prompt_prefix .= implode('', $voice_prompts);
  9945. }
  9946. // 旁白的voice_prompt放在最后
  9947. if (!empty($narrator_voice_prompt)) {
  9948. $voice_prompt_prefix .= $narrator_voice_prompt;
  9949. }
  9950. // 如果有voice_prompt信息,添加到内容开头
  9951. if (!empty($voice_prompt_prefix)) {
  9952. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  9953. }
  9954. return [
  9955. 'content' => $processedContent,
  9956. 'reference_images' => $reference_images,
  9957. 'reference_images_all' => $reference_images_all,
  9958. 'reference_audios' => $reference_audios,
  9959. 'audio_voice_fallbacks' => $audio_voice_fallbacks
  9960. ];
  9961. }
  9962. /**
  9963. * 用剧本资产关联(mappings)的数据补齐资产数组
  9964. * 批量转视频时资产取值的优先级:剧本资产关联(mappings) > extra_products > 剧集单独设置
  9965. * 资产库对应字段为空时不覆盖,避免把分集里的有效数据清空
  9966. *
  9967. * @param array $products 资产数组
  9968. * @param int $script_id 剧本ID
  9969. * @param bool $overwrite 资产库有值时是否覆盖数组中的已有值(true 表示 mappings 优先级最高)
  9970. * @return array
  9971. */
  9972. public function fillProductsFromMapping($products, $script_id, $overwrite = false) {
  9973. if (empty($products) || !$script_id) {
  9974. return $products;
  9975. }
  9976. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  9977. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9978. ->where('mapping.script_id', $script_id)
  9979. ->where('product.is_deleted', 0)
  9980. ->select(
  9981. 'mapping.product_id',
  9982. 'product.product_name',
  9983. 'product.product',
  9984. 'product.pic_prompt',
  9985. 'product.url',
  9986. 'product.three_view_image_url',
  9987. 'product.timbre_url'
  9988. )
  9989. ->get();
  9990. if ($mappingItems->isEmpty()) {
  9991. return $products;
  9992. }
  9993. $mappingMap = [];
  9994. foreach ($mappingItems as $item) {
  9995. $normalized_name = $this->normalizeProductName($item->product_name);
  9996. if ($normalized_name === '' || isset($mappingMap[$normalized_name])) {
  9997. continue;
  9998. }
  9999. // 资产库字段有值才纳入覆盖范围(三视图、音色等为选填,可能为空)
  10000. $mappingProduct = [];
  10001. if (!empty($item->product_id)) {
  10002. $mappingProduct['product_id'] = (int)$item->product_id;
  10003. }
  10004. if (!empty($item->product)) {
  10005. $mappingProduct['product'] = (int)$item->product;
  10006. }
  10007. if (!empty($item->pic_prompt)) {
  10008. $mappingProduct['pic_prompt'] = $item->pic_prompt;
  10009. }
  10010. if (!empty($item->url)) {
  10011. $mappingProduct['url'] = $item->url;
  10012. }
  10013. if (!empty($item->three_view_image_url)) {
  10014. $mappingProduct['three_view_image_url'] = $item->three_view_image_url;
  10015. }
  10016. if (!empty($item->timbre_url)) {
  10017. $mappingProduct['timbre_url'] = $item->timbre_url;
  10018. }
  10019. if (!empty($mappingProduct)) {
  10020. $mappingMap[$normalized_name] = $mappingProduct;
  10021. }
  10022. }
  10023. if (empty($mappingMap)) {
  10024. return $products;
  10025. }
  10026. foreach ($products as &$product) {
  10027. $normalized_name = $this->normalizeProductName(getProp($product, 'product_name'));
  10028. if ($normalized_name === '' || empty($mappingMap[$normalized_name])) {
  10029. continue;
  10030. }
  10031. foreach ($mappingMap[$normalized_name] as $key => $value) {
  10032. // 不覆盖模式:只补齐数组中缺失的字段
  10033. if (!$overwrite && !empty(getProp($product, $key))) {
  10034. continue;
  10035. }
  10036. $product[$key] = $value;
  10037. }
  10038. }
  10039. unset($product);
  10040. return $products;
  10041. }
  10042. /**
  10043. * 资产名称归一化(去掉首尾空白、方括号、花括号等符号)
  10044. *
  10045. * @param string $name
  10046. * @return string
  10047. */
  10048. private function normalizeProductName($name) {
  10049. return trim(preg_replace(
  10050. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  10051. '',
  10052. trim((string)$name)
  10053. ));
  10054. }
  10055. /**
  10056. * 是否启用参考音频(角色音色)
  10057. * 优先取调用方传入的 enable_reference_audio,未传时读取环境变量 ENABLE_REFERENCE_AUDIO,默认开启
  10058. *
  10059. * @param array $data 调用方入参
  10060. * @return bool
  10061. */
  10062. public function isReferenceAudioEnabled($data) {
  10063. // 环境变量兜底:兼容 true/false/1/0/on/off/yes/no 等写法,无法识别时按默认开启
  10064. $envValue = env('ENABLE_REFERENCE_AUDIO', true);
  10065. $envDefault = is_bool($envValue)
  10066. ? $envValue
  10067. : filter_var($envValue, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
  10068. if ($envDefault === null) {
  10069. $envDefault = true;
  10070. }
  10071. $value = getProp($data, 'enable_reference_audio', null);
  10072. if ($value === null || $value === '') {
  10073. return $envDefault;
  10074. }
  10075. $bool = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
  10076. return $bool === null ? $envDefault : $bool;
  10077. }
  10078. /**
  10079. * 判断视频模型是否支持角色参考音频(音色)
  10080. * 目前支持:智帧统一API、Seedance 2.0 系列(国内百度/海外百度/快快AI)
  10081. *
  10082. * @param string $model
  10083. * @return bool
  10084. */
  10085. public function isActReferenceAudioSupported($model) {
  10086. if (!$model) {
  10087. return false;
  10088. }
  10089. return strpos($model, 'zhizhen') !== false || $this->isSeedance20SeriesModel($model);
  10090. }
  10091. /**
  10092. * 获取模型对参考图片的数量上限
  10093. * Seedance 2.0(含 2.0 mini/fast)与智帧:9 张;Seedance 2.5:30 张
  10094. *
  10095. * @param string $model
  10096. * @return int 0 表示该模型不走参考图逻辑(不做限制)
  10097. */
  10098. public function getActReferenceImageLimit($model) {
  10099. if (!$this->isActReferenceAudioSupported($model)) {
  10100. return 0;
  10101. }
  10102. if (strpos($model, '2.5') !== false || strpos($model, '2-5') !== false) {
  10103. return 30;
  10104. }
  10105. return 9;
  10106. }
  10107. /**
  10108. * 生成提示词之前解析可用的资产参考图
  10109. * 按正文中{资产名}首次出现的顺序取有图片的资产(相同图片URL复用同一编号);
  10110. * 超过模型上限的资产不分配图片编号,提示词中也不会出现<图片N>引用
  10111. * 调用方显式传入的 reference_images 不占用这里的额度,由调用方按剩余额度补充
  10112. *
  10113. * @param string $actContent 片段内容
  10114. * @param array $products 资产数组
  10115. * @param string $model 视频模型
  10116. * @return array ['allowed' => [产品名 => 图片URL], 'excluded' => [产品名 => 原因], 'limit' => 上限]
  10117. */
  10118. public function resolveActReferenceImages($actContent, $products, $model) {
  10119. $result = ['allowed' => [], 'excluded' => [], 'limit' => 0];
  10120. $limit = $this->getActReferenceImageLimit($model);
  10121. if ($limit <= 0 || empty($actContent) || empty($products)) {
  10122. return $result;
  10123. }
  10124. $result['limit'] = $limit;
  10125. // 产品名 => 图片(优先三视图,其次原图)
  10126. $imageMap = [];
  10127. foreach ($products as $product) {
  10128. $name = getProp($product, 'product_name');
  10129. if (!$name) {
  10130. continue;
  10131. }
  10132. $url = trim((string)(getProp($product, 'three_view_image_url') ?: getProp($product, 'url')));
  10133. if ($url !== '') {
  10134. $imageMap[$name] = $url;
  10135. }
  10136. }
  10137. if (empty($imageMap)) {
  10138. return $result;
  10139. }
  10140. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  10141. $orderedNames = [];
  10142. foreach (($matches[1] ?? []) as $name) {
  10143. if (!isset($orderedNames[$name])) {
  10144. $orderedNames[$name] = true;
  10145. }
  10146. }
  10147. $usedUrls = [];
  10148. foreach (array_keys($orderedNames) as $name) {
  10149. $url = $imageMap[$name] ?? '';
  10150. if ($url === '') {
  10151. continue;
  10152. }
  10153. // 相同图片复用同一编号,不重复计数
  10154. if (isset($usedUrls[$url])) {
  10155. $result['allowed'][$name] = $url;
  10156. continue;
  10157. }
  10158. if (count($usedUrls) >= $limit) {
  10159. $result['excluded'][$name] = '超过参考图数量上限(' . $limit . '张)';
  10160. continue;
  10161. }
  10162. $usedUrls[$url] = true;
  10163. $result['allowed'][$name] = $url;
  10164. }
  10165. if (!empty($result['excluded'])) {
  10166. dLog('anime')->info('资产参考图超出模型限制,已截断', [
  10167. 'model' => $model,
  10168. 'limit' => $limit,
  10169. 'allowed' => array_keys($result['allowed']),
  10170. 'excluded' => $result['excluded'],
  10171. ]);
  10172. }
  10173. return $result;
  10174. }
  10175. /**
  10176. * 获取模型对参考音频的限制
  10177. * Seedance 2.0(含 2.0 lite / 2.0 fast):最多3段,单个[2,15]s,总时长不超过15s
  10178. * Seedance 2.5:最多10段,单个[2,30]s,总时长不超过30s
  10179. *
  10180. * @param string $model
  10181. * @return array|null 非参考音频模型返回 null
  10182. */
  10183. public function getActAudioLimits($model) {
  10184. if (!$this->isActReferenceAudioSupported($model)) {
  10185. return null;
  10186. }
  10187. if (strpos($model, '2.5') !== false || strpos($model, '2-5') !== false) {
  10188. return ['max_count' => 10, 'max_single' => 30, 'max_total' => 30];
  10189. }
  10190. return ['max_count' => 3, 'max_single' => 15, 'max_total' => 15];
  10191. }
  10192. /**
  10193. * 生成提示词之前解析可用的参考音频
  10194. * 按正文中{资产名}首次出现的顺序,逐个校验单个音频时长、段数与总时长,超出限制的部分直接截断;
  10195. * 被截断(或单个时长超限)的角色不会出现在提示词的<音频N>引用中,会自动回退使用音色提示词
  10196. *
  10197. * @param string $actContent 片段内容
  10198. * @param array $products 资产数组
  10199. * @param string $model 视频模型
  10200. * @return array ['allowed' => [产品名 => 音频URL], 'excluded' => [产品名 => 原因], 'total_duration' => 秒]
  10201. */
  10202. public function resolveActReferenceAudios($actContent, $products, $model) {
  10203. $result = ['allowed' => [], 'excluded' => [], 'total_duration' => 0];
  10204. $limits = $this->getActAudioLimits($model);
  10205. if (!$limits || empty($actContent) || empty($products)) {
  10206. return $result;
  10207. }
  10208. // 产品名 => 音色音频
  10209. $timbreMap = [];
  10210. foreach ($products as $product) {
  10211. $name = getProp($product, 'product_name');
  10212. if (!$name) {
  10213. continue;
  10214. }
  10215. $timbre = trim((string)getProp($product, 'timbre_url', ''));
  10216. if ($timbre !== '') {
  10217. $timbreMap[$name] = $timbre;
  10218. }
  10219. }
  10220. if (empty($timbreMap)) {
  10221. return $result;
  10222. }
  10223. // 按正文中{资产名}首次出现的顺序确定音频编号顺序(与提示词生成保持一致)
  10224. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  10225. $orderedNames = [];
  10226. foreach (($matches[1] ?? []) as $name) {
  10227. if (!isset($orderedNames[$name])) {
  10228. $orderedNames[$name] = true;
  10229. }
  10230. }
  10231. $usedUrls = [];
  10232. $totalDuration = 0;
  10233. foreach (array_keys($orderedNames) as $name) {
  10234. $timbre = $timbreMap[$name] ?? '';
  10235. if ($timbre === '') {
  10236. continue;
  10237. }
  10238. // 相同音频复用同一段素材,不重复计数
  10239. if (isset($usedUrls[$timbre])) {
  10240. $result['allowed'][$name] = $timbre;
  10241. continue;
  10242. }
  10243. $duration = $this->getRemoteAudioDurationSeconds($timbre);
  10244. if ($duration > 0 && $duration > $limits['max_single']) {
  10245. $result['excluded'][$name] = '单个音频时长超限(' . $duration . 's > ' . $limits['max_single'] . 's)';
  10246. continue;
  10247. }
  10248. if (count($usedUrls) >= $limits['max_count']) {
  10249. $result['excluded'][$name] = '超过参考音频段数上限(' . $limits['max_count'] . '段)';
  10250. continue;
  10251. }
  10252. if ($duration > 0 && ($totalDuration + $duration) > $limits['max_total']) {
  10253. $result['excluded'][$name] = '超过参考音频总时长上限(' . $limits['max_total'] . 's)';
  10254. continue;
  10255. }
  10256. $usedUrls[$timbre] = true;
  10257. $totalDuration += max(0, $duration);
  10258. $result['allowed'][$name] = $timbre;
  10259. }
  10260. $result['total_duration'] = round($totalDuration, 2);
  10261. if (!empty($result['excluded'])) {
  10262. dLog('anime')->info('参考音频超出模型限制,已截断', [
  10263. 'model' => $model,
  10264. 'limits' => $limits,
  10265. 'allowed' => array_keys($result['allowed']),
  10266. 'excluded' => $result['excluded'],
  10267. 'total_duration' => $result['total_duration'],
  10268. ]);
  10269. }
  10270. return $result;
  10271. }
  10272. /**
  10273. * 探测远程音频时长(wav 精确解析;mp3 按首帧码率估算)
  10274. *
  10275. * @param string $url 音频URL
  10276. * @return float 秒;无法探测时返回 0
  10277. */
  10278. public function getRemoteAudioDurationSeconds($url) {
  10279. try {
  10280. // 使用 Guzzle(不依赖 allow_url_fopen,LNMP 环境下同样可用)
  10281. $client = new \GuzzleHttp\Client(['verify' => false, 'timeout' => 20, 'connect_timeout' => 10]);
  10282. $response = $client->get($url, [
  10283. 'headers' => ['Range' => 'bytes=0-1048575'],
  10284. 'http_errors' => false,
  10285. ]);
  10286. $data = (string)$response->getBody();
  10287. if (strlen($data) < 64) {
  10288. return 0;
  10289. }
  10290. // 文件总大小:206 时取 Content-Range 的分母,否则用 Content-Length
  10291. $totalSize = 0;
  10292. $contentRange = $response->getHeaderLine('Content-Range');
  10293. if ($contentRange !== '' && preg_match('#/(\d+)#', $contentRange, $m)) {
  10294. $totalSize = (int)$m[1];
  10295. } else {
  10296. $contentLength = $response->getHeaderLine('Content-Length');
  10297. if ($contentLength !== '') {
  10298. $totalSize = (int)$contentLength;
  10299. }
  10300. }
  10301. // WAV:解析 fmt/data chunk 精确计算
  10302. if (substr($data, 0, 4) === 'RIFF' && substr($data, 8, 4) === 'WAVE') {
  10303. $offset = 12;
  10304. $byteRate = 0;
  10305. $dataSize = 0;
  10306. while ($offset + 8 <= strlen($data)) {
  10307. $chunkId = substr($data, $offset, 4);
  10308. $chunkSize = unpack('V', substr($data, $offset + 4, 4))[1];
  10309. if ($chunkId === 'fmt ' && $offset + 8 + 12 <= strlen($data)) {
  10310. $byteRate = unpack('V', substr($data, $offset + 16, 4))[1];
  10311. } elseif ($chunkId === 'data') {
  10312. $dataSize = $chunkSize;
  10313. break;
  10314. }
  10315. $offset += 8 + $chunkSize + ($chunkSize % 2);
  10316. }
  10317. if ($byteRate > 0 && $dataSize > 0) {
  10318. return round($dataSize / $byteRate, 2);
  10319. }
  10320. return 0;
  10321. }
  10322. // MP3:优先 Xing/Info 帧数,其次逐帧统计,最后按码率估算
  10323. $scanStart = 0;
  10324. if (strlen($data) >= 10 && substr($data, 0, 3) === 'ID3') {
  10325. // 跳过 ID3v2 标签,避免命中标签数据中的伪同步字
  10326. $tagSize = ((ord($data[6]) & 0x7F) << 21) | ((ord($data[7]) & 0x7F) << 14)
  10327. | ((ord($data[8]) & 0x7F) << 7) | (ord($data[9]) & 0x7F);
  10328. $scanStart = 10 + $tagSize;
  10329. }
  10330. $mpeg1Layer3 = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320];
  10331. $mpeg2Layer3 = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
  10332. $sampleRatesV1 = [44100, 48000, 32000, 0];
  10333. $sampleRatesV2 = [22050, 24000, 16000, 0];
  10334. $parseFrame = function ($buffer, $offset) use ($mpeg1Layer3, $mpeg2Layer3, $sampleRatesV1, $sampleRatesV2) {
  10335. if ($offset < 0 || $offset + 4 > strlen($buffer)) {
  10336. return null;
  10337. }
  10338. if (ord($buffer[$offset]) !== 0xFF) {
  10339. return null;
  10340. }
  10341. $b1 = ord($buffer[$offset + 1]);
  10342. if (($b1 & 0xE0) !== 0xE0) {
  10343. return null;
  10344. }
  10345. $b2 = ord($buffer[$offset + 2]);
  10346. $b3 = ord($buffer[$offset + 3]);
  10347. $versionBits = ($b1 >> 3) & 0x03; // 3=MPEG1, 2=MPEG2, 0=MPEG2.5
  10348. $layerBits = ($b1 >> 1) & 0x03; // 1=Layer3
  10349. $bitrateIndex = ($b2 >> 4) & 0x0F;
  10350. $sampleIndex = ($b2 >> 2) & 0x03;
  10351. $channelMode = ($b3 >> 6) & 0x03; // 3=单声道
  10352. if ($versionBits === 1 || $layerBits !== 1 || $bitrateIndex === 0 || $bitrateIndex === 15 || $sampleIndex === 3) {
  10353. return null;
  10354. }
  10355. $bitrate = $versionBits === 3 ? $mpeg1Layer3[$bitrateIndex] : $mpeg2Layer3[$bitrateIndex];
  10356. $rate = $versionBits === 3 ? $sampleRatesV1[$sampleIndex] : $sampleRatesV2[$sampleIndex];
  10357. if ($bitrate <= 0 || $rate <= 0) {
  10358. return null;
  10359. }
  10360. $samplesPerFrame = $versionBits === 3 ? 1152 : 576;
  10361. $frameLen = (int)(($samplesPerFrame / 8 * $bitrate * 1000) / $rate);
  10362. if ($frameLen <= 4) {
  10363. return null;
  10364. }
  10365. return [
  10366. 'version' => $versionBits,
  10367. 'bitrate' => $bitrate,
  10368. 'rate' => $rate,
  10369. 'samples' => $samplesPerFrame,
  10370. 'length' => $frameLen,
  10371. 'channel_mode' => $channelMode,
  10372. ];
  10373. };
  10374. // 定位首个有效帧,并校验下一帧也合法(避免命中伪同步字)
  10375. $firstFrame = null;
  10376. $frameOffset = -1;
  10377. for ($i = $scanStart; $i + 4 <= strlen($data); $i++) {
  10378. $frame = $parseFrame($data, $i);
  10379. if (!$frame) {
  10380. continue;
  10381. }
  10382. $nextOffset = $i + $frame['length'];
  10383. if ($nextOffset + 4 <= strlen($data) && !$parseFrame($data, $nextOffset)) {
  10384. continue;
  10385. }
  10386. $firstFrame = $frame;
  10387. $frameOffset = $i;
  10388. break;
  10389. }
  10390. if (!$firstFrame) {
  10391. return 0;
  10392. }
  10393. // 1) Xing/Info 头包含总帧数,可直接精确计算
  10394. $sideInfoSize = $firstFrame['version'] === 3
  10395. ? ($firstFrame['channel_mode'] === 3 ? 17 : 32)
  10396. : ($firstFrame['channel_mode'] === 3 ? 9 : 17);
  10397. $xingOffset = $frameOffset + 4 + $sideInfoSize;
  10398. $xingTag = substr($data, $xingOffset, 4);
  10399. if (($xingTag === 'Xing' || $xingTag === 'Info') && strlen($data) >= $xingOffset + 12) {
  10400. $flags = unpack('N', substr($data, $xingOffset + 4, 4))[1];
  10401. if ($flags & 0x01) {
  10402. $frameCount = unpack('N', substr($data, $xingOffset + 8, 4))[1];
  10403. if ($frameCount > 0) {
  10404. return round($frameCount * $firstFrame['samples'] / $firstFrame['rate'], 2);
  10405. }
  10406. }
  10407. }
  10408. // 2) 文件不大时下载完整内容逐帧统计(精确)
  10409. $fullData = $data;
  10410. if ($totalSize > 0 && strlen($data) < $totalSize && $totalSize <= 10485760) {
  10411. $fullData = (string)$client->get($url, ['http_errors' => false])->getBody();
  10412. }
  10413. if ($totalSize > 0 && strlen($fullData) >= $totalSize) {
  10414. $samples = 0;
  10415. $i = $frameOffset;
  10416. $bufferLength = strlen($fullData);
  10417. while ($i + 4 <= $bufferLength) {
  10418. $frame = $parseFrame($fullData, $i);
  10419. if (!$frame) {
  10420. $i++;
  10421. continue;
  10422. }
  10423. $samples += $frame['samples'];
  10424. $i += $frame['length'];
  10425. }
  10426. if ($samples > 0) {
  10427. return round($samples / $firstFrame['rate'], 2);
  10428. }
  10429. }
  10430. // 3) 回退:按首帧码率估算(仅用于无法读取完整文件的极端情况)
  10431. return round(($totalSize * 8) / ($firstFrame['bitrate'] * 1000), 2);
  10432. } catch (\Throwable $e) {
  10433. dLog('anime')->warning('参考音频时长探测失败', ['url' => $url, 'error' => $e->getMessage()]);
  10434. return 0;
  10435. }
  10436. }
  10437. /**
  10438. * 将角色音色参考音频按模型分支上传为素材
  10439. * 上传失败时对应素材的<音频N>标记会从 $prompt 中清理(引用传递),与参考图处理保持一致
  10440. *
  10441. * @param array $referenceAudios 参考音频URL数组(顺序与<音频N>标记一一对应)
  10442. * @param string $model 视频模型
  10443. * @param string $prompt 完整提示词(引用传递)
  10444. * @return array 素材数组(asset://格式),非支持模型返回空数组
  10445. */
  10446. public function processActReferenceAudiosToAssets(array $referenceAudios, $model, &$prompt) {
  10447. if (empty($referenceAudios)) {
  10448. return [];
  10449. }
  10450. if (strpos($model, 'zhizhen') !== false) {
  10451. return $this->aiImageGenerationService->processReferenceAudiosToAssets($referenceAudios, $prompt);
  10452. }
  10453. if ($this->isSeedance20SeriesModel($model)) {
  10454. if ($this->isKuaikuaiSeedanceModel($model)) {
  10455. return $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($referenceAudios, $prompt);
  10456. }
  10457. if ($this->isOverseasBaiduSeedanceModel($model)) {
  10458. return $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($referenceAudios, $prompt);
  10459. }
  10460. return $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($referenceAudios, $prompt);
  10461. }
  10462. return [];
  10463. }
  10464. /**
  10465. * 参考音频素材上传失败时,用该角色原本的音色提示词兜底
  10466. * 说明行中的<音频N>标记被清理即代表该角色的音频素材不可用
  10467. *
  10468. * @param string $prompt 完整提示词
  10469. * @param array $audioVoiceFallbacks 角色名 => voice_prompt(仅包含配置了参考音频的角色)
  10470. * @return string
  10471. */
  10472. public function applyAudioVoiceFallbacks($prompt, array $audioVoiceFallbacks) {
  10473. if (empty($prompt) || empty($audioVoiceFallbacks)) {
  10474. return $prompt;
  10475. }
  10476. foreach ($audioVoiceFallbacks as $product_name => $voice_prompt) {
  10477. $voice_prompt = trim((string)$voice_prompt);
  10478. if ($product_name === '') {
  10479. continue;
  10480. }
  10481. $escaped_name = preg_quote($product_name, '/');
  10482. // 说明行中仍有<音频N>标记,说明该角色的音频素材可用,无需兜底
  10483. if (preg_match('/^参考<音频\d+>中的音色,为' . $escaped_name . '配音[^\n]*$/mu', $prompt)) {
  10484. continue;
  10485. }
  10486. $linePattern = '/^参考<音频\d+>中的音色,为' . $escaped_name . '配音[^\n]*$/mu';
  10487. if (!preg_match($linePattern, $prompt)) {
  10488. continue;
  10489. }
  10490. if ($voice_prompt === '') {
  10491. // 该角色没有音色提示词,素材不可用时直接移除残留的说明行
  10492. $prompt = preg_replace('/^参考<音频\d+>中的音色,为' . $escaped_name . '配音[^\n]*\n?/mu', '', $prompt, 1);
  10493. } else {
  10494. // 素材不可用:把说明行替换为该角色原本的音色提示词
  10495. $prompt = preg_replace_callback($linePattern, function () use ($product_name, $voice_prompt) {
  10496. return $product_name . ':' . $voice_prompt;
  10497. }, $prompt, 1);
  10498. }
  10499. dLog('anime')->info('参考音频素材不可用,使用音色提示词兜底', [
  10500. 'product_name' => $product_name,
  10501. 'has_voice_prompt' => $voice_prompt === '' ? 0 : 1,
  10502. ]);
  10503. }
  10504. return $prompt;
  10505. }
  10506. /**
  10507. * 整段配音音频素材不可用时,移除对应的提示语句,避免出现残句
  10508. *
  10509. * @param string $prompt 完整提示词
  10510. * @return string
  10511. */
  10512. public function removeUnavailableSegmentAudioPrompt($prompt) {
  10513. if (empty($prompt) || strpos($prompt, '作为视频配音') === false) {
  10514. return $prompt;
  10515. }
  10516. return preg_replace_callback('/^全程使用[^\n]*?作为视频配音。\n?/mu', function ($matches) {
  10517. return strpos($matches[0], '<音频') === false ? '' : $matches[0];
  10518. }, $prompt);
  10519. }
  10520. /**
  10521. * 生成整段配音音频的提示词引用,并返回合并后的参考音频数组
  10522. * 角色音色音频排在前面(音频1..N,与提示词中的<音频N>一一对应),整段配音音频排在其后
  10523. *
  10524. * @param string $prompt 当前提示词
  10525. * @param array $referenceAudios 角色音色参考音频URL数组
  10526. * @param string $segmentAudioUrl 整段配音音频URL(为空表示无整段配音)
  10527. * @return array ['prompt' => 新提示词, 'has_audio_mark' => 是否使用<音频N>标记, 'reference_audios' => 合并后的音频数组]
  10528. */
  10529. public function buildSegmentAudioReference($prompt, array $referenceAudios, $segmentAudioUrl) {
  10530. $result = [
  10531. 'prompt' => $prompt,
  10532. 'has_audio_mark' => false,
  10533. 'reference_audios' => $referenceAudios,
  10534. ];
  10535. if (empty($segmentAudioUrl)) {
  10536. return $result;
  10537. }
  10538. // 有角色音色时整段配音排在角色音色之后,使用<音频N>标记交由素材上传统一做失败清理与序号重排;
  10539. // 没有角色音色时保持原有文案
  10540. $audioReference = $referenceAudios
  10541. ? "使用<音频" . (count($referenceAudios) + 1) . ">"
  10542. : "使用音频1";
  10543. $hasAudioMark = strpos($audioReference, '<音频') !== false;
  10544. // 有角色音色时整段配音独占一行,便于失败时按行清理
  10545. $result['prompt'] = $hasAudioMark
  10546. ? "全程" . $audioReference . "作为视频配音。\n" . $prompt
  10547. : "全程" . $audioReference . "作为视频配音。" . $prompt;
  10548. $result['has_audio_mark'] = $hasAudioMark;
  10549. $result['reference_audios'] = array_merge($referenceAudios, [$segmentAudioUrl]);
  10550. return $result;
  10551. }
  10552. /**
  10553. * 任务记录用:把参考音频追加到 ref_image_url 中
  10554. * 参考图与参考音色音频一起保存,便于后续核对任务实际使用的素材
  10555. * 合并后统一去重并过滤空值,保证同一素材只出现一次
  10556. *
  10557. * @param string $refImageUrlJson 当前 ref_image_url(JSON数组字符串)
  10558. * @param array $referenceAudios 参考音频URL数组
  10559. * @return string
  10560. */
  10561. public function mergeReferenceAudiosIntoRefImageUrl($refImageUrlJson, array $referenceAudios) {
  10562. $refImageUrls = json_decode((string)$refImageUrlJson, true) ?: [];
  10563. if (!is_array($refImageUrls)) {
  10564. $refImageUrls = [];
  10565. }
  10566. // 参考图在前、参考音频在后,合并后去重并过滤空值
  10567. $merged = array_values(array_unique(array_filter(array_merge($refImageUrls, $referenceAudios))));
  10568. return json_encode($merged, 256);
  10569. }
  10570. public function saveActVideoGenerateParams($data) {
  10571. $episode_id = getProp($data, 'episode_id');
  10572. $model = getProp($data, 'video_model');
  10573. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  10574. if (!in_array($model, $valid_models)) {
  10575. Utils::throwError('20003:该模型不可用');
  10576. }
  10577. // 验证模型是否在可用模型表中
  10578. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10579. Utils::throwError('20003:该模型已不可用,请更换!');
  10580. }
  10581. $video_resolution = getProp($data, 'video_resolution', '720p');
  10582. $ratio = getProp($data, 'ratio');
  10583. if (!$ratio) $ratio = '9:16';
  10584. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  10585. if (!$episode) {
  10586. Utils::throwError('20003:分集不存在');
  10587. }
  10588. dLog('anime')->info('保存分集视频参数', $data);
  10589. try {
  10590. DB::beginTransaction();
  10591. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10592. 'video_model' => $model,
  10593. 'video_resolution' => $video_resolution,
  10594. 'ratio' => $ratio,
  10595. 'updated_at' => date('Y-m-d H:i:s')
  10596. ]);
  10597. if ($result === false) {
  10598. Utils::throwError('20003:分集视频参数保存失败');
  10599. }
  10600. // 同步更新mp_animes表
  10601. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  10602. 'video_model' => $model,
  10603. 'video_resolution' => $video_resolution,
  10604. 'video_ratio' => $ratio,
  10605. 'updated_at' => date('Y-m-d H:i:s')
  10606. ]);
  10607. if ($anime_result === false) {
  10608. Utils::throwError('20003:动漫视频参数保存失败');
  10609. }
  10610. } catch (\Exception $e) {
  10611. DB::rollBack();
  10612. Utils::throwError('20003:'.$e->getMessage());
  10613. }
  10614. DB::commit();
  10615. return $result;
  10616. }
  10617. public function confirmActs($data) {
  10618. $episode_id = getProp($data, 'episode_id');
  10619. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  10620. if (!$episode) {
  10621. Utils::throwError('20003:分集不存在');
  10622. }
  10623. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10624. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10625. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  10626. // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
  10627. $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
  10628. // 获取所有片段数据
  10629. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  10630. // 先构建完整的 products(角色、场景、道具、extra_products,并用资产库映射覆盖),
  10631. // 再处理每个片段的 act_content,避免 extra_products 等资产名未被格式化为 {资产名}
  10632. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  10633. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  10634. $products = [];
  10635. // 先处理角色数组
  10636. foreach ($roles as $role) {
  10637. $product = $role;
  10638. // 将role字段重命名为product_name
  10639. if (isset($product['role'])) {
  10640. $product['product_name'] = $product['role'];
  10641. unset($product['role']);
  10642. $product['product'] = 1; // 标记类型为角色
  10643. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10644. }
  10645. }
  10646. // 处理场景数组
  10647. foreach ($scenes as $scene) {
  10648. $product = $scene;
  10649. // 将scene字段重命名为product_name
  10650. if (isset($product['scene'])) {
  10651. $product['product_name'] = $product['scene'];
  10652. unset($product['scene']);
  10653. $product['product'] = 2; // 标记类型为场景
  10654. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10655. }
  10656. }
  10657. // 处理道具数组(逻辑与场景一致)
  10658. foreach ($props as $prop) {
  10659. $product = $prop;
  10660. // 将prop字段重命名为product_name
  10661. if (isset($product['prop'])) {
  10662. $product['product_name'] = $product['prop'];
  10663. unset($product['prop']);
  10664. $product['product'] = 3; // 标记类型为道具
  10665. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  10666. }
  10667. }
  10668. // extra_products优先级更高,直接覆盖同名的roles和scenes
  10669. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  10670. foreach ($extra_products as $extra_product) {
  10671. $product_name = getProp($extra_product, 'product_name');
  10672. if ($product_name) {
  10673. $products[$product_name] = $extra_product; // 覆盖同名数据
  10674. }
  10675. }
  10676. // mp_script_product_mappings 信息优先级更高:
  10677. // 获取当前剧集所属动漫剧本下、与本集资产同名的资产库最新数据(url/三视图/提示词等),
  10678. // 覆盖分集 JSON 中保存的同名旧快照;分集内独有的 description、voice_prompt 等字段保留
  10679. $anime = DB::table('mp_animes')->where('id', getProp($episode, 'anime_id'))->first();
  10680. $script_id = $anime ? (int)getProp($anime, 'script_id', 0) : 0;
  10681. if ($script_id && !empty($products)) {
  10682. $currentProductNames = array_keys($products);
  10683. $normalizeName = function($name) {
  10684. return trim(preg_replace(
  10685. '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
  10686. '',
  10687. trim((string)$name)
  10688. ));
  10689. };
  10690. $mappingItems = DB::table('mp_script_product_mappings as mapping')
  10691. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  10692. ->where('mapping.script_id', $script_id)
  10693. ->where('product.is_deleted', 0)
  10694. ->whereIn('product.product_name', $currentProductNames)
  10695. ->select(
  10696. 'mapping.product_id',
  10697. 'product.product_name',
  10698. 'product.product',
  10699. 'product.pic_prompt',
  10700. 'product.url',
  10701. 'product.three_view_image_url',
  10702. 'product.timbre_url',
  10703. )
  10704. ->get();
  10705. $mappingByName = [];
  10706. foreach ($mappingItems as $mappingItem) {
  10707. $normalizedName = $normalizeName($mappingItem->product_name);
  10708. if (!$normalizedName) continue;
  10709. $mappingProduct = [
  10710. 'product_id' => (int)$mappingItem->product_id,
  10711. 'product_name' => $mappingItem->product_name,
  10712. 'product' => (int)$mappingItem->product,
  10713. 'pic_prompt' => $mappingItem->pic_prompt ?? '',
  10714. 'url' => $mappingItem->url ?? '',
  10715. 'three_view_image_url' => $mappingItem->three_view_image_url ?? '',
  10716. ];
  10717. // 音色音频:资产库有值时才覆盖分集自带的值,避免空值把已有音色清掉
  10718. if (!empty($mappingItem->timbre_url)) {
  10719. $mappingProduct['timbre_url'] = $mappingItem->timbre_url;
  10720. }
  10721. $mappingByName[$normalizedName] = $mappingProduct;
  10722. }
  10723. foreach ($products as $key => &$product) {
  10724. $normalizedKey = $normalizeName($key);
  10725. if ($normalizedKey && isset($mappingByName[$normalizedKey])) {
  10726. $product = array_merge($product, $mappingByName[$normalizedKey]);
  10727. }
  10728. }
  10729. unset($product);
  10730. }
  10731. // 兼容返回 three_view_image_url / timbre_url 字段(旧数据可能没有该键,统一补空值)
  10732. foreach ($products as &$product) {
  10733. if (!isset($product['three_view_image_url'])) {
  10734. $product['three_view_image_url'] = '';
  10735. }
  10736. if (!isset($product['timbre_url'])) {
  10737. $product['timbre_url'] = '';
  10738. }
  10739. }
  10740. unset($product);
  10741. // 重新索引数组(去除key)
  10742. $products = array_values($products);
  10743. // 基于构建完成的 products 收集所有资产名称(含 extra_products 中的资产)
  10744. $product_names = [];
  10745. foreach ($products as $product) {
  10746. $product_name = getProp($product, 'product_name');
  10747. if ($product_name && $product_name !== '旁白') {
  10748. $product_names[] = $product_name;
  10749. }
  10750. }
  10751. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  10752. $product_names = array_unique($product_names);
  10753. usort($product_names, function($a, $b) {
  10754. return mb_strlen($b) - mb_strlen($a);
  10755. });
  10756. try {
  10757. DB::beginTransaction();
  10758. // 处理每个片段
  10759. foreach ($acts as $act) {
  10760. $act_content = getProp($act, 'act_content');
  10761. if (!$act_content) continue;
  10762. $processed_content = $act_content;
  10763. // 统一替换所有资产名称为 {资产名} 格式
  10764. // 使用占位符避免嵌套替换问题
  10765. $placeholder_map = [];
  10766. $placeholder_index = 0;
  10767. foreach ($product_names as $product_name) {
  10768. // 转义特殊字符
  10769. $escaped_product = preg_quote($product_name, '/');
  10770. // 检查是否匹配且未被 {} 包裹
  10771. $processed_content = preg_replace_callback(
  10772. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  10773. function($matches) use (&$placeholder_map, &$placeholder_index) {
  10774. // 使用唯一占位符
  10775. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  10776. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  10777. $placeholder_index++;
  10778. return $placeholder;
  10779. },
  10780. $processed_content
  10781. );
  10782. }
  10783. // 将所有占位符替换回实际内容
  10784. foreach ($placeholder_map as $placeholder => $replacement) {
  10785. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  10786. }
  10787. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  10788. $shot_counter = 0;
  10789. $processed_content = preg_replace_callback(
  10790. '/【(?:镜头|分镜)(\d+)】/u',
  10791. function($matches) use (&$shot_counter) {
  10792. $shot_counter++;
  10793. return '【镜头' . $shot_counter . '】';
  10794. },
  10795. $processed_content
  10796. );
  10797. // 更新数据库
  10798. $boolen = DB::table('mp_episode_segments')
  10799. ->where('id', $act->id)
  10800. ->update([
  10801. 'act_show_content' => $processed_content,
  10802. 'updated_at' => date('Y-m-d H:i:s')
  10803. ]);
  10804. if (!$boolen) {
  10805. Utils::throwError('20003:片段处理失败');
  10806. }
  10807. }
  10808. }catch (\Exception $e) {
  10809. DB::rollBack();
  10810. Utils::throwError('20003:'.$e->getMessage());
  10811. }
  10812. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10813. 'is_generated' => 1,
  10814. 'updated_at' => date('Y-m-d H:i:s')
  10815. ]);
  10816. if (!$boolen1) {
  10817. DB::rollBack();
  10818. Utils::throwError('20003:分集处理失败!');
  10819. }
  10820. DB::commit();
  10821. // 重新查询更新后的片段数据
  10822. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  10823. // 构建返回的acts数组
  10824. $return_acts = [];
  10825. foreach ($acts as $act) {
  10826. $return_acts[] = [
  10827. 'act_id' => getProp($act, 'id'),
  10828. 'act_number' => getProp($act, 'act_number'),
  10829. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  10830. 'act_show_content' => getProp($act, 'act_show_content'),
  10831. 'video_url' => getProp($act, 'video_url'),
  10832. 'video_duration' => getProp($act, 'video_duration'),
  10833. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  10834. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  10835. ];
  10836. }
  10837. return [
  10838. 'anime_id' => getProp($episode, 'anime_id'),
  10839. 'episode_id' => $episode_id,
  10840. 'title' => getProp($episode, 'title'),
  10841. 'episode_number' => getProp($episode, 'episode_number'),
  10842. 'is_generated' => getProp($episode, 'is_generated'),
  10843. 'video_params' => [
  10844. 'video_model' => getProp($episode, 'video_model'),
  10845. 'video_resolution' => getProp($episode, 'video_resolution'),
  10846. 'ratio' => getProp($episode, 'ratio'),
  10847. ],
  10848. 'products' => $products,
  10849. 'acts' => $return_acts
  10850. ];
  10851. }
  10852. /**
  10853. * 参照 episodePicsInfo 的更新与监控逻辑:
  10854. * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
  10855. * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
  10856. */
  10857. private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
  10858. $pollInterval = 5; // 每5秒查询一次
  10859. $maxWaitSeconds = 60; // 最多持续1分钟
  10860. $startTime = time();
  10861. while (true) {
  10862. // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
  10863. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  10864. if (!$episode) {
  10865. Utils::throwError('20003:分集不存在');
  10866. }
  10867. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10868. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10869. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  10870. $updated = false;
  10871. $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
  10872. $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
  10873. $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
  10874. $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
  10875. $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
  10876. // 有图片任务结果更新时写回分集表
  10877. if ($updated) {
  10878. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10879. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  10880. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  10881. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  10882. 'updated_at' => date('Y-m-d H:i:s')
  10883. ]);
  10884. }
  10885. // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
  10886. if (empty($waitingAssets) && empty($missingAssets)) {
  10887. return;
  10888. }
  10889. // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
  10890. if (empty($waitingAssets)) {
  10891. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10892. }
  10893. // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
  10894. if (time() - $startTime >= $maxWaitSeconds) {
  10895. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  10896. }
  10897. sleep($pollInterval);
  10898. }
  10899. }
  10900. /**
  10901. * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
  10902. * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
  10903. * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
  10904. */
  10905. private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
  10906. foreach ($assets as &$asset) {
  10907. $assetName = getProp($asset, $nameKey);
  10908. if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
  10909. continue;
  10910. }
  10911. // 已有图片URL的资产视为已生成
  10912. if (getProp($asset, 'url')) {
  10913. continue;
  10914. }
  10915. $task_id = getProp($asset, 'task_id');
  10916. // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
  10917. if (!$task_id) {
  10918. $missingAssets[] = $assetName;
  10919. continue;
  10920. }
  10921. $task = DB::table('mp_generate_pic_tasks')
  10922. ->where('id', $task_id)
  10923. ->select('status', 'result_url')
  10924. ->first();
  10925. // 任务不存在:同样记录为缺失项,不在此处直接报错
  10926. if (!$task) {
  10927. $missingAssets[] = $assetName;
  10928. continue;
  10929. }
  10930. if ($task->status === 'success') {
  10931. $result_url = getProp($task, 'result_url');
  10932. if ($result_url) {
  10933. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  10934. if (is_array($result_urls) && !empty($result_urls[0])) {
  10935. $asset['url'] = $result_urls[0];
  10936. $asset['task_status'] = 'success';
  10937. $updated = true;
  10938. continue;
  10939. }
  10940. }
  10941. // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
  10942. $waitingAssets[] = $assetName;
  10943. } elseif ($task->status === 'failed') {
  10944. // 生成失败:记录为缺失项,待其他任务处理完后统一报错
  10945. $missingAssets[] = $assetName;
  10946. } else {
  10947. // 任务仍在生成中,等待下一次轮询
  10948. $waitingAssets[] = $assetName;
  10949. }
  10950. }
  10951. unset($asset);
  10952. }
  10953. /**
  10954. * 导出动漫剧本为PDF(参照示例PDF版式)
  10955. * @param int $animeId 动漫ID
  10956. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  10957. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  10958. * @return string|null
  10959. */
  10960. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  10961. // 图片下载与转换可能占用较多内存
  10962. ini_set('memory_limit', '512M');
  10963. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  10964. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  10965. $anime = (array)$anime;
  10966. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  10967. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  10968. // 获取分集(默认展示版本,按集数升序)
  10969. $episodeQuery = DB::table('mp_anime_episodes')
  10970. ->where('anime_id', $animeId)
  10971. ->where('is_default', 1)
  10972. ->orderBy('episode_number')
  10973. ->orderBy('id');
  10974. if ($episodeCount > 0) {
  10975. $episodeQuery->limit($episodeCount);
  10976. }
  10977. $episodes = $episodeQuery->get()->map(function ($value) {
  10978. return (array)$value;
  10979. })->toArray();
  10980. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  10981. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  10982. $roles = $this->mergeEpisodeItems($episodes, 'role');
  10983. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  10984. $props = $this->mergeEpisodeItems($episodes, 'prop');
  10985. // 组装分集剧本数据
  10986. $episodeScripts = [];
  10987. foreach ($episodes as $episode) {
  10988. $segments = DB::table('mp_episode_segments')
  10989. ->where('anime_id', $animeId)
  10990. ->where('episode_id', $episode['id'])
  10991. ->get();
  10992. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  10993. $acts = [];
  10994. foreach ($segments as $segment) {
  10995. $segment = (array)$segment;
  10996. $actNumber = (int)getProp($segment, 'act_number', 0);
  10997. if ($actNumber <= 0) continue;
  10998. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  10999. $acts[$actNumber] = [
  11000. 'id' => (int)$segment['id'],
  11001. 'act_number' => $actNumber,
  11002. 'duration' => getProp($segment, 'act_duration', ''),
  11003. 'content' => getProp($segment, 'act_content', ''),
  11004. ];
  11005. }
  11006. }
  11007. ksort($acts);
  11008. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  11009. $segmentCounter = 0;
  11010. foreach ($acts as &$act) {
  11011. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  11012. }
  11013. unset($act);
  11014. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  11015. $narratorVoice = '';
  11016. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  11017. foreach ($episodeRoles as $role) {
  11018. if (getProp($role, 'role') === '旁白') {
  11019. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  11020. break;
  11021. }
  11022. }
  11023. if ($narratorVoice === '') {
  11024. foreach ($acts as $act) {
  11025. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  11026. $narratorVoice = trim($match[1]);
  11027. break;
  11028. }
  11029. }
  11030. }
  11031. $episodeScripts[] = [
  11032. 'episode_number' => getProp($episode, 'episode_number'),
  11033. 'title' => getProp($episode, 'title', ''),
  11034. 'act_count' => count($acts),
  11035. 'narrator_voice' => $narratorVoice,
  11036. 'acts' => array_values($acts),
  11037. ];
  11038. }
  11039. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  11040. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  11041. // 构建PDF
  11042. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  11043. // 图片已嵌入PDF,清理临时文件
  11044. foreach ($imageCache as $imgFile) {
  11045. @unlink($imgFile);
  11046. }
  11047. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  11048. if ($savePath) {
  11049. $pdf->Output($savePath, 'F');
  11050. return $savePath;
  11051. }
  11052. // 直接下载输出
  11053. header('Content-Type: application/pdf');
  11054. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  11055. $pdf->Output($filename . '.pdf', 'D');
  11056. exit();
  11057. }
  11058. /**
  11059. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  11060. * @param array $episodes 分集数据
  11061. * @param string $nameKey role|scene|prop
  11062. * @return array
  11063. */
  11064. private function mergeEpisodeItems(array $episodes, $nameKey) {
  11065. $fieldMap = [
  11066. 'role' => 'roles',
  11067. 'scene' => 'scenes',
  11068. 'prop' => 'props',
  11069. ];
  11070. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  11071. $items = [];
  11072. foreach ($episodes as $episode) {
  11073. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  11074. foreach ($list as $item) {
  11075. if (!is_array($item)) continue;
  11076. $name = trim((string)getProp($item, $nameKey, ''));
  11077. if ($name === '') continue;
  11078. // 旁白不进入主体列表(仅作为旁白音色来源)
  11079. if ($nameKey === 'role' && $name === '旁白') continue;
  11080. if (!isset($items[$name])) {
  11081. $items[$name] = $item;
  11082. }
  11083. }
  11084. }
  11085. return array_values($items);
  11086. }
  11087. /**
  11088. * 构建动漫剧本PDF
  11089. * @param array $anime 动漫信息
  11090. * @param array $roles 主体列表
  11091. * @param array $scenes 场景列表
  11092. * @param array $props 道具列表
  11093. * @param array $episodeScripts 分集剧本数据
  11094. * @param array $imageCache 图片缓存(url => 临时文件路径)
  11095. * @return \TCPDF
  11096. */
  11097. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  11098. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  11099. $pdf->SetCreator('动漫剧本导出系统');
  11100. $pdf->SetAuthor('系统');
  11101. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  11102. $pdf->SetSubject('动漫剧本导出');
  11103. $pdf->SetMargins(15, 15, 15);
  11104. $pdf->SetAutoPageBreak(true, 15);
  11105. // 剧本名
  11106. $pdf->AddPage();
  11107. $pdf->SetFont('simsun', 'B', 20);
  11108. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  11109. $pdf->Ln(5);
  11110. // 故事梗概
  11111. $intro = trim((string)getProp($anime, 'intro', ''));
  11112. if ($intro !== '') {
  11113. $this->pdfSectionTitle($pdf, '故事梗概');
  11114. $this->pdfBody($pdf, $intro);
  11115. }
  11116. // 美术风格
  11117. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  11118. if ($artStyle !== '') {
  11119. $this->pdfSectionTitle($pdf, '美术风格');
  11120. $this->pdfBody($pdf, $artStyle);
  11121. }
  11122. // 主体列表(文字+图片)
  11123. $this->pdfSectionTitle($pdf, '主体列表');
  11124. foreach ($roles as $index => $role) {
  11125. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  11126. }
  11127. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  11128. // 场景列表(文字+图片)
  11129. $this->pdfSectionTitle($pdf, '场景列表');
  11130. foreach ($scenes as $index => $scene) {
  11131. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  11132. }
  11133. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  11134. // 道具列表(文字+图片)
  11135. $this->pdfSectionTitle($pdf, '道具列表');
  11136. foreach ($props as $index => $prop) {
  11137. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  11138. }
  11139. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  11140. // 分镜剧本
  11141. $this->pdfSectionTitle($pdf, '分镜剧本');
  11142. foreach ($episodeScripts as $episodeScript) {
  11143. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  11144. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  11145. if ($episodeTitleRaw !== '') {
  11146. // title 字段可能已带"第N集"前缀,避免重复
  11147. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  11148. $episodeTitle = $episodeTitleRaw;
  11149. } else {
  11150. $episodeTitle .= ':' . $episodeTitleRaw;
  11151. }
  11152. }
  11153. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  11154. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  11155. if (getProp($episodeScript, 'narrator_voice') !== '') {
  11156. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  11157. }
  11158. foreach (getProp($episodeScript, 'acts', []) as $act) {
  11159. $actTitle = '片段' . getProp($act, 'act_number');
  11160. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  11161. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  11162. }
  11163. $this->pdfSubTitle($pdf, $actTitle, 12);
  11164. if (getProp($act, 'content') !== '') {
  11165. $this->pdfBody($pdf, getProp($act, 'content'));
  11166. }
  11167. }
  11168. }
  11169. return $pdf;
  11170. }
  11171. /**
  11172. * PDF章节标题(带分隔线)
  11173. */
  11174. private function pdfSectionTitle($pdf, $title) {
  11175. if ($pdf->GetY() > 230) {
  11176. $pdf->AddPage();
  11177. }
  11178. $pdf->SetFont('simsun', 'B', 15);
  11179. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  11180. $y = $pdf->GetY();
  11181. $pdf->SetLineWidth(0.4);
  11182. $pdf->Line(15, $y, 195, $y);
  11183. $pdf->Ln(4);
  11184. }
  11185. /**
  11186. * PDF子标题(集数/片段标题)
  11187. */
  11188. private function pdfSubTitle($pdf, $title, $size = 13) {
  11189. if ($pdf->GetY() > 240) {
  11190. $pdf->AddPage();
  11191. }
  11192. $pdf->SetFont('simsun', 'B', $size);
  11193. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  11194. $pdf->Ln(1);
  11195. }
  11196. /**
  11197. * PDF正文段落
  11198. */
  11199. private function pdfBody($pdf, $text) {
  11200. $pdf->SetFont('simsun', '', 11);
  11201. $pdf->MultiCell(0, 6, $text, 0, 'L');
  11202. $pdf->Ln(2);
  11203. }
  11204. /**
  11205. * 输出列表项图片(每张图单独一页,图下标注名称)
  11206. * @param \TCPDF $pdf
  11207. * @param array $items 列表项
  11208. * @param string $nameKey role|scene|prop
  11209. * @param array $imageCache 图片缓存(url => 临时文件路径)
  11210. */
  11211. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  11212. foreach ($items as $item) {
  11213. $url = trim((string)getProp($item, 'url', ''));
  11214. $name = trim((string)getProp($item, $nameKey, ''));
  11215. if ($url === '' || !isset($imageCache[$url])) continue;
  11216. $imgPath = $imageCache[$url];
  11217. $size = @getimagesize($imgPath);
  11218. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  11219. continue;
  11220. }
  11221. $pdf->AddPage();
  11222. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  11223. $maxW = 160;
  11224. $maxH = 170;
  11225. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  11226. $drawW = $size[0] * $ratio;
  11227. $drawH = $size[1] * $ratio;
  11228. $x = (210 - $drawW) / 2;
  11229. $y = max(15, (297 - $drawH) / 2 - 10);
  11230. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  11231. // 图下标注名称
  11232. $pdf->SetFont('simsun', 'B', 13);
  11233. $pdf->SetY(297 - 28);
  11234. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  11235. }
  11236. }
  11237. /**
  11238. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  11239. * @param array $items 包含url字段的列表项
  11240. * @return array url => 临时文件路径
  11241. */
  11242. private function downloadImagesConcurrently(array $items) {
  11243. // 收集唯一的图片URL
  11244. $urls = [];
  11245. foreach ($items as $item) {
  11246. $url = trim((string)getProp($item, 'url', ''));
  11247. if ($url !== '') $urls[$url] = true;
  11248. }
  11249. if (!$urls) return [];
  11250. $urls = array_keys($urls);
  11251. $tmpDir = sys_get_temp_dir();
  11252. $rawFiles = [];
  11253. foreach ($urls as $url) {
  11254. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  11255. $rawFiles[$url] = $rawFile;
  11256. }
  11257. $client = new Client(['timeout' => 180, 'verify' => false]);
  11258. // 低并发下载,sink写入文件避免大图占用内存
  11259. $generator = (function () use ($urls, $client, $rawFiles) {
  11260. foreach ($urls as $url) {
  11261. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  11262. }
  11263. })();
  11264. $errors = [];
  11265. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  11266. 'concurrency' => 4,
  11267. 'rejected' => function ($reason, $url) use (&$errors) {
  11268. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  11269. },
  11270. ]);
  11271. $each->promise()->wait();
  11272. // 失败的图片串行重试一次(独占带宽,提高成功率)
  11273. foreach ($urls as $url) {
  11274. if (!isset($errors[$url])) continue;
  11275. try {
  11276. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  11277. unset($errors[$url]);
  11278. } catch (\Throwable $e) {
  11279. // 重试仍失败
  11280. }
  11281. }
  11282. $cache = [];
  11283. foreach ($urls as $url) {
  11284. $rawFile = $rawFiles[$url];
  11285. if (isset($errors[$url])) {
  11286. dLog('anime')->error('导出PDF图片下载失败', [
  11287. 'url' => $url,
  11288. 'error' => $errors[$url],
  11289. ]);
  11290. @unlink($rawFile);
  11291. continue;
  11292. }
  11293. $converted = $this->convertImageFile($rawFile, $url);
  11294. if ($converted !== null) {
  11295. $cache[$url] = $converted;
  11296. } else {
  11297. @unlink($rawFile);
  11298. }
  11299. }
  11300. return $cache;
  11301. }
  11302. /**
  11303. * 将已下载的图片文件缩放并转为JPEG
  11304. * @param string $rawFile 原始图片临时文件
  11305. * @param string $url 图片地址(用于命名)
  11306. * @return string|null 转换后的文件路径,转换失败返回null
  11307. */
  11308. private function convertImageFile($rawFile, $url) {
  11309. $content = @file_get_contents($rawFile);
  11310. if ($content === false || $content === '') return null;
  11311. if (!function_exists('imagecreatefromstring')) return null;
  11312. $image = @imagecreatefromstring($content);
  11313. if ($image === false) return null;
  11314. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  11315. imagedestroy($image);
  11316. if ($jpeg !== null) {
  11317. @unlink($rawFile);
  11318. }
  11319. return $jpeg;
  11320. }
  11321. /**
  11322. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  11323. * @param resource $srcImage GD图片资源
  11324. * @param string $rawFile 原始图片临时文件
  11325. * @param string $url 图片地址(用于命名)
  11326. * @return string|null 压缩后的JPEG文件路径
  11327. */
  11328. private function compressImageForPdf($srcImage, $rawFile, $url) {
  11329. $maxBytes = 2 * 1024 * 1024; // 2MB
  11330. $sizes = [2048, 1600, 1280, 1024, 800];
  11331. $qualities = [85, 70, 55, 40];
  11332. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  11333. foreach ($sizes as $size) {
  11334. $resized = $this->copyAndResize($srcImage, $size);
  11335. $flat = $this->flattenToWhite($resized);
  11336. imagedestroy($resized);
  11337. foreach ($qualities as $quality) {
  11338. ob_start();
  11339. $saved = imagejpeg($flat, null, $quality);
  11340. $data = ob_get_clean();
  11341. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  11342. file_put_contents($jpeg, $data);
  11343. imagedestroy($flat);
  11344. dLog('anime')->info('导出PDF图片压缩完成', [
  11345. 'url' => $url,
  11346. 'size' => filesize($jpeg),
  11347. 'edge' => $size,
  11348. 'quality' => $quality,
  11349. ]);
  11350. return $jpeg;
  11351. }
  11352. }
  11353. imagedestroy($flat);
  11354. }
  11355. // 兜底:最小尺寸、最低质量强制输出
  11356. $resized = $this->copyAndResize($srcImage, 800);
  11357. $flat = $this->flattenToWhite($resized);
  11358. imagedestroy($resized);
  11359. $saved = imagejpeg($flat, $jpeg, 30);
  11360. imagedestroy($flat);
  11361. if (!$saved) return null;
  11362. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  11363. 'url' => $url,
  11364. 'size' => filesize($jpeg),
  11365. ]);
  11366. return $jpeg;
  11367. }
  11368. /**
  11369. * 等比缩放图片副本(不销毁原图)
  11370. * @param resource $srcImage GD图片资源
  11371. * @param int $maxEdge 最大边长
  11372. * @return resource
  11373. */
  11374. private function copyAndResize($srcImage, $maxEdge) {
  11375. $width = imagesx($srcImage);
  11376. $height = imagesy($srcImage);
  11377. $max = max($width, $height);
  11378. if ($max <= $maxEdge) {
  11379. $copy = imagecreatetruecolor($width, $height);
  11380. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  11381. return $copy;
  11382. }
  11383. $ratio = $maxEdge / $max;
  11384. $newWidth = max(1, (int)round($width * $ratio));
  11385. $newHeight = max(1, (int)round($height * $ratio));
  11386. $resized = imagecreatetruecolor($newWidth, $newHeight);
  11387. imagealphablending($resized, false);
  11388. imagesavealpha($resized, true);
  11389. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  11390. return $resized;
  11391. }
  11392. /**
  11393. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  11394. * @param resource $image GD图片资源
  11395. * @return resource
  11396. */
  11397. private function flattenToWhite($image) {
  11398. $width = imagesx($image);
  11399. $height = imagesy($image);
  11400. $flat = imagecreatetruecolor($width, $height);
  11401. $white = imagecolorallocate($flat, 255, 255, 255);
  11402. imagefill($flat, 0, 0, $white);
  11403. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  11404. return $flat;
  11405. }
  11406. /**
  11407. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  11408. * @param string $content 片段内容
  11409. * @param int $counter 当前已编号数量(引用传递,整集累计)
  11410. * @return string
  11411. */
  11412. private function renumberSegmentBlocks($content, &$counter) {
  11413. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  11414. $counter++;
  11415. return '【' . $match[1] . $counter . '】';
  11416. }, $content);
  11417. }
  11418. }