| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890 |
- <?php
- namespace App\Services\Anime;
- use App\Consts\BaseConst;
- use App\Consts\ErrorConst;
- use App\Exceptions\ApiException;
- use App\Facade\Site;
- use App\Libs\Utils;
- use App\Models\MpGeneratePicTask;
- use App\Models\MpTaskCenter;
- use App\Services\AIGeneration\AIImageGenerationService;
- use App\Services\AIGeneration\AIVideoGenerationService;
- use App\Services\DeepSeek\DeepSeekService;
- use App\Services\PointsService;
- use App\Services\TaskCenterService;
- use Dflydev\DotAccessData\Util;
- use GuzzleHttp\Client;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Redis;
- use OSS\Core\OssException;
- use OSS\OssClient;
- use PhpOffice\PhpSpreadsheet\IOFactory;
- class AnimeService
- {
- protected $aiImageGenerationService;
- protected $aiVideoGenerationService;
- protected $DeepSeekService;
- protected $pointsService;
- protected $taskCenterService;
- private $url;
- private $api_key;
- private $headers;
- public function __construct(
- AIImageGenerationService $aiImageGenerationService,
- AIVideoGenerationService $aiVideoGenerationService,
- DeepSeekService $DeepSeekService,
- PointsService $pointsService,
- TaskCenterService $taskCenterService
- ) {
- $this->aiImageGenerationService = $aiImageGenerationService;
- $this->aiVideoGenerationService = $aiVideoGenerationService;
- $this->DeepSeekService = $DeepSeekService;
- $this->pointsService = $pointsService;
- $this->taskCenterService = $taskCenterService;
- $this->url = 'https://api.deepseek.com/chat/completions';
- $this->api_key = env('DEEPSEEK_API_KEY');
- $this->headers = [
- 'Authorization' => 'Bearer '.$this->api_key,
- 'Content-Type' => 'application/json; charset=UTF-8'
- ];
- }
- /**
- * 构建统一的分镜数据结构(episodeInfo格式)
- * @param array $segments 分镜数据数组
- * @return array 返回包含acts和total_duration的数组
- */
- public function buildEpisodeSegmentsStructure($segments) {
- $acts = [];
- $totalDuration = 0; // 初始化总时长
-
- foreach($segments as $segment) {
- // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
- $videoDuration = getProp($segment, 'video_duration');
- $audioDuration = getProp($segment, 'audio_duration');
-
- if (!empty($videoDuration) && is_numeric($videoDuration)) {
- $totalDuration += floatval($videoDuration);
- } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
- $totalDuration += floatval($audioDuration);
- } else {
- $totalDuration += 5; // 默认5秒
- }
-
- $segment_content = getProp($segment, 'segment_content');
- // 判断是否有尾帧描述,如果有则去掉这部分内容
- if (strpos($segment_content, '尾帧') !== false) {
- // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
- $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
- }
- // 构建分镜信息
- $segmentInfo = [
- 'segment_id' => getProp($segment, 'segment_id'),
- 'segment_number' => getProp($segment, 'segment_number'),
- 'segment_content' => $segment_content,
- 'description' => getProp($segment, 'description'),
- 'composition' => getProp($segment, 'composition'),
- 'camera_movement' => getProp($segment, 'camera_movement'),
- 'voice_actor' => getProp($segment, 'voice_actor'),
- 'dialogue' => getProp($segment, 'dialogue'),
- 'frame_type' => getProp($segment, 'frame_type'),
- 'scene' => getProp($segment, 'scene'),
- 'characters' => getProp($segment, 'characters'),
- 'tail_frame' => getProp($segment, 'tail_frame'),
- 'emotion' => getProp($segment, 'emotion'),
- 'emotion_type' => getProp($segment, 'emotion_type'),
- 'gender' => getProp($segment, 'gender'),
- 'speed_ratio' => getProp($segment, 'speed_ratio'),
- 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
- 'emotion_scale' => getProp($segment, 'emotion_scale'),
- 'pitch' => getProp($segment, 'pitch'),
- 'voice_name' => getProp($segment, 'voice_name'),
- 'voice_type' => getProp($segment, 'voice_type'),
- 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
- 'img_url' => getProp($segment, 'img_url'),
- 'audio_url' => getProp($segment, 'audio_url'),
- 'audio_duration' => getProp($segment, 'audio_duration', 0),
- 'video_url' => getProp($segment, 'video_url'),
- 'video_duration' => getProp($segment, 'video_duration', 0),
- 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
- 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
- 'last_frame_url' => getProp($segment, 'last_frame_url'),
- 'current_type' => getProp($segment, 'current_type'),
- ];
-
- $actNumber = getProp($segment, 'act_number');
- if (isset($acts[$actNumber])) {
- $acts[$actNumber]['segments'][] = $segmentInfo;
- } else {
- $acts[$actNumber] = [
- 'act_number' => $actNumber,
- 'act_title' => getProp($segment, 'act_title'),
- 'act_duration' => getProp($segment, 'act_duration'),
- 'segments' => [$segmentInfo]
- ];
- }
- }
-
- return [
- 'acts' => array_values($acts),
- 'total_duration' => intval(round($totalDuration))
- ];
- }
- /**
- * 构建统一的分段数据结构(episodeInfoForAce格式)
- * @param array $segments 分段数据数组
- * @return array 返回包含acts和total_duration的数组
- */
- public function buildEpisodeActsStructureForAce($segments) {
- $acts = [];
- $totalDuration = 0; // 初始化总时长
-
- foreach($segments as $segment) {
- // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
- $videoDuration = getProp($segment, 'video_duration');
- $actDuration = getProp($segment, 'act_duration');
-
- if (!empty($videoDuration) && is_numeric($videoDuration)) {
- $totalDuration += floatval($videoDuration);
- } elseif (!empty($actDuration) && is_numeric($actDuration)) {
- $totalDuration += floatval($actDuration);
- } else {
- $totalDuration += 5; // 默认5秒
- }
- // 构建分镜信息
- $segmentInfo = [
- 'act_id' => getProp($segment, 'id'),
- 'act_number' => getProp($segment, 'act_number'),
- 'act_title' => getProp($segment, 'act_title'),
- 'act_duration' => getProp($segment, 'act_duration'),
- 'act_content' => getProp($segment, 'act_content'),
- 'video_url' => getProp($segment, 'video_url'),
- 'video_duration' => getProp($segment, 'video_duration', 0),
- 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
- 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
- 'last_frame_url' => getProp($segment, 'last_frame_url'),
- 'current_type' => getProp($segment, 'current_type'),
- ];
- $acts[] = $segmentInfo;
- }
-
- return [
- 'acts' => array_values($acts),
- 'total_duration' => intval(round($totalDuration))
- ];
- }
- /**
- * 验证画面比例是否有效
- * @param string $ratio 画面比例
- * @return bool
- */
- public function validateRatio($ratio) {
- return isset(BaseConst::IMAGE_RATIOS[$ratio]);
- }
- /**
- * 获取画面比例对应的宽高
- * @param string $ratio 画面比例
- * @return array ['width' => int, 'height' => int]
- * @throws \Exception
- */
- private function getRatioDimensions($ratio) {
- if ($ratio && !$this->validateRatio($ratio)) {
- $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
- Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
- }
- return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
- }
- public function createAnime($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $input_art_style = getProp($data, 'art_style');
- $file = getProp($data, 'file');
- $content = getProp($data, 'content', '');
- $bid = getProp($data, 'bid', 0);
- $script_id = getProp($data, 'script_id', 0);
- $ace_mode = getProp($data, 'ace_mode', 0);
- $extra_products = getProp($data, 'products', []);
- if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
- if (!is_array($extra_products)) {
- Utils::throwError('20003:传入的资产格式不正确');
- }
-
- // 替换美术风格
- $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
- // 提取文件内容
- if ($file) {
- $content = $this->DeepSeekService->extractFileContent($file);
- if (!$content) {
- Utils::throwError('20003:无法提取文件内容,请检查文件格式');
- }
- } elseif ($script_id) {
- $content = $this->DeepSeekService->getContentByScriptId($script_id);
- if (!$content) {
- Utils::throwError('20003:无法获取剧本内容,请检查剧本');
- }
- } elseif ($bid) {
- $content = $this->DeepSeekService->getContentByBid($bid);
- if (!$content) {
- Utils::throwError('20003:无法获取书籍内容,请检查书籍');
- }
- } elseif ($content) {
- $content = filterContent($content);
- }else {
- $content = '';
- }
- $anime_data = [
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'anime_name' => '新剧本策划',
- 'is_multi' => getProp($data, 'is_multi', 1),
- 'content' => $content,
- 'art_style_type' => $input_art_style,
- 'ace_mode' => $ace_mode,
- 'script_id' => $script_id,
- 'extra_products' => json_encode($extra_products, 256),
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- // 处理文本模型
- $model = getProp($data, 'model');
- if (!$model) {
- // 用户没有输入,使用默认值
- $model = 'deepseek-v4-pro';
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'deepseek-v4-pro';
- }
- $anime_data['model'] = $model;
- if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
- return DB::table('mp_animes')->insertGetId($anime_data);
- }
- public function chatList($data) {
- $uid = Site::getUid();
- $anime_name = getProp($data, 'anime_name');
- $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
- if ($anime_name) {
- $query->where('anime_name', 'like', "%$anime_name%");
- }
- return $query->orderBy('id', 'desc')->paginate();
- }
- public function chatHistory($data) {
- $anime_id = getProp($data, 'anime_id');
- $sequence = getProp($data, 'sequence', 0);
- if (!$anime_id) Utils::throwError('20003:请选择对话!');
- $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)
- ->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');
-
- return $query->orderBy('ar.id')->get()->map(function ($value) {
- $value = (array)$value;
- if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
- $value['created_at'] = transDate($value['created_at']);
- $value['episode_created_at'] = transDate($value['episode_created_at']);
- return $value;
- })->toArray();
- }
- public function batchSetRoleImg($data) {
- $episode_id = getProp($data, 'episode_id');
- if (!$episode_id) Utils::throwError('1002:请选择分集');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- $roles = json_decode(getProp($data, 'roles'), true) ?: [];
- $art_style = getProp($episode, 'art_style');
- $anime_id = getProp($episode, 'anime_id');
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- $art_style_type = getProp($anime, 'art_style_type');
- $character_prefix = '';
- $scene_prefix = '';
- if ($art_style_type) {
- $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
- $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
- $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
- }
-
- foreach ($roles as &$role) {
- $role_name = getProp($role, 'role');
- if ($role_name == '旁白') continue;
-
- // 优先使用 pic_prompt,如果没有则使用 description
- $pic_prompt = getProp($role, 'pic_prompt');
- $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
-
- // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
- $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
- // 参考图地址
- $ref_img_url = getProp($role, 'url');
- if ($ref_img_url) continue; // 已有图片则跳过
-
- // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
- try {
- $params = [
- 'prompt' => $description,
- 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError("20003:角色({$role_name})生成图片失败");
- }
-
- $role['task_id'] = $task_id;
- $role['task_status'] = 'processing';
- } catch (\Exception $e) {
- logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
- Utils::throwError("20003:" . $e->getMessage());
- }
- }
-
- // 保存角色信息
- $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'roles' => json_encode($roles, 256),
- 'generate_status' => '执行中',
- 'generate_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$boolen) {
- Utils::throwError('20003:保存角色信息失败');
- }
- return $boolen;
- }
- public function batchSetSceneImg($data) {
- $episode_id = getProp($data, 'episode_id');
- if (!$episode_id) Utils::throwError('1002:请选择分集');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- $scenes = json_decode(getProp($episode, 'scenes'), true);
- $art_style = getProp($episode, 'art_style');
- $target_scene = getProp($data, 'target_scene');
- $anime_id = getProp($episode, 'anime_id');
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- $art_style_type = getProp($anime, 'art_style_type');
- $character_prefix = '';
- $scene_prefix = '';
- if ($art_style_type) {
- $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
- $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
- $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
- }
-
- foreach ($scenes as &$scene) {
- $scene_name = getProp($scene, 'scene');
- if ($scene_name != $target_scene) continue;
-
- // 优先使用 pic_prompt,如果没有则使用 description
- $pic_prompt = getProp($scene, 'pic_prompt');
- $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
-
- // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
- $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
- // 参考图地址
- $ref_img_url = getProp($scene, 'url');
- if ($ref_img_url) continue; // 已有图片则跳过
-
- // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
- try {
- $params = [
- 'prompt' => $description,
- 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError("20003:场景({$scene_name})生成图片失败");
- }
-
- $scene['task_id'] = $task_id;
- $scene['task_status'] = 'processing';
- } catch (\Exception $e) {
- logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
- Utils::throwError("20003:" . $e->getMessage());
- }
- }
-
- // 保存场景信息
- $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'scenes' => json_encode($scenes, 256),
- 'generate_status' => '执行中',
- 'generate_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$boolen) {
- Utils::throwError('20003:保存角色信息失败');
- }
- return $boolen;
- }
- public function editAnime($data) {
- $anime_id = getProp($data, 'anime_id');
- $anime_name = trim(getProp($data, 'anime_name'));
- // 确认对话名称唯一性
- if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
- if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
- }
- if (!$anime_id || !$anime_name) {
- Utils::throwError('20003:参数异常');
- }
- return DB::table('mp_animes')->where('id', $anime_id)->update([
- 'anime_name' => $anime_name,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- // $script_arr =getProp($data, 'script', []);
- // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
- // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
- // $anime_id = getProp($data, 'anime_id');
- // try {
- // DB::beginTransaction();
- // $table_data = [
- // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
- // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
- // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
- // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
- // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
- // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
- // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
- // 'status' => 3,
- // 'start_episode_sequence' => $start_episode_sequence,
- // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
- // 'episode_num' => count($script_arr['episodes']),
- // 'updated_at' => date('Y-m-d H:i:s')
- // ];
- // // 保存剧本内容
- // if (!empty($anime_id)) {
- // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
- // if (!$boolen) {
- // dLog('anime')->info('对话保存失败', $table_data);
- // Utils::throwError('20003:对话保存失败');
- // }
- // }else {
- // $table['created_at'] = $table_data['updated_at'];
- // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
- // if (!$anime_id) {
- // dLog('anime')->info('对话保存失败', $table_data);
- // Utils::throwError('20003:对话保存失败');
- // }
- // }
-
-
- // // 保存分集内容
- // // 删除历史分集内容
- // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
-
- // $episodes = [];
- // $sequence = 1;
- // foreach ($script_arr['episodes'] as $episode) {
- // $segment_number = 1;
- // foreach($episode['segments'] as $segment) {
- // $episodes[] = [
- // 'anime_id' => $anime_id,
- // 'episode_number' => $episode['episode_number'],
- // 'title' => $episode['title'],
- // // 'content' => $episode['content'],
- // 'content' => '',
- // 'segment_number' => $segment_number,
- // 'segment_content' => $segment['segment_content'],
- // 'sequence' => $sequence,
- // 'created_at' => date('Y-m-d H:i:s'),
- // 'updated_at' => date('Y-m-d H:i:s')
- // ];
- // $sequence++;
- // $segment_number++;
- // }
-
- // }
- // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
- // if (!$boolen2) {
- // dLog('deepseek')->info('分集内容保存失败', $episodes);
- // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
- // Utils::throwError('20003:分集内容保存失败');
- // }
- // } catch (\Exception $e) {
- // DB::rollBack();
- // Utils::throwError('20003:'.$e->getMessage());
- // }
- // DB::commit();
- // return true;
- }
- public function delAnime($data) {
- $anime_id = getProp($data, 'anime_id');
- if (!$anime_id) {
- Utils::throwError('20003:请选择剧本');
- }
- return DB::table('mp_animes')->where('id', $anime_id)->update([
- 'is_deleted' => 1,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- public function animeDetail($data) {
- $uid = Site::getUid();
- $anime_id = getProp($data, 'anime_id');
- $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
- ->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();
- if (!$anime) Utils::throwError('20003:权限不足');
- $anime = (array)$anime;
- $anime['roles'] = json_decode($anime['roles']);
- $anime['scenes'] = json_decode($anime['scenes']);
- // 获取分集信息
- $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
- ->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"))
- ->orderBy('episode_number')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
- $anime['episodes'] = $episodes;
- // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
- $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
- $episodeTasks = DB::table('mp_batch_episode_generation_details')
- ->where('anime_id', $anime_id)
- ->whereIn('status', ['pending', 'processing', 'failed']) // 只获取待生成/生成中任务,已完成或失败的不显示
- ->orderBy('episode_number')
- ->get()
- ->map(function ($task) use ($episodeNumbers) {
- if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
- return null;
- }
- return [
- 'episode_number' => (int)$task->episode_number,
- 'status' => $task->status,
- 'error_message' => $task->status == 'failed' ? $task->error_message : '',
- ];
- })
- ->filter()
- ->values()
- ->toArray();
- $anime['episode_tasks'] = $episodeTasks;
- return $anime;
- }
- public function episodeInfo($data) {
- $uid = Site::getUid();
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择剧集');
- }
- // 验证用户权限
- $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
- if (!$anime) Utils::throwError('20003:权限不足');
- $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();
- if (!$episode) Utils::throwError('20003:该剧集不存在!');
- $episode = (array)$episode;
- $episode['roles'] = json_decode($episode['roles'], true);
- // foreach($episode['roles'] as &$item) {
- // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
- // }
- $episode['scenes'] = json_decode($episode['scenes'], true);
- // foreach($episode['scenes'] as &$item) {
- // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
- // }
-
- // 获取分镜信息
- $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
- ->select('*')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
-
- // 使用公共方法构建分镜结构
- $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
- $episode['acts'] = $segmentsStructure['acts'];
- $episode['total_duration'] = $segmentsStructure['total_duration'];
- return $episode;
- }
- public function episodeInfoForAce($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择剧集');
- }
- $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();
- if (!$episode) Utils::throwError('20003:该剧集不存在!');
- $episode = (array)$episode;
- $episode['roles'] = json_decode($episode['roles'], true);
- // foreach($episode['roles'] as &$item) {
- // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
- // }
- $episode['scenes'] = json_decode($episode['scenes'], true);
- // foreach($episode['scenes'] as &$item) {
- // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
- // }
- $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
-
- // 获取分镜信息
- $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
- ->select('*')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
-
- $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
- $episode['acts'] = $segmentsStructure['acts'];
- $episode['total_duration'] = $segmentsStructure['total_duration'];
- // 获取mp_animes表中的视频参数
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
- $episode['video_params'] = [
- 'video_model' => getProp($anime, 'video_model'),
- 'video_resolution' => getProp($anime, 'video_resolution'),
- 'ratio' => getProp($anime, 'video_ratio'),
- ];
- return $episode;
- }
- public function segmentInfo($data) {
- $uid = Site::getUid();
- $segment_id = getProp($data, 'segment_id');
- if (!$segment_id) {
- Utils::throwError('1002:请选择分镜');
- }
-
- // 获取分镜信息
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
-
- // 验证用户权限
- if ($segment) {
- $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
- if (!$anime) Utils::throwError('20003:权限不足');
- }
-
- $result = [
- 'segment_id' => getProp($segment, 'segment_id'),
- 'segment_number' => getProp($segment, 'segment_number'),
- 'segment_content' => getProp($segment, 'segment_content'),
- 'description' => getProp($segment, 'description'),
- 'composition' => getProp($segment, 'composition'),
- 'camera_movement' => getProp($segment, 'camera_movement'),
- 'voice_actor' => getProp($segment, 'voice_actor'),
- 'dialogue' => getProp($segment, 'dialogue'),
- 'frame_type' => getProp($segment, 'frame_type'),
- 'scene' => getProp($segment, 'scene'),
- 'characters' => getProp($segment, 'characters'),
- 'tail_frame' => getProp($segment, 'tail_frame'),
- 'emotion' => getProp($segment, 'emotion'),
- 'emotion_type' => getProp($segment, 'emotion_type'),
- 'gender' => getProp($segment, 'gender'),
- 'speed_ratio' => getProp($segment, 'speed_ratio'),
- 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
- 'emotion_scale' => getProp($segment, 'emotion_scale'),
- 'pitch' => getProp($segment, 'pitch'),
- 'voice_name' => getProp($segment, 'voice_name'),
- 'voice_type' => getProp($segment, 'voice_type'),
- 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
- 'img_url' => getProp($segment, 'img_url'),
- 'video_url' => getProp($segment, 'video_url'),
- 'last_frame_url' => getProp($segment, 'last_frame_url'),
- ];
- return $result;
- }
- public function copyEpisodeVersion($data) {
- $episode_id = getProp($data, 'episode_id');
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$episode) Utils::throwError('20003:该剧集不存在');
- $episode = (array)$episode;
- $anime_id = $episode['anime_id'];
- $episode_number = $episode['episode_number'];
- $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
- $sequence = $count + 1;
- unset($episode['id']);
- $now = date('Y-m-d H:i:s');
- $episode['created_at'] = $now;
- $episode['updated_at'] = $now;
- $episode['is_default'] = 1;
- // 获取版本中含有"(副本"字样的个数
- $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
- $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
- $episode['sequence'] = $sequence;
- $episode['is_generated'] = 0;
- $episode['cpid'] = $cpid;
- // 获取ace_mode
- $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
- try {
- DB::beginTransaction();
- DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
- // 新增副本
- $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
- if (!$new_episode_id) {
- Utils::throwError('20003:创建副本失败!');
- }
- // 获取分镜数据并准备插入
- $segments_for_insert = DB::table('mp_episode_segments')
- ->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')
- ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
- $item = (array)$item;
- $item['episode_id'] = $new_episode_id;
- if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
- $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
- return $item;
- })->toArray();
- // 写入分镜数据
- $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
- if (!$boolen2) {
- Utils::throwError('20003:写入分镜数据失败!');
- }
- // 写入对话历史
- $records = [
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'role' => 'user',
- 'content' => '创建副本',
- 'sequence' => $episode_number,
- 'episode_id' => $new_episode_id,
- 'created_at' => $now,
- 'updated_at' => $now
- ],
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'role' => 'assistant',
- 'content' => '好的,已为您创建副本',
- 'sequence' => $episode_number,
- 'episode_id' => $new_episode_id,
- 'created_at' => $now,
- 'updated_at' => $now
- ]
- ];
- $boolen3 = DB::table('mp_anime_records')->insert($records);
- if (!$boolen3) {
- Utils::throwError('20003:对话记录保存失败');
- }
-
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- // 构建与 episodeInfo 方法一致的返回数据结构
- $result = [
- 'episode_id' => $new_episode_id,
- 'anime_id' => $anime_id,
- 'episode_number' => $episode_number,
- 'title' => $episode['title'],
- 'intro' => $episode['intro'],
- 'art_style' => $episode['art_style'],
- 'roles' => json_decode($episode['roles'], true),
- 'scenes' => json_decode($episode['scenes'], true),
- 'is_generated' => (int)$episode['is_generated']
- ];
- if ((int)$ace_mode === 1) {
- // 获取分镜信息
- $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
- ->select('*')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
- $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
- }else {
- // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
- $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
- }
- $result['acts'] = $segmentsStructure['acts'];
- $result['total_duration'] = $segmentsStructure['total_duration'];
- return $result;
- }
- public function episodeVersions($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择剧集');
- }
- $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
- $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) {
- return (array)$value;
- })->toArray();
- if (!$episodes) Utils::throwError('20003:该剧集不存在!');
-
- foreach($episodes as &$episode) {
- $episode['version'] = 'V'.$episode['sequence'];
- $episode['roles'] = json_decode($episode['roles'], true);
- $episode['scenes'] = json_decode($episode['scenes'], true);
-
- // 获取分镜信息
- $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
- ->select('*')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
-
- // 使用公共方法构建分镜结构
- $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
- $episode['acts'] = $segmentsStructure['acts'];
- $episode['total_duration'] = $segmentsStructure['total_duration'];
- }
- return $episodes;
- }
- public function bindEpisodeVersion($data) {
- $episode_id = getProp($data, 'episode_id');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$episode) Utils::throwError('20003:该剧集不存在');
- $episode = (array)$episode;
- if ((int)$episode['is_default'] === 1) return true;
- try {
- DB::beginTransaction();
- // 移除is_default标志
- $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')]);
- if (!$boolen) {
- Utils::throwError('20003:更新失败!');
- }
- // 绑定副本
- $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
- if (!$boolen2) {
- Utils::throwError('20003:绑定失败!');
- }
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- return true;
- }
- public function chatChangeImg($data) {
- $segment_id = getProp($data, 'segment_id');
- $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
- $prompt = getProp($data, 'prompt');
- if (!$prompt || !$segment_id) {
- Utils::throwError('1002:请输入提示词,并且选择分镜');
- }
- $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
- if (!$segment) Utils::throwError('20003:该分镜不存在!');
- if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
- else $ref_img_url = '';
- // $ref_img_url = '';
- if (empty($prompt)) {
- if (empty($ref_img_url)) {
- $prompt = getProp($segment, 'segment_content');
- }else {
- $prompt = '请根据图片生成';
- }
- }
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- $ratio = getProp($data, 'ratio');
- if (!$ratio) {
- $ratio = getProp($episode, 'ratio');
- if (!$ratio) $ratio = '9:16';
- }
- $art_style = getProp($episode, 'art_style');
- if ($art_style) {
- $prompt = "美术风格:{$art_style}\n{$prompt}";
- }
- $dimensions = $this->getRatioDimensions($ratio);
- $width = $dimensions['width'];
- $height = $dimensions['height'];
- try {
- $params = [
- 'alias_segment_id' => $segment_id,
- 'prompt' => $prompt,
- 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
- 'width' => $width,
- 'height' => $height
- ];
- // 优化提示词(不要生成字幕)
- $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError("20003:生成图片失败");
- }
-
- // 更新任务ID
- $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')]);
- if (!$boolen) Utils::throwError('20003:更新任务ID失败');
- } catch (\Exception $e) {
- Utils::throwError("20003:" . $e->getMessage());
- }
- // 创建任务之后先暂停10s等待异步任务完成
- sleep(10);
- $img_url = $this->loopGetPicTaskResult($task_id);
- if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
- // 图片生成后新增对话记录
- try {
- $uid = Site::getUid();
- $now = date('Y-m-d H:i:s');
-
- // 使用AI反推图片提示词
- $pic_prompt = $this->generateImagePromptFromUrl($img_url);
-
- // 保存对话记录
- $records = [
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'sequence' => $episode_number,
- 'role' => 'user',
- 'content' => $prompt,
- 'segment_id' => $segment_id,
- 'pic_task_id' => $task_id,
- 'image_url' => '',
- 'created_at' => $now,
- 'updated_at' => $now
- ],
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'sequence' => $episode_number,
- 'role' => 'assistant',
- 'content' => $pic_prompt,
- 'segment_id' => $segment_id,
- 'pic_task_id' => $task_id,
- 'image_url' => $img_url,
- 'created_at' => $now,
- 'updated_at' => $now
- ]
- ];
-
- DB::table('mp_anime_records')->insert($records);
-
- } catch (\Exception $e) {
- // 记录日志但不影响主流程
- dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
- 'segment_id' => $segment_id,
- 'img_url' => $img_url
- ]);
- logDB('anime', 'error', '保存对话记录失败', [
- 'segment_id' => $segment_id,
- 'img_url' => $img_url,
- 'error' => $e->getMessage()
- ]);
- }
- return $img_url;
- }
- public function segmentChatHistory($data) {
- $segment_id = getProp($data, 'segment_id');
- if (!$segment_id) Utils::throwError('20003:请选择分镜!');
- $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');
-
- $chat = $query->orderBy('id')->get()->map(function ($value) {
- $value = (array)$value;
- $value['created_at'] = transDate($value['created_at']);
- return $value;
- })->toArray();
- // 获取历史图片
- $url = [];
- $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($pic_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $url = array_merge($url, json_decode($result_url, true));
- }else {
- $url[] = $result_url;
- }
- }
-
- // 获取历史视频
- $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($video_history as $task) {
- $result_url = getProp($task, 'compressed_url');
- if (is_json($result_url)) {
- $url = array_merge($url, json_decode($result_url, true));
- }else {
- $url[] = $result_url;
- }
- }
- return compact('chat', 'url');
- }
- public function changeEpisodeRoles($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- $target_roles = getProp($data, 'roles');
- // 删除标志位于角色对象内部(roles.is_deleted),不在最外层
- $is_deleted = getProp($target_roles, 'is_deleted', 0);
- // 控制字段不随角色内容写入分集roles存储
- if (is_array($target_roles)) {
- unset($target_roles['is_deleted']);
- }
- // 参数验证
- if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
- if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
- if (!$target_roles) Utils::throwError('20003:请提供角色信息');
- // 验证剧集是否存在
- $episode = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->first();
-
- if (!$episode) Utils::throwError('20003:该剧集不存在');
- $roles = json_decode(getProp($episode, 'roles'), true);
- // 获取anime信息,检查是否有关联的script_id
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- if (!$anime) Utils::throwError('20003:动漫不存在');
-
- $script_id = getProp($anime, 'script_id');
- $episode_number = getProp($episode, 'episode_number', 1);
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- try {
- $target_role_name = getProp($target_roles, 'role');
- if (empty($target_role_name)) {
- Utils::throwError('20003:角色名称不能为空');
- }
-
- // 如果是删除操作
- if ($is_deleted == 1) {
- // 从角色列表中移除该角色
- $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
- return getProp($role, 'role') !== $target_role_name;
- }));
-
- // 更新角色列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'roles' => json_encode($roles, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:删除角色失败');
- }
- } else {
- // 新增或更新操作
- $role_found = false;
- $is_new_role = false;
-
- // 查找并更新已存在的角色
- foreach($roles as &$role) {
- if (getProp($role, 'role') === $target_role_name) {
- $role = $target_roles;
- $role_found = true;
- break;
- }
- }
-
- // 如果角色不存在,则新增
- if (!$role_found) {
- $roles[] = $target_roles;
- $is_new_role = true;
- }
- // 更新角色列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'roles' => json_encode($roles, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:更新角色列表失败');
- }
-
- // 同步更新分镜表中对应主体的音色信息
- $voice_name = getProp($target_roles, 'voice_name');
- $voice_type = getProp($target_roles, 'voice_type');
- $voice_audio_url = getProp($target_roles, 'voice_audio_url');
-
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('voice_actor', $target_role_name)
- ->update([
- 'voice_name' => $voice_name,
- 'voice_type' => $voice_type,
- 'voice_audio_url' => $voice_audio_url,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- // 如果有关联的script_id,则同步到mp_products表
- if ($script_id) {
- // 查询剧本信息
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
-
- if ($script) {
- $script_name = $script->script_name ?? 'script_' . $script_id;
- $product_name = getProp($target_roles, 'role');
- $pic_prompt = getProp($target_roles, 'pic_prompt', '');
- $url = getProp($target_roles, 'url', '');
- $product_type = 1; // 1=角色
-
- // 查找或创建以script_name命名的文件夹
- $folder = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('type', 2) // 文件夹类型
- ->where('product', $product_type) // 角色类型
- ->where('product_name', $script_name)
- ->where('parent_id', 0)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$folder) {
- // 创建文件夹
- $folder_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 2, // 文件夹
- 'product' => $product_type, // 角色类型
- 'parent_id' => 0,
- 'level' => 1,
- 'product_name' => $script_name,
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- } else {
- $folder_id = $folder->id;
- }
-
- // 查找该文件夹下是否已存在同名资产
- $existing_product = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('type', 1) // 资产类型
- ->where('product', $product_type)
- ->where('parent_id', $folder_id)
- ->where('product_name', $product_name)
- ->where('is_deleted', 0)
- ->first();
-
- if ($existing_product) {
- // 更新已存在的资产
- $updateData = [
- 'pic_task_status' => '生成成功',
- ];
- if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
- if ($url) $updateData['url'] = $url;
-
- // 处理versions字段
- $versions = getProp($target_roles, 'versions', []);
- if ($versions && is_array($versions)) {
- $updateData['versions'] = json_encode($versions, 256);
- }
-
- $updateData['updated_at'] = date('Y-m-d H:i:s');
-
- DB::table('mp_products')
- ->where('id', $existing_product->id)
- ->update($updateData);
-
- $product_id = $existing_product->id;
- } else {
- // 创建新资产
- $versions = getProp($target_roles, 'versions', []);
-
- $product_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 1, // 资产
- 'product' => $product_type, // 角色
- 'parent_id' => $folder_id,
- 'level' => 2,
- 'product_name' => $product_name,
- 'url' => $url,
- 'pic_prompt' => $pic_prompt,
- 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'pic_task_status' => '生成成功',
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
-
- // 建立或更新绑定关系
- $existing_mapping = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->where('product_id', $product_id)
- ->where('episode_number', $episode_number)
- ->first();
-
- if (!$existing_mapping) {
- // 创建绑定关系
- DB::table('mp_script_product_mappings')->insert([
- 'script_id' => $script_id,
- 'product_id' => $product_id,
- 'episode_number' => $episode_number,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- }
- }
- }
- } catch (\Exception $e) {
- dLog('anime')->error('更新剧集角色失败', [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'error' => $e->getMessage()
- ]);
- Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
- }
- return true;
- }
- public function changeEpisodeScenes($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- $target_scenes = getProp($data, 'scenes');
- // 删除标志位于场景对象内部(scenes.is_deleted),不在最外层
- $is_deleted = getProp($target_scenes, 'is_deleted', 0);
- // 控制字段不随场景内容写入分集scenes存储
- if (is_array($target_scenes)) {
- unset($target_scenes['is_deleted']);
- }
- // 参数验证
- if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
- if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
- if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
- // 验证剧集是否存在
- $episode = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->first();
-
- if (!$episode) Utils::throwError('20003:该剧集不存在');
- $scenes = json_decode(getProp($episode, 'scenes'), true);
- // 获取anime信息,检查是否有关联的script_id
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- if (!$anime) Utils::throwError('20003:动漫不存在');
-
- $script_id = getProp($anime, 'script_id');
- $episode_number = getProp($episode, 'episode_number', 1);
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- try {
- $target_scene_name = getProp($target_scenes, 'scene');
- if (empty($target_scene_name)) {
- Utils::throwError('20003:场景名称不能为空');
- }
-
- // 如果是删除操作
- if ($is_deleted == 1) {
- // 从场景列表中移除该场景
- $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
- return getProp($scene, 'scene') !== $target_scene_name;
- }));
-
- // 更新场景列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'scenes' => json_encode($scenes, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:删除场景失败');
- }
- } else {
- // 新增或更新操作
- $scene_found = false;
- $is_new_scene = false;
-
- // 查找并更新已存在的场景
- foreach($scenes as &$scene) {
- if (getProp($scene, 'scene') === $target_scene_name) {
- $scene = $target_scenes;
- $scene_found = true;
- break;
- }
- }
-
- // 如果场景不存在,则新增
- if (!$scene_found) {
- $scenes[] = $target_scenes;
- $is_new_scene = true;
- }
- // 更新场景列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'scenes' => json_encode($scenes, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:更新场景列表失败');
- }
- // 如果有关联的script_id,则同步到mp_products表
- if ($script_id) {
- // 查询剧本信息
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
-
- if ($script) {
- $script_name = $script->script_name ?? 'script_' . $script_id;
- $product_name = getProp($target_scenes, 'scene');
- $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
- $url = getProp($target_scenes, 'url', '');
- $product_type = 2; // 2=场景
-
- // 查找或创建以script_name命名的文件夹
- $folder = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('type', 2) // 文件夹类型
- ->where('product', $product_type) // 场景类型
- ->where('product_name', $script_name)
- ->where('parent_id', 0)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$folder) {
- // 创建文件夹
- $folder_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 2, // 文件夹
- 'product' => $product_type, // 场景类型
- 'parent_id' => 0,
- 'level' => 1,
- 'product_name' => $script_name,
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- } else {
- $folder_id = $folder->id;
- }
-
- // 查找该文件夹下是否已存在同名资产
- $existing_product = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('type', 1) // 资产类型
- ->where('product', $product_type)
- ->where('parent_id', $folder_id)
- ->where('product_name', $product_name)
- ->where('is_deleted', 0)
- ->first();
-
- if ($existing_product) {
- // 更新已存在的资产
- $updateData = [
- 'pic_task_status' => '生成成功'
- ];
- if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
- if ($url) $updateData['url'] = $url;
-
- // 处理versions字段
- $versions = getProp($target_scenes, 'versions', []);
- if ($versions && is_array($versions)) {
- $updateData['versions'] = json_encode($versions, 256);
- }
-
- $updateData['updated_at'] = date('Y-m-d H:i:s');
-
- DB::table('mp_products')
- ->where('id', $existing_product->id)
- ->update($updateData);
-
- $product_id = $existing_product->id;
- } else {
- // 创建新资产
- $versions = getProp($target_scenes, 'versions', []);
-
- $product_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 1, // 资产
- 'product' => $product_type, // 场景
- 'parent_id' => $folder_id,
- 'level' => 2,
- 'product_name' => $product_name,
- 'url' => $url,
- 'pic_prompt' => $pic_prompt,
- 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'pic_task_status' => '生成成功',
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
-
- // 建立或更新绑定关系
- $existing_mapping = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->where('product_id', $product_id)
- ->where('episode_number', $episode_number)
- ->first();
-
- if (!$existing_mapping) {
- // 创建绑定关系
- DB::table('mp_script_product_mappings')->insert([
- 'script_id' => $script_id,
- 'product_id' => $product_id,
- 'episode_number' => $episode_number,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- }
- }
- }
- } catch (\Exception $e) {
- dLog('anime')->error('更新剧集场景失败', [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'error' => $e->getMessage()
- ]);
- Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
- }
- return true;
- }
- public function changeEpisodeProps($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- $target_props = getProp($data, 'props');
- // 删除标志位于道具对象内部(props.is_deleted),不在最外层
- $is_deleted = getProp($target_props, 'is_deleted', 0);
- // 控制字段不随道具内容写入分集props存储
- if (is_array($target_props)) {
- unset($target_props['is_deleted']);
- }
- // 参数验证
- if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
- if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
- if (!$target_props) Utils::throwError('20003:请提供道具信息');
- // 验证剧集是否存在
- $episode = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->first();
-
- if (!$episode) Utils::throwError('20003:该剧集不存在');
- $props = json_decode(getProp($episode, 'props'), true);
- // 获取anime信息,检查是否有关联的script_id
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- if (!$anime) Utils::throwError('20003:动漫不存在');
-
- $script_id = getProp($anime, 'script_id');
- $episode_number = getProp($episode, 'episode_number', 1);
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- try {
- $target_prop_name = getProp($target_props, 'prop');
- if (empty($target_prop_name)) {
- Utils::throwError('20003:道具名称不能为空');
- }
-
- // 如果是删除操作
- if ($is_deleted == 1) {
- // 从道具列表中移除该道具
- $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
- return getProp($prop, 'prop') !== $target_prop_name;
- }));
-
- // 更新道具列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'props' => json_encode($props, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:删除道具失败');
- }
- } else {
- // 新增或更新操作
- $prop_found = false;
- $is_new_prop = false;
-
- // 查找并更新已存在的道具
- foreach($props as &$prop) {
- if (getProp($prop, 'prop') === $target_prop_name) {
- $prop = $target_props;
- $prop_found = true;
- break;
- }
- }
-
- // 如果道具不存在,则新增
- if (!$prop_found) {
- $props[] = $target_props;
- $is_new_prop = true;
- }
- // 更新道具列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'props' => json_encode($props, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:更新道具列表失败');
- }
- // 如果有关联的script_id,则同步到mp_products表
- if ($script_id) {
- // 查询剧本信息
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
-
- if ($script) {
- $script_name = $script->script_name ?? 'script_' . $script_id;
- $product_name = getProp($target_props, 'prop');
- $pic_prompt = getProp($target_props, 'pic_prompt', '');
- $url = getProp($target_props, 'url', '');
- $product_type = 3; // 3=道具
-
- // 查找或创建以script_name命名的文件夹
- $folder = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('type', 2) // 文件夹类型
- ->where('product', $product_type) // 道具类型
- ->where('product_name', $script_name)
- ->where('parent_id', 0)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$folder) {
- // 创建文件夹
- $folder_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 2, // 文件夹
- 'product' => $product_type, // 道具类型
- 'parent_id' => 0,
- 'level' => 1,
- 'product_name' => $script_name,
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- } else {
- $folder_id = $folder->id;
- }
-
- // 查找该文件夹下是否已存在同名资产
- $existing_product = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('type', 1) // 资产类型
- ->where('product', $product_type)
- ->where('parent_id', $folder_id)
- ->where('product_name', $product_name)
- ->where('is_deleted', 0)
- ->first();
-
- if ($existing_product) {
- // 更新已存在的资产
- $updateData = [
- 'pic_task_status' => '生成成功'
- ];
- if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
- if ($url) $updateData['url'] = $url;
-
- // 处理versions字段
- $versions = getProp($target_props, 'versions', []);
- if ($versions && is_array($versions)) {
- $updateData['versions'] = json_encode($versions, 256);
- }
-
- $updateData['updated_at'] = date('Y-m-d H:i:s');
-
- DB::table('mp_products')
- ->where('id', $existing_product->id)
- ->update($updateData);
-
- $product_id = $existing_product->id;
- } else {
- // 创建新资产
- $versions = getProp($target_props, 'versions', []);
-
- $product_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 1, // 资产
- 'product' => $product_type, // 道具
- 'parent_id' => $folder_id,
- 'level' => 2,
- 'product_name' => $product_name,
- 'url' => $url,
- 'pic_prompt' => $pic_prompt,
- 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'pic_task_status' => '生成成功',
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
-
- // 建立或更新绑定关系
- $existing_mapping = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->where('product_id', $product_id)
- ->where('episode_number', $episode_number)
- ->first();
-
- if (!$existing_mapping) {
- // 创建绑定关系
- DB::table('mp_script_product_mappings')->insert([
- 'script_id' => $script_id,
- 'product_id' => $product_id,
- 'episode_number' => $episode_number,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- }
- }
- }
- } catch (\Exception $e) {
- dLog('anime')->error('更新剧集道具失败', [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'error' => $e->getMessage()
- ]);
- Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
- }
- return true;
- }
- public function editSegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $segment_content = getProp($data, 'segment_content');
- $image_url = getProp($data, 'image_url');
- $video_url = getProp($data, 'video_url');
- // 参数验证
- if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
- // 验证分镜是否存在
- $segment = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->first();
-
- if (!$segment) Utils::throwError('20003:该分镜不存在');
- $dubTaskId = 0;
- try {
- DB::beginTransaction();
- // 准备更新数据
- $update_data = [
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- if ($segment_content) {
- // 先将segment_content赋值到update_data
- $update_data['segment_content'] = $segment_content;
-
- // 使用现有方法分析segment_content,提取各个字段
- $this->handleSegmentContent($update_data);
-
- // 如果有对话内容,创建视频配音合成任务
- $dialogue = getProp($update_data, 'dialogue');
- if (!empty($dialogue)) {
- $now = date('Y-m-d H:i:s');
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($update_data, 'voice_actor'),
- 'voice_type' => getProp($update_data, 'voice_type'),
- 'voice_name' => getProp($update_data, 'voice_name'),
- 'emotion' => getProp($update_data, 'emotion'),
- 'emotion_type' => getProp($update_data, 'emotion_type'),
- 'gender' => getProp($update_data, 'gender'),
- 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
- 'pitch' => getProp($update_data, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $segment_id,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
-
- if (!$dubTaskId) {
- Utils::throwError('20003:创建配音任务失败!');
- }
- $update_data['audio_url'] = '';
- } else {
- // dialogue为空时,直接写入默认音频信息
- $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
- $update_data['audio_duration'] = 2.0;
- $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
- }
- }
- if ($image_url) {
- $update_data['img_url'] = $image_url;
- // 同时写入一个简单的图片生成任务
- $pic_task = [
- 'alias_segment_id' => $segment_id,
- 'ref_img_url' => json_encode([]),
- 'status' => 'success',
- 'result_url' => json_encode([$image_url], 256),
- 'model' => '',
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- DB::table('mp_generate_pic_tasks')->insert($pic_task);
- }
- if ($video_url) {
- $update_data['origin_video_url'] = $video_url;
- $compressed_video_url = compressVideo($video_url);
- $update_data['current_type'] = 2;
- $update_data['video_url'] = $compressed_video_url ?: $video_url;
- // 同时写入一个简单的视频生成任务
- $video_task = [
- 'alias_segment_id' => $segment_id,
- 'status' => 'success',
- 'result_url' => $update_data['origin_video_url'],
- 'compressed_url' => $update_data['video_url'],
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- DB::table('mp_generate_video_tasks')->insert($video_task);
- }
- // 更新分镜信息
- $result = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($update_data);
- if ($result === false) {
- Utils::throwError('20003:更新分镜剧本失败');
- }
- DB::commit();
- // 如果有创建音频生成任务则调用API
- if ($dubTaskId) {
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
- logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
- Utils::throwError('20003:火山生成音频失败');
- }
- }
- return true;
- } catch (\Exception $e) {
- DB::rollBack();
- dLog('anime')->error('更新分镜剧本失败', [
- 'segment_id' => $segment_id,
- 'error' => $e->getMessage()
- ]);
- Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
- }
- }
- public function batchSetSegmentPics($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- $ratio = getProp($data, 'ratio');
- $dimensions = $this->getRatioDimensions($ratio);
- $width = $dimensions['width'];
- $height = $dimensions['height'];
-
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择剧集');
- }
- // 获取剧集信息
- $episode = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->where('is_default', 1)
- ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
- ->first();
-
- if (!$episode) {
- Utils::throwError('20003:该剧集不存在');
- }
- $model = getProp($data, 'model');
- if (!$model) {
- $model = getProp($episode, 'image_model');
- if (!$model) {
- // episode表也没有,使用默认值
- $model = 'doubao-seedream-5-0-lite-260128';
- }
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'doubao-seedream-5-0-lite-260128';
- }
- $roles = json_decode(getProp($episode, 'roles'), true);
- if (!$roles) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $role_map = [];
- foreach ($roles as $role) {
- $role_name = getProp($role, 'role');
- $role_url = getProp($role, 'url');
- if (!empty($role_name) && !empty($role_url)) {
- // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
- // $base_name = preg_replace('/[--].*$/u', '', $role_name);
- // $role_map[$base_name] = $role_url;
- // 同时保存完整名称的映射
- $role_map[$role_name] = $role_url;
- }
- }
- $scenes = json_decode(getProp($episode, 'roles'), true);
- if (!$scenes) {
- Utils::throwError('20003:场景信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $scene_map = [];
- foreach ($scenes as $scene) {
- $scene_name = getProp($scene, 'scene');
- $scene_url = getProp($scene, 'url');
- if (!empty($scene_name) && !empty($scene_url)) {
- $scene_map[$scene_name] = $scene_url;
- }
- }
- // 获取所有分镜信息
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->whereNotIn('pic_task_status', ['已完成', '生成中'])
- ->orderBy('segment_number')
- ->get()
- ->toArray();
- if (empty($segments)) {
- Utils::throwError('20003:所有分镜图片已完成或正在生成中');
- }
- // 保存图片比例
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
- $updated_segments = [];
- $failed_segments = [];
- // 批量为每个分镜生成图片任务
- foreach ($segments as $segment) {
- $segment_id = $segment->segment_id;
- $segment_content = $segment->segment_content;
-
- if (empty($segment_content)) {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => '分镜内容为空'
- ];
- continue;
- }
- try {
- $dubTaskId = 0;
- // 解析分镜内容,提取画面描述作为主要提示词
- $prompt = $segment_content;
- $ref_img_urls = [];
- // 分镜场景
- $scene = getProp($segment, 'scene');
- $matched_scene = '';
- if (isset($scene_map[$scene])) {
- $img_index = count($ref_img_urls) + 1;
- $prompt = "场景:$scene(图$img_index)\n$prompt";
- $ref_img_urls[] = $scene_map[$scene];
- $matched_scene = $scene;
- }
- // 分镜角色
- $characters = getProp($segment, 'characters');
- $characters = str_replace(['、', ',', ';'], ',', $characters);
- $roles = explode(',', $characters);
-
- // 从分镜内容中提取涉及的角色
- $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
-
- // 获取匹配角色的参考图
- foreach ($segment_characters as $character) {
- if (isset($role_map[$character])) {
- // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
- $img_index = count($ref_img_urls) + 1;
- $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
- $ref_img_urls[] = $role_map[$character];
- }
- }
-
- // 如果没有找到匹配的角色参考图,不使用参考图
- if (empty($ref_img_urls)) {
- $ref_img_urls = [];
- }
- // 准备生成任务参数
- $params = [
- 'model' => $model,
- 'alias_segment_id' => $segment_id,
- 'prompt' => $prompt,
- 'ref_img_urls' => $ref_img_urls,
- 'width' => $width,
- 'height' => $height,
- ];
- // 优化提示词(不要生成字幕)
- $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
-
- // $task_id = mt_rand(100000, 999999);
- // 调用AI图片生成服务
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => '创建生成任务失败'
- ];
- continue;
- }
- $update_data = [
- 'pic_task_id' => $task_id,
- 'pic_task_status' => '生成中',
- 'audio_url' => '',
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- // 如果有对话内容,创建视频配音合成任务
- $dialogue = getProp($segment, 'dialogue');
- if (!empty($dialogue)) {
- $now = date('Y-m-d H:i:s');
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($segment, 'voice_actor'),
- 'voice_type' => getProp($segment, 'voice_type'),
- 'voice_name' => getProp($segment, 'voice_name'),
- 'emotion' => getProp($segment, 'emotion'),
- 'emotion_type' => getProp($segment, 'emotion_type'),
- 'gender' => getProp($segment, 'gender'),
- 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
- 'pitch' => getProp($segment, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $segment_id,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
-
- if (!$dubTaskId) {
- dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
- logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
- // Utils::throwError('20003:创建配音任务失败!');
- }
-
- } else {
- // dialogue为空时,直接写入默认音频信息到分镜表
- $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
- $update_data['audio_duration'] = 2.0;
- $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
- }
-
- // 更新分镜的任务信息
- $update_result = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($update_data);
- // 如果是第一集的首帧图片,则存入待更新数组
- if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
- Redis::sadd('anime_first_frame_urls', $segment_id);
- }
-
- if ($update_result) {
- $updated_segments[] = [
- 'segment_id' => $segment_id,
- 'task_id' => $task_id,
- 'status' => '生成中',
- 'matched_scenes' => $matched_scene,
- 'matched_roles' => $segment_characters,
- 'ref_urls_count' => count($ref_img_urls)
- ];
- } else {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => '更新分镜任务状态失败'
- ];
- }
- if ($dubTaskId) {
- sleep(1);
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
- logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
- }
- }
-
- } catch (\Exception $e) {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => $e->getMessage()
- ];
- }
- }
- // 更新剧集生成状态
- if (!empty($updated_segments)) {
- DB::table('mp_anime_episodes')
- ->where('id', $episode_id)
- ->update([
- 'is_generated' => 1,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- return [
- 'success_count' => count($updated_segments),
- 'failed_count' => count($failed_segments),
- 'success_segments' => $updated_segments,
- 'failed_segments' => $failed_segments,
- 'total_segments' => count($segments)
- ];
- }
- public function reGenerateSegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_content = getProp($data, 'segment_content');
- $ratio = getProp($data, 'ratio');
- if (!$ratio) {
- $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
- if (!$ratio) $ratio = '9:16';
- }
- $dimensions = $this->getRatioDimensions($ratio);
- $width = $dimensions['width'];
- $height = $dimensions['height'];
-
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择分镜');
- }
- // 使用文生文模型重新解析segment_content
- if (!empty($segment_content)) {
- $segment_content = $this->parseSegmentContentWithAI($segment_content);
- }
- // 获取动漫的角色信息(包含参考图)
- $anime = DB::table('mp_animes')
- ->where('id', $anime_id)
- ->select('roles', 'scenes')
- ->first();
-
- if (!$anime || !$anime->roles) {
- Utils::throwError('20003:未找到角色信息');
- }
- $roles = json_decode($anime->roles, true);
- if (!$roles) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $role_map = [];
- foreach ($roles as $role) {
- $role_name = getProp($role, 'role');
- $role_url = getProp($role, 'url');
- if (!empty($role_name) && !empty($role_url)) {
- $role_map[$role_name] = $role_url;
- }
- }
- $scenes = json_decode($anime->scenes, true);
- if (!$scenes) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $scene_map = [];
- foreach ($scenes as $scene) {
- $scene_name = getProp($scene, 'scene');
- $scene_url = getProp($scene, 'url');
- if (!empty($scene_name) && !empty($scene_url)) {
- $scene_map[$scene_name] = $scene_url;
- }
- }
- $segment_id = $segment->segment_id;
- $original_segment_content = $segment->segment_content;
-
- // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
- $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
-
- if (empty($final_segment_content)) {
- Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
- }
- try {
- $dubTaskId = 0;
- // 分镜剧本数组
- $update_data = [
- 'segment_content' => $final_segment_content,
- 'pic_task_status' => '生成中',
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- // 解析分镜内容,提取画面描述作为主要提示词
- $prompt = $final_segment_content;
- $ref_img_urls = [];
- // 分镜场景
- $scene = getProp($data, 'scene');
- if ($scene) {
- $matched_scene = '';
- if (isset($scene_map[$scene])) {
- $img_index = count($ref_img_urls) + 1;
- $prompt = "场景:$scene(图$img_index)\n$prompt";
- $ref_img_urls[] = $scene_map[$scene];
- $matched_scene = $scene;
- }
- $update_data['scene'] = $scene;
- }
- // 分镜角色
- $characters = getProp($data, 'characters');
- if ($characters) {
- $update_data['characters'] = $characters;
- $characters = str_replace(['、', ',', ';'], ',', $characters);
- $characters = explode(',', $characters);
-
- // 从分镜内容中提取涉及的角色
- $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
-
- // 获取匹配角色的参考图
- foreach ($segment_characters as $character) {
- if (isset($role_map[$character])) {
- // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
- $img_index = count($ref_img_urls) + 1;
- $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
- $ref_img_urls[] = $role_map[$character];
- }
- }
- }
-
-
- // 如果没有找到匹配的角色参考图,不使用参考图
- if (empty($ref_img_urls)) {
- $ref_img_urls = [];
- }
- // 准备生成任务参数
- $params = [
- 'alias_segment_id' => $segment_id,
- 'prompt' => $prompt,
- 'ref_img_urls' => $ref_img_urls,
- 'width' => $width,
- 'height' => $height,
- ];
- // 优化提示词(不要生成字幕)
- $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
-
- // 调用AI图片生成服务
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError('20003:创建生成任务失败!');
- }
- $update_data['pic_task_id'] = $task_id;
-
- // 更新分镜剧本信息
- $this->handleSegmentContent($update_data);
- // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
- if ($segment_content) {
- $dialogue = getProp($update_data, 'dialogue');
- if (!empty($dialogue)) {
- $now = date('Y-m-d H:i:s');
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($update_data, 'voice_actor'),
- 'voice_type' => getProp($update_data, 'voice_type'),
- 'voice_name' => getProp($update_data, 'voice_name'),
- 'emotion' => getProp($update_data, 'emotion'),
- 'emotion_type' => getProp($update_data, 'emotion_type'),
- 'gender' => getProp($update_data, 'gender'),
- 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
- 'pitch' => getProp($update_data, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $segment_id,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ]);
-
- if (!$dubTaskId) {
- Utils::throwError('20003:创建配音任务失败!');
- }
-
- $update_data['audio_url'] = '';
- } else {
- // dialogue为空时,直接写入默认音频信息
- $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
- $update_data['audio_duration'] = 2.0;
- $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
- }
- }
- $boolen = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($update_data);
- // 如果是第一集的首帧图片,则存入待更新数组
- if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
- Redis::sadd('anime_first_frame_urls', $segment_id);
- }
- if ($dubTaskId) {
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
- logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
- Utils::throwError('20003:火山生成音频失败');
- }
- }
-
- } catch (\Exception $e) {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => $e->getMessage()
- ];
- }
- // 创建任务之后先暂停10s等待异步任务完成
- sleep(10);
- $img_url = $this->loopGetPicTaskResult($task_id);
- if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
-
- // 图片生成后新增对话记录
- try {
- $uid = Site::getUid();
- $now = date('Y-m-d H:i:s');
-
- // 使用AI反推图片提示词
- $pic_prompt = $this->generateImagePromptFromUrl($img_url);
-
- // 保存对话记录
- $records = [
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'sequence' => $episode_number,
- 'role' => 'user',
- 'content' => '重新生成',
- 'segment_id' => $segment_id,
- 'pic_task_id' => $task_id,
- 'image_url' => '',
- 'created_at' => $now,
- 'updated_at' => $now
- ],
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'sequence' => $episode_number,
- 'role' => 'assistant',
- 'content' => $pic_prompt,
- 'segment_id' => $segment_id,
- 'pic_task_id' => $task_id,
- 'image_url' => $img_url,
- 'created_at' => $now,
- 'updated_at' => $now
- ]
- ];
-
- DB::table('mp_anime_records')->insert($records);
- } catch (\Exception $e) {
- // 记录日志但不影响主流程
- dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
- 'segment_id' => $segment_id,
- 'img_url' => $img_url
- ]);
- }
-
- return $img_url;
- }
- public function addSegment($data) {
- $prev_segment_id = getProp($data, 'prev_segment_id');
- $img_url = getProp($data, 'img_url');
- $video_url = getProp($data, 'video_url');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
- if (!$segment) Utils::throwError('20003:该分镜不存在');
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_number = getProp($segment, 'segment_number');
- $new_segment_number = $segment_number + 1;
- $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
- // 分镜剧本数组
- $insert_data = [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'episode_number' => $episode_number,
- 'act_number' => getProp($segment, 'act_number'),
- 'act_title' => getProp($segment, 'act_title'),
- 'segment_id' => $segment_id,
- 'segment_number' => $new_segment_number,
- 'segment_content' => '',
- 'img_url' => '',
- 'video_url' => '',
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- if ($img_url) $insert_data['img_url'] = $img_url;
- if ($video_url) {
- $insert_data['origin_video_url'] = $video_url;
- $insert_data['current_type'] = 2;
- $compressed_video_url = compressVideo($video_url);
- $insert_data['video_url'] = $compressed_video_url ?: $video_url;
- }
- try {
- DB::beginTransaction();
- // 先更新序号
- DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
- $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
- if (!$id) {
- Utils::throwError('20003:新增分镜失败!');
- }
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
- $segment = $segment ? (array)$segment : [];
- return $segment;
- // 以下代码暂弃用
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_number = getProp($segment, 'segment_number');
- $segment_content = getProp($data, 'segment_content');
- $img_url = getProp($data, 'img_url');
- $video_url = getProp($data, 'video_url');
- $ratio = getProp($data, 'ratio');
- $dimensions = $this->getRatioDimensions($ratio);
- $width = $dimensions['width'];
- $height = $dimensions['height'];
-
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择分镜');
- }
- // 使用文生文模型重新解析segment_content
- if (!empty($segment_content)) {
- $segment_content = $this->parseSegmentContentWithAI($segment_content);
- }
- // 获取动漫的角色信息(包含参考图)
- $anime = DB::table('mp_animes')
- ->where('id', $anime_id)
- ->select('roles', 'scenes')
- ->first();
-
- if (!$anime || !$anime->roles) {
- Utils::throwError('20003:未找到角色信息');
- }
- $roles = json_decode($anime->roles, true);
- if (!$roles) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $role_map = [];
- foreach ($roles as $role) {
- $role_name = getProp($role, 'role');
- $role_url = getProp($role, 'url');
- if (!empty($role_name) && !empty($role_url)) {
- $role_map[$role_name] = $role_url;
- }
- }
- $scenes = json_decode($anime->scenes, true);
- if (!$scenes) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $scene_map = [];
- foreach ($scenes as $scene) {
- $scene_name = getProp($scene, 'scene');
- $scene_url = getProp($scene, 'url');
- if (!empty($scene_name) && !empty($scene_url)) {
- $scene_map[$scene_name] = $scene_url;
- }
- }
- $segment_id = $segment->segment_id;
- $original_segment_content = $segment->segment_content;
-
- // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
- $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
-
- if (empty($final_segment_content)) {
- Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
- }
- try {
- $dubTaskId = 0;
- DB::beginTransaction();
- $new_segment_number = $segment_number + 1;
- $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
- // 分镜剧本数组
- $insert_data = [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'episode_number' => $episode_number,
- 'act_number' => getProp($segment, 'act_number'),
- 'act_title' => getProp($segment, 'act_title'),
- 'segment_id' => $segment_id,
- 'segment_number' => $new_segment_number,
- 'segment_content' => $final_segment_content,
- 'img_url' => $img_url,
- 'video_url' => $video_url,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- // 更新分镜剧本信息
- $this->handleSegmentContent($insert_data);
- // 如果有对话内容,创建视频配音合成任务
- $dialogue = getProp($insert_data, 'dialogue');
- if (!empty($dialogue)) {
- $now = date('Y-m-d H:i:s');
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($insert_data, 'voice_actor'),
- 'voice_type' => getProp($insert_data, 'voice_type'),
- 'voice_name' => getProp($insert_data, 'voice_name'),
- 'emotion' => getProp($insert_data, 'emotion'),
- 'emotion_type' => getProp($insert_data, 'emotion_type'),
- 'gender' => getProp($insert_data, 'gender'),
- 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
- 'pitch' => getProp($insert_data, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $segment_id,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
-
- if (!$dubTaskId) {
- Utils::throwError('20003:创建配音任务失败!');
- }
- $insert_data['audio_url'] = '';
- } else {
- // dialogue为空时,直接写入默认音频信息
- $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
- $insert_data['audio_duration'] = 2.0;
- $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
- }
- // 如果没有上传图片则使用当前描述进行生成
- if (!$img_url) {
- // 解析分镜内容,提取画面描述作为主要提示词
- $prompt = $final_segment_content;
- $ref_img_urls = [];
- // 分镜场景
- $scene = getProp($insert_data, 'scene');
- if ($scene) {
- $matched_scene = '';
- if (isset($scene_map[$scene])) {
- $img_index = count($ref_img_urls) + 1;
- $prompt = "场景:$scene(图$img_index)\n$prompt";
- $ref_img_urls[] = $scene_map[$scene];
- $matched_scene = $scene;
- }
- $update_data['scene'] = $scene;
- }
- // 分镜角色
- $characters = getProp($insert_data, 'characters');
- if ($characters) {
- $update_data['characters'] = $characters;
- $characters = str_replace(['、', ',', ';'], ',', $characters);
- $characters = explode(',', $characters);
-
- // 从分镜内容中提取涉及的角色
- $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
-
- // 获取匹配角色的参考图
- foreach ($segment_characters as $character) {
- if (isset($role_map[$character])) {
- // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
- $img_index = count($ref_img_urls) + 1;
- $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
- $ref_img_urls[] = $role_map[$character];
- }
- }
- }
-
-
- // 如果没有找到匹配的角色参考图,不使用参考图
- if (empty($ref_img_urls)) {
- $ref_img_urls = [];
- }
- // 准备生成任务参数
- $params = [
- 'alias_segment_id' => $segment_id,
- 'prompt' => $prompt,
- 'ref_img_urls' => $ref_img_urls,
- 'width' => $width,
- 'height' => $height,
- ];
-
- // 调用AI图片生成服务
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
- // $task_id = 'whatever';
- if (!$task_id) {
- Utils::throwError('20003:创建生成任务失败!');
- }
- $insert_data['pic_task_status'] = '生成中';
- $insert_data['pic_task_id'] = $task_id;
- }
-
- // 先更新序号
- DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
- $boolen = DB::table('mp_episode_segments')->insert($insert_data);
- if (!$boolen) {
- Utils::throwError('20003:新增分镜失败!');
- }
- // 如果是第一集的首帧图片,则存入待更新数组
- if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
- Redis::sadd('anime_first_frame_urls', $segment_id);
- }
-
- if ($dubTaskId) {
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
- Utils::throwError('20003:火山生成音频失败');
- }
- }
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- // 创建任务之后先暂停10s等待异步任务完成
- sleep(10);
- if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
- if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- $segment = $segment ? (array)$segment : [];
- return $segment;
- }
- public function copySegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$segment) Utils::throwError('20003:请选择分镜');
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_number = getProp($segment, 'segment_number');
- $new_segment_id = 0;
- try {
- DB::beginTransaction();
- $segment = (array)$segment;
- unset($segment['id']);
- $segment['segment_number'] += 1;
- $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
- // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
- $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
- // 更新其他分镜序号
- DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
- // 复制分镜
- $id = DB::table('mp_episode_segments')->insertGetId($segment);
- if (!$id) {
- Utils::throwError('20003:复制分镜失败');
- }
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
- $segment = $segment ? (array)$segment : [];
- return $segment;
- }
- public function moveSegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $target_segment_id = getProp($data, 'target_segment_id');
-
- // 获取源分镜信息
- $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$source_segment) Utils::throwError('20003:请选择分镜');
-
- // 获取目标分镜信息
- $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
- if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
-
- $anime_id = getProp($source_segment, 'anime_id');
- $episode_id = getProp($source_segment, 'episode_id');
- $episode_number = getProp($source_segment, 'episode_number');
- $source_segment_number = getProp($source_segment, 'segment_number');
- $target_segment_number = getProp($target_segment, 'segment_number');
-
- // 验证源分镜和目标分镜必须属于同一个动漫的同一集
- $target_anime_id = getProp($target_segment, 'anime_id');
- $target_episode_number = getProp($target_segment, 'episode_number');
-
- if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
- Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
- }
-
- // 如果源分镜和目标分镜相同,无需移动
- if ($source_segment_number == $target_segment_number) {
- return true;
- }
- try {
- DB::beginTransaction();
- if ($source_segment_number < $target_segment_number) {
- // 向后移动:源分镜移动到目标分镜之后
- // 1. 将源分镜和目标分镜之间的所有分镜序号减1
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('segment_number', '>', $source_segment_number)
- ->where('segment_number', '<=', $target_segment_number)
- ->decrement('segment_number');
-
- // 2. 将源分镜移动到目标分镜之后
- $new_segment_number = $target_segment_number;
-
- } else {
- // 向前移动:源分镜移动到目标分镜之后
- // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('segment_number', '>', $target_segment_number)
- ->where('segment_number', '<', $source_segment_number)
- ->increment('segment_number');
-
- // 2. 将源分镜移动到目标分镜之后
- $new_segment_number = $target_segment_number + 1;
- }
-
- // 3. 更新源分镜的序号
- $update_result = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update([
- 'segment_number' => $new_segment_number,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- if (!$update_result) {
- Utils::throwError('20003:更新分镜序号失败');
- }
- DB::commit();
- return true;
-
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- public function delSegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$segment) Utils::throwError('20003:请选择分镜');
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_number = getProp($segment, 'segment_number');
- try {
- DB::beginTransaction();
- // 删除分镜
- $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
- if (!$boolen) {
- Utils::throwError('20003:删除分镜失败');
- }
- // 更新其他分镜序号
- DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- return true;
- }
- public function applySegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $url = getProp($data, 'url');
- if (!$segment_id) Utils::throwError('20003:请选择分镜');
- if (!$url) Utils::throwError('20003:URL不能为空');
-
- // 获取URL的文件扩展名
- $urlPath = parse_url($url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- // 定义图片和视频的扩展名
- $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
- $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
-
- // 判断是图片还是视频
- $updateData = ['updated_at' => date('Y-m-d H:i:s')];
-
- if (in_array($extension, $imageExtensions)) {
- // 图片类型
- $updateData['img_url'] = $url;
- $updateData['current_type'] = 1;
- } elseif (in_array($extension, $videoExtensions)) {
- // 视频类型
- $updateData['video_url'] = $url;
- $updateData['current_type'] = 2;
- } else {
- Utils::throwError('20003:不支持的文件类型');
- }
-
- // 更新分镜表
- $result = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($updateData);
-
- if (!$result) {
- Utils::throwError('20003:更新分镜失败');
- }
-
- return true;
- }
- public function segmentHistory($data) {
- $segment_id = getProp($data, 'segment_id');
- // 获取历史图片
- $pics = [];
- $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($pic_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $pics = array_merge($pics, json_decode($result_url, true));
- }else {
- $pics[] = $result_url;
- }
- }
-
- // 获取历史视频
- $videos = [];
- $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($video_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $videos = array_merge($videos, json_decode($result_url, true));
- }else {
- $videos[] = $result_url;
- }
- }
- return compact('pics', 'videos');
- }
- public function addAct($data) {
- $prev_act_id = getProp($data, 'prev_act_id');
- $act_title = getProp($data, 'act_title', '');
- $act_content = getProp($data, 'act_content', '');
- $act_duration = getProp($data, 'act_duration', 5);
- $video_url = getProp($data, 'video_url');
-
- // 根据prev_act_id获取记录
- $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
- if (!$prev_segment) Utils::throwError('20003:该片段不存在');
-
- $anime_id = getProp($prev_segment, 'anime_id');
- $episode_id = getProp($prev_segment, 'episode_id');
- $episode_number = getProp($prev_segment, 'episode_number');
- $prev_act_number = getProp($prev_segment, 'act_number');
-
- // 获取新的act_number
- $new_act_number = $prev_act_number + 1;
- try {
- DB::beginTransaction();
-
- // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $prev_act_number)
- ->increment('act_number');
- // 插入新片段记录
- $insert_data = [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'episode_number' => $episode_number,
- 'act_number' => $new_act_number,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- if ($act_title) {
- $insert_data['act_title'] = $act_title;
- }
- if ($act_content) {
- $insert_data['act_content'] = $act_content;
- }
- if ($act_duration) {
- $insert_data['act_duration'] = $act_duration;
- }
- if ($video_url) {
- $insert_data['origin_video_url'] = $video_url;
- $insert_data['current_type'] = 2;
- $compressed_video_url = compressVideo($video_url);
- $insert_data['video_url'] = $compressed_video_url ?: $video_url;
- }
- $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
- if (!$id) {
- Utils::throwError('20003:新增片段失败!');
- }
-
- DB::commit();
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
-
- $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();
- $segment = $segment ? (array)$segment : [];
- return $segment;
- }
- public function editAct($data) {
- $act_id = getProp($data, 'act_id');
- $act_content = getProp($data, 'act_content');
- $act_duration = getProp($data, 'act_duration');
- $act_title = getProp($data, 'act_title');
- $image_url = getProp($data, 'image_url');
- $video_url = getProp($data, 'video_url');
- // 参数验证
- if (!$act_id) Utils::throwError('20003:请提供片段ID');
- // 验证片段是否存在(全能模式下每个act只有一条记录)
- $segment = DB::table('mp_episode_segments')
- ->where('id', $act_id)
- ->first();
-
- if (!$segment) Utils::throwError('20003:该片段不存在');
- try {
- DB::beginTransaction();
-
- // 准备更新数据
- $update_data = [
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- // 更新act相关字段
- if (!empty($act_content)) {
- $update_data['act_show_content'] = $act_content;
- $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
- // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
- $shot_counter = 0;
- $update_data['act_show_content'] = preg_replace_callback(
- '/【(?:镜头|分镜)(\d+)】/u',
- function($matches) use (&$shot_counter) {
- $shot_counter++;
- return '【镜头' . $shot_counter . '】';
- },
- $update_data['act_show_content']
- );
- }
-
- if (!empty($act_duration)) {
- $update_data['act_duration'] = $act_duration;
- }
-
- if (!empty($act_title)) {
- $update_data['act_title'] = $act_title;
- }
- // 处理图片上传
- if ($image_url) {
- $update_data['img_url'] = $image_url;
- $update_data['current_type'] = 1;
- // 同时写入一个图片生成任务记录
- if ($act_id) {
- $pic_task = [
- 'alias_act_id' => $act_id,
- 'ref_img_url' => json_encode([]),
- 'status' => 'success',
- 'result_url' => json_encode([$image_url], 256),
- 'model' => '',
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- DB::table('mp_generate_pic_tasks')->insert($pic_task);
- }
- }
- // 处理视频上传
- if ($video_url) {
- $update_data['origin_video_url'] = $video_url;
- $compressed_video_url = compressVideo($video_url);
- $update_data['current_type'] = 2;
- $update_data['video_url'] = $compressed_video_url ?: $video_url;
- // 同时写入一个视频生成任务记录
- if ($act_id) {
- $video_task = [
- 'alias_act_id' => $act_id,
- 'status' => 'success',
- 'result_url' => $update_data['origin_video_url'],
- 'compressed_url' => $update_data['video_url'],
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- DB::table('mp_generate_video_tasks')->insert($video_task);
- }
- }
- // 更新片段信息
- $result = DB::table('mp_episode_segments')
- ->where('id', $act_id)
- ->update($update_data);
- if ($result === false) {
- Utils::throwError('20003:更新片段失败');
- }
- DB::commit();
- // 返回新复制的记录
- $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();
- $new_segment = (array)$new_segment;
- return $new_segment;
- } catch (\Exception $e) {
- DB::rollBack();
- dLog('anime')->error('更新片段失败', [
- 'act_id' => $act_id,
- 'error' => $e->getMessage()
- ]);
- Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
- }
- }
- public function copyAct($data) {
- $act_id = getProp($data, 'act_id');
-
- // 根据act_id获取记录(全能模式下每个act只有一条记录)
- $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if (!$source_segment) Utils::throwError('20003:请选择片段');
-
- $anime_id = getProp($source_segment, 'anime_id');
- $episode_id = getProp($source_segment, 'episode_id');
- $episode_number = getProp($source_segment, 'episode_number');
- $act_number = getProp($source_segment, 'act_number');
- try {
- DB::beginTransaction();
- // 新act的编号
- $new_act_number = $act_number + 1;
-
- // 更新后续所有act的act_number
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $act_number)
- ->increment('act_number');
- // 复制该片段记录
- $segment_data = (array)$source_segment;
- unset($segment_data['id']);
- $segment_data['video_url'] = '';
- $segment_data['video_task_id'] = '';
- $segment_data['video_task_status'] = '';
- $segment_data['act_number'] = $new_act_number;
- $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
- $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
- if (!$id) {
- Utils::throwError('20003:复制片段失败');
- }
-
- DB::commit();
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- // 返回新复制的记录
- $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();
- $new_segment = $new_segment ? (array)$new_segment : [];
- $new_segment['act_id'] = $id;
- return $new_segment;
- }
- public function moveAct($data) {
- $act_id = getProp($data, 'act_id');
- $target_act_id = getProp($data, 'target_act_id');
-
- // 获取源片段信息
- $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if (!$source_segment) Utils::throwError('20003:请选择片段');
-
- // 获取目标片段信息
- $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
- if (!$target_segment) Utils::throwError('20003:目标片段不存在');
-
- $anime_id = getProp($source_segment, 'anime_id');
- $episode_id = getProp($source_segment, 'episode_id');
- $source_act_number = getProp($source_segment, 'act_number');
- $target_act_number = getProp($target_segment, 'act_number');
-
- // 验证源片段和目标片段必须属于同一个动漫的同一集
- $target_anime_id = getProp($target_segment, 'anime_id');
- $target_episode_id = getProp($target_segment, 'episode_id');
-
- if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
- Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
- }
-
- // 如果源片段和目标片段相同,无需移动
- if ($source_act_number == $target_act_number) {
- return true;
- }
- try {
- DB::beginTransaction();
- if ($source_act_number < $target_act_number) {
- // 向后移动:源片段移动到目标片段之后
- // 1. 将源片段和目标片段之间的所有片段编号减1
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $source_act_number)
- ->where('act_number', '<=', $target_act_number)
- ->decrement('act_number');
-
- // 2. 将源片段移动到目标片段之后
- $new_act_number = $target_act_number;
-
- } else {
- // 向前移动:源片段移动到目标片段之后
- // 1. 将目标片段之后到源片段之前的所有片段编号加1
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $target_act_number)
- ->where('act_number', '<', $source_act_number)
- ->increment('act_number');
-
- // 2. 将源片段移动到目标片段之后
- $new_act_number = $target_act_number + 1;
- }
-
- // 3. 更新源片段的编号
- $update_result = DB::table('mp_episode_segments')
- ->where('id', $act_id)
- ->update([
- 'act_number' => $new_act_number,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- if (!$update_result) {
- Utils::throwError('20003:更新片段编号失败');
- }
- DB::commit();
- return true;
-
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- public function delAct($data) {
- $act_id = getProp($data, 'act_id');
-
- // 根据act_id获取记录(全能模式下每个act只有一条记录)
- $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if (!$segment) Utils::throwError('20003:请选择片段');
-
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $act_number = getProp($segment, 'act_number');
- try {
- DB::beginTransaction();
- // 删除该片段记录
- $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
- if (!$deleted) {
- Utils::throwError('20003:删除片段失败');
- }
- // 更新后续act的编号
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $act_number)
- ->decrement('act_number');
-
- DB::commit();
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- return true;
- }
- public function applyAct($data) {
- $act_id = getProp($data, 'act_id');
- $url = getProp($data, 'url');
-
- if (!$act_id) Utils::throwError('20003:请选择片段');
- if (!$url) Utils::throwError('20003:URL不能为空');
-
- // 获取URL的文件扩展名
- $urlPath = parse_url($url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- // 定义图片和视频的扩展名
- $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
- $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
-
- // 判断是图片还是视频
- $updateData = ['updated_at' => date('Y-m-d H:i:s')];
-
- if (in_array($extension, $imageExtensions)) {
- // 图片类型
- $updateData['img_url'] = $url;
- $updateData['current_type'] = 1;
- } elseif (in_array($extension, $videoExtensions)) {
- // 视频类型
- $updateData['video_url'] = $url;
- $updateData['current_type'] = 2;
- } else {
- Utils::throwError('20003:不支持的文件类型');
- }
-
- // 更新片段记录(全能模式下每个act只有一条记录)
- $result = DB::table('mp_episode_segments')
- ->where('id', $act_id)
- ->update($updateData);
-
- if (!$result) {
- Utils::throwError('20003:更新片段失败');
- }
-
- return true;
- }
- public function actChatHistory($data) {
- $act_id = getProp($data, 'act_id');
- if (!$act_id) Utils::throwError('20003:请选择片段!');
- $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');
-
- $chat = $query->orderBy('id')->get()->map(function ($value) {
- $value = (array)$value;
- $value['created_at'] = transDate($value['created_at']);
- if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
- else $value['reference_images'] = [];
- return $value;
- })->toArray();
- // 获取历史图片
- $url = [];
- $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($pic_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $url = array_merge($url, json_decode($result_url, true));
- }else {
- $url[] = $result_url;
- }
- }
-
- // 获取历史视频
- $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($video_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $url = array_merge($url, json_decode($result_url, true));
- }else {
- $url[] = $result_url;
- }
- }
- // 获取资产库
- $products = [];
-
- // 通过act_id查询片段信息获取episode_id
- $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if ($segment) {
- $episode_id = getProp($segment, 'episode_id');
-
- // 查询剧集信息获取roles、scenes和extra_products
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if ($episode) {
- $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
- $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
- $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
- $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
-
- // 先合并roles、scenes和props
- // 处理角色数组
- foreach ($roles as $role) {
- $product = $role;
- // 将role字段重命名为product_name
- if (is_array($product) && !empty($product['role'] ?? null)) {
- $product['product_name'] = $product['role'];
- unset($product['role']);
- $product['product'] = 1; // 标记类型为角色
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
- }
-
- // 处理场景数组
- foreach ($scenes as $scene) {
- $product = $scene;
- // 将scene字段重命名为product_name
- if (is_array($product) && !empty($product['scene'] ?? null)) {
- $product['product_name'] = $product['scene'];
- unset($product['scene']);
- $product['product'] = 2; // 标记类型为场景
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
- }
- // 处理道具数组
- foreach ($props as $prop) {
- $product = $prop;
- // 将prop字段重命名为product_name
- if (is_array($product) && !empty($product['prop'] ?? null)) {
- $product['product_name'] = $product['prop'];
- unset($product['prop']);
- $product['product'] = 3; // 标记类型为道具
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
- }
-
- // extra_products优先级更高,直接覆盖同名的roles和scenes
- foreach ($extra_products as $extra_product) {
- $product_name = getProp($extra_product, 'product_name');
- if ($product_name) {
- $products[$product_name] = $extra_product; // 覆盖同名数据
- }
- }
-
- // 重新索引数组(去除key)
- $products = array_values($products);
- }
- }
- // 获取执行中的任务
- $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) {
- $value = (array)$value;
- if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
- else $value['ref_image_url'] = [];
- $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
- // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
- if (!empty($value['prompt'])) {
- $prompt = $value['prompt'];
-
- // 查找第一个【镜头】的位置
- if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
- // 从【镜头】开始截取
- $prompt = substr($prompt, $matches[0][1]);
- }
-
- // 去除所有<图片X>格式的标记(X可以是任意数字)
- $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
-
- $value['prompt'] = $prompt;
- }
-
- return $value;
- })->toArray();
- return compact('chat', 'url', 'products', 'tasks');
- }
- public function applyAudioData($data) {
- $segment_id = getProp($data, 'segment_id');
- $global_data = getProp($data, 'global_data');
- $segment_data = getProp($data, 'segment_data');
- if (!$segment_id) Utils::throwError('20003:请选择分镜');
- $global_data = is_array($global_data) ? $global_data : [];
- $segment_data = is_array($segment_data) ? $segment_data : [];
-
- // dialogue只能在segment_data中,如果在global_data中则移到segment_data
- $dialogue_item = null;
- foreach ($global_data as $key => $item) {
- if (trim((string)getProp($item, 'name')) === 'dialogue') {
- $dialogue_item = $item;
- unset($global_data[$key]);
- break;
- }
- }
- if ($dialogue_item) {
- $segment_data[] = $dialogue_item;
- }
- // 特殊参数: audio_url,audio_duration,subtitle_info
- // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
- // 如果不是全部存在,则仍需创建音频任务
- $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
- $special_update_data = [];
- $has_all_special_params = false;
-
- // 从segment_data中提取特殊参数
- $filtered_segment_data = [];
- foreach ($segment_data as $item) {
- $field_name = trim((string)getProp($item, 'name'));
- if (in_array($field_name, $special_fields)) {
- $special_update_data[$field_name] = getProp($item, 'value');
- } else {
- // 非特殊参数保留,继续后续处理
- $filtered_segment_data[] = $item;
- }
- }
-
- // 检查是否三个特殊参数都存在
- if (count($special_update_data) === 3 &&
- isset($special_update_data['audio_url']) &&
- isset($special_update_data['audio_duration']) &&
- isset($special_update_data['subtitle_info'])) {
- $has_all_special_params = true;
-
- // 立即更新到当前分镜
- $special_update_data['updated_at'] = date('Y-m-d H:i:s');
- DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($special_update_data);
- }
-
- // 使用过滤后的segment_data继续处理其他参数
- $segment_data = $filtered_segment_data;
-
- $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
- $global_update_data = [];
- $segment_update_data = [];
- $global_voice_type = '';
- $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$target_segment) Utils::throwError('20003:分镜不存在');
- $episode_id = getProp($target_segment, 'episode_id');
- $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$episode) Utils::throwError('20003:分集不存在');
- foreach ($global_data as $item) {
- $field_name = trim((string)getProp($item, 'name'));
- if (!$field_name || !in_array($field_name, $allow_fields)) {
- continue;
- }
- $global_update_data[$field_name] = getProp($item, 'value');
- if ($field_name === 'voice_type') {
- $global_voice_type = trim((string)getProp($item, 'value'));
- }
- }
- foreach ($segment_data as $item) {
- $field_name = trim((string)getProp($item, 'name'));
- if (!$field_name || !in_array($field_name, $allow_fields)) {
- continue;
- }
- $segment_update_data[$field_name] = getProp($item, 'value');
- }
- if ($global_voice_type) {
- $timbre_info = DB::table('mp_timbres')
- ->where('timbre_type', $global_voice_type)
- ->select('audio_url', 'timbre_name')
- ->first();
- if ($timbre_info) {
- $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
- $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
- }
- }
- try {
- DB::beginTransaction();
-
- // 收集需要创建音频合成任务的segment_id和对应的分镜数据
- $segment_ids_to_create_task = [];
- $segments_data = [];
- // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
- if (!empty($global_update_data)) {
- // 如果角色不存在,则只更新当前分镜
- if (!$target_voice_actor) {
- // 只处理当前分镜
- $affected_segments = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->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')
- ->get();
- } else {
- // 获取该角色的所有分镜
- $affected_segments = DB::table('mp_episode_segments')
- ->where('episode_id', $episode_id)
- ->where('voice_actor', $target_voice_actor)
- ->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')
- ->get();
- }
-
- foreach ($affected_segments as $seg) {
- $seg = (array)$seg;
- $sid = getProp($seg, 'segment_id');
-
- // 检查参数是否发生变化
- $has_changed = false;
- foreach ($global_update_data as $field => $new_value) {
- $old_value = getProp($seg, $field);
- if ($old_value != $new_value) {
- $has_changed = true;
- break;
- }
- }
-
- if ($has_changed) {
- $segment_ids_to_create_task[] = $sid;
- $segments_data[$sid] = $seg;
- }
- }
-
- // 只有在有变化的分镜时才更新
- if (!empty($segment_ids_to_create_task)) {
- $global_segment_update_data = $global_update_data;
- $global_segment_update_data['audio_url'] = ''; // 清空音频URL
- $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
- DB::table('mp_episode_segments')
- ->where('episode_id', $episode_id)
- ->where('voice_actor', $target_voice_actor)
- ->whereIn('segment_id', $segment_ids_to_create_task)
- ->update($global_segment_update_data);
- }
- if ($global_voice_type) {
- $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
- $episode_roles = is_array($episode_roles) ? $episode_roles : [];
- $roles_updated = false;
- foreach ($episode_roles as &$role) {
- // 通过 role 字段匹配角色名,而不是 voice_name
- if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
- continue;
- }
- $role['voice_type'] = $global_voice_type;
- $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
- $role['voice_name'] = getProp($global_update_data, 'voice_name');
- $roles_updated = true;
- }
- unset($role);
- if ($roles_updated) {
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'roles' => json_encode($episode_roles, 256),
- 'updated_at' => date('Y-m-d H:i:s'),
- ]);
- }
- }
- }
- // 如果有单个分镜更新,检查是否有变化
- if (!empty($segment_update_data)) {
- // 获取当前分镜数据
- $current_segment = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->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')
- ->first();
-
- if ($current_segment) {
- $current_segment = (array)$current_segment;
-
- // 检查参数是否发生变化
- $has_changed = false;
- foreach ($segment_update_data as $field => $new_value) {
- $old_value = getProp($current_segment, $field);
- if ($old_value != $new_value) {
- $has_changed = true;
- break;
- }
- }
-
- if ($has_changed) {
- // 如果该分镜还未在列表中,添加进去
- if (!in_array($segment_id, $segment_ids_to_create_task)) {
- $segment_ids_to_create_task[] = $segment_id;
- $segments_data[$segment_id] = $current_segment;
- }
-
- // 更新分镜数据并清空音频URL
- $segment_update_data['audio_url'] = '';
- $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
- DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
- }
- }
- }
- // 为所有有变化的分镜创建音频合成任务
- // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
- if (!empty($segment_ids_to_create_task)) {
- foreach ($segment_ids_to_create_task as $sid) {
- // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
- if ($sid === $segment_id && $has_all_special_params) {
- continue;
- }
-
- // 重新获取更新后的分镜数据
- $updated_segment = DB::table('mp_episode_segments')
- ->where('segment_id', $sid)
- ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
- ->first();
-
- if (!$updated_segment) continue;
-
- $updated_segment = (array)$updated_segment;
-
- // 检查dialogue是否为空
- $dialogue = getProp($updated_segment, 'dialogue');
- if (empty($dialogue)) {
- // dialogue为空时,直接写入默认音频信息
- DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
- 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
- 'audio_duration' => 2.0,
- 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- continue;
- }
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($updated_segment, 'voice_actor'),
- 'voice_type' => getProp($updated_segment, 'voice_type'),
- 'voice_name' => getProp($updated_segment, 'voice_name'),
- 'emotion' => getProp($updated_segment, 'emotion'),
- 'emotion_type' => getProp($updated_segment, 'emotion_type'),
- 'gender' => getProp($updated_segment, 'gender'),
- 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
- 'pitch' => getProp($updated_segment, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $sid,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ]);
-
- if (!$dubTaskId) {
- dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
- continue;
- }
- // 将任务ID添加到Redis列表中
- Redis::lpush('dub_video_task_queue', $dubTaskId);
-
- // 请求远程服务器执行生成
- try {
- sleep(1);
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
-
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
- logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
- logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
- }
- }
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- return true;
- }
- public function episodePicsInfo($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- // 参数验证
- if (!$anime_id && !$episode_id) {
- Utils::throwError('20003:请提供动漫ID或分集ID');
- }
- // 根据参数获取数据源
- if ($episode_id) {
- // 从剧集表获取
- $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$source) Utils::throwError('20003:该剧集不存在');
- $table_name = 'mp_anime_episodes';
- $id_field = 'id';
- $id_value = $episode_id;
-
- // 获取剧集的anime_id用于继承全局数据
- $anime_id = getProp($source, 'anime_id');
- } else {
- // 从动漫表获取
- $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
- if (!$source) Utils::throwError('20003:该动漫不存在');
- $table_name = 'mp_animes';
- $id_field = 'id';
- $id_value = $anime_id;
- }
- $source = (array)$source;
- $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
- $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
- $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
-
- // 如果是分集数据,需要处理继承和任务创建逻辑
- if ($episode_id) {
- $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
- }
- // 返回生成器函数,用于 SSE 流式输出
- return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
- $startTime = time();
- $maxDuration = 600; // 10分钟超时
- $checkInterval = 3; // 每3秒检查一次
- // Redis 缓存键
- $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
-
- // 生成当前数据的哈希值用于比较
- $generateHash = function($roles, $scenes, $props) {
- return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
- };
- // 发送初始数据
- $currentHash = $generateHash($roles, $scenes, $props);
- Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
- echo "data: " . json_encode([
- 'type' => 'init',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'props' => $props,
- 'start_time' => $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- if (ob_get_level() > 0) {
- ob_flush();
- }
- flush();
- // 持续轮询任务状态
- while (time() - $startTime < $maxDuration) {
- $hasProcessing = false;
- $updated = false;
- // 检查角色任务状态
- foreach ($roles as $index => &$role) {
- $task_id = getProp($role, 'task_id');
- $task_status = getProp($role, 'task_status');
- $existing_url = getProp($role, 'url');
- // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
- if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
- $hasProcessing = ($task_status === 'processing');
-
- // 查询任务状态
- $task = DB::table('mp_generate_pic_tasks')
- ->where('id', $task_id)
- ->select('id', 'status', 'result_url', 'error_message')
- ->first();
- if ($task) {
- $task = (array)$task;
- $status = getProp($task, 'status');
- // 如果任务完成或失败
- if (in_array($status, ['success', 'failed'])) {
- $role['task_status'] = $status;
-
- if ($status === 'success') {
- $result_url = getProp($task, 'result_url');
- if ($result_url) {
- $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
- if (is_array($result_urls) && !empty($result_urls[0])) {
- $role['url'] = $result_urls[0];
- }
- }
- }
-
- $updated = true;
- } else if ($status === 'processing') {
- $hasProcessing = true;
- }
- }
- }
- }
- // 检查场景任务状态
- foreach ($scenes as $index => &$scene) {
- $task_id = getProp($scene, 'task_id');
- $task_status = getProp($scene, 'task_status');
- $existing_url = getProp($scene, 'url');
- // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
- if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
- $hasProcessing = ($task_status === 'processing');
-
- // 查询任务状态
- $task = DB::table('mp_generate_pic_tasks')
- ->where('id', $task_id)
- ->select('id', 'status', 'result_url', 'error_message')
- ->first();
- if ($task) {
- $task = (array)$task;
- $status = getProp($task, 'status');
- // 如果任务完成或失败
- if (in_array($status, ['success', 'failed'])) {
- $scene['task_status'] = $status;
-
- if ($status === 'success') {
- $result_url = getProp($task, 'result_url');
- if ($result_url) {
- $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
- if (is_array($result_urls) && !empty($result_urls[0])) {
- $scene['url'] = $result_urls[0];
- }
- }
- }
-
- $updated = true;
- } else if ($status === 'processing') {
- $hasProcessing = true;
- }
- }
- }
- }
- // 检查道具任务状态
- foreach ($props as $index => &$prop) {
- $task_id = getProp($prop, 'task_id');
- $task_status = getProp($prop, 'task_status');
- $existing_url = getProp($prop, 'url');
- // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
- if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
- $hasProcessing = ($task_status === 'processing');
-
- // 查询任务状态
- $task = DB::table('mp_generate_pic_tasks')
- ->where('id', $task_id)
- ->select('id', 'status', 'result_url', 'error_message')
- ->first();
- if ($task) {
- $task = (array)$task;
- $status = getProp($task, 'status');
- // 如果任务完成或失败
- if (in_array($status, ['success', 'failed'])) {
- $prop['task_status'] = $status;
-
- if ($status === 'success') {
- $result_url = getProp($task, 'result_url');
- if ($result_url) {
- $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
- if (is_array($result_urls) && !empty($result_urls[0])) {
- $prop['url'] = $result_urls[0];
- }
- }
- }
-
- $updated = true;
- } else if ($status === 'processing') {
- $hasProcessing = true;
- }
- }
- }
- }
- // 如果有更新,检查数据是否真的变化了(通过哈希对比)
- if ($updated) {
- $newHash = $generateHash($roles, $scenes, $props);
- $cachedHash = Redis::get($cacheKey);
- // 只有当数据真正变化时才更新数据库和发送事件
- if ($newHash !== $cachedHash) {
- try {
- // 更新数据库
- DB::table($table_name)->where($id_field, $id_value)->update([
- 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
- 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
- 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- // 更新缓存
- Redis::setex($cacheKey, 600, $newHash);
- // 发送更新事件
- echo "data: " . json_encode([
- 'type' => 'update',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'props' => $props,
- 'elapsed_time' => time() - $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- if (ob_get_level() > 0) {
- ob_flush();
- }
- flush();
- } catch (\Exception $e) {
- dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
- }
- } else {
- // 即使哈希相同,如果有URL更新也要发送事件
- $hasUrlUpdate = false;
- foreach ($roles as $role) {
- if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
- $hasUrlUpdate = true;
- break;
- }
- }
- if (!$hasUrlUpdate) {
- foreach ($scenes as $scene) {
- if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
- $hasUrlUpdate = true;
- break;
- }
- }
- }
- if (!$hasUrlUpdate) {
- foreach ($props as $prop) {
- if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
- $hasUrlUpdate = true;
- break;
- }
- }
- }
-
- if ($hasUrlUpdate) {
- // 强制更新数据库和发送事件
- try {
- DB::table($table_name)->where($id_field, $id_value)->update([
- 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
- 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
- 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- // 更新缓存
- Redis::setex($cacheKey, 600, $newHash);
- // 发送更新事件
- echo "data: " . json_encode([
- 'type' => 'update',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'props' => $props,
- 'elapsed_time' => time() - $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- if (ob_get_level() > 0) {
- ob_flush();
- }
- flush();
- } catch (\Exception $e) {
- dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
- }
- }
- }
- }
- // 如果所有任务都已完成,发送完成事件并退出
- if (!$hasProcessing) {
- // 查询数据库中的最终数据,确保返回最新的完整数据
- try {
- $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
- if ($finalSource) {
- $finalSource = (array)$finalSource;
- $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
- $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
- $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
-
- // 使用数据库中的最终数据
- $roles = $finalRoles;
- $scenes = $finalScenes;
- $props = $finalProps;
- }
- } catch (\Exception $e) {
- dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
- // 如果查询失败,继续使用内存中的数据
- }
-
- // 清理缓存
- Redis::del($cacheKey);
- echo "data: " . json_encode([
- 'type' => 'completed',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'props' => $props,
- 'total_time' => time() - $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- if (ob_get_level() > 0) {
- ob_flush();
- }
- flush();
- break;
- }
- // 等待下次检查
- sleep($checkInterval);
- }
- // 超时处理
- if (time() - $startTime >= $maxDuration) {
- // 查询数据库中的最终数据,即使超时也要返回最新数据
- try {
- $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
- if ($finalSource) {
- $finalSource = (array)$finalSource;
- $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
- $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
- $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
-
- // 使用数据库中的最终数据
- $roles = $finalRoles;
- $scenes = $finalScenes;
- $props = $finalProps;
- }
- } catch (\Exception $e) {
- dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
- // 如果查询失败,继续使用内存中的数据
- }
-
- // 清理缓存
- Redis::del($cacheKey);
- echo "data: " . json_encode([
- 'type' => 'timeout',
- 'message' => '轮询超时,请刷新页面查看最新状态',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'props' => $props
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- if (ob_get_level() > 0) {
- ob_flush();
- }
- flush();
- }
- };
- }
- public function clipSegmentVideo($data) {
- $segment_id = getProp($data, 'segment_id');
- $video_time_point_start = getProp($data, 'video_time_point_start');
- $video_time_point_end = getProp($data, 'video_time_point_end');
- if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
- Utils::throwError('20003:参数异常');
- }
- if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
- Utils::throwError('20003:该分镜没有视频,无法裁剪');
- }
- $video_duration = $video_time_point_end - $video_time_point_start;
- if (!$video_duration < 0) Utils::throwError('20003:参数异常');
- return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
- 'video_duration' => $video_duration,
- 'video_time_point_start' => $video_time_point_start,
- 'video_time_point_end' => $video_time_point_end,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- // 轮训获取图片任务结果
- private function loopGetPicTaskResult($task_id) {
- $task = MpGeneratePicTask::where('id', $task_id)->first();
- if (!$task) {
- return '';
- }
- // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
- $model = getProp($task, 'model');
- $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
- $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
- $isSyncModel = $isVolcModel || $isGptModel;
- // 轮询查询任务状态(火山API和即梦AI都需要轮询)
- $start_count = 0;
- $img_url = '';
- while ($start_count <= 60) { // 循环20次请求,每3s一次
- sleep(3);
- $task = MpGeneratePicTask::where('id', $task_id)->first();
-
- // 如果任务已经完成,直接返回结果
- if ($task->status === 'success' && $task->result_url) {
- $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
- return is_array($result_urls) ? $result_urls[0] : $task->result_url;
- }
-
- // 如果任务已失败,返回空
- if ($task->status === 'failed') {
- return '';
- }
- if ($isSyncModel) continue;
-
- // 查询任务状态
- $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
- if ($statusInfo['status'] === 'success') {
- $task->updateStatus('success', [
- 'result_url' => $statusInfo['result_url'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
- // 同步调整分镜图片状态和结果
- if (getProp($task, 'alias_segment_id')) {
- DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
- 'img_url' => $statusInfo['result_url'][0],
- 'pic_task_status' => '已完成',
- ]);
- }
- $img_url = $statusInfo['result_url'][0];
- break;
- } elseif ($statusInfo['status'] === 'failed') {
- $task->updateStatus('failed', [
- 'error_message' => $statusInfo['error_message'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
- if (getProp($task, 'alias_segment_id')) {
- DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
- 'pic_task_status' => '失败',
- ]);
- }
- break;
- }
- $start_count++;
- }
- return $img_url;
- }
- /**
- * 从分镜内容中提取涉及的角色
- */
- private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
- $found_characters = [];
-
- foreach ($available_characters as $character) {
- // 检查角色名称是否在分镜内容中出现
- if (strpos($segment_content, $character) !== false) {
- $found_characters[] = $character;
- }
- }
- if (!$found_characters) {
- foreach ($roles as $character) {
- // 检查角色名称是否在分镜内容中出现
- if (strpos($segment_content, $character) !== false) {
- $found_characters[] = $character;
- }
- }
- }
-
- return array_unique($found_characters);
- }
- // 从分镜剧本中提取关键字段
- private function handleSegmentContent(&$data) {
- $segmentContent = getProp($data, 'segment_content');
- // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
- $segmentData = [
- 'description' => '',
- 'composition' => '',
- 'camera_movement' => '',
- 'voice_actor' => '',
- 'dialogue' => '',
- 'frame_type' => '',
- 'scene' => '', // 场景
- 'characters' => '', // 出镜角色
- 'tail_frame' => '', // 尾帧描述
- 'emotion' => '中性', // 情感
- 'gender' => '0', // 性别(0未知,1男,2女)
- 'speed_ratio' => 0, // 语速
- 'loudness_ratio' => 0, // 音量
- 'emotion_scale' => 4, // 情感强度
- 'pitch' => 0, // 音调
- ];
-
- // 用于存储需要从 segment_content 中移除的匹配项
- $replaceEmptyArr = [];
-
- // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
- if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
- $segmentData['description'] = trim($descMatch[1]);
- $data['description'] = trim($descMatch[1]);
- }
- if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
- $segmentData['composition'] = trim($compMatch[1]);
- $data['composition'] = trim($compMatch[1]);
- }
- if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
- $segmentData['camera_movement'] = trim($cameraMatch[1]);
- $data['camera_movement'] = trim($cameraMatch[1]);
- }
- if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
- $segmentData['voice_actor'] = trim($voiceMatch[1]);
- $data['voice_actor'] = trim($voiceMatch[1]);
- }
- if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
- $segmentData['dialogue'] = trim($dialogueMatch[1]);
- $data['dialogue'] = trim($dialogueMatch[1]);
- }
- if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
- $segmentData['frame_type'] = trim($frameMatch[1]);
- $data['frame_type'] = trim($frameMatch[1]);
- }
- // 场景字段
- if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
- $segmentData['scene'] = trim($sceneMatch[1]);
- $data['scene'] = trim($sceneMatch[1]);
- }
- // 出镜角色字段
- if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
- $segmentData['characters'] = trim($charactersMatch[1]);
- $data['characters'] = trim($charactersMatch[1]);
- }
- // 尾帧描述字段
- if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
- $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
- $data['tail_frame'] = trim($tailFrameMatch[1]);
- }
-
- // 情感字段
- if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
- $replaceEmptyArr[] = trim($emotionMatch[0]);
- $segmentData['emotion'] = trim($emotionMatch[1]);
- $data['emotion'] = trim($emotionMatch[1]);
- }
-
- // 性别字段
- if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
- $replaceEmptyArr[] = trim($genderMatch[0]);
- $genderStr = trim($genderMatch[1]);
- if (strpos($genderStr, '男') !== false || $genderStr === '1') {
- $segmentData['gender'] = '1';
- $data['gender'] = '1';
- } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
- $segmentData['gender'] = '2';
- $data['gender'] = '2';
- } else {
- $segmentData['gender'] = '0';
- $data['gender'] = '0';
- }
- }
-
- // 语速字段
- if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
- $replaceEmptyArr[] = trim($speedMatch[0]);
- $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
- $data['speed_ratio'] = (float)trim($speedMatch[1]);
- }
-
- // 音量字段
- if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
- $replaceEmptyArr[] = trim($loudnessMatch[0]);
- $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
- $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
- }
-
- // 情感强度字段
- if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
- $replaceEmptyArr[] = trim($scaleMatch[0]);
- $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
- $data['emotion_scale'] = (int)trim($scaleMatch[1]);
- }
-
- // 音调字段
- if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
- $replaceEmptyArr[] = trim($pitchMatch[0]);
- $segmentData['pitch'] = (int)trim($pitchMatch[1]);
- $data['pitch'] = (int)trim($pitchMatch[1]);
- }
-
- // 从 segment_content 中移除已提取的配音参数字段
- if (!empty($replaceEmptyArr)) {
- $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
- }
-
- // 如果有配音角色,查询音色信息并验证情感
- $voice_actor = $segmentData['voice_actor'];
- if (!empty($voice_actor) && $voice_actor !== '旁白') {
- // 从当前分镜所属的剧集或动漫中查找角色音色信息
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
-
- // 优先从剧集的角色列表中查找
- $roles = [];
- if ($episode_id) {
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if ($episode && getProp($episode, 'roles')) {
- $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
- }
- }
-
- // 如果剧集中没有,从动漫的角色列表中查找
- if (empty($roles) && $anime_id) {
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- if ($anime && getProp($anime, 'roles')) {
- $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
- }
- }
-
- // 查找匹配的角色音色信息
- $timbre_info = null;
- foreach ($roles as $role) {
- if (getProp($role, 'role') === $voice_actor) {
- $timbre_info = $role;
- break;
- }
- }
-
- // 如果找到音色信息,添加到数据中
- if ($timbre_info) {
- $voice_type = getProp($timbre_info, 'voice_type');
- $voice_name = getProp($timbre_info, 'voice_name');
- $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
-
- if ($voice_type) {
- $data['voice_type'] = $voice_type;
- $segmentData['voice_type'] = $voice_type;
- }
- if ($voice_name) {
- $data['voice_name'] = $voice_name;
- $segmentData['voice_name'] = $voice_name;
- }
- if ($voice_audio_url) {
- $data['voice_audio_url'] = $voice_audio_url;
- $segmentData['voice_audio_url'] = $voice_audio_url;
- }
-
- // 验证情感是否在音色支持的情感列表中
- if ($voice_type) {
- $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
- if ($timbre_emotion) {
- $timbre_emotion = explode(',', $timbre_emotion);
- } else {
- $timbre_emotion = [];
- }
- $emotion = getProp($segmentData, 'emotion', '中性');
- if (!in_array($emotion, $timbre_emotion)) {
- $emotion = '中性';
- }
- $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
- $emotion_list = array_flip($emotion_list);
- $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
- $data['emotion_type'] = $emotion_type;
- $segmentData['emotion_type'] = $emotion_type;
- }
- }
- }
- return $segmentData;
- }
- public function createSegmentVideoTask($data) {
- $segment_id = getProp($data, 'segment_id');
- $tail_frame = getProp($data, 'tail_frame');
- $first_frame_url = getProp($data, 'first_frame_url');
- $tail_frame_url = getProp($data, 'tail_frame_url');
- $generate_audio = getProp($data, 'generate_audio', 0);
-
- if (!$segment_id) {
- Utils::throwError('1002:分镜ID不能为空');
- }
-
- // 获取分镜信息
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$segment) {
- Utils::throwError('20003:分镜不存在');
- }
-
- $segment = (array)$segment;
- $episode_id = getProp($segment, 'episode_id');
- $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
- if (!$ratio) $ratio = '9:16';
-
- // 获取分镜内容
- $segmentContent = getProp($segment, 'segment_content', '');
-
- // 检查 $segmentContent 中是否已有尾帧描述
- $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
-
- // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
- $finalTailFrame = '';
- if ($tail_frame) {
- // 用户输入了尾帧描述,优先使用
- $finalTailFrame = $tail_frame;
-
- // 如果 segmentContent 中已有尾帧描述,需要替换
- if ($contentHasTailFrame) {
- $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
- }
- } elseif ($contentHasTailFrame) {
- // segmentContent 中有尾帧描述,使用它
- $finalTailFrame = trim($contentTailFrameMatch[1]);
- } else {
- // 两者都没有,使用分镜表中的尾帧描述
- $finalTailFrame = getProp($segment, 'tail_frame', '');
- }
-
- // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
- $hasDialogue = false;
- if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
- $dialogue = trim($dialogueMatch[1]);
-
- // 如果台词不为空且不是"无"
- if (!empty($dialogue) && $dialogue !== '无') {
- // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
- $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
- if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
- $hasDialogue = true;
- }
- $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
- $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
- // 句首或句尾没有中文双引号,则分别添加中文左右双引号
- if (!preg_match('/^[“]/', $dialogue)) {
- $dialogue = '“' . $dialogue;
- }
- if (!preg_match('/[”]$/', $dialogue)) {
- $dialogue .= '”';
- }
-
- // 将修改后的台词替换回 $segmentContent
- $originalDialogue = $dialogueMatch[1];
- $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
- }
- }
- // 构建完整的提示词
- $fullPrompt = $segmentContent;
- if ($finalTailFrame && !$contentHasTailFrame) {
- // 只有当 segmentContent 中没有尾帧描述时才追加
- $fullPrompt .= "\n尾帧描述:$finalTailFrame";
- }
-
- // 去除多余的换行符(将连续多个换行符替换为单个换行符)
- $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
- $fullPrompt = trim($fullPrompt);
- // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
- $current_generate_audio = $hasDialogue ? $generate_audio : 0;
-
- // 智能选择视频时长
- // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
- $videoDuration = -1;
-
- // 处理视频模型
- $model = getProp($data, 'model');
- if (!$model) {
- // 用户没有输入,从episode表获取
- $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
- $model = getProp($episode, 'video_model');
- if (!$model) {
- // episode表也没有,使用默认值
- $model = 'doubao-seedance-1-5-pro-251215';
- }
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'doubao-seedance-1-5-pro-251215';
- }
- // 保存到episode表
- $episode_id = getProp($segment, 'episode_id');
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'video_model' => $model,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 构建视频生成参数
- $videoParams = [
- 'model' => $model,
- 'alias_segment_id' => $segment_id,
- 'prompt' => trim($fullPrompt),
- 'video_duration' => $videoDuration,
- 'video_resolution' => '720P',
- 'seed' => -1,
- 'ratio' => $ratio,
- 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
- 'draft' => false,
- 'watermark' => false,
- 'camera_fixed' => false,
- // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
- ];
-
- // 如果分镜有图片,作为首帧
- $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
- $hasVideo = !empty(getProp($segment, 'video_url'));
-
- if ($hasImage) {
- if ($first_frame_url) {
- $videoParams['first_frame_url'] = $first_frame_url;
- }else {
- $videoParams['first_frame_url'] = getProp($segment, 'img_url');
- }
- if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
- }
-
- // 构建content数组
- $videoParams['content'] = [
- [
- 'type' => 'text',
- 'text' => $videoParams['prompt'],
- ]
- ];
-
- // 如果有首帧图片,添加到content中
- if ($hasImage) {
- 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'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'reference_image',
- ];
- if (isset($videoParams['tail_frame_url'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['tail_frame_url'],
- ],
- 'role' => 'reference_image',
- ];
- }
- }else {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'first_frame',
- ];
- if (isset($videoParams['tail_frame_url'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['tail_frame_url'],
- ],
- 'role' => 'last_frame',
- ];
- }
- }
- }
-
- // 获取配音音频URL
- $audioUrl = getProp($segment, 'audio_url');
- $audioDuration = getProp($segment, 'audio_duration');
-
- // 音频传入的前提:必须有至少一张图片或一个视频
- $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
- // 余额预检:按预估时长计算所需积分,不足直接报错
- $chargeDuration = (int)ceil((float)$audioDuration);
- if ($chargeDuration <= 0) {
- $chargeDuration = 5; // 无音频时长时按默认5秒预估
- }
- $this->pointsService->checkUserPointsEnough(
- $this->pointsService->getVideoChargePoints([
- 'model' => $model,
- 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
- 'video_duration' => $chargeDuration,
- 'ratio' => $ratio,
- 'generate_audio' => $current_generate_audio,
- ])
- );
- // dd($videoParams);
-
- // 根据模型选择不同的视频生成方法
- if (strpos($model, 'jimeng') !== false) {
- // 即梦模型参数调整
- $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
- unset($videoParams['content']); // 即梦不使用content格式
- $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
- } elseif (strpos($model, 'kling') !== false) {
- // Keling模型参数调整
- $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
- $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
- unset($videoParams['ratio']);
- unset($videoParams['content']); // Keling不使用content格式
- $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
- } elseif (strpos($model, 'zhizhen') !== false) {
- // 智帧20等新模型使用统一API
- // 构建统一API参数
- $unifiedParams = [
- 'model_code' => $model,
- 'alias_segment_id' => $segment_id,
- 'prompt' => trim($fullPrompt),
- 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
- 'video_resolution' => strtolower($videoParams['video_resolution']),
- 'video_ratio' => $ratio,
- 'seed' => -1,
- ];
-
- // 构建parameters参数
- $parameters = [
- 'seconds' => $unifiedParams['video_duration'],
- 'resolution' => $unifiedParams['video_resolution'],
- 'ratio' => $ratio,
- // 'video_mode' => 'multi_image',
- // 'mode' => 'multi_image',
- 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
- ];
-
- $hasImage = false;
- // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
- if ($hasImage) {
- $parameters['first_frame_url'] = $videoParams['first_frame_url'];
- if (isset($videoParams['tail_frame_url'])) {
- $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
- }
-
- // 只有在有图片的情况下才能添加参考音频
- if ($audioUrl) {
- // $parameters['reference_audios'] = [$audioUrl];
- }
- } else {
- // 没有图片时,记录错误日志
- logDB('anime', 'error', '智帧20模型缺少首帧图片', [
- 'segment_id' => $segment_id,
- 'model' => $model
- ]);
- }
-
- $unifiedParams['parameters'] = $parameters;
-
- // 调用统一API创建任务
- $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
- } else {
- // Seedance模型(默认)
- // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
- if ($this->isKuaikuaiSeedanceModel($model)) {
- $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
- if ($canUseAudio && $audioUrl) {
- // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
- $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
- $videoParams['reference_audio_assets'] = $reference_audio_assets;
- // 优化提示词,增加音频相关描述
- $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
- $videoParams['prompt'] = $audioPrompt;
- } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
- $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
- }
- $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
- } 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'])) {
- // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
- // 添加配音音频到content中
- $videoParams['content'][] = [
- 'type' => 'audio_url',
- 'audio_url' => [
- 'url' => $audioUrl,
- ],
- 'role' => 'reference_audio',
- ];
-
- // 优化提示词,增加音频相关描述
- $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
- $videoParams['prompt'] = $audioPrompt;
- $videoParams['content'][0]['text'] = $audioPrompt;
- } else {
- if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
- $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
- }
- $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
- }
- }
-
- // 更新分镜表的视频任务信息
- DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
- 'video_task_id' => $task->id,
- 'video_task_status' => '生成中',
- 'generate_audio' => $generate_audio,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- return [
- 'task_id' => $task->id,
- 'status' => $task->status,
- 'segment_id' => $segment_id,
- 'video_duration' => $videoDuration
- ];
- }
-
- /**
- * 是否为快快AI Seedance 2.0/2.5 系列模型
- * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
- *
- * @param string $model
- * @return bool
- */
- public function isKuaikuaiSeedanceModel(string $model): bool
- {
- return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
- }
- /**
- * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
- *
- * @param string $model
- * @return bool
- */
- public function isBaiduSeedanceModel(string $model): bool
- {
- return in_array($model, [
- 'baidu-doubao-seedance-2-0-260128',
- 'baidu-doubao-seedance-2-0-fast-260128',
- 'baidu-doubao-seedance-2-0-mini-260615',
- 'baidu-doubao-seedance-2-5-260628',
- ], true);
- }
- /**
- * 是否为海外百度Seedance(dreamina真人素材空间)模型
- * 系统内使用 baidu-dreamina- 前缀名,请求网关时映射为 dreamina-* 原名
- *
- * @param string $model
- * @return bool
- */
- public function isOverseasBaiduSeedanceModel(string $model): bool
- {
- return in_array($model, [
- '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',
- ], true);
- }
- /**
- * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-doubao-* / baidu-dreamina-* / 快快AI seed-2 系列)
- * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
- *
- * @param string $model
- * @return bool
- */
- public function isSeedance20SeriesModel(string $model): bool
- {
- return strpos($model, 'doubao-seedance-2.0') !== false
- || $this->isKuaikuaiSeedanceModel($model)
- || $this->isBaiduSeedanceModel($model)
- || $this->isOverseasBaiduSeedanceModel($model);
- }
- public function createActVideoTask($data) {
- $act_id = getProp($data, 'act_id');
- $first_frame_url = getProp($data, 'first_frame_url');
- $tail_frame_url = getProp($data, 'tail_frame_url');
- $generate_audio = getProp($data, 'generate_audio', 1);
- $video_duration = getProp($data, 'video_duration');
- $video_resolution = getProp($data, 'video_resolution');
- $ratio = getProp($data, 'ratio');
- $products = getProp($data, 'products', []);
- $reference_images = array_unique(getProp($data, 'reference_images', []));
- if (!is_array($reference_images) || !is_array($products)) {
- Utils::throwError('20003:传入的参考图或资产格式不正确');
- }
-
- if (!$act_id) {
- Utils::throwError('1002:片段ID不能为空');
- }
-
- // 获取片段信息
- $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if (!$act) {
- Utils::throwError('20003:片段不存在');
- }
-
- $act = (array)$act;
- $anime_id = getProp($act, 'anime_id');
- $episode_id = getProp($act, 'episode_id');
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- $ace_mode = getProp($anime, 'ace_mode');
- $art_style_type = getProp($anime, 'art_style_type');
- $art_style = getProp($anime, 'art_style');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
- if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
- // 将资产中新出现的资产放到extra_products中
- // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
- if (!empty($products) && $episode) {
- // 获取剧集中的角色、场景和道具列表
- $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
- $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
- $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
- $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
-
- // 构建角色名称列表
- $role_names = array_column($roles, 'role');
- // 构建场景名称列表
- $scene_names = array_column($scenes, 'scene');
- // 构建道具名称列表
- $prop_names = array_column($props, 'prop');
-
- // 遍历传入的products
- foreach ($products as $product) {
- $product_name = getProp($product, 'product_name');
-
- // 如果product_name不在roles、scenes和props中
- if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
- // 查找是否在extra_products中存在同名的
- $found = false;
- foreach ($extra_products as $key => $extra_product) {
- if (getProp($extra_product, 'product_name') === $product_name) {
- // 有同名的则覆盖
- $extra_products[$key] = $product;
- $found = true;
- break;
- }
- }
-
- // 没有则新增
- if (!$found) {
- $extra_products[] = $product;
- }
- }
- }
-
- if ($extra_products) {
- // 保存到数据库
- DB::table('mp_anime_episodes')
- ->where('id', $episode_id)
- ->update([
- 'extra_products' => json_encode($extra_products, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
-
- }
-
- // 获取分镜内容
- $actContent = getProp($act, 'act_show_content', '');
- // 音效同出(默认使用)
- $current_generate_audio = $generate_audio ? 1 : 0;
- // 构建完整的提示词
- $processResult = $this->processActContentWithProducts($actContent, $products);
- $fullPrompt = $processResult['content'];
- // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
- $reference_images = array_merge($processResult['reference_images'], $reference_images);
-
- $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
-
- // 处理视频模型
- $model = getProp($data, 'model');
- if (!$model) {
- $model = getProp($episode, 'video_model');
- if (!$model) {
- // episode表也没有,使用默认值
- $model = 'seed-2';
- }
- }
- // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
- $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
- if (!in_array($model, $valid_models)) {
- $model = 'seed-2';
- }
- // 保存到episode表(仅在专用方法中更新模型)
- // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- // 'video_model' => $model,
- // 'updated_at' => date('Y-m-d H:i:s')
- // ]);
- // 余额预检:按预估时长计算所需积分,不足直接报错
- $chargeDuration = (int)$videoDuration;
- if ($chargeDuration <= 0) {
- $chargeDuration = 5; // 无时长时按默认5秒预估
- }
- $this->pointsService->checkUserPointsEnough(
- $this->pointsService->getVideoChargePoints([
- 'model' => $model,
- 'video_resolution' => strtolower($video_resolution ?? '720p'),
- 'video_duration' => $chargeDuration,
- 'ratio' => $ratio,
- 'generate_audio' => $current_generate_audio,
- ])
- );
-
- // 构建视频生成参数
- $videoParams = [
- 'model' => $model,
- 'alias_act_id' => $act_id,
- 'prompt' => trim($fullPrompt),
- 'video_duration' => $videoDuration,
- 'video_resolution' => $video_resolution,
- 'seed' => -1,
- 'ratio' => $ratio,
- 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
- 'draft' => false,
- 'watermark' => false,
- 'camera_fixed' => false,
- // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
- ];
- // 如果分镜有图片,作为首帧
- $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
- $hasVideo = !empty(getProp($act, 'video_url'));
-
- if ($hasImage) {
- if ($first_frame_url) {
- $videoParams['first_frame_url'] = $first_frame_url;
- }else {
- $videoParams['first_frame_url'] = getProp($act, 'img_url');
- }
- if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
- }
-
- // 构建content数组
- $videoParams['content'] = [
- [
- 'type' => 'text',
- 'text' => $videoParams['prompt'],
- ]
- ];
-
- // 如果有首帧图片,添加到content中
- if ($hasImage) {
- 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'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'reference_image',
- ];
- if (isset($videoParams['tail_frame_url'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['tail_frame_url'],
- ],
- 'role' => 'reference_image',
- ];
- }
- }else {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'first_frame',
- ];
- if (isset($videoParams['tail_frame_url'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['tail_frame_url'],
- ],
- 'role' => 'last_frame',
- ];
- }
- }
- }
- // dd($videoParams);
-
- // 根据模型选择不同的视频生成方法
- try {
- if (strpos($model, 'jimeng') !== false) {
- // 即梦模型参数调整
- unset($videoParams['content']); // 即梦不使用content格式
- $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
- } elseif (strpos($model, 'kling') !== false) {
- // Keling模型参数调整
- $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
- unset($videoParams['ratio']);
- unset($videoParams['content']); // Keling不使用content格式
- $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
- } elseif (strpos($model, 'zhizhen') !== false) {
- // 智帧20等新模型使用统一API
- // 构建统一API参数
- $unifiedParams = [
- 'model_code' => $model,
- 'alias_act_id' => $act_id,
- 'prompt' => trim($fullPrompt),
- 'video_duration' => $videoDuration,
- 'video_resolution' => strtolower($videoParams['video_resolution']),
- 'video_ratio' => $ratio,
- 'seed' => -1,
- ];
-
- // 构建parameters参数
- $parameters = [
- 'seconds' => $unifiedParams['video_duration'],
- 'resolution' => $unifiedParams['video_resolution'],
- 'ratio' => $ratio,
- // 'video_mode' => 'multi_image',
- // 'mode' => 'multi_image',
- 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
- ];
-
- $hasImage = false;
- // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
- if ($hasImage) {
- $parameters['first_frame_url'] = $videoParams['first_frame_url'];
- if (isset($videoParams['tail_frame_url'])) {
- $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
- }
- } else {
- // 没有图片时,记录错误日志
- logDB('anime', 'error', '智帧20模型缺少首帧图片', [
- 'act_id' => $act_id,
- 'model' => $model
- ]);
- }
- if ($reference_images) {
- // 限制只传入9张参考图
- $reference_images = array_slice($reference_images, 0, 9);
- // 在处理之前先保存原始reference_images到任务参数中
- $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
- $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
- $parameters['reference_images'] = $reference_images;
- $parameters['video_mode'] = 'multi_image';
- $parameters['mode'] = 'multi_image';
- }
-
- $unifiedParams['parameters'] = $parameters;
-
- // 调用统一API创建任务
- $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
- } elseif ($this->isSeedance20SeriesModel($model)) {
- // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
- $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
- $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
- // 保存原始参考图用于任务记录
- $videoParams['reference_images'] = $reference_images;
- if ($reference_images) {
- // 限制只传入9张参考图
- $reference_images = array_slice($reference_images, 0, 9);
- // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
- $videoParams['ref_image_url'] = json_encode($reference_images, 256);
- // 参考图上传为素材(国内百度/海外百度dreamina/快快AI),上传失败时同步清理提示词中的<图片N>标记
- $reference_image_assets = $isKuaikuai
- ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
- : ($isDreamina
- ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $fullPrompt)
- : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt));
- // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
- $videoParams['prompt'] = trim($fullPrompt);
- $videoParams['content'][0]['text'] = trim($fullPrompt);
- $videoParams['reference_image_assets'] = $reference_image_assets;
- }
- // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
- if ($isKuaikuai) {
- $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
- $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
- } else {
- $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
- }
- } else {
- $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
- }
- } catch (ApiException $e) {
- // 上游调用抛出的网关异常统一做友好化处理;本地业务错误(非1001)保持原提示不变
- if ($e->getCode() === 1001) {
- Utils::throwError('1001:' . mapErrorMessage($e->getMessage()));
- }
- throw $e;
- } catch (\Exception $e) {
- // 其他未包装的异常,同样只对报错信息做格式化,便于前端展示友好提示
- Utils::throwError('20003:' . mapErrorMessage($e->getMessage()));
- }
-
- // 更新分镜表的视频任务信息
- DB::table('mp_episode_segments')->where('id', $act_id)->update([
- 'video_task_id' => $task->id,
- 'video_task_status' => '生成中',
- 'generate_audio' => $generate_audio,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
- $episode_number = getProp($act, 'episode_number');
- $act_number = getProp($act, 'act_number');
- if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
- Redis::sadd('anime_act_first_frame_urls', $act_id);
- }
-
- $result = [
- 'task_id' => $task->id,
- 'status' => $task->status,
- 'act_id' => $act_id,
- 'video_duration' => $videoDuration
- ];
- // 仅当任务提交阶段就已失败时,附带格式化后的错误信息;正常返回结构不受影响
- if ($task->status === 'failed' && !empty($task->error_message)) {
- $result['error_message'] = mapErrorMessage($task->error_message);
- }
- return $result;
- }
- /**
- * 文生视频通用方法
- * 支持传入视频参数、提示词、参考图等信息,不支持products入参
- * 用户提示词不做任何处理,直接组装参数后根据模型调用
- *
- * @param array $data 请求参数
- * @return array
- */
- public function generateVideo($data) {
- $prompt = getProp($data, 'prompt');
- if (empty($prompt)) {
- Utils::throwError('20003:提示词不能为空');
- }
- $model = getProp($data, 'model');
- if (!$model) {
- $model = 'seed-2';
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
- $video_duration = getProp($data, 'video_duration', 5);
- // 默认超分720p档(按480p生成后本地超分到720p);480p为原始档需前端显式指定
- $video_resolution = getProp($data, 'video_resolution', 'sr_720p');
- $ratio = getProp($data, 'ratio', '9:16');
- $generate_audio = getProp($data, 'generate_audio', 1);
- $seed = getProp($data, 'seed', -1);
- $first_frame_url = getProp($data, 'first_frame_url');
- $tail_frame_url = getProp($data, 'tail_frame_url');
- // 参考图(支持数组或JSON字符串,最多9张)
- $reference_images = getProp($data, 'reference_images', []);
- if (is_string($reference_images)) {
- $reference_images = json_decode($reference_images, true) ?: [];
- }
- if (!is_array($reference_images)) {
- Utils::throwError('20003:参考图格式不正确');
- }
- $reference_images = array_values(array_unique(array_filter($reference_images)));
- $reference_images = array_slice($reference_images, 0, 9);
- // 参考视频(支持数组或JSON字符串,最多3个)
- $reference_videos = getProp($data, 'reference_videos', []);
- if (is_string($reference_videos)) {
- $reference_videos = json_decode($reference_videos, true) ?: [];
- }
- if (!is_array($reference_videos)) {
- Utils::throwError('20003:参考视频格式不正确');
- }
- $reference_videos = array_values(array_unique(array_filter($reference_videos)));
- if (count($reference_videos) > 3) {
- Utils::throwError('20003:参考视频最多选择3个');
- }
- $reference_videos = array_slice($reference_videos, 0, 3);
- // 参考音频(支持数组或JSON字符串,最多3个)
- $reference_audios = getProp($data, 'reference_audios', []);
- if (is_string($reference_audios)) {
- $reference_audios = json_decode($reference_audios, true) ?: [];
- }
- if (!is_array($reference_audios)) {
- Utils::throwError('20003:参考音频格式不正确');
- }
- $reference_audios = array_values(array_unique(array_filter($reference_audios)));
- if (count($reference_audios) > 3) {
- Utils::throwError('20003:参考音频最多选择3个');
- }
- $reference_audios = array_slice($reference_audios, 0, 3);
- // 余额预检:按预估时长计算所需积分,不足直接报错
- $chargeDuration = (int)ceil((float)$video_duration);
- if ($chargeDuration <= 0) {
- $chargeDuration = 5; // 无时长时按默认5秒预估
- }
- $this->pointsService->checkUserPointsEnough(
- $this->pointsService->getVideoChargePoints([
- 'model' => $model,
- 'video_resolution' => strtolower($video_resolution ?? '720p'),
- 'video_duration' => $chargeDuration,
- 'ratio' => $ratio,
- 'generate_audio' => (int)$generate_audio,
- ])
- );
- // 构建视频生成参数(用户参数直接透传,提示词不做处理)
- $videoParams = [
- 'model' => $model,
- 'prompt' => $prompt,
- 'video_duration' => $video_duration,
- 'video_resolution' => $video_resolution,
- 'seed' => $seed,
- 'ratio' => $ratio,
- 'generate_audio' => (int)$generate_audio === 1 ? true : false,
- 'draft' => getProp($data, 'draft', false),
- 'watermark' => getProp($data, 'watermark', false),
- 'camera_fixed' => getProp($data, 'camera_fixed', false),
- ];
- if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
- if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
- // 构建content数组
- $videoParams['content'] = [
- [
- 'type' => 'text',
- 'text' => $prompt,
- ]
- ];
- // 根据模型选择不同的视频生成方法
- if (strpos($model, 'jimeng') !== false) {
- // 即梦模型参数调整
- unset($videoParams['content']); // 即梦不使用content格式
- $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
- } elseif (strpos($model, 'kling') !== false) {
- // 可灵模型参数调整
- $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
- unset($videoParams['ratio']);
- unset($videoParams['content']); // 可灵不使用content格式
- $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
- } elseif (strpos($model, 'zhizhen') !== false) {
- // 智帧等新模型使用统一API
- $unifiedParams = [
- 'model_code' => $model,
- 'prompt' => $prompt,
- 'video_duration' => $video_duration,
- 'video_resolution' => strtolower($video_resolution),
- 'video_ratio' => $ratio,
- 'seed' => $seed,
- ];
- // 构建parameters参数
- $parameters = [
- 'seconds' => $unifiedParams['video_duration'],
- 'resolution' => $unifiedParams['video_resolution'],
- 'ratio' => $ratio,
- 'generate_audio' => (int)$generate_audio === 1 ? true : false,
- ];
- // 首帧和尾帧
- if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
- if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
- // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
- $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
- if ($refImageUrls) {
- $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
- }
- // 参考图处理
- if ($reference_images) {
- $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
- $parameters['reference_images'] = $reference_images;
- $parameters['video_mode'] = 'multi_image';
- $parameters['mode'] = 'multi_image';
- }
- // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
- if ($reference_videos) {
- $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
- $parameters['reference_videos'] = $reference_videos;
- }
- if ($reference_audios) {
- $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
- $parameters['reference_audios'] = $reference_audios;
- }
- $unifiedParams['parameters'] = $parameters;
- // 调用统一API创建任务
- $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
- } elseif ($this->isSeedance20SeriesModel($model)) {
- // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
- $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
- $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
- $videoParams['reference_images'] = $reference_images;
- // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
- $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
- if ($refImageUrls) {
- $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
- }
- if ($reference_images) {
- // 参考图上传为素材(国内百度/海外百度dreamina/快快AI)
- $reference_image_assets = $isKuaikuai
- ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
- : ($isDreamina
- ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $videoParams['prompt'])
- : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']));
- $videoParams['reference_image_assets'] = $reference_image_assets;
- }
- // 参考视频上传为素材(国内百度/海外百度dreamina/快快AI)
- if ($reference_videos) {
- $reference_video_assets = $isKuaikuai
- ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
- : ($isDreamina
- ? $this->aiVideoGenerationService->processReferenceVideosToBaiduDreaminaAssets($reference_videos, $videoParams['prompt'])
- : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']));
- $videoParams['reference_video_assets'] = $reference_video_assets;
- }
- // 参考音频上传为素材(国内百度/海外百度dreamina/快快AI)
- if ($reference_audios) {
- $reference_audio_assets = $isKuaikuai
- ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
- : ($isDreamina
- ? $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($reference_audios, $videoParams['prompt'])
- : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']));
- $videoParams['reference_audio_assets'] = $reference_audio_assets;
- }
- // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
- if ($reference_images || $reference_videos || $reference_audios) {
- $videoParams['content'][0]['text'] = $videoParams['prompt'];
- }
- // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
- if ($isKuaikuai) {
- $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
- $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
- } else {
- $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
- }
- } else {
- // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
- // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
- $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
- if ($refImageUrls) {
- $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
- }
- if ($reference_videos) {
- foreach ($reference_videos as $videoUrl) {
- $videoParams['content'][] = [
- 'type' => 'video_url',
- 'video_url' => [
- 'url' => $videoUrl,
- ],
- 'role' => 'reference_video',
- ];
- }
- }
- if ($reference_audios) {
- foreach ($reference_audios as $audioUrl) {
- $videoParams['content'][] = [
- 'type' => 'audio_url',
- 'audio_url' => [
- 'url' => $audioUrl,
- ],
- 'role' => 'reference_audio',
- ];
- }
- }
- $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
- }
- return [
- 'task_id' => $task->id,
- 'status' => $task->status,
- 'model' => $model,
- 'video_duration' => $video_duration,
- 'video_resolution' => $video_resolution,
- 'ratio' => $ratio
- ];
- }
- /**
- * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
- *
- * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
- * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
- * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
- *
- * @param array $data
- * @return array
- */
- public function previewCharge(array $data): array
- {
- $mode = (string)getProp($data, 'mode', '');
- if (!in_array($mode, ['chat', 'image', 'video'])) {
- Utils::throwError('1003:请传入mode参数(chat/image/video)');
- }
- // 视频计费场景(video_generation/video_to_video),默认视频生成
- $scene = (string)getProp($data, 'scene', 'video_generation');
- // 未显式传scene且带参考视频时,自动按video_to_video定价
- if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
- $scene = 'video_to_video';
- }
- $items = [];
- $model = '';
- $resolution = '';
- if ($mode === 'video') {
- // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
- $model = (string)getProp($data, 'model', '');
- if (!$model) {
- Utils::throwError('1002:model参数不能为空');
- }
- $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
- $duration = (int)getProp($data, 'video_duration', 5);
- if ($duration <= 0) {
- $duration = 5;
- }
- $count = max(1, (int)getProp($data, 'count', 1));
- $pointsPerVideo = $this->pointsService->getVideoChargePoints([
- 'model' => $model,
- 'video_resolution' => $resolution,
- 'video_duration' => $duration,
- 'mode' => $scene,
- ]);
- $points = $pointsPerVideo * $count;
- $items[] = [
- 'type' => 'video',
- 'model' => $model,
- 'video_resolution' => $resolution,
- 'video_duration' => $duration,
- 'count' => $count,
- 'points' => $points,
- ];
- } elseif ($mode === 'image') {
- // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
- $model = (string)getProp($data, 'model', '');
- if (!$model) {
- Utils::throwError('1002:model参数不能为空');
- }
- $resolution = strtolower((string)getProp($data, 'resolution', ''));
- if (!$resolution) {
- $width = (int)getProp($data, 'width', 0);
- $height = (int)getProp($data, 'height', 0);
- if ($width <= 0 || $height <= 0) {
- $width = 1600;
- $height = 2848;
- }
- $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
- }
- $imageNum = max(1, (int)getProp($data, 'image_num', 1));
- $points = $this->pointsService->getImageChargePoints([
- 'model' => $model,
- 'resolution' => $resolution,
- ]) * $imageNum;
- $items[] = [
- 'type' => 'image',
- 'model' => $model,
- 'resolution' => $resolution,
- 'image_num' => $imageNum,
- 'points' => $points,
- ];
- } else {
- // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
- // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
- $priceType = (string)getProp($data, 'price_type', 'special');
- if (!in_array($priceType, ['special', 'normal'], true)) {
- Utils::throwError('1003:price_type参数仅支持special或normal');
- }
- $count = max(1, (int)getProp($data, 'count', 1));
- $animeId = getProp($data, 'anime_id');
- $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
- if ($animeId && $generateEpisodes > 0) {
- // 批量生成分集按 special 档预估,与实际扣费口径一致
- $priceType = 'special';
- $currentMaxEpisode = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('is_default', 1)
- ->max('episode_number');
- $currentMaxEpisode = $currentMaxEpisode ?: 0;
- $startEpisodeNumber = $currentMaxEpisode + 1;
- $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
- $existingSkipped = DB::table('mp_batch_episode_generation_details')
- ->where('anime_id', $animeId)
- ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
- ->whereIn('status', ['pending', 'processing', 'completed'])
- ->count();
- $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
- if ($count < 0) {
- $count = 0;
- }
- }
- $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
- $items[] = [
- 'type' => 'chat',
- 'count' => $count,
- 'price_type' => $priceType,
- 'points' => $points,
- ];
- }
- $totalPoints = 0;
- foreach ($items as $item) {
- $totalPoints += $item['points'];
- }
- return [
- 'mode' => $mode,
- 'total_points' => $totalPoints,
- 'items' => $items,
- 'points_balance' => $this->pointsService->getUserPointsBalance(),
- 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
- ];
- }
- /**
- * 根据提示词内容智能计算最优视频时长
- *
- * @param string $segmentContent 分镜内容
- * @param string $tailFrame 尾帧描述
- * @return int 视频时长(2-12秒)
- */
- public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
- // 合并所有文本内容
- $fullText = trim($segmentContent . ' ' . $tailFrame);
-
- // 如果没有内容,返回默认时长
- if (empty($fullText)) {
- return 5;
- }
-
- // 计算文本长度(中文字符按2个字符计算)
- $textLength = mb_strlen($fullText, 'UTF-8');
- $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
- $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
-
- // 分析内容复杂度
- $complexityScore = $this->analyzeContentComplexity($fullText);
-
- // 基础时长计算(根据文本长度)
- $baseDuration = 3; // 默认2秒
-
- // if ($adjustedLength <= 20) {
- // $baseDuration = 3;
- // } elseif ($adjustedLength <= 40) {
- // $baseDuration = 4;
- // } elseif ($adjustedLength <= 60) {
- // $baseDuration = 5;
- // } elseif ($adjustedLength <= 80) {
- // $baseDuration = 6;
- // } elseif ($adjustedLength <= 100) {
- // $baseDuration = 7;
- // } elseif ($adjustedLength <= 120) {
- // $baseDuration = 8;
- // } else {
- // $baseDuration = 9;
- // }
-
- // 根据内容复杂度调整时长
- $finalDuration = $baseDuration + $complexityScore;
-
- // 确保时长在2-12秒范围内
- return max(4, min(12, $finalDuration));
- }
- /**
- * 分析内容复杂度,返回时长调整值
- *
- * @param string $text 文本内容
- * @return int 调整值(-2到+3)
- */
- private function analyzeContentComplexity($text) {
- $score = 0;
-
- // 动作关键词(需要更长时间展现)
- $actionKeywords = [
- '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
- '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
- '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
- ];
-
- // 静态关键词(可以用较短时间)
- $staticKeywords = [
- '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
- '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
- ];
-
- // 复杂场景关键词(需要更长时间)
- $complexSceneKeywords = [
- '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
- '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
- ];
-
- // 情感关键词(需要适中时间表现)
- $emotionKeywords = [
- '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
- '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
- ];
-
- // 检查动作关键词
- foreach ($actionKeywords as $keyword) {
- if (strpos($text, $keyword) !== false) {
- $score += 1;
- break; // 避免重复加分
- }
- }
-
- // 检查静态关键词
- foreach ($staticKeywords as $keyword) {
- if (strpos($text, $keyword) !== false) {
- $score -= 1;
- break;
- }
- }
-
- // 检查复杂场景关键词
- foreach ($complexSceneKeywords as $keyword) {
- if (strpos($text, $keyword) !== false) {
- $score += 1;
- break;
- }
- }
-
- // 检查情感关键词
- foreach ($emotionKeywords as $keyword) {
- if (strpos($text, $keyword) !== false) {
- $score += 1;
- break;
- }
- }
-
- // 检查时间相关词汇
- if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
- $score += 1;
- }
-
- if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
- $score -= 1;
- }
-
- // 检查转场词汇
- if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
- $score += 1;
- }
-
- // 检查环境描述(复杂环境需要更多时间)
- if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
- $score += 1;
- }
-
- // 检查对话内容(对话需要更多时间)
- if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
- $score += 1;
- }
-
- // 限制调整范围
- return max(-1, min(4, $score));
- }
- /**
- * 创建完整视频合成任务
- *
- * @param array $data
- * @return array
- */
- public function createCompleteVideoTask($data)
- {
- $animeId = getProp($data, 'anime_id');
- $episodeId = getProp($data, 'episode_id');
- // 验证参数
- if (!$animeId || !$episodeId) {
- Utils::throwError('20003:anime_id 和 episode_id 不能为空');
- }
- // 检查是否已存在处理中的任务
- $existingTask = DB::table('mp_complete_video_tasks')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->whereIn('generate_status', ['执行中'])
- ->first();
- if ($existingTask) {
- Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
- }
- // 获取全能模式状态
- $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
- if ((int)$ace_mode === 1) {
- // 获取所有片段的配音视频,按 act_number 排序
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->orderBy('segment_number')
- ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
- ->get();
-
- // 检查是否所有片段都有视频
- $missingVideos = $segments->filter(function($segment) {
- return empty($segment->video_url);
- });
- if ($missingVideos->isNotEmpty()) {
- Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
- }
- }else {
- // 获取所有分镜的配音视频,按 segment_number 排序
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->orderBy('segment_number')
- ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
- ->get();
- // 检查是否所有分镜都有配音和视频
- $missingVideos = $segments->filter(function($segment) {
- return empty($segment->audio_url) || empty($segment->video_url);
- });
- if ($missingVideos->isNotEmpty()) {
- Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
- }
- }
- if ($segments->isEmpty()) {
- Utils::throwError('20003:未找到该剧集的分镜数据');
- }
- // 获取当前完整视频url
- $completeVideoUrl = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->value('complete_video_url');
- // 构建 generate_json
- $generateJson = [];
- $sequence = 1;
- foreach ($segments as $segment) {
- if ((int)$ace_mode === 1) {
- $generateJson[] = [
- 'sequence' => $sequence++,
- 'video_url' => $segment->video_url,
- 'video_time_point_start' => $segment->video_time_point_start,
- 'video_time_point_end' => $segment->video_time_point_end
- ];
- }else {
- $generateJson[] = [
- 'sequence' => $sequence++,
- 'video_url' => $segment->video_url,
- 'audio_url' => $segment->audio_url,
- 'video_time_point_start' => $segment->video_time_point_start,
- 'video_time_point_end' => $segment->video_time_point_end
- ];
- }
- }
- // 创建任务
- $now = date('Y-m-d H:i:s');
- $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'generate_json' => json_encode($generateJson, 256),
- 'generate_status' => '执行中',
- 'complete_video_url' => '',
- 'created_at' => $now,
- 'updated_at' => $now
- ]);
- if (!$taskId) {
- Utils::throwError('20003:创建任务失败');
- }
- // 更新剧集表的任务ID和状态
- $boolen = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->update([
- 'complete_video_task_id' => $taskId,
- 'complete_video_task_status' => '执行中',
- 'updated_at' => $now
- ]);
- if (!$boolen) {
- Utils::throwError('20003:更新剧集表失败');
- }
- dLog('anime')->info('创建完整视频合成任务', [
- 'task_id' => $taskId,
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'segment_count' => count($generateJson)
- ]);
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 600, 'verify' => false]);
- try {
- $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
-
- // // 更新任务状态为失败
- // DB::table('mp_complete_video_tasks')
- // ->where('id', $taskId)
- // ->update([
- // 'generate_status' => '执行失败',
- // 'error_message' => $error_msg,
- // 'updated_at' => date('Y-m-d H:i:s')
- // ]);
-
- // // 同步更新剧集表状态
- // DB::table('mp_anime_episodes')
- // ->where('complete_video_task_id', $taskId)
- // ->update([
- // 'complete_video_task_status' => '执行失败',
- // 'updated_at' => date('Y-m-d H:i:s')
- // ]);
-
- Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
-
- // 更新任务状态为失败
- DB::table('mp_complete_video_tasks')
- ->where('id', $taskId)
- ->update([
- 'generate_status' => '执行失败',
- 'error_message' => $e->getMessage(),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 同步更新剧集表状态
- DB::table('mp_anime_episodes')
- ->where('complete_video_task_id', $taskId)
- ->update([
- 'complete_video_task_status' => '执行失败',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
- }
- // 开始轮询任务状态
- $maxAttempts = 60; // 5分钟 = 60次 * 5秒
- $pollInterval = 5; // 每5秒轮询一次
- $attempt = 0;
- dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
- while ($attempt < $maxAttempts) {
- sleep($pollInterval);
- $attempt++;
- // 查询任务状态
- $task = DB::table('mp_complete_video_tasks')
- ->where('id', $taskId)
- ->first();
- if (!$task) {
- dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
- Utils::throwError('20003:任务不存在');
- }
- dLog('anime')->info('轮询任务状态', [
- 'task_id' => $taskId,
- 'attempt' => $attempt,
- 'status' => $task->generate_status
- ]);
- // 检查任务是否完成
- if ($task->generate_status === '执行成功') {
- // 同步更新剧集表状态
- $boolen3 = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->update([
- 'complete_video_url' => $task->complete_video_url,
- 'complete_video_task_status' => '执行成功',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- dLog('anime')->info('视频合成任务完成', [
- 'task_id' => $taskId,
- 'video_url' => $task->complete_video_url,
- 'attempts' => $attempt
- ]);
- // 如果更新成功则远程删除之前的文件
- if ($boolen3 && $completeVideoUrl) {
- $encode_url = urlencode($completeVideoUrl);
- $client = new Client(['timeout' => 300, 'verify' => false]);
- // 根据ID通过API通知合成音频
- // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
- $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- Log::info('火山删除音频返回: '.$response);
- if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- Log::info('火山删除音频失败: '.$error_msg);
- // Utils::throwError('20003:火山删除音频失败');
- }
- }
- return [
- 'task_id' => $taskId,
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'segment_count' => count($generateJson),
- 'generate_status' => '执行成功',
- 'complete_video_url' => $task->complete_video_url,
- ];
- }
- // 检查任务是否失败
- if ($task->generate_status === '执行失败') {
- // 同步更新剧集表状态
- DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->update([
- 'complete_video_task_status' => '执行失败',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- $errorMessage = $task->error_message ?? '未知错误';
- dLog('anime')->error('视频合成任务失败', [
- 'task_id' => $taskId,
- 'error' => $errorMessage,
- 'attempts' => $attempt
- ]);
- return [
- 'task_id' => $taskId,
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'segment_count' => count($generateJson),
- 'generate_status' => '执行失败',
- 'error_message' => $errorMessage
- ];
- }
- }
- // 超时处理
- dLog('anime')->warning('视频合成任务超时', [
- 'task_id' => $taskId,
- 'max_attempts' => $maxAttempts,
- 'timeout_seconds' => $maxAttempts * $pollInterval
- ]);
- // 更新任务状态为超时
- DB::table('mp_complete_video_tasks')
- ->where('id', $taskId)
- ->update([
- 'generate_status' => '超时',
- 'error_message' => '任务执行超时(5分钟)',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- return [
- 'task_id' => $taskId,
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'segment_count' => count($generateJson),
- 'generate_status' => '超时',
- 'error_message' => '任务执行超时,请稍后查询任务状态'
- ];
- }
- /**
- * 根据 inner_prompt_type 附加内置提示词
- *
- * @param string $prompt 用户提示词
- * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
- * @return string 合并后的提示词
- */
- public static function appendInnerPrompt($prompt, $innerPromptType = 0)
- {
- $innerPromptMap = [
- 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
- 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
- ];
- if (!isset($innerPromptMap[$innerPromptType])) {
- return $prompt;
- }
- return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
- }
- /**
- * 根据 inner_prompt_type 获取生成图片数量
- *
- * @param int $innerPromptType 内置提示词类型
- * @param int $imageNum 传入的图片张数
- * @return int 图片数量
- */
- public static function getInnerImageNum($innerPromptType = 0, $imageNum)
- {
- return (int)$innerPromptType === 2 ? 9 : $imageNum;
- }
- /**
- * 提取图片生成结果URL
- *
- * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
- * @param int $innerPromptType 内置提示词类型
- * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
- */
- public static function extractResultUrls($resultUrl, $innerPromptType = 0)
- {
- $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
- if (is_array($resultUrls) && !empty($resultUrls)) {
- $resultUrls = array_values($resultUrls);
- return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
- }
- if (!empty($resultUrl)) {
- return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
- }
- return (int)$innerPromptType === 2 ? [] : '';
- }
- public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
- $prompt = getProp($data, 'prompt');
- $episode_id = getProp($data, 'episode_id');
- $ref_img_urls = getProp($data, 'ref_img_urls');
- $ratio = getProp($data, 'ratio', '9:16');
- $resolution = getProp($data, 'resolution', '2k');
- $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
- $imageNum = (int)getProp($data, 'image_num', 1);
-
- // 分辨率档位与尺寸映射统一从 BaseConst 获取
- $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
-
- // 参数验证
- $resolution = strtolower($resolution);
- if (!isset($sizeMap[$resolution])) {
- Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
- }
-
- if (!isset($sizeMap[$resolution][$ratio])) {
- Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
- }
-
- // 根据 ratio 和 resolution 确定宽高
- $width = $sizeMap[$resolution][$ratio]['width'];
- $height = $sizeMap[$resolution][$ratio]['height'];
-
- if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
- if (is_json($ref_img_urls)) {
- $ref_img_urls = json_decode($ref_img_urls, true);
- }else {
- $ref_img_urls = explode(',', $ref_img_urls);
- }
- }
- // 处理图片模型
- $model = getProp($data, 'model');
- if (!$model) {
- // 用户没有输入,从episode表获取
- if ($episode_id) {
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- $model = getProp($episode, 'image_model');
- }
- if (!$model) {
- // episode表也没有,使用默认值
- $model = 'doubao-seedream-5-0-lite-260128';
- }
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- // $model = 'doubao-seedream-5-0-lite-260128';
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
- // 保存到episode表
- if ($episode_id) {
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'image_model' => $model,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- // 参数验证
- if (!$prompt) Utils::throwError('20003:请提供提示词');
- // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
- $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
- $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
- try {
- // 创建图片生成任务
- $params = [
- 'prompt' => $prompt,
- 'model' => $model,
- 'ref_img_urls' => '',
- 'width' => $width,
- 'height' => $height,
- 'image_num' => $imageNum
- ];
- if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError('20003:创建图片生成任务失败');
- }
- // 创建任务中心记录并关联图片任务ID
- $taskCenter = $this->taskCenterService->createTask('image', [
- 'title' => '文生图',
- 'ref_task_id' => $task_id,
- // 'prompt' => $prompt,
- // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
- ]);
- $taskCenterId = $taskCenter->id;
- // 组装本次任务信息(用于init消息,类似generateVideo)
- $taskInfo = [
- 'task_id' => $task_id,
- 'status' => getProp($task, 'status', 'processing'),
- 'model' => $model,
- 'ratio' => $ratio,
- 'resolution' => $resolution,
- 'image_num' => $imageNum,
- ];
- // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
- if (is_callable($onTaskCreated)) {
- $onTaskCreated($taskCenterId, $taskInfo);
- }
- // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
- $model = getProp($task, 'model');
- $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
- $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
- $isSyncModel = $isVolcModel || $isGptModel;
- // 任务需要轮询获取结果(15分钟超时,每3秒查询一次)
- $start_time = time();
- $timeout = 900; // 15分钟
- $img_url = '';
- $img_urls = [];
- $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
- $queueMessageInterval = 60; // 队列消息发送间隔(秒)
-
- while (time() - $start_time < $timeout) {
- sleep(3);
- // 每分钟发送一次队列状态消息(仅流式模式)
- if (is_callable($onPoll)) {
- $currentTime = time();
- if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
- $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
- $lastQueueMessageTime = $currentTime;
- }
- }
- // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
- if ($isSyncModel) {
- // 刷新任务状态
- $task = MpGeneratePicTask::where('id', $task_id)->first();
-
- if ($task->status === 'success' && $task->result_url) {
- $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
- $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
- if (!empty($resultUrls)) {
- $img_urls = $resultUrls;
- $img_url = $resultUrls[0];
- } else {
- $img_url = (string)$task->result_url;
- }
- break;
- } elseif ($task->status === 'failed') {
- $errorMsg = mapErrorMessage($task->error_message ?? '');
- Utils::throwError('20003:图片生成失败,' . $errorMsg);
- }
-
- // // 如果还在处理中,提示用户稍后查看
- // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
- }else {
- $task = MpGeneratePicTask::where('id', $task_id)->first();
- $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
-
- if ($statusInfo['status'] === 'success') {
- $task->updateStatus('success', [
- 'result_url' => $statusInfo['result_url'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
-
- $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
- $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
- if (!empty($resultUrls)) {
- $img_urls = $resultUrls;
- $img_url = $resultUrls[0];
- } else {
- $img_url = (string)$statusInfo['result_url'];
- }
- break;
- } elseif ($statusInfo['status'] === 'failed') {
- $task->updateStatus('failed', [
- 'error_message' => $statusInfo['error_message'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
- dLog('anime')->error('图片生成失败,', [
- 'error' => $statusInfo['error_message'] ?? '未知错误'
- ]);
- $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
- Utils::throwError('20003:图片生成失败,' . $errorMsg);
- }
- }
- }
-
- if (empty($img_url)) {
- Utils::throwError('20003:图片生成超时,请稍后重试');
- }
-
- // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
- if (count($img_urls) > 1) {
- return [
- 'img_url' => $img_url,
- 'image_urls' => $img_urls,
- 'task_id' => $taskCenterId,
- ];
- }
-
- return [
- 'img_url' => $img_url,
- 'task_id' => $taskCenterId,
- ];
-
- } catch (\Exception $e) {
- dLog('anime')->error('更新角色或场景失败', [
- 'error' => $e->getMessage()
- ]);
- logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
-
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- /**
- * 使用文生文模型解析分镜内容
- */
- private function parseSegmentContentWithAI($segment_content) {
- try {
- // 使用DeepSeek服务的公开方法解析分镜内容
- return $this->DeepSeekService->parseSegmentContent($segment_content);
- } catch (\Exception $e) {
- // 如果AI解析失败,记录日志并返回原内容
- dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
- return $segment_content;
- }
- }
- /**
- * 处理分集的角色和场景数据(继承全局数据或创建新任务)
- *
- * @param int $episode_id 分集ID
- * @param int $anime_id 动漫ID
- * @param array $roles 分集角色数组(引用传递)
- * @param array $scenes 分集场景数组(引用传递)
- * @param array $episode 分集数据
- */
- private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
- // 获取全局动漫的角色和场景数据
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- if (!$anime) return;
- $art_style_type = getProp($anime, 'art_style_type');
- $character_prefix = '';
- $scene_prefix = '';
- if ($art_style_type) {
- $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
- $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
- $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
- }
-
- $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
- $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
-
- $roles_updated = false;
- $scenes_updated = false;
-
- // 处理角色
- foreach ($roles as &$role) {
- $role_name = getProp($role, 'role');
- $role_description = getProp($role, 'description');
- $role_pic_prompt = getProp($role, 'pic_prompt');
- $role_url = getProp($role, 'url');
- $role_task_id = getProp($role, 'task_id');
-
- // 如果已有URL或已有任务ID,跳过
- if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
- continue;
- }
-
- $url_inherited = false;
-
- // 尝试从全局数据中继承
- foreach ($global_roles as $global_role) {
- $global_role_name = getProp($global_role, 'role');
- $global_role_description = getProp($global_role, 'description');
- $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
- $global_role_url = getProp($global_role, 'url');
- $global_role_task_id = getProp($global_role, 'task_id');
- $global_role_task_status = getProp($global_role, 'task_status');
-
- // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
- if ($role_name === $global_role_name
- && $role_description === $global_role_description
- && $role_pic_prompt === $global_role_pic_prompt
- && !empty($global_role_url)) {
- // 继承 task_id、task_status 和 url
- $role['task_id'] = $global_role_task_id;
- $role['task_status'] = $global_role_task_status;
- $role['url'] = $global_role_url;
- $roles_updated = true;
- $url_inherited = true;
- dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
- break;
- }
- }
-
- // 如果无法继承且没有任务ID,创建新任务
- if (!$url_inherited && empty($role_task_id)) {
- try {
- $art_style = getProp($episode, 'art_style');
-
- // 优先使用 pic_prompt,如果没有则使用 description
- $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
-
- // if ($art_style) {
- // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
- // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
- // }
- $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
-
- $params = [
- 'prompt' => $description,
- 'ref_img_urls' => []
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if ($task_id) {
- $role['task_id'] = $task_id;
- $role['task_status'] = 'processing';
- $roles_updated = true;
- dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
- }
- } catch (\Exception $e) {
- dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
- }
- }
- }
-
- // 处理场景
- foreach ($scenes as &$scene) {
- $scene_name = getProp($scene, 'scene');
- $scene_description = getProp($scene, 'description');
- $scene_pic_prompt = getProp($scene, 'pic_prompt');
- $scene_url = getProp($scene, 'url');
- $scene_task_id = getProp($scene, 'task_id');
-
- // 如果已有URL或已有任务ID,跳过
- if (!empty($scene_url) || !empty($scene_task_id)) {
- continue;
- }
-
- $url_inherited = false;
-
- // 尝试从全局数据中继承
- foreach ($global_scenes as $global_scene) {
- $global_scene_name = getProp($global_scene, 'scene');
- $global_scene_description = getProp($global_scene, 'description');
- $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
- $global_scene_url = getProp($global_scene, 'url');
- $global_scene_task_id = getProp($global_scene, 'task_id');
- $global_scene_task_status = getProp($global_scene, 'task_status');
-
- // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
- if ($scene_name === $global_scene_name
- && $scene_description === $global_scene_description
- && $scene_pic_prompt === $global_scene_pic_prompt
- && !empty($global_scene_url)) {
- // 继承 task_id、task_status 和 url
- $scene['task_id'] = $global_scene_task_id;
- $scene['task_status'] = $global_scene_task_status;
- $scene['url'] = $global_scene_url;
- $scenes_updated = true;
- $url_inherited = true;
- dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
- break;
- }
- }
-
- // 如果无法继承且没有任务ID,创建新任务
- if (!$url_inherited && empty($scene_task_id)) {
- try {
- $art_style = getProp($episode, 'art_style');
-
- // 优先使用 pic_prompt,如果没有则使用 description
- $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
-
- // if ($art_style) {
- // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
- // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
- // }
- $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
-
- $params = [
- 'prompt' => $description,
- 'ref_img_urls' => []
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if ($task_id) {
- $scene['task_id'] = $task_id;
- $scene['task_status'] = 'processing';
- $scenes_updated = true;
- dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
- }
- } catch (\Exception $e) {
- dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
- }
- }
- }
-
- // 如果有更新,保存到数据库
- if ($roles_updated || $scenes_updated) {
- $update_data = ['updated_at' => date('Y-m-d H:i:s')];
-
- if ($roles_updated) {
- $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
- }
-
- if ($scenes_updated) {
- $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
- }
-
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
- dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
- }
- }
- /**
- * 根据图片URL使用AI反推图片提示词
- *
- * @param string $img_url 图片URL
- * @return string 反推的提示词
- */
- private function generateImagePromptFromUrl($img_url) {
- try {
- // 获取默认模型
- $model = 'doubao-seed-2-0-mini-260215';
-
- // 构建messages参数
- $messages = [
- [
- 'role' => 'user',
- 'content' => [
- [
- 'type' => 'text',
- 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
- ],
- [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $img_url
- ]
- ]
- ]
- ]
- ];
-
- // 构建请求参数
- $params = [
- 'model' => $model,
- 'messages' => $messages,
- 'stream' => false,
- 'thinking' => ['type' => 'disabled'] // 不使用思考模式
- ];
-
- // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
- $result = $this->DeepSeekService->volcEngineChatCompletion($params);
-
- // 仅记录 token 使用明细(不扣积分)
- $uid = 0;
- try {
- $uid = (int)Site::getUid();
- } catch (\Throwable $e) {
- // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
- }
- $this->pointsService->recordTokenOnlyDetail(
- $uid,
- $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
- [
- 'model' => $model,
- 'img_url' => $img_url,
- 'source' => 'generateImagePromptFromUrl',
- ],
- 'chat',
- $model,
- ''
- );
- // 返回生成的内容
- return getProp($result, 'fullContent', '图片描述生成失败');
-
- } catch (\Exception $e) {
- dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
- 'img_url' => $img_url
- ]);
- logDB('anime', 'error', 'AI反推图片提示词失败', [
- 'error' => $e->getMessage(),
- 'img_url' => $img_url
- ]);
- return '图片描述生成失败: ' . $e->getMessage();
- }
- }
- /**
- * 音频试听接口
- * 创建音频任务并轮询获取结果
- *
- * @param array $data 参数数组
- * @return array 返回音频URL或错误信息
- */
- public function previewAudio($data) {
- $dialogue = getProp($data, 'dialogue');
-
- // 必填参数验证
- if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
-
- // 获取参数,优先使用传入的参数,否则使用分镜中的参数
- $voice_type = getProp($data, 'voice_type');
- $voice_name = getProp($data, 'voice_name');
- $voice_actor = getProp($data, 'voice_actor');
- $emotion_type = getProp($data, 'emotion_type');
- $gender = getProp($data, 'gender', 0);
- $emotion = getProp($data, 'emotion');
- $speed_ratio = getProp($data, 'speed_ratio', 0);
- $loudness_ratio = getProp($data, 'loudness_ratio', 0);
- $emotion_scale = getProp($data, 'emotion_scale', 0);
- $pitch = getProp($data, 'pitch', 0);
-
- try {
- $now = date('Y-m-d H:i:s');
-
- // 构建生成参数
- $generate_json = json_encode([
- 'text' => $dialogue,
- 'role' => $voice_actor,
- 'voice_type' => $voice_type,
- 'voice_name' => $voice_name,
- 'emotion' => $emotion,
- 'emotion_type' => $emotion_type,
- 'gender' => $gender,
- 'speed_ratio' => $speed_ratio,
- 'loudness_ratio' => $loudness_ratio,
- 'emotion_scale' => $emotion_scale,
- 'pitch' => $pitch,
- ], 256);
-
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 600, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
-
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
- Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
- }
- $arr = $response_arr['data'];
- $subtitle_info = $arr['subtitle_info'];
- $audio_duration = json_decode($subtitle_info, true)['duration'];
- if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
- return [
- 'audio_url' => $arr['url'],
- 'subtitle_info' => $subtitle_info,
- 'audio_duration' => round($audio_duration, 2)
- ];
-
- } catch (\Exception $e) {
- dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- /**
- * 获取角色库列表(支持文件夹递归查询)
- * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
- * @return array 返回当前目录下的所有子目录和角色列表(递归)
- */
- public function globalProducts($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $role = Site::getRole();
- $id = getProp($data, 'id', 0);
- $parent_id = getProp($data, 'parent_id', 0);
- $product_name = getProp($data, 'product_name');
- $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
- $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
-
- if (!$product) {
- Utils::throwError('20003:请选择产品类型');
- }
-
- // 根据角色和is_public参数确定查询范围
- // admin角色:获取所有个人库+公共库(忽略is_public参数)
- // user角色:根据is_public参数筛选
- $query_user_ids = [];
- if ($role === 'admin') {
- // admin获取所有个人库和公共库
- $query_user_ids = [$uid, 0];
- } else {
- // user角色根据is_public参数筛选
- if ($is_public == 2) {
- // 个人库+公共库
- $query_user_ids = [$uid, 0];
- } elseif ($is_public == 0) {
- // 仅个人库
- $query_user_ids = [$uid];
- } elseif ($is_public == 1) {
- // 仅公共库
- $query_user_ids = [0];
- }
- }
-
- // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
- if ($id || $product_name) {
- $query = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->whereIn('user_id', $query_user_ids)
- ->where('is_deleted', 0);
-
- // 如果指定了 id,按 id 精确查询
- if ($id) {
- $query->where('id', $id);
- }
-
- // 如果指定了 product_name,按名称模糊查询
- if ($product_name) {
- $query->where('product_name', 'like', "%{$product_name}%");
- }
-
- // 如果指定了 product,添加筛选条件
- if ($product) {
- $query->where('product', $product);
- }
-
- $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
- ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
- ->get()
- ->map(function($value) {
- $value = (array)$value;
- $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
- $value['type'] = (int)$value['type'];
- $value['parent_id'] = (int)$value['parent_id'];
- $value['level'] = (int)$value['level'];
- $value['product'] = (int)($value['product'] ?? 1);
- $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
- $value['versions'] = json_decode($value['versions'], true) ?: [];
- unset($value['user_id']);
- return $value;
- })
- ->toArray();
-
- return $result;
- }
-
- // 递归获取所有子目录和角色
- return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
- }
-
- /**
- * 递归获取指定目录下的所有子目录和角色
- * @param int $cpid 公司ID
- * @param int $parent_id 父目录ID
- * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
- * @param array $query_user_ids 用户ID数组(支持多个)
- * @param int $current_uid 当前用户ID(用于排序)
- * @return array
- */
- private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
- // 查询当前层级的所有项(文件夹和角色)
- $query = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('is_deleted', 0)
- ->where('parent_id', $parent_id);
-
- // 添加用户ID验证(支持多个user_id)
- if (!empty($query_user_ids)) {
- $query->whereIn('user_id', $query_user_ids);
- }
-
- // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
- if ($product) {
- $query->where('product', $product);
- }
-
- // 排序规则:
- // 1. 文件夹在前(type DESC)
- // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
- // 3. 其他排序规则
- $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
- ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
- ->get();
-
- $result = [];
-
- foreach ($items as $item) {
- $itemArray = [
- 'id' => $item->id,
- 'type' => (int)$item->type,
- 'parent_id' => (int)$item->parent_id,
- 'level' => (int)$item->level,
- 'product_name' => $item->product_name,
- 'url' => $item->url,
- 'pic_prompt' => $item->pic_prompt ?? '',
- 'three_view_image_url' => $item->three_view_image_url,
- 'product' => (int)($item->product ?? 1),
- 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
- 'created_at' => transDate($item->created_at, 'Y-m-d')
- ];
- $itemArray['versions'] = json_decode($item->versions, true) ?: [];
-
- // 如果是文件夹,递归获取其子项
- if ($item->type == 2) {
- $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
- if (!empty($children)) {
- $itemArray['children'] = $children;
- }
- }
-
- $result[] = $itemArray;
- }
-
- return $result;
- }
-
- /**
- * 创建文件夹
- * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
- * @return int 返回新建文件夹ID
- */
- public function createFolder($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $role = Site::getRole();
- $parent_id = getProp($data, 'parent_id', 0);
- $folder_name = getProp($data, 'product_name', '新建文件夹');
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- // 如果是公共库操作,需要admin权限
- if ($is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能操作公共资产库');
- }
-
- // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
- $store_uid = $is_public ? 0 : $uid;
-
- // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
- $product = getProp($data, 'product');
- if (!in_array($product, [1, 2, 3])) {
- // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
- }
-
- // 验证父文件夹
- $parent_level = 0;
- if ($parent_id > 0) {
- $parent = DB::table('mp_products')
- ->where('id', $parent_id)
- ->where('cpid', $cpid)
- ->where('user_id', $store_uid)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$parent) {
- Utils::throwError('20003:父文件夹不存在');
- }
-
- // 检查父文件夹的 product 类型是否一致
- if ($parent->product != $product) {
- Utils::throwError('20003:文件夹类型必须与父文件夹一致');
- }
-
- $parent_level = $parent->level;
-
- // 检查层级限制(最多3层)
- if ($parent_level >= 3) {
- Utils::throwError('20003:文件夹层级不能超过3层');
- }
- }
-
- // 检查当前目录下是否已存在空白文件夹
- $empty_folder_exists = DB::table('mp_products')
- ->where('parent_id', $parent_id)
- ->where('cpid', $cpid)
- ->where('user_id', $store_uid)
- ->where('type', 2)
- ->where('product', $product)
- ->where('product_name', '新建文件夹')
- ->where('is_deleted', 0)
- ->exists();
-
- if ($empty_folder_exists && $folder_name == '新建文件夹') {
- Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
- }
-
- // 创建文件夹
- $folder_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $store_uid,
- 'cpid' => $cpid,
- 'type' => 2,
- 'parent_id' => $parent_id,
- 'level' => $parent_level + 1,
- 'product_name' => $folder_name,
- 'product' => $product,
- 'sort_order' => time(), // 使用时间戳作为排序权重
- 'is_deleted' => 0,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- return [
- 'id' => $folder_id,
- 'type' => 2,
- 'parent_id' => $parent_id,
- 'level' => $parent_level + 1,
- 'product_name' => $folder_name,
- 'product' => $product,
- ];
- }
-
- /**
- * 重命名文件夹或角色
- * @param array $data 包含 id、product_name(新名称)
- * @return bool
- */
- public function renameFolder($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $role = Site::getRole();
- $id = getProp($data, 'id');
- $new_name = getProp($data, 'product_name');
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- if (!$id || !$new_name) {
- Utils::throwError('20003:参数不完整');
- }
-
- // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
- $query_uid = $is_public ? 0 : $uid;
-
- // 如果是公共库操作,需要admin权限
- if ($is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能操作公共资产库');
- }
-
- // 检查是否存在
- $item = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$item) {
- Utils::throwError('20003:项目不存在');
- }
-
- return DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->update([
- 'product_name' => $new_name,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
-
- /**
- * 移动角色或文件夹到指定文件夹
- * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
- * @return bool
- */
- public function moveProductOrFolder($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $role = Site::getRole();
- $id = getProp($data, 'id');
- $target_parent_id = getProp($data, 'target_parent_id', 0);
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- if (!$id) {
- Utils::throwError('20003:请选择要移动的项目');
- }
-
- // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
- $query_uid = $is_public ? 0 : $uid;
-
- // 如果是公共库操作,需要admin权限
- if ($is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能操作公共资产库');
- }
-
- // 检查要移动的项目
- $item = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$item) {
- Utils::throwError('20003:项目不存在');
- }
-
- // 验证目标文件夹
- $target_level = 0;
- $target_product = $item->product; // 默认使用当前项目的 product
-
- if ($target_parent_id > 0) {
- $target_parent = DB::table('mp_products')
- ->where('id', $target_parent_id)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$target_parent) {
- Utils::throwError('20003:目标文件夹不存在');
- }
-
- // 检查 product 类型是否一致
- if ($target_parent->product != $item->product) {
- Utils::throwError('20003:不能移动到不同类型的文件夹下');
- }
-
- $target_level = $target_parent->level;
- $target_product = $target_parent->product;
-
- // 如果移动的是文件夹,需要检查层级
- if ($item->type == 2) {
- // 计算移动后的最大层级
- $max_child_level = $this->getMaxChildLevel($id);
- $depth = $max_child_level - $item->level;
-
- if ($target_level + 1 + $depth > 3) {
- Utils::throwError('20003:移动后文件夹层级将超过3层限制');
- }
-
- // 不能移动到自己或自己的子文件夹下
- if ($this->isDescendant($target_parent_id, $id)) {
- Utils::throwError('20003:不能移动到自己或子文件夹下');
- }
- }
- }
-
- // 更新父文件夹和层级
- $new_level = $target_level + 1;
- DB::table('mp_products')
- ->where('id', $id)
- ->update([
- 'parent_id' => $target_parent_id,
- 'level' => $new_level,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 如果是文件夹,需要递归更新所有子项的层级
- if ($item->type == 2) {
- $this->updateChildrenLevel($id, $new_level);
- }
-
- return true;
- }
-
- /**
- * 获取文件夹下最大子层级
- * @param int $folder_id
- * @return int
- */
- private function getMaxChildLevel($folder_id) {
- $max_level = DB::table('mp_products')
- ->where('parent_id', $folder_id)
- ->where('is_deleted', 0)
- ->max('level');
-
- if (!$max_level) {
- return DB::table('mp_products')->where('id', $folder_id)->value('level');
- }
-
- // 递归查找子文件夹
- $children = DB::table('mp_products')
- ->where('parent_id', $folder_id)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->pluck('id');
-
- foreach ($children as $child_id) {
- $child_max = $this->getMaxChildLevel($child_id);
- if ($child_max > $max_level) {
- $max_level = $child_max;
- }
- }
-
- return $max_level;
- }
-
- /**
- * 检查 target_id 是否是 folder_id 的后代
- * @param int $target_id
- * @param int $folder_id
- * @return bool
- */
- private function isDescendant($target_id, $folder_id) {
- if ($target_id == $folder_id) {
- return true;
- }
-
- $parent = DB::table('mp_products')
- ->where('id', $target_id)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$parent || $parent->parent_id == 0) {
- return false;
- }
-
- return $this->isDescendant($parent->parent_id, $folder_id);
- }
-
- /**
- * 递归更新子项层级
- * @param int $parent_id
- * @param int $parent_level
- */
- private function updateChildrenLevel($parent_id, $parent_level) {
- $children = DB::table('mp_products')
- ->where('parent_id', $parent_id)
- ->where('is_deleted', 0)
- ->get();
-
- foreach ($children as $child) {
- $new_level = $parent_level + 1;
- DB::table('mp_products')
- ->where('id', $child->id)
- ->update([
- 'level' => $new_level,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 如果是文件夹,继续递归
- if ($child->type == 2) {
- $this->updateChildrenLevel($child->id, $new_level);
- }
- }
- }
-
- /**
- * 获取文件夹路径(面包屑导航)
- * @param array $data 包含 folder_id
- * @return array 返回路径数组
- */
- public function getFolderPath($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $folder_id = getProp($data, 'id', 0);
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- if ($folder_id == 0) {
- return [
- ['id' => 0, 'name' => '根目录']
- ];
- }
-
- // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
- $query_uid = $is_public ? 0 : $uid;
-
- $path = [];
- $current_id = $folder_id;
-
- while ($current_id > 0) {
- $folder = DB::table('mp_products')
- ->where('id', $current_id)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$folder) {
- break;
- }
-
- array_unshift($path, [
- 'id' => $folder->id,
- 'name' => $folder->product_name
- ]);
-
- $current_id = $folder->parent_id;
- }
-
- // 添加根目录
- array_unshift($path, ['id' => 0, 'name' => '根目录']);
-
- return $path;
- }
- public function createProduct($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $role = Site::getRole();
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- // 如果是公共库操作,需要admin权限
- if ($is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能操作公共资产库');
- }
-
- // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
- $store_uid = $is_public ? 0 : $uid;
-
- // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
- $script_id = (int)getProp($data, 'script_id', 0);
- $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
- if ($script_id && empty($episode_numbers)) {
- Utils::throwError('20003:剧集序号不能为空');
- }
- if (!$script_id && !empty($episode_numbers)) {
- Utils::throwError('20003:请提供剧本ID');
- }
-
- $product_name = trim(getProp($data, 'product_name'));
- if (!$product_name) Utils::throwError('20003:名称不能为空');
- $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
- // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
- // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
- $url = trim(getProp($data, 'url'));
- if (!$url) Utils::throwError('20003:图片地址不能为空');
- $versions = getProp($data, 'versions');
-
- // 检查是否是正确的图片格式
- $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
- $urlPath = parse_url($url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- if (!in_array($extension, $allowedExtensions)) {
- Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
- }
- // 选填三视图图片地址,格式校验与 url 一致
- $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
- if ($three_view_image_url) {
- $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
- $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
- if (!in_array($threeViewExtension, $allowedExtensions)) {
- Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
- }
- }
- $pic_prompt = trim(getProp($data, 'pic_prompt'));
- if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
-
- // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
- $product = getProp($data, 'product');
- if (!in_array($product, [1, 2, 3])) {
- // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
- }
-
- // 获取父文件夹ID和层级
- $parent_id = getProp($data, 'parent_id', 0);
- $parent_level = 0;
-
- if ($parent_id > 0) {
- $parent = DB::table('mp_products')
- ->where('id', $parent_id)
- ->where('cpid', $cpid)
- ->where('user_id', $store_uid)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$parent) {
- Utils::throwError('20003:父文件夹不存在');
- }
-
- $parent_level = $parent->level;
- }
- // 创建资产并保存剧本资产关联关系(同一事务)
- DB::beginTransaction();
- try {
- $id = DB::table('mp_products')->insertGetId([
- 'user_id' => $store_uid,
- 'cpid' => $cpid,
- 'type' => 1, // 1=角色图片
- 'parent_id' => $parent_id,
- 'level' => $parent_level + 1,
- 'product_name' => $product_name,
- 'url' => $url,
- 'three_view_image_url' => $three_view_image_url,
- 'pic_prompt' => $pic_prompt,
- 'product' => $product,
- 'versions' => json_encode($versions, 256),
- 'sort_order' => time(), // 使用时间戳作为排序权重
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$id) Utils::throwError('20003:创建失败');
-
- // 保存剧本资产关联关系
- if ($script_id) {
- $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
- }
-
- DB::commit();
- } catch (\Exception $e) {
- DB::rollback();
- throw $e;
- }
-
- return [
- 'id' => $id,
- 'type' => 1,
- 'parent_id' => $parent_id,
- 'level' => $parent_level + 1,
- 'product_name' => $product_name,
- 'url' => $url,
- 'three_view_image_url' => $three_view_image_url,
- 'pic_prompt' => $pic_prompt,
- 'product' => $product,
- 'versions' => $versions
- ];
- }
- public function editProduct($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $role = Site::getRole();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:ID不能为空');
- $versions = getProp($data, 'versions');
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
- $script_id = (int)getProp($data, 'script_id', 0);
- $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
- if ($script_id && empty($episode_numbers)) {
- Utils::throwError('20003:剧集序号不能为空');
- }
- if (!$script_id && !empty($episode_numbers)) {
- Utils::throwError('20003:请提供剧本ID');
- }
-
- // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
- $query_uid = $is_public ? 0 : $uid;
-
- // 如果是公共库操作,需要admin权限
- if ($is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能操作公共资产库');
- }
-
- // 检查是否存在且属于当前用户或公共库
- $role = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->where('type', 1)->first();
- if (!$role) Utils::throwError('20003:记录不存在');
-
- $updateData = [];
- // $needVersionRecord = false; // 是否需要记录版本
-
- // 名称
- $product_name = trim(getProp($data, 'product_name'));
- if ($product_name) {
- $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
- $updateData['product_name'] = $product_name;
- }
- // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
- // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
-
- // 图片地址
- $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
- $url = trim(getProp($data, 'url'));
- if ($url) {
- // 检查是否是正确的图片格式
- $urlPath = parse_url($url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- if (!in_array($extension, $allowedExtensions)) {
- Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
- }
-
- // // 如果 url 有变更,记录版本
- // if ($url !== $role->url) {
- // $needVersionRecord = true;
- // }
-
- $updateData['url'] = $url;
- }
- // 三视图图片地址(选填),格式校验与 url 一致
- $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
- if ($three_view_image_url) {
- $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
- $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
- if (!in_array($threeViewExtension, $allowedExtensions)) {
- Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
- }
- $updateData['three_view_image_url'] = $three_view_image_url;
- }
-
- // 提示词
- $pic_prompt = trim(getProp($data, 'pic_prompt'));
- if ($pic_prompt) {
- // // 如果 pic_prompt 有变更,记录版本
- // if ($pic_prompt !== $role->pic_prompt) {
- // $needVersionRecord = true;
- // }
-
- $updateData['pic_prompt'] = $pic_prompt;
- }
-
- if (empty($updateData) && !$script_id) {
- Utils::throwError('20003:没有需要更新的数据');
- }
-
- // // 如果需要记录版本,将数据添加到 versions 数组
- // if ($needVersionRecord) {
- // // 获取现有的 versions 数据
- // $versions = json_decode($role->versions, true) ?: [];
- // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
-
- // // 如果是第一次记录版本,先添加旧版本(变更前)
- // if ($isFirstVersion) {
- // $oldVersion = [
- // 'url' => $role->url,
- // 'description' => $role->pic_prompt,
- // ];
- // // 旧版本添加到数组末尾
- // $versions[] = $oldVersion;
- // }
-
- // // 构建新版本(变更后)
- // $newVersion = [
- // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
- // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
- // ];
-
- // // 检查新版本是否已存在于历史版本中
- // $existingIndex = -1;
- // foreach ($versions as $index => $version) {
- // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
- // $existingIndex = $index;
- // break;
- // }
- // }
-
- // if ($existingIndex !== -1) {
- // // 如果已存在,移除旧的位置
- // array_splice($versions, $existingIndex, 1);
- // }
-
- // // 新版本添加到数组开头(最新的在前)
- // array_unshift($versions, $newVersion);
-
- // // // 限制版本数量(可选,例如只保留最近10个版本)
- // // if (count($versions) > 10) {
- // // $versions = array_slice($versions, 0, 10);
- // // }
-
- // $updateData['versions'] = json_encode($versions, 256);
- // }
- if ($versions) {
- $updateData['versions'] = json_encode($versions, 256);
- }
-
- if (!empty($updateData)) {
- $updateData['updated_at'] = date('Y-m-d H:i:s');
- }
-
- // 更新资产并保存剧本资产关联关系(同一事务)
- DB::beginTransaction();
- try {
- $updated = true;
- if (!empty($updateData)) {
- $updated = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('id', $id)
- ->update($updateData);
- }
-
- // 保存剧本资产关联关系
- if ($script_id) {
- $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
- }
-
- DB::commit();
- } catch (\Exception $e) {
- DB::rollback();
- throw $e;
- }
-
- return $updated;
- }
-
- /**
- * 保存单一资产与剧本剧集的关联关系
- *
- * @param int $product_id 资产ID
- * @param int $script_id 剧本ID
- * @param array $episode_numbers 剧集序号数组(序号从1开始)
- * @return int 新增关联数量
- */
- private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
- $uid = Site::getUid();
-
- // 验证剧本是否存在
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$script) {
- Utils::throwError('20003:剧本不存在');
- }
-
- // 验证剧本归属:只能关联自己的剧本
- if ((int)$script->user_id !== (int)$uid) {
- Utils::throwError('20003:只能添加到自己的剧本');
- }
-
- // 使用 splitContent 拆分剧本内容获取总集数
- $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
-
- // 解析剧集序号(数组)
- $episodes = [];
- foreach ($episode_numbers as $item) {
- if (is_array($item)) {
- continue;
- }
- $item = trim((string)$item);
- if ($item === '' || !is_numeric($item)) {
- Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
- }
- $episodes[] = (int)$item;
- }
-
- // 去重并校验序号范围(序号从1开始)
- $episodes = array_values(array_unique($episodes));
- if (empty($episodes)) {
- Utils::throwError('20003:剧集序号不能为空');
- }
-
- foreach ($episodes as $episode) {
- if ($episode < 1 || $episode > $totalEpisodes) {
- Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
- }
- }
-
- $now = now();
-
- // 过滤已存在的关联,避免重复
- $existingEpisodes = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->where('product_id', $product_id)
- ->whereIn('episode_number', $episodes)
- ->pluck('episode_number')
- ->all();
-
- $mappingRecords = [];
- foreach ($episodes as $episode) {
- if (in_array($episode, $existingEpisodes)) {
- continue;
- }
- $mappingRecords[] = [
- 'script_id' => $script_id,
- 'product_id' => $product_id,
- 'episode_number' => $episode,
- 'created_at' => $now,
- 'updated_at' => $now,
- ];
- }
-
- $insertedCount = 0;
- if (!empty($mappingRecords)) {
- $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
- }
-
- return $insertedCount;
- }
-
- /**
- * 规范化剧集序号参数,统一为数组
- * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
- *
- * @param mixed $episode_number 剧集序号参数
- * @return array
- */
- private function normalizeEpisodeNumbers($episode_number) {
- if (!is_array($episode_number)) {
- $episode_number = explode(',', (string)$episode_number);
- }
-
- $items = [];
- foreach ($episode_number as $item) {
- if (is_array($item)) {
- continue;
- }
- foreach (explode(',', (string)$item) as $part) {
- $part = trim($part);
- if ($part !== '') {
- $items[] = $part;
- }
- }
- }
-
- return $items;
- }
-
- /**
- * 获取剧本总集数(通过 splitContent 拆分剧本内容)
- *
- * @param object $script 剧本记录
- * @return int 总集数
- */
- private function getScriptTotalEpisodeCount($script) {
- if (empty($script->content)) {
- Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
- }
-
- $totalEpisodes = count(splitContent($script->content));
- if ($totalEpisodes < 1) {
- Utils::throwError('20003:剧本内容无法拆分出剧集');
- }
-
- return $totalEpisodes;
- }
-
- /**
- * 获取剧本总集数
- *
- * @param array $data 包含 script_id(剧本ID)
- * @return array
- */
- public function getScriptTotalEpisodes($data) {
- $script_id = (int)getProp($data, 'script_id', 0);
- if (!$script_id) {
- Utils::throwError('20003:请提供剧本ID');
- }
-
- // 验证剧本是否存在
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$script) {
- Utils::throwError('20003:剧本不存在');
- }
-
- return [
- 'script_id' => $script_id,
- 'script_name' => $script->script_name ?? 'script_' . $script_id,
- 'episode_num' => $this->getScriptTotalEpisodeCount($script),
- ];
- }
-
- /**
- * 获取角色版本历史
- * @param array $data 包含 id(角色ID)
- * @return array 返回版本历史列表
- */
- public function getProductVersions($data) {
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:角色ID不能为空');
-
- $role = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('type', 1)
- ->first();
-
- if (!$role) Utils::throwError('20003:角色不存在');
-
- // 获取版本历史
- $versions = json_decode($role->versions, true) ?: [];
-
- // 添加当前版本作为最新版本
- $currentVersion = [
- 'version' => 0, // 0 表示当前版本
- 'url' => $role->url,
- 'pic_prompt' => $role->pic_prompt,
- 'updated_at' => $role->updated_at,
- 'is_current' => true
- ];
-
- array_unshift($versions, $currentVersion);
-
- return $versions;
- }
-
- /**
- * 恢复到指定版本
- * @param array $data 包含 id(角色ID)、version(版本号)
- * @return bool
- */
- public function restoreProductVersion($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- $version = getProp($data, 'version');
-
- if (!$id) Utils::throwError('20003:角色ID不能为空');
- if (!$version) Utils::throwError('20003:版本号不能为空');
-
- $role = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('type', 1)
- ->first();
-
- if (!$role) Utils::throwError('20003:角色不存在');
-
- // 获取版本历史
- $versions = json_decode($role->versions, true) ?: [];
-
- // 查找指定版本
- $targetVersion = null;
- foreach ($versions as $v) {
- if ($v['version'] == $version) {
- $targetVersion = $v;
- break;
- }
- }
-
- if (!$targetVersion) Utils::throwError('20003:版本不存在');
-
- // 先将当前版本保存到历史
- $newVersion = [
- 'version' => count($versions) + 1,
- 'url' => $role->url,
- 'pic_prompt' => $role->pic_prompt,
- 'updated_at' => date('Y-m-d H:i:s'),
- 'updated_by' => $uid
- ];
-
- array_unshift($versions, $newVersion);
-
- // 限制版本数量
- if (count($versions) > 10) {
- $versions = array_slice($versions, 0, 10);
- }
-
- // 恢复到指定版本
- return DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->update([
- 'url' => $targetVersion['url'],
- 'pic_prompt' => $targetVersion['pic_prompt'],
- 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- public function deleteProduct($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $role = Site::getRole();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:ID不能为空');
- $ids = explode(',', $id);
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
- $query_uid = $is_public ? 0 : $uid;
-
- // 如果是公共库操作,需要admin权限
- if ($is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能操作公共资产库');
- }
-
- // 检查是否存在且属于当前用户或公共库
- $role = DB::table('mp_products')
- ->whereIn('id', $ids)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->get();
- if (!$role) Utils::throwError('20003:记录不存在');
-
- return DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->whereIn('id', $ids)
- ->update([
- 'is_deleted' => 1,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- public function generateThreeView($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $role = Site::getRole();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:ID不能为空');
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
- $query_uid = $is_public ? 0 : $uid;
-
- // 如果是公共库操作,需要admin权限
- if ($is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能操作公共资产库');
- }
-
- // 检查是否存在且属于当前用户或公共库
- $product = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->where('type', 1)->first();
- if (!$product) Utils::throwError('20003:资产不存在');
-
- $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
- $ref_img_url = trim(getProp($data, 'ref_img_url'));
- if (!$ref_img_url) {
- // 如果没有传入参考图,使用角色表中的图片
- $ref_img_url = $product->url ?? '';
- if (!$ref_img_url) {
- Utils::throwError('20003:参考图不能为空');
- }
- }
- $pic_prompt = getProp($product, 'pic_prompt');
- if ($pic_prompt) {
- $prompt .= '\n参考图原始提示词: '.$pic_prompt;
- }
-
- // 检查参考图是否是正确的图片格式
- $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
- $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- if (!in_array($extension, $allowedExtensions)) {
- Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
- }
-
- // 处理图片模型
- $model = getProp($data, 'model');
- if (!$model) {
- // 使用默认模型
- $model = 'doubao-seedream-5-0-lite-260128';
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
- $ratio = getProp($data, 'ratio', '16:9');
- $resolution = getProp($data, 'resolution', '2k');
- // 分辨率档位与尺寸映射统一从 BaseConst 获取
- $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
-
- // 参数验证
- $resolution = strtolower($resolution);
- if (!isset($sizeMap[$resolution])) {
- Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
- }
-
- if (!isset($sizeMap[$resolution][$ratio])) {
- Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
- }
-
- // 根据 ratio 和 resolution 确定宽高
- $width = $sizeMap[$resolution][$ratio]['width'];
- $height = $sizeMap[$resolution][$ratio]['height'];
-
- try {
- // 创建图片生成任务
- $params = [
- 'prompt' => $prompt,
- 'model' => $model,
- 'ref_img_urls' => [$ref_img_url],
- 'width' => $width,
- 'height' => $height
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError('20003:创建图片生成任务失败');
- }
- // 轮询获取结果
- // 只查询数据库,不调用API,不更新任务表
- $start_time = time();
- $timeout = 1800;
- $img_url = '';
-
- while (time() - $start_time < $timeout) {
- sleep(5);
- // 只查询数据库中的任务状态,不调用API,不更新任务表
- $task = DB::table('mp_generate_pic_tasks')
- ->where('id', $task_id)
- ->first();
-
- if (!$task) {
- Utils::throwError('20003:任务不存在');
- }
-
- if ($task->status === 'success' && $task->result_url) {
- $result_urls = is_string($task->result_url)
- ? json_decode($task->result_url, true)
- : $task->result_url;
- $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
- break;
- } elseif ($task->status === 'failed') {
- Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
- }
- // 其他状态继续轮询
- }
-
- if (empty($img_url)) {
- Utils::throwError('20003:三视图生成超时,请稍后重试');
- }
-
- // 更新 mp_products 表(不是任务表)
- DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->update([
- 'three_view_image_url' => $img_url,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- return ['three_view_image_url' => $img_url];
-
- } catch (\Exception $e) {
- dLog('anime')->error('生成三视图失败', [
- 'error' => $e->getMessage()
- ]);
- logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
-
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- /**
- * 推送(复制)资产或文件夹到目标位置
- * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
- * @return array 返回推送结果
- */
- public function pushProductOrFolder($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $role = Site::getRole();
- $product_id = getProp($data, 'product_id');
- $target_parent_id = getProp($data, 'target_parent_id', 0);
- $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
-
- if (!$product_id) {
- Utils::throwError('20003:请选择要推送的项目');
- }
-
- // 查询源项目(只通过cpid查询,不限制user_id)
- $sourceItem = DB::table('mp_products')
- ->where('id', $product_id)
- ->where('cpid', $cpid)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$sourceItem) {
- Utils::throwError('20003:要推送的项目不存在');
- }
-
- // 通过user_id判断源是公共库还是个人库
- $source_uid = $sourceItem->user_id;
- $source_is_public = ($source_uid == 0) ? 1 : 0;
-
- // 验证目标文件夹并确定目标是公共库还是个人库
- $target_level = 0;
- $target_uid = $uid; // 默认推送到个人库
- $target_is_public = 0;
- $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
-
- if ($target_parent_id > 0) {
- // 查询目标文件夹(只通过cpid查询,不限制user_id)
- $targetParent = DB::table('mp_products')
- ->where('id', $target_parent_id)
- ->where('cpid', $cpid)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$targetParent) {
- Utils::throwError('20003:目标文件夹不存在');
- }
-
- // 通过user_id判断目标是公共库还是个人库
- $target_level = $targetParent->level;
- $target_uid = $targetParent->user_id;
- $target_is_public = ($target_uid == 0) ? 1 : 0;
-
- // 使用目标文件夹的 product 类型
- $final_product_type = $targetParent->product;
- }
- // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
- else {
- $push_to_public = getProp($data, 'push_to_public');
- if ($push_to_public === '') {
- Utils::throwError('20003:请选择是否推送到公共库');
- }
- if ($push_to_public) {
- $target_uid = 0;
- $target_is_public = 1;
- }
-
- // 推送到根目录时,必须指定 product 类型
- if ($target_product === null || $target_product === '') {
- Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
- }
- $final_product_type = $target_product;
- }
-
- // 如果目标是公共库,需要admin权限
- if ($target_is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能推送到公共资产库');
- }
-
- // 权限验证:验证是否符合允许的推送规则
- $this->validatePushPermission($source_uid, $target_uid, $uid);
-
- try {
- DB::beginTransaction();
-
- // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
- if ($sourceItem->type == 1) {
- $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
- DB::commit();
- return [
- 'product_id' => $newId,
- ];
- }
-
- // 如果是文件夹,递归复制(支持跨类型推送)
- $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
-
- DB::commit();
- return [
- 'product_id' => $newFolderId,
- ];
-
- } catch (\Exception $e) {
- DB::rollBack();
- dLog('anime')->error('推送失败', [
- 'error' => $e->getMessage(),
- 'product_id' => $product_id
- ]);
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
-
- /**
- * 验证推送权限
- * 允许的推送规则:
- * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
- * 2. 公共库推送给自己的个人库(公共库 → 个人库)
- * 3. 公共库推送给公共库(公共库 → 公共库)
- *
- * @param int $source_uid 源的user_id
- * @param int $target_uid 目标的user_id
- * @param int $current_uid 当前用户ID
- * @throws \Exception
- */
- private function validatePushPermission($source_uid, $target_uid, $current_uid) {
- // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
- if ($source_uid == $current_uid && $target_uid == $current_uid) {
- return; // 允许
- }
-
- // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
- if ($source_uid == 0 && $target_uid == $current_uid) {
- return; // 允许
- }
-
- // 规则3:公共库推送给公共库(公共库 → 公共库)
- if ($source_uid == 0 && $target_uid == 0) {
- return; // 允许
- }
-
- // 其他情况都不允许
- if ($source_uid != 0 && $source_uid != $current_uid) {
- // 源是别人的个人库
- Utils::throwError('20003:无权限访问该资产');
- } elseif ($source_uid == $current_uid && $target_uid == 0) {
- // 个人库推送给公共库(不允许)
- Utils::throwError('20003:不允许将个人资产推送到公共库');
- } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
- // 不同用户的个人库之间推送(不允许)
- Utils::throwError('20003:不允许推送到其他用户的个人库');
- } else {
- // 其他未知情况
- Utils::throwError('20003:不允许的推送操作');
- }
- }
-
- /**
- * 复制单个资产
- * @param object $sourceProduct 源资产对象
- * @param int $targetParentId 目标父文件夹ID
- * @param int $targetLevel 目标层级
- * @param int $cpid 公司ID
- * @param int $targetUid 目标用户ID
- * @return int 返回新资产ID
- */
- private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
- // 如果指定了 productType,使用指定的;否则使用源的 product 类型
- $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
-
- $newProductData = [
- 'user_id' => $targetUid,
- 'cpid' => $cpid,
- 'type' => 1,
- 'parent_id' => $targetParentId,
- 'level' => $targetLevel,
- 'product_name' => $sourceProduct->product_name,
- 'url' => $sourceProduct->url,
- 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
- 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
- 'product' => $finalProductType,
- 'versions' => $sourceProduct->versions ?? '',
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ];
-
- return DB::table('mp_products')->insertGetId($newProductData);
- }
-
- /**
- * 递归复制文件夹及其子项
- * @param object $sourceFolder 源文件夹对象
- * @param int $targetParentId 目标父文件夹ID
- * @param int $targetLevel 目标层级
- * @param int $cpid 公司ID
- * @param int $targetUid 目标用户ID
- * @param int $sourceUid 源用户ID
- * @return int 返回新文件夹ID
- */
- private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
- // 如果指定了 productType,使用指定的;否则使用源的 product 类型
- $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
-
- // 创建新文件夹
- $newFolderData = [
- 'user_id' => $targetUid,
- 'cpid' => $cpid,
- 'type' => 2,
- 'parent_id' => $targetParentId,
- 'level' => $targetLevel,
- 'product_name' => $sourceFolder->product_name,
- 'product' => $finalProductType,
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ];
-
- $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
-
- // 获取源文件夹下的所有子项
- $children = DB::table('mp_products')
- ->where('parent_id', $sourceFolder->id)
- ->where('cpid', $cpid)
- ->where('user_id', $sourceUid)
- ->where('is_deleted', 0)
- ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
- ->get();
-
- // 递归复制子项(子项继承目标文件夹的 product 类型)
- foreach ($children as $child) {
- if ($child->type == 1) {
- // 资产
- $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
- } else {
- // 文件夹
- $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
- }
- }
-
- return $newFolderId;
- }
- /**
- * 转让剧本归属(剧本及其关联资产)
- *
- * 仅调整 mp_scripts.user_id 与 mp_products.user_id,其他表保持不变。
- * 权限:仅 admin / superadmin 可操作;目标用户必须是同组(cpid 相同)且角色为 user(组员)的用户,禁止跨组转让。
- * 多个剧本逐个独立事务处理,单个剧本失败不影响其他剧本;
- * 单个剧本内的剧本记录与关联资产必须全部更新成功,否则整体回滚。
- *
- * @param array $data 请求参数:script_ids(数组或英文逗号分隔,兼容单个 script_id)、target_user_id
- * @return array
- */
- public function transferScriptOwner($data) {
- $operatorRole = Site::getRole();
- $operatorCpid = Site::getCpid();
- // 1.权限校验:仅管理员和超管可操作
- if (!in_array($operatorRole, ['admin', 'superadmin'], true)) {
- Utils::throwError(ErrorConst::NOT_ACCESS);
- }
- // 2.目标用户校验:必须存在且角色为 user(组员)
- $targetUserId = (int)getProp($data, 'target_user_id', 0);
- if ($targetUserId < 1) {
- Utils::throwError('1002:请选择转让的目标用户');
- }
- $targetUser = DB::table('mp_manage_users')
- ->where('id', $targetUserId)
- ->where('is_deleted', 0)
- ->first();
- if (!$targetUser) {
- Utils::throwError('20003:目标用户不存在');
- }
- if ((string)getProp($targetUser, 'role') !== 'user') {
- Utils::throwError('20003:只能转让给角色为组员(user)的用户');
- }
- $targetCpid = (int)getProp($targetUser, 'cpid');
- // 3.规范化剧本ID列表(兼容数组、逗号分隔字符串、script_id 单值)
- $rawScriptIds = getProp($data, 'script_ids');
- if (empty($rawScriptIds)) {
- $rawScriptIds = getProp($data, 'script_id');
- }
- $scriptIds = $this->normalizeIdList($rawScriptIds);
- if (empty($scriptIds)) {
- Utils::throwError('20003:请提供剧本ID');
- }
- // 预取剧本名称,便于失败结果中回显
- $scriptNameMap = DB::table('mp_scripts')
- ->whereIn('id', $scriptIds)
- ->pluck('script_name', 'id')
- ->all();
- $successList = [];
- $failedList = [];
- // 4.逐个剧本独立事务处理,单个失败不影响其他剧本
- foreach ($scriptIds as $scriptId) {
- DB::beginTransaction();
- try {
- $successList[] = $this->transferSingleScriptOwner(
- $scriptId,
- $targetUserId,
- $targetCpid,
- $operatorRole,
- $operatorCpid,
- Site::getUid()
- );
- DB::commit();
- } catch (\Throwable $e) {
- DB::rollBack();
- $failedList[] = [
- 'script_id' => (int)$scriptId,
- 'script_name' => (string)($scriptNameMap[$scriptId] ?? ''),
- 'reason' => $e->getMessage() !== '' ? $e->getMessage() : '转让失败',
- ];
- dLog('anime')->error('剧本归属转让失败', [
- 'script_id' => $scriptId,
- 'target_user_id' => $targetUserId,
- 'operator_uid' => Site::getUid(),
- 'error' => $e->getMessage(),
- ]);
- }
- }
- return [
- 'target_user_id' => $targetUserId,
- 'success_count' => count($successList),
- 'failed_count' => count($failedList),
- 'success_list' => $successList,
- 'failed_list' => $failedList,
- ];
- }
- /**
- * 单个剧本的归属转让(需在事务中调用)
- *
- * @param int $scriptId 剧本ID
- * @param int $targetUserId 目标用户ID
- * @param int $targetCpid 目标用户所属公司ID
- * @param string $operatorRole 操作人角色
- * @param int $operatorCpid 操作人所属公司ID
- * @param int $operatorUid 操作人用户ID
- * @return array
- */
- private function transferSingleScriptOwner($scriptId, $targetUserId, $targetCpid, $operatorRole, $operatorCpid, $operatorUid) {
- $script = DB::table('mp_scripts')
- ->where('id', $scriptId)
- ->where('is_deleted', 0)
- ->first();
- if (!$script) {
- Utils::throwError('20003:剧本不存在');
- }
- $scriptCpid = (int)getProp($script, 'cpid');
- $fromUserId = (int)getProp($script, 'user_id');
- // 管理员仅可操作本组剧本
- if ($operatorRole !== 'superadmin' && $scriptCpid !== $operatorCpid) {
- Utils::throwError(ErrorConst::NOT_ACCESS);
- }
- // 管理员仅可转让自己创建的剧本(超管不做此验证)
- if ($operatorRole !== 'superadmin' && $fromUserId !== (int)$operatorUid) {
- Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
- }
- // 禁止跨组转让:目标用户必须与剧本同组
- if ($targetCpid !== $scriptCpid) {
- Utils::throwError('20003:不能跨组转让,目标用户与剧本不在同一组');
- }
- // 关联资产ID(同一资产可能关联多个剧集序号,需去重)
- $productIds = $this->normalizeIdList(
- DB::table('mp_script_product_mappings')
- ->where('script_id', $scriptId)
- ->pluck('product_id')
- ->all()
- );
- $folderIds = [];
- if (!empty($productIds)) {
- $products = DB::table('mp_products')
- ->whereIn('id', $productIds)
- ->select('id', 'cpid', 'parent_id', 'user_id')
- ->get();
- // 关联资产必须全部存在,否则视为数据异常,不提交
- if ($products->count() !== count($productIds)) {
- Utils::throwError('20003:剧本存在已丢失的关联资产,无法完成转让');
- }
- foreach ($products as $product) {
- // 关联资产必须与剧本同组,避免误转让跨组资产
- if ((int)getProp($product, 'cpid') !== $scriptCpid) {
- Utils::throwError('20003:剧本存在跨组关联资产,无法完成转让');
- }
- $parentId = (int)getProp($product, 'parent_id', 0);
- if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
- $folderIds[] = $parentId;
- }
- }
- // 仅转让归属于原剧本所有者的资产
- $folderIds = DB::table('mp_products')
- ->whereIn('id', $folderIds)
- ->where('type', 2)
- ->where('cpid', $scriptCpid)
- ->where('user_id', $fromUserId)
- ->pluck('id')
- ->map('intval')
- ->all();
- // 管理员仅可转让自己创建的资产及其所属文件夹(超管不做此验证)
- if ($operatorRole !== 'superadmin') {
- foreach ($products as $product) {
- if ((int)getProp($product, 'user_id') !== (int)$operatorUid) {
- Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
- }
- }
- foreach ($products as $product) {
- $parentId = (int)getProp($product, 'parent_id', 0);
- if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
- Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
- }
- }
- }
- }
- $now = now();
- // 5.更新剧本归属
- DB::table('mp_scripts')
- ->where('id', $scriptId)
- ->update([
- 'user_id' => $targetUserId,
- 'updated_at' => $now,
- ]);
- // 6.更新关联资产归属
- if (!empty($productIds)) {
- DB::table('mp_products')
- ->whereIn('id', $productIds)
- ->update([
- 'user_id' => $targetUserId,
- 'updated_at' => $now,
- ]);
- }
- // 7.更新资产所属的类型根文件夹归属(文件夹属于 mp_products,随资产一并转让)
- if (!empty($folderIds)) {
- DB::table('mp_products')
- ->whereIn('id', $folderIds)
- ->update([
- 'user_id' => $targetUserId,
- 'updated_at' => $now,
- ]);
- }
- // 8.校验剧本与资产是否全部更新成功,任一未成功则回滚
- $scriptOwner = (int)DB::table('mp_scripts')->where('id', $scriptId)->value('user_id');
- if ($scriptOwner !== $targetUserId) {
- Utils::throwError('20003:剧本归属更新失败');
- }
- if (!empty($productIds)) {
- $updatedProductCount = DB::table('mp_products')
- ->whereIn('id', $productIds)
- ->where('user_id', $targetUserId)
- ->count();
- if ($updatedProductCount !== count($productIds)) {
- Utils::throwError('20003:部分剧本资产转让失败,已回滚');
- }
- }
- if (!empty($folderIds)) {
- $updatedFolderCount = DB::table('mp_products')
- ->whereIn('id', $folderIds)
- ->where('user_id', $targetUserId)
- ->count();
- if ($updatedFolderCount !== count($folderIds)) {
- Utils::throwError('20003:部分资产文件夹转让失败,已回滚');
- }
- }
- return [
- 'script_id' => (int)$scriptId,
- 'script_name' => (string)getProp($script, 'script_name', ''),
- 'from_user_id' => $fromUserId,
- 'to_user_id' => $targetUserId,
- 'product_count' => count($productIds),
- 'folder_count' => count($folderIds),
- ];
- }
- /**
- * 规范化ID列表,兼容数组、逗号分隔字符串以及字符串数组
- *
- * @param mixed $ids 待处理的ID集合
- * @return array 去重后的正整数ID数组
- */
- private function normalizeIdList($ids) {
- if (!is_array($ids)) {
- $ids = explode(',', (string)$ids);
- }
- $result = [];
- foreach ($ids as $item) {
- if (is_array($item)) {
- continue;
- }
- foreach (explode(',', (string)$item) as $part) {
- $part = trim($part);
- if ($part !== '' && is_numeric($part) && (int)$part > 0) {
- $result[] = (int)$part;
- }
- }
- }
- return array_values(array_unique($result));
- }
- /**
- * 通过 Excel 批量导入剧本资产(独立实现,不依赖 saveScriptProducts)
- *
- * 流程:
- * 1. 校验剧本存在且属于当前用户
- * 2. 解析 Excel 并校验强制列与数据完整性(资产类型/资产名称/使用范围/参考提示词)
- * 3. 名称去重(与 Excel 内及该剧本已有关联资产比对)
- * 4. 事务内创建类型文件夹、资产与剧本映射
- * 5. 为没有图片的资产创建图片生成任务,生成中返回 SSE 轮询
- *
- * @param array $data 请求参数
- * @param \Illuminate\Http\UploadedFile $file 上传的 Excel 文件
- * @return array|\Generator
- */
- public function importScriptProductsByExcel($data, $file) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $script_id = (int)getProp($data, 'script_id', 0);
- if (!$script_id) {
- Utils::throwError('20003:请提供剧本ID');
- }
- // 验证剧本是否存在,且只能导入自己创建的剧本
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->where('user_id', $uid)
- ->first();
- if (!$script) {
- Utils::throwError('20003:剧本不存在或无权限操作');
- }
- $script_name = $script->script_name ?? 'script_' . $script_id;
- // 校验上传文件
- if (!$file) {
- Utils::throwError('20003:请上传Excel文件');
- }
- $extension = strtolower($file->getClientOriginalExtension());
- if (!in_array($extension, ['xlsx', 'xls'])) {
- Utils::throwError('20003:文件格式错误,仅支持 xlsx、xls 格式');
- }
- if ($file->getSize() > 10 * 1024 * 1024) {
- Utils::throwError('20003:文件大小不能超过10M');
- }
- // 解析 Excel(第一行为表头)
- $rows = $this->readImportExcelRows($file);
- if (empty($rows)) {
- Utils::throwError('20003:Excel内容为空');
- }
- $headers = array_shift($rows);
- // 定位强制列
- $typeColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产类型'], ['资产类型', '类型']);
- $nameColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产名称'], ['资产名称', '名称']);
- $rangeColumnIndex = $this->findImportExcelColumnIndex($headers, ['使用范围'], ['使用范围', '范围']);
- $promptColumnIndex = $this->findImportExcelColumnIndex($headers, ['参考提示词', '提示词'], ['提示词']);
- $missingColumns = [];
- if ($typeColumnIndex < 0) {
- $missingColumns[] = '资产类型';
- }
- if ($nameColumnIndex < 0) {
- $missingColumns[] = '资产名称';
- }
- if ($rangeColumnIndex < 0) {
- $missingColumns[] = '使用范围';
- }
- if ($promptColumnIndex < 0) {
- $missingColumns[] = '参考提示词';
- }
- if (!empty($missingColumns)) {
- Utils::throwError('20003:Excel缺少必填列:' . implode('、', $missingColumns));
- }
- // 先整体校验 Excel 数据,所有异常行一次性返回
- $validation = $this->validateImportExcelRows(
- $rows,
- $typeColumnIndex,
- $nameColumnIndex,
- $rangeColumnIndex,
- $promptColumnIndex
- );
- $errors = $validation['errors'];
- $checkedRows = $validation['checked_rows'];
- if (empty($checkedRows)) {
- $errors[] = 'Excel中没有有效的数据行';
- }
- if (!empty($errors)) {
- Utils::throwError('20003:Excel数据校验失败:' . implode(';', $errors));
- }
- // 名称去重:Excel 内部 + 该剧本已关联资产(按 createProduct 的名称判断逻辑)
- $existingNames = $this->getScriptProductNames($script_id, $cpid);
- $dedupResult = $this->deduplicateImportRows($checkedRows, $existingNames);
- $validRows = $dedupResult['valid_rows'];
- $skipped = $dedupResult['skipped'];
- // 图片生成参数(与 saveScriptProducts 保持一致的校验规则)
- $model = getProp($data, 'model');
- if (!$model) {
- $model = 'doubao-seedream-5-0-lite-260128';
- }
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
- $ratio = getProp($data, 'ratio', '9:16');
- $resolution = strtolower(getProp($data, 'resolution', '2k'));
- $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
- if (!isset($sizeMap[$resolution])) {
- Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
- }
- if (!isset($sizeMap[$resolution][$ratio])) {
- Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
- }
- $width = $sizeMap[$resolution][$ratio]['width'];
- $height = $sizeMap[$resolution][$ratio]['height'];
- $autoRaw = getProp($data, 'auto_generate_images', true);
- $auto_generate_images = !in_array($autoRaw, [false, 0, '0', 'false', 'False'], true);
- // 创建/复用任务中心记录(md5 验重,避免重复任务)
- $taskCenterId = $this->createScriptProductTaskCenter(
- $uid,
- $cpid,
- $script_id,
- $validRows,
- $model,
- $ratio,
- $resolution,
- $auto_generate_images
- );
- // 全部为重复项:参照 saveScriptProducts,检查已存在资产的图片状态,缺图的补建任务
- if (empty($validRows)) {
- $existingTaskInfo = $this->prepareExistingScriptProductTasks(
- $script_id,
- $model,
- $width,
- $height,
- $auto_generate_images
- );
- $productTaskMap = $existingTaskInfo['product_task_map'];
- $typeFolderIds = $existingTaskInfo['type_folder_ids'];
- if (!empty($productTaskMap)) {
- $message = 'Excel中的资产均已存在,正在为缺少图片的资产生成图片';
- } elseif (!$existingTaskInfo['has_all_tasks']) {
- $message = 'Excel中的资产均已存在,部分资产没有参考提示词,无法生成图片';
- } else {
- $message = 'Excel中的资产均已存在,且图片已全部生成完成';
- }
- $resultData = [
- 'success' => true,
- 'message' => $message,
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'imported_count' => 0,
- 'existing_products' => $existingTaskInfo['product_count'],
- 'skipped_count' => count($skipped),
- 'skipped' => $skipped,
- 'created_products' => [],
- 'type_folder_ids' => $typeFolderIds,
- 'pending_tasks_count' => count($productTaskMap),
- 'image_tasks_created' => $existingTaskInfo['created_count'],
- 'task_center_id' => $taskCenterId,
- ];
- // 有需要轮询的任务(已有任务或本次补建):走 SSE 返回结果
- if (!empty($productTaskMap)) {
- return $this->pollProductImageTasks(
- $script_id,
- $script_name,
- $productTaskMap,
- $typeFolderIds,
- $taskCenterId,
- ['import_result' => $resultData]
- );
- }
- // 资产图片已全部生成完成或无法生成:直接返回结果
- if ($taskCenterId) {
- $this->taskCenterService->updateTask($taskCenterId, [
- 'status' => MpTaskCenter::STATUS_SUCCESS,
- 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
- 'error_message' => null,
- ]);
- }
- return $resultData;
- }
- // 事务内创建资产、类型文件夹与剧本映射
- $typeFolderIds = [];
- $createdProducts = [];
- $mappingRecords = [];
- $now = now();
- DB::beginTransaction();
- try {
- foreach ($validRows as $row) {
- $type = $row['type'];
- if (!isset($typeFolderIds[$type])) {
- // 与 createProduct 一致:先查找该剧本已存在的类型文件夹,没有则创建
- $folder = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('type', 2)
- ->where('product', $type)
- ->where('product_name', $script_name)
- ->where('parent_id', 0)
- ->where('is_deleted', 0)
- ->first();
- if ($folder) {
- $typeFolderIds[$type] = $folder->id;
- } else {
- $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 2, // 文件夹
- 'product' => $type, // 1=角色 2=场景 3=道具
- 'parent_id' => 0,
- 'level' => 1,
- 'product_name' => $script_name,
- 'sort_order' => time() + $type,
- 'is_deleted' => 0,
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
- }
- }
- $folder_id = $typeFolderIds[$type];
- $product_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 1, // 资产
- 'product' => $type,
- 'parent_id' => $folder_id,
- 'level' => 2,
- 'product_name' => $row['product_name'],
- 'pic_prompt' => $row['pic_prompt'],
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
- $createdProducts[] = [
- 'id' => $product_id,
- 'type' => $type,
- 'product_name' => $row['product_name'],
- 'pic_prompt' => $row['pic_prompt'],
- ];
- // 为每个使用范围(集数)创建映射记录
- foreach ($row['episode_numbers'] as $episodeNumber) {
- $mappingRecords[] = [
- 'script_id' => $script_id,
- 'product_id' => $product_id,
- 'episode_number' => $episodeNumber,
- 'created_at' => $now,
- 'updated_at' => $now,
- ];
- }
- }
- // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
- DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
- // 剧本已有资产,同步更新is_products标记
- DB::table('mp_scripts')->where('id', $script_id)->update([
- 'is_products' => 1,
- 'updated_at' => $now,
- ]);
- DB::commit();
- } catch (\Exception $e) {
- DB::rollback();
- if ($taskCenterId) {
- $this->taskCenterService->updateTask($taskCenterId, [
- 'status' => MpTaskCenter::STATUS_FAILED,
- 'error_message' => $e->getMessage(),
- ]);
- }
- dLog('anime')->error('Excel导入剧本资产失败: ' . $e->getMessage(), [
- 'script_id' => $script_id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
- Utils::throwError('20003:Excel导入剧本资产失败:' . $e->getMessage());
- }
- // 参照 saveScriptProducts:为新建资产以及已存在但缺图的资产统一补建图片生成任务
- $existingTaskInfo = $this->prepareExistingScriptProductTasks(
- $script_id,
- $model,
- $width,
- $height,
- $auto_generate_images
- );
- $productTaskMap = $existingTaskInfo['product_task_map'];
- $resultData = [
- 'success' => true,
- 'message' => '导入完成',
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'imported_count' => count($createdProducts),
- 'skipped_count' => count($skipped),
- 'skipped' => $skipped,
- 'created_products' => array_map(function ($item) {
- return [
- 'id' => $item['id'],
- 'type' => $item['type'],
- 'product_name' => $item['product_name'],
- ];
- }, $createdProducts),
- 'type_folder_ids' => $typeFolderIds,
- 'pending_tasks_count' => count($productTaskMap),
- 'image_tasks_created' => $existingTaskInfo['created_count'],
- 'task_center_id' => $taskCenterId,
- ];
- // 有待生成的图片任务:返回 SSE 轮询结果(导入统计放在 init 事件中)
- if (!empty($productTaskMap)) {
- return $this->pollProductImageTasks(
- $script_id,
- $script_name,
- $productTaskMap,
- $typeFolderIds,
- $taskCenterId,
- ['import_result' => $resultData]
- );
- }
- // 所有资产都已有图片或未开启生成:直接返回结果
- if ($taskCenterId) {
- $this->taskCenterService->updateTask($taskCenterId, [
- 'status' => MpTaskCenter::STATUS_SUCCESS,
- 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
- 'error_message' => null,
- ]);
- }
- return $resultData;
- }
- /**
- * 校验 Excel 数据行(先校验完毕,再进行后续逻辑)
- *
- * @param array $rows
- * @param int $typeColumnIndex
- * @param int $nameColumnIndex
- * @param int $rangeColumnIndex
- * @param int $promptColumnIndex
- * @return array ['errors' => [], 'checked_rows' => []]
- */
- private function validateImportExcelRows(array $rows, $typeColumnIndex, $nameColumnIndex, $rangeColumnIndex, $promptColumnIndex) {
- $errors = [];
- $checkedRows = [];
- foreach ($rows as $rowIndex => $row) {
- // 数据从第2行开始(表头占第1行)
- $excelRowNo = $rowIndex + 2;
- if (!is_array($row) || $this->isImportExcelRowEmpty($row)) {
- continue;
- }
- $typeRaw = trim((string)($row[$typeColumnIndex] ?? ''));
- $nameRaw = trim((string)($row[$nameColumnIndex] ?? ''));
- $rangeRaw = trim((string)($row[$rangeColumnIndex] ?? ''));
- $promptRaw = trim((string)($row[$promptColumnIndex] ?? ''));
- $missingFields = [];
- if ($typeRaw === '') {
- $missingFields[] = '资产类型';
- }
- if ($nameRaw === '') {
- $missingFields[] = '资产名称';
- }
- if ($rangeRaw === '') {
- $missingFields[] = '使用范围';
- }
- if ($promptRaw === '') {
- $missingFields[] = '参考提示词';
- }
- if (!empty($missingFields)) {
- $errors[] = "第{$excelRowNo}行:" . implode('、', $missingFields) . '不能为空';
- continue;
- }
- // 资产类型校验
- $productType = $this->resolveImportProductType($typeRaw);
- if (!$productType) {
- $errors[] = "第{$excelRowNo}行:资产类型「{$typeRaw}」不正确,仅支持 角色/场景/道具";
- continue;
- }
- // 资产名称去除两边特殊符号
- $productName = $this->normalizeImportProductName($nameRaw);
- if ($productName === '') {
- $errors[] = "第{$excelRowNo}行:资产名称「{$nameRaw}」去除特殊符号后为空";
- continue;
- }
- if (mb_strlen($productName, 'UTF-8') > 64) {
- $errors[] = "第{$excelRowNo}行:资产名称「{$productName}」超过64个字符";
- continue;
- }
- // 解析使用范围(逗号分隔的集数)
- $episodeNumbers = $this->parseImportEpisodeNumbers($rangeRaw);
- if (empty($episodeNumbers)) {
- $errors[] = "第{$excelRowNo}行:使用范围「{$rangeRaw}」格式错误,仅支持数字或逗号分隔的数字";
- continue;
- }
- $checkedRows[] = [
- 'row' => $excelRowNo,
- 'type' => $productType,
- 'product_name' => $productName,
- 'episode_numbers' => $episodeNumbers,
- 'pic_prompt' => $promptRaw,
- ];
- }
- return [
- 'errors' => $errors,
- 'checked_rows' => $checkedRows,
- ];
- }
- /**
- * Excel 资产名称去重:Excel 内部 + 剧本已有关联资产
- *
- * @param array $checkedRows
- * @param array $existingNames 剧本已有关联资产名称集合(name => true)
- * @return array ['valid_rows' => [], 'skipped' => []]
- */
- private function deduplicateImportRows(array $checkedRows, array $existingNames) {
- $seenNames = [];
- $validRows = [];
- $skipped = [];
- foreach ($checkedRows as $row) {
- $nameKey = $row['product_name'];
- $typeText = $this->getImportProductTypeText($row['type']);
- if (isset($seenNames[$nameKey])) {
- $skipped[] = [
- 'row' => $row['row'],
- 'type' => $typeText,
- 'product_name' => $row['product_name'],
- 'reason' => 'Excel中资产名称重复',
- ];
- continue;
- }
- if (isset($existingNames[$nameKey])) {
- $skipped[] = [
- 'row' => $row['row'],
- 'type' => $typeText,
- 'product_name' => $row['product_name'],
- 'reason' => '剧本中已存在同名资产',
- ];
- continue;
- }
- $seenNames[$nameKey] = true;
- $validRows[] = $row;
- }
- return [
- 'valid_rows' => $validRows,
- 'skipped' => $skipped,
- ];
- }
- /**
- * 读取 Excel 文件为二维数组(第一行为表头)
- *
- * @param \Illuminate\Http\UploadedFile $file
- * @return array
- */
- private function readImportExcelRows($file) {
- try {
- $reader = IOFactory::createReaderForFile($file->getRealPath());
- $reader->setReadDataOnly(true);
- $spreadsheet = $reader->load($file->getRealPath());
- $sheet = $spreadsheet->getSheet(0);
- $rows = $sheet->toArray(null, true, true, false);
- $spreadsheet->disconnectWorksheets();
- unset($spreadsheet);
- return $rows;
- } catch (\Exception $e) {
- dLog('anime')->error('Excel文件解析失败', [
- 'error' => $e->getMessage(),
- ]);
- Utils::throwError('20003:Excel文件解析失败,请确认文件格式正确');
- }
- }
- /**
- * 查找 Excel 表头列索引(先精确匹配,再模糊匹配)
- *
- * @param array $headers
- * @param array $exactKeywords
- * @param array $fuzzyKeywords
- * @return int
- */
- private function findImportExcelColumnIndex(array $headers, array $exactKeywords, array $fuzzyKeywords) {
- foreach ($headers as $index => $header) {
- $header = trim((string)$header);
- if ($header === '') {
- continue;
- }
- foreach ($exactKeywords as $keyword) {
- if ($header === $keyword) {
- return $index;
- }
- }
- }
- foreach ($headers as $index => $header) {
- $header = trim((string)$header);
- if ($header === '') {
- continue;
- }
- foreach ($fuzzyKeywords as $keyword) {
- if (mb_strpos($header, $keyword) !== false) {
- return $index;
- }
- }
- }
- return -1;
- }
- /**
- * 判断 Excel 行是否为空行
- *
- * @param array $row
- * @return bool
- */
- private function isImportExcelRowEmpty(array $row) {
- foreach ($row as $cell) {
- if (trim((string)$cell) !== '') {
- return false;
- }
- }
- return true;
- }
- /**
- * 资产名称去除两边特殊符号(与 createProduct 保持一致)
- *
- * @param string $name
- * @return string
- */
- private function normalizeImportProductName($name) {
- $name = trim((string)$name);
- $name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $name);
- if (!$name || preg_match('/^[-—_]+$/u', $name)) {
- return '';
- }
- return $name;
- }
- /**
- * 解析 Excel 中的资产类型
- *
- * @param string $value
- * @return int|null 1=角色 2=场景 3=道具
- */
- private function resolveImportProductType($value) {
- $value = trim((string)$value);
- $map = [
- '角色' => 1,
- '主体' => 1,
- '人物' => 1,
- '1' => 1,
- '场景' => 2,
- '2' => 2,
- '道具' => 3,
- '3' => 3,
- ];
- return isset($map[$value]) ? $map[$value] : null;
- }
- /**
- * 资产类型文案
- *
- * @param int $type
- * @return string
- */
- private function getImportProductTypeText($type) {
- $map = [1 => '角色', 2 => '场景', 3 => '道具'];
- return isset($map[$type]) ? $map[$type] : (string)$type;
- }
- /**
- * 解析使用范围(逗号分隔的集数)
- *
- * @param string $value
- * @return array
- */
- private function parseImportEpisodeNumbers($value) {
- $parts = preg_split('/[,,、\s]+/u', trim((string)$value));
- $episodeNumbers = [];
- foreach ($parts as $part) {
- if ($part === '') {
- continue;
- }
- if (!is_numeric($part)) {
- return [];
- }
- $episodeNumbers[] = (int)$part;
- }
- $episodeNumbers = array_values(array_unique($episodeNumbers));
- sort($episodeNumbers);
- return $episodeNumbers;
- }
- /**
- * 获取剧本已关联资产名称集合(按 createProduct 的名称判断逻辑)
- *
- * @param int $script_id
- * @param int $cpid
- * @return array
- */
- private function getScriptProductNames($script_id, $cpid) {
- $products = DB::table('mp_script_product_mappings as m')
- ->join('mp_products as p', 'm.product_id', '=', 'p.id')
- ->where('m.script_id', $script_id)
- ->where('p.cpid', $cpid)
- ->where('p.type', 1)
- ->where('p.is_deleted', 0)
- ->get(['p.product_name']);
- $names = [];
- foreach ($products as $product) {
- $name = $this->normalizeImportProductName($product->product_name);
- if ($name !== '') {
- $names[$name] = true;
- }
- }
- return $names;
- }
- /**
- * 已有关联资产的图片任务处理(参照 saveScriptProducts 的处理方式)
- *
- * - 已有图片任务的资产:收集任务ID,交给轮询
- * - 已有图片且生成成功的资产:跳过
- * - 没有图片的资产:允许自动生成时补建图片任务(需要提示词)
- *
- * @param int $script_id
- * @param string $model
- * @param int $width
- * @param int $height
- * @param bool $auto_generate_images
- * @return array ['product_task_map' => [], 'type_folder_ids' => [], 'has_all_tasks' => bool, 'product_count' => int, 'created_count' => int]
- */
- private function prepareExistingScriptProductTasks($script_id, $model, $width, $height, $auto_generate_images) {
- $productTaskMap = [];
- $typeFolderIds = [];
- $hasAllTasks = true;
- $createdCount = 0;
- $existingMappings = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->get();
- $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
- $productsWithTasks = DB::table('mp_products')
- ->whereIn('id', $productIds)
- ->where('is_deleted', 0)
- ->get();
- foreach ($productsWithTasks as $product) {
- // 收集类型文件夹ID
- if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
- $parentFolder = DB::table('mp_products')
- ->where('id', $product->parent_id)
- ->where('type', 2)
- ->first();
- if ($parentFolder) {
- $typeFolderIds[$parentFolder->product] = $parentFolder->id;
- }
- }
- // 检查是否有图片生成任务
- if (!empty($product->pic_task_id)) {
- $productTaskMap[$product->id] = $product->pic_task_id;
- } elseif ($product->url && $product->pic_task_status == '生成成功') {
- continue;
- } else {
- // 有资产没有图片
- $hasAllTasks = false;
- }
- }
- // 为没有图片的资产补建图片生成任务
- if (!$hasAllTasks && $auto_generate_images && $productsWithTasks->isNotEmpty()) {
- DB::beginTransaction();
- try {
- foreach ($productsWithTasks as $product) {
- // 跳过已有任务的资产
- if (!empty($product->pic_task_id)) {
- continue;
- }
- // 跳过没有提示词的资产
- if (empty($product->pic_prompt)) {
- dLog('anime')->warning('资产没有提示词,跳过图片生成', [
- 'product_id' => $product->id,
- 'product_name' => $product->product_name,
- ]);
- continue;
- }
- try {
- $task = $this->aiImageGenerationService->createImageGenerationTask([
- 'prompt' => $product->pic_prompt,
- 'model' => $model,
- 'ref_img_urls' => [],
- 'width' => $width,
- 'height' => $height,
- ]);
- $task_id = $task->id;
- if ($task_id) {
- $productTaskMap[$product->id] = $task_id;
- $createdCount++;
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_id' => $task_id,
- 'pic_task_status' => '生成中',
- 'updated_at' => now(),
- ]);
- dLog('anime')->info('为已存在资产创建图片生成任务', [
- 'product_id' => $product->id,
- 'task_id' => $task_id,
- ]);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('创建资产图片生成任务失败', [
- 'product_id' => $product->id,
- 'error' => $e->getMessage(),
- ]);
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成失败',
- 'updated_at' => now(),
- ]);
- }
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollback();
- dLog('anime')->error('为已存在资产创建图片任务失败', [
- 'script_id' => $script_id,
- 'error' => $e->getMessage(),
- ]);
- Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
- }
- }
- return [
- 'product_task_map' => $productTaskMap,
- 'type_folder_ids' => $typeFolderIds,
- 'has_all_tasks' => $hasAllTasks,
- 'product_count' => count($productIds),
- 'created_count' => $createdCount,
- ];
- }
- /**
- * 保存剧本资产关联关系
- * @param array $data 请求参数
- * @return bool
- */
- public function saveScriptProducts($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $script_id = getProp($data, 'script_id');
- $products = getProp($data, 'products', []);
- $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
- if (!$script_id) {
- Utils::throwError('20003:请提供剧本ID');
- }
- // 验证剧本是否存在
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$script) {
- Utils::throwError('20003:剧本不存在');
- }
- // 处理图片模型
- $model = getProp($data, 'model');
- if (!$model) {
- // 使用默认模型
- $model = 'doubao-seedream-5-0-lite-260128';
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
- $ratio = getProp($data, 'ratio', '9:16');
- $resolution = getProp($data, 'resolution', '2k');
- // 分辨率档位与尺寸映射统一从 BaseConst 获取
- $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
-
- // 参数验证
- $resolution = strtolower($resolution);
- if (!isset($sizeMap[$resolution])) {
- Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
- }
-
- if (!isset($sizeMap[$resolution][$ratio])) {
- Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
- }
-
- // 根据 ratio 和 resolution 确定宽高
- $width = $sizeMap[$resolution][$ratio]['width'];
- $height = $sizeMap[$resolution][$ratio]['height'];
-
- $script_name = $script->script_name ?? 'script_' . $script_id;
-
- // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
- $taskCenterId = $this->createScriptProductTaskCenter(
- $uid,
- $cpid,
- $script_id,
- $products,
- $model,
- $ratio,
- $resolution,
- $auto_generate_images
- );
- // 检查是否已经有该剧本的资产数据
- $existingMappings = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->get();
-
- if ($existingMappings->isNotEmpty()) {
- // 已存在资产映射,检查是否所有资产都有图片生成任务
- $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
-
- // 查询这些资产的图片生成任务状态
- $productsWithTasks = DB::table('mp_products')
- ->whereIn('id', $productIds)
- ->where('is_deleted', 0)
- ->get();
-
- $productTaskMap = [];
- $typeFolderIds = [];
- $hasAllTasks = true;
-
- foreach ($productsWithTasks as $product) {
- // 收集类型文件夹ID
- if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
- $parentFolder = DB::table('mp_products')
- ->where('id', $product->parent_id)
- ->where('type', 2)
- ->first();
-
- if ($parentFolder) {
- $typeFolderIds[$parentFolder->product] = $parentFolder->id;
- }
- }
-
- // 检查是否有图片生成任务
- if (!empty($product->pic_task_id)) {
- $productTaskMap[$product->id] = $product->pic_task_id;
- } else if($product->url && $product->pic_task_status == '生成成功') {
- continue;
- } else {
- // 有资产没有图片任务
- $hasAllTasks = false;
- }
- }
-
- // 如果所有资产都有任务ID,直接轮询返回结果
- if ($hasAllTasks && !empty($productTaskMap)) {
- dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'product_count' => count($productTaskMap)
- ]);
-
- // 直接返回 SSE 流轮询结果
- return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
- }
-
- // 如果部分资产没有任务ID,只为这些资产创建任务
- if (!$hasAllTasks && $auto_generate_images) {
- dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
- 'script_id' => $script_id,
- 'script_name' => $script_name
- ]);
- // 开启事务
- DB::beginTransaction();
-
- try {
-
- foreach ($productsWithTasks as $product) {
- // 跳过已有任务的资产
- if (!empty($product->pic_task_id)) {
- continue;
- }
-
- // 跳过没有提示词的资产
- if (empty($product->pic_prompt)) {
- dLog('anime')->warning('资产没有提示词,跳过图片生成', [
- 'product_id' => $product->id,
- 'product_name' => $product->product_name
- ]);
- continue;
- }
-
- try {
- // 创建图片生成任务
- $params = [
- 'prompt' => $product->pic_prompt,
- 'model' => $model,
- 'ref_img_urls' => [],
- 'width' => $width,
- 'height' => $height
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if ($task_id) {
- $productTaskMap[$product->id] = $task_id;
-
- // 在事务中更新资产表的任务ID和状态
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_id' => $task_id,
- 'pic_task_status' => '生成中',
- 'updated_at' => now()
- ]);
-
- dLog('anime')->info('为已存在资产创建图片生成任务', [
- 'product_id' => $product->id,
- 'task_id' => $task_id
- ]);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('创建资产图片生成任务失败', [
- 'product_id' => $product->id,
- 'error' => $e->getMessage()
- ]);
-
- // 标记为失败(仍在事务中)
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成失败',
- 'updated_at' => now()
- ]);
- }
- }
-
- // 提交事务
- DB::commit();
-
- // 如果有新创建的任务,返回 SSE 流
- if (!empty($productTaskMap)) {
- return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
- }
-
- } catch (\Exception $e) {
- // 回滚事务
- DB::rollback();
-
- dLog('anime')->error('为已存在资产创建图片任务失败', [
- 'script_id' => $script_id,
- 'error' => $e->getMessage()
- ]);
-
- Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
- }
- }
-
- // 如果不需要生成图片,返回已存在的信息
- $resultData = [
- 'success' => true,
- 'message' => '剧本资产已存在',
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'type_folder_ids' => $typeFolderIds,
- 'existing_products' => count($productIds),
- 'tasks_count' => count($productTaskMap),
- 'task_center_id' => $taskCenterId
- ];
- // 接口已正常完成,更新任务中心状态和结果
- if ($taskCenterId) {
- $this->taskCenterService->updateTask($taskCenterId, [
- 'status' => MpTaskCenter::STATUS_SUCCESS,
- 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
- 'error_message' => null
- ]);
- }
- return $resultData;
- }
- // 解析 products(可能是 JSON 字符串或数组)
- if (is_string($products)) {
- $products = json_decode($products, true);
- if (json_last_error() !== JSON_ERROR_NONE) {
- Utils::throwError('20003:产品数据格式错误');
- }
- }
- if (!is_array($products) || empty($products)) {
- Utils::throwError('20003:产品数据不能为空');
- }
- // 以下是原有的创建逻辑...
- // 开启事务
- DB::beginTransaction();
-
- try {
- $now = now();
- $mappingRecords = [];
- $createdProductIds = []; // 记录所有创建的资产ID
-
- // 获取剧本名称
- $script_name = $script->script_name ?? 'script_' . $script_id;
-
- // 存储每个类型的根文件夹ID
- $typeFolderIds = [];
-
- // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
- foreach ($products as $productGroup) {
- $type = getProp($productGroup, 'type');
- $title = getProp($productGroup, 'title', '');
- $content = getProp($productGroup, 'content', []);
-
- if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
- continue;
- }
-
- // 为当前类型创建根文件夹(如果还未创建)
- if (!isset($typeFolderIds[$type])) {
- $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 2, // 1.资产 2文件夹
- 'product' => $type, // 1.主体 2.场景 3.道具
- 'parent_id' => 0, // 根文件夹,parent_id=0
- 'level' => 1, // 第一层级
- 'product_name' => $script_name,
- 'sort_order' => time() + $type,
- 'is_deleted' => 0,
- 'created_at' => $now,
- 'updated_at' => $now
- ]);
- }
-
- $folder_id = $typeFolderIds[$type];
-
- // 获取表头(第一行)并查找关键列的位置
- $headers = $content[0];
- $nameColumnIndex = -1; // 资产名称列索引
- $sequenceColumnIndex = -1; // 使用范围列索引
- $promptColumnIndex = -1; // 参考提示词列索引
-
- foreach ($headers as $index => $header) {
- // 查找"资产名称"列
- if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
- $nameColumnIndex = $index;
- }
- // 查找"使用范围"列
- if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
- $sequenceColumnIndex = $index;
- }
- // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
- if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
- $promptColumnIndex = $index;
- }
- }
-
- // 验证必要的列是否都找到了
- if ($nameColumnIndex === -1) {
- dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
- continue;
- }
- if ($sequenceColumnIndex === -1) {
- dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
- continue;
- }
-
- // 跳过表头,解析每一行数据
- for ($i = 1; $i < count($content); $i++) {
- $row = $content[$i];
-
- // 确保行数据有效
- if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
- continue;
- }
-
- // 根据动态查找的列索引提取数据
- $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
- $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
- $pic_prompt = '';
-
- // 提取参考提示词(如果找到了该列)
- if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
- $pic_prompt = trim($row[$promptColumnIndex]);
- }
-
- // 解析使用范围(逗号分隔的序号)
- $sequences = [];
- if (!empty($sequence_str)) {
- $sequenceParts = array_map('trim', explode(',', $sequence_str));
- foreach ($sequenceParts as $part) {
- if (is_numeric($part)) {
- $sequences[] = (int)$part;
- }
- }
- }
-
- if (empty($product_name)) {
- continue;
- }
- // 处理product_name两边的符号
- $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
- // 如果名称不存在或仅剩占位符号,则跳过
- if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
- dLog('anime')->warning('资产名称无效,跳过保存', [
- 'script_id' => $script_id,
- 'type' => $type,
- 'product_name' => $product_name
- ]);
- continue;
- }
-
- // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
- $product_id = DB::table('mp_products')->insertGetId([
- 'product_name' => $product_name,
- 'type' => 1, // 1=资产 2.文件夹
- 'product' => $type, // 1=角色, 2=场景, 3=道具
- 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
- 'level' => 2, // 第二层级
- 'pic_prompt' => $pic_prompt,
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
-
- // 记录创建的资产ID
- $createdProductIds[] = $product_id;
-
- // 为每个序号创建映射记录
- if (!empty($sequences)) {
- foreach ($sequences as $sequence) {
- $mappingRecords[] = [
- 'script_id' => $script_id,
- 'product_id' => $product_id,
- 'episode_number' => $sequence,
- 'created_at' => $now,
- 'updated_at' => $now,
- ];
- }
- } else {
- // 如果没有指定序号,创建一个默认映射(序号为0)
- $mappingRecords[] = [
- 'script_id' => $script_id,
- 'product_id' => $product_id,
- 'episode_number' => 0,
- 'created_at' => $now,
- 'updated_at' => $now,
- ];
- }
- }
- }
- if (empty($mappingRecords)) {
- Utils::throwError('20003:没有有效的产品数据');
- }
- // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
- $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
- // 剧本已有资产,同步更新is_products标记
- DB::table('mp_scripts')->where('id', $script_id)->update([
- 'is_products' => 1,
- 'updated_at' => $now
- ]);
-
- // 如果需要自动生成图片,在事务中创建图片生成任务
- $productTaskMap = [];
- if ($auto_generate_images && !empty($createdProductIds)) {
- // 查询所有创建的资产
- $productsToGenerate = DB::table('mp_products')
- ->whereIn('id', $createdProductIds)
- ->where('is_deleted', 0)
- ->get();
-
- foreach ($productsToGenerate as $product) {
- if (empty($product->pic_prompt)) {
- dLog('anime')->warning('资产没有提示词,跳过图片生成', [
- 'product_id' => $product->id,
- 'product_name' => $product->product_name
- ]);
- continue;
- }
-
- try {
- // 创建图片生成任务
- $params = [
- 'prompt' => $product->pic_prompt,
- 'model' => $model,
- 'ref_img_urls' => [],
- 'width' => $width,
- 'height' => $height
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if ($task_id) {
- $productTaskMap[$product->id] = $task_id;
-
- // 在事务中更新资产表的任务ID和状态
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_id' => $task_id,
- 'pic_task_status' => '生成中',
- 'updated_at' => now()
- ]);
-
- dLog('anime')->info('创建资产图片生成任务', [
- 'product_id' => $product->id,
- 'task_id' => $task_id
- ]);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('创建资产图片生成任务失败', [
- 'product_id' => $product->id,
- 'error' => $e->getMessage()
- ]);
-
- // 标记为失败(仍在事务中)
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成失败',
- 'updated_at' => now()
- ]);
- }
- }
- }
-
- // 提交事务
- DB::commit();
-
- // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
- if ($auto_generate_images && !empty($productTaskMap)) {
- // 返回 SSE 流(事务外轮询)
- return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
- }
-
- // 如果不需要生成图片,返回普通结果
- $resultData = [
- 'success' => true,
- 'type_folder_ids' => $typeFolderIds,
- 'inserted_count' => $insertedCount,
- 'total_records' => count($mappingRecords),
- 'created_products' => count($createdProductIds),
- 'image_tasks_created' => count($productTaskMap),
- 'task_center_id' => $taskCenterId
- ];
- // 接口已正常完成,更新任务中心状态和结果
- if ($taskCenterId) {
- $this->taskCenterService->updateTask($taskCenterId, [
- 'status' => MpTaskCenter::STATUS_SUCCESS,
- 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
- 'error_message' => null
- ]);
- }
- return $resultData;
-
- } catch (\Exception $e) {
- // 回滚事务
- DB::rollback();
-
- // 更新任务中心状态为失败
- if (!empty($taskCenterId)) {
- $this->taskCenterService->updateTask($taskCenterId, [
- 'status' => MpTaskCenter::STATUS_FAILED,
- 'error_message' => $e->getMessage()
- ]);
- }
- // 记录错误日志
- dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
- 'script_id' => $script_id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
-
- // 统一使用 Utils::throwError 抛出错误
- Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
- }
- }
- /**
- * 根据入参创建或复用任务中心记录
- *
- * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
- * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
- * 避免生成重复任务。
- *
- * @param int|string $uid
- * @param int|string $cpid
- * @param int|string $script_id
- * @param mixed $products
- * @param string $model
- * @param string $ratio
- * @param string $resolution
- * @param mixed $auto_generate_images
- * @return int 任务中心ID
- */
- private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
- // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
- if (is_string($products)) {
- $decoded = json_decode($products, true);
- if (json_last_error() === JSON_ERROR_NONE) {
- $products = $decoded;
- }
- }
- $params = [
- 'script_id' => (int)$script_id,
- 'products' => $products,
- 'model' => $model,
- 'ratio' => $ratio,
- 'resolution' => $resolution,
- 'auto_generate_images' => (bool)$auto_generate_images,
- ];
- $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
- // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
- $existing = DB::table('mp_task_center')
- ->where('uid', (int)$uid)
- ->where('cpid', (int)$cpid)
- ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
- ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
- ->where('params_md5', $paramsMd5)
- ->orderBy('id', 'desc')
- ->first();
- if ($existing) {
- dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
- 'script_id' => $script_id,
- 'task_center_id' => $existing->id,
- 'params_md5' => $paramsMd5,
- ]);
- return (int)$existing->id;
- }
- // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
- $now = date('Y-m-d H:i:s');
- DB::table('mp_task_center')->insertOrIgnore([
- 'uid' => (int)$uid,
- 'cpid' => (int)$cpid,
- 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
- 'title' => '剧本资产图片生成',
- 'ref_task_id' => 0,
- 'status' => MpTaskCenter::STATUS_PROCESSING,
- 'result' => null,
- 'error_message' => null,
- 'prompt' => null,
- 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
- 'params_md5' => $paramsMd5,
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
- // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
- $taskId = (int)DB::table('mp_task_center')
- ->where('uid', (int)$uid)
- ->where('cpid', (int)$cpid)
- ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
- ->where('params_md5', $paramsMd5)
- ->orderBy('id', 'desc')
- ->value('id');
- dLog('anime')->info('创建任务中心记录', [
- 'script_id' => $script_id,
- 'task_center_id' => $taskId,
- 'params_md5' => $paramsMd5,
- ]);
- return $taskId;
- }
- /**
- * 任务结束时更新任务中心记录的状态和结果
- *
- * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
- * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
- *
- * @param int|null $taskCenterId
- * @param array $resultData 接口返回结果数组
- * @param bool $timeout 是否超时未完成
- */
- private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
- if (!$taskCenterId) {
- return;
- }
- $stats = $resultData['stats'] ?? [];
- $successCount = (int)array_sum(array_column((array)$stats, 'success'));
- $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
- $failedCount = $completedCount - $successCount;
- // 与接口返回给客户端的结果保持一致
- $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
- if ($timeout) {
- $this->taskCenterService->updateTask((int)$taskCenterId, [
- 'status' => MpTaskCenter::STATUS_FAILED,
- 'result' => $result,
- 'error_message' => '部分任务超时,请稍后查看结果',
- ]);
- return;
- }
- $this->taskCenterService->updateTask((int)$taskCenterId, [
- 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
- 'result' => $result,
- 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
- ]);
- }
- /**
- * 批量为剧本资产生成图片
- *
- * @param array $data 请求参数
- * @return \Generator 返回 SSE 流
- */
- public function batchGenerateProductImages($data) {
- $script_id = getProp($data, 'script_id');
- $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
-
- if (!$script_id) {
- Utils::throwError('20003:请提供剧本ID');
- }
-
- // 验证剧本是否存在
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$script) {
- Utils::throwError('20003:剧本不存在');
- }
-
- $script_name = $script->script_name ?? 'script_' . $script_id;
-
- // 获取需要生成图片的所有资产
- $products = DB::table('mp_products')
- ->whereIn('parent_id', array_values($type_folder_ids))
- ->where('is_deleted', 0)
- ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
- ->get();
-
- if ($products->isEmpty()) {
- Utils::throwError('20003:没有找到需要生成图片的资产');
- }
-
- // 默认参数
- $model = 'doubao-seedream-5-0-lite-260128';
- $width = 1600;
- $height = 2848;
-
- // 开始为每个资产创建图片生成任务
- $taskIds = [];
- $productTaskMap = []; // 资产ID到任务ID的映射
-
- foreach ($products as $product) {
- if (empty($product->pic_prompt)) {
- dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
- continue;
- }
-
- try {
- // 创建图片生成任务
- $params = [
- 'prompt' => $product->pic_prompt,
- 'model' => $model,
- 'ref_img_urls' => [],
- 'width' => $width,
- 'height' => $height
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if ($task_id) {
- $taskIds[] = $task_id;
- $productTaskMap[$product->id] = $task_id;
-
- // 更新资产表的任务ID和状态
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_id' => $task_id,
- 'pic_task_status' => '生成中',
- 'updated_at' => now()
- ]);
-
- dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('创建资产图片生成任务失败', [
- 'product_id' => $product->id,
- 'error' => $e->getMessage()
- ]);
-
- // 标记为失败
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成失败',
- 'updated_at' => now()
- ]);
- }
- }
-
- if (empty($taskIds)) {
- Utils::throwError('20003:没有成功创建任何图片生成任务');
- }
-
- // 返回 SSE 流
- return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
- }
-
- /**
- * 轮询资产图片生成任务状态(SSE流式返回)
- * 只通过查询数据库获取任务状态,不主动调用API
- *
- * @param int $script_id 剧本ID
- * @param string $script_name 剧本名称
- * @param array $productTaskMap 资产ID到任务ID的映射
- * @param array $type_folder_ids 类型文件夹ID映射
- * @param int|null $taskCenterId 任务中心ID
- * @param array $initExtra 追加到 init 事件中的额外数据
- * @return \Generator
- */
- private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null, array $initExtra = []) {
- $startTime = time();
- $timeout = 1800; // 30分钟超时
- $pollInterval = 10; // 10秒轮询一次
- $lastStatus = []; // 记录上次的状态,用于判断是否有变化
- // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
- if ($taskCenterId) {
- $initResponse = array_merge([
- 'type' => 'init',
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'timestamp' => date('Y-m-d H:i:s'),
- 'task_center_id' => (int)$taskCenterId,
- ], $initExtra);
- yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
- }
-
- // 定义类型名称映射
- $typeNames = [
- 1 => 'roles', // 角色
- 2 => 'scenes', // 场景
- 3 => 'props' // 道具
- ];
-
- while (time() - $startTime < $timeout) {
- sleep($pollInterval);
-
- // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
- $mappings = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->pluck('product_id')
- ->unique()
- ->toArray();
-
- if (empty($mappings)) {
- dLog('anime')->warning('该剧本没有关联的资产', [
- 'script_id' => $script_id,
- 'script_name' => $script_name
- ]);
- break;
- }
-
- // 查询所有资产的当前状态
- $products = DB::table('mp_products')
- ->whereIn('id', $mappings)
- ->where('is_deleted', 0)
- ->get();
-
- // 统计各类型的状态(使用类型名称作为键名)
- $stats = [
- 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
- 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
- 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
- ];
-
- $allCompleted = true;
- $hasStatusChange = false;
-
- foreach ($products as $product) {
- $type = $product->product;
- $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
-
- // 如果类型名称不在 stats 中,初始化
- if (!isset($stats[$typeName])) {
- $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
- }
-
- $stats[$typeName]['total']++;
-
- $task_id = $product->pic_task_id;
- $currentStatus = $product->pic_task_status;
-
- // 检查状态是否有变化
- if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
- $hasStatusChange = true;
- $lastStatus[$product->id] = $currentStatus;
- }
-
- // 如果是生成中,查询任务表状态
- if ($currentStatus === '生成中' && $task_id) {
- // 只查询数据库,不调用API
- $task = DB::table('mp_generate_pic_tasks')
- ->where('id', $task_id)
- ->first();
-
- if ($task) {
- // 检查任务状态
- if ($task->status === 'success' && $task->result_url) {
- // 解析图片URL
- $result_urls = $task->result_url;
- if (is_string($result_urls)) {
- $result_urls = json_decode($result_urls, true);
- }
- $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
-
- // 更新资产表状态
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成成功',
- 'url' => $img_url,
- 'updated_at' => now()
- ]);
-
- $stats[$typeName]['success']++;
- $stats[$typeName]['completed']++;
- $hasStatusChange = true;
-
- dLog('anime')->info('资产图片生成成功', [
- 'product_id' => $product->id,
- 'task_id' => $task_id,
- 'img_url' => $img_url
- ]);
- } elseif ($task->status === 'failed') {
- // 更新资产表状态
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成失败',
- 'updated_at' => now()
- ]);
-
- $stats[$typeName]['completed']++;
- $hasStatusChange = true;
-
- dLog('anime')->warning('资产图片生成失败', [
- 'product_id' => $product->id,
- 'task_id' => $task_id,
- 'error' => $task->error_message ?? '未知错误'
- ]);
- } else {
- // 任务还在处理中
- $allCompleted = false;
- }
- } else {
- // 任务不存在,标记为失败
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成失败',
- 'updated_at' => now()
- ]);
-
- $stats[$typeName]['completed']++;
- $hasStatusChange = true;
-
- dLog('anime')->error('图片生成任务不存在', [
- 'product_id' => $product->id,
- 'task_id' => $task_id
- ]);
- }
- } elseif ($currentStatus === '生成成功') {
- $stats[$typeName]['success']++;
- $stats[$typeName]['completed']++;
- } elseif ($currentStatus === '生成失败') {
- $stats[$typeName]['completed']++;
- } else {
- // 其他状态也认为未完成
- $allCompleted = false;
- }
- }
-
- // 移除没有数据的类型(total=0)
- foreach ($stats as $typeName => $stat) {
- if ($stat['total'] === 0) {
- unset($stats[$typeName]);
- }
- }
-
- // 如果有状态变化,发送 SSE 更新
- if ($hasStatusChange) {
- $eventType = $allCompleted ? 'complete' : 'update';
-
- $response = [
- 'type' => $eventType,
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'stats' => $stats,
- 'timestamp' => date('Y-m-d H:i:s')
- ];
- if ($taskCenterId) {
- $response['task_center_id'] = $taskCenterId;
- }
-
- yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
-
- dLog('anime')->info('SSE更新', [
- 'event_type' => $eventType,
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'stats' => $stats
- ]);
-
- if ($allCompleted) {
- dLog('anime')->info('所有资产图片生成任务已完成', [
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'stats' => $stats
- ]);
-
- // 全部任务完成,更新任务中心状态和结果
- $this->finishScriptProductTask($taskCenterId, $response);
- break;
- }
- }
- }
-
- // 超时处理
- if (time() - $startTime >= $timeout && !$allCompleted) {
- $response = [
- 'type' => 'timeout',
- 'message' => '部分任务超时,请稍后查看结果',
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'timestamp' => date('Y-m-d H:i:s')
- ];
- if ($taskCenterId) {
- $response['task_center_id'] = $taskCenterId;
- }
-
- yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
-
- dLog('anime')->warning('资产图片生成任务超时', [
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'timeout' => $timeout
- ]);
- // 超时未完成,更新任务中心状态和结果
- $this->finishScriptProductTask($taskCenterId, $response, true);
- }
- }
- /**
- * 定时任务:检查产品图片生成任务状态并更新产品记录
- * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
- * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
- *
- * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
- */
- public function checkProductPicTasks() {
- // 查询所有生成中的产品图片任务
- $products = DB::table('mp_products')
- ->whereNotNull('pic_task_id')
- ->where('pic_task_status', '生成中')
- ->where('is_deleted', 0)
- ->get();
- $stats = [
- 'total' => $products->count(),
- 'success' => 0,
- 'failed' => 0,
- 'pending' => 0,
- ];
- foreach ($products as $product) {
- try {
- $task_id = $product->pic_task_id;
- // 通过 pic_task_id 查询图片生成任务结果
- $task = DB::table('mp_generate_pic_tasks')
- ->where('id', $task_id)
- ->first();
- if ($task) {
- if ($task->status === 'success' && $task->result_url) {
- // 解析图片URL
- $result_urls = $task->result_url;
- if (is_string($result_urls)) {
- $result_urls = json_decode($result_urls, true);
- }
- $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
- // 更新资产表状态
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成成功',
- 'url' => $img_url,
- 'updated_at' => now()
- ]);
- $stats['success']++;
- dLog('anime')->info('资产图片生成成功', [
- 'product_id' => $product->id,
- 'task_id' => $task_id,
- 'img_url' => $img_url
- ]);
- } elseif ($task->status === 'failed') {
- // 更新资产表状态
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成失败',
- 'updated_at' => now()
- ]);
- $stats['failed']++;
- dLog('anime')->warning('资产图片生成失败', [
- 'product_id' => $product->id,
- 'task_id' => $task_id,
- 'error' => $task->error_message ?? '未知错误'
- ]);
- } else {
- // 任务还在处理中
- $stats['pending']++;
- }
- } else {
- // 任务不存在,标记为失败
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成失败',
- 'updated_at' => now()
- ]);
- $stats['failed']++;
- dLog('anime')->error('图片生成任务不存在', [
- 'product_id' => $product->id,
- 'task_id' => $task_id
- ]);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('检查产品图片生成任务异常', [
- 'product_id' => $product->id,
- 'task_id' => $product->pic_task_id ?? null,
- 'error' => $e->getMessage()
- ]);
- }
- }
- return $stats;
- }
- /**
- * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
- *
- * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
- * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
- * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
- *
- * @return int 更新的任务中心记录数
- */
- public function checkSaveScriptProductTaskCenters() {
- $updated = 0;
- // 只扫描尚未结束的 saveScriptProducts 任务
- $tasks = DB::table('mp_task_center')
- ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
- ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
- ->orderBy('id', 'desc')
- ->limit(500)
- ->get();
- // 与 pollProductImageTasks 保持一致的类型名称映射
- $typeNames = [
- 1 => 'roles', // 角色
- 2 => 'scenes', // 场景
- 3 => 'props', // 道具
- ];
- foreach ($tasks as $task) {
- try {
- $taskParams = json_decode((string)$task->params, true);
- $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
- if (!$script_id) {
- dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
- 'task_center_id' => $task->id,
- ]);
- continue;
- }
- // 获取该剧本关联的全部资产ID
- $productIds = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->pluck('product_id')
- ->unique()
- ->toArray();
- if (empty($productIds)) {
- // 剧本没有关联资产,不视为完成,等待下一次检查
- continue;
- }
- $products = DB::table('mp_products')
- ->whereIn('id', $productIds)
- ->where('is_deleted', 0)
- ->get();
- $stats = [];
- $allCompleted = true;
- foreach ($products as $product) {
- $typeName = $typeNames[$product->product] ?? 'unknown';
- if (!isset($stats[$typeName])) {
- $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
- }
- $stats[$typeName]['total']++;
- if ($product->pic_task_status === '生成成功') {
- $stats[$typeName]['success']++;
- $stats[$typeName]['completed']++;
- } elseif ($product->pic_task_status === '生成失败') {
- $stats[$typeName]['completed']++;
- } else {
- // 仍有资产在生成中或未生成,任务未完成
- $allCompleted = false;
- }
- }
- if (!$allCompleted) {
- continue;
- }
- // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
- $script_name = $script->script_name ?? 'script_' . $script_id;
- $this->finishScriptProductTask($task->id, [
- 'type' => 'complete',
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'stats' => $stats,
- 'timestamp' => date('Y-m-d H:i:s'),
- 'task_center_id' => (int)$task->id,
- ]);
- $updated++;
- dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
- 'task_center_id' => $task->id,
- 'script_id' => $script_id,
- 'stats' => $stats,
- ]);
- } catch (\Exception $e) {
- dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
- 'task_center_id' => $task->id,
- 'error' => $e->getMessage(),
- ]);
- }
- }
- return $updated;
- }
- /**
- * 获取剧本关联的资产列表
- * @param array $data 请求参数
- * @return array
- */
- public function getScriptProducts($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $script_id = getProp($data, 'script_id');
- $episode_number = getProp($data, 'episode_number');
- if (!$script_id) {
- Utils::throwError('20003:请提供剧本ID');
- }
- // 验证剧本是否存在
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$script) {
- Utils::throwError('20003:剧本不存在');
- }
- // 联表查询资产信息
- $query = DB::table('mp_script_product_mappings as mapping')
- ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
- ->where('mapping.script_id', $script_id)
- ->where('product.cpid', $cpid)
- ->where('product.is_deleted', 0);
- // 如果提供了 episode_number,则过滤指定集数
- if ($episode_number !== null && $episode_number !== '') {
- $query->where('mapping.episode_number', $episode_number);
- }
- $mappings = $query->select(
- 'mapping.script_id',
- 'mapping.product_id',
- 'mapping.episode_number',
- 'product.product_name',
- 'product.type',
- 'product.product',
- 'product.pic_prompt',
- 'product.url',
- 'product.pic_task_id',
- 'product.pic_task_status',
- 'product.three_view_image_url',
- 'mapping.created_at'
- )
- ->orderBy('mapping.product_id', 'asc')
- ->orderBy('mapping.episode_number', 'asc')
- ->get();
- // 按 product_id 分组,合并 episode_number
- $productMap = [];
- foreach ($mappings as $item) {
- $product_id = $item->product_id;
-
- if (!isset($productMap[$product_id])) {
- $productMap[$product_id] = [
- 'product_id' => $product_id,
- 'product_name' => $item->product_name,
- 'type' => (int)$item->type,
- 'product' => (int)$item->product,
- 'pic_prompt' => $item->pic_prompt,
- 'url' => $item->url,
- 'pic_task_id' => $item->pic_task_id,
- 'pic_task_status' => $item->pic_task_status,
- 'episode_numbers' => [],
- 'created_at' => $item->created_at,
- ];
- }
-
- // 添加 episode_number(去重)
- if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
- $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
- }
- }
-
- // 按类型分组
- $roles = []; // type=1 角色/主体
- $scenes = []; // type=2 场景
- $props = []; // type=3 道具
-
- foreach ($productMap as $product) {
- // 将 episode_numbers 数组转换为逗号分隔的字符串
- $episodeNumbersStr = implode(',', $product['episode_numbers']);
-
- // 构造返回数据
- $productData = [
- 'product_id' => $product['product_id'],
- 'product_name' => $product['product_name'],
- 'product' => $product['product'],
- 'pic_prompt' => $product['pic_prompt'],
- 'url' => $product['url'],
- 'pic_task_id' => $product['pic_task_id'],
- 'pic_task_status' => $product['pic_task_status'],
- 'episode_numbers' => $episodeNumbersStr,
- 'created_at' => $product['created_at'],
- ];
-
- // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
- // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
- switch ($product['product']) {
- case 1:
- $roles[] = $productData;
- break;
- case 2:
- $scenes[] = $productData;
- break;
- case 3:
- $props[] = $productData;
- break;
- }
- }
- return [
- 'script_id' => $script_id,
- 'script_name' => $script->script_name ?? '',
- 'roles' => $roles, // 主体
- 'scenes' => $scenes, // 场景
- 'props' => $props, // 道具
- ];
- }
- /**
- * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
- * @param string $actContent 原始内容
- * @param array $products 产品数组(包含product_name和url)
- * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
- */
- public function processActContentWithProducts($actContent, $products) {
- if (empty($actContent) || empty($products)) {
- return [
- 'content' => $actContent,
- 'reference_images' => []
- ];
- }
-
- // 构建产品名称到产品信息的映射
- $product_dict = [];
- foreach ($products as $product) {
- $product_name = getProp($product, 'product_name');
- if ($product_name) {
- $product_dict[$product_name] = [
- // 优先使用三视图图片作为素材/参考图,否则使用原图 url
- 'url' => getProp($product, 'three_view_image_url') ?: getProp($product, 'url'),
- 'voice_prompt' => getProp($product, 'voice_prompt')
- ];
- }
- }
-
- // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
- preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
-
- $reference_images = [];
- $product_index_map = []; // 产品名称 => 图片序号的映射
- $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
- $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
- $current_index = 1;
-
- if (!empty($matches[1])) {
- // 按照在内容中第一次出现的顺序,为每个产品分配序号
- $seen_products = []; // 用于去重
-
- foreach ($matches[1] as $product_name) {
- // 跳过已处理的产品
- if (isset($seen_products[$product_name])) {
- continue;
- }
-
- $seen_products[$product_name] = true;
-
- // 检查产品是否在字典中
- if (isset($product_dict[$product_name])) {
- $url = $product_dict[$product_name]['url'];
- $voice_prompt = $product_dict[$product_name]['voice_prompt'];
-
- // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
- if (!empty($voice_prompt) && $product_name !== '旁白') {
- $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
- }
-
- // 只有URL非空才分配序号和添加到参考图片
- if (!empty($url)) {
- // 检查URL是否已经在reference_images中(去重)
- if (!in_array($url, $reference_images)) {
- $reference_images[] = $url;
- $product_index_map[$product_name] = $current_index;
- $current_index++;
- } else {
- // URL重复,找到已有的序号
- $existing_index = array_search($url, $reference_images) + 1;
- $product_index_map[$product_name] = $existing_index;
- }
- } else {
- // URL为空,不分配序号(后续直接去掉{})
- $product_index_map[$product_name] = 0;
- }
- } else {
- // 产品不在字典中,不分配序号
- $product_index_map[$product_name] = 0;
- }
- }
- }
-
- // 第二步:替换内容中的 {产品名称}
- $processedContent = $actContent;
- foreach ($product_index_map as $product_name => $index) {
- $escaped_name = preg_quote($product_name, '/');
-
- if ($index > 0) {
- // 有图片,替换为:产品名称(图X)
- $replacement = $product_name . '<图片' . $index . '>';
- } else {
- // 无图片,只保留产品名称
- $replacement = $product_name;
- }
-
- // 替换所有 {产品名称} 为处理后的格式
- $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
- }
-
- // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
- foreach ($products as $product) {
- $product_name = getProp($product, 'product_name');
- $voice_prompt = getProp($product, 'voice_prompt');
-
- if ($product_name === '旁白' && !empty($voice_prompt)) {
- $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
- break; // 找到旁白后退出循环
- }
- }
-
- // 第四步:将voice_prompt信息添加到内容最前面
- $voice_prompt_prefix = '';
- if (!empty($voice_prompts)) {
- $voice_prompt_prefix .= implode('', $voice_prompts);
- }
- // 旁白的voice_prompt放在最后
- if (!empty($narrator_voice_prompt)) {
- $voice_prompt_prefix .= $narrator_voice_prompt;
- }
-
- // 如果有voice_prompt信息,添加到内容开头
- if (!empty($voice_prompt_prefix)) {
- $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
- }
-
- return [
- 'content' => $processedContent,
- 'reference_images' => $reference_images
- ];
- }
- public function saveActVideoGenerateParams($data) {
- $episode_id = getProp($data, 'episode_id');
- $model = getProp($data, 'video_model');
- $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
- if (!in_array($model, $valid_models)) {
- Utils::throwError('20003:该模型不可用');
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
- $video_resolution = getProp($data, 'video_resolution', '720p');
- $ratio = getProp($data, 'ratio');
- if (!$ratio) $ratio = '9:16';
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
- if (!$episode) {
- Utils::throwError('20003:分集不存在');
- }
- dLog('anime')->info('保存分集视频参数', $data);
- try {
- DB::beginTransaction();
- $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'video_model' => $model,
- 'video_resolution' => $video_resolution,
- 'ratio' => $ratio,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:分集视频参数保存失败');
- }
- // 同步更新mp_animes表
- $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
- 'video_model' => $model,
- 'video_resolution' => $video_resolution,
- 'video_ratio' => $ratio,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($anime_result === false) {
- Utils::throwError('20003:动漫视频参数保存失败');
- }
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- return $result;
-
- }
- public function confirmActs($data) {
- $episode_id = getProp($data, 'episode_id');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$episode) {
- Utils::throwError('20003:分集不存在');
- }
- $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
- $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
- $props = json_decode(getProp($episode, 'props'), true) ?: [];
- // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
- $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
- // 获取所有片段数据
- $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
-
- // 先构建完整的 products(角色、场景、道具、extra_products,并用资产库映射覆盖),
- // 再处理每个片段的 act_content,避免 extra_products 等资产名未被格式化为 {资产名}
- // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
- // extra_products优先级更高,会覆盖同名的roles、scenes和props
- $products = [];
-
- // 先处理角色数组
- foreach ($roles as $role) {
- $product = $role;
- // 将role字段重命名为product_name
- if (isset($product['role'])) {
- $product['product_name'] = $product['role'];
- unset($product['role']);
- $product['product'] = 1; // 标记类型为角色
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
- }
-
- // 处理场景数组
- foreach ($scenes as $scene) {
- $product = $scene;
- // 将scene字段重命名为product_name
- if (isset($product['scene'])) {
- $product['product_name'] = $product['scene'];
- unset($product['scene']);
- $product['product'] = 2; // 标记类型为场景
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
-
- }
-
- // 处理道具数组(逻辑与场景一致)
- foreach ($props as $prop) {
- $product = $prop;
- // 将prop字段重命名为product_name
- if (isset($product['prop'])) {
- $product['product_name'] = $product['prop'];
- unset($product['prop']);
- $product['product'] = 3; // 标记类型为道具
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
- }
-
- // extra_products优先级更高,直接覆盖同名的roles和scenes
- $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
- foreach ($extra_products as $extra_product) {
- $product_name = getProp($extra_product, 'product_name');
- if ($product_name) {
- $products[$product_name] = $extra_product; // 覆盖同名数据
- }
- }
- // mp_script_product_mappings 信息优先级更高:
- // 获取当前剧集所属动漫剧本下、与本集资产同名的资产库最新数据(url/三视图/提示词等),
- // 覆盖分集 JSON 中保存的同名旧快照;分集内独有的 description、voice_prompt 等字段保留
- $anime = DB::table('mp_animes')->where('id', getProp($episode, 'anime_id'))->first();
- $script_id = $anime ? (int)getProp($anime, 'script_id', 0) : 0;
- if ($script_id && !empty($products)) {
- $currentProductNames = array_keys($products);
- $normalizeName = function($name) {
- return trim(preg_replace(
- '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
- '',
- trim((string)$name)
- ));
- };
- $mappingItems = DB::table('mp_script_product_mappings as mapping')
- ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
- ->where('mapping.script_id', $script_id)
- ->where('product.is_deleted', 0)
- ->whereIn('product.product_name', $currentProductNames)
- ->select(
- 'mapping.product_id',
- 'product.product_name',
- 'product.product',
- 'product.pic_prompt',
- 'product.url',
- 'product.three_view_image_url',
- )
- ->get();
- $mappingByName = [];
- foreach ($mappingItems as $mappingItem) {
- $normalizedName = $normalizeName($mappingItem->product_name);
- if (!$normalizedName) continue;
- $mappingByName[$normalizedName] = [
- 'product_id' => (int)$mappingItem->product_id,
- 'product_name' => $mappingItem->product_name,
- 'product' => (int)$mappingItem->product,
- 'pic_prompt' => $mappingItem->pic_prompt ?? '',
- 'url' => $mappingItem->url ?? '',
- 'three_view_image_url' => $mappingItem->three_view_image_url ?? '',
- ];
- }
- foreach ($products as $key => &$product) {
- $normalizedKey = $normalizeName($key);
- if ($normalizedKey && isset($mappingByName[$normalizedKey])) {
- $product = array_merge($product, $mappingByName[$normalizedKey]);
- }
- }
- unset($product);
- }
- // 兼容返回 three_view_image_url 字段(旧数据可能没有该键,统一补空值)
- foreach ($products as &$product) {
- if (!isset($product['three_view_image_url'])) {
- $product['three_view_image_url'] = '';
- }
- }
- unset($product);
-
- // 重新索引数组(去除key)
- $products = array_values($products);
-
- // 基于构建完成的 products 收集所有资产名称(含 extra_products 中的资产)
- $product_names = [];
- foreach ($products as $product) {
- $product_name = getProp($product, 'product_name');
- if ($product_name && $product_name !== '旁白') {
- $product_names[] = $product_name;
- }
- }
-
- // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
- $product_names = array_unique($product_names);
- usort($product_names, function($a, $b) {
- return mb_strlen($b) - mb_strlen($a);
- });
- try {
- DB::beginTransaction();
- // 处理每个片段
- foreach ($acts as $act) {
- $act_content = getProp($act, 'act_content');
- if (!$act_content) continue;
-
- $processed_content = $act_content;
-
- // 统一替换所有资产名称为 {资产名} 格式
- // 使用占位符避免嵌套替换问题
- $placeholder_map = [];
- $placeholder_index = 0;
-
- foreach ($product_names as $product_name) {
- // 转义特殊字符
- $escaped_product = preg_quote($product_name, '/');
-
- // 检查是否匹配且未被 {} 包裹
- $processed_content = preg_replace_callback(
- '/(?<![{])(' . $escaped_product . ')(?![}])/u',
- function($matches) use (&$placeholder_map, &$placeholder_index) {
- // 使用唯一占位符
- $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
- $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
- $placeholder_index++;
- return $placeholder;
- },
- $processed_content
- );
- }
-
- // 将所有占位符替换回实际内容
- foreach ($placeholder_map as $placeholder => $replacement) {
- $processed_content = str_replace($placeholder, $replacement, $processed_content);
- }
-
- // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
- $shot_counter = 0;
- $processed_content = preg_replace_callback(
- '/【(?:镜头|分镜)(\d+)】/u',
- function($matches) use (&$shot_counter) {
- $shot_counter++;
- return '【镜头' . $shot_counter . '】';
- },
- $processed_content
- );
-
- // 更新数据库
- $boolen = DB::table('mp_episode_segments')
- ->where('id', $act->id)
- ->update([
- 'act_show_content' => $processed_content,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$boolen) {
- Utils::throwError('20003:片段处理失败');
- }
- }
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
-
- $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'is_generated' => 1,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$boolen1) {
- DB::rollBack();
- Utils::throwError('20003:分集处理失败!');
- }
- DB::commit();
- // 重新查询更新后的片段数据
- $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
- // 构建返回的acts数组
- $return_acts = [];
- foreach ($acts as $act) {
- $return_acts[] = [
- 'act_id' => getProp($act, 'id'),
- 'act_number' => getProp($act, 'act_number'),
- 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
- 'act_show_content' => getProp($act, 'act_show_content'),
- 'video_url' => getProp($act, 'video_url'),
- 'video_duration' => getProp($act, 'video_duration'),
- 'video_time_point_start' => getProp($act, 'video_time_point_start'),
- 'video_time_point_end' => getProp($act, 'video_time_point_end'),
- ];
- }
- return [
- 'anime_id' => getProp($episode, 'anime_id'),
- 'episode_id' => $episode_id,
- 'title' => getProp($episode, 'title'),
- 'episode_number' => getProp($episode, 'episode_number'),
- 'is_generated' => getProp($episode, 'is_generated'),
- 'video_params' => [
- 'video_model' => getProp($episode, 'video_model'),
- 'video_resolution' => getProp($episode, 'video_resolution'),
- 'ratio' => getProp($episode, 'ratio'),
- ],
- 'products' => $products,
- 'acts' => $return_acts
- ];
- }
- /**
- * 参照 episodePicsInfo 的更新与监控逻辑:
- * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
- * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
- */
- private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
- $pollInterval = 5; // 每5秒查询一次
- $maxWaitSeconds = 60; // 最多持续1分钟
- $startTime = time();
- while (true) {
- // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$episode) {
- Utils::throwError('20003:分集不存在');
- }
- $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
- $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
- $props = json_decode(getProp($episode, 'props'), true) ?: [];
- $updated = false;
- $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
- $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
- $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
- $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
- $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
- // 有图片任务结果更新时写回分集表
- if ($updated) {
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
- 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
- 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
- if (empty($waitingAssets) && empty($missingAssets)) {
- return;
- }
- // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
- if (empty($waitingAssets)) {
- Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
- }
- // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
- if (time() - $startTime >= $maxWaitSeconds) {
- Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
- }
- sleep($pollInterval);
- }
- }
- /**
- * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
- * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
- * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
- */
- private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
- foreach ($assets as &$asset) {
- $assetName = getProp($asset, $nameKey);
- if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
- continue;
- }
- // 已有图片URL的资产视为已生成
- if (getProp($asset, 'url')) {
- continue;
- }
- $task_id = getProp($asset, 'task_id');
- // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
- if (!$task_id) {
- $missingAssets[] = $assetName;
- continue;
- }
- $task = DB::table('mp_generate_pic_tasks')
- ->where('id', $task_id)
- ->select('status', 'result_url')
- ->first();
- // 任务不存在:同样记录为缺失项,不在此处直接报错
- if (!$task) {
- $missingAssets[] = $assetName;
- continue;
- }
- if ($task->status === 'success') {
- $result_url = getProp($task, 'result_url');
- if ($result_url) {
- $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
- if (is_array($result_urls) && !empty($result_urls[0])) {
- $asset['url'] = $result_urls[0];
- $asset['task_status'] = 'success';
- $updated = true;
- continue;
- }
- }
- // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
- $waitingAssets[] = $assetName;
- } elseif ($task->status === 'failed') {
- // 生成失败:记录为缺失项,待其他任务处理完后统一报错
- $missingAssets[] = $assetName;
- } else {
- // 任务仍在生成中,等待下一次轮询
- $waitingAssets[] = $assetName;
- }
- }
- unset($asset);
- }
- /**
- * 导出动漫剧本为PDF(参照示例PDF版式)
- * @param int $animeId 动漫ID
- * @param int $episodeCount 导出集数,默认8,传-1表示全部
- * @param string|null $savePath 指定保存路径(为空则直接下载输出)
- * @return string|null
- */
- public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
- // 图片下载与转换可能占用较多内存
- ini_set('memory_limit', '512M');
- $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
- if (!$anime) Utils::throwError('20003:该动漫不存在!');
- $anime = (array)$anime;
- // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
- $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
- // 获取分集(默认展示版本,按集数升序)
- $episodeQuery = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('is_default', 1)
- ->orderBy('episode_number')
- ->orderBy('id');
- if ($episodeCount > 0) {
- $episodeQuery->limit($episodeCount);
- }
- $episodes = $episodeQuery->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
- if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
- // 聚合主体/场景/道具列表(前N集内容,按名称去重)
- $roles = $this->mergeEpisodeItems($episodes, 'role');
- $scenes = $this->mergeEpisodeItems($episodes, 'scene');
- $props = $this->mergeEpisodeItems($episodes, 'prop');
- // 组装分集剧本数据
- $episodeScripts = [];
- foreach ($episodes as $episode) {
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episode['id'])
- ->get();
- // 按act_number分组,同一片段多版本时取最新一条(id最大)
- $acts = [];
- foreach ($segments as $segment) {
- $segment = (array)$segment;
- $actNumber = (int)getProp($segment, 'act_number', 0);
- if ($actNumber <= 0) continue;
- if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
- $acts[$actNumber] = [
- 'id' => (int)$segment['id'],
- 'act_number' => $actNumber,
- 'duration' => getProp($segment, 'act_duration', ''),
- 'content' => getProp($segment, 'act_content', ''),
- ];
- }
- }
- ksort($acts);
- // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
- $segmentCounter = 0;
- foreach ($acts as &$act) {
- $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
- }
- unset($act);
- // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
- $narratorVoice = '';
- $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
- foreach ($episodeRoles as $role) {
- if (getProp($role, 'role') === '旁白') {
- $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
- break;
- }
- }
- if ($narratorVoice === '') {
- foreach ($acts as $act) {
- if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
- $narratorVoice = trim($match[1]);
- break;
- }
- }
- }
- $episodeScripts[] = [
- 'episode_number' => getProp($episode, 'episode_number'),
- 'title' => getProp($episode, 'title', ''),
- 'act_count' => count($acts),
- 'narrator_voice' => $narratorVoice,
- 'acts' => array_values($acts),
- ];
- }
- // 并发下载列表图片(主体/场景/道具),url => 临时文件
- $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
- // 构建PDF
- $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
- // 图片已嵌入PDF,清理临时文件
- foreach ($imageCache as $imgFile) {
- @unlink($imgFile);
- }
- $filename = $anime['anime_name'] . '_' . date('YmdHis');
- if ($savePath) {
- $pdf->Output($savePath, 'F');
- return $savePath;
- }
- // 直接下载输出
- header('Content-Type: application/pdf');
- header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
- $pdf->Output($filename . '.pdf', 'D');
- exit();
- }
- /**
- * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
- * @param array $episodes 分集数据
- * @param string $nameKey role|scene|prop
- * @return array
- */
- private function mergeEpisodeItems(array $episodes, $nameKey) {
- $fieldMap = [
- 'role' => 'roles',
- 'scene' => 'scenes',
- 'prop' => 'props',
- ];
- $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
- $items = [];
- foreach ($episodes as $episode) {
- $list = json_decode(getProp($episode, $field, ''), true) ?: [];
- foreach ($list as $item) {
- if (!is_array($item)) continue;
- $name = trim((string)getProp($item, $nameKey, ''));
- if ($name === '') continue;
- // 旁白不进入主体列表(仅作为旁白音色来源)
- if ($nameKey === 'role' && $name === '旁白') continue;
- if (!isset($items[$name])) {
- $items[$name] = $item;
- }
- }
- }
- return array_values($items);
- }
- /**
- * 构建动漫剧本PDF
- * @param array $anime 动漫信息
- * @param array $roles 主体列表
- * @param array $scenes 场景列表
- * @param array $props 道具列表
- * @param array $episodeScripts 分集剧本数据
- * @param array $imageCache 图片缓存(url => 临时文件路径)
- * @return \TCPDF
- */
- private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
- $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
- $pdf->SetCreator('动漫剧本导出系统');
- $pdf->SetAuthor('系统');
- $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
- $pdf->SetSubject('动漫剧本导出');
- $pdf->SetMargins(15, 15, 15);
- $pdf->SetAutoPageBreak(true, 15);
- // 剧本名
- $pdf->AddPage();
- $pdf->SetFont('simsun', 'B', 20);
- $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
- $pdf->Ln(5);
- // 故事梗概
- $intro = trim((string)getProp($anime, 'intro', ''));
- if ($intro !== '') {
- $this->pdfSectionTitle($pdf, '故事梗概');
- $this->pdfBody($pdf, $intro);
- }
- // 美术风格
- $artStyle = trim((string)getProp($anime, 'art_style', ''));
- if ($artStyle !== '') {
- $this->pdfSectionTitle($pdf, '美术风格');
- $this->pdfBody($pdf, $artStyle);
- }
- // 主体列表(文字+图片)
- $this->pdfSectionTitle($pdf, '主体列表');
- foreach ($roles as $index => $role) {
- $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
- }
- $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
- // 场景列表(文字+图片)
- $this->pdfSectionTitle($pdf, '场景列表');
- foreach ($scenes as $index => $scene) {
- $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
- }
- $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
- // 道具列表(文字+图片)
- $this->pdfSectionTitle($pdf, '道具列表');
- foreach ($props as $index => $prop) {
- $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
- }
- $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
- // 分镜剧本
- $this->pdfSectionTitle($pdf, '分镜剧本');
- foreach ($episodeScripts as $episodeScript) {
- $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
- $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
- if ($episodeTitleRaw !== '') {
- // title 字段可能已带"第N集"前缀,避免重复
- if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
- $episodeTitle = $episodeTitleRaw;
- } else {
- $episodeTitle .= ':' . $episodeTitleRaw;
- }
- }
- $this->pdfSubTitle($pdf, $episodeTitle, 13);
- $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
- if (getProp($episodeScript, 'narrator_voice') !== '') {
- $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
- }
- foreach (getProp($episodeScript, 'acts', []) as $act) {
- $actTitle = '片段' . getProp($act, 'act_number');
- if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
- $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
- }
- $this->pdfSubTitle($pdf, $actTitle, 12);
- if (getProp($act, 'content') !== '') {
- $this->pdfBody($pdf, getProp($act, 'content'));
- }
- }
- }
- return $pdf;
- }
- /**
- * PDF章节标题(带分隔线)
- */
- private function pdfSectionTitle($pdf, $title) {
- if ($pdf->GetY() > 230) {
- $pdf->AddPage();
- }
- $pdf->SetFont('simsun', 'B', 15);
- $pdf->Cell(0, 10, $title, 0, 1, 'L');
- $y = $pdf->GetY();
- $pdf->SetLineWidth(0.4);
- $pdf->Line(15, $y, 195, $y);
- $pdf->Ln(4);
- }
- /**
- * PDF子标题(集数/片段标题)
- */
- private function pdfSubTitle($pdf, $title, $size = 13) {
- if ($pdf->GetY() > 240) {
- $pdf->AddPage();
- }
- $pdf->SetFont('simsun', 'B', $size);
- $pdf->Cell(0, 8, $title, 0, 1, 'L');
- $pdf->Ln(1);
- }
- /**
- * PDF正文段落
- */
- private function pdfBody($pdf, $text) {
- $pdf->SetFont('simsun', '', 11);
- $pdf->MultiCell(0, 6, $text, 0, 'L');
- $pdf->Ln(2);
- }
- /**
- * 输出列表项图片(每张图单独一页,图下标注名称)
- * @param \TCPDF $pdf
- * @param array $items 列表项
- * @param string $nameKey role|scene|prop
- * @param array $imageCache 图片缓存(url => 临时文件路径)
- */
- private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
- foreach ($items as $item) {
- $url = trim((string)getProp($item, 'url', ''));
- $name = trim((string)getProp($item, $nameKey, ''));
- if ($url === '' || !isset($imageCache[$url])) continue;
- $imgPath = $imageCache[$url];
- $size = @getimagesize($imgPath);
- if (!$size || $size[0] <= 0 || $size[1] <= 0) {
- continue;
- }
- $pdf->AddPage();
- // 图片按比例缩放,居中偏上,为底部名称标注预留空间
- $maxW = 160;
- $maxH = 170;
- $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
- $drawW = $size[0] * $ratio;
- $drawH = $size[1] * $ratio;
- $x = (210 - $drawW) / 2;
- $y = max(15, (297 - $drawH) / 2 - 10);
- $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
- // 图下标注名称
- $pdf->SetFont('simsun', 'B', 13);
- $pdf->SetY(297 - 28);
- $pdf->Cell(0, 8, $name, 0, 1, 'C');
- }
- }
- /**
- * 并发下载远程图片到临时文件,并统一缩放转为JPEG
- * @param array $items 包含url字段的列表项
- * @return array url => 临时文件路径
- */
- private function downloadImagesConcurrently(array $items) {
- // 收集唯一的图片URL
- $urls = [];
- foreach ($items as $item) {
- $url = trim((string)getProp($item, 'url', ''));
- if ($url !== '') $urls[$url] = true;
- }
- if (!$urls) return [];
- $urls = array_keys($urls);
- $tmpDir = sys_get_temp_dir();
- $rawFiles = [];
- foreach ($urls as $url) {
- $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
- $rawFiles[$url] = $rawFile;
- }
- $client = new Client(['timeout' => 180, 'verify' => false]);
- // 低并发下载,sink写入文件避免大图占用内存
- $generator = (function () use ($urls, $client, $rawFiles) {
- foreach ($urls as $url) {
- yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
- }
- })();
- $errors = [];
- $each = new \GuzzleHttp\Promise\EachPromise($generator, [
- 'concurrency' => 4,
- 'rejected' => function ($reason, $url) use (&$errors) {
- $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
- },
- ]);
- $each->promise()->wait();
- // 失败的图片串行重试一次(独占带宽,提高成功率)
- foreach ($urls as $url) {
- if (!isset($errors[$url])) continue;
- try {
- $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
- unset($errors[$url]);
- } catch (\Throwable $e) {
- // 重试仍失败
- }
- }
- $cache = [];
- foreach ($urls as $url) {
- $rawFile = $rawFiles[$url];
- if (isset($errors[$url])) {
- dLog('anime')->error('导出PDF图片下载失败', [
- 'url' => $url,
- 'error' => $errors[$url],
- ]);
- @unlink($rawFile);
- continue;
- }
- $converted = $this->convertImageFile($rawFile, $url);
- if ($converted !== null) {
- $cache[$url] = $converted;
- } else {
- @unlink($rawFile);
- }
- }
- return $cache;
- }
- /**
- * 将已下载的图片文件缩放并转为JPEG
- * @param string $rawFile 原始图片临时文件
- * @param string $url 图片地址(用于命名)
- * @return string|null 转换后的文件路径,转换失败返回null
- */
- private function convertImageFile($rawFile, $url) {
- $content = @file_get_contents($rawFile);
- if ($content === false || $content === '') return null;
- if (!function_exists('imagecreatefromstring')) return null;
- $image = @imagecreatefromstring($content);
- if ($image === false) return null;
- $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
- imagedestroy($image);
- if ($jpeg !== null) {
- @unlink($rawFile);
- }
- return $jpeg;
- }
- /**
- * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
- * @param resource $srcImage GD图片资源
- * @param string $rawFile 原始图片临时文件
- * @param string $url 图片地址(用于命名)
- * @return string|null 压缩后的JPEG文件路径
- */
- private function compressImageForPdf($srcImage, $rawFile, $url) {
- $maxBytes = 2 * 1024 * 1024; // 2MB
- $sizes = [2048, 1600, 1280, 1024, 800];
- $qualities = [85, 70, 55, 40];
- $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
- foreach ($sizes as $size) {
- $resized = $this->copyAndResize($srcImage, $size);
- $flat = $this->flattenToWhite($resized);
- imagedestroy($resized);
- foreach ($qualities as $quality) {
- ob_start();
- $saved = imagejpeg($flat, null, $quality);
- $data = ob_get_clean();
- if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
- file_put_contents($jpeg, $data);
- imagedestroy($flat);
- dLog('anime')->info('导出PDF图片压缩完成', [
- 'url' => $url,
- 'size' => filesize($jpeg),
- 'edge' => $size,
- 'quality' => $quality,
- ]);
- return $jpeg;
- }
- }
- imagedestroy($flat);
- }
- // 兜底:最小尺寸、最低质量强制输出
- $resized = $this->copyAndResize($srcImage, 800);
- $flat = $this->flattenToWhite($resized);
- imagedestroy($resized);
- $saved = imagejpeg($flat, $jpeg, 30);
- imagedestroy($flat);
- if (!$saved) return null;
- dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
- 'url' => $url,
- 'size' => filesize($jpeg),
- ]);
- return $jpeg;
- }
- /**
- * 等比缩放图片副本(不销毁原图)
- * @param resource $srcImage GD图片资源
- * @param int $maxEdge 最大边长
- * @return resource
- */
- private function copyAndResize($srcImage, $maxEdge) {
- $width = imagesx($srcImage);
- $height = imagesy($srcImage);
- $max = max($width, $height);
- if ($max <= $maxEdge) {
- $copy = imagecreatetruecolor($width, $height);
- imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
- return $copy;
- }
- $ratio = $maxEdge / $max;
- $newWidth = max(1, (int)round($width * $ratio));
- $newHeight = max(1, (int)round($height * $ratio));
- $resized = imagecreatetruecolor($newWidth, $newHeight);
- imagealphablending($resized, false);
- imagesavealpha($resized, true);
- imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
- return $resized;
- }
- /**
- * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
- * @param resource $image GD图片资源
- * @return resource
- */
- private function flattenToWhite($image) {
- $width = imagesx($image);
- $height = imagesy($image);
- $flat = imagecreatetruecolor($width, $height);
- $white = imagecolorallocate($flat, 255, 255, 255);
- imagefill($flat, 0, 0, $white);
- imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
- return $flat;
- }
- /**
- * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
- * @param string $content 片段内容
- * @param int $counter 当前已编号数量(引用传递,整集累计)
- * @return string
- */
- private function renumberSegmentBlocks($content, &$counter) {
- return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
- $counter++;
- return '【' . $match[1] . $counter . '】';
- }, $content);
- }
- }
|