AnimeService.php 377 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Services\AIGeneration\AIImageGenerationService;
  9. use App\Services\AIGeneration\AIVideoGenerationService;
  10. use App\Services\DeepSeek\DeepSeekService;
  11. use App\Services\PointsService;
  12. use Dflydev\DotAccessData\Util;
  13. use GuzzleHttp\Client;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Log;
  16. use Illuminate\Support\Facades\Redis;
  17. use OSS\Core\OssException;
  18. use OSS\OssClient;
  19. class AnimeService
  20. {
  21. protected $aiImageGenerationService;
  22. protected $aiVideoGenerationService;
  23. protected $DeepSeekService;
  24. protected $pointsService;
  25. private $url;
  26. private $api_key;
  27. private $headers;
  28. public function __construct(
  29. AIImageGenerationService $aiImageGenerationService,
  30. AIVideoGenerationService $aiVideoGenerationService,
  31. DeepSeekService $DeepSeekService,
  32. PointsService $pointsService
  33. ) {
  34. $this->aiImageGenerationService = $aiImageGenerationService;
  35. $this->aiVideoGenerationService = $aiVideoGenerationService;
  36. $this->DeepSeekService = $DeepSeekService;
  37. $this->pointsService = $pointsService;
  38. $this->url = 'https://api.deepseek.com/chat/completions';
  39. $this->api_key = env('DEEPSEEK_API_KEY');
  40. $this->headers = [
  41. 'Authorization' => 'Bearer '.$this->api_key,
  42. 'Content-Type' => 'application/json; charset=UTF-8'
  43. ];
  44. }
  45. /**
  46. * 构建统一的分镜数据结构(episodeInfo格式)
  47. * @param array $segments 分镜数据数组
  48. * @return array 返回包含acts和total_duration的数组
  49. */
  50. public function buildEpisodeSegmentsStructure($segments) {
  51. $acts = [];
  52. $totalDuration = 0; // 初始化总时长
  53. foreach($segments as $segment) {
  54. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  55. $videoDuration = getProp($segment, 'video_duration');
  56. $audioDuration = getProp($segment, 'audio_duration');
  57. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  58. $totalDuration += floatval($videoDuration);
  59. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  60. $totalDuration += floatval($audioDuration);
  61. } else {
  62. $totalDuration += 5; // 默认5秒
  63. }
  64. $segment_content = getProp($segment, 'segment_content');
  65. // 判断是否有尾帧描述,如果有则去掉这部分内容
  66. if (strpos($segment_content, '尾帧') !== false) {
  67. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  68. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  69. }
  70. // 构建分镜信息
  71. $segmentInfo = [
  72. 'segment_id' => getProp($segment, 'segment_id'),
  73. 'segment_number' => getProp($segment, 'segment_number'),
  74. 'segment_content' => $segment_content,
  75. 'description' => getProp($segment, 'description'),
  76. 'composition' => getProp($segment, 'composition'),
  77. 'camera_movement' => getProp($segment, 'camera_movement'),
  78. 'voice_actor' => getProp($segment, 'voice_actor'),
  79. 'dialogue' => getProp($segment, 'dialogue'),
  80. 'frame_type' => getProp($segment, 'frame_type'),
  81. 'scene' => getProp($segment, 'scene'),
  82. 'characters' => getProp($segment, 'characters'),
  83. 'tail_frame' => getProp($segment, 'tail_frame'),
  84. 'emotion' => getProp($segment, 'emotion'),
  85. 'emotion_type' => getProp($segment, 'emotion_type'),
  86. 'gender' => getProp($segment, 'gender'),
  87. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  88. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  89. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  90. 'pitch' => getProp($segment, 'pitch'),
  91. 'voice_name' => getProp($segment, 'voice_name'),
  92. 'voice_type' => getProp($segment, 'voice_type'),
  93. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  94. 'img_url' => getProp($segment, 'img_url'),
  95. 'audio_url' => getProp($segment, 'audio_url'),
  96. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  97. 'video_url' => getProp($segment, 'video_url'),
  98. 'video_duration' => getProp($segment, 'video_duration', 0),
  99. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  100. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  101. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  102. 'current_type' => getProp($segment, 'current_type'),
  103. ];
  104. $actNumber = getProp($segment, 'act_number');
  105. if (isset($acts[$actNumber])) {
  106. $acts[$actNumber]['segments'][] = $segmentInfo;
  107. } else {
  108. $acts[$actNumber] = [
  109. 'act_number' => $actNumber,
  110. 'act_title' => getProp($segment, 'act_title'),
  111. 'act_duration' => getProp($segment, 'act_duration'),
  112. 'segments' => [$segmentInfo]
  113. ];
  114. }
  115. }
  116. return [
  117. 'acts' => array_values($acts),
  118. 'total_duration' => intval(round($totalDuration))
  119. ];
  120. }
  121. /**
  122. * 构建统一的分段数据结构(episodeInfoForAce格式)
  123. * @param array $segments 分段数据数组
  124. * @return array 返回包含acts和total_duration的数组
  125. */
  126. public function buildEpisodeActsStructureForAce($segments) {
  127. $acts = [];
  128. $totalDuration = 0; // 初始化总时长
  129. foreach($segments as $segment) {
  130. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  131. $videoDuration = getProp($segment, 'video_duration');
  132. $actDuration = getProp($segment, 'act_duration');
  133. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  134. $totalDuration += floatval($videoDuration);
  135. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  136. $totalDuration += floatval($actDuration);
  137. } else {
  138. $totalDuration += 5; // 默认5秒
  139. }
  140. // 构建分镜信息
  141. $segmentInfo = [
  142. 'act_id' => getProp($segment, 'id'),
  143. 'act_number' => getProp($segment, 'act_number'),
  144. 'act_title' => getProp($segment, 'act_title'),
  145. 'act_duration' => getProp($segment, 'act_duration'),
  146. 'act_content' => getProp($segment, 'act_content'),
  147. 'video_url' => getProp($segment, 'video_url'),
  148. 'video_duration' => getProp($segment, 'video_duration', 0),
  149. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  150. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  151. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  152. 'current_type' => getProp($segment, 'current_type'),
  153. ];
  154. $acts[] = $segmentInfo;
  155. }
  156. return [
  157. 'acts' => array_values($acts),
  158. 'total_duration' => intval(round($totalDuration))
  159. ];
  160. }
  161. /**
  162. * 验证画面比例是否有效
  163. * @param string $ratio 画面比例
  164. * @return bool
  165. */
  166. public function validateRatio($ratio) {
  167. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  168. }
  169. /**
  170. * 获取画面比例对应的宽高
  171. * @param string $ratio 画面比例
  172. * @return array ['width' => int, 'height' => int]
  173. * @throws \Exception
  174. */
  175. private function getRatioDimensions($ratio) {
  176. if ($ratio && !$this->validateRatio($ratio)) {
  177. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  178. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  179. }
  180. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  181. }
  182. public function createAnime($data) {
  183. $uid = Site::getUid();
  184. $input_art_style = getProp($data, 'art_style');
  185. $file = getProp($data, 'file');
  186. $content = getProp($data, 'content', '');
  187. $bid = getProp($data, 'bid', 0);
  188. $script_id = getProp($data, 'script_id', 0);
  189. $ace_mode = getProp($data, 'ace_mode', 0);
  190. $extra_products = getProp($data, 'products', []);
  191. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  192. if (!is_array($extra_products)) {
  193. Utils::throwError('20003:传入的资产格式不正确');
  194. }
  195. // 替换美术风格
  196. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  197. // 提取文件内容
  198. if ($file) {
  199. $content = $this->DeepSeekService->extractFileContent($file);
  200. if (!$content) {
  201. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  202. }
  203. } elseif ($script_id) {
  204. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  205. if (!$content) {
  206. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  207. }
  208. } elseif ($bid) {
  209. $content = $this->DeepSeekService->getContentByBid($bid);
  210. if (!$content) {
  211. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  212. }
  213. } elseif ($content) {
  214. $content = filterContent($content);
  215. }else {
  216. $content = '';
  217. }
  218. $anime_data = [
  219. 'user_id' => $uid,
  220. 'anime_name' => '新剧本策划',
  221. 'is_multi' => getProp($data, 'is_multi', 1),
  222. 'content' => $content,
  223. 'art_style_type' => $input_art_style,
  224. 'ace_mode' => $ace_mode,
  225. 'script_id' => $script_id,
  226. 'extra_products' => json_encode($extra_products, 256),
  227. 'created_at' => date('Y-m-d H:i:s'),
  228. 'updated_at' => date('Y-m-d H:i:s'),
  229. ];
  230. // 处理文本模型
  231. $model = getProp($data, 'model');
  232. if (!$model) {
  233. // 用户没有输入,使用默认值
  234. $model = 'deepseek-v4-pro';
  235. }
  236. // 验证模型是否在可用模型表中
  237. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  238. $model = 'deepseek-v4-pro';
  239. }
  240. $anime_data['model'] = $model;
  241. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  242. return DB::table('mp_animes')->insertGetId($anime_data);
  243. }
  244. public function chatList($data) {
  245. $uid = Site::getUid();
  246. $anime_name = getProp($data, 'anime_name');
  247. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  248. if ($anime_name) {
  249. $query->where('anime_name', 'like', "%$anime_name%");
  250. }
  251. return $query->orderBy('id', 'desc')->paginate();
  252. }
  253. public function chatHistory($data) {
  254. $anime_id = getProp($data, 'anime_id');
  255. $sequence = getProp($data, 'sequence', 0);
  256. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  257. $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)
  258. ->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');
  259. return $query->orderBy('ar.id')->get()->map(function ($value) {
  260. $value = (array)$value;
  261. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  262. $value['created_at'] = transDate($value['created_at']);
  263. $value['episode_created_at'] = transDate($value['episode_created_at']);
  264. return $value;
  265. })->toArray();
  266. }
  267. public function batchSetRoleImg($data) {
  268. $episode_id = getProp($data, 'episode_id');
  269. if (!$episode_id) Utils::throwError('1002:请选择分集');
  270. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  271. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  272. $art_style = getProp($episode, 'art_style');
  273. $anime_id = getProp($episode, 'anime_id');
  274. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  275. $art_style_type = getProp($anime, 'art_style_type');
  276. $character_prefix = '';
  277. $scene_prefix = '';
  278. if ($art_style_type) {
  279. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  280. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  281. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  282. }
  283. foreach ($roles as &$role) {
  284. $role_name = getProp($role, 'role');
  285. if ($role_name == '旁白') continue;
  286. // 优先使用 pic_prompt,如果没有则使用 description
  287. $pic_prompt = getProp($role, 'pic_prompt');
  288. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  289. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  290. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  291. // 参考图地址
  292. $ref_img_url = getProp($role, 'url');
  293. if ($ref_img_url) continue; // 已有图片则跳过
  294. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  295. try {
  296. $params = [
  297. 'prompt' => $description,
  298. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  299. ];
  300. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  301. $task_id = $task->id;
  302. if (!$task_id) {
  303. Utils::throwError("20003:角色({$role_name})生成图片失败");
  304. }
  305. $role['task_id'] = $task_id;
  306. $role['task_status'] = 'processing';
  307. } catch (\Exception $e) {
  308. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  309. Utils::throwError("20003:" . $e->getMessage());
  310. }
  311. }
  312. // 保存角色信息
  313. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  314. 'roles' => json_encode($roles, 256),
  315. 'generate_status' => '执行中',
  316. 'generate_at' => date('Y-m-d H:i:s'),
  317. 'updated_at' => date('Y-m-d H:i:s')
  318. ]);
  319. if (!$boolen) {
  320. Utils::throwError('20003:保存角色信息失败');
  321. }
  322. return $boolen;
  323. }
  324. public function batchSetSceneImg($data) {
  325. $episode_id = getProp($data, 'episode_id');
  326. if (!$episode_id) Utils::throwError('1002:请选择分集');
  327. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  328. $scenes = json_decode(getProp($episode, 'scenes'), true);
  329. $art_style = getProp($episode, 'art_style');
  330. $target_scene = getProp($data, 'target_scene');
  331. $anime_id = getProp($episode, 'anime_id');
  332. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  333. $art_style_type = getProp($anime, 'art_style_type');
  334. $character_prefix = '';
  335. $scene_prefix = '';
  336. if ($art_style_type) {
  337. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  338. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  339. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  340. }
  341. foreach ($scenes as &$scene) {
  342. $scene_name = getProp($scene, 'scene');
  343. if ($scene_name != $target_scene) continue;
  344. // 优先使用 pic_prompt,如果没有则使用 description
  345. $pic_prompt = getProp($scene, 'pic_prompt');
  346. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  347. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  348. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  349. // 参考图地址
  350. $ref_img_url = getProp($scene, 'url');
  351. if ($ref_img_url) continue; // 已有图片则跳过
  352. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  353. try {
  354. $params = [
  355. 'prompt' => $description,
  356. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  357. ];
  358. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  359. $task_id = $task->id;
  360. if (!$task_id) {
  361. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  362. }
  363. $scene['task_id'] = $task_id;
  364. $scene['task_status'] = 'processing';
  365. } catch (\Exception $e) {
  366. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  367. Utils::throwError("20003:" . $e->getMessage());
  368. }
  369. }
  370. // 保存场景信息
  371. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  372. 'scenes' => json_encode($scenes, 256),
  373. 'generate_status' => '执行中',
  374. 'generate_at' => date('Y-m-d H:i:s'),
  375. 'updated_at' => date('Y-m-d H:i:s')
  376. ]);
  377. if (!$boolen) {
  378. Utils::throwError('20003:保存角色信息失败');
  379. }
  380. return $boolen;
  381. }
  382. public function editAnime($data) {
  383. $anime_id = getProp($data, 'anime_id');
  384. $anime_name = trim(getProp($data, 'anime_name'));
  385. // 确认对话名称唯一性
  386. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  387. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  388. }
  389. if (!$anime_id || !$anime_name) {
  390. Utils::throwError('20003:参数异常');
  391. }
  392. return DB::table('mp_animes')->where('id', $anime_id)->update([
  393. 'anime_name' => $anime_name,
  394. 'updated_at' => date('Y-m-d H:i:s')
  395. ]);
  396. // $script_arr =getProp($data, 'script', []);
  397. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  398. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  399. // $anime_id = getProp($data, 'anime_id');
  400. // try {
  401. // DB::beginTransaction();
  402. // $table_data = [
  403. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  404. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  405. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  406. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  407. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  408. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  409. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  410. // 'status' => 3,
  411. // 'start_episode_sequence' => $start_episode_sequence,
  412. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  413. // 'episode_num' => count($script_arr['episodes']),
  414. // 'updated_at' => date('Y-m-d H:i:s')
  415. // ];
  416. // // 保存剧本内容
  417. // if (!empty($anime_id)) {
  418. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  419. // if (!$boolen) {
  420. // dLog('anime')->info('对话保存失败', $table_data);
  421. // Utils::throwError('20003:对话保存失败');
  422. // }
  423. // }else {
  424. // $table['created_at'] = $table_data['updated_at'];
  425. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  426. // if (!$anime_id) {
  427. // dLog('anime')->info('对话保存失败', $table_data);
  428. // Utils::throwError('20003:对话保存失败');
  429. // }
  430. // }
  431. // // 保存分集内容
  432. // // 删除历史分集内容
  433. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  434. // $episodes = [];
  435. // $sequence = 1;
  436. // foreach ($script_arr['episodes'] as $episode) {
  437. // $segment_number = 1;
  438. // foreach($episode['segments'] as $segment) {
  439. // $episodes[] = [
  440. // 'anime_id' => $anime_id,
  441. // 'episode_number' => $episode['episode_number'],
  442. // 'title' => $episode['title'],
  443. // // 'content' => $episode['content'],
  444. // 'content' => '',
  445. // 'segment_number' => $segment_number,
  446. // 'segment_content' => $segment['segment_content'],
  447. // 'sequence' => $sequence,
  448. // 'created_at' => date('Y-m-d H:i:s'),
  449. // 'updated_at' => date('Y-m-d H:i:s')
  450. // ];
  451. // $sequence++;
  452. // $segment_number++;
  453. // }
  454. // }
  455. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  456. // if (!$boolen2) {
  457. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  458. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  459. // Utils::throwError('20003:分集内容保存失败');
  460. // }
  461. // } catch (\Exception $e) {
  462. // DB::rollBack();
  463. // Utils::throwError('20003:'.$e->getMessage());
  464. // }
  465. // DB::commit();
  466. // return true;
  467. }
  468. public function delAnime($data) {
  469. $anime_id = getProp($data, 'anime_id');
  470. if (!$anime_id) {
  471. Utils::throwError('20003:请选择剧本');
  472. }
  473. return DB::table('mp_animes')->where('id', $anime_id)->update([
  474. 'is_deleted' => 1,
  475. 'updated_at' => date('Y-m-d H:i:s')
  476. ]);
  477. }
  478. public function animeDetail($data) {
  479. $uid = Site::getUid();
  480. $anime_id = getProp($data, 'anime_id');
  481. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  482. ->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();
  483. if (!$anime) Utils::throwError('20003:权限不足');
  484. $anime = (array)$anime;
  485. $anime['roles'] = json_decode($anime['roles']);
  486. $anime['scenes'] = json_decode($anime['scenes']);
  487. // 获取分集信息
  488. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  489. ->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"))
  490. ->orderBy('episode_number')->get()->map(function ($value) {
  491. return (array)$value;
  492. })->toArray();
  493. $anime['episodes'] = $episodes;
  494. return $anime;
  495. }
  496. public function episodeInfo($data) {
  497. $uid = Site::getUid();
  498. $anime_id = getProp($data, 'anime_id');
  499. $episode_id = getProp($data, 'episode_id');
  500. if (!$anime_id || !$episode_id) {
  501. Utils::throwError('1002:请选择剧集');
  502. }
  503. // 验证用户权限
  504. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  505. if (!$anime) Utils::throwError('20003:权限不足');
  506. $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();
  507. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  508. $episode = (array)$episode;
  509. $episode['roles'] = json_decode($episode['roles'], true);
  510. // foreach($episode['roles'] as &$item) {
  511. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  512. // }
  513. $episode['scenes'] = json_decode($episode['scenes'], true);
  514. // foreach($episode['scenes'] as &$item) {
  515. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  516. // }
  517. // 获取分镜信息
  518. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  519. ->select('*')->get()->map(function ($value) {
  520. return (array)$value;
  521. })->toArray();
  522. // 使用公共方法构建分镜结构
  523. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  524. $episode['acts'] = $segmentsStructure['acts'];
  525. $episode['total_duration'] = $segmentsStructure['total_duration'];
  526. return $episode;
  527. }
  528. public function episodeInfoForAce($data) {
  529. $anime_id = getProp($data, 'anime_id');
  530. $episode_id = getProp($data, 'episode_id');
  531. if (!$anime_id || !$episode_id) {
  532. Utils::throwError('1002:请选择剧集');
  533. }
  534. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'props', 'is_generated')->first();
  535. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  536. $episode = (array)$episode;
  537. $episode['roles'] = json_decode($episode['roles'], true);
  538. // foreach($episode['roles'] as &$item) {
  539. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  540. // }
  541. $episode['scenes'] = json_decode($episode['scenes'], true);
  542. // foreach($episode['scenes'] as &$item) {
  543. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  544. // }
  545. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  546. // 获取分镜信息
  547. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  548. ->select('*')->get()->map(function ($value) {
  549. return (array)$value;
  550. })->toArray();
  551. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  552. $episode['acts'] = $segmentsStructure['acts'];
  553. $episode['total_duration'] = $segmentsStructure['total_duration'];
  554. return $episode;
  555. }
  556. public function segmentInfo($data) {
  557. $uid = Site::getUid();
  558. $segment_id = getProp($data, 'segment_id');
  559. if (!$segment_id) {
  560. Utils::throwError('1002:请选择分镜');
  561. }
  562. // 获取分镜信息
  563. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  564. // 验证用户权限
  565. if ($segment) {
  566. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  567. if (!$anime) Utils::throwError('20003:权限不足');
  568. }
  569. $result = [
  570. 'segment_id' => getProp($segment, 'segment_id'),
  571. 'segment_number' => getProp($segment, 'segment_number'),
  572. 'segment_content' => getProp($segment, 'segment_content'),
  573. 'description' => getProp($segment, 'description'),
  574. 'composition' => getProp($segment, 'composition'),
  575. 'camera_movement' => getProp($segment, 'camera_movement'),
  576. 'voice_actor' => getProp($segment, 'voice_actor'),
  577. 'dialogue' => getProp($segment, 'dialogue'),
  578. 'frame_type' => getProp($segment, 'frame_type'),
  579. 'scene' => getProp($segment, 'scene'),
  580. 'characters' => getProp($segment, 'characters'),
  581. 'tail_frame' => getProp($segment, 'tail_frame'),
  582. 'emotion' => getProp($segment, 'emotion'),
  583. 'emotion_type' => getProp($segment, 'emotion_type'),
  584. 'gender' => getProp($segment, 'gender'),
  585. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  586. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  587. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  588. 'pitch' => getProp($segment, 'pitch'),
  589. 'voice_name' => getProp($segment, 'voice_name'),
  590. 'voice_type' => getProp($segment, 'voice_type'),
  591. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  592. 'img_url' => getProp($segment, 'img_url'),
  593. 'video_url' => getProp($segment, 'video_url'),
  594. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  595. ];
  596. return $result;
  597. }
  598. public function copyEpisodeVersion($data) {
  599. $episode_id = getProp($data, 'episode_id');
  600. $uid = Site::getUid();
  601. $cpid = Site::getCpid();
  602. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  603. if (!$episode) Utils::throwError('20003:该剧集不存在');
  604. $episode = (array)$episode;
  605. $anime_id = $episode['anime_id'];
  606. $episode_number = $episode['episode_number'];
  607. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  608. $sequence = $count + 1;
  609. unset($episode['id']);
  610. $now = date('Y-m-d H:i:s');
  611. $episode['created_at'] = $now;
  612. $episode['updated_at'] = $now;
  613. $episode['is_default'] = 1;
  614. // 获取版本中含有"(副本"字样的个数
  615. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  616. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  617. $episode['sequence'] = $sequence;
  618. $episode['is_generated'] = 0;
  619. $episode['cpid'] = $cpid;
  620. // 获取ace_mode
  621. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  622. try {
  623. DB::beginTransaction();
  624. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  625. // 新增副本
  626. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  627. if (!$new_episode_id) {
  628. Utils::throwError('20003:创建副本失败!');
  629. }
  630. // 获取分镜数据并准备插入
  631. $segments_for_insert = DB::table('mp_episode_segments')
  632. ->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')
  633. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  634. $item = (array)$item;
  635. $item['episode_id'] = $new_episode_id;
  636. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  637. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  638. return $item;
  639. })->toArray();
  640. // 写入分镜数据
  641. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  642. if (!$boolen2) {
  643. Utils::throwError('20003:写入分镜数据失败!');
  644. }
  645. // 写入对话历史
  646. $records = [
  647. [
  648. 'uid' => $uid,
  649. 'anime_id' => $anime_id,
  650. 'role' => 'user',
  651. 'content' => '创建副本',
  652. 'sequence' => $episode_number,
  653. 'episode_id' => $new_episode_id,
  654. 'created_at' => $now,
  655. 'updated_at' => $now
  656. ],
  657. [
  658. 'uid' => $uid,
  659. 'anime_id' => $anime_id,
  660. 'role' => 'assistant',
  661. 'content' => '好的,已为您创建副本',
  662. 'sequence' => $episode_number,
  663. 'episode_id' => $new_episode_id,
  664. 'created_at' => $now,
  665. 'updated_at' => $now
  666. ]
  667. ];
  668. $boolen3 = DB::table('mp_anime_records')->insert($records);
  669. if (!$boolen3) {
  670. Utils::throwError('20003:对话记录保存失败');
  671. }
  672. }catch (\Exception $e) {
  673. DB::rollBack();
  674. Utils::throwError('20003:'.$e->getMessage());
  675. }
  676. DB::commit();
  677. // 构建与 episodeInfo 方法一致的返回数据结构
  678. $result = [
  679. 'episode_id' => $new_episode_id,
  680. 'anime_id' => $anime_id,
  681. 'episode_number' => $episode_number,
  682. 'title' => $episode['title'],
  683. 'intro' => $episode['intro'],
  684. 'art_style' => $episode['art_style'],
  685. 'roles' => json_decode($episode['roles'], true),
  686. 'scenes' => json_decode($episode['scenes'], true),
  687. 'is_generated' => (int)$episode['is_generated']
  688. ];
  689. if ((int)$ace_mode === 1) {
  690. // 获取分镜信息
  691. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  692. ->select('*')->get()->map(function ($value) {
  693. return (array)$value;
  694. })->toArray();
  695. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  696. }else {
  697. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  698. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  699. }
  700. $result['acts'] = $segmentsStructure['acts'];
  701. $result['total_duration'] = $segmentsStructure['total_duration'];
  702. return $result;
  703. }
  704. public function episodeVersions($data) {
  705. $anime_id = getProp($data, 'anime_id');
  706. $episode_id = getProp($data, 'episode_id');
  707. if (!$anime_id || !$episode_id) {
  708. Utils::throwError('1002:请选择剧集');
  709. }
  710. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  711. $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) {
  712. return (array)$value;
  713. })->toArray();
  714. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  715. foreach($episodes as &$episode) {
  716. $episode['version'] = 'V'.$episode['sequence'];
  717. $episode['roles'] = json_decode($episode['roles'], true);
  718. $episode['scenes'] = json_decode($episode['scenes'], true);
  719. // 获取分镜信息
  720. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  721. ->select('*')->get()->map(function ($value) {
  722. return (array)$value;
  723. })->toArray();
  724. // 使用公共方法构建分镜结构
  725. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  726. $episode['acts'] = $segmentsStructure['acts'];
  727. $episode['total_duration'] = $segmentsStructure['total_duration'];
  728. }
  729. return $episodes;
  730. }
  731. public function bindEpisodeVersion($data) {
  732. $episode_id = getProp($data, 'episode_id');
  733. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  734. if (!$episode) Utils::throwError('20003:该剧集不存在');
  735. $episode = (array)$episode;
  736. if ((int)$episode['is_default'] === 1) return true;
  737. try {
  738. DB::beginTransaction();
  739. // 移除is_default标志
  740. $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')]);
  741. if (!$boolen) {
  742. Utils::throwError('20003:更新失败!');
  743. }
  744. // 绑定副本
  745. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  746. if (!$boolen2) {
  747. Utils::throwError('20003:绑定失败!');
  748. }
  749. }catch (\Exception $e) {
  750. DB::rollBack();
  751. Utils::throwError('20003:'.$e->getMessage());
  752. }
  753. DB::commit();
  754. return true;
  755. }
  756. public function chatChangeImg($data) {
  757. $segment_id = getProp($data, 'segment_id');
  758. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  759. $prompt = getProp($data, 'prompt');
  760. if (!$prompt || !$segment_id) {
  761. Utils::throwError('1002:请输入提示词,并且选择分镜');
  762. }
  763. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  764. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  765. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  766. else $ref_img_url = '';
  767. // $ref_img_url = '';
  768. if (empty($prompt)) {
  769. if (empty($ref_img_url)) {
  770. $prompt = getProp($segment, 'segment_content');
  771. }else {
  772. $prompt = '请根据图片生成';
  773. }
  774. }
  775. $anime_id = getProp($segment, 'anime_id');
  776. $episode_id = getProp($segment, 'episode_id');
  777. $episode_number = getProp($segment, 'episode_number');
  778. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  779. $ratio = getProp($data, 'ratio');
  780. if (!$ratio) {
  781. $ratio = getProp($episode, 'ratio');
  782. if (!$ratio) $ratio = '9:16';
  783. }
  784. $art_style = getProp($episode, 'art_style');
  785. if ($art_style) {
  786. $prompt = "美术风格:{$art_style}\n{$prompt}";
  787. }
  788. $dimensions = $this->getRatioDimensions($ratio);
  789. $width = $dimensions['width'];
  790. $height = $dimensions['height'];
  791. try {
  792. $params = [
  793. 'alias_segment_id' => $segment_id,
  794. 'prompt' => $prompt,
  795. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  796. 'width' => $width,
  797. 'height' => $height
  798. ];
  799. // 优化提示词(不要生成字幕)
  800. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  801. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  802. $task_id = $task->id;
  803. if (!$task_id) {
  804. Utils::throwError("20003:生成图片失败");
  805. }
  806. // 更新任务ID
  807. $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')]);
  808. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  809. } catch (\Exception $e) {
  810. Utils::throwError("20003:" . $e->getMessage());
  811. }
  812. // 创建任务之后先暂停10s等待异步任务完成
  813. sleep(10);
  814. $img_url = $this->loopGetPicTaskResult($task_id);
  815. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  816. // 图片生成后新增对话记录
  817. try {
  818. $uid = Site::getUid();
  819. $now = date('Y-m-d H:i:s');
  820. // 使用AI反推图片提示词
  821. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  822. // 保存对话记录
  823. $records = [
  824. [
  825. 'uid' => $uid,
  826. 'anime_id' => $anime_id,
  827. 'sequence' => $episode_number,
  828. 'role' => 'user',
  829. 'content' => $prompt,
  830. 'segment_id' => $segment_id,
  831. 'image_url' => '',
  832. 'created_at' => $now,
  833. 'updated_at' => $now
  834. ],
  835. [
  836. 'uid' => $uid,
  837. 'anime_id' => $anime_id,
  838. 'sequence' => $episode_number,
  839. 'role' => 'assistant',
  840. 'content' => $pic_prompt,
  841. 'segment_id' => $segment_id,
  842. 'image_url' => $img_url,
  843. 'created_at' => $now,
  844. 'updated_at' => $now
  845. ]
  846. ];
  847. DB::table('mp_anime_records')->insert($records);
  848. } catch (\Exception $e) {
  849. // 记录日志但不影响主流程
  850. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  851. 'segment_id' => $segment_id,
  852. 'img_url' => $img_url
  853. ]);
  854. logDB('anime', 'error', '保存对话记录失败', [
  855. 'segment_id' => $segment_id,
  856. 'img_url' => $img_url,
  857. 'error' => $e->getMessage()
  858. ]);
  859. }
  860. return $img_url;
  861. }
  862. public function segmentChatHistory($data) {
  863. $segment_id = getProp($data, 'segment_id');
  864. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  865. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
  866. $chat = $query->orderBy('id')->get()->map(function ($value) {
  867. $value = (array)$value;
  868. $value['created_at'] = transDate($value['created_at']);
  869. return $value;
  870. })->toArray();
  871. // 获取历史图片
  872. $url = [];
  873. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  874. foreach($pic_history as $task) {
  875. $result_url = getProp($task, 'result_url');
  876. if (is_json($result_url)) {
  877. $url = array_merge($url, json_decode($result_url, true));
  878. }else {
  879. $url[] = $result_url;
  880. }
  881. }
  882. // 获取历史视频
  883. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  884. foreach($video_history as $task) {
  885. $result_url = getProp($task, 'compressed_url');
  886. if (is_json($result_url)) {
  887. $url = array_merge($url, json_decode($result_url, true));
  888. }else {
  889. $url[] = $result_url;
  890. }
  891. }
  892. return compact('chat', 'url');
  893. }
  894. public function changeEpisodeRoles($data) {
  895. $anime_id = getProp($data, 'anime_id');
  896. $episode_id = getProp($data, 'episode_id');
  897. $target_roles = getProp($data, 'roles');
  898. $is_deleted = getProp($data, 'is_deleted', 0);
  899. // 参数验证
  900. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  901. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  902. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  903. // 验证剧集是否存在
  904. $episode = DB::table('mp_anime_episodes')
  905. ->where('anime_id', $anime_id)
  906. ->where('id', $episode_id)
  907. ->first();
  908. if (!$episode) Utils::throwError('20003:该剧集不存在');
  909. $roles = json_decode(getProp($episode, 'roles'), true);
  910. // 获取anime信息,检查是否有关联的script_id
  911. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  912. if (!$anime) Utils::throwError('20003:动漫不存在');
  913. $script_id = getProp($anime, 'script_id');
  914. $episode_number = getProp($episode, 'episode_number', 1);
  915. $uid = Site::getUid();
  916. $cpid = Site::getCpid();
  917. try {
  918. $target_role_name = getProp($target_roles, 'role');
  919. // 如果是删除操作
  920. if ($is_deleted == 1) {
  921. // 从角色列表中移除该角色
  922. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  923. return getProp($role, 'role') !== $target_role_name;
  924. }));
  925. // 更新角色列表
  926. $result = DB::table('mp_anime_episodes')
  927. ->where('anime_id', $anime_id)
  928. ->where('id', $episode_id)
  929. ->update([
  930. 'roles' => json_encode($roles, 256),
  931. 'updated_at' => date('Y-m-d H:i:s')
  932. ]);
  933. if ($result === false) {
  934. Utils::throwError('20003:删除角色失败');
  935. }
  936. } else {
  937. // 新增或更新操作
  938. $role_found = false;
  939. $is_new_role = false;
  940. // 查找并更新已存在的角色
  941. foreach($roles as &$role) {
  942. if (getProp($role, 'role') === $target_role_name) {
  943. $role = $target_roles;
  944. $role_found = true;
  945. break;
  946. }
  947. }
  948. // 如果角色不存在,则新增
  949. if (!$role_found) {
  950. $roles[] = $target_roles;
  951. $is_new_role = true;
  952. }
  953. // 更新角色列表
  954. $result = DB::table('mp_anime_episodes')
  955. ->where('anime_id', $anime_id)
  956. ->where('id', $episode_id)
  957. ->update([
  958. 'roles' => json_encode($roles, 256),
  959. 'updated_at' => date('Y-m-d H:i:s')
  960. ]);
  961. if ($result === false) {
  962. Utils::throwError('20003:更新角色列表失败');
  963. }
  964. // 同步更新分镜表中对应主体的音色信息
  965. $voice_name = getProp($target_roles, 'voice_name');
  966. $voice_type = getProp($target_roles, 'voice_type');
  967. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  968. DB::table('mp_episode_segments')
  969. ->where('anime_id', $anime_id)
  970. ->where('episode_id', $episode_id)
  971. ->where('voice_actor', $target_role_name)
  972. ->update([
  973. 'voice_name' => $voice_name,
  974. 'voice_type' => $voice_type,
  975. 'voice_audio_url' => $voice_audio_url,
  976. 'updated_at' => date('Y-m-d H:i:s')
  977. ]);
  978. // 如果有关联的script_id,则同步到mp_products表
  979. if ($script_id) {
  980. // 查询剧本信息
  981. $script = DB::table('mp_scripts')
  982. ->where('id', $script_id)
  983. ->where('is_deleted', 0)
  984. ->first();
  985. if ($script) {
  986. $script_name = $script->script_name ?? 'script_' . $script_id;
  987. $product_name = getProp($target_roles, 'role');
  988. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  989. $url = getProp($target_roles, 'url', '');
  990. $product_type = 1; // 1=角色
  991. // 查找或创建以script_name命名的文件夹
  992. $folder = DB::table('mp_products')
  993. ->where('cpid', $cpid)
  994. ->where('type', 2) // 文件夹类型
  995. ->where('product', $product_type) // 角色类型
  996. ->where('product_name', $script_name)
  997. ->where('parent_id', 0)
  998. ->where('is_deleted', 0)
  999. ->first();
  1000. if (!$folder) {
  1001. // 创建文件夹
  1002. $folder_id = DB::table('mp_products')->insertGetId([
  1003. 'user_id' => $uid,
  1004. 'cpid' => $cpid,
  1005. 'type' => 2, // 文件夹
  1006. 'product' => $product_type, // 角色类型
  1007. 'parent_id' => 0,
  1008. 'level' => 1,
  1009. 'product_name' => $script_name,
  1010. 'sort_order' => time(),
  1011. 'is_deleted' => 0,
  1012. 'created_at' => date('Y-m-d H:i:s'),
  1013. 'updated_at' => date('Y-m-d H:i:s')
  1014. ]);
  1015. } else {
  1016. $folder_id = $folder->id;
  1017. }
  1018. // 查找该文件夹下是否已存在同名资产
  1019. $existing_product = DB::table('mp_products')
  1020. ->where('cpid', $cpid)
  1021. ->where('type', 1) // 资产类型
  1022. ->where('product', $product_type)
  1023. ->where('parent_id', $folder_id)
  1024. ->where('product_name', $product_name)
  1025. ->where('is_deleted', 0)
  1026. ->first();
  1027. if ($existing_product) {
  1028. // 更新已存在的资产
  1029. $updateData = [
  1030. 'pic_task_status' => '生成成功',
  1031. ];
  1032. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1033. if ($url) $updateData['url'] = $url;
  1034. // 处理versions字段
  1035. $versions = getProp($target_roles, 'versions', []);
  1036. if ($versions && is_array($versions)) {
  1037. $updateData['versions'] = json_encode($versions, 256);
  1038. }
  1039. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1040. DB::table('mp_products')
  1041. ->where('id', $existing_product->id)
  1042. ->update($updateData);
  1043. $product_id = $existing_product->id;
  1044. } else {
  1045. // 创建新资产
  1046. $versions = getProp($target_roles, 'versions', []);
  1047. $product_id = DB::table('mp_products')->insertGetId([
  1048. 'user_id' => $uid,
  1049. 'cpid' => $cpid,
  1050. 'type' => 1, // 资产
  1051. 'product' => $product_type, // 角色
  1052. 'parent_id' => $folder_id,
  1053. 'level' => 2,
  1054. 'product_name' => $product_name,
  1055. 'url' => $url,
  1056. 'pic_prompt' => $pic_prompt,
  1057. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1058. 'sort_order' => time(),
  1059. 'is_deleted' => 0,
  1060. 'pic_task_status' => '生成成功',
  1061. 'created_at' => date('Y-m-d H:i:s'),
  1062. 'updated_at' => date('Y-m-d H:i:s')
  1063. ]);
  1064. }
  1065. // 建立或更新绑定关系
  1066. $existing_mapping = DB::table('mp_script_product_mappings')
  1067. ->where('script_id', $script_id)
  1068. ->where('product_id', $product_id)
  1069. ->where('episode_number', $episode_number)
  1070. ->first();
  1071. if (!$existing_mapping) {
  1072. // 创建绑定关系
  1073. DB::table('mp_script_product_mappings')->insert([
  1074. 'script_id' => $script_id,
  1075. 'product_id' => $product_id,
  1076. 'episode_number' => $episode_number,
  1077. 'created_at' => date('Y-m-d H:i:s'),
  1078. 'updated_at' => date('Y-m-d H:i:s')
  1079. ]);
  1080. }
  1081. }
  1082. }
  1083. }
  1084. } catch (\Exception $e) {
  1085. dLog('anime')->error('更新剧集角色失败', [
  1086. 'anime_id' => $anime_id,
  1087. 'episode_id' => $episode_id,
  1088. 'error' => $e->getMessage()
  1089. ]);
  1090. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1091. }
  1092. return true;
  1093. }
  1094. public function changeEpisodeScenes($data) {
  1095. $anime_id = getProp($data, 'anime_id');
  1096. $episode_id = getProp($data, 'episode_id');
  1097. $target_scenes = getProp($data, 'scenes');
  1098. $is_deleted = getProp($data, 'is_deleted', 0);
  1099. // 参数验证
  1100. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1101. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1102. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1103. // 验证剧集是否存在
  1104. $episode = DB::table('mp_anime_episodes')
  1105. ->where('anime_id', $anime_id)
  1106. ->where('id', $episode_id)
  1107. ->first();
  1108. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1109. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1110. // 获取anime信息,检查是否有关联的script_id
  1111. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1112. if (!$anime) Utils::throwError('20003:动漫不存在');
  1113. $script_id = getProp($anime, 'script_id');
  1114. $episode_number = getProp($episode, 'episode_number', 1);
  1115. $uid = Site::getUid();
  1116. $cpid = Site::getCpid();
  1117. try {
  1118. $target_scene_name = getProp($target_scenes, 'scene');
  1119. // 如果是删除操作
  1120. if ($is_deleted == 1) {
  1121. // 从场景列表中移除该场景
  1122. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1123. return getProp($scene, 'scene') !== $target_scene_name;
  1124. }));
  1125. // 更新场景列表
  1126. $result = DB::table('mp_anime_episodes')
  1127. ->where('anime_id', $anime_id)
  1128. ->where('id', $episode_id)
  1129. ->update([
  1130. 'scenes' => json_encode($scenes, 256),
  1131. 'updated_at' => date('Y-m-d H:i:s')
  1132. ]);
  1133. if ($result === false) {
  1134. Utils::throwError('20003:删除场景失败');
  1135. }
  1136. } else {
  1137. // 新增或更新操作
  1138. $scene_found = false;
  1139. $is_new_scene = false;
  1140. // 查找并更新已存在的场景
  1141. foreach($scenes as &$scene) {
  1142. if (getProp($scene, 'scene') === $target_scene_name) {
  1143. $scene = $target_scenes;
  1144. $scene_found = true;
  1145. break;
  1146. }
  1147. }
  1148. // 如果场景不存在,则新增
  1149. if (!$scene_found) {
  1150. $scenes[] = $target_scenes;
  1151. $is_new_scene = true;
  1152. }
  1153. // 更新场景列表
  1154. $result = DB::table('mp_anime_episodes')
  1155. ->where('anime_id', $anime_id)
  1156. ->where('id', $episode_id)
  1157. ->update([
  1158. 'scenes' => json_encode($scenes, 256),
  1159. 'updated_at' => date('Y-m-d H:i:s')
  1160. ]);
  1161. if ($result === false) {
  1162. Utils::throwError('20003:更新场景列表失败');
  1163. }
  1164. // 如果有关联的script_id,则同步到mp_products表
  1165. if ($script_id) {
  1166. // 查询剧本信息
  1167. $script = DB::table('mp_scripts')
  1168. ->where('id', $script_id)
  1169. ->where('is_deleted', 0)
  1170. ->first();
  1171. if ($script) {
  1172. $script_name = $script->script_name ?? 'script_' . $script_id;
  1173. $product_name = getProp($target_scenes, 'scene');
  1174. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1175. $url = getProp($target_scenes, 'url', '');
  1176. $product_type = 2; // 2=场景
  1177. // 查找或创建以script_name命名的文件夹
  1178. $folder = DB::table('mp_products')
  1179. ->where('cpid', $cpid)
  1180. ->where('type', 2) // 文件夹类型
  1181. ->where('product', $product_type) // 场景类型
  1182. ->where('product_name', $script_name)
  1183. ->where('parent_id', 0)
  1184. ->where('is_deleted', 0)
  1185. ->first();
  1186. if (!$folder) {
  1187. // 创建文件夹
  1188. $folder_id = DB::table('mp_products')->insertGetId([
  1189. 'user_id' => $uid,
  1190. 'cpid' => $cpid,
  1191. 'type' => 2, // 文件夹
  1192. 'product' => $product_type, // 场景类型
  1193. 'parent_id' => 0,
  1194. 'level' => 1,
  1195. 'product_name' => $script_name,
  1196. 'sort_order' => time(),
  1197. 'is_deleted' => 0,
  1198. 'created_at' => date('Y-m-d H:i:s'),
  1199. 'updated_at' => date('Y-m-d H:i:s')
  1200. ]);
  1201. } else {
  1202. $folder_id = $folder->id;
  1203. }
  1204. // 查找该文件夹下是否已存在同名资产
  1205. $existing_product = DB::table('mp_products')
  1206. ->where('cpid', $cpid)
  1207. ->where('type', 1) // 资产类型
  1208. ->where('product', $product_type)
  1209. ->where('parent_id', $folder_id)
  1210. ->where('product_name', $product_name)
  1211. ->where('is_deleted', 0)
  1212. ->first();
  1213. if ($existing_product) {
  1214. // 更新已存在的资产
  1215. $updateData = [
  1216. 'pic_task_status' => '生成成功'
  1217. ];
  1218. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1219. if ($url) $updateData['url'] = $url;
  1220. // 处理versions字段
  1221. $versions = getProp($target_scenes, 'versions', []);
  1222. if ($versions && is_array($versions)) {
  1223. $updateData['versions'] = json_encode($versions, 256);
  1224. }
  1225. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1226. DB::table('mp_products')
  1227. ->where('id', $existing_product->id)
  1228. ->update($updateData);
  1229. $product_id = $existing_product->id;
  1230. } else {
  1231. // 创建新资产
  1232. $versions = getProp($target_scenes, 'versions', []);
  1233. $product_id = DB::table('mp_products')->insertGetId([
  1234. 'user_id' => $uid,
  1235. 'cpid' => $cpid,
  1236. 'type' => 1, // 资产
  1237. 'product' => $product_type, // 场景
  1238. 'parent_id' => $folder_id,
  1239. 'level' => 2,
  1240. 'product_name' => $product_name,
  1241. 'url' => $url,
  1242. 'pic_prompt' => $pic_prompt,
  1243. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1244. 'sort_order' => time(),
  1245. 'is_deleted' => 0,
  1246. 'pic_task_status' => '生成成功',
  1247. 'created_at' => date('Y-m-d H:i:s'),
  1248. 'updated_at' => date('Y-m-d H:i:s')
  1249. ]);
  1250. }
  1251. // 建立或更新绑定关系
  1252. $existing_mapping = DB::table('mp_script_product_mappings')
  1253. ->where('script_id', $script_id)
  1254. ->where('product_id', $product_id)
  1255. ->where('episode_number', $episode_number)
  1256. ->first();
  1257. if (!$existing_mapping) {
  1258. // 创建绑定关系
  1259. DB::table('mp_script_product_mappings')->insert([
  1260. 'script_id' => $script_id,
  1261. 'product_id' => $product_id,
  1262. 'episode_number' => $episode_number,
  1263. 'created_at' => date('Y-m-d H:i:s'),
  1264. 'updated_at' => date('Y-m-d H:i:s')
  1265. ]);
  1266. }
  1267. }
  1268. }
  1269. }
  1270. } catch (\Exception $e) {
  1271. dLog('anime')->error('更新剧集场景失败', [
  1272. 'anime_id' => $anime_id,
  1273. 'episode_id' => $episode_id,
  1274. 'error' => $e->getMessage()
  1275. ]);
  1276. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1277. }
  1278. return true;
  1279. }
  1280. public function changeEpisodeProps($data) {
  1281. $anime_id = getProp($data, 'anime_id');
  1282. $episode_id = getProp($data, 'episode_id');
  1283. $target_props = getProp($data, 'props');
  1284. $is_deleted = getProp($data, 'is_deleted', 0);
  1285. // 参数验证
  1286. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1287. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1288. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1289. // 验证剧集是否存在
  1290. $episode = DB::table('mp_anime_episodes')
  1291. ->where('anime_id', $anime_id)
  1292. ->where('id', $episode_id)
  1293. ->first();
  1294. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1295. $props = json_decode(getProp($episode, 'props'), true);
  1296. // 获取anime信息,检查是否有关联的script_id
  1297. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1298. if (!$anime) Utils::throwError('20003:动漫不存在');
  1299. $script_id = getProp($anime, 'script_id');
  1300. $episode_number = getProp($episode, 'episode_number', 1);
  1301. $uid = Site::getUid();
  1302. $cpid = Site::getCpid();
  1303. try {
  1304. $target_prop_name = getProp($target_props, 'prop');
  1305. // 如果是删除操作
  1306. if ($is_deleted == 1) {
  1307. // 从道具列表中移除该道具
  1308. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1309. return getProp($prop, 'prop') !== $target_prop_name;
  1310. }));
  1311. // 更新道具列表
  1312. $result = DB::table('mp_anime_episodes')
  1313. ->where('anime_id', $anime_id)
  1314. ->where('id', $episode_id)
  1315. ->update([
  1316. 'props' => json_encode($props, 256),
  1317. 'updated_at' => date('Y-m-d H:i:s')
  1318. ]);
  1319. if ($result === false) {
  1320. Utils::throwError('20003:删除道具失败');
  1321. }
  1322. } else {
  1323. // 新增或更新操作
  1324. $prop_found = false;
  1325. $is_new_prop = false;
  1326. // 查找并更新已存在的道具
  1327. foreach($props as &$prop) {
  1328. if (getProp($prop, 'prop') === $target_prop_name) {
  1329. $prop = $target_props;
  1330. $prop_found = true;
  1331. break;
  1332. }
  1333. }
  1334. // 如果道具不存在,则新增
  1335. if (!$prop_found) {
  1336. $props[] = $target_props;
  1337. $is_new_prop = true;
  1338. }
  1339. // 更新道具列表
  1340. $result = DB::table('mp_anime_episodes')
  1341. ->where('anime_id', $anime_id)
  1342. ->where('id', $episode_id)
  1343. ->update([
  1344. 'props' => json_encode($props, 256),
  1345. 'updated_at' => date('Y-m-d H:i:s')
  1346. ]);
  1347. if ($result === false) {
  1348. Utils::throwError('20003:更新道具列表失败');
  1349. }
  1350. // 如果有关联的script_id,则同步到mp_products表
  1351. if ($script_id) {
  1352. // 查询剧本信息
  1353. $script = DB::table('mp_scripts')
  1354. ->where('id', $script_id)
  1355. ->where('is_deleted', 0)
  1356. ->first();
  1357. if ($script) {
  1358. $script_name = $script->script_name ?? 'script_' . $script_id;
  1359. $product_name = getProp($target_props, 'prop');
  1360. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1361. $url = getProp($target_props, 'url', '');
  1362. $product_type = 3; // 3=道具
  1363. // 查找或创建以script_name命名的文件夹
  1364. $folder = DB::table('mp_products')
  1365. ->where('cpid', $cpid)
  1366. ->where('type', 2) // 文件夹类型
  1367. ->where('product', $product_type) // 道具类型
  1368. ->where('product_name', $script_name)
  1369. ->where('parent_id', 0)
  1370. ->where('is_deleted', 0)
  1371. ->first();
  1372. if (!$folder) {
  1373. // 创建文件夹
  1374. $folder_id = DB::table('mp_products')->insertGetId([
  1375. 'user_id' => $uid,
  1376. 'cpid' => $cpid,
  1377. 'type' => 2, // 文件夹
  1378. 'product' => $product_type, // 道具类型
  1379. 'parent_id' => 0,
  1380. 'level' => 1,
  1381. 'product_name' => $script_name,
  1382. 'sort_order' => time(),
  1383. 'is_deleted' => 0,
  1384. 'created_at' => date('Y-m-d H:i:s'),
  1385. 'updated_at' => date('Y-m-d H:i:s')
  1386. ]);
  1387. } else {
  1388. $folder_id = $folder->id;
  1389. }
  1390. // 查找该文件夹下是否已存在同名资产
  1391. $existing_product = DB::table('mp_products')
  1392. ->where('cpid', $cpid)
  1393. ->where('type', 1) // 资产类型
  1394. ->where('product', $product_type)
  1395. ->where('parent_id', $folder_id)
  1396. ->where('product_name', $product_name)
  1397. ->where('is_deleted', 0)
  1398. ->first();
  1399. if ($existing_product) {
  1400. // 更新已存在的资产
  1401. $updateData = [
  1402. 'pic_task_status' => '生成成功'
  1403. ];
  1404. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1405. if ($url) $updateData['url'] = $url;
  1406. // 处理versions字段
  1407. $versions = getProp($target_props, 'versions', []);
  1408. if ($versions && is_array($versions)) {
  1409. $updateData['versions'] = json_encode($versions, 256);
  1410. }
  1411. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1412. DB::table('mp_products')
  1413. ->where('id', $existing_product->id)
  1414. ->update($updateData);
  1415. $product_id = $existing_product->id;
  1416. } else {
  1417. // 创建新资产
  1418. $versions = getProp($target_props, 'versions', []);
  1419. $product_id = DB::table('mp_products')->insertGetId([
  1420. 'user_id' => $uid,
  1421. 'cpid' => $cpid,
  1422. 'type' => 1, // 资产
  1423. 'product' => $product_type, // 道具
  1424. 'parent_id' => $folder_id,
  1425. 'level' => 2,
  1426. 'product_name' => $product_name,
  1427. 'url' => $url,
  1428. 'pic_prompt' => $pic_prompt,
  1429. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1430. 'sort_order' => time(),
  1431. 'is_deleted' => 0,
  1432. 'pic_task_status' => '生成成功',
  1433. 'created_at' => date('Y-m-d H:i:s'),
  1434. 'updated_at' => date('Y-m-d H:i:s')
  1435. ]);
  1436. }
  1437. // 建立或更新绑定关系
  1438. $existing_mapping = DB::table('mp_script_product_mappings')
  1439. ->where('script_id', $script_id)
  1440. ->where('product_id', $product_id)
  1441. ->where('episode_number', $episode_number)
  1442. ->first();
  1443. if (!$existing_mapping) {
  1444. // 创建绑定关系
  1445. DB::table('mp_script_product_mappings')->insert([
  1446. 'script_id' => $script_id,
  1447. 'product_id' => $product_id,
  1448. 'episode_number' => $episode_number,
  1449. 'created_at' => date('Y-m-d H:i:s'),
  1450. 'updated_at' => date('Y-m-d H:i:s')
  1451. ]);
  1452. }
  1453. }
  1454. }
  1455. }
  1456. } catch (\Exception $e) {
  1457. dLog('anime')->error('更新剧集道具失败', [
  1458. 'anime_id' => $anime_id,
  1459. 'episode_id' => $episode_id,
  1460. 'error' => $e->getMessage()
  1461. ]);
  1462. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1463. }
  1464. return true;
  1465. }
  1466. public function editSegment($data) {
  1467. $segment_id = getProp($data, 'segment_id');
  1468. $segment_content = getProp($data, 'segment_content');
  1469. $image_url = getProp($data, 'image_url');
  1470. $video_url = getProp($data, 'video_url');
  1471. // 参数验证
  1472. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1473. // 验证分镜是否存在
  1474. $segment = DB::table('mp_episode_segments')
  1475. ->where('segment_id', $segment_id)
  1476. ->first();
  1477. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1478. $dubTaskId = 0;
  1479. try {
  1480. DB::beginTransaction();
  1481. // 准备更新数据
  1482. $update_data = [
  1483. 'updated_at' => date('Y-m-d H:i:s')
  1484. ];
  1485. if ($segment_content) {
  1486. // 先将segment_content赋值到update_data
  1487. $update_data['segment_content'] = $segment_content;
  1488. // 使用现有方法分析segment_content,提取各个字段
  1489. $this->handleSegmentContent($update_data);
  1490. // 如果有对话内容,创建视频配音合成任务
  1491. $dialogue = getProp($update_data, 'dialogue');
  1492. if (!empty($dialogue)) {
  1493. $now = date('Y-m-d H:i:s');
  1494. $generate_json = [
  1495. 'text' => $dialogue,
  1496. 'role' => getProp($update_data, 'voice_actor'),
  1497. 'voice_type' => getProp($update_data, 'voice_type'),
  1498. 'voice_name' => getProp($update_data, 'voice_name'),
  1499. 'emotion' => getProp($update_data, 'emotion'),
  1500. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1501. 'gender' => getProp($update_data, 'gender'),
  1502. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1503. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1504. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1505. 'pitch' => getProp($update_data, 'pitch', 0),
  1506. ];
  1507. // 插入视频配音合成任务
  1508. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1509. 'alias_segment_id' => $segment_id,
  1510. 'generate_status' => '执行中',
  1511. 'audio_url' => '',
  1512. 'generate_json' => json_encode($generate_json, 256),
  1513. 'created_at' => $now,
  1514. 'updated_at' => $now,
  1515. ]);
  1516. if (!$dubTaskId) {
  1517. Utils::throwError('20003:创建配音任务失败!');
  1518. }
  1519. $update_data['audio_url'] = '';
  1520. } else {
  1521. // dialogue为空时,直接写入默认音频信息
  1522. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1523. $update_data['audio_duration'] = 2.0;
  1524. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1525. }
  1526. }
  1527. if ($image_url) {
  1528. $update_data['img_url'] = $image_url;
  1529. // 同时写入一个简单的图片生成任务
  1530. $pic_task = [
  1531. 'alias_segment_id' => $segment_id,
  1532. 'ref_img_url' => json_encode([]),
  1533. 'status' => 'success',
  1534. 'result_url' => json_encode([$image_url], 256),
  1535. 'model' => '',
  1536. 'created_at' => date('Y-m-d H:i:s'),
  1537. 'updated_at' => date('Y-m-d H:i:s'),
  1538. ];
  1539. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1540. }
  1541. if ($video_url) {
  1542. $update_data['origin_video_url'] = $video_url;
  1543. $compressed_video_url = compressVideo($video_url);
  1544. $update_data['current_type'] = 2;
  1545. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1546. // 同时写入一个简单的视频生成任务
  1547. $video_task = [
  1548. 'alias_segment_id' => $segment_id,
  1549. 'status' => 'success',
  1550. 'result_url' => $update_data['origin_video_url'],
  1551. 'compressed_url' => $update_data['video_url'],
  1552. 'created_at' => date('Y-m-d H:i:s'),
  1553. 'updated_at' => date('Y-m-d H:i:s'),
  1554. ];
  1555. DB::table('mp_generate_video_tasks')->insert($video_task);
  1556. }
  1557. // 更新分镜信息
  1558. $result = DB::table('mp_episode_segments')
  1559. ->where('segment_id', $segment_id)
  1560. ->update($update_data);
  1561. if ($result === false) {
  1562. Utils::throwError('20003:更新分镜剧本失败');
  1563. }
  1564. DB::commit();
  1565. // 如果有创建音频生成任务则调用API
  1566. if ($dubTaskId) {
  1567. // 请求远程服务器执行生成
  1568. $client = new Client(['timeout' => 300, 'verify' => false]);
  1569. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1570. $response = $result->getBody()->getContents();
  1571. $response_arr = json_decode($response, true);
  1572. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1573. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1574. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1575. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1576. Utils::throwError('20003:火山生成音频失败');
  1577. }
  1578. }
  1579. return true;
  1580. } catch (\Exception $e) {
  1581. DB::rollBack();
  1582. dLog('anime')->error('更新分镜剧本失败', [
  1583. 'segment_id' => $segment_id,
  1584. 'error' => $e->getMessage()
  1585. ]);
  1586. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1587. }
  1588. }
  1589. public function batchSetSegmentPics($data) {
  1590. $anime_id = getProp($data, 'anime_id');
  1591. $episode_id = getProp($data, 'episode_id');
  1592. $ratio = getProp($data, 'ratio');
  1593. $dimensions = $this->getRatioDimensions($ratio);
  1594. $width = $dimensions['width'];
  1595. $height = $dimensions['height'];
  1596. if (!$anime_id || !$episode_id) {
  1597. Utils::throwError('1002:请选择剧集');
  1598. }
  1599. // 获取剧集信息
  1600. $episode = DB::table('mp_anime_episodes')
  1601. ->where('anime_id', $anime_id)
  1602. ->where('id', $episode_id)
  1603. ->where('is_default', 1)
  1604. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1605. ->first();
  1606. if (!$episode) {
  1607. Utils::throwError('20003:该剧集不存在');
  1608. }
  1609. $model = getProp($data, 'model');
  1610. if (!$model) {
  1611. $model = getProp($episode, 'image_model');
  1612. if (!$model) {
  1613. // episode表也没有,使用默认值
  1614. $model = 'doubao-seedream-5-0-lite-260128';
  1615. }
  1616. }
  1617. // 验证模型是否在可用模型表中
  1618. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1619. $model = 'doubao-seedream-5-0-lite-260128';
  1620. }
  1621. $roles = json_decode(getProp($episode, 'roles'), true);
  1622. if (!$roles) {
  1623. Utils::throwError('20003:角色信息格式错误');
  1624. }
  1625. // 构建角色名称到参考图的映射
  1626. $role_map = [];
  1627. foreach ($roles as $role) {
  1628. $role_name = getProp($role, 'role');
  1629. $role_url = getProp($role, 'url');
  1630. if (!empty($role_name) && !empty($role_url)) {
  1631. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1632. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1633. // $role_map[$base_name] = $role_url;
  1634. // 同时保存完整名称的映射
  1635. $role_map[$role_name] = $role_url;
  1636. }
  1637. }
  1638. $scenes = json_decode(getProp($episode, 'roles'), true);
  1639. if (!$scenes) {
  1640. Utils::throwError('20003:场景信息格式错误');
  1641. }
  1642. // 构建角色名称到参考图的映射
  1643. $scene_map = [];
  1644. foreach ($scenes as $scene) {
  1645. $scene_name = getProp($scene, 'scene');
  1646. $scene_url = getProp($scene, 'url');
  1647. if (!empty($scene_name) && !empty($scene_url)) {
  1648. $scene_map[$scene_name] = $scene_url;
  1649. }
  1650. }
  1651. // 获取所有分镜信息
  1652. $segments = DB::table('mp_episode_segments')
  1653. ->where('anime_id', $anime_id)
  1654. ->where('episode_id', $episode_id)
  1655. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1656. ->orderBy('segment_number')
  1657. ->get()
  1658. ->toArray();
  1659. if (empty($segments)) {
  1660. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1661. }
  1662. // 保存图片比例
  1663. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1664. $updated_segments = [];
  1665. $failed_segments = [];
  1666. // 批量为每个分镜生成图片任务
  1667. foreach ($segments as $segment) {
  1668. $segment_id = $segment->segment_id;
  1669. $segment_content = $segment->segment_content;
  1670. if (empty($segment_content)) {
  1671. $failed_segments[] = [
  1672. 'segment_id' => $segment_id,
  1673. 'error' => '分镜内容为空'
  1674. ];
  1675. continue;
  1676. }
  1677. try {
  1678. $dubTaskId = 0;
  1679. // 解析分镜内容,提取画面描述作为主要提示词
  1680. $prompt = $segment_content;
  1681. $ref_img_urls = [];
  1682. // 分镜场景
  1683. $scene = getProp($segment, 'scene');
  1684. $matched_scene = '';
  1685. if (isset($scene_map[$scene])) {
  1686. $img_index = count($ref_img_urls) + 1;
  1687. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1688. $ref_img_urls[] = $scene_map[$scene];
  1689. $matched_scene = $scene;
  1690. }
  1691. // 分镜角色
  1692. $characters = getProp($segment, 'characters');
  1693. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1694. $roles = explode(',', $characters);
  1695. // 从分镜内容中提取涉及的角色
  1696. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1697. // 获取匹配角色的参考图
  1698. foreach ($segment_characters as $character) {
  1699. if (isset($role_map[$character])) {
  1700. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1701. $img_index = count($ref_img_urls) + 1;
  1702. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1703. $ref_img_urls[] = $role_map[$character];
  1704. }
  1705. }
  1706. // 如果没有找到匹配的角色参考图,不使用参考图
  1707. if (empty($ref_img_urls)) {
  1708. $ref_img_urls = [];
  1709. }
  1710. // 准备生成任务参数
  1711. $params = [
  1712. 'model' => $model,
  1713. 'alias_segment_id' => $segment_id,
  1714. 'prompt' => $prompt,
  1715. 'ref_img_urls' => $ref_img_urls,
  1716. 'width' => $width,
  1717. 'height' => $height,
  1718. ];
  1719. // 优化提示词(不要生成字幕)
  1720. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1721. // $task_id = mt_rand(100000, 999999);
  1722. // 调用AI图片生成服务
  1723. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1724. $task_id = $task->id;
  1725. if (!$task_id) {
  1726. $failed_segments[] = [
  1727. 'segment_id' => $segment_id,
  1728. 'error' => '创建生成任务失败'
  1729. ];
  1730. continue;
  1731. }
  1732. $update_data = [
  1733. 'pic_task_id' => $task_id,
  1734. 'pic_task_status' => '生成中',
  1735. 'audio_url' => '',
  1736. 'updated_at' => date('Y-m-d H:i:s')
  1737. ];
  1738. // 如果有对话内容,创建视频配音合成任务
  1739. $dialogue = getProp($segment, 'dialogue');
  1740. if (!empty($dialogue)) {
  1741. $now = date('Y-m-d H:i:s');
  1742. $generate_json = [
  1743. 'text' => $dialogue,
  1744. 'role' => getProp($segment, 'voice_actor'),
  1745. 'voice_type' => getProp($segment, 'voice_type'),
  1746. 'voice_name' => getProp($segment, 'voice_name'),
  1747. 'emotion' => getProp($segment, 'emotion'),
  1748. 'emotion_type' => getProp($segment, 'emotion_type'),
  1749. 'gender' => getProp($segment, 'gender'),
  1750. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1751. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1752. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1753. 'pitch' => getProp($segment, 'pitch', 0),
  1754. ];
  1755. // 插入视频配音合成任务
  1756. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1757. 'alias_segment_id' => $segment_id,
  1758. 'generate_status' => '执行中',
  1759. 'audio_url' => '',
  1760. 'generate_json' => json_encode($generate_json, 256),
  1761. 'created_at' => $now,
  1762. 'updated_at' => $now,
  1763. ]);
  1764. if (!$dubTaskId) {
  1765. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1766. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1767. // Utils::throwError('20003:创建配音任务失败!');
  1768. }
  1769. } else {
  1770. // dialogue为空时,直接写入默认音频信息到分镜表
  1771. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1772. $update_data['audio_duration'] = 2.0;
  1773. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1774. }
  1775. // 更新分镜的任务信息
  1776. $update_result = DB::table('mp_episode_segments')
  1777. ->where('segment_id', $segment_id)
  1778. ->update($update_data);
  1779. // 如果是第一集的首帧图片,则存入待更新数组
  1780. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1781. Redis::sadd('anime_first_frame_urls', $segment_id);
  1782. }
  1783. if ($update_result) {
  1784. $updated_segments[] = [
  1785. 'segment_id' => $segment_id,
  1786. 'task_id' => $task_id,
  1787. 'status' => '生成中',
  1788. 'matched_scenes' => $matched_scene,
  1789. 'matched_roles' => $segment_characters,
  1790. 'ref_urls_count' => count($ref_img_urls)
  1791. ];
  1792. } else {
  1793. $failed_segments[] = [
  1794. 'segment_id' => $segment_id,
  1795. 'error' => '更新分镜任务状态失败'
  1796. ];
  1797. }
  1798. if ($dubTaskId) {
  1799. sleep(1);
  1800. // 请求远程服务器执行生成
  1801. $client = new Client(['timeout' => 300, 'verify' => false]);
  1802. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1803. $response = $result->getBody()->getContents();
  1804. $response_arr = json_decode($response, true);
  1805. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1806. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1807. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1808. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1809. }
  1810. }
  1811. } catch (\Exception $e) {
  1812. $failed_segments[] = [
  1813. 'segment_id' => $segment_id,
  1814. 'error' => $e->getMessage()
  1815. ];
  1816. }
  1817. }
  1818. // 更新剧集生成状态
  1819. if (!empty($updated_segments)) {
  1820. DB::table('mp_anime_episodes')
  1821. ->where('id', $episode_id)
  1822. ->update([
  1823. 'is_generated' => 1,
  1824. 'updated_at' => date('Y-m-d H:i:s')
  1825. ]);
  1826. }
  1827. return [
  1828. 'success_count' => count($updated_segments),
  1829. 'failed_count' => count($failed_segments),
  1830. 'success_segments' => $updated_segments,
  1831. 'failed_segments' => $failed_segments,
  1832. 'total_segments' => count($segments)
  1833. ];
  1834. }
  1835. public function reGenerateSegment($data) {
  1836. $segment_id = getProp($data, 'segment_id');
  1837. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1838. $anime_id = getProp($segment, 'anime_id');
  1839. $episode_id = getProp($segment, 'episode_id');
  1840. $episode_number = getProp($segment, 'episode_number');
  1841. $segment_content = getProp($data, 'segment_content');
  1842. $ratio = getProp($data, 'ratio');
  1843. if (!$ratio) {
  1844. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1845. if (!$ratio) $ratio = '9:16';
  1846. }
  1847. $dimensions = $this->getRatioDimensions($ratio);
  1848. $width = $dimensions['width'];
  1849. $height = $dimensions['height'];
  1850. if (!$anime_id || !$episode_id) {
  1851. Utils::throwError('1002:请选择分镜');
  1852. }
  1853. // 使用文生文模型重新解析segment_content
  1854. if (!empty($segment_content)) {
  1855. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1856. }
  1857. // 获取动漫的角色信息(包含参考图)
  1858. $anime = DB::table('mp_animes')
  1859. ->where('id', $anime_id)
  1860. ->select('roles', 'scenes')
  1861. ->first();
  1862. if (!$anime || !$anime->roles) {
  1863. Utils::throwError('20003:未找到角色信息');
  1864. }
  1865. $roles = json_decode($anime->roles, true);
  1866. if (!$roles) {
  1867. Utils::throwError('20003:角色信息格式错误');
  1868. }
  1869. // 构建角色名称到参考图的映射
  1870. $role_map = [];
  1871. foreach ($roles as $role) {
  1872. $role_name = getProp($role, 'role');
  1873. $role_url = getProp($role, 'url');
  1874. if (!empty($role_name) && !empty($role_url)) {
  1875. $role_map[$role_name] = $role_url;
  1876. }
  1877. }
  1878. $scenes = json_decode($anime->scenes, true);
  1879. if (!$scenes) {
  1880. Utils::throwError('20003:角色信息格式错误');
  1881. }
  1882. // 构建角色名称到参考图的映射
  1883. $scene_map = [];
  1884. foreach ($scenes as $scene) {
  1885. $scene_name = getProp($scene, 'scene');
  1886. $scene_url = getProp($scene, 'url');
  1887. if (!empty($scene_name) && !empty($scene_url)) {
  1888. $scene_map[$scene_name] = $scene_url;
  1889. }
  1890. }
  1891. $segment_id = $segment->segment_id;
  1892. $original_segment_content = $segment->segment_content;
  1893. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1894. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1895. if (empty($final_segment_content)) {
  1896. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1897. }
  1898. try {
  1899. $dubTaskId = 0;
  1900. // 分镜剧本数组
  1901. $update_data = [
  1902. 'segment_content' => $final_segment_content,
  1903. 'pic_task_status' => '生成中',
  1904. 'updated_at' => date('Y-m-d H:i:s')
  1905. ];
  1906. // 解析分镜内容,提取画面描述作为主要提示词
  1907. $prompt = $final_segment_content;
  1908. $ref_img_urls = [];
  1909. // 分镜场景
  1910. $scene = getProp($data, 'scene');
  1911. if ($scene) {
  1912. $matched_scene = '';
  1913. if (isset($scene_map[$scene])) {
  1914. $img_index = count($ref_img_urls) + 1;
  1915. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1916. $ref_img_urls[] = $scene_map[$scene];
  1917. $matched_scene = $scene;
  1918. }
  1919. $update_data['scene'] = $scene;
  1920. }
  1921. // 分镜角色
  1922. $characters = getProp($data, 'characters');
  1923. if ($characters) {
  1924. $update_data['characters'] = $characters;
  1925. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1926. $characters = explode(',', $characters);
  1927. // 从分镜内容中提取涉及的角色
  1928. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1929. // 获取匹配角色的参考图
  1930. foreach ($segment_characters as $character) {
  1931. if (isset($role_map[$character])) {
  1932. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1933. $img_index = count($ref_img_urls) + 1;
  1934. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1935. $ref_img_urls[] = $role_map[$character];
  1936. }
  1937. }
  1938. }
  1939. // 如果没有找到匹配的角色参考图,不使用参考图
  1940. if (empty($ref_img_urls)) {
  1941. $ref_img_urls = [];
  1942. }
  1943. // 准备生成任务参数
  1944. $params = [
  1945. 'alias_segment_id' => $segment_id,
  1946. 'prompt' => $prompt,
  1947. 'ref_img_urls' => $ref_img_urls,
  1948. 'width' => $width,
  1949. 'height' => $height,
  1950. ];
  1951. // 优化提示词(不要生成字幕)
  1952. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1953. // 调用AI图片生成服务
  1954. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1955. $task_id = $task->id;
  1956. if (!$task_id) {
  1957. Utils::throwError('20003:创建生成任务失败!');
  1958. }
  1959. $update_data['pic_task_id'] = $task_id;
  1960. // 更新分镜剧本信息
  1961. $this->handleSegmentContent($update_data);
  1962. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1963. if ($segment_content) {
  1964. $dialogue = getProp($update_data, 'dialogue');
  1965. if (!empty($dialogue)) {
  1966. $now = date('Y-m-d H:i:s');
  1967. $generate_json = [
  1968. 'text' => $dialogue,
  1969. 'role' => getProp($update_data, 'voice_actor'),
  1970. 'voice_type' => getProp($update_data, 'voice_type'),
  1971. 'voice_name' => getProp($update_data, 'voice_name'),
  1972. 'emotion' => getProp($update_data, 'emotion'),
  1973. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1974. 'gender' => getProp($update_data, 'gender'),
  1975. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1976. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1977. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1978. 'pitch' => getProp($update_data, 'pitch', 0),
  1979. ];
  1980. // 插入视频配音合成任务
  1981. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1982. 'alias_segment_id' => $segment_id,
  1983. 'generate_status' => '执行中',
  1984. 'audio_url' => '',
  1985. 'generate_json' => json_encode($generate_json, 256),
  1986. 'created_at' => date('Y-m-d H:i:s'),
  1987. 'updated_at' => date('Y-m-d H:i:s'),
  1988. ]);
  1989. if (!$dubTaskId) {
  1990. Utils::throwError('20003:创建配音任务失败!');
  1991. }
  1992. $update_data['audio_url'] = '';
  1993. } else {
  1994. // dialogue为空时,直接写入默认音频信息
  1995. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1996. $update_data['audio_duration'] = 2.0;
  1997. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1998. }
  1999. }
  2000. $boolen = DB::table('mp_episode_segments')
  2001. ->where('segment_id', $segment_id)
  2002. ->update($update_data);
  2003. // 如果是第一集的首帧图片,则存入待更新数组
  2004. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2005. Redis::sadd('anime_first_frame_urls', $segment_id);
  2006. }
  2007. if ($dubTaskId) {
  2008. // 请求远程服务器执行生成
  2009. $client = new Client(['timeout' => 300, 'verify' => false]);
  2010. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2011. $response = $result->getBody()->getContents();
  2012. $response_arr = json_decode($response, true);
  2013. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2014. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2015. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2016. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2017. Utils::throwError('20003:火山生成音频失败');
  2018. }
  2019. }
  2020. } catch (\Exception $e) {
  2021. $failed_segments[] = [
  2022. 'segment_id' => $segment_id,
  2023. 'error' => $e->getMessage()
  2024. ];
  2025. }
  2026. // 创建任务之后先暂停10s等待异步任务完成
  2027. sleep(10);
  2028. $img_url = $this->loopGetPicTaskResult($task_id);
  2029. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2030. // 图片生成后新增对话记录
  2031. try {
  2032. $uid = Site::getUid();
  2033. $now = date('Y-m-d H:i:s');
  2034. // 使用AI反推图片提示词
  2035. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2036. // 保存对话记录
  2037. $records = [
  2038. [
  2039. 'uid' => $uid,
  2040. 'anime_id' => $anime_id,
  2041. 'sequence' => $episode_number,
  2042. 'role' => 'user',
  2043. 'content' => '重新生成',
  2044. 'segment_id' => $segment_id,
  2045. 'image_url' => '',
  2046. 'created_at' => $now,
  2047. 'updated_at' => $now
  2048. ],
  2049. [
  2050. 'uid' => $uid,
  2051. 'anime_id' => $anime_id,
  2052. 'sequence' => $episode_number,
  2053. 'role' => 'assistant',
  2054. 'content' => $pic_prompt,
  2055. 'segment_id' => $segment_id,
  2056. 'image_url' => $img_url,
  2057. 'created_at' => $now,
  2058. 'updated_at' => $now
  2059. ]
  2060. ];
  2061. DB::table('mp_anime_records')->insert($records);
  2062. } catch (\Exception $e) {
  2063. // 记录日志但不影响主流程
  2064. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2065. 'segment_id' => $segment_id,
  2066. 'img_url' => $img_url
  2067. ]);
  2068. }
  2069. return $img_url;
  2070. }
  2071. public function addSegment($data) {
  2072. $prev_segment_id = getProp($data, 'prev_segment_id');
  2073. $img_url = getProp($data, 'img_url');
  2074. $video_url = getProp($data, 'video_url');
  2075. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2076. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2077. $anime_id = getProp($segment, 'anime_id');
  2078. $episode_id = getProp($segment, 'episode_id');
  2079. $episode_number = getProp($segment, 'episode_number');
  2080. $segment_number = getProp($segment, 'segment_number');
  2081. $new_segment_number = $segment_number + 1;
  2082. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2083. // 分镜剧本数组
  2084. $insert_data = [
  2085. 'anime_id' => $anime_id,
  2086. 'episode_id' => $episode_id,
  2087. 'episode_number' => $episode_number,
  2088. 'act_number' => getProp($segment, 'act_number'),
  2089. 'act_title' => getProp($segment, 'act_title'),
  2090. 'segment_id' => $segment_id,
  2091. 'segment_number' => $new_segment_number,
  2092. 'segment_content' => '',
  2093. 'img_url' => '',
  2094. 'video_url' => '',
  2095. 'created_at' => date('Y-m-d H:i:s'),
  2096. 'updated_at' => date('Y-m-d H:i:s')
  2097. ];
  2098. if ($img_url) $insert_data['img_url'] = $img_url;
  2099. if ($video_url) {
  2100. $insert_data['origin_video_url'] = $video_url;
  2101. $insert_data['current_type'] = 2;
  2102. $compressed_video_url = compressVideo($video_url);
  2103. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2104. }
  2105. try {
  2106. DB::beginTransaction();
  2107. // 先更新序号
  2108. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2109. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2110. if (!$id) {
  2111. Utils::throwError('20003:新增分镜失败!');
  2112. }
  2113. }catch (\Exception $e) {
  2114. DB::rollBack();
  2115. Utils::throwError('20003:'.$e->getMessage());
  2116. }
  2117. DB::commit();
  2118. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2119. $segment = $segment ? (array)$segment : [];
  2120. return $segment;
  2121. // 以下代码暂弃用
  2122. $anime_id = getProp($segment, 'anime_id');
  2123. $episode_id = getProp($segment, 'episode_id');
  2124. $episode_number = getProp($segment, 'episode_number');
  2125. $segment_number = getProp($segment, 'segment_number');
  2126. $segment_content = getProp($data, 'segment_content');
  2127. $img_url = getProp($data, 'img_url');
  2128. $video_url = getProp($data, 'video_url');
  2129. $ratio = getProp($data, 'ratio');
  2130. $dimensions = $this->getRatioDimensions($ratio);
  2131. $width = $dimensions['width'];
  2132. $height = $dimensions['height'];
  2133. if (!$anime_id || !$episode_id) {
  2134. Utils::throwError('1002:请选择分镜');
  2135. }
  2136. // 使用文生文模型重新解析segment_content
  2137. if (!empty($segment_content)) {
  2138. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2139. }
  2140. // 获取动漫的角色信息(包含参考图)
  2141. $anime = DB::table('mp_animes')
  2142. ->where('id', $anime_id)
  2143. ->select('roles', 'scenes')
  2144. ->first();
  2145. if (!$anime || !$anime->roles) {
  2146. Utils::throwError('20003:未找到角色信息');
  2147. }
  2148. $roles = json_decode($anime->roles, true);
  2149. if (!$roles) {
  2150. Utils::throwError('20003:角色信息格式错误');
  2151. }
  2152. // 构建角色名称到参考图的映射
  2153. $role_map = [];
  2154. foreach ($roles as $role) {
  2155. $role_name = getProp($role, 'role');
  2156. $role_url = getProp($role, 'url');
  2157. if (!empty($role_name) && !empty($role_url)) {
  2158. $role_map[$role_name] = $role_url;
  2159. }
  2160. }
  2161. $scenes = json_decode($anime->scenes, true);
  2162. if (!$scenes) {
  2163. Utils::throwError('20003:角色信息格式错误');
  2164. }
  2165. // 构建角色名称到参考图的映射
  2166. $scene_map = [];
  2167. foreach ($scenes as $scene) {
  2168. $scene_name = getProp($scene, 'scene');
  2169. $scene_url = getProp($scene, 'url');
  2170. if (!empty($scene_name) && !empty($scene_url)) {
  2171. $scene_map[$scene_name] = $scene_url;
  2172. }
  2173. }
  2174. $segment_id = $segment->segment_id;
  2175. $original_segment_content = $segment->segment_content;
  2176. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2177. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2178. if (empty($final_segment_content)) {
  2179. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2180. }
  2181. try {
  2182. $dubTaskId = 0;
  2183. DB::beginTransaction();
  2184. $new_segment_number = $segment_number + 1;
  2185. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2186. // 分镜剧本数组
  2187. $insert_data = [
  2188. 'anime_id' => $anime_id,
  2189. 'episode_id' => $episode_id,
  2190. 'episode_number' => $episode_number,
  2191. 'act_number' => getProp($segment, 'act_number'),
  2192. 'act_title' => getProp($segment, 'act_title'),
  2193. 'segment_id' => $segment_id,
  2194. 'segment_number' => $new_segment_number,
  2195. 'segment_content' => $final_segment_content,
  2196. 'img_url' => $img_url,
  2197. 'video_url' => $video_url,
  2198. 'created_at' => date('Y-m-d H:i:s'),
  2199. 'updated_at' => date('Y-m-d H:i:s')
  2200. ];
  2201. // 更新分镜剧本信息
  2202. $this->handleSegmentContent($insert_data);
  2203. // 如果有对话内容,创建视频配音合成任务
  2204. $dialogue = getProp($insert_data, 'dialogue');
  2205. if (!empty($dialogue)) {
  2206. $now = date('Y-m-d H:i:s');
  2207. $generate_json = [
  2208. 'text' => $dialogue,
  2209. 'role' => getProp($insert_data, 'voice_actor'),
  2210. 'voice_type' => getProp($insert_data, 'voice_type'),
  2211. 'voice_name' => getProp($insert_data, 'voice_name'),
  2212. 'emotion' => getProp($insert_data, 'emotion'),
  2213. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2214. 'gender' => getProp($insert_data, 'gender'),
  2215. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2216. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2217. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2218. 'pitch' => getProp($insert_data, 'pitch', 0),
  2219. ];
  2220. // 插入视频配音合成任务
  2221. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2222. 'alias_segment_id' => $segment_id,
  2223. 'generate_status' => '执行中',
  2224. 'audio_url' => '',
  2225. 'generate_json' => json_encode($generate_json, 256),
  2226. 'created_at' => $now,
  2227. 'updated_at' => $now,
  2228. ]);
  2229. if (!$dubTaskId) {
  2230. Utils::throwError('20003:创建配音任务失败!');
  2231. }
  2232. $insert_data['audio_url'] = '';
  2233. } else {
  2234. // dialogue为空时,直接写入默认音频信息
  2235. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2236. $insert_data['audio_duration'] = 2.0;
  2237. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2238. }
  2239. // 如果没有上传图片则使用当前描述进行生成
  2240. if (!$img_url) {
  2241. // 解析分镜内容,提取画面描述作为主要提示词
  2242. $prompt = $final_segment_content;
  2243. $ref_img_urls = [];
  2244. // 分镜场景
  2245. $scene = getProp($insert_data, 'scene');
  2246. if ($scene) {
  2247. $matched_scene = '';
  2248. if (isset($scene_map[$scene])) {
  2249. $img_index = count($ref_img_urls) + 1;
  2250. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2251. $ref_img_urls[] = $scene_map[$scene];
  2252. $matched_scene = $scene;
  2253. }
  2254. $update_data['scene'] = $scene;
  2255. }
  2256. // 分镜角色
  2257. $characters = getProp($insert_data, 'characters');
  2258. if ($characters) {
  2259. $update_data['characters'] = $characters;
  2260. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2261. $characters = explode(',', $characters);
  2262. // 从分镜内容中提取涉及的角色
  2263. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2264. // 获取匹配角色的参考图
  2265. foreach ($segment_characters as $character) {
  2266. if (isset($role_map[$character])) {
  2267. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2268. $img_index = count($ref_img_urls) + 1;
  2269. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2270. $ref_img_urls[] = $role_map[$character];
  2271. }
  2272. }
  2273. }
  2274. // 如果没有找到匹配的角色参考图,不使用参考图
  2275. if (empty($ref_img_urls)) {
  2276. $ref_img_urls = [];
  2277. }
  2278. // 准备生成任务参数
  2279. $params = [
  2280. 'alias_segment_id' => $segment_id,
  2281. 'prompt' => $prompt,
  2282. 'ref_img_urls' => $ref_img_urls,
  2283. 'width' => $width,
  2284. 'height' => $height,
  2285. ];
  2286. // 调用AI图片生成服务
  2287. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2288. $task_id = $task->id;
  2289. // $task_id = 'whatever';
  2290. if (!$task_id) {
  2291. Utils::throwError('20003:创建生成任务失败!');
  2292. }
  2293. $insert_data['pic_task_status'] = '生成中';
  2294. $insert_data['pic_task_id'] = $task_id;
  2295. }
  2296. // 先更新序号
  2297. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2298. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2299. if (!$boolen) {
  2300. Utils::throwError('20003:新增分镜失败!');
  2301. }
  2302. // 如果是第一集的首帧图片,则存入待更新数组
  2303. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2304. Redis::sadd('anime_first_frame_urls', $segment_id);
  2305. }
  2306. if ($dubTaskId) {
  2307. // 请求远程服务器执行生成
  2308. $client = new Client(['timeout' => 300, 'verify' => false]);
  2309. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2310. $response = $result->getBody()->getContents();
  2311. $response_arr = json_decode($response, true);
  2312. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2313. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2314. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2315. Utils::throwError('20003:火山生成音频失败');
  2316. }
  2317. }
  2318. } catch (\Exception $e) {
  2319. DB::rollBack();
  2320. Utils::throwError('20003:'.$e->getMessage());
  2321. }
  2322. DB::commit();
  2323. // 创建任务之后先暂停10s等待异步任务完成
  2324. sleep(10);
  2325. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2326. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2327. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2328. $segment = $segment ? (array)$segment : [];
  2329. return $segment;
  2330. }
  2331. public function copySegment($data) {
  2332. $segment_id = getProp($data, 'segment_id');
  2333. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2334. if (!$segment) Utils::throwError('20003:请选择分镜');
  2335. $anime_id = getProp($segment, 'anime_id');
  2336. $episode_id = getProp($segment, 'episode_id');
  2337. $episode_number = getProp($segment, 'episode_number');
  2338. $segment_number = getProp($segment, 'segment_number');
  2339. $new_segment_id = 0;
  2340. try {
  2341. DB::beginTransaction();
  2342. $segment = (array)$segment;
  2343. unset($segment['id']);
  2344. $segment['segment_number'] += 1;
  2345. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2346. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2347. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2348. // 更新其他分镜序号
  2349. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2350. // 复制分镜
  2351. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2352. if (!$id) {
  2353. Utils::throwError('20003:复制分镜失败');
  2354. }
  2355. }catch (\Exception $e) {
  2356. DB::rollBack();
  2357. Utils::throwError('20003:'.$e->getMessage());
  2358. }
  2359. DB::commit();
  2360. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2361. $segment = $segment ? (array)$segment : [];
  2362. return $segment;
  2363. }
  2364. public function moveSegment($data) {
  2365. $segment_id = getProp($data, 'segment_id');
  2366. $target_segment_id = getProp($data, 'target_segment_id');
  2367. // 获取源分镜信息
  2368. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2369. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2370. // 获取目标分镜信息
  2371. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2372. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2373. $anime_id = getProp($source_segment, 'anime_id');
  2374. $episode_id = getProp($source_segment, 'episode_id');
  2375. $episode_number = getProp($source_segment, 'episode_number');
  2376. $source_segment_number = getProp($source_segment, 'segment_number');
  2377. $target_segment_number = getProp($target_segment, 'segment_number');
  2378. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2379. $target_anime_id = getProp($target_segment, 'anime_id');
  2380. $target_episode_number = getProp($target_segment, 'episode_number');
  2381. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2382. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2383. }
  2384. // 如果源分镜和目标分镜相同,无需移动
  2385. if ($source_segment_number == $target_segment_number) {
  2386. return true;
  2387. }
  2388. try {
  2389. DB::beginTransaction();
  2390. if ($source_segment_number < $target_segment_number) {
  2391. // 向后移动:源分镜移动到目标分镜之后
  2392. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2393. DB::table('mp_episode_segments')
  2394. ->where('anime_id', $anime_id)
  2395. ->where('episode_id', $episode_id)
  2396. ->where('segment_number', '>', $source_segment_number)
  2397. ->where('segment_number', '<=', $target_segment_number)
  2398. ->decrement('segment_number');
  2399. // 2. 将源分镜移动到目标分镜之后
  2400. $new_segment_number = $target_segment_number;
  2401. } else {
  2402. // 向前移动:源分镜移动到目标分镜之后
  2403. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2404. DB::table('mp_episode_segments')
  2405. ->where('anime_id', $anime_id)
  2406. ->where('episode_id', $episode_id)
  2407. ->where('segment_number', '>', $target_segment_number)
  2408. ->where('segment_number', '<', $source_segment_number)
  2409. ->increment('segment_number');
  2410. // 2. 将源分镜移动到目标分镜之后
  2411. $new_segment_number = $target_segment_number + 1;
  2412. }
  2413. // 3. 更新源分镜的序号
  2414. $update_result = DB::table('mp_episode_segments')
  2415. ->where('segment_id', $segment_id)
  2416. ->update([
  2417. 'segment_number' => $new_segment_number,
  2418. 'updated_at' => date('Y-m-d H:i:s')
  2419. ]);
  2420. if (!$update_result) {
  2421. Utils::throwError('20003:更新分镜序号失败');
  2422. }
  2423. DB::commit();
  2424. return true;
  2425. } catch (\Exception $e) {
  2426. DB::rollBack();
  2427. Utils::throwError('20003:' . $e->getMessage());
  2428. }
  2429. }
  2430. public function delSegment($data) {
  2431. $segment_id = getProp($data, 'segment_id');
  2432. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2433. if (!$segment) Utils::throwError('20003:请选择分镜');
  2434. $anime_id = getProp($segment, 'anime_id');
  2435. $episode_id = getProp($segment, 'episode_id');
  2436. $episode_number = getProp($segment, 'episode_number');
  2437. $segment_number = getProp($segment, 'segment_number');
  2438. try {
  2439. DB::beginTransaction();
  2440. // 删除分镜
  2441. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2442. if (!$boolen) {
  2443. Utils::throwError('20003:删除分镜失败');
  2444. }
  2445. // 更新其他分镜序号
  2446. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2447. }catch (\Exception $e) {
  2448. DB::rollBack();
  2449. Utils::throwError('20003:'.$e->getMessage());
  2450. }
  2451. DB::commit();
  2452. return true;
  2453. }
  2454. public function applySegment($data) {
  2455. $segment_id = getProp($data, 'segment_id');
  2456. $url = getProp($data, 'url');
  2457. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2458. if (!$url) Utils::throwError('20003:URL不能为空');
  2459. // 获取URL的文件扩展名
  2460. $urlPath = parse_url($url, PHP_URL_PATH);
  2461. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2462. // 定义图片和视频的扩展名
  2463. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2464. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2465. // 判断是图片还是视频
  2466. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2467. if (in_array($extension, $imageExtensions)) {
  2468. // 图片类型
  2469. $updateData['img_url'] = $url;
  2470. $updateData['current_type'] = 1;
  2471. } elseif (in_array($extension, $videoExtensions)) {
  2472. // 视频类型
  2473. $updateData['video_url'] = $url;
  2474. $updateData['current_type'] = 2;
  2475. } else {
  2476. Utils::throwError('20003:不支持的文件类型');
  2477. }
  2478. // 更新分镜表
  2479. $result = DB::table('mp_episode_segments')
  2480. ->where('segment_id', $segment_id)
  2481. ->update($updateData);
  2482. if (!$result) {
  2483. Utils::throwError('20003:更新分镜失败');
  2484. }
  2485. return true;
  2486. }
  2487. public function segmentHistory($data) {
  2488. $segment_id = getProp($data, 'segment_id');
  2489. // 获取历史图片
  2490. $pics = [];
  2491. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2492. foreach($pic_history as $task) {
  2493. $result_url = getProp($task, 'result_url');
  2494. if (is_json($result_url)) {
  2495. $pics = array_merge($pics, json_decode($result_url, true));
  2496. }else {
  2497. $pics[] = $result_url;
  2498. }
  2499. }
  2500. // 获取历史视频
  2501. $videos = [];
  2502. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2503. foreach($video_history as $task) {
  2504. $result_url = getProp($task, 'result_url');
  2505. if (is_json($result_url)) {
  2506. $videos = array_merge($videos, json_decode($result_url, true));
  2507. }else {
  2508. $videos[] = $result_url;
  2509. }
  2510. }
  2511. return compact('pics', 'videos');
  2512. }
  2513. public function addAct($data) {
  2514. $prev_act_id = getProp($data, 'prev_act_id');
  2515. $act_title = getProp($data, 'act_title', '');
  2516. $act_content = getProp($data, 'act_content', '');
  2517. $act_duration = getProp($data, 'act_duration', 5);
  2518. $video_url = getProp($data, 'video_url');
  2519. // 根据prev_act_id获取记录
  2520. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2521. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2522. $anime_id = getProp($prev_segment, 'anime_id');
  2523. $episode_id = getProp($prev_segment, 'episode_id');
  2524. $episode_number = getProp($prev_segment, 'episode_number');
  2525. $prev_act_number = getProp($prev_segment, 'act_number');
  2526. // 获取新的act_number
  2527. $new_act_number = $prev_act_number + 1;
  2528. try {
  2529. DB::beginTransaction();
  2530. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2531. DB::table('mp_episode_segments')
  2532. ->where('anime_id', $anime_id)
  2533. ->where('episode_id', $episode_id)
  2534. ->where('act_number', '>', $prev_act_number)
  2535. ->increment('act_number');
  2536. // 插入新片段记录
  2537. $insert_data = [
  2538. 'anime_id' => $anime_id,
  2539. 'episode_id' => $episode_id,
  2540. 'episode_number' => $episode_number,
  2541. 'act_number' => $new_act_number,
  2542. 'created_at' => date('Y-m-d H:i:s'),
  2543. 'updated_at' => date('Y-m-d H:i:s')
  2544. ];
  2545. if ($act_title) {
  2546. $insert_data['act_title'] = $act_title;
  2547. }
  2548. if ($act_content) {
  2549. $insert_data['act_content'] = $act_content;
  2550. }
  2551. if ($act_duration) {
  2552. $insert_data['act_duration'] = $act_duration;
  2553. }
  2554. if ($video_url) {
  2555. $insert_data['origin_video_url'] = $video_url;
  2556. $insert_data['current_type'] = 2;
  2557. $compressed_video_url = compressVideo($video_url);
  2558. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2559. }
  2560. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2561. if (!$id) {
  2562. Utils::throwError('20003:新增片段失败!');
  2563. }
  2564. DB::commit();
  2565. }catch (\Exception $e) {
  2566. DB::rollBack();
  2567. Utils::throwError('20003:'.$e->getMessage());
  2568. }
  2569. $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();
  2570. $segment = $segment ? (array)$segment : [];
  2571. return $segment;
  2572. }
  2573. public function editAct($data) {
  2574. $act_id = getProp($data, 'act_id');
  2575. $act_content = getProp($data, 'act_content');
  2576. $act_duration = getProp($data, 'act_duration');
  2577. $act_title = getProp($data, 'act_title');
  2578. $image_url = getProp($data, 'image_url');
  2579. $video_url = getProp($data, 'video_url');
  2580. // 参数验证
  2581. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2582. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2583. $segment = DB::table('mp_episode_segments')
  2584. ->where('id', $act_id)
  2585. ->first();
  2586. if (!$segment) Utils::throwError('20003:该片段不存在');
  2587. try {
  2588. DB::beginTransaction();
  2589. // 准备更新数据
  2590. $update_data = [
  2591. 'updated_at' => date('Y-m-d H:i:s')
  2592. ];
  2593. // 更新act相关字段
  2594. if (!empty($act_content)) {
  2595. $update_data['act_show_content'] = $act_content;
  2596. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2597. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2598. $shot_counter = 0;
  2599. $update_data['act_show_content'] = preg_replace_callback(
  2600. '/【(?:镜头|分镜)(\d+)】/u',
  2601. function($matches) use (&$shot_counter) {
  2602. $shot_counter++;
  2603. return '【镜头' . $shot_counter . '】';
  2604. },
  2605. $update_data['act_show_content']
  2606. );
  2607. }
  2608. if (!empty($act_duration)) {
  2609. $update_data['act_duration'] = $act_duration;
  2610. }
  2611. if (!empty($act_title)) {
  2612. $update_data['act_title'] = $act_title;
  2613. }
  2614. // 处理图片上传
  2615. if ($image_url) {
  2616. $update_data['img_url'] = $image_url;
  2617. $update_data['current_type'] = 1;
  2618. // 同时写入一个图片生成任务记录
  2619. if ($act_id) {
  2620. $pic_task = [
  2621. 'alias_act_id' => $act_id,
  2622. 'ref_img_url' => json_encode([]),
  2623. 'status' => 'success',
  2624. 'result_url' => json_encode([$image_url], 256),
  2625. 'model' => '',
  2626. 'created_at' => date('Y-m-d H:i:s'),
  2627. 'updated_at' => date('Y-m-d H:i:s'),
  2628. ];
  2629. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2630. }
  2631. }
  2632. // 处理视频上传
  2633. if ($video_url) {
  2634. $update_data['origin_video_url'] = $video_url;
  2635. $compressed_video_url = compressVideo($video_url);
  2636. $update_data['current_type'] = 2;
  2637. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2638. // 同时写入一个视频生成任务记录
  2639. if ($act_id) {
  2640. $video_task = [
  2641. 'alias_act_id' => $act_id,
  2642. 'status' => 'success',
  2643. 'result_url' => $update_data['origin_video_url'],
  2644. 'compressed_url' => $update_data['video_url'],
  2645. 'created_at' => date('Y-m-d H:i:s'),
  2646. 'updated_at' => date('Y-m-d H:i:s'),
  2647. ];
  2648. DB::table('mp_generate_video_tasks')->insert($video_task);
  2649. }
  2650. }
  2651. // 更新片段信息
  2652. $result = DB::table('mp_episode_segments')
  2653. ->where('id', $act_id)
  2654. ->update($update_data);
  2655. if ($result === false) {
  2656. Utils::throwError('20003:更新片段失败');
  2657. }
  2658. DB::commit();
  2659. // 返回新复制的记录
  2660. $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();
  2661. $new_segment = (array)$new_segment;
  2662. return $new_segment;
  2663. } catch (\Exception $e) {
  2664. DB::rollBack();
  2665. dLog('anime')->error('更新片段失败', [
  2666. 'act_id' => $act_id,
  2667. 'error' => $e->getMessage()
  2668. ]);
  2669. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2670. }
  2671. }
  2672. public function copyAct($data) {
  2673. $act_id = getProp($data, 'act_id');
  2674. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2675. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2676. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2677. $anime_id = getProp($source_segment, 'anime_id');
  2678. $episode_id = getProp($source_segment, 'episode_id');
  2679. $episode_number = getProp($source_segment, 'episode_number');
  2680. $act_number = getProp($source_segment, 'act_number');
  2681. try {
  2682. DB::beginTransaction();
  2683. // 新act的编号
  2684. $new_act_number = $act_number + 1;
  2685. // 更新后续所有act的act_number
  2686. DB::table('mp_episode_segments')
  2687. ->where('anime_id', $anime_id)
  2688. ->where('episode_id', $episode_id)
  2689. ->where('act_number', '>', $act_number)
  2690. ->increment('act_number');
  2691. // 复制该片段记录
  2692. $segment_data = (array)$source_segment;
  2693. unset($segment_data['id']);
  2694. $segment_data['video_url'] = '';
  2695. $segment_data['video_task_id'] = '';
  2696. $segment_data['video_task_status'] = '';
  2697. $segment_data['act_number'] = $new_act_number;
  2698. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2699. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2700. if (!$id) {
  2701. Utils::throwError('20003:复制片段失败');
  2702. }
  2703. DB::commit();
  2704. }catch (\Exception $e) {
  2705. DB::rollBack();
  2706. Utils::throwError('20003:'.$e->getMessage());
  2707. }
  2708. // 返回新复制的记录
  2709. $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();
  2710. $new_segment = $new_segment ? (array)$new_segment : [];
  2711. $new_segment['act_id'] = $id;
  2712. return $new_segment;
  2713. }
  2714. public function moveAct($data) {
  2715. $act_id = getProp($data, 'act_id');
  2716. $target_act_id = getProp($data, 'target_act_id');
  2717. // 获取源片段信息
  2718. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2719. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2720. // 获取目标片段信息
  2721. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2722. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2723. $anime_id = getProp($source_segment, 'anime_id');
  2724. $episode_id = getProp($source_segment, 'episode_id');
  2725. $source_act_number = getProp($source_segment, 'act_number');
  2726. $target_act_number = getProp($target_segment, 'act_number');
  2727. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2728. $target_anime_id = getProp($target_segment, 'anime_id');
  2729. $target_episode_id = getProp($target_segment, 'episode_id');
  2730. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2731. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2732. }
  2733. // 如果源片段和目标片段相同,无需移动
  2734. if ($source_act_number == $target_act_number) {
  2735. return true;
  2736. }
  2737. try {
  2738. DB::beginTransaction();
  2739. if ($source_act_number < $target_act_number) {
  2740. // 向后移动:源片段移动到目标片段之后
  2741. // 1. 将源片段和目标片段之间的所有片段编号减1
  2742. DB::table('mp_episode_segments')
  2743. ->where('anime_id', $anime_id)
  2744. ->where('episode_id', $episode_id)
  2745. ->where('act_number', '>', $source_act_number)
  2746. ->where('act_number', '<=', $target_act_number)
  2747. ->decrement('act_number');
  2748. // 2. 将源片段移动到目标片段之后
  2749. $new_act_number = $target_act_number;
  2750. } else {
  2751. // 向前移动:源片段移动到目标片段之后
  2752. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2753. DB::table('mp_episode_segments')
  2754. ->where('anime_id', $anime_id)
  2755. ->where('episode_id', $episode_id)
  2756. ->where('act_number', '>', $target_act_number)
  2757. ->where('act_number', '<', $source_act_number)
  2758. ->increment('act_number');
  2759. // 2. 将源片段移动到目标片段之后
  2760. $new_act_number = $target_act_number + 1;
  2761. }
  2762. // 3. 更新源片段的编号
  2763. $update_result = DB::table('mp_episode_segments')
  2764. ->where('id', $act_id)
  2765. ->update([
  2766. 'act_number' => $new_act_number,
  2767. 'updated_at' => date('Y-m-d H:i:s')
  2768. ]);
  2769. if (!$update_result) {
  2770. Utils::throwError('20003:更新片段编号失败');
  2771. }
  2772. DB::commit();
  2773. return true;
  2774. } catch (\Exception $e) {
  2775. DB::rollBack();
  2776. Utils::throwError('20003:' . $e->getMessage());
  2777. }
  2778. }
  2779. public function delAct($data) {
  2780. $act_id = getProp($data, 'act_id');
  2781. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2782. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2783. if (!$segment) Utils::throwError('20003:请选择片段');
  2784. $anime_id = getProp($segment, 'anime_id');
  2785. $episode_id = getProp($segment, 'episode_id');
  2786. $act_number = getProp($segment, 'act_number');
  2787. try {
  2788. DB::beginTransaction();
  2789. // 删除该片段记录
  2790. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2791. if (!$deleted) {
  2792. Utils::throwError('20003:删除片段失败');
  2793. }
  2794. // 更新后续act的编号
  2795. DB::table('mp_episode_segments')
  2796. ->where('anime_id', $anime_id)
  2797. ->where('episode_id', $episode_id)
  2798. ->where('act_number', '>', $act_number)
  2799. ->decrement('act_number');
  2800. DB::commit();
  2801. }catch (\Exception $e) {
  2802. DB::rollBack();
  2803. Utils::throwError('20003:'.$e->getMessage());
  2804. }
  2805. return true;
  2806. }
  2807. public function applyAct($data) {
  2808. $act_id = getProp($data, 'act_id');
  2809. $url = getProp($data, 'url');
  2810. if (!$act_id) Utils::throwError('20003:请选择片段');
  2811. if (!$url) Utils::throwError('20003:URL不能为空');
  2812. // 获取URL的文件扩展名
  2813. $urlPath = parse_url($url, PHP_URL_PATH);
  2814. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2815. // 定义图片和视频的扩展名
  2816. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2817. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2818. // 判断是图片还是视频
  2819. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2820. if (in_array($extension, $imageExtensions)) {
  2821. // 图片类型
  2822. $updateData['img_url'] = $url;
  2823. $updateData['current_type'] = 1;
  2824. } elseif (in_array($extension, $videoExtensions)) {
  2825. // 视频类型
  2826. $updateData['video_url'] = $url;
  2827. $updateData['current_type'] = 2;
  2828. } else {
  2829. Utils::throwError('20003:不支持的文件类型');
  2830. }
  2831. // 更新片段记录(全能模式下每个act只有一条记录)
  2832. $result = DB::table('mp_episode_segments')
  2833. ->where('id', $act_id)
  2834. ->update($updateData);
  2835. if (!$result) {
  2836. Utils::throwError('20003:更新片段失败');
  2837. }
  2838. return true;
  2839. }
  2840. public function actChatHistory($data) {
  2841. $act_id = getProp($data, 'act_id');
  2842. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2843. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2844. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2845. $value = (array)$value;
  2846. $value['created_at'] = transDate($value['created_at']);
  2847. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2848. else $value['reference_images'] = [];
  2849. return $value;
  2850. })->toArray();
  2851. // 获取历史图片
  2852. $url = [];
  2853. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2854. foreach($pic_history as $task) {
  2855. $result_url = getProp($task, 'result_url');
  2856. if (is_json($result_url)) {
  2857. $url = array_merge($url, json_decode($result_url, true));
  2858. }else {
  2859. $url[] = $result_url;
  2860. }
  2861. }
  2862. // 获取历史视频
  2863. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2864. foreach($video_history as $task) {
  2865. $result_url = getProp($task, 'result_url');
  2866. if (is_json($result_url)) {
  2867. $url = array_merge($url, json_decode($result_url, true));
  2868. }else {
  2869. $url[] = $result_url;
  2870. }
  2871. }
  2872. // 获取资产库
  2873. $products = [];
  2874. // 通过act_id查询片段信息获取episode_id
  2875. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2876. if ($segment) {
  2877. $episode_id = getProp($segment, 'episode_id');
  2878. // 查询剧集信息获取roles、scenes和extra_products
  2879. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2880. if ($episode) {
  2881. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2882. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2883. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2884. // 先合并roles和scenes
  2885. // 处理角色数组
  2886. foreach ($roles as $role) {
  2887. $product = $role;
  2888. // 将role字段重命名为product_name
  2889. if (isset($product['role'])) {
  2890. $product['product_name'] = $product['role'];
  2891. unset($product['role']);
  2892. }
  2893. $product['product'] = 1; // 标记类型为角色
  2894. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2895. }
  2896. // 处理场景数组
  2897. foreach ($scenes as $scene) {
  2898. $product = $scene;
  2899. // 将scene字段重命名为product_name
  2900. if (isset($product['scene'])) {
  2901. $product['product_name'] = $product['scene'];
  2902. unset($product['scene']);
  2903. }
  2904. $product['product'] = 2; // 标记类型为场景
  2905. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2906. }
  2907. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2908. foreach ($extra_products as $extra_product) {
  2909. $product_name = getProp($extra_product, 'product_name');
  2910. if ($product_name) {
  2911. $products[$product_name] = $extra_product; // 覆盖同名数据
  2912. }
  2913. }
  2914. // 重新索引数组(去除key)
  2915. $products = array_values($products);
  2916. }
  2917. }
  2918. // 获取执行中的任务
  2919. $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) {
  2920. $value = (array)$value;
  2921. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2922. else $value['ref_image_url'] = [];
  2923. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2924. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2925. if (!empty($value['prompt'])) {
  2926. $prompt = $value['prompt'];
  2927. // 查找第一个【镜头】的位置
  2928. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2929. // 从【镜头】开始截取
  2930. $prompt = substr($prompt, $matches[0][1]);
  2931. }
  2932. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2933. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2934. $value['prompt'] = $prompt;
  2935. }
  2936. return $value;
  2937. })->toArray();
  2938. return compact('chat', 'url', 'products', 'tasks');
  2939. }
  2940. public function applyAudioData($data) {
  2941. $segment_id = getProp($data, 'segment_id');
  2942. $global_data = getProp($data, 'global_data');
  2943. $segment_data = getProp($data, 'segment_data');
  2944. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2945. $global_data = is_array($global_data) ? $global_data : [];
  2946. $segment_data = is_array($segment_data) ? $segment_data : [];
  2947. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2948. $dialogue_item = null;
  2949. foreach ($global_data as $key => $item) {
  2950. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2951. $dialogue_item = $item;
  2952. unset($global_data[$key]);
  2953. break;
  2954. }
  2955. }
  2956. if ($dialogue_item) {
  2957. $segment_data[] = $dialogue_item;
  2958. }
  2959. // 特殊参数: audio_url,audio_duration,subtitle_info
  2960. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2961. // 如果不是全部存在,则仍需创建音频任务
  2962. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2963. $special_update_data = [];
  2964. $has_all_special_params = false;
  2965. // 从segment_data中提取特殊参数
  2966. $filtered_segment_data = [];
  2967. foreach ($segment_data as $item) {
  2968. $field_name = trim((string)getProp($item, 'name'));
  2969. if (in_array($field_name, $special_fields)) {
  2970. $special_update_data[$field_name] = getProp($item, 'value');
  2971. } else {
  2972. // 非特殊参数保留,继续后续处理
  2973. $filtered_segment_data[] = $item;
  2974. }
  2975. }
  2976. // 检查是否三个特殊参数都存在
  2977. if (count($special_update_data) === 3 &&
  2978. isset($special_update_data['audio_url']) &&
  2979. isset($special_update_data['audio_duration']) &&
  2980. isset($special_update_data['subtitle_info'])) {
  2981. $has_all_special_params = true;
  2982. // 立即更新到当前分镜
  2983. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  2984. DB::table('mp_episode_segments')
  2985. ->where('segment_id', $segment_id)
  2986. ->update($special_update_data);
  2987. }
  2988. // 使用过滤后的segment_data继续处理其他参数
  2989. $segment_data = $filtered_segment_data;
  2990. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  2991. $global_update_data = [];
  2992. $segment_update_data = [];
  2993. $global_voice_type = '';
  2994. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2995. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  2996. $episode_id = getProp($target_segment, 'episode_id');
  2997. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  2998. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2999. if (!$episode) Utils::throwError('20003:分集不存在');
  3000. foreach ($global_data as $item) {
  3001. $field_name = trim((string)getProp($item, 'name'));
  3002. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3003. continue;
  3004. }
  3005. $global_update_data[$field_name] = getProp($item, 'value');
  3006. if ($field_name === 'voice_type') {
  3007. $global_voice_type = trim((string)getProp($item, 'value'));
  3008. }
  3009. }
  3010. foreach ($segment_data as $item) {
  3011. $field_name = trim((string)getProp($item, 'name'));
  3012. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3013. continue;
  3014. }
  3015. $segment_update_data[$field_name] = getProp($item, 'value');
  3016. }
  3017. if ($global_voice_type) {
  3018. $timbre_info = DB::table('mp_timbres')
  3019. ->where('timbre_type', $global_voice_type)
  3020. ->select('audio_url', 'timbre_name')
  3021. ->first();
  3022. if ($timbre_info) {
  3023. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3024. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3025. }
  3026. }
  3027. try {
  3028. DB::beginTransaction();
  3029. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3030. $segment_ids_to_create_task = [];
  3031. $segments_data = [];
  3032. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3033. if (!empty($global_update_data)) {
  3034. // 如果角色不存在,则只更新当前分镜
  3035. if (!$target_voice_actor) {
  3036. // 只处理当前分镜
  3037. $affected_segments = DB::table('mp_episode_segments')
  3038. ->where('segment_id', $segment_id)
  3039. ->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')
  3040. ->get();
  3041. } else {
  3042. // 获取该角色的所有分镜
  3043. $affected_segments = DB::table('mp_episode_segments')
  3044. ->where('episode_id', $episode_id)
  3045. ->where('voice_actor', $target_voice_actor)
  3046. ->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')
  3047. ->get();
  3048. }
  3049. foreach ($affected_segments as $seg) {
  3050. $seg = (array)$seg;
  3051. $sid = getProp($seg, 'segment_id');
  3052. // 检查参数是否发生变化
  3053. $has_changed = false;
  3054. foreach ($global_update_data as $field => $new_value) {
  3055. $old_value = getProp($seg, $field);
  3056. if ($old_value != $new_value) {
  3057. $has_changed = true;
  3058. break;
  3059. }
  3060. }
  3061. if ($has_changed) {
  3062. $segment_ids_to_create_task[] = $sid;
  3063. $segments_data[$sid] = $seg;
  3064. }
  3065. }
  3066. // 只有在有变化的分镜时才更新
  3067. if (!empty($segment_ids_to_create_task)) {
  3068. $global_segment_update_data = $global_update_data;
  3069. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3070. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3071. DB::table('mp_episode_segments')
  3072. ->where('episode_id', $episode_id)
  3073. ->where('voice_actor', $target_voice_actor)
  3074. ->whereIn('segment_id', $segment_ids_to_create_task)
  3075. ->update($global_segment_update_data);
  3076. }
  3077. if ($global_voice_type) {
  3078. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3079. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3080. $roles_updated = false;
  3081. foreach ($episode_roles as &$role) {
  3082. // 通过 role 字段匹配角色名,而不是 voice_name
  3083. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3084. continue;
  3085. }
  3086. $role['voice_type'] = $global_voice_type;
  3087. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3088. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3089. $roles_updated = true;
  3090. }
  3091. unset($role);
  3092. if ($roles_updated) {
  3093. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3094. 'roles' => json_encode($episode_roles, 256),
  3095. 'updated_at' => date('Y-m-d H:i:s'),
  3096. ]);
  3097. }
  3098. }
  3099. }
  3100. // 如果有单个分镜更新,检查是否有变化
  3101. if (!empty($segment_update_data)) {
  3102. // 获取当前分镜数据
  3103. $current_segment = DB::table('mp_episode_segments')
  3104. ->where('segment_id', $segment_id)
  3105. ->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')
  3106. ->first();
  3107. if ($current_segment) {
  3108. $current_segment = (array)$current_segment;
  3109. // 检查参数是否发生变化
  3110. $has_changed = false;
  3111. foreach ($segment_update_data as $field => $new_value) {
  3112. $old_value = getProp($current_segment, $field);
  3113. if ($old_value != $new_value) {
  3114. $has_changed = true;
  3115. break;
  3116. }
  3117. }
  3118. if ($has_changed) {
  3119. // 如果该分镜还未在列表中,添加进去
  3120. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3121. $segment_ids_to_create_task[] = $segment_id;
  3122. $segments_data[$segment_id] = $current_segment;
  3123. }
  3124. // 更新分镜数据并清空音频URL
  3125. $segment_update_data['audio_url'] = '';
  3126. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3127. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3128. }
  3129. }
  3130. }
  3131. // 为所有有变化的分镜创建音频合成任务
  3132. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3133. if (!empty($segment_ids_to_create_task)) {
  3134. foreach ($segment_ids_to_create_task as $sid) {
  3135. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3136. if ($sid === $segment_id && $has_all_special_params) {
  3137. continue;
  3138. }
  3139. // 重新获取更新后的分镜数据
  3140. $updated_segment = DB::table('mp_episode_segments')
  3141. ->where('segment_id', $sid)
  3142. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3143. ->first();
  3144. if (!$updated_segment) continue;
  3145. $updated_segment = (array)$updated_segment;
  3146. // 检查dialogue是否为空
  3147. $dialogue = getProp($updated_segment, 'dialogue');
  3148. if (empty($dialogue)) {
  3149. // dialogue为空时,直接写入默认音频信息
  3150. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3151. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3152. 'audio_duration' => 2.0,
  3153. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3154. 'updated_at' => date('Y-m-d H:i:s')
  3155. ]);
  3156. continue;
  3157. }
  3158. $generate_json = [
  3159. 'text' => $dialogue,
  3160. 'role' => getProp($updated_segment, 'voice_actor'),
  3161. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3162. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3163. 'emotion' => getProp($updated_segment, 'emotion'),
  3164. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3165. 'gender' => getProp($updated_segment, 'gender'),
  3166. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3167. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3168. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3169. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3170. ];
  3171. // 插入视频配音合成任务
  3172. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3173. 'alias_segment_id' => $sid,
  3174. 'generate_status' => '执行中',
  3175. 'audio_url' => '',
  3176. 'generate_json' => json_encode($generate_json, 256),
  3177. 'created_at' => date('Y-m-d H:i:s'),
  3178. 'updated_at' => date('Y-m-d H:i:s'),
  3179. ]);
  3180. if (!$dubTaskId) {
  3181. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3182. continue;
  3183. }
  3184. // 将任务ID添加到Redis列表中
  3185. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3186. // 请求远程服务器执行生成
  3187. try {
  3188. sleep(1);
  3189. $client = new Client(['timeout' => 300, 'verify' => false]);
  3190. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3191. $response = $result->getBody()->getContents();
  3192. $response_arr = json_decode($response, true);
  3193. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3194. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3195. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3196. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3197. }
  3198. } catch (\Exception $e) {
  3199. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3200. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3201. }
  3202. }
  3203. }
  3204. DB::commit();
  3205. } catch (\Exception $e) {
  3206. DB::rollBack();
  3207. Utils::throwError('20003:'.$e->getMessage());
  3208. }
  3209. return true;
  3210. }
  3211. public function episodePicsInfo($data) {
  3212. $anime_id = getProp($data, 'anime_id');
  3213. $episode_id = getProp($data, 'episode_id');
  3214. // 参数验证
  3215. if (!$anime_id && !$episode_id) {
  3216. Utils::throwError('20003:请提供动漫ID或分集ID');
  3217. }
  3218. // 根据参数获取数据源
  3219. if ($episode_id) {
  3220. // 从剧集表获取
  3221. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3222. if (!$source) Utils::throwError('20003:该剧集不存在');
  3223. $table_name = 'mp_anime_episodes';
  3224. $id_field = 'id';
  3225. $id_value = $episode_id;
  3226. // 获取剧集的anime_id用于继承全局数据
  3227. $anime_id = getProp($source, 'anime_id');
  3228. } else {
  3229. // 从动漫表获取
  3230. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3231. if (!$source) Utils::throwError('20003:该动漫不存在');
  3232. $table_name = 'mp_animes';
  3233. $id_field = 'id';
  3234. $id_value = $anime_id;
  3235. }
  3236. $source = (array)$source;
  3237. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3238. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3239. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3240. // 如果是分集数据,需要处理继承和任务创建逻辑
  3241. if ($episode_id) {
  3242. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3243. }
  3244. // 返回生成器函数,用于 SSE 流式输出
  3245. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3246. $startTime = time();
  3247. $maxDuration = 600; // 10分钟超时
  3248. $checkInterval = 3; // 每3秒检查一次
  3249. // Redis 缓存键
  3250. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3251. // 生成当前数据的哈希值用于比较
  3252. $generateHash = function($roles, $scenes, $props) {
  3253. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3254. };
  3255. // 发送初始数据
  3256. $currentHash = $generateHash($roles, $scenes, $props);
  3257. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3258. echo "data: " . json_encode([
  3259. 'type' => 'init',
  3260. 'data' => [
  3261. 'roles' => $roles,
  3262. 'scenes' => $scenes,
  3263. 'props' => $props,
  3264. 'start_time' => $startTime
  3265. ]
  3266. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3267. if (ob_get_level() > 0) {
  3268. ob_flush();
  3269. }
  3270. flush();
  3271. // 持续轮询任务状态
  3272. while (time() - $startTime < $maxDuration) {
  3273. $hasProcessing = false;
  3274. $updated = false;
  3275. // 检查角色任务状态
  3276. foreach ($roles as $index => &$role) {
  3277. $task_id = getProp($role, 'task_id');
  3278. $task_status = getProp($role, 'task_status');
  3279. $existing_url = getProp($role, 'url');
  3280. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3281. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3282. $hasProcessing = ($task_status === 'processing');
  3283. // 查询任务状态
  3284. $task = DB::table('mp_generate_pic_tasks')
  3285. ->where('id', $task_id)
  3286. ->select('id', 'status', 'result_url', 'error_message')
  3287. ->first();
  3288. if ($task) {
  3289. $task = (array)$task;
  3290. $status = getProp($task, 'status');
  3291. // 如果任务完成或失败
  3292. if (in_array($status, ['success', 'failed'])) {
  3293. $role['task_status'] = $status;
  3294. if ($status === 'success') {
  3295. $result_url = getProp($task, 'result_url');
  3296. if ($result_url) {
  3297. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3298. if (is_array($result_urls) && !empty($result_urls[0])) {
  3299. $role['url'] = $result_urls[0];
  3300. }
  3301. }
  3302. }
  3303. $updated = true;
  3304. } else if ($status === 'processing') {
  3305. $hasProcessing = true;
  3306. }
  3307. }
  3308. }
  3309. }
  3310. // 检查场景任务状态
  3311. foreach ($scenes as $index => &$scene) {
  3312. $task_id = getProp($scene, 'task_id');
  3313. $task_status = getProp($scene, 'task_status');
  3314. $existing_url = getProp($scene, 'url');
  3315. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3316. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3317. $hasProcessing = ($task_status === 'processing');
  3318. // 查询任务状态
  3319. $task = DB::table('mp_generate_pic_tasks')
  3320. ->where('id', $task_id)
  3321. ->select('id', 'status', 'result_url', 'error_message')
  3322. ->first();
  3323. if ($task) {
  3324. $task = (array)$task;
  3325. $status = getProp($task, 'status');
  3326. // 如果任务完成或失败
  3327. if (in_array($status, ['success', 'failed'])) {
  3328. $scene['task_status'] = $status;
  3329. if ($status === 'success') {
  3330. $result_url = getProp($task, 'result_url');
  3331. if ($result_url) {
  3332. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3333. if (is_array($result_urls) && !empty($result_urls[0])) {
  3334. $scene['url'] = $result_urls[0];
  3335. }
  3336. }
  3337. }
  3338. $updated = true;
  3339. } else if ($status === 'processing') {
  3340. $hasProcessing = true;
  3341. }
  3342. }
  3343. }
  3344. }
  3345. // 检查道具任务状态
  3346. foreach ($props as $index => &$prop) {
  3347. $task_id = getProp($prop, 'task_id');
  3348. $task_status = getProp($prop, 'task_status');
  3349. $existing_url = getProp($prop, 'url');
  3350. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3351. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3352. $hasProcessing = ($task_status === 'processing');
  3353. // 查询任务状态
  3354. $task = DB::table('mp_generate_pic_tasks')
  3355. ->where('id', $task_id)
  3356. ->select('id', 'status', 'result_url', 'error_message')
  3357. ->first();
  3358. if ($task) {
  3359. $task = (array)$task;
  3360. $status = getProp($task, 'status');
  3361. // 如果任务完成或失败
  3362. if (in_array($status, ['success', 'failed'])) {
  3363. $prop['task_status'] = $status;
  3364. if ($status === 'success') {
  3365. $result_url = getProp($task, 'result_url');
  3366. if ($result_url) {
  3367. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3368. if (is_array($result_urls) && !empty($result_urls[0])) {
  3369. $prop['url'] = $result_urls[0];
  3370. }
  3371. }
  3372. }
  3373. $updated = true;
  3374. } else if ($status === 'processing') {
  3375. $hasProcessing = true;
  3376. }
  3377. }
  3378. }
  3379. }
  3380. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3381. if ($updated) {
  3382. $newHash = $generateHash($roles, $scenes, $props);
  3383. $cachedHash = Redis::get($cacheKey);
  3384. // 只有当数据真正变化时才更新数据库和发送事件
  3385. if ($newHash !== $cachedHash) {
  3386. try {
  3387. // 更新数据库
  3388. DB::table($table_name)->where($id_field, $id_value)->update([
  3389. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3390. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3391. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3392. 'updated_at' => date('Y-m-d H:i:s')
  3393. ]);
  3394. // 更新缓存
  3395. Redis::setex($cacheKey, 600, $newHash);
  3396. // 发送更新事件
  3397. echo "data: " . json_encode([
  3398. 'type' => 'update',
  3399. 'data' => [
  3400. 'roles' => $roles,
  3401. 'scenes' => $scenes,
  3402. 'props' => $props,
  3403. 'elapsed_time' => time() - $startTime
  3404. ]
  3405. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3406. if (ob_get_level() > 0) {
  3407. ob_flush();
  3408. }
  3409. flush();
  3410. } catch (\Exception $e) {
  3411. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3412. }
  3413. } else {
  3414. // 即使哈希相同,如果有URL更新也要发送事件
  3415. $hasUrlUpdate = false;
  3416. foreach ($roles as $role) {
  3417. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3418. $hasUrlUpdate = true;
  3419. break;
  3420. }
  3421. }
  3422. if (!$hasUrlUpdate) {
  3423. foreach ($scenes as $scene) {
  3424. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3425. $hasUrlUpdate = true;
  3426. break;
  3427. }
  3428. }
  3429. }
  3430. if (!$hasUrlUpdate) {
  3431. foreach ($props as $prop) {
  3432. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3433. $hasUrlUpdate = true;
  3434. break;
  3435. }
  3436. }
  3437. }
  3438. if ($hasUrlUpdate) {
  3439. // 强制更新数据库和发送事件
  3440. try {
  3441. DB::table($table_name)->where($id_field, $id_value)->update([
  3442. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3443. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3444. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3445. 'updated_at' => date('Y-m-d H:i:s')
  3446. ]);
  3447. // 更新缓存
  3448. Redis::setex($cacheKey, 600, $newHash);
  3449. // 发送更新事件
  3450. echo "data: " . json_encode([
  3451. 'type' => 'update',
  3452. 'data' => [
  3453. 'roles' => $roles,
  3454. 'scenes' => $scenes,
  3455. 'props' => $props,
  3456. 'elapsed_time' => time() - $startTime
  3457. ]
  3458. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3459. if (ob_get_level() > 0) {
  3460. ob_flush();
  3461. }
  3462. flush();
  3463. } catch (\Exception $e) {
  3464. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3465. }
  3466. }
  3467. }
  3468. }
  3469. // 如果所有任务都已完成,发送完成事件并退出
  3470. if (!$hasProcessing) {
  3471. // 查询数据库中的最终数据,确保返回最新的完整数据
  3472. try {
  3473. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3474. if ($finalSource) {
  3475. $finalSource = (array)$finalSource;
  3476. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3477. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3478. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3479. // 使用数据库中的最终数据
  3480. $roles = $finalRoles;
  3481. $scenes = $finalScenes;
  3482. $props = $finalProps;
  3483. }
  3484. } catch (\Exception $e) {
  3485. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3486. // 如果查询失败,继续使用内存中的数据
  3487. }
  3488. // 清理缓存
  3489. Redis::del($cacheKey);
  3490. echo "data: " . json_encode([
  3491. 'type' => 'completed',
  3492. 'data' => [
  3493. 'roles' => $roles,
  3494. 'scenes' => $scenes,
  3495. 'props' => $props,
  3496. 'total_time' => time() - $startTime
  3497. ]
  3498. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3499. if (ob_get_level() > 0) {
  3500. ob_flush();
  3501. }
  3502. flush();
  3503. break;
  3504. }
  3505. // 等待下次检查
  3506. sleep($checkInterval);
  3507. }
  3508. // 超时处理
  3509. if (time() - $startTime >= $maxDuration) {
  3510. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3511. try {
  3512. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3513. if ($finalSource) {
  3514. $finalSource = (array)$finalSource;
  3515. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3516. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3517. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3518. // 使用数据库中的最终数据
  3519. $roles = $finalRoles;
  3520. $scenes = $finalScenes;
  3521. $props = $finalProps;
  3522. }
  3523. } catch (\Exception $e) {
  3524. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3525. // 如果查询失败,继续使用内存中的数据
  3526. }
  3527. // 清理缓存
  3528. Redis::del($cacheKey);
  3529. echo "data: " . json_encode([
  3530. 'type' => 'timeout',
  3531. 'message' => '轮询超时,请刷新页面查看最新状态',
  3532. 'data' => [
  3533. 'roles' => $roles,
  3534. 'scenes' => $scenes,
  3535. 'props' => $props
  3536. ]
  3537. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3538. if (ob_get_level() > 0) {
  3539. ob_flush();
  3540. }
  3541. flush();
  3542. }
  3543. };
  3544. }
  3545. public function clipSegmentVideo($data) {
  3546. $segment_id = getProp($data, 'segment_id');
  3547. $video_time_point_start = getProp($data, 'video_time_point_start');
  3548. $video_time_point_end = getProp($data, 'video_time_point_end');
  3549. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3550. Utils::throwError('20003:参数异常');
  3551. }
  3552. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3553. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3554. }
  3555. $video_duration = $video_time_point_end - $video_time_point_start;
  3556. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3557. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3558. 'video_duration' => $video_duration,
  3559. 'video_time_point_start' => $video_time_point_start,
  3560. 'video_time_point_end' => $video_time_point_end,
  3561. 'updated_at' => date('Y-m-d H:i:s')
  3562. ]);
  3563. }
  3564. // 轮训获取图片任务结果
  3565. private function loopGetPicTaskResult($task_id) {
  3566. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3567. if (!$task) {
  3568. return '';
  3569. }
  3570. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3571. $model = getProp($task, 'model');
  3572. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3573. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3574. $isSyncModel = $isVolcModel || $isGptModel;
  3575. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3576. $start_count = 0;
  3577. $img_url = '';
  3578. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3579. sleep(3);
  3580. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3581. // 如果任务已经完成,直接返回结果
  3582. if ($task->status === 'success' && $task->result_url) {
  3583. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3584. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3585. }
  3586. // 如果任务已失败,返回空
  3587. if ($task->status === 'failed') {
  3588. return '';
  3589. }
  3590. if ($isSyncModel) continue;
  3591. // 查询任务状态
  3592. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3593. if ($statusInfo['status'] === 'success') {
  3594. $task->updateStatus('success', [
  3595. 'result_url' => $statusInfo['result_url'],
  3596. 'result_json' => $statusInfo['result_json'] ?? []
  3597. ]);
  3598. // 同步调整分镜图片状态和结果
  3599. if (getProp($task, 'alias_segment_id')) {
  3600. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3601. 'img_url' => $statusInfo['result_url'][0],
  3602. 'pic_task_status' => '已完成',
  3603. ]);
  3604. }
  3605. $img_url = $statusInfo['result_url'][0];
  3606. break;
  3607. } elseif ($statusInfo['status'] === 'failed') {
  3608. $task->updateStatus('failed', [
  3609. 'error_message' => $statusInfo['error_message'],
  3610. 'result_json' => $statusInfo['result_json'] ?? []
  3611. ]);
  3612. if (getProp($task, 'alias_segment_id')) {
  3613. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3614. 'pic_task_status' => '失败',
  3615. ]);
  3616. }
  3617. break;
  3618. }
  3619. $start_count++;
  3620. }
  3621. return $img_url;
  3622. }
  3623. /**
  3624. * 从分镜内容中提取涉及的角色
  3625. */
  3626. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3627. $found_characters = [];
  3628. foreach ($available_characters as $character) {
  3629. // 检查角色名称是否在分镜内容中出现
  3630. if (strpos($segment_content, $character) !== false) {
  3631. $found_characters[] = $character;
  3632. }
  3633. }
  3634. if (!$found_characters) {
  3635. foreach ($roles as $character) {
  3636. // 检查角色名称是否在分镜内容中出现
  3637. if (strpos($segment_content, $character) !== false) {
  3638. $found_characters[] = $character;
  3639. }
  3640. }
  3641. }
  3642. return array_unique($found_characters);
  3643. }
  3644. // 从分镜剧本中提取关键字段
  3645. private function handleSegmentContent(&$data) {
  3646. $segmentContent = getProp($data, 'segment_content');
  3647. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3648. $segmentData = [
  3649. 'description' => '',
  3650. 'composition' => '',
  3651. 'camera_movement' => '',
  3652. 'voice_actor' => '',
  3653. 'dialogue' => '',
  3654. 'frame_type' => '',
  3655. 'scene' => '', // 场景
  3656. 'characters' => '', // 出镜角色
  3657. 'tail_frame' => '', // 尾帧描述
  3658. 'emotion' => '中性', // 情感
  3659. 'gender' => '0', // 性别(0未知,1男,2女)
  3660. 'speed_ratio' => 0, // 语速
  3661. 'loudness_ratio' => 0, // 音量
  3662. 'emotion_scale' => 4, // 情感强度
  3663. 'pitch' => 0, // 音调
  3664. ];
  3665. // 用于存储需要从 segment_content 中移除的匹配项
  3666. $replaceEmptyArr = [];
  3667. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3668. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3669. $segmentData['description'] = trim($descMatch[1]);
  3670. $data['description'] = trim($descMatch[1]);
  3671. }
  3672. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3673. $segmentData['composition'] = trim($compMatch[1]);
  3674. $data['composition'] = trim($compMatch[1]);
  3675. }
  3676. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3677. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3678. $data['camera_movement'] = trim($cameraMatch[1]);
  3679. }
  3680. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3681. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3682. $data['voice_actor'] = trim($voiceMatch[1]);
  3683. }
  3684. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3685. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3686. $data['dialogue'] = trim($dialogueMatch[1]);
  3687. }
  3688. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3689. $segmentData['frame_type'] = trim($frameMatch[1]);
  3690. $data['frame_type'] = trim($frameMatch[1]);
  3691. }
  3692. // 场景字段
  3693. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3694. $segmentData['scene'] = trim($sceneMatch[1]);
  3695. $data['scene'] = trim($sceneMatch[1]);
  3696. }
  3697. // 出镜角色字段
  3698. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3699. $segmentData['characters'] = trim($charactersMatch[1]);
  3700. $data['characters'] = trim($charactersMatch[1]);
  3701. }
  3702. // 尾帧描述字段
  3703. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3704. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3705. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3706. }
  3707. // 情感字段
  3708. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3709. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3710. $segmentData['emotion'] = trim($emotionMatch[1]);
  3711. $data['emotion'] = trim($emotionMatch[1]);
  3712. }
  3713. // 性别字段
  3714. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3715. $replaceEmptyArr[] = trim($genderMatch[0]);
  3716. $genderStr = trim($genderMatch[1]);
  3717. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3718. $segmentData['gender'] = '1';
  3719. $data['gender'] = '1';
  3720. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3721. $segmentData['gender'] = '2';
  3722. $data['gender'] = '2';
  3723. } else {
  3724. $segmentData['gender'] = '0';
  3725. $data['gender'] = '0';
  3726. }
  3727. }
  3728. // 语速字段
  3729. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3730. $replaceEmptyArr[] = trim($speedMatch[0]);
  3731. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3732. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3733. }
  3734. // 音量字段
  3735. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3736. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3737. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3738. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3739. }
  3740. // 情感强度字段
  3741. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3742. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3743. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3744. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3745. }
  3746. // 音调字段
  3747. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3748. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3749. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3750. $data['pitch'] = (int)trim($pitchMatch[1]);
  3751. }
  3752. // 从 segment_content 中移除已提取的配音参数字段
  3753. if (!empty($replaceEmptyArr)) {
  3754. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3755. }
  3756. // 如果有配音角色,查询音色信息并验证情感
  3757. $voice_actor = $segmentData['voice_actor'];
  3758. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3759. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3760. $anime_id = getProp($data, 'anime_id');
  3761. $episode_id = getProp($data, 'episode_id');
  3762. // 优先从剧集的角色列表中查找
  3763. $roles = [];
  3764. if ($episode_id) {
  3765. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3766. if ($episode && getProp($episode, 'roles')) {
  3767. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3768. }
  3769. }
  3770. // 如果剧集中没有,从动漫的角色列表中查找
  3771. if (empty($roles) && $anime_id) {
  3772. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3773. if ($anime && getProp($anime, 'roles')) {
  3774. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3775. }
  3776. }
  3777. // 查找匹配的角色音色信息
  3778. $timbre_info = null;
  3779. foreach ($roles as $role) {
  3780. if (getProp($role, 'role') === $voice_actor) {
  3781. $timbre_info = $role;
  3782. break;
  3783. }
  3784. }
  3785. // 如果找到音色信息,添加到数据中
  3786. if ($timbre_info) {
  3787. $voice_type = getProp($timbre_info, 'voice_type');
  3788. $voice_name = getProp($timbre_info, 'voice_name');
  3789. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3790. if ($voice_type) {
  3791. $data['voice_type'] = $voice_type;
  3792. $segmentData['voice_type'] = $voice_type;
  3793. }
  3794. if ($voice_name) {
  3795. $data['voice_name'] = $voice_name;
  3796. $segmentData['voice_name'] = $voice_name;
  3797. }
  3798. if ($voice_audio_url) {
  3799. $data['voice_audio_url'] = $voice_audio_url;
  3800. $segmentData['voice_audio_url'] = $voice_audio_url;
  3801. }
  3802. // 验证情感是否在音色支持的情感列表中
  3803. if ($voice_type) {
  3804. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3805. if ($timbre_emotion) {
  3806. $timbre_emotion = explode(',', $timbre_emotion);
  3807. } else {
  3808. $timbre_emotion = [];
  3809. }
  3810. $emotion = getProp($segmentData, 'emotion', '中性');
  3811. if (!in_array($emotion, $timbre_emotion)) {
  3812. $emotion = '中性';
  3813. }
  3814. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3815. $emotion_list = array_flip($emotion_list);
  3816. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3817. $data['emotion_type'] = $emotion_type;
  3818. $segmentData['emotion_type'] = $emotion_type;
  3819. }
  3820. }
  3821. }
  3822. return $segmentData;
  3823. }
  3824. public function createSegmentVideoTask($data) {
  3825. $segment_id = getProp($data, 'segment_id');
  3826. $tail_frame = getProp($data, 'tail_frame');
  3827. $first_frame_url = getProp($data, 'first_frame_url');
  3828. $tail_frame_url = getProp($data, 'tail_frame_url');
  3829. $generate_audio = getProp($data, 'generate_audio', 0);
  3830. if (!$segment_id) {
  3831. Utils::throwError('1002:分镜ID不能为空');
  3832. }
  3833. // 获取分镜信息
  3834. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3835. if (!$segment) {
  3836. Utils::throwError('20003:分镜不存在');
  3837. }
  3838. $segment = (array)$segment;
  3839. $episode_id = getProp($segment, 'episode_id');
  3840. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3841. if (!$ratio) $ratio = '9:16';
  3842. // 获取分镜内容
  3843. $segmentContent = getProp($segment, 'segment_content', '');
  3844. // 检查 $segmentContent 中是否已有尾帧描述
  3845. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3846. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3847. $finalTailFrame = '';
  3848. if ($tail_frame) {
  3849. // 用户输入了尾帧描述,优先使用
  3850. $finalTailFrame = $tail_frame;
  3851. // 如果 segmentContent 中已有尾帧描述,需要替换
  3852. if ($contentHasTailFrame) {
  3853. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3854. }
  3855. } elseif ($contentHasTailFrame) {
  3856. // segmentContent 中有尾帧描述,使用它
  3857. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3858. } else {
  3859. // 两者都没有,使用分镜表中的尾帧描述
  3860. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3861. }
  3862. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3863. $hasDialogue = false;
  3864. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3865. $dialogue = trim($dialogueMatch[1]);
  3866. // 如果台词不为空且不是"无"
  3867. if (!empty($dialogue) && $dialogue !== '无') {
  3868. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3869. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3870. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3871. $hasDialogue = true;
  3872. }
  3873. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3874. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3875. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3876. if (!preg_match('/^[“]/', $dialogue)) {
  3877. $dialogue = '“' . $dialogue;
  3878. }
  3879. if (!preg_match('/[”]$/', $dialogue)) {
  3880. $dialogue .= '”';
  3881. }
  3882. // 将修改后的台词替换回 $segmentContent
  3883. $originalDialogue = $dialogueMatch[1];
  3884. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3885. }
  3886. }
  3887. // 构建完整的提示词
  3888. $fullPrompt = $segmentContent;
  3889. if ($finalTailFrame && !$contentHasTailFrame) {
  3890. // 只有当 segmentContent 中没有尾帧描述时才追加
  3891. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3892. }
  3893. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3894. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3895. $fullPrompt = trim($fullPrompt);
  3896. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3897. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3898. // 智能选择视频时长
  3899. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3900. $videoDuration = -1;
  3901. // 处理视频模型
  3902. $model = getProp($data, 'model');
  3903. if (!$model) {
  3904. // 用户没有输入,从episode表获取
  3905. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3906. $model = getProp($episode, 'video_model');
  3907. if (!$model) {
  3908. // episode表也没有,使用默认值
  3909. $model = 'doubao-seedance-1-5-pro-251215';
  3910. }
  3911. }
  3912. // 验证模型是否在可用模型表中
  3913. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3914. $model = 'doubao-seedance-1-5-pro-251215';
  3915. }
  3916. // 保存到episode表
  3917. $episode_id = getProp($segment, 'episode_id');
  3918. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3919. 'video_model' => $model,
  3920. 'updated_at' => date('Y-m-d H:i:s')
  3921. ]);
  3922. // 构建视频生成参数
  3923. $videoParams = [
  3924. 'model' => $model,
  3925. 'alias_segment_id' => $segment_id,
  3926. 'prompt' => trim($fullPrompt),
  3927. 'video_duration' => $videoDuration,
  3928. 'video_resolution' => '720P',
  3929. 'seed' => -1,
  3930. 'ratio' => $ratio,
  3931. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3932. 'draft' => false,
  3933. 'watermark' => false,
  3934. 'camera_fixed' => false,
  3935. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3936. ];
  3937. // 如果分镜有图片,作为首帧
  3938. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3939. $hasVideo = !empty(getProp($segment, 'video_url'));
  3940. if ($hasImage) {
  3941. if ($first_frame_url) {
  3942. $videoParams['first_frame_url'] = $first_frame_url;
  3943. }else {
  3944. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3945. }
  3946. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3947. }
  3948. // 构建content数组
  3949. $videoParams['content'] = [
  3950. [
  3951. 'type' => 'text',
  3952. 'text' => $videoParams['prompt'],
  3953. ]
  3954. ];
  3955. // 如果有首帧图片,添加到content中
  3956. if ($hasImage) {
  3957. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3958. $videoParams['content'][] = [
  3959. 'type' => 'image_url',
  3960. 'image_url' => [
  3961. 'url' => $videoParams['first_frame_url'],
  3962. ],
  3963. 'role' => 'reference_image',
  3964. ];
  3965. if (isset($videoParams['tail_frame_url'])) {
  3966. $videoParams['content'][] = [
  3967. 'type' => 'image_url',
  3968. 'image_url' => [
  3969. 'url' => $videoParams['tail_frame_url'],
  3970. ],
  3971. 'role' => 'reference_image',
  3972. ];
  3973. }
  3974. }else {
  3975. $videoParams['content'][] = [
  3976. 'type' => 'image_url',
  3977. 'image_url' => [
  3978. 'url' => $videoParams['first_frame_url'],
  3979. ],
  3980. 'role' => 'first_frame',
  3981. ];
  3982. if (isset($videoParams['tail_frame_url'])) {
  3983. $videoParams['content'][] = [
  3984. 'type' => 'image_url',
  3985. 'image_url' => [
  3986. 'url' => $videoParams['tail_frame_url'],
  3987. ],
  3988. 'role' => 'last_frame',
  3989. ];
  3990. }
  3991. }
  3992. }
  3993. // 获取配音音频URL
  3994. $audioUrl = getProp($segment, 'audio_url');
  3995. $audioDuration = getProp($segment, 'audio_duration');
  3996. // 音频传入的前提:必须有至少一张图片或一个视频
  3997. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  3998. // 余额预检:积分不足直接报错
  3999. $this->pointsService->checkUserPointsEnough(
  4000. $this->pointsService->getVideoChargePoints([
  4001. 'model' => $model,
  4002. 'video_resolution' => $videoParams['video_resolution'] ?? '720P',
  4003. 'video_duration' => $videoDuration,
  4004. 'ratio' => $ratio,
  4005. 'generate_audio' => $current_generate_audio,
  4006. ])
  4007. );
  4008. // dd($videoParams);
  4009. // 根据模型选择不同的视频生成方法
  4010. if (strpos($model, 'jimeng') !== false) {
  4011. // 即梦模型参数调整
  4012. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4013. unset($videoParams['content']); // 即梦不使用content格式
  4014. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4015. } elseif (strpos($model, 'kling') !== false) {
  4016. // Keling模型参数调整
  4017. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4018. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4019. unset($videoParams['ratio']);
  4020. unset($videoParams['content']); // Keling不使用content格式
  4021. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4022. } elseif (strpos($model, 'zhizhen') !== false) {
  4023. // 智帧20等新模型使用统一API
  4024. // 构建统一API参数
  4025. $unifiedParams = [
  4026. 'model_code' => $model,
  4027. 'alias_segment_id' => $segment_id,
  4028. 'prompt' => trim($fullPrompt),
  4029. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4030. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4031. 'video_ratio' => $ratio,
  4032. 'seed' => -1,
  4033. ];
  4034. // 构建parameters参数
  4035. $parameters = [
  4036. 'seconds' => $unifiedParams['video_duration'],
  4037. 'resolution' => $unifiedParams['video_resolution'],
  4038. 'ratio' => $ratio,
  4039. // 'video_mode' => 'multi_image',
  4040. // 'mode' => 'multi_image',
  4041. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4042. ];
  4043. $hasImage = false;
  4044. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4045. if ($hasImage) {
  4046. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4047. if (isset($videoParams['tail_frame_url'])) {
  4048. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4049. }
  4050. // 只有在有图片的情况下才能添加参考音频
  4051. if ($audioUrl) {
  4052. // $parameters['reference_audios'] = [$audioUrl];
  4053. }
  4054. } else {
  4055. // 没有图片时,记录错误日志
  4056. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4057. 'segment_id' => $segment_id,
  4058. 'model' => $model
  4059. ]);
  4060. }
  4061. $unifiedParams['parameters'] = $parameters;
  4062. // 调用统一API创建任务
  4063. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4064. } else {
  4065. // Seedance模型(默认)
  4066. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4067. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4068. // 添加配音音频到content中
  4069. $videoParams['content'][] = [
  4070. 'type' => 'audio_url',
  4071. 'audio_url' => [
  4072. 'url' => $audioUrl,
  4073. ],
  4074. 'role' => 'reference_audio',
  4075. ];
  4076. // 优化提示词,增加音频相关描述
  4077. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4078. $videoParams['prompt'] = $audioPrompt;
  4079. $videoParams['content'][0]['text'] = $audioPrompt;
  4080. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4081. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4082. }
  4083. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4084. }
  4085. // 更新分镜表的视频任务信息
  4086. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4087. 'video_task_id' => $task->id,
  4088. 'video_task_status' => '生成中',
  4089. 'generate_audio' => $generate_audio,
  4090. 'updated_at' => date('Y-m-d H:i:s')
  4091. ]);
  4092. return [
  4093. 'task_id' => $task->id,
  4094. 'status' => $task->status,
  4095. 'segment_id' => $segment_id,
  4096. 'video_duration' => $videoDuration
  4097. ];
  4098. }
  4099. public function createActVideoTask($data) {
  4100. $act_id = getProp($data, 'act_id');
  4101. $first_frame_url = getProp($data, 'first_frame_url');
  4102. $tail_frame_url = getProp($data, 'tail_frame_url');
  4103. $generate_audio = getProp($data, 'generate_audio', 1);
  4104. $video_duration = getProp($data, 'video_duration');
  4105. $video_resolution = getProp($data, 'video_resolution');
  4106. $ratio = getProp($data, 'ratio');
  4107. $products = getProp($data, 'products', []);
  4108. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4109. if (!is_array($reference_images) || !is_array($products)) {
  4110. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4111. }
  4112. if (!$act_id) {
  4113. Utils::throwError('1002:片段ID不能为空');
  4114. }
  4115. // 获取片段信息
  4116. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4117. if (!$act) {
  4118. Utils::throwError('20003:片段不存在');
  4119. }
  4120. $act = (array)$act;
  4121. $anime_id = getProp($act, 'anime_id');
  4122. $episode_id = getProp($act, 'episode_id');
  4123. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4124. $ace_mode = getProp($anime, 'ace_mode');
  4125. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4126. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4127. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4128. // 将资产中新出现的资产放到extra_products中
  4129. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4130. if (!empty($products) && $episode) {
  4131. // 获取剧集中的角色、场景和道具列表
  4132. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4133. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4134. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4135. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4136. // 构建角色名称列表
  4137. $role_names = array_column($roles, 'role');
  4138. // 构建场景名称列表
  4139. $scene_names = array_column($scenes, 'scene');
  4140. // 构建道具名称列表
  4141. $prop_names = array_column($props, 'prop');
  4142. // 遍历传入的products
  4143. foreach ($products as $product) {
  4144. $product_name = getProp($product, 'product_name');
  4145. // 如果product_name不在roles、scenes和props中
  4146. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4147. // 查找是否在extra_products中存在同名的
  4148. $found = false;
  4149. foreach ($extra_products as $key => $extra_product) {
  4150. if (getProp($extra_product, 'product_name') === $product_name) {
  4151. // 有同名的则覆盖
  4152. $extra_products[$key] = $product;
  4153. $found = true;
  4154. break;
  4155. }
  4156. }
  4157. // 没有则新增
  4158. if (!$found) {
  4159. $extra_products[] = $product;
  4160. }
  4161. }
  4162. }
  4163. if ($extra_products) {
  4164. // 保存到数据库
  4165. DB::table('mp_anime_episodes')
  4166. ->where('id', $episode_id)
  4167. ->update([
  4168. 'extra_products' => json_encode($extra_products, 256),
  4169. 'updated_at' => date('Y-m-d H:i:s')
  4170. ]);
  4171. }
  4172. }
  4173. // 获取分镜内容
  4174. $actContent = getProp($act, 'act_show_content', '');
  4175. // 音效同出(默认使用)
  4176. $current_generate_audio = $generate_audio ? 1 : 0;
  4177. // 构建完整的提示词
  4178. $processResult = $this->processActContentWithProducts($actContent, $products);
  4179. $fullPrompt = $processResult['content'];
  4180. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4181. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4182. // 处理视频模型
  4183. $model = getProp($data, 'model');
  4184. if (!$model) {
  4185. $model = getProp($episode, 'video_model');
  4186. if (!$model) {
  4187. // episode表也没有,使用默认值
  4188. $model = 'zhizhen-20';
  4189. }
  4190. }
  4191. // 验证模型是否在可用模型表中
  4192. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4193. $model = 'zhizhen-20';
  4194. }
  4195. // 保存到episode表
  4196. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4197. 'video_model' => $model,
  4198. 'updated_at' => date('Y-m-d H:i:s')
  4199. ]);
  4200. // 余额预检:积分不足直接报错
  4201. $this->pointsService->checkUserPointsEnough(
  4202. $this->pointsService->getVideoChargePoints([
  4203. 'model' => $model,
  4204. 'video_resolution' => $video_resolution ?? '720P',
  4205. 'video_duration' => $videoDuration,
  4206. 'ratio' => $ratio,
  4207. 'generate_audio' => $current_generate_audio,
  4208. ])
  4209. );
  4210. // 构建视频生成参数
  4211. $videoParams = [
  4212. 'model' => $model,
  4213. 'alias_act_id' => $act_id,
  4214. 'prompt' => trim($fullPrompt),
  4215. 'video_duration' => $videoDuration,
  4216. 'video_resolution' => $video_resolution,
  4217. 'seed' => -1,
  4218. 'ratio' => $ratio,
  4219. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4220. 'draft' => false,
  4221. 'watermark' => false,
  4222. 'camera_fixed' => false,
  4223. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4224. ];
  4225. // 如果分镜有图片,作为首帧
  4226. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4227. $hasVideo = !empty(getProp($act, 'video_url'));
  4228. if ($hasImage) {
  4229. if ($first_frame_url) {
  4230. $videoParams['first_frame_url'] = $first_frame_url;
  4231. }else {
  4232. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4233. }
  4234. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4235. }
  4236. // 构建content数组
  4237. $videoParams['content'] = [
  4238. [
  4239. 'type' => 'text',
  4240. 'text' => $videoParams['prompt'],
  4241. ]
  4242. ];
  4243. // 如果有首帧图片,添加到content中
  4244. if ($hasImage) {
  4245. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4246. $videoParams['content'][] = [
  4247. 'type' => 'image_url',
  4248. 'image_url' => [
  4249. 'url' => $videoParams['first_frame_url'],
  4250. ],
  4251. 'role' => 'reference_image',
  4252. ];
  4253. if (isset($videoParams['tail_frame_url'])) {
  4254. $videoParams['content'][] = [
  4255. 'type' => 'image_url',
  4256. 'image_url' => [
  4257. 'url' => $videoParams['tail_frame_url'],
  4258. ],
  4259. 'role' => 'reference_image',
  4260. ];
  4261. }
  4262. }else {
  4263. $videoParams['content'][] = [
  4264. 'type' => 'image_url',
  4265. 'image_url' => [
  4266. 'url' => $videoParams['first_frame_url'],
  4267. ],
  4268. 'role' => 'first_frame',
  4269. ];
  4270. if (isset($videoParams['tail_frame_url'])) {
  4271. $videoParams['content'][] = [
  4272. 'type' => 'image_url',
  4273. 'image_url' => [
  4274. 'url' => $videoParams['tail_frame_url'],
  4275. ],
  4276. 'role' => 'last_frame',
  4277. ];
  4278. }
  4279. }
  4280. }
  4281. // dd($videoParams);
  4282. // 根据模型选择不同的视频生成方法
  4283. if (strpos($model, 'jimeng') !== false) {
  4284. // 即梦模型参数调整
  4285. unset($videoParams['content']); // 即梦不使用content格式
  4286. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4287. } elseif (strpos($model, 'kling') !== false) {
  4288. // Keling模型参数调整
  4289. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4290. unset($videoParams['ratio']);
  4291. unset($videoParams['content']); // Keling不使用content格式
  4292. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4293. } elseif (strpos($model, 'zhizhen') !== false) {
  4294. // 智帧20等新模型使用统一API
  4295. // 构建统一API参数
  4296. $unifiedParams = [
  4297. 'model_code' => $model,
  4298. 'alias_act_id' => $act_id,
  4299. 'prompt' => trim($fullPrompt),
  4300. 'video_duration' => $videoDuration,
  4301. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4302. 'video_ratio' => $ratio,
  4303. 'seed' => -1,
  4304. ];
  4305. // 构建parameters参数
  4306. $parameters = [
  4307. 'seconds' => $unifiedParams['video_duration'],
  4308. 'resolution' => $unifiedParams['video_resolution'],
  4309. 'ratio' => $ratio,
  4310. // 'video_mode' => 'multi_image',
  4311. // 'mode' => 'multi_image',
  4312. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4313. ];
  4314. $hasImage = false;
  4315. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4316. if ($hasImage) {
  4317. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4318. if (isset($videoParams['tail_frame_url'])) {
  4319. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4320. }
  4321. } else {
  4322. // 没有图片时,记录错误日志
  4323. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4324. 'act_id' => $act_id,
  4325. 'model' => $model
  4326. ]);
  4327. }
  4328. if ($reference_images) {
  4329. // 限制只传入9张参考图
  4330. $reference_images = array_slice($reference_images, 0, 9);
  4331. // 在处理之前先保存原始reference_images到任务参数中
  4332. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4333. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4334. $parameters['reference_images'] = $reference_images;
  4335. $parameters['video_mode'] = 'multi_image';
  4336. $parameters['mode'] = 'multi_image';
  4337. }
  4338. $unifiedParams['parameters'] = $parameters;
  4339. // 调用统一API创建任务
  4340. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4341. } else {
  4342. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4343. }
  4344. // 更新分镜表的视频任务信息
  4345. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4346. 'video_task_id' => $task->id,
  4347. 'video_task_status' => '生成中',
  4348. 'generate_audio' => $generate_audio,
  4349. 'updated_at' => date('Y-m-d H:i:s')
  4350. ]);
  4351. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4352. $episode_number = getProp($act, 'episode_number');
  4353. $act_number = getProp($act, 'act_number');
  4354. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4355. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4356. }
  4357. return [
  4358. 'task_id' => $task->id,
  4359. 'status' => $task->status,
  4360. 'act_id' => $act_id,
  4361. 'video_duration' => $videoDuration
  4362. ];
  4363. }
  4364. /**
  4365. * 根据提示词内容智能计算最优视频时长
  4366. *
  4367. * @param string $segmentContent 分镜内容
  4368. * @param string $tailFrame 尾帧描述
  4369. * @return int 视频时长(2-12秒)
  4370. */
  4371. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4372. // 合并所有文本内容
  4373. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4374. // 如果没有内容,返回默认时长
  4375. if (empty($fullText)) {
  4376. return 5;
  4377. }
  4378. // 计算文本长度(中文字符按2个字符计算)
  4379. $textLength = mb_strlen($fullText, 'UTF-8');
  4380. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4381. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4382. // 分析内容复杂度
  4383. $complexityScore = $this->analyzeContentComplexity($fullText);
  4384. // 基础时长计算(根据文本长度)
  4385. $baseDuration = 3; // 默认2秒
  4386. // if ($adjustedLength <= 20) {
  4387. // $baseDuration = 3;
  4388. // } elseif ($adjustedLength <= 40) {
  4389. // $baseDuration = 4;
  4390. // } elseif ($adjustedLength <= 60) {
  4391. // $baseDuration = 5;
  4392. // } elseif ($adjustedLength <= 80) {
  4393. // $baseDuration = 6;
  4394. // } elseif ($adjustedLength <= 100) {
  4395. // $baseDuration = 7;
  4396. // } elseif ($adjustedLength <= 120) {
  4397. // $baseDuration = 8;
  4398. // } else {
  4399. // $baseDuration = 9;
  4400. // }
  4401. // 根据内容复杂度调整时长
  4402. $finalDuration = $baseDuration + $complexityScore;
  4403. // 确保时长在2-12秒范围内
  4404. return max(4, min(12, $finalDuration));
  4405. }
  4406. /**
  4407. * 分析内容复杂度,返回时长调整值
  4408. *
  4409. * @param string $text 文本内容
  4410. * @return int 调整值(-2到+3)
  4411. */
  4412. private function analyzeContentComplexity($text) {
  4413. $score = 0;
  4414. // 动作关键词(需要更长时间展现)
  4415. $actionKeywords = [
  4416. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4417. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4418. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4419. ];
  4420. // 静态关键词(可以用较短时间)
  4421. $staticKeywords = [
  4422. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4423. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4424. ];
  4425. // 复杂场景关键词(需要更长时间)
  4426. $complexSceneKeywords = [
  4427. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4428. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4429. ];
  4430. // 情感关键词(需要适中时间表现)
  4431. $emotionKeywords = [
  4432. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4433. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4434. ];
  4435. // 检查动作关键词
  4436. foreach ($actionKeywords as $keyword) {
  4437. if (strpos($text, $keyword) !== false) {
  4438. $score += 1;
  4439. break; // 避免重复加分
  4440. }
  4441. }
  4442. // 检查静态关键词
  4443. foreach ($staticKeywords as $keyword) {
  4444. if (strpos($text, $keyword) !== false) {
  4445. $score -= 1;
  4446. break;
  4447. }
  4448. }
  4449. // 检查复杂场景关键词
  4450. foreach ($complexSceneKeywords as $keyword) {
  4451. if (strpos($text, $keyword) !== false) {
  4452. $score += 1;
  4453. break;
  4454. }
  4455. }
  4456. // 检查情感关键词
  4457. foreach ($emotionKeywords as $keyword) {
  4458. if (strpos($text, $keyword) !== false) {
  4459. $score += 1;
  4460. break;
  4461. }
  4462. }
  4463. // 检查时间相关词汇
  4464. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4465. $score += 1;
  4466. }
  4467. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4468. $score -= 1;
  4469. }
  4470. // 检查转场词汇
  4471. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4472. $score += 1;
  4473. }
  4474. // 检查环境描述(复杂环境需要更多时间)
  4475. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4476. $score += 1;
  4477. }
  4478. // 检查对话内容(对话需要更多时间)
  4479. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4480. $score += 1;
  4481. }
  4482. // 限制调整范围
  4483. return max(-1, min(4, $score));
  4484. }
  4485. /**
  4486. * 创建完整视频合成任务
  4487. *
  4488. * @param array $data
  4489. * @return array
  4490. */
  4491. public function createCompleteVideoTask($data)
  4492. {
  4493. $animeId = getProp($data, 'anime_id');
  4494. $episodeId = getProp($data, 'episode_id');
  4495. // 验证参数
  4496. if (!$animeId || !$episodeId) {
  4497. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4498. }
  4499. // 检查是否已存在处理中的任务
  4500. $existingTask = DB::table('mp_complete_video_tasks')
  4501. ->where('anime_id', $animeId)
  4502. ->where('episode_id', $episodeId)
  4503. ->whereIn('generate_status', ['执行中'])
  4504. ->first();
  4505. if ($existingTask) {
  4506. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4507. }
  4508. // 获取全能模式状态
  4509. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4510. if ((int)$ace_mode === 1) {
  4511. // 获取所有片段的配音视频,按 act_number 排序
  4512. $segments = DB::table('mp_episode_segments')
  4513. ->where('anime_id', $animeId)
  4514. ->where('episode_id', $episodeId)
  4515. ->orderBy('segment_number')
  4516. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4517. ->get();
  4518. // 检查是否所有片段都有视频
  4519. $missingVideos = $segments->filter(function($segment) {
  4520. return empty($segment->video_url);
  4521. });
  4522. if ($missingVideos->isNotEmpty()) {
  4523. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4524. }
  4525. }else {
  4526. // 获取所有分镜的配音视频,按 segment_number 排序
  4527. $segments = DB::table('mp_episode_segments')
  4528. ->where('anime_id', $animeId)
  4529. ->where('episode_id', $episodeId)
  4530. ->orderBy('segment_number')
  4531. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4532. ->get();
  4533. // 检查是否所有分镜都有配音和视频
  4534. $missingVideos = $segments->filter(function($segment) {
  4535. return empty($segment->audio_url) || empty($segment->video_url);
  4536. });
  4537. if ($missingVideos->isNotEmpty()) {
  4538. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4539. }
  4540. }
  4541. if ($segments->isEmpty()) {
  4542. Utils::throwError('20003:未找到该剧集的分镜数据');
  4543. }
  4544. // 获取当前完整视频url
  4545. $completeVideoUrl = DB::table('mp_anime_episodes')
  4546. ->where('anime_id', $animeId)
  4547. ->where('id', $episodeId)
  4548. ->value('complete_video_url');
  4549. // 构建 generate_json
  4550. $generateJson = [];
  4551. $sequence = 1;
  4552. foreach ($segments as $segment) {
  4553. if ((int)$ace_mode === 1) {
  4554. $generateJson[] = [
  4555. 'sequence' => $sequence++,
  4556. 'video_url' => $segment->video_url,
  4557. 'video_time_point_start' => $segment->video_time_point_start,
  4558. 'video_time_point_end' => $segment->video_time_point_end
  4559. ];
  4560. }else {
  4561. $generateJson[] = [
  4562. 'sequence' => $sequence++,
  4563. 'video_url' => $segment->video_url,
  4564. 'audio_url' => $segment->audio_url,
  4565. 'video_time_point_start' => $segment->video_time_point_start,
  4566. 'video_time_point_end' => $segment->video_time_point_end
  4567. ];
  4568. }
  4569. }
  4570. // 创建任务
  4571. $now = date('Y-m-d H:i:s');
  4572. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4573. 'anime_id' => $animeId,
  4574. 'episode_id' => $episodeId,
  4575. 'generate_json' => json_encode($generateJson, 256),
  4576. 'generate_status' => '执行中',
  4577. 'complete_video_url' => '',
  4578. 'created_at' => $now,
  4579. 'updated_at' => $now
  4580. ]);
  4581. if (!$taskId) {
  4582. Utils::throwError('20003:创建任务失败');
  4583. }
  4584. // 更新剧集表的任务ID和状态
  4585. $boolen = DB::table('mp_anime_episodes')
  4586. ->where('anime_id', $animeId)
  4587. ->where('id', $episodeId)
  4588. ->update([
  4589. 'complete_video_task_id' => $taskId,
  4590. 'complete_video_task_status' => '执行中',
  4591. 'updated_at' => $now
  4592. ]);
  4593. if (!$boolen) {
  4594. Utils::throwError('20003:更新剧集表失败');
  4595. }
  4596. dLog('anime')->info('创建完整视频合成任务', [
  4597. 'task_id' => $taskId,
  4598. 'anime_id' => $animeId,
  4599. 'episode_id' => $episodeId,
  4600. 'segment_count' => count($generateJson)
  4601. ]);
  4602. // 请求远程服务器执行生成
  4603. $client = new Client(['timeout' => 600, 'verify' => false]);
  4604. try {
  4605. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4606. $response = $result->getBody()->getContents();
  4607. $response_arr = json_decode($response, true);
  4608. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4609. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4610. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4611. // // 更新任务状态为失败
  4612. // DB::table('mp_complete_video_tasks')
  4613. // ->where('id', $taskId)
  4614. // ->update([
  4615. // 'generate_status' => '执行失败',
  4616. // 'error_message' => $error_msg,
  4617. // 'updated_at' => date('Y-m-d H:i:s')
  4618. // ]);
  4619. // // 同步更新剧集表状态
  4620. // DB::table('mp_anime_episodes')
  4621. // ->where('complete_video_task_id', $taskId)
  4622. // ->update([
  4623. // 'complete_video_task_status' => '执行失败',
  4624. // 'updated_at' => date('Y-m-d H:i:s')
  4625. // ]);
  4626. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4627. }
  4628. } catch (\Exception $e) {
  4629. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4630. // 更新任务状态为失败
  4631. DB::table('mp_complete_video_tasks')
  4632. ->where('id', $taskId)
  4633. ->update([
  4634. 'generate_status' => '执行失败',
  4635. 'error_message' => $e->getMessage(),
  4636. 'updated_at' => date('Y-m-d H:i:s')
  4637. ]);
  4638. // 同步更新剧集表状态
  4639. DB::table('mp_anime_episodes')
  4640. ->where('complete_video_task_id', $taskId)
  4641. ->update([
  4642. 'complete_video_task_status' => '执行失败',
  4643. 'updated_at' => date('Y-m-d H:i:s')
  4644. ]);
  4645. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4646. }
  4647. // 开始轮询任务状态
  4648. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4649. $pollInterval = 5; // 每5秒轮询一次
  4650. $attempt = 0;
  4651. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4652. while ($attempt < $maxAttempts) {
  4653. sleep($pollInterval);
  4654. $attempt++;
  4655. // 查询任务状态
  4656. $task = DB::table('mp_complete_video_tasks')
  4657. ->where('id', $taskId)
  4658. ->first();
  4659. if (!$task) {
  4660. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4661. Utils::throwError('20003:任务不存在');
  4662. }
  4663. dLog('anime')->info('轮询任务状态', [
  4664. 'task_id' => $taskId,
  4665. 'attempt' => $attempt,
  4666. 'status' => $task->generate_status
  4667. ]);
  4668. // 检查任务是否完成
  4669. if ($task->generate_status === '执行成功') {
  4670. // 同步更新剧集表状态
  4671. $boolen3 = DB::table('mp_anime_episodes')
  4672. ->where('anime_id', $animeId)
  4673. ->where('id', $episodeId)
  4674. ->update([
  4675. 'complete_video_url' => $task->complete_video_url,
  4676. 'complete_video_task_status' => '执行成功',
  4677. 'updated_at' => date('Y-m-d H:i:s')
  4678. ]);
  4679. dLog('anime')->info('视频合成任务完成', [
  4680. 'task_id' => $taskId,
  4681. 'video_url' => $task->complete_video_url,
  4682. 'attempts' => $attempt
  4683. ]);
  4684. // 如果更新成功则远程删除之前的文件
  4685. if ($boolen3 && $completeVideoUrl) {
  4686. $encode_url = urlencode($completeVideoUrl);
  4687. $client = new Client(['timeout' => 300, 'verify' => false]);
  4688. // 根据ID通过API通知合成音频
  4689. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4690. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4691. $response = $result->getBody()->getContents();
  4692. $response_arr = json_decode($response, true);
  4693. Log::info('火山删除音频返回: '.$response);
  4694. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4695. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4696. Log::info('火山删除音频失败: '.$error_msg);
  4697. // Utils::throwError('20003:火山删除音频失败');
  4698. }
  4699. }
  4700. return [
  4701. 'task_id' => $taskId,
  4702. 'anime_id' => $animeId,
  4703. 'episode_id' => $episodeId,
  4704. 'segment_count' => count($generateJson),
  4705. 'generate_status' => '执行成功',
  4706. 'complete_video_url' => $task->complete_video_url,
  4707. ];
  4708. }
  4709. // 检查任务是否失败
  4710. if ($task->generate_status === '执行失败') {
  4711. // 同步更新剧集表状态
  4712. DB::table('mp_anime_episodes')
  4713. ->where('anime_id', $animeId)
  4714. ->where('id', $episodeId)
  4715. ->update([
  4716. 'complete_video_task_status' => '执行失败',
  4717. 'updated_at' => date('Y-m-d H:i:s')
  4718. ]);
  4719. $errorMessage = $task->error_message ?? '未知错误';
  4720. dLog('anime')->error('视频合成任务失败', [
  4721. 'task_id' => $taskId,
  4722. 'error' => $errorMessage,
  4723. 'attempts' => $attempt
  4724. ]);
  4725. return [
  4726. 'task_id' => $taskId,
  4727. 'anime_id' => $animeId,
  4728. 'episode_id' => $episodeId,
  4729. 'segment_count' => count($generateJson),
  4730. 'generate_status' => '执行失败',
  4731. 'error_message' => $errorMessage
  4732. ];
  4733. }
  4734. }
  4735. // 超时处理
  4736. dLog('anime')->warning('视频合成任务超时', [
  4737. 'task_id' => $taskId,
  4738. 'max_attempts' => $maxAttempts,
  4739. 'timeout_seconds' => $maxAttempts * $pollInterval
  4740. ]);
  4741. // 更新任务状态为超时
  4742. DB::table('mp_complete_video_tasks')
  4743. ->where('id', $taskId)
  4744. ->update([
  4745. 'generate_status' => '超时',
  4746. 'error_message' => '任务执行超时(5分钟)',
  4747. 'updated_at' => date('Y-m-d H:i:s')
  4748. ]);
  4749. return [
  4750. 'task_id' => $taskId,
  4751. 'anime_id' => $animeId,
  4752. 'episode_id' => $episodeId,
  4753. 'segment_count' => count($generateJson),
  4754. 'generate_status' => '超时',
  4755. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4756. ];
  4757. }
  4758. /**
  4759. * 根据 inner_prompt_type 附加内置提示词
  4760. *
  4761. * @param string $prompt 用户提示词
  4762. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  4763. * @return string 合并后的提示词
  4764. */
  4765. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  4766. {
  4767. $innerPromptMap = [
  4768. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  4769. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  4770. ];
  4771. if (!isset($innerPromptMap[$innerPromptType])) {
  4772. return $prompt;
  4773. }
  4774. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  4775. }
  4776. /**
  4777. * 根据 inner_prompt_type 获取生成图片数量
  4778. *
  4779. * @param int $innerPromptType 内置提示词类型
  4780. * @return int 图片数量
  4781. */
  4782. public static function getInnerImageNum($innerPromptType = 0)
  4783. {
  4784. return (int)$innerPromptType === 2 ? 9 : 1;
  4785. }
  4786. /**
  4787. * 提取图片生成结果URL
  4788. *
  4789. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  4790. * @param int $innerPromptType 内置提示词类型
  4791. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  4792. */
  4793. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  4794. {
  4795. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  4796. if (is_array($resultUrls) && !empty($resultUrls)) {
  4797. $resultUrls = array_values($resultUrls);
  4798. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  4799. }
  4800. if (!empty($resultUrl)) {
  4801. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  4802. }
  4803. return (int)$innerPromptType === 2 ? [] : '';
  4804. }
  4805. public function generateImg($data) {
  4806. $prompt = getProp($data, 'prompt');
  4807. $episode_id = getProp($data, 'episode_id');
  4808. $ref_img_urls = getProp($data, 'ref_img_urls');
  4809. $ratio = getProp($data, 'ratio', '9:16');
  4810. $resolution = getProp($data, 'resolution', '2k');
  4811. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  4812. // 定义分辨率和宽高比对应的尺寸映射表
  4813. $sizeMap = [
  4814. '2k' => [
  4815. '1:1' => ['width' => 2048, 'height' => 2048],
  4816. '4:3' => ['width' => 2304, 'height' => 1728],
  4817. '3:4' => ['width' => 1728, 'height' => 2304],
  4818. '16:9' => ['width' => 2848, 'height' => 1600],
  4819. '9:16' => ['width' => 1600, 'height' => 2848],
  4820. '3:2' => ['width' => 2496, 'height' => 1664],
  4821. '2:3' => ['width' => 1664, 'height' => 2496],
  4822. '21:9' => ['width' => 3136, 'height' => 1344],
  4823. ],
  4824. '3k' => [
  4825. '1:1' => ['width' => 3072, 'height' => 3072],
  4826. '4:3' => ['width' => 3456, 'height' => 2592],
  4827. '3:4' => ['width' => 2592, 'height' => 3456],
  4828. '16:9' => ['width' => 4096, 'height' => 2304],
  4829. '9:16' => ['width' => 2304, 'height' => 4096],
  4830. '2:3' => ['width' => 2496, 'height' => 3744],
  4831. '3:2' => ['width' => 3744, 'height' => 2496],
  4832. '21:9' => ['width' => 4704, 'height' => 2016],
  4833. ],
  4834. '4k' => [
  4835. '1:1' => ['width' => 4096, 'height' => 4096],
  4836. '3:4' => ['width' => 3520, 'height' => 4704],
  4837. '4:3' => ['width' => 4704, 'height' => 3520],
  4838. '16:9' => ['width' => 5504, 'height' => 3040],
  4839. '9:16' => ['width' => 3040, 'height' => 5504],
  4840. '2:3' => ['width' => 3328, 'height' => 4992],
  4841. '3:2' => ['width' => 4992, 'height' => 3328],
  4842. '21:9' => ['width' => 6240, 'height' => 2656],
  4843. ],
  4844. ];
  4845. // 参数验证
  4846. $resolution = strtolower($resolution);
  4847. if (!isset($sizeMap[$resolution])) {
  4848. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  4849. }
  4850. if (!isset($sizeMap[$resolution][$ratio])) {
  4851. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  4852. }
  4853. // 根据 ratio 和 resolution 确定宽高
  4854. $width = $sizeMap[$resolution][$ratio]['width'];
  4855. $height = $sizeMap[$resolution][$ratio]['height'];
  4856. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  4857. if (is_json($ref_img_urls)) {
  4858. $ref_img_urls = json_decode($ref_img_urls, true);
  4859. }else {
  4860. $ref_img_urls = explode(',', $ref_img_urls);
  4861. }
  4862. }
  4863. // 处理图片模型
  4864. $model = getProp($data, 'model');
  4865. if (!$model) {
  4866. // 用户没有输入,从episode表获取
  4867. if ($episode_id) {
  4868. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4869. $model = getProp($episode, 'image_model');
  4870. }
  4871. if (!$model) {
  4872. // episode表也没有,使用默认值
  4873. $model = 'doubao-seedream-5-0-lite-260128';
  4874. }
  4875. }
  4876. // 验证模型是否在可用模型表中
  4877. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4878. // $model = 'doubao-seedream-5-0-lite-260128';
  4879. Utils::throwError('20003:该模型已不可用,请更换!');
  4880. }
  4881. // 保存到episode表
  4882. if ($episode_id) {
  4883. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4884. 'image_model' => $model,
  4885. 'updated_at' => date('Y-m-d H:i:s')
  4886. ]);
  4887. }
  4888. // 参数验证
  4889. if (!$prompt) Utils::throwError('20003:请提供提示词');
  4890. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  4891. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  4892. $imageNum = self::getInnerImageNum($inner_prompt_type);
  4893. try {
  4894. // 创建图片生成任务
  4895. $params = [
  4896. 'prompt' => $prompt,
  4897. 'model' => $model,
  4898. 'ref_img_urls' => '',
  4899. 'width' => $width,
  4900. 'height' => $height,
  4901. 'image_num' => $imageNum
  4902. ];
  4903. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  4904. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4905. $task_id = $task->id;
  4906. if (!$task_id) {
  4907. Utils::throwError('20003:创建图片生成任务失败');
  4908. }
  4909. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  4910. $model = getProp($task, 'model');
  4911. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  4912. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  4913. $isSyncModel = $isVolcModel || $isGptModel;
  4914. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  4915. $start_time = time();
  4916. $timeout = 300; // 5分钟
  4917. $img_url = '';
  4918. while (time() - $start_time < $timeout) {
  4919. sleep(3);
  4920. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  4921. if ($isSyncModel) {
  4922. // 刷新任务状态
  4923. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4924. if ($task->status === 'success' && $task->result_url) {
  4925. $img_url = self::extractResultUrls($task->result_url, $inner_prompt_type);
  4926. break;
  4927. } elseif ($task->status === 'failed') {
  4928. $errorMsg = mapErrorMessage($task->error_message ?? '');
  4929. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4930. }
  4931. // // 如果还在处理中,提示用户稍后查看
  4932. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  4933. }else {
  4934. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4935. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  4936. if ($statusInfo['status'] === 'success') {
  4937. $task->updateStatus('success', [
  4938. 'result_url' => $statusInfo['result_url'],
  4939. 'result_json' => $statusInfo['result_json'] ?? []
  4940. ]);
  4941. $img_url = self::extractResultUrls($statusInfo['result_url'], $inner_prompt_type);
  4942. break;
  4943. } elseif ($statusInfo['status'] === 'failed') {
  4944. $task->updateStatus('failed', [
  4945. 'error_message' => $statusInfo['error_message'],
  4946. 'result_json' => $statusInfo['result_json'] ?? []
  4947. ]);
  4948. dLog('anime')->error('图片生成失败,', [
  4949. 'error' => $statusInfo['error_message'] ?? '未知错误'
  4950. ]);
  4951. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  4952. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4953. }
  4954. }
  4955. }
  4956. if (empty($img_url)) {
  4957. Utils::throwError('20003:图片生成超时,请稍后重试');
  4958. }
  4959. return $img_url;
  4960. } catch (\Exception $e) {
  4961. dLog('anime')->error('更新角色或场景失败', [
  4962. 'error' => $e->getMessage()
  4963. ]);
  4964. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  4965. Utils::throwError('20003:' . $e->getMessage());
  4966. }
  4967. }
  4968. /**
  4969. * 使用文生文模型解析分镜内容
  4970. */
  4971. private function parseSegmentContentWithAI($segment_content) {
  4972. try {
  4973. // 使用DeepSeek服务的公开方法解析分镜内容
  4974. return $this->DeepSeekService->parseSegmentContent($segment_content);
  4975. } catch (\Exception $e) {
  4976. // 如果AI解析失败,记录日志并返回原内容
  4977. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  4978. return $segment_content;
  4979. }
  4980. }
  4981. /**
  4982. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  4983. *
  4984. * @param int $episode_id 分集ID
  4985. * @param int $anime_id 动漫ID
  4986. * @param array $roles 分集角色数组(引用传递)
  4987. * @param array $scenes 分集场景数组(引用传递)
  4988. * @param array $episode 分集数据
  4989. */
  4990. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  4991. // 获取全局动漫的角色和场景数据
  4992. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4993. if (!$anime) return;
  4994. $art_style_type = getProp($anime, 'art_style_type');
  4995. $character_prefix = '';
  4996. $scene_prefix = '';
  4997. if ($art_style_type) {
  4998. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  4999. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5000. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5001. }
  5002. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5003. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5004. $roles_updated = false;
  5005. $scenes_updated = false;
  5006. // 处理角色
  5007. foreach ($roles as &$role) {
  5008. $role_name = getProp($role, 'role');
  5009. $role_description = getProp($role, 'description');
  5010. $role_pic_prompt = getProp($role, 'pic_prompt');
  5011. $role_url = getProp($role, 'url');
  5012. $role_task_id = getProp($role, 'task_id');
  5013. // 如果已有URL或已有任务ID,跳过
  5014. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5015. continue;
  5016. }
  5017. $url_inherited = false;
  5018. // 尝试从全局数据中继承
  5019. foreach ($global_roles as $global_role) {
  5020. $global_role_name = getProp($global_role, 'role');
  5021. $global_role_description = getProp($global_role, 'description');
  5022. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5023. $global_role_url = getProp($global_role, 'url');
  5024. $global_role_task_id = getProp($global_role, 'task_id');
  5025. $global_role_task_status = getProp($global_role, 'task_status');
  5026. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5027. if ($role_name === $global_role_name
  5028. && $role_description === $global_role_description
  5029. && $role_pic_prompt === $global_role_pic_prompt
  5030. && !empty($global_role_url)) {
  5031. // 继承 task_id、task_status 和 url
  5032. $role['task_id'] = $global_role_task_id;
  5033. $role['task_status'] = $global_role_task_status;
  5034. $role['url'] = $global_role_url;
  5035. $roles_updated = true;
  5036. $url_inherited = true;
  5037. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5038. break;
  5039. }
  5040. }
  5041. // 如果无法继承且没有任务ID,创建新任务
  5042. if (!$url_inherited && empty($role_task_id)) {
  5043. try {
  5044. $art_style = getProp($episode, 'art_style');
  5045. // 优先使用 pic_prompt,如果没有则使用 description
  5046. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5047. // if ($art_style) {
  5048. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5049. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5050. // }
  5051. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5052. $params = [
  5053. 'prompt' => $description,
  5054. 'ref_img_urls' => []
  5055. ];
  5056. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5057. $task_id = $task->id;
  5058. if ($task_id) {
  5059. $role['task_id'] = $task_id;
  5060. $role['task_status'] = 'processing';
  5061. $roles_updated = true;
  5062. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5063. }
  5064. } catch (\Exception $e) {
  5065. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5066. }
  5067. }
  5068. }
  5069. // 处理场景
  5070. foreach ($scenes as &$scene) {
  5071. $scene_name = getProp($scene, 'scene');
  5072. $scene_description = getProp($scene, 'description');
  5073. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5074. $scene_url = getProp($scene, 'url');
  5075. $scene_task_id = getProp($scene, 'task_id');
  5076. // 如果已有URL或已有任务ID,跳过
  5077. if (!empty($scene_url) || !empty($scene_task_id)) {
  5078. continue;
  5079. }
  5080. $url_inherited = false;
  5081. // 尝试从全局数据中继承
  5082. foreach ($global_scenes as $global_scene) {
  5083. $global_scene_name = getProp($global_scene, 'scene');
  5084. $global_scene_description = getProp($global_scene, 'description');
  5085. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5086. $global_scene_url = getProp($global_scene, 'url');
  5087. $global_scene_task_id = getProp($global_scene, 'task_id');
  5088. $global_scene_task_status = getProp($global_scene, 'task_status');
  5089. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5090. if ($scene_name === $global_scene_name
  5091. && $scene_description === $global_scene_description
  5092. && $scene_pic_prompt === $global_scene_pic_prompt
  5093. && !empty($global_scene_url)) {
  5094. // 继承 task_id、task_status 和 url
  5095. $scene['task_id'] = $global_scene_task_id;
  5096. $scene['task_status'] = $global_scene_task_status;
  5097. $scene['url'] = $global_scene_url;
  5098. $scenes_updated = true;
  5099. $url_inherited = true;
  5100. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5101. break;
  5102. }
  5103. }
  5104. // 如果无法继承且没有任务ID,创建新任务
  5105. if (!$url_inherited && empty($scene_task_id)) {
  5106. try {
  5107. $art_style = getProp($episode, 'art_style');
  5108. // 优先使用 pic_prompt,如果没有则使用 description
  5109. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5110. // if ($art_style) {
  5111. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5112. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5113. // }
  5114. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5115. $params = [
  5116. 'prompt' => $description,
  5117. 'ref_img_urls' => []
  5118. ];
  5119. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5120. $task_id = $task->id;
  5121. if ($task_id) {
  5122. $scene['task_id'] = $task_id;
  5123. $scene['task_status'] = 'processing';
  5124. $scenes_updated = true;
  5125. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5126. }
  5127. } catch (\Exception $e) {
  5128. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5129. }
  5130. }
  5131. }
  5132. // 如果有更新,保存到数据库
  5133. if ($roles_updated || $scenes_updated) {
  5134. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5135. if ($roles_updated) {
  5136. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5137. }
  5138. if ($scenes_updated) {
  5139. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5140. }
  5141. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5142. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5143. }
  5144. }
  5145. /**
  5146. * 根据图片URL使用AI反推图片提示词
  5147. *
  5148. * @param string $img_url 图片URL
  5149. * @return string 反推的提示词
  5150. */
  5151. private function generateImagePromptFromUrl($img_url) {
  5152. try {
  5153. // 获取默认模型
  5154. $model = 'doubao-seed-2-0-mini-260215';
  5155. // 构建messages参数
  5156. $messages = [
  5157. [
  5158. 'role' => 'user',
  5159. 'content' => [
  5160. [
  5161. 'type' => 'text',
  5162. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5163. ],
  5164. [
  5165. 'type' => 'image_url',
  5166. 'image_url' => [
  5167. 'url' => $img_url
  5168. ]
  5169. ]
  5170. ]
  5171. ]
  5172. ];
  5173. // 构建请求参数
  5174. $params = [
  5175. 'model' => $model,
  5176. 'messages' => $messages,
  5177. 'stream' => false,
  5178. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5179. ];
  5180. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5181. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5182. // 返回生成的内容
  5183. return getProp($result, 'fullContent', '图片描述生成失败');
  5184. } catch (\Exception $e) {
  5185. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5186. 'img_url' => $img_url
  5187. ]);
  5188. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5189. 'error' => $e->getMessage(),
  5190. 'img_url' => $img_url
  5191. ]);
  5192. return '图片描述生成失败: ' . $e->getMessage();
  5193. }
  5194. }
  5195. /**
  5196. * 音频试听接口
  5197. * 创建音频任务并轮询获取结果
  5198. *
  5199. * @param array $data 参数数组
  5200. * @return array 返回音频URL或错误信息
  5201. */
  5202. public function previewAudio($data) {
  5203. $dialogue = getProp($data, 'dialogue');
  5204. // 必填参数验证
  5205. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5206. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5207. $voice_type = getProp($data, 'voice_type');
  5208. $voice_name = getProp($data, 'voice_name');
  5209. $voice_actor = getProp($data, 'voice_actor');
  5210. $emotion_type = getProp($data, 'emotion_type');
  5211. $gender = getProp($data, 'gender', 0);
  5212. $emotion = getProp($data, 'emotion');
  5213. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5214. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5215. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5216. $pitch = getProp($data, 'pitch', 0);
  5217. try {
  5218. $now = date('Y-m-d H:i:s');
  5219. // 构建生成参数
  5220. $generate_json = json_encode([
  5221. 'text' => $dialogue,
  5222. 'role' => $voice_actor,
  5223. 'voice_type' => $voice_type,
  5224. 'voice_name' => $voice_name,
  5225. 'emotion' => $emotion,
  5226. 'emotion_type' => $emotion_type,
  5227. 'gender' => $gender,
  5228. 'speed_ratio' => $speed_ratio,
  5229. 'loudness_ratio' => $loudness_ratio,
  5230. 'emotion_scale' => $emotion_scale,
  5231. 'pitch' => $pitch,
  5232. ], 256);
  5233. // 请求远程服务器执行生成
  5234. $client = new Client(['timeout' => 600, 'verify' => false]);
  5235. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5236. $response = $result->getBody()->getContents();
  5237. $response_arr = json_decode($response, true);
  5238. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5239. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5240. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5241. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5242. }
  5243. $arr = $response_arr['data'];
  5244. $subtitle_info = $arr['subtitle_info'];
  5245. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5246. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5247. return [
  5248. 'audio_url' => $arr['url'],
  5249. 'subtitle_info' => $subtitle_info,
  5250. 'audio_duration' => round($audio_duration, 2)
  5251. ];
  5252. } catch (\Exception $e) {
  5253. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5254. Utils::throwError('20003:' . $e->getMessage());
  5255. }
  5256. }
  5257. /**
  5258. * 获取角色库列表(支持文件夹递归查询)
  5259. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5260. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5261. */
  5262. public function globalProducts($data) {
  5263. $uid = Site::getUid();
  5264. $cpid = Site::getCpid();
  5265. $role = Site::getRole();
  5266. $id = getProp($data, 'id', 0);
  5267. $parent_id = getProp($data, 'parent_id', 0);
  5268. $product_name = getProp($data, 'product_name');
  5269. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5270. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5271. if (!$product) {
  5272. Utils::throwError('20003:请选择产品类型');
  5273. }
  5274. // 根据角色和is_public参数确定查询范围
  5275. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5276. // user角色:根据is_public参数筛选
  5277. $query_user_ids = [];
  5278. if ($role === 'admin') {
  5279. // admin获取所有个人库和公共库
  5280. $query_user_ids = [$uid, 0];
  5281. } else {
  5282. // user角色根据is_public参数筛选
  5283. if ($is_public == 2) {
  5284. // 个人库+公共库
  5285. $query_user_ids = [$uid, 0];
  5286. } elseif ($is_public == 0) {
  5287. // 仅个人库
  5288. $query_user_ids = [$uid];
  5289. } elseif ($is_public == 1) {
  5290. // 仅公共库
  5291. $query_user_ids = [0];
  5292. }
  5293. }
  5294. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5295. if ($id || $product_name) {
  5296. $query = DB::table('mp_products')
  5297. ->where('cpid', $cpid)
  5298. ->whereIn('user_id', $query_user_ids)
  5299. ->where('is_deleted', 0);
  5300. // 如果指定了 id,按 id 精确查询
  5301. if ($id) {
  5302. $query->where('id', $id);
  5303. }
  5304. // 如果指定了 product_name,按名称模糊查询
  5305. if ($product_name) {
  5306. $query->where('product_name', 'like', "%{$product_name}%");
  5307. }
  5308. // 如果指定了 product,添加筛选条件
  5309. if ($product) {
  5310. $query->where('product', $product);
  5311. }
  5312. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5313. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5314. ->get()
  5315. ->map(function($value) {
  5316. $value = (array)$value;
  5317. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5318. $value['type'] = (int)$value['type'];
  5319. $value['parent_id'] = (int)$value['parent_id'];
  5320. $value['level'] = (int)$value['level'];
  5321. $value['product'] = (int)($value['product'] ?? 1);
  5322. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5323. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5324. unset($value['user_id']);
  5325. return $value;
  5326. })
  5327. ->toArray();
  5328. return $result;
  5329. }
  5330. // 递归获取所有子目录和角色
  5331. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5332. }
  5333. /**
  5334. * 递归获取指定目录下的所有子目录和角色
  5335. * @param int $cpid 公司ID
  5336. * @param int $parent_id 父目录ID
  5337. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5338. * @param array $query_user_ids 用户ID数组(支持多个)
  5339. * @param int $current_uid 当前用户ID(用于排序)
  5340. * @return array
  5341. */
  5342. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5343. // 查询当前层级的所有项(文件夹和角色)
  5344. $query = DB::table('mp_products')
  5345. ->where('cpid', $cpid)
  5346. ->where('is_deleted', 0)
  5347. ->where('parent_id', $parent_id);
  5348. // 添加用户ID验证(支持多个user_id)
  5349. if (!empty($query_user_ids)) {
  5350. $query->whereIn('user_id', $query_user_ids);
  5351. }
  5352. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5353. if ($product) {
  5354. $query->where('product', $product);
  5355. }
  5356. // 排序规则:
  5357. // 1. 文件夹在前(type DESC)
  5358. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5359. // 3. 其他排序规则
  5360. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5361. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5362. ->get();
  5363. $result = [];
  5364. foreach ($items as $item) {
  5365. $itemArray = [
  5366. 'id' => $item->id,
  5367. 'type' => (int)$item->type,
  5368. 'parent_id' => (int)$item->parent_id,
  5369. 'level' => (int)$item->level,
  5370. 'product_name' => $item->product_name,
  5371. 'url' => $item->url,
  5372. 'pic_prompt' => $item->pic_prompt ?? '',
  5373. 'three_view_image_url' => $item->three_view_image_url,
  5374. 'product' => (int)($item->product ?? 1),
  5375. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5376. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5377. ];
  5378. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5379. // 如果是文件夹,递归获取其子项
  5380. if ($item->type == 2) {
  5381. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5382. if (!empty($children)) {
  5383. $itemArray['children'] = $children;
  5384. }
  5385. }
  5386. $result[] = $itemArray;
  5387. }
  5388. return $result;
  5389. }
  5390. /**
  5391. * 创建文件夹
  5392. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5393. * @return int 返回新建文件夹ID
  5394. */
  5395. public function createFolder($data) {
  5396. $uid = Site::getUid();
  5397. $cpid = Site::getCpid();
  5398. $role = Site::getRole();
  5399. $parent_id = getProp($data, 'parent_id', 0);
  5400. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5401. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5402. // 如果是公共库操作,需要admin权限
  5403. if ($is_public && $role !== 'admin') {
  5404. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5405. }
  5406. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5407. $store_uid = $is_public ? 0 : $uid;
  5408. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5409. $product = getProp($data, 'product');
  5410. if (!in_array($product, [1, 2, 3])) {
  5411. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5412. }
  5413. // 验证父文件夹
  5414. $parent_level = 0;
  5415. if ($parent_id > 0) {
  5416. $parent = DB::table('mp_products')
  5417. ->where('id', $parent_id)
  5418. ->where('cpid', $cpid)
  5419. ->where('user_id', $store_uid)
  5420. ->where('type', 2)
  5421. ->where('is_deleted', 0)
  5422. ->first();
  5423. if (!$parent) {
  5424. Utils::throwError('20003:父文件夹不存在');
  5425. }
  5426. // 检查父文件夹的 product 类型是否一致
  5427. if ($parent->product != $product) {
  5428. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5429. }
  5430. $parent_level = $parent->level;
  5431. // 检查层级限制(最多3层)
  5432. if ($parent_level >= 3) {
  5433. Utils::throwError('20003:文件夹层级不能超过3层');
  5434. }
  5435. }
  5436. // 检查当前目录下是否已存在空白文件夹
  5437. $empty_folder_exists = DB::table('mp_products')
  5438. ->where('parent_id', $parent_id)
  5439. ->where('cpid', $cpid)
  5440. ->where('user_id', $store_uid)
  5441. ->where('type', 2)
  5442. ->where('product', $product)
  5443. ->where('product_name', '新建文件夹')
  5444. ->where('is_deleted', 0)
  5445. ->exists();
  5446. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5447. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5448. }
  5449. // 创建文件夹
  5450. $folder_id = DB::table('mp_products')->insertGetId([
  5451. 'user_id' => $store_uid,
  5452. 'cpid' => $cpid,
  5453. 'type' => 2,
  5454. 'parent_id' => $parent_id,
  5455. 'level' => $parent_level + 1,
  5456. 'product_name' => $folder_name,
  5457. 'product' => $product,
  5458. 'sort_order' => time(), // 使用时间戳作为排序权重
  5459. 'is_deleted' => 0,
  5460. 'created_at' => date('Y-m-d H:i:s'),
  5461. 'updated_at' => date('Y-m-d H:i:s')
  5462. ]);
  5463. return [
  5464. 'id' => $folder_id,
  5465. 'type' => 2,
  5466. 'parent_id' => $parent_id,
  5467. 'level' => $parent_level + 1,
  5468. 'product_name' => $folder_name,
  5469. 'product' => $product,
  5470. ];
  5471. }
  5472. /**
  5473. * 重命名文件夹或角色
  5474. * @param array $data 包含 id、product_name(新名称)
  5475. * @return bool
  5476. */
  5477. public function renameFolder($data) {
  5478. $uid = Site::getUid();
  5479. $cpid = Site::getCpid();
  5480. $role = Site::getRole();
  5481. $id = getProp($data, 'id');
  5482. $new_name = getProp($data, 'product_name');
  5483. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5484. if (!$id || !$new_name) {
  5485. Utils::throwError('20003:参数不完整');
  5486. }
  5487. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5488. $query_uid = $is_public ? 0 : $uid;
  5489. // 如果是公共库操作,需要admin权限
  5490. if ($is_public && $role !== 'admin') {
  5491. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5492. }
  5493. // 检查是否存在
  5494. $item = DB::table('mp_products')
  5495. ->where('id', $id)
  5496. ->where('cpid', $cpid)
  5497. ->where('user_id', $query_uid)
  5498. ->where('is_deleted', 0)
  5499. ->first();
  5500. if (!$item) {
  5501. Utils::throwError('20003:项目不存在');
  5502. }
  5503. return DB::table('mp_products')
  5504. ->where('id', $id)
  5505. ->where('cpid', $cpid)
  5506. ->where('user_id', $query_uid)
  5507. ->update([
  5508. 'product_name' => $new_name,
  5509. 'updated_at' => date('Y-m-d H:i:s')
  5510. ]);
  5511. }
  5512. /**
  5513. * 移动角色或文件夹到指定文件夹
  5514. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5515. * @return bool
  5516. */
  5517. public function moveProductOrFolder($data) {
  5518. $uid = Site::getUid();
  5519. $cpid = Site::getCpid();
  5520. $role = Site::getRole();
  5521. $id = getProp($data, 'id');
  5522. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5523. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5524. if (!$id) {
  5525. Utils::throwError('20003:请选择要移动的项目');
  5526. }
  5527. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5528. $query_uid = $is_public ? 0 : $uid;
  5529. // 如果是公共库操作,需要admin权限
  5530. if ($is_public && $role !== 'admin') {
  5531. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5532. }
  5533. // 检查要移动的项目
  5534. $item = DB::table('mp_products')
  5535. ->where('id', $id)
  5536. ->where('cpid', $cpid)
  5537. ->where('user_id', $query_uid)
  5538. ->where('is_deleted', 0)
  5539. ->first();
  5540. if (!$item) {
  5541. Utils::throwError('20003:项目不存在');
  5542. }
  5543. // 验证目标文件夹
  5544. $target_level = 0;
  5545. $target_product = $item->product; // 默认使用当前项目的 product
  5546. if ($target_parent_id > 0) {
  5547. $target_parent = DB::table('mp_products')
  5548. ->where('id', $target_parent_id)
  5549. ->where('cpid', $cpid)
  5550. ->where('user_id', $query_uid)
  5551. ->where('type', 2)
  5552. ->where('is_deleted', 0)
  5553. ->first();
  5554. if (!$target_parent) {
  5555. Utils::throwError('20003:目标文件夹不存在');
  5556. }
  5557. // 检查 product 类型是否一致
  5558. if ($target_parent->product != $item->product) {
  5559. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5560. }
  5561. $target_level = $target_parent->level;
  5562. $target_product = $target_parent->product;
  5563. // 如果移动的是文件夹,需要检查层级
  5564. if ($item->type == 2) {
  5565. // 计算移动后的最大层级
  5566. $max_child_level = $this->getMaxChildLevel($id);
  5567. $depth = $max_child_level - $item->level;
  5568. if ($target_level + 1 + $depth > 3) {
  5569. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5570. }
  5571. // 不能移动到自己或自己的子文件夹下
  5572. if ($this->isDescendant($target_parent_id, $id)) {
  5573. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5574. }
  5575. }
  5576. }
  5577. // 更新父文件夹和层级
  5578. $new_level = $target_level + 1;
  5579. DB::table('mp_products')
  5580. ->where('id', $id)
  5581. ->update([
  5582. 'parent_id' => $target_parent_id,
  5583. 'level' => $new_level,
  5584. 'updated_at' => date('Y-m-d H:i:s')
  5585. ]);
  5586. // 如果是文件夹,需要递归更新所有子项的层级
  5587. if ($item->type == 2) {
  5588. $this->updateChildrenLevel($id, $new_level);
  5589. }
  5590. return true;
  5591. }
  5592. /**
  5593. * 获取文件夹下最大子层级
  5594. * @param int $folder_id
  5595. * @return int
  5596. */
  5597. private function getMaxChildLevel($folder_id) {
  5598. $max_level = DB::table('mp_products')
  5599. ->where('parent_id', $folder_id)
  5600. ->where('is_deleted', 0)
  5601. ->max('level');
  5602. if (!$max_level) {
  5603. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5604. }
  5605. // 递归查找子文件夹
  5606. $children = DB::table('mp_products')
  5607. ->where('parent_id', $folder_id)
  5608. ->where('type', 2)
  5609. ->where('is_deleted', 0)
  5610. ->pluck('id');
  5611. foreach ($children as $child_id) {
  5612. $child_max = $this->getMaxChildLevel($child_id);
  5613. if ($child_max > $max_level) {
  5614. $max_level = $child_max;
  5615. }
  5616. }
  5617. return $max_level;
  5618. }
  5619. /**
  5620. * 检查 target_id 是否是 folder_id 的后代
  5621. * @param int $target_id
  5622. * @param int $folder_id
  5623. * @return bool
  5624. */
  5625. private function isDescendant($target_id, $folder_id) {
  5626. if ($target_id == $folder_id) {
  5627. return true;
  5628. }
  5629. $parent = DB::table('mp_products')
  5630. ->where('id', $target_id)
  5631. ->where('is_deleted', 0)
  5632. ->first();
  5633. if (!$parent || $parent->parent_id == 0) {
  5634. return false;
  5635. }
  5636. return $this->isDescendant($parent->parent_id, $folder_id);
  5637. }
  5638. /**
  5639. * 递归更新子项层级
  5640. * @param int $parent_id
  5641. * @param int $parent_level
  5642. */
  5643. private function updateChildrenLevel($parent_id, $parent_level) {
  5644. $children = DB::table('mp_products')
  5645. ->where('parent_id', $parent_id)
  5646. ->where('is_deleted', 0)
  5647. ->get();
  5648. foreach ($children as $child) {
  5649. $new_level = $parent_level + 1;
  5650. DB::table('mp_products')
  5651. ->where('id', $child->id)
  5652. ->update([
  5653. 'level' => $new_level,
  5654. 'updated_at' => date('Y-m-d H:i:s')
  5655. ]);
  5656. // 如果是文件夹,继续递归
  5657. if ($child->type == 2) {
  5658. $this->updateChildrenLevel($child->id, $new_level);
  5659. }
  5660. }
  5661. }
  5662. /**
  5663. * 获取文件夹路径(面包屑导航)
  5664. * @param array $data 包含 folder_id
  5665. * @return array 返回路径数组
  5666. */
  5667. public function getFolderPath($data) {
  5668. $uid = Site::getUid();
  5669. $cpid = Site::getCpid();
  5670. $folder_id = getProp($data, 'id', 0);
  5671. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5672. if ($folder_id == 0) {
  5673. return [
  5674. ['id' => 0, 'name' => '根目录']
  5675. ];
  5676. }
  5677. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5678. $query_uid = $is_public ? 0 : $uid;
  5679. $path = [];
  5680. $current_id = $folder_id;
  5681. while ($current_id > 0) {
  5682. $folder = DB::table('mp_products')
  5683. ->where('id', $current_id)
  5684. ->where('cpid', $cpid)
  5685. ->where('user_id', $query_uid)
  5686. ->where('type', 2)
  5687. ->where('is_deleted', 0)
  5688. ->first();
  5689. if (!$folder) {
  5690. break;
  5691. }
  5692. array_unshift($path, [
  5693. 'id' => $folder->id,
  5694. 'name' => $folder->product_name
  5695. ]);
  5696. $current_id = $folder->parent_id;
  5697. }
  5698. // 添加根目录
  5699. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5700. return $path;
  5701. }
  5702. public function createProduct($data) {
  5703. $uid = Site::getUid();
  5704. $cpid = Site::getCpid();
  5705. $role = Site::getRole();
  5706. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5707. // 如果是公共库操作,需要admin权限
  5708. if ($is_public && $role !== 'admin') {
  5709. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5710. }
  5711. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5712. $store_uid = $is_public ? 0 : $uid;
  5713. $product_name = trim(getProp($data, 'product_name'));
  5714. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5715. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5716. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5717. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5718. $url = trim(getProp($data, 'url'));
  5719. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5720. $versions = getProp($data, 'versions');
  5721. // 检查是否是正确的图片格式
  5722. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5723. $urlPath = parse_url($url, PHP_URL_PATH);
  5724. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5725. if (!in_array($extension, $allowedExtensions)) {
  5726. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5727. }
  5728. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5729. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5730. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5731. $product = getProp($data, 'product');
  5732. if (!in_array($product, [1, 2, 3])) {
  5733. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5734. }
  5735. // 获取父文件夹ID和层级
  5736. $parent_id = getProp($data, 'parent_id', 0);
  5737. $parent_level = 0;
  5738. if ($parent_id > 0) {
  5739. $parent = DB::table('mp_products')
  5740. ->where('id', $parent_id)
  5741. ->where('cpid', $cpid)
  5742. ->where('user_id', $store_uid)
  5743. ->where('type', 2)
  5744. ->where('is_deleted', 0)
  5745. ->first();
  5746. if (!$parent) {
  5747. Utils::throwError('20003:父文件夹不存在');
  5748. }
  5749. $parent_level = $parent->level;
  5750. }
  5751. $id = DB::table('mp_products')->insertGetId([
  5752. 'user_id' => $store_uid,
  5753. 'cpid' => $cpid,
  5754. 'type' => 1, // 1=角色图片
  5755. 'parent_id' => $parent_id,
  5756. 'level' => $parent_level + 1,
  5757. 'product_name' => $product_name,
  5758. 'url' => $url,
  5759. 'pic_prompt' => $pic_prompt,
  5760. 'product' => $product,
  5761. 'versions' => json_encode($versions, 256),
  5762. 'sort_order' => time(), // 使用时间戳作为排序权重
  5763. 'created_at' => date('Y-m-d H:i:s'),
  5764. 'updated_at' => date('Y-m-d H:i:s')
  5765. ]);
  5766. if (!$id) Utils::throwError('20003:创建失败');
  5767. return [
  5768. 'id' => $id,
  5769. 'type' => 1,
  5770. 'parent_id' => $parent_id,
  5771. 'level' => $parent_level + 1,
  5772. 'product_name' => $product_name,
  5773. 'url' => $url,
  5774. 'pic_prompt' => $pic_prompt,
  5775. 'product' => $product,
  5776. 'versions' => $versions
  5777. ];
  5778. }
  5779. public function editProduct($data) {
  5780. $uid = Site::getUid();
  5781. $cpid = Site::getCpid();
  5782. $role = Site::getRole();
  5783. $id = getProp($data, 'id');
  5784. if (!$id) Utils::throwError('20003:ID不能为空');
  5785. $versions = getProp($data, 'versions');
  5786. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5787. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5788. $query_uid = $is_public ? 0 : $uid;
  5789. // 如果是公共库操作,需要admin权限
  5790. if ($is_public && $role !== 'admin') {
  5791. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5792. }
  5793. // 检查是否存在且属于当前用户或公共库
  5794. $role = DB::table('mp_products')
  5795. ->where('id', $id)
  5796. ->where('cpid', $cpid)
  5797. ->where('user_id', $query_uid)
  5798. ->where('type', 1)->first();
  5799. if (!$role) Utils::throwError('20003:记录不存在');
  5800. $updateData = [];
  5801. // $needVersionRecord = false; // 是否需要记录版本
  5802. // 名称
  5803. $product_name = trim(getProp($data, 'product_name'));
  5804. if ($product_name) {
  5805. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5806. $updateData['product_name'] = $product_name;
  5807. }
  5808. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5809. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5810. // 图片地址
  5811. $url = trim(getProp($data, 'url'));
  5812. if ($url) {
  5813. // 检查是否是正确的图片格式
  5814. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5815. $urlPath = parse_url($url, PHP_URL_PATH);
  5816. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5817. if (!in_array($extension, $allowedExtensions)) {
  5818. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5819. }
  5820. // // 如果 url 有变更,记录版本
  5821. // if ($url !== $role->url) {
  5822. // $needVersionRecord = true;
  5823. // }
  5824. $updateData['url'] = $url;
  5825. }
  5826. // 提示词
  5827. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5828. if ($pic_prompt) {
  5829. // // 如果 pic_prompt 有变更,记录版本
  5830. // if ($pic_prompt !== $role->pic_prompt) {
  5831. // $needVersionRecord = true;
  5832. // }
  5833. $updateData['pic_prompt'] = $pic_prompt;
  5834. }
  5835. if (empty($updateData)) {
  5836. Utils::throwError('20003:没有需要更新的数据');
  5837. }
  5838. // // 如果需要记录版本,将数据添加到 versions 数组
  5839. // if ($needVersionRecord) {
  5840. // // 获取现有的 versions 数据
  5841. // $versions = json_decode($role->versions, true) ?: [];
  5842. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  5843. // // 如果是第一次记录版本,先添加旧版本(变更前)
  5844. // if ($isFirstVersion) {
  5845. // $oldVersion = [
  5846. // 'url' => $role->url,
  5847. // 'description' => $role->pic_prompt,
  5848. // ];
  5849. // // 旧版本添加到数组末尾
  5850. // $versions[] = $oldVersion;
  5851. // }
  5852. // // 构建新版本(变更后)
  5853. // $newVersion = [
  5854. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  5855. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  5856. // ];
  5857. // // 检查新版本是否已存在于历史版本中
  5858. // $existingIndex = -1;
  5859. // foreach ($versions as $index => $version) {
  5860. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  5861. // $existingIndex = $index;
  5862. // break;
  5863. // }
  5864. // }
  5865. // if ($existingIndex !== -1) {
  5866. // // 如果已存在,移除旧的位置
  5867. // array_splice($versions, $existingIndex, 1);
  5868. // }
  5869. // // 新版本添加到数组开头(最新的在前)
  5870. // array_unshift($versions, $newVersion);
  5871. // // // 限制版本数量(可选,例如只保留最近10个版本)
  5872. // // if (count($versions) > 10) {
  5873. // // $versions = array_slice($versions, 0, 10);
  5874. // // }
  5875. // $updateData['versions'] = json_encode($versions, 256);
  5876. // }
  5877. if ($versions) {
  5878. $updateData['versions'] = json_encode($versions, 256);
  5879. }
  5880. $updateData['updated_at'] = date('Y-m-d H:i:s');
  5881. return DB::table('mp_products')
  5882. ->where('cpid', $cpid)
  5883. ->where('id', $id)->update($updateData);
  5884. }
  5885. /**
  5886. * 获取角色版本历史
  5887. * @param array $data 包含 id(角色ID)
  5888. * @return array 返回版本历史列表
  5889. */
  5890. public function getProductVersions($data) {
  5891. $cpid = Site::getCpid();
  5892. $id = getProp($data, 'id');
  5893. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5894. $role = DB::table('mp_products')
  5895. ->where('id', $id)
  5896. ->where('cpid', $cpid)
  5897. ->where('type', 1)
  5898. ->first();
  5899. if (!$role) Utils::throwError('20003:角色不存在');
  5900. // 获取版本历史
  5901. $versions = json_decode($role->versions, true) ?: [];
  5902. // 添加当前版本作为最新版本
  5903. $currentVersion = [
  5904. 'version' => 0, // 0 表示当前版本
  5905. 'url' => $role->url,
  5906. 'pic_prompt' => $role->pic_prompt,
  5907. 'updated_at' => $role->updated_at,
  5908. 'is_current' => true
  5909. ];
  5910. array_unshift($versions, $currentVersion);
  5911. return $versions;
  5912. }
  5913. /**
  5914. * 恢复到指定版本
  5915. * @param array $data 包含 id(角色ID)、version(版本号)
  5916. * @return bool
  5917. */
  5918. public function restoreProductVersion($data) {
  5919. $uid = Site::getUid();
  5920. $cpid = Site::getCpid();
  5921. $id = getProp($data, 'id');
  5922. $version = getProp($data, 'version');
  5923. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5924. if (!$version) Utils::throwError('20003:版本号不能为空');
  5925. $role = DB::table('mp_products')
  5926. ->where('id', $id)
  5927. ->where('cpid', $cpid)
  5928. ->where('type', 1)
  5929. ->first();
  5930. if (!$role) Utils::throwError('20003:角色不存在');
  5931. // 获取版本历史
  5932. $versions = json_decode($role->versions, true) ?: [];
  5933. // 查找指定版本
  5934. $targetVersion = null;
  5935. foreach ($versions as $v) {
  5936. if ($v['version'] == $version) {
  5937. $targetVersion = $v;
  5938. break;
  5939. }
  5940. }
  5941. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  5942. // 先将当前版本保存到历史
  5943. $newVersion = [
  5944. 'version' => count($versions) + 1,
  5945. 'url' => $role->url,
  5946. 'pic_prompt' => $role->pic_prompt,
  5947. 'updated_at' => date('Y-m-d H:i:s'),
  5948. 'updated_by' => $uid
  5949. ];
  5950. array_unshift($versions, $newVersion);
  5951. // 限制版本数量
  5952. if (count($versions) > 10) {
  5953. $versions = array_slice($versions, 0, 10);
  5954. }
  5955. // 恢复到指定版本
  5956. return DB::table('mp_products')
  5957. ->where('id', $id)
  5958. ->where('cpid', $cpid)
  5959. ->update([
  5960. 'url' => $targetVersion['url'],
  5961. 'pic_prompt' => $targetVersion['pic_prompt'],
  5962. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  5963. 'updated_at' => date('Y-m-d H:i:s')
  5964. ]);
  5965. }
  5966. public function deleteProduct($data) {
  5967. $uid = Site::getUid();
  5968. $cpid = Site::getCpid();
  5969. $role = Site::getRole();
  5970. $id = getProp($data, 'id');
  5971. if (!$id) Utils::throwError('20003:ID不能为空');
  5972. $ids = explode(',', $id);
  5973. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5974. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5975. $query_uid = $is_public ? 0 : $uid;
  5976. // 如果是公共库操作,需要admin权限
  5977. if ($is_public && $role !== 'admin') {
  5978. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5979. }
  5980. // 检查是否存在且属于当前用户或公共库
  5981. $role = DB::table('mp_products')
  5982. ->whereIn('id', $ids)
  5983. ->where('cpid', $cpid)
  5984. ->where('user_id', $query_uid)
  5985. ->get();
  5986. if (!$role) Utils::throwError('20003:记录不存在');
  5987. return DB::table('mp_products')
  5988. ->where('cpid', $cpid)
  5989. ->where('user_id', $query_uid)
  5990. ->whereIn('id', $ids)
  5991. ->update([
  5992. 'is_deleted' => 1,
  5993. 'updated_at' => date('Y-m-d H:i:s')
  5994. ]);
  5995. }
  5996. public function generateThreeView($data) {
  5997. $uid = Site::getUid();
  5998. $cpid = Site::getCpid();
  5999. $role = Site::getRole();
  6000. $id = getProp($data, 'id');
  6001. if (!$id) Utils::throwError('20003:ID不能为空');
  6002. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6003. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6004. $query_uid = $is_public ? 0 : $uid;
  6005. // 如果是公共库操作,需要admin权限
  6006. if ($is_public && $role !== 'admin') {
  6007. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6008. }
  6009. // 检查是否存在且属于当前用户或公共库
  6010. $product = DB::table('mp_products')
  6011. ->where('id', $id)
  6012. ->where('cpid', $cpid)
  6013. ->where('user_id', $query_uid)
  6014. ->where('type', 1)->first();
  6015. if (!$product) Utils::throwError('20003:资产不存在');
  6016. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6017. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6018. if (!$ref_img_url) {
  6019. // 如果没有传入参考图,使用角色表中的图片
  6020. $ref_img_url = $product->url ?? '';
  6021. if (!$ref_img_url) {
  6022. Utils::throwError('20003:参考图不能为空');
  6023. }
  6024. }
  6025. $pic_prompt = getProp($product, 'pic_prompt');
  6026. if ($pic_prompt) {
  6027. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6028. }
  6029. // 检查参考图是否是正确的图片格式
  6030. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6031. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6032. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6033. if (!in_array($extension, $allowedExtensions)) {
  6034. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6035. }
  6036. // 处理图片模型
  6037. $model = getProp($data, 'model');
  6038. if (!$model) {
  6039. // 使用默认模型
  6040. $model = 'doubao-seedream-5-0-lite-260128';
  6041. }
  6042. // 验证模型是否在可用模型表中
  6043. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6044. Utils::throwError('20003:该模型已不可用,请更换!');
  6045. }
  6046. $ratio = getProp($data, 'ratio', '16:9');
  6047. $resolution = getProp($data, 'resolution', '2k');
  6048. // 定义分辨率和宽高比对应的尺寸映射表
  6049. $sizeMap = [
  6050. '2k' => [
  6051. '1:1' => ['width' => 2048, 'height' => 2048],
  6052. '4:3' => ['width' => 2304, 'height' => 1728],
  6053. '3:4' => ['width' => 1728, 'height' => 2304],
  6054. '16:9' => ['width' => 2848, 'height' => 1600],
  6055. '9:16' => ['width' => 1600, 'height' => 2848],
  6056. '3:2' => ['width' => 2496, 'height' => 1664],
  6057. '2:3' => ['width' => 1664, 'height' => 2496],
  6058. '21:9' => ['width' => 3136, 'height' => 1344],
  6059. ],
  6060. '3k' => [
  6061. '1:1' => ['width' => 3072, 'height' => 3072],
  6062. '4:3' => ['width' => 3456, 'height' => 2592],
  6063. '3:4' => ['width' => 2592, 'height' => 3456],
  6064. '16:9' => ['width' => 4096, 'height' => 2304],
  6065. '9:16' => ['width' => 2304, 'height' => 4096],
  6066. '2:3' => ['width' => 2496, 'height' => 3744],
  6067. '3:2' => ['width' => 3744, 'height' => 2496],
  6068. '21:9' => ['width' => 4704, 'height' => 2016],
  6069. ],
  6070. '4k' => [
  6071. '1:1' => ['width' => 4096, 'height' => 4096],
  6072. '3:4' => ['width' => 3520, 'height' => 4704],
  6073. '4:3' => ['width' => 4704, 'height' => 3520],
  6074. '16:9' => ['width' => 5504, 'height' => 3040],
  6075. '9:16' => ['width' => 3040, 'height' => 5504],
  6076. '2:3' => ['width' => 3328, 'height' => 4992],
  6077. '3:2' => ['width' => 4992, 'height' => 3328],
  6078. '21:9' => ['width' => 6240, 'height' => 2656],
  6079. ],
  6080. ];
  6081. // 参数验证
  6082. $resolution = strtolower($resolution);
  6083. if (!isset($sizeMap[$resolution])) {
  6084. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6085. }
  6086. if (!isset($sizeMap[$resolution][$ratio])) {
  6087. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6088. }
  6089. // 根据 ratio 和 resolution 确定宽高
  6090. $width = $sizeMap[$resolution][$ratio]['width'];
  6091. $height = $sizeMap[$resolution][$ratio]['height'];
  6092. try {
  6093. // 创建图片生成任务
  6094. $params = [
  6095. 'prompt' => $prompt,
  6096. 'model' => $model,
  6097. 'ref_img_urls' => [$ref_img_url],
  6098. 'width' => $width,
  6099. 'height' => $height
  6100. ];
  6101. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6102. $task_id = $task->id;
  6103. if (!$task_id) {
  6104. Utils::throwError('20003:创建图片生成任务失败');
  6105. }
  6106. // 轮询获取结果
  6107. // 只查询数据库,不调用API,不更新任务表
  6108. $start_time = time();
  6109. $timeout = 1800;
  6110. $img_url = '';
  6111. while (time() - $start_time < $timeout) {
  6112. sleep(5);
  6113. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6114. $task = DB::table('mp_generate_pic_tasks')
  6115. ->where('id', $task_id)
  6116. ->first();
  6117. if (!$task) {
  6118. Utils::throwError('20003:任务不存在');
  6119. }
  6120. if ($task->status === 'success' && $task->result_url) {
  6121. $result_urls = is_string($task->result_url)
  6122. ? json_decode($task->result_url, true)
  6123. : $task->result_url;
  6124. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6125. break;
  6126. } elseif ($task->status === 'failed') {
  6127. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6128. }
  6129. // 其他状态继续轮询
  6130. }
  6131. if (empty($img_url)) {
  6132. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6133. }
  6134. // 更新 mp_products 表(不是任务表)
  6135. DB::table('mp_products')
  6136. ->where('id', $id)
  6137. ->where('cpid', $cpid)
  6138. ->update([
  6139. 'three_view_image_url' => $img_url,
  6140. 'updated_at' => date('Y-m-d H:i:s')
  6141. ]);
  6142. return ['three_view_image_url' => $img_url];
  6143. } catch (\Exception $e) {
  6144. dLog('anime')->error('生成三视图失败', [
  6145. 'error' => $e->getMessage()
  6146. ]);
  6147. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6148. Utils::throwError('20003:' . $e->getMessage());
  6149. }
  6150. }
  6151. /**
  6152. * 推送(复制)资产或文件夹到目标位置
  6153. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6154. * @return array 返回推送结果
  6155. */
  6156. public function pushProductOrFolder($data) {
  6157. $uid = Site::getUid();
  6158. $cpid = Site::getCpid();
  6159. $role = Site::getRole();
  6160. $product_id = getProp($data, 'product_id');
  6161. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6162. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6163. if (!$product_id) {
  6164. Utils::throwError('20003:请选择要推送的项目');
  6165. }
  6166. // 查询源项目(只通过cpid查询,不限制user_id)
  6167. $sourceItem = DB::table('mp_products')
  6168. ->where('id', $product_id)
  6169. ->where('cpid', $cpid)
  6170. ->where('is_deleted', 0)
  6171. ->first();
  6172. if (!$sourceItem) {
  6173. Utils::throwError('20003:要推送的项目不存在');
  6174. }
  6175. // 通过user_id判断源是公共库还是个人库
  6176. $source_uid = $sourceItem->user_id;
  6177. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6178. // 验证目标文件夹并确定目标是公共库还是个人库
  6179. $target_level = 0;
  6180. $target_uid = $uid; // 默认推送到个人库
  6181. $target_is_public = 0;
  6182. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6183. if ($target_parent_id > 0) {
  6184. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6185. $targetParent = DB::table('mp_products')
  6186. ->where('id', $target_parent_id)
  6187. ->where('cpid', $cpid)
  6188. ->where('type', 2)
  6189. ->where('is_deleted', 0)
  6190. ->first();
  6191. if (!$targetParent) {
  6192. Utils::throwError('20003:目标文件夹不存在');
  6193. }
  6194. // 通过user_id判断目标是公共库还是个人库
  6195. $target_level = $targetParent->level;
  6196. $target_uid = $targetParent->user_id;
  6197. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6198. // 使用目标文件夹的 product 类型
  6199. $final_product_type = $targetParent->product;
  6200. }
  6201. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6202. else {
  6203. $push_to_public = getProp($data, 'push_to_public');
  6204. if ($push_to_public === '') {
  6205. Utils::throwError('20003:请选择是否推送到公共库');
  6206. }
  6207. if ($push_to_public) {
  6208. $target_uid = 0;
  6209. $target_is_public = 1;
  6210. }
  6211. // 推送到根目录时,必须指定 product 类型
  6212. if ($target_product === null || $target_product === '') {
  6213. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6214. }
  6215. $final_product_type = $target_product;
  6216. }
  6217. // 如果目标是公共库,需要admin权限
  6218. if ($target_is_public && $role !== 'admin') {
  6219. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6220. }
  6221. // 权限验证:验证是否符合允许的推送规则
  6222. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6223. try {
  6224. DB::beginTransaction();
  6225. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6226. if ($sourceItem->type == 1) {
  6227. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6228. DB::commit();
  6229. return [
  6230. 'product_id' => $newId,
  6231. ];
  6232. }
  6233. // 如果是文件夹,递归复制(支持跨类型推送)
  6234. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6235. DB::commit();
  6236. return [
  6237. 'product_id' => $newFolderId,
  6238. ];
  6239. } catch (\Exception $e) {
  6240. DB::rollBack();
  6241. dLog('anime')->error('推送失败', [
  6242. 'error' => $e->getMessage(),
  6243. 'product_id' => $product_id
  6244. ]);
  6245. Utils::throwError('20003:' . $e->getMessage());
  6246. }
  6247. }
  6248. /**
  6249. * 验证推送权限
  6250. * 允许的推送规则:
  6251. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6252. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6253. * 3. 公共库推送给公共库(公共库 → 公共库)
  6254. *
  6255. * @param int $source_uid 源的user_id
  6256. * @param int $target_uid 目标的user_id
  6257. * @param int $current_uid 当前用户ID
  6258. * @throws \Exception
  6259. */
  6260. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6261. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6262. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6263. return; // 允许
  6264. }
  6265. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6266. if ($source_uid == 0 && $target_uid == $current_uid) {
  6267. return; // 允许
  6268. }
  6269. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6270. if ($source_uid == 0 && $target_uid == 0) {
  6271. return; // 允许
  6272. }
  6273. // 其他情况都不允许
  6274. if ($source_uid != 0 && $source_uid != $current_uid) {
  6275. // 源是别人的个人库
  6276. Utils::throwError('20003:无权限访问该资产');
  6277. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6278. // 个人库推送给公共库(不允许)
  6279. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6280. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6281. // 不同用户的个人库之间推送(不允许)
  6282. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6283. } else {
  6284. // 其他未知情况
  6285. Utils::throwError('20003:不允许的推送操作');
  6286. }
  6287. }
  6288. /**
  6289. * 复制单个资产
  6290. * @param object $sourceProduct 源资产对象
  6291. * @param int $targetParentId 目标父文件夹ID
  6292. * @param int $targetLevel 目标层级
  6293. * @param int $cpid 公司ID
  6294. * @param int $targetUid 目标用户ID
  6295. * @return int 返回新资产ID
  6296. */
  6297. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6298. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6299. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6300. $newProductData = [
  6301. 'user_id' => $targetUid,
  6302. 'cpid' => $cpid,
  6303. 'type' => 1,
  6304. 'parent_id' => $targetParentId,
  6305. 'level' => $targetLevel,
  6306. 'product_name' => $sourceProduct->product_name,
  6307. 'url' => $sourceProduct->url,
  6308. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6309. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6310. 'product' => $finalProductType,
  6311. 'versions' => $sourceProduct->versions ?? '',
  6312. 'sort_order' => time(),
  6313. 'is_deleted' => 0,
  6314. 'created_at' => date('Y-m-d H:i:s'),
  6315. 'updated_at' => date('Y-m-d H:i:s')
  6316. ];
  6317. return DB::table('mp_products')->insertGetId($newProductData);
  6318. }
  6319. /**
  6320. * 递归复制文件夹及其子项
  6321. * @param object $sourceFolder 源文件夹对象
  6322. * @param int $targetParentId 目标父文件夹ID
  6323. * @param int $targetLevel 目标层级
  6324. * @param int $cpid 公司ID
  6325. * @param int $targetUid 目标用户ID
  6326. * @param int $sourceUid 源用户ID
  6327. * @return int 返回新文件夹ID
  6328. */
  6329. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6330. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6331. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6332. // 创建新文件夹
  6333. $newFolderData = [
  6334. 'user_id' => $targetUid,
  6335. 'cpid' => $cpid,
  6336. 'type' => 2,
  6337. 'parent_id' => $targetParentId,
  6338. 'level' => $targetLevel,
  6339. 'product_name' => $sourceFolder->product_name,
  6340. 'product' => $finalProductType,
  6341. 'sort_order' => time(),
  6342. 'is_deleted' => 0,
  6343. 'created_at' => date('Y-m-d H:i:s'),
  6344. 'updated_at' => date('Y-m-d H:i:s')
  6345. ];
  6346. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6347. // 获取源文件夹下的所有子项
  6348. $children = DB::table('mp_products')
  6349. ->where('parent_id', $sourceFolder->id)
  6350. ->where('cpid', $cpid)
  6351. ->where('user_id', $sourceUid)
  6352. ->where('is_deleted', 0)
  6353. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6354. ->get();
  6355. // 递归复制子项(子项继承目标文件夹的 product 类型)
  6356. foreach ($children as $child) {
  6357. if ($child->type == 1) {
  6358. // 资产
  6359. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  6360. } else {
  6361. // 文件夹
  6362. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  6363. }
  6364. }
  6365. return $newFolderId;
  6366. }
  6367. /**
  6368. * 保存剧本资产关联关系
  6369. * @param array $data 请求参数
  6370. * @return bool
  6371. */
  6372. public function saveScriptProducts($data) {
  6373. $uid = Site::getUid();
  6374. $cpid = Site::getCpid();
  6375. $script_id = getProp($data, 'script_id');
  6376. $products = getProp($data, 'products', []);
  6377. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6378. if (!$script_id) {
  6379. Utils::throwError('20003:请提供剧本ID');
  6380. }
  6381. // 验证剧本是否存在
  6382. $script = DB::table('mp_scripts')
  6383. ->where('id', $script_id)
  6384. ->where('is_deleted', 0)
  6385. ->first();
  6386. if (!$script) {
  6387. Utils::throwError('20003:剧本不存在');
  6388. }
  6389. // 处理图片模型
  6390. $model = getProp($data, 'model');
  6391. if (!$model) {
  6392. // 使用默认模型
  6393. $model = 'doubao-seedream-5-0-lite-260128';
  6394. }
  6395. // 验证模型是否在可用模型表中
  6396. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6397. Utils::throwError('20003:该模型已不可用,请更换!');
  6398. }
  6399. $ratio = getProp($data, 'ratio', '9:16');
  6400. $resolution = getProp($data, 'resolution', '2k');
  6401. // 定义分辨率和宽高比对应的尺寸映射表
  6402. $sizeMap = [
  6403. '2k' => [
  6404. '1:1' => ['width' => 2048, 'height' => 2048],
  6405. '4:3' => ['width' => 2304, 'height' => 1728],
  6406. '3:4' => ['width' => 1728, 'height' => 2304],
  6407. '16:9' => ['width' => 2848, 'height' => 1600],
  6408. '9:16' => ['width' => 1600, 'height' => 2848],
  6409. '3:2' => ['width' => 2496, 'height' => 1664],
  6410. '2:3' => ['width' => 1664, 'height' => 2496],
  6411. '21:9' => ['width' => 3136, 'height' => 1344],
  6412. ],
  6413. '3k' => [
  6414. '1:1' => ['width' => 3072, 'height' => 3072],
  6415. '4:3' => ['width' => 3456, 'height' => 2592],
  6416. '3:4' => ['width' => 2592, 'height' => 3456],
  6417. '16:9' => ['width' => 4096, 'height' => 2304],
  6418. '9:16' => ['width' => 2304, 'height' => 4096],
  6419. '2:3' => ['width' => 2496, 'height' => 3744],
  6420. '3:2' => ['width' => 3744, 'height' => 2496],
  6421. '21:9' => ['width' => 4704, 'height' => 2016],
  6422. ],
  6423. '4k' => [
  6424. '1:1' => ['width' => 4096, 'height' => 4096],
  6425. '3:4' => ['width' => 3520, 'height' => 4704],
  6426. '4:3' => ['width' => 4704, 'height' => 3520],
  6427. '16:9' => ['width' => 5504, 'height' => 3040],
  6428. '9:16' => ['width' => 3040, 'height' => 5504],
  6429. '2:3' => ['width' => 3328, 'height' => 4992],
  6430. '3:2' => ['width' => 4992, 'height' => 3328],
  6431. '21:9' => ['width' => 6240, 'height' => 2656],
  6432. ],
  6433. ];
  6434. // 参数验证
  6435. $resolution = strtolower($resolution);
  6436. if (!isset($sizeMap[$resolution])) {
  6437. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6438. }
  6439. if (!isset($sizeMap[$resolution][$ratio])) {
  6440. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6441. }
  6442. // 根据 ratio 和 resolution 确定宽高
  6443. $width = $sizeMap[$resolution][$ratio]['width'];
  6444. $height = $sizeMap[$resolution][$ratio]['height'];
  6445. $script_name = $script->script_name ?? 'script_' . $script_id;
  6446. // 检查是否已经有该剧本的资产数据
  6447. $existingMappings = DB::table('mp_script_product_mappings')
  6448. ->where('script_id', $script_id)
  6449. ->get();
  6450. if ($existingMappings->isNotEmpty()) {
  6451. // 已存在资产映射,检查是否所有资产都有图片生成任务
  6452. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  6453. // 查询这些资产的图片生成任务状态
  6454. $productsWithTasks = DB::table('mp_products')
  6455. ->whereIn('id', $productIds)
  6456. ->where('is_deleted', 0)
  6457. ->get();
  6458. $productTaskMap = [];
  6459. $typeFolderIds = [];
  6460. $hasAllTasks = true;
  6461. foreach ($productsWithTasks as $product) {
  6462. // 收集类型文件夹ID
  6463. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  6464. $parentFolder = DB::table('mp_products')
  6465. ->where('id', $product->parent_id)
  6466. ->where('type', 2)
  6467. ->first();
  6468. if ($parentFolder) {
  6469. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  6470. }
  6471. }
  6472. // 检查是否有图片生成任务
  6473. if (!empty($product->pic_task_id)) {
  6474. $productTaskMap[$product->id] = $product->pic_task_id;
  6475. } else if($product->url && $product->pic_task_status == '生成成功') {
  6476. continue;
  6477. } else {
  6478. // 有资产没有图片任务
  6479. $hasAllTasks = false;
  6480. }
  6481. }
  6482. // 如果所有资产都有任务ID,直接轮询返回结果
  6483. if ($hasAllTasks && !empty($productTaskMap)) {
  6484. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  6485. 'script_id' => $script_id,
  6486. 'script_name' => $script_name,
  6487. 'product_count' => count($productTaskMap)
  6488. ]);
  6489. // 直接返回 SSE 流轮询结果
  6490. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6491. }
  6492. // 如果部分资产没有任务ID,只为这些资产创建任务
  6493. if (!$hasAllTasks && $auto_generate_images) {
  6494. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  6495. 'script_id' => $script_id,
  6496. 'script_name' => $script_name
  6497. ]);
  6498. // 开启事务
  6499. DB::beginTransaction();
  6500. try {
  6501. foreach ($productsWithTasks as $product) {
  6502. // 跳过已有任务的资产
  6503. if (!empty($product->pic_task_id)) {
  6504. continue;
  6505. }
  6506. // 跳过没有提示词的资产
  6507. if (empty($product->pic_prompt)) {
  6508. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6509. 'product_id' => $product->id,
  6510. 'product_name' => $product->product_name
  6511. ]);
  6512. continue;
  6513. }
  6514. try {
  6515. // 创建图片生成任务
  6516. $params = [
  6517. 'prompt' => $product->pic_prompt,
  6518. 'model' => $model,
  6519. 'ref_img_urls' => [],
  6520. 'width' => $width,
  6521. 'height' => $height
  6522. ];
  6523. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6524. $task_id = $task->id;
  6525. if ($task_id) {
  6526. $productTaskMap[$product->id] = $task_id;
  6527. // 在事务中更新资产表的任务ID和状态
  6528. DB::table('mp_products')
  6529. ->where('id', $product->id)
  6530. ->update([
  6531. 'pic_task_id' => $task_id,
  6532. 'pic_task_status' => '生成中',
  6533. 'updated_at' => now()
  6534. ]);
  6535. dLog('anime')->info('为已存在资产创建图片生成任务', [
  6536. 'product_id' => $product->id,
  6537. 'task_id' => $task_id
  6538. ]);
  6539. }
  6540. } catch (\Exception $e) {
  6541. dLog('anime')->error('创建资产图片生成任务失败', [
  6542. 'product_id' => $product->id,
  6543. 'error' => $e->getMessage()
  6544. ]);
  6545. // 标记为失败(仍在事务中)
  6546. DB::table('mp_products')
  6547. ->where('id', $product->id)
  6548. ->update([
  6549. 'pic_task_status' => '生成失败',
  6550. 'updated_at' => now()
  6551. ]);
  6552. }
  6553. }
  6554. // 提交事务
  6555. DB::commit();
  6556. // 如果有新创建的任务,返回 SSE 流
  6557. if (!empty($productTaskMap)) {
  6558. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6559. }
  6560. } catch (\Exception $e) {
  6561. // 回滚事务
  6562. DB::rollback();
  6563. dLog('anime')->error('为已存在资产创建图片任务失败', [
  6564. 'script_id' => $script_id,
  6565. 'error' => $e->getMessage()
  6566. ]);
  6567. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  6568. }
  6569. }
  6570. // 如果不需要生成图片,返回已存在的信息
  6571. return [
  6572. 'success' => true,
  6573. 'message' => '剧本资产已存在',
  6574. 'script_id' => $script_id,
  6575. 'script_name' => $script_name,
  6576. 'type_folder_ids' => $typeFolderIds,
  6577. 'existing_products' => count($productIds),
  6578. 'tasks_count' => count($productTaskMap)
  6579. ];
  6580. }
  6581. // 解析 products(可能是 JSON 字符串或数组)
  6582. if (is_string($products)) {
  6583. $products = json_decode($products, true);
  6584. if (json_last_error() !== JSON_ERROR_NONE) {
  6585. Utils::throwError('20003:产品数据格式错误');
  6586. }
  6587. }
  6588. if (!is_array($products) || empty($products)) {
  6589. Utils::throwError('20003:产品数据不能为空');
  6590. }
  6591. // 以下是原有的创建逻辑...
  6592. // 开启事务
  6593. DB::beginTransaction();
  6594. try {
  6595. $now = now();
  6596. $mappingRecords = [];
  6597. $createdProductIds = []; // 记录所有创建的资产ID
  6598. // 获取剧本名称
  6599. $script_name = $script->script_name ?? 'script_' . $script_id;
  6600. // 存储每个类型的根文件夹ID
  6601. $typeFolderIds = [];
  6602. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  6603. foreach ($products as $productGroup) {
  6604. $type = getProp($productGroup, 'type');
  6605. $title = getProp($productGroup, 'title', '');
  6606. $content = getProp($productGroup, 'content', []);
  6607. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  6608. continue;
  6609. }
  6610. // 为当前类型创建根文件夹(如果还未创建)
  6611. if (!isset($typeFolderIds[$type])) {
  6612. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  6613. 'user_id' => $uid,
  6614. 'cpid' => $cpid,
  6615. 'type' => 2, // 1.资产 2文件夹
  6616. 'product' => $type, // 1.主体 2.场景 3.道具
  6617. 'parent_id' => 0, // 根文件夹,parent_id=0
  6618. 'level' => 1, // 第一层级
  6619. 'product_name' => $script_name,
  6620. 'sort_order' => time() + $type,
  6621. 'is_deleted' => 0,
  6622. 'created_at' => $now,
  6623. 'updated_at' => $now
  6624. ]);
  6625. }
  6626. $folder_id = $typeFolderIds[$type];
  6627. // 获取表头(第一行)并查找关键列的位置
  6628. $headers = $content[0];
  6629. $nameColumnIndex = -1; // 资产名称列索引
  6630. $sequenceColumnIndex = -1; // 使用范围列索引
  6631. $promptColumnIndex = -1; // 参考提示词列索引
  6632. foreach ($headers as $index => $header) {
  6633. // 查找"资产名称"列
  6634. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  6635. $nameColumnIndex = $index;
  6636. }
  6637. // 查找"使用范围"列
  6638. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  6639. $sequenceColumnIndex = $index;
  6640. }
  6641. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  6642. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  6643. $promptColumnIndex = $index;
  6644. }
  6645. }
  6646. // 验证必要的列是否都找到了
  6647. if ($nameColumnIndex === -1) {
  6648. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  6649. continue;
  6650. }
  6651. if ($sequenceColumnIndex === -1) {
  6652. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  6653. continue;
  6654. }
  6655. // 跳过表头,解析每一行数据
  6656. for ($i = 1; $i < count($content); $i++) {
  6657. $row = $content[$i];
  6658. // 确保行数据有效
  6659. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  6660. continue;
  6661. }
  6662. // 根据动态查找的列索引提取数据
  6663. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  6664. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6665. $pic_prompt = '';
  6666. // 提取参考提示词(如果找到了该列)
  6667. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6668. $pic_prompt = trim($row[$promptColumnIndex]);
  6669. }
  6670. // 解析使用范围(逗号分隔的序号)
  6671. $sequences = [];
  6672. if (!empty($sequence_str)) {
  6673. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  6674. foreach ($sequenceParts as $part) {
  6675. if (is_numeric($part)) {
  6676. $sequences[] = (int)$part;
  6677. }
  6678. }
  6679. }
  6680. if (empty($product_name)) {
  6681. continue;
  6682. }
  6683. // 处理product_name两边的符号
  6684. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6685. // 如果名称不存在则跳过
  6686. if (!$product_name) continue;
  6687. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  6688. $product_id = DB::table('mp_products')->insertGetId([
  6689. 'product_name' => $product_name,
  6690. 'type' => 1, // 1=资产 2.文件夹
  6691. 'product' => $type, // 1=角色, 2=场景, 3=道具
  6692. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  6693. 'level' => 2, // 第二层级
  6694. 'pic_prompt' => $pic_prompt,
  6695. 'user_id' => $uid,
  6696. 'cpid' => $cpid,
  6697. 'sort_order' => time(),
  6698. 'is_deleted' => 0,
  6699. 'created_at' => $now,
  6700. 'updated_at' => $now,
  6701. ]);
  6702. // 记录创建的资产ID
  6703. $createdProductIds[] = $product_id;
  6704. // 为每个序号创建映射记录
  6705. if (!empty($sequences)) {
  6706. foreach ($sequences as $sequence) {
  6707. $mappingRecords[] = [
  6708. 'script_id' => $script_id,
  6709. 'product_id' => $product_id,
  6710. 'episode_number' => $sequence,
  6711. 'created_at' => $now,
  6712. 'updated_at' => $now,
  6713. ];
  6714. }
  6715. } else {
  6716. // 如果没有指定序号,创建一个默认映射(序号为0)
  6717. $mappingRecords[] = [
  6718. 'script_id' => $script_id,
  6719. 'product_id' => $product_id,
  6720. 'episode_number' => 0,
  6721. 'created_at' => $now,
  6722. 'updated_at' => $now,
  6723. ];
  6724. }
  6725. }
  6726. }
  6727. if (empty($mappingRecords)) {
  6728. Utils::throwError('20003:没有有效的产品数据');
  6729. }
  6730. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  6731. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  6732. // 如果需要自动生成图片,在事务中创建图片生成任务
  6733. $productTaskMap = [];
  6734. if ($auto_generate_images && !empty($createdProductIds)) {
  6735. // 查询所有创建的资产
  6736. $productsToGenerate = DB::table('mp_products')
  6737. ->whereIn('id', $createdProductIds)
  6738. ->where('is_deleted', 0)
  6739. ->get();
  6740. foreach ($productsToGenerate as $product) {
  6741. if (empty($product->pic_prompt)) {
  6742. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6743. 'product_id' => $product->id,
  6744. 'product_name' => $product->product_name
  6745. ]);
  6746. continue;
  6747. }
  6748. try {
  6749. // 创建图片生成任务
  6750. $params = [
  6751. 'prompt' => $product->pic_prompt,
  6752. 'model' => $model,
  6753. 'ref_img_urls' => [],
  6754. 'width' => $width,
  6755. 'height' => $height
  6756. ];
  6757. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6758. $task_id = $task->id;
  6759. if ($task_id) {
  6760. $productTaskMap[$product->id] = $task_id;
  6761. // 在事务中更新资产表的任务ID和状态
  6762. DB::table('mp_products')
  6763. ->where('id', $product->id)
  6764. ->update([
  6765. 'pic_task_id' => $task_id,
  6766. 'pic_task_status' => '生成中',
  6767. 'updated_at' => now()
  6768. ]);
  6769. dLog('anime')->info('创建资产图片生成任务', [
  6770. 'product_id' => $product->id,
  6771. 'task_id' => $task_id
  6772. ]);
  6773. }
  6774. } catch (\Exception $e) {
  6775. dLog('anime')->error('创建资产图片生成任务失败', [
  6776. 'product_id' => $product->id,
  6777. 'error' => $e->getMessage()
  6778. ]);
  6779. // 标记为失败(仍在事务中)
  6780. DB::table('mp_products')
  6781. ->where('id', $product->id)
  6782. ->update([
  6783. 'pic_task_status' => '生成失败',
  6784. 'updated_at' => now()
  6785. ]);
  6786. }
  6787. }
  6788. }
  6789. // 提交事务
  6790. DB::commit();
  6791. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6792. if ($auto_generate_images && !empty($productTaskMap)) {
  6793. // 返回 SSE 流(事务外轮询)
  6794. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6795. }
  6796. // 如果不需要生成图片,返回普通结果
  6797. return [
  6798. 'success' => true,
  6799. 'type_folder_ids' => $typeFolderIds,
  6800. 'inserted_count' => $insertedCount,
  6801. 'total_records' => count($mappingRecords),
  6802. 'created_products' => count($createdProductIds),
  6803. 'image_tasks_created' => count($productTaskMap)
  6804. ];
  6805. } catch (\Exception $e) {
  6806. // 回滚事务
  6807. DB::rollback();
  6808. // 记录错误日志
  6809. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6810. 'script_id' => $script_id,
  6811. 'error' => $e->getMessage(),
  6812. 'trace' => $e->getTraceAsString()
  6813. ]);
  6814. // 统一使用 Utils::throwError 抛出错误
  6815. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6816. }
  6817. }
  6818. /**
  6819. * 批量为剧本资产生成图片
  6820. *
  6821. * @param array $data 请求参数
  6822. * @return \Generator 返回 SSE 流
  6823. */
  6824. public function batchGenerateProductImages($data) {
  6825. $script_id = getProp($data, 'script_id');
  6826. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  6827. if (!$script_id) {
  6828. Utils::throwError('20003:请提供剧本ID');
  6829. }
  6830. // 验证剧本是否存在
  6831. $script = DB::table('mp_scripts')
  6832. ->where('id', $script_id)
  6833. ->where('is_deleted', 0)
  6834. ->first();
  6835. if (!$script) {
  6836. Utils::throwError('20003:剧本不存在');
  6837. }
  6838. $script_name = $script->script_name ?? 'script_' . $script_id;
  6839. // 获取需要生成图片的所有资产
  6840. $products = DB::table('mp_products')
  6841. ->whereIn('parent_id', array_values($type_folder_ids))
  6842. ->where('is_deleted', 0)
  6843. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  6844. ->get();
  6845. if ($products->isEmpty()) {
  6846. Utils::throwError('20003:没有找到需要生成图片的资产');
  6847. }
  6848. // 默认参数
  6849. $model = 'doubao-seedream-5-0-lite-260128';
  6850. $width = 1600;
  6851. $height = 2848;
  6852. // 开始为每个资产创建图片生成任务
  6853. $taskIds = [];
  6854. $productTaskMap = []; // 资产ID到任务ID的映射
  6855. foreach ($products as $product) {
  6856. if (empty($product->pic_prompt)) {
  6857. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  6858. continue;
  6859. }
  6860. try {
  6861. // 创建图片生成任务
  6862. $params = [
  6863. 'prompt' => $product->pic_prompt,
  6864. 'model' => $model,
  6865. 'ref_img_urls' => [],
  6866. 'width' => $width,
  6867. 'height' => $height
  6868. ];
  6869. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6870. $task_id = $task->id;
  6871. if ($task_id) {
  6872. $taskIds[] = $task_id;
  6873. $productTaskMap[$product->id] = $task_id;
  6874. // 更新资产表的任务ID和状态
  6875. DB::table('mp_products')
  6876. ->where('id', $product->id)
  6877. ->update([
  6878. 'pic_task_id' => $task_id,
  6879. 'pic_task_status' => '生成中',
  6880. 'updated_at' => now()
  6881. ]);
  6882. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  6883. }
  6884. } catch (\Exception $e) {
  6885. dLog('anime')->error('创建资产图片生成任务失败', [
  6886. 'product_id' => $product->id,
  6887. 'error' => $e->getMessage()
  6888. ]);
  6889. // 标记为失败
  6890. DB::table('mp_products')
  6891. ->where('id', $product->id)
  6892. ->update([
  6893. 'pic_task_status' => '生成失败',
  6894. 'updated_at' => now()
  6895. ]);
  6896. }
  6897. }
  6898. if (empty($taskIds)) {
  6899. Utils::throwError('20003:没有成功创建任何图片生成任务');
  6900. }
  6901. // 返回 SSE 流
  6902. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  6903. }
  6904. /**
  6905. * 轮询资产图片生成任务状态(SSE流式返回)
  6906. * 只通过查询数据库获取任务状态,不主动调用API
  6907. *
  6908. * @param int $script_id 剧本ID
  6909. * @param string $script_name 剧本名称
  6910. * @param array $productTaskMap 资产ID到任务ID的映射
  6911. * @param array $type_folder_ids 类型文件夹ID映射
  6912. * @return \Generator
  6913. */
  6914. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  6915. $startTime = time();
  6916. $timeout = 1800; // 30分钟超时
  6917. $pollInterval = 10; // 10秒轮询一次
  6918. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  6919. // 定义类型名称映射
  6920. $typeNames = [
  6921. 1 => 'roles', // 角色
  6922. 2 => 'scenes', // 场景
  6923. 3 => 'props' // 道具
  6924. ];
  6925. while (time() - $startTime < $timeout) {
  6926. sleep($pollInterval);
  6927. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  6928. $mappings = DB::table('mp_script_product_mappings')
  6929. ->where('script_id', $script_id)
  6930. ->pluck('product_id')
  6931. ->unique()
  6932. ->toArray();
  6933. if (empty($mappings)) {
  6934. dLog('anime')->warning('该剧本没有关联的资产', [
  6935. 'script_id' => $script_id,
  6936. 'script_name' => $script_name
  6937. ]);
  6938. break;
  6939. }
  6940. // 查询所有资产的当前状态
  6941. $products = DB::table('mp_products')
  6942. ->whereIn('id', $mappings)
  6943. ->where('is_deleted', 0)
  6944. ->get();
  6945. // 统计各类型的状态(使用类型名称作为键名)
  6946. $stats = [
  6947. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  6948. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  6949. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  6950. ];
  6951. $allCompleted = true;
  6952. $hasStatusChange = false;
  6953. foreach ($products as $product) {
  6954. $type = $product->product;
  6955. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  6956. // 如果类型名称不在 stats 中,初始化
  6957. if (!isset($stats[$typeName])) {
  6958. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  6959. }
  6960. $stats[$typeName]['total']++;
  6961. $task_id = $product->pic_task_id;
  6962. $currentStatus = $product->pic_task_status;
  6963. // 检查状态是否有变化
  6964. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  6965. $hasStatusChange = true;
  6966. $lastStatus[$product->id] = $currentStatus;
  6967. }
  6968. // 如果是生成中,查询任务表状态
  6969. if ($currentStatus === '生成中' && $task_id) {
  6970. // 只查询数据库,不调用API
  6971. $task = DB::table('mp_generate_pic_tasks')
  6972. ->where('id', $task_id)
  6973. ->first();
  6974. if ($task) {
  6975. // 检查任务状态
  6976. if ($task->status === 'success' && $task->result_url) {
  6977. // 解析图片URL
  6978. $result_urls = $task->result_url;
  6979. if (is_string($result_urls)) {
  6980. $result_urls = json_decode($result_urls, true);
  6981. }
  6982. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6983. // 更新资产表状态
  6984. DB::table('mp_products')
  6985. ->where('id', $product->id)
  6986. ->update([
  6987. 'pic_task_status' => '生成成功',
  6988. 'url' => $img_url,
  6989. 'updated_at' => now()
  6990. ]);
  6991. $stats[$typeName]['success']++;
  6992. $stats[$typeName]['completed']++;
  6993. $hasStatusChange = true;
  6994. dLog('anime')->info('资产图片生成成功', [
  6995. 'product_id' => $product->id,
  6996. 'task_id' => $task_id,
  6997. 'img_url' => $img_url
  6998. ]);
  6999. } elseif ($task->status === 'failed') {
  7000. // 更新资产表状态
  7001. DB::table('mp_products')
  7002. ->where('id', $product->id)
  7003. ->update([
  7004. 'pic_task_status' => '生成失败',
  7005. 'updated_at' => now()
  7006. ]);
  7007. $stats[$typeName]['completed']++;
  7008. $hasStatusChange = true;
  7009. dLog('anime')->warning('资产图片生成失败', [
  7010. 'product_id' => $product->id,
  7011. 'task_id' => $task_id,
  7012. 'error' => $task->error_message ?? '未知错误'
  7013. ]);
  7014. } else {
  7015. // 任务还在处理中
  7016. $allCompleted = false;
  7017. }
  7018. } else {
  7019. // 任务不存在,标记为失败
  7020. DB::table('mp_products')
  7021. ->where('id', $product->id)
  7022. ->update([
  7023. 'pic_task_status' => '生成失败',
  7024. 'updated_at' => now()
  7025. ]);
  7026. $stats[$type]['completed']++;
  7027. $hasStatusChange = true;
  7028. dLog('anime')->error('图片生成任务不存在', [
  7029. 'product_id' => $product->id,
  7030. 'task_id' => $task_id
  7031. ]);
  7032. }
  7033. } elseif ($currentStatus === '生成成功') {
  7034. $stats[$typeName]['success']++;
  7035. $stats[$typeName]['completed']++;
  7036. } elseif ($currentStatus === '生成失败') {
  7037. $stats[$typeName]['completed']++;
  7038. } else {
  7039. // 其他状态也认为未完成
  7040. $allCompleted = false;
  7041. }
  7042. }
  7043. // 移除没有数据的类型(total=0)
  7044. foreach ($stats as $typeName => $stat) {
  7045. if ($stat['total'] === 0) {
  7046. unset($stats[$typeName]);
  7047. }
  7048. }
  7049. // 如果有状态变化,发送 SSE 更新
  7050. if ($hasStatusChange) {
  7051. $eventType = $allCompleted ? 'complete' : 'update';
  7052. $response = [
  7053. 'type' => $eventType,
  7054. 'script_id' => $script_id,
  7055. 'script_name' => $script_name,
  7056. 'stats' => $stats,
  7057. 'timestamp' => date('Y-m-d H:i:s')
  7058. ];
  7059. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7060. dLog('anime')->info('SSE更新', [
  7061. 'event_type' => $eventType,
  7062. 'script_id' => $script_id,
  7063. 'script_name' => $script_name,
  7064. 'stats' => $stats
  7065. ]);
  7066. if ($allCompleted) {
  7067. dLog('anime')->info('所有资产图片生成任务已完成', [
  7068. 'script_id' => $script_id,
  7069. 'script_name' => $script_name,
  7070. 'stats' => $stats
  7071. ]);
  7072. break;
  7073. }
  7074. }
  7075. }
  7076. // 超时处理
  7077. if (time() - $startTime >= $timeout && !$allCompleted) {
  7078. $response = [
  7079. 'type' => 'timeout',
  7080. 'message' => '部分任务超时,请稍后查看结果',
  7081. 'script_id' => $script_id,
  7082. 'script_name' => $script_name,
  7083. 'timestamp' => date('Y-m-d H:i:s')
  7084. ];
  7085. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7086. dLog('anime')->warning('资产图片生成任务超时', [
  7087. 'script_id' => $script_id,
  7088. 'script_name' => $script_name,
  7089. 'timeout' => $timeout
  7090. ]);
  7091. }
  7092. }
  7093. /**
  7094. * 获取剧本关联的资产列表
  7095. * @param array $data 请求参数
  7096. * @return array
  7097. */
  7098. public function getScriptProducts($data) {
  7099. $uid = Site::getUid();
  7100. $cpid = Site::getCpid();
  7101. $script_id = getProp($data, 'script_id');
  7102. $episode_number = getProp($data, 'episode_number');
  7103. if (!$script_id) {
  7104. Utils::throwError('20003:请提供剧本ID');
  7105. }
  7106. // 验证剧本是否存在
  7107. $script = DB::table('mp_scripts')
  7108. ->where('id', $script_id)
  7109. ->where('is_deleted', 0)
  7110. ->first();
  7111. if (!$script) {
  7112. Utils::throwError('20003:剧本不存在');
  7113. }
  7114. // 联表查询资产信息
  7115. $query = DB::table('mp_script_product_mappings as mapping')
  7116. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7117. ->where('mapping.script_id', $script_id)
  7118. ->where('product.cpid', $cpid)
  7119. ->where('product.is_deleted', 0);
  7120. // 如果提供了 episode_number,则过滤指定集数
  7121. if ($episode_number !== null && $episode_number !== '') {
  7122. $query->where('mapping.episode_number', $episode_number);
  7123. }
  7124. $mappings = $query->select(
  7125. 'mapping.script_id',
  7126. 'mapping.product_id',
  7127. 'mapping.episode_number',
  7128. 'product.product_name',
  7129. 'product.type',
  7130. 'product.product',
  7131. 'product.pic_prompt',
  7132. 'product.url',
  7133. 'product.pic_task_id',
  7134. 'product.pic_task_status',
  7135. 'product.three_view_image_url',
  7136. 'mapping.created_at'
  7137. )
  7138. ->orderBy('mapping.product_id', 'asc')
  7139. ->orderBy('mapping.episode_number', 'asc')
  7140. ->get();
  7141. // 按 product_id 分组,合并 episode_number
  7142. $productMap = [];
  7143. foreach ($mappings as $item) {
  7144. $product_id = $item->product_id;
  7145. if (!isset($productMap[$product_id])) {
  7146. $productMap[$product_id] = [
  7147. 'product_id' => $product_id,
  7148. 'product_name' => $item->product_name,
  7149. 'type' => (int)$item->type,
  7150. 'product' => (int)$item->product,
  7151. 'pic_prompt' => $item->pic_prompt,
  7152. 'url' => $item->url,
  7153. 'pic_task_id' => $item->pic_task_id,
  7154. 'pic_task_status' => $item->pic_task_status,
  7155. 'episode_numbers' => [],
  7156. 'created_at' => $item->created_at,
  7157. ];
  7158. }
  7159. // 添加 episode_number(去重)
  7160. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7161. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7162. }
  7163. }
  7164. // 按类型分组
  7165. $roles = []; // type=1 角色/主体
  7166. $scenes = []; // type=2 场景
  7167. $props = []; // type=3 道具
  7168. foreach ($productMap as $product) {
  7169. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7170. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7171. // 构造返回数据
  7172. $productData = [
  7173. 'product_id' => $product['product_id'],
  7174. 'product_name' => $product['product_name'],
  7175. 'product' => $product['product'],
  7176. 'pic_prompt' => $product['pic_prompt'],
  7177. 'url' => $product['url'],
  7178. 'pic_task_id' => $product['pic_task_id'],
  7179. 'pic_task_status' => $product['pic_task_status'],
  7180. 'episode_numbers' => $episodeNumbersStr,
  7181. 'created_at' => $product['created_at'],
  7182. ];
  7183. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7184. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7185. switch ($product['product']) {
  7186. case 1:
  7187. $roles[] = $productData;
  7188. break;
  7189. case 2:
  7190. $scenes[] = $productData;
  7191. break;
  7192. case 3:
  7193. $props[] = $productData;
  7194. break;
  7195. }
  7196. }
  7197. return [
  7198. 'script_id' => $script_id,
  7199. 'script_name' => $script->script_name ?? '',
  7200. 'roles' => $roles, // 主体
  7201. 'scenes' => $scenes, // 场景
  7202. 'props' => $props, // 道具
  7203. ];
  7204. }
  7205. /**
  7206. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7207. * @param string $actContent 原始内容
  7208. * @param array $products 产品数组(包含product_name和url)
  7209. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7210. */
  7211. public function processActContentWithProducts($actContent, $products) {
  7212. if (empty($actContent) || empty($products)) {
  7213. return [
  7214. 'content' => $actContent,
  7215. 'reference_images' => []
  7216. ];
  7217. }
  7218. // 构建产品名称到产品信息的映射
  7219. $product_dict = [];
  7220. foreach ($products as $product) {
  7221. $product_name = getProp($product, 'product_name');
  7222. if ($product_name) {
  7223. $product_dict[$product_name] = [
  7224. 'url' => getProp($product, 'url'),
  7225. 'voice_prompt' => getProp($product, 'voice_prompt')
  7226. ];
  7227. }
  7228. }
  7229. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7230. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7231. $reference_images = [];
  7232. $product_index_map = []; // 产品名称 => 图片序号的映射
  7233. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7234. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7235. $current_index = 1;
  7236. if (!empty($matches[1])) {
  7237. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7238. $seen_products = []; // 用于去重
  7239. foreach ($matches[1] as $product_name) {
  7240. // 跳过已处理的产品
  7241. if (isset($seen_products[$product_name])) {
  7242. continue;
  7243. }
  7244. $seen_products[$product_name] = true;
  7245. // 检查产品是否在字典中
  7246. if (isset($product_dict[$product_name])) {
  7247. $url = $product_dict[$product_name]['url'];
  7248. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7249. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7250. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7251. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7252. }
  7253. // 只有URL非空才分配序号和添加到参考图片
  7254. if (!empty($url)) {
  7255. // 检查URL是否已经在reference_images中(去重)
  7256. if (!in_array($url, $reference_images)) {
  7257. $reference_images[] = $url;
  7258. $product_index_map[$product_name] = $current_index;
  7259. $current_index++;
  7260. } else {
  7261. // URL重复,找到已有的序号
  7262. $existing_index = array_search($url, $reference_images) + 1;
  7263. $product_index_map[$product_name] = $existing_index;
  7264. }
  7265. } else {
  7266. // URL为空,不分配序号(后续直接去掉{})
  7267. $product_index_map[$product_name] = 0;
  7268. }
  7269. } else {
  7270. // 产品不在字典中,不分配序号
  7271. $product_index_map[$product_name] = 0;
  7272. }
  7273. }
  7274. }
  7275. // 第二步:替换内容中的 {产品名称}
  7276. $processedContent = $actContent;
  7277. foreach ($product_index_map as $product_name => $index) {
  7278. $escaped_name = preg_quote($product_name, '/');
  7279. if ($index > 0) {
  7280. // 有图片,替换为:产品名称(图X)
  7281. $replacement = $product_name . '<图片' . $index . '>';
  7282. } else {
  7283. // 无图片,只保留产品名称
  7284. $replacement = $product_name;
  7285. }
  7286. // 替换所有 {产品名称} 为处理后的格式
  7287. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7288. }
  7289. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7290. foreach ($products as $product) {
  7291. $product_name = getProp($product, 'product_name');
  7292. $voice_prompt = getProp($product, 'voice_prompt');
  7293. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7294. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7295. break; // 找到旁白后退出循环
  7296. }
  7297. }
  7298. // 第四步:将voice_prompt信息添加到内容最前面
  7299. $voice_prompt_prefix = '';
  7300. if (!empty($voice_prompts)) {
  7301. $voice_prompt_prefix .= implode('', $voice_prompts);
  7302. }
  7303. // 旁白的voice_prompt放在最后
  7304. if (!empty($narrator_voice_prompt)) {
  7305. $voice_prompt_prefix .= $narrator_voice_prompt;
  7306. }
  7307. // 如果有voice_prompt信息,添加到内容开头
  7308. if (!empty($voice_prompt_prefix)) {
  7309. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7310. }
  7311. return [
  7312. 'content' => $processedContent,
  7313. 'reference_images' => $reference_images
  7314. ];
  7315. }
  7316. public function saveActVideoGenerateParams($data) {
  7317. $episode_id = getProp($data, 'episode_id');
  7318. $model = getProp($data, 'video_model');
  7319. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7320. Utils::throwError('20003:该模型不可用');
  7321. }
  7322. if (!$model) {
  7323. // 使用默认模型
  7324. $model = 'zhizhen-20';
  7325. }
  7326. // 验证模型是否在可用模型表中
  7327. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7328. Utils::throwError('20003:该模型已不可用,请更换!');
  7329. }
  7330. $video_resolution = getProp($data, 'video_resolution', '720p');
  7331. $ratio = getProp($data, 'ratio');
  7332. if (!$ratio) $ratio = '9:16';
  7333. return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7334. 'video_model' => $model,
  7335. 'video_resolution' => $video_resolution,
  7336. 'ratio' => $ratio,
  7337. 'updated_at' => date('Y-m-d H:i:s')
  7338. ]);
  7339. }
  7340. public function confirmActs($data) {
  7341. $episode_id = getProp($data, 'episode_id');
  7342. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7343. if (!$episode) {
  7344. Utils::throwError('20003:分集不存在');
  7345. }
  7346. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7347. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7348. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  7349. // 获取所有片段数据
  7350. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7351. // 收集所有资产名称(角色、场景、道具)
  7352. $product_names = [];
  7353. // 收集角色名称
  7354. foreach ($roles as $role) {
  7355. $role_name = getProp($role, 'role');
  7356. if ($role_name && $role_name != '旁白') {
  7357. $product_names[] = $role_name;
  7358. }
  7359. }
  7360. // 收集场景名称
  7361. foreach ($scenes as $scene) {
  7362. $scene_name = getProp($scene, 'scene');
  7363. if ($scene_name) {
  7364. $product_names[] = $scene_name;
  7365. }
  7366. }
  7367. // 收集道具名称
  7368. foreach ($props as $prop) {
  7369. $prop_name = getProp($prop, 'prop');
  7370. if ($prop_name) {
  7371. $product_names[] = $prop_name;
  7372. }
  7373. }
  7374. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  7375. $product_names = array_unique($product_names);
  7376. usort($product_names, function($a, $b) {
  7377. return mb_strlen($b) - mb_strlen($a);
  7378. });
  7379. try {
  7380. DB::beginTransaction();
  7381. // 处理每个片段
  7382. foreach ($acts as $act) {
  7383. $act_content = getProp($act, 'act_content');
  7384. if (!$act_content) continue;
  7385. $processed_content = $act_content;
  7386. // 统一替换所有资产名称为 {资产名} 格式
  7387. // 使用占位符避免嵌套替换问题
  7388. $placeholder_map = [];
  7389. $placeholder_index = 0;
  7390. foreach ($product_names as $product_name) {
  7391. // 转义特殊字符
  7392. $escaped_product = preg_quote($product_name, '/');
  7393. // 检查是否匹配且未被 {} 包裹
  7394. $processed_content = preg_replace_callback(
  7395. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  7396. function($matches) use (&$placeholder_map, &$placeholder_index) {
  7397. // 使用唯一占位符
  7398. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  7399. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  7400. $placeholder_index++;
  7401. return $placeholder;
  7402. },
  7403. $processed_content
  7404. );
  7405. }
  7406. // 将所有占位符替换回实际内容
  7407. foreach ($placeholder_map as $placeholder => $replacement) {
  7408. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  7409. }
  7410. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7411. $shot_counter = 0;
  7412. $processed_content = preg_replace_callback(
  7413. '/【(?:镜头|分镜)(\d+)】/u',
  7414. function($matches) use (&$shot_counter) {
  7415. $shot_counter++;
  7416. return '【镜头' . $shot_counter . '】';
  7417. },
  7418. $processed_content
  7419. );
  7420. // 更新数据库
  7421. $boolen = DB::table('mp_episode_segments')
  7422. ->where('id', $act->id)
  7423. ->update([
  7424. 'act_show_content' => $processed_content,
  7425. 'updated_at' => date('Y-m-d H:i:s')
  7426. ]);
  7427. if (!$boolen) {
  7428. Utils::throwError('20003:片段处理失败');
  7429. }
  7430. }
  7431. }catch (\Exception $e) {
  7432. DB::rollBack();
  7433. Utils::throwError('20003:'.$e->getMessage());
  7434. }
  7435. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7436. 'is_generated' => 1,
  7437. 'updated_at' => date('Y-m-d H:i:s')
  7438. ]);
  7439. if (!$boolen1) {
  7440. DB::rollBack();
  7441. Utils::throwError('20003:分集处理失败!');
  7442. }
  7443. DB::commit();
  7444. // 重新查询更新后的片段数据
  7445. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7446. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  7447. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  7448. $products = [];
  7449. // 先处理角色数组
  7450. foreach ($roles as $role) {
  7451. $product = $role;
  7452. // 将role字段重命名为product_name
  7453. if (isset($product['role'])) {
  7454. $product['product_name'] = $product['role'];
  7455. unset($product['role']);
  7456. $product['product'] = 1; // 标记类型为角色
  7457. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7458. }
  7459. }
  7460. // 处理场景数组
  7461. foreach ($scenes as $scene) {
  7462. $product = $scene;
  7463. // 将scene字段重命名为product_name
  7464. if (isset($product['scene'])) {
  7465. $product['product_name'] = $product['scene'];
  7466. unset($product['scene']);
  7467. $product['product'] = 2; // 标记类型为场景
  7468. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7469. }
  7470. }
  7471. // 处理道具数组(逻辑与场景一致)
  7472. foreach ($props as $prop) {
  7473. $product = $prop;
  7474. // 将prop字段重命名为product_name
  7475. if (isset($product['prop'])) {
  7476. $product['product_name'] = $product['prop'];
  7477. unset($product['prop']);
  7478. $product['product'] = 3; // 标记类型为道具
  7479. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7480. }
  7481. }
  7482. // extra_products优先级更高,直接覆盖同名的roles和scenes
  7483. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  7484. foreach ($extra_products as $extra_product) {
  7485. $product_name = getProp($extra_product, 'product_name');
  7486. if ($product_name) {
  7487. $products[$product_name] = $extra_product; // 覆盖同名数据
  7488. }
  7489. }
  7490. // 重新索引数组(去除key)
  7491. $products = array_values($products);
  7492. // 构建返回的acts数组
  7493. $return_acts = [];
  7494. foreach ($acts as $act) {
  7495. $return_acts[] = [
  7496. 'act_id' => getProp($act, 'id'),
  7497. 'act_number' => getProp($act, 'act_number'),
  7498. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  7499. 'act_show_content' => getProp($act, 'act_show_content'),
  7500. 'video_url' => getProp($act, 'video_url'),
  7501. 'video_duration' => getProp($act, 'video_duration'),
  7502. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  7503. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  7504. ];
  7505. }
  7506. return [
  7507. 'anime_id' => getProp($episode, 'anime_id'),
  7508. 'episode_id' => $episode_id,
  7509. 'title' => getProp($episode, 'title'),
  7510. 'episode_number' => getProp($episode, 'episode_number'),
  7511. 'is_generated' => getProp($episode, 'is_generated'),
  7512. 'products' => $products,
  7513. 'acts' => $return_acts
  7514. ];
  7515. }
  7516. }