AnimeService.php 369 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560
  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 Dflydev\DotAccessData\Util;
  12. use GuzzleHttp\Client;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. use OSS\Core\OssException;
  17. use OSS\OssClient;
  18. class AnimeService
  19. {
  20. protected $aiImageGenerationService;
  21. protected $aiVideoGenerationService;
  22. protected $DeepSeekService;
  23. private $url;
  24. private $api_key;
  25. private $headers;
  26. public function __construct(
  27. AIImageGenerationService $aiImageGenerationService,
  28. AIVideoGenerationService $aiVideoGenerationService,
  29. DeepSeekService $DeepSeekService
  30. ) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->aiVideoGenerationService = $aiVideoGenerationService;
  33. $this->DeepSeekService = $DeepSeekService;
  34. $this->url = 'https://api.deepseek.com/chat/completions';
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. }
  41. /**
  42. * 构建统一的分镜数据结构(episodeInfo格式)
  43. * @param array $segments 分镜数据数组
  44. * @return array 返回包含acts和total_duration的数组
  45. */
  46. public function buildEpisodeSegmentsStructure($segments) {
  47. $acts = [];
  48. $totalDuration = 0; // 初始化总时长
  49. foreach($segments as $segment) {
  50. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  51. $videoDuration = getProp($segment, 'video_duration');
  52. $audioDuration = getProp($segment, 'audio_duration');
  53. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  54. $totalDuration += floatval($videoDuration);
  55. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  56. $totalDuration += floatval($audioDuration);
  57. } else {
  58. $totalDuration += 5; // 默认5秒
  59. }
  60. $segment_content = getProp($segment, 'segment_content');
  61. // 判断是否有尾帧描述,如果有则去掉这部分内容
  62. if (strpos($segment_content, '尾帧') !== false) {
  63. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  64. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  65. }
  66. // 构建分镜信息
  67. $segmentInfo = [
  68. 'segment_id' => getProp($segment, 'segment_id'),
  69. 'segment_number' => getProp($segment, 'segment_number'),
  70. 'segment_content' => $segment_content,
  71. 'description' => getProp($segment, 'description'),
  72. 'composition' => getProp($segment, 'composition'),
  73. 'camera_movement' => getProp($segment, 'camera_movement'),
  74. 'voice_actor' => getProp($segment, 'voice_actor'),
  75. 'dialogue' => getProp($segment, 'dialogue'),
  76. 'frame_type' => getProp($segment, 'frame_type'),
  77. 'scene' => getProp($segment, 'scene'),
  78. 'characters' => getProp($segment, 'characters'),
  79. 'tail_frame' => getProp($segment, 'tail_frame'),
  80. 'emotion' => getProp($segment, 'emotion'),
  81. 'emotion_type' => getProp($segment, 'emotion_type'),
  82. 'gender' => getProp($segment, 'gender'),
  83. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  84. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  85. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  86. 'pitch' => getProp($segment, 'pitch'),
  87. 'voice_name' => getProp($segment, 'voice_name'),
  88. 'voice_type' => getProp($segment, 'voice_type'),
  89. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  90. 'img_url' => getProp($segment, 'img_url'),
  91. 'audio_url' => getProp($segment, 'audio_url'),
  92. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  93. 'video_url' => getProp($segment, 'video_url'),
  94. 'video_duration' => getProp($segment, 'video_duration', 0),
  95. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  96. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  97. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  98. 'current_type' => getProp($segment, 'current_type'),
  99. ];
  100. $actNumber = getProp($segment, 'act_number');
  101. if (isset($acts[$actNumber])) {
  102. $acts[$actNumber]['segments'][] = $segmentInfo;
  103. } else {
  104. $acts[$actNumber] = [
  105. 'act_number' => $actNumber,
  106. 'act_title' => getProp($segment, 'act_title'),
  107. 'act_duration' => getProp($segment, 'act_duration'),
  108. 'segments' => [$segmentInfo]
  109. ];
  110. }
  111. }
  112. return [
  113. 'acts' => array_values($acts),
  114. 'total_duration' => intval(round($totalDuration))
  115. ];
  116. }
  117. /**
  118. * 构建统一的分段数据结构(episodeInfoForAce格式)
  119. * @param array $segments 分段数据数组
  120. * @return array 返回包含acts和total_duration的数组
  121. */
  122. public function buildEpisodeActsStructureForAce($segments) {
  123. $acts = [];
  124. $totalDuration = 0; // 初始化总时长
  125. foreach($segments as $segment) {
  126. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  127. $videoDuration = getProp($segment, 'video_duration');
  128. $actDuration = getProp($segment, 'act_duration');
  129. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  130. $totalDuration += floatval($videoDuration);
  131. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  132. $totalDuration += floatval($actDuration);
  133. } else {
  134. $totalDuration += 5; // 默认5秒
  135. }
  136. // 构建分镜信息
  137. $segmentInfo = [
  138. 'act_id' => getProp($segment, 'id'),
  139. 'act_number' => getProp($segment, 'act_number'),
  140. 'act_title' => getProp($segment, 'act_title'),
  141. 'act_duration' => getProp($segment, 'act_duration'),
  142. 'act_content' => getProp($segment, 'act_content'),
  143. 'video_url' => getProp($segment, 'video_url'),
  144. 'video_duration' => getProp($segment, 'video_duration', 0),
  145. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  146. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  147. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  148. 'current_type' => getProp($segment, 'current_type'),
  149. ];
  150. $acts[] = $segmentInfo;
  151. }
  152. return [
  153. 'acts' => array_values($acts),
  154. 'total_duration' => intval(round($totalDuration))
  155. ];
  156. }
  157. /**
  158. * 验证画面比例是否有效
  159. * @param string $ratio 画面比例
  160. * @return bool
  161. */
  162. public function validateRatio($ratio) {
  163. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  164. }
  165. /**
  166. * 获取画面比例对应的宽高
  167. * @param string $ratio 画面比例
  168. * @return array ['width' => int, 'height' => int]
  169. * @throws \Exception
  170. */
  171. private function getRatioDimensions($ratio) {
  172. if ($ratio && !$this->validateRatio($ratio)) {
  173. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  174. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  175. }
  176. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  177. }
  178. public function createAnime($data) {
  179. $uid = Site::getUid();
  180. $input_art_style = getProp($data, 'art_style');
  181. $file = getProp($data, 'file');
  182. $content = getProp($data, 'content', '');
  183. $bid = getProp($data, 'bid', 0);
  184. $script_id = getProp($data, 'script_id', 0);
  185. $ace_mode = getProp($data, 'ace_mode', 0);
  186. $extra_products = getProp($data, 'products', []);
  187. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  188. if (!is_array($extra_products)) {
  189. Utils::throwError('20003:传入的资产格式不正确');
  190. }
  191. // 替换美术风格
  192. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  193. // 提取文件内容
  194. if ($file) {
  195. $content = $this->DeepSeekService->extractFileContent($file);
  196. if (!$content) {
  197. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  198. }
  199. } elseif ($script_id) {
  200. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  201. if (!$content) {
  202. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  203. }
  204. } elseif ($bid) {
  205. $content = $this->DeepSeekService->getContentByBid($bid);
  206. if (!$content) {
  207. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  208. }
  209. } elseif ($content) {
  210. $content = filterContent($content);
  211. }else {
  212. $content = '';
  213. }
  214. $anime_data = [
  215. 'user_id' => $uid,
  216. 'anime_name' => '新剧本策划',
  217. 'is_multi' => getProp($data, 'is_multi', 1),
  218. 'content' => $content,
  219. 'art_style_type' => $input_art_style,
  220. 'ace_mode' => $ace_mode,
  221. 'script_id' => $script_id,
  222. 'extra_products' => json_encode($extra_products, 256),
  223. 'created_at' => date('Y-m-d H:i:s'),
  224. 'updated_at' => date('Y-m-d H:i:s'),
  225. ];
  226. // 处理文本模型
  227. $model = getProp($data, 'model');
  228. if (!$model) {
  229. // 用户没有输入,使用默认值
  230. $model = 'doubao-seed-2-0-mini-260215';
  231. }
  232. // 验证模型是否在可用模型表中
  233. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  234. $model = 'doubao-seed-2-0-mini-260215';
  235. }
  236. $anime_data['model'] = $model;
  237. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  238. return DB::table('mp_animes')->insertGetId($anime_data);
  239. }
  240. public function chatList($data) {
  241. $uid = Site::getUid();
  242. $anime_name = getProp($data, 'anime_name');
  243. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  244. if ($anime_name) {
  245. $query->where('anime_name', 'like', "%$anime_name%");
  246. }
  247. return $query->orderBy('id', 'desc')->paginate();
  248. }
  249. public function chatHistory($data) {
  250. $anime_id = getProp($data, 'anime_id');
  251. $sequence = getProp($data, 'sequence', 0);
  252. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  253. $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)
  254. ->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');
  255. return $query->orderBy('ar.id')->get()->map(function ($value) {
  256. $value = (array)$value;
  257. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  258. $value['created_at'] = transDate($value['created_at']);
  259. $value['episode_created_at'] = transDate($value['episode_created_at']);
  260. return $value;
  261. })->toArray();
  262. }
  263. public function batchSetRoleImg($data) {
  264. $episode_id = getProp($data, 'episode_id');
  265. if (!$episode_id) Utils::throwError('1002:请选择分集');
  266. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  267. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  268. $art_style = getProp($episode, 'art_style');
  269. $anime_id = getProp($episode, 'anime_id');
  270. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  271. $art_style_type = getProp($anime, 'art_style_type');
  272. $character_prefix = '';
  273. $scene_prefix = '';
  274. if ($art_style_type) {
  275. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  276. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  277. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  278. }
  279. foreach ($roles as &$role) {
  280. $role_name = getProp($role, 'role');
  281. if ($role_name == '旁白') continue;
  282. // 优先使用 pic_prompt,如果没有则使用 description
  283. $pic_prompt = getProp($role, 'pic_prompt');
  284. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  285. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  286. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  287. // 参考图地址
  288. $ref_img_url = getProp($role, 'url');
  289. if ($ref_img_url) continue; // 已有图片则跳过
  290. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  291. try {
  292. $params = [
  293. 'prompt' => $description,
  294. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  295. ];
  296. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  297. $task_id = $task->id;
  298. if (!$task_id) {
  299. Utils::throwError("20003:角色({$role_name})生成图片失败");
  300. }
  301. $role['task_id'] = $task_id;
  302. $role['task_status'] = 'processing';
  303. } catch (\Exception $e) {
  304. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  305. Utils::throwError("20003:" . $e->getMessage());
  306. }
  307. }
  308. // 保存角色信息
  309. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  310. 'roles' => json_encode($roles, 256),
  311. 'generate_status' => '执行中',
  312. 'generate_at' => date('Y-m-d H:i:s'),
  313. 'updated_at' => date('Y-m-d H:i:s')
  314. ]);
  315. if (!$boolen) {
  316. Utils::throwError('20003:保存角色信息失败');
  317. }
  318. return $boolen;
  319. }
  320. public function batchSetSceneImg($data) {
  321. $episode_id = getProp($data, 'episode_id');
  322. if (!$episode_id) Utils::throwError('1002:请选择分集');
  323. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  324. $scenes = json_decode(getProp($episode, 'scenes'), true);
  325. $art_style = getProp($episode, 'art_style');
  326. $target_scene = getProp($data, 'target_scene');
  327. $anime_id = getProp($episode, 'anime_id');
  328. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  329. $art_style_type = getProp($anime, 'art_style_type');
  330. $character_prefix = '';
  331. $scene_prefix = '';
  332. if ($art_style_type) {
  333. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  334. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  335. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  336. }
  337. foreach ($scenes as &$scene) {
  338. $scene_name = getProp($scene, 'scene');
  339. if ($scene_name != $target_scene) continue;
  340. // 优先使用 pic_prompt,如果没有则使用 description
  341. $pic_prompt = getProp($scene, 'pic_prompt');
  342. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  343. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  344. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  345. // 参考图地址
  346. $ref_img_url = getProp($scene, 'url');
  347. if ($ref_img_url) continue; // 已有图片则跳过
  348. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  349. try {
  350. $params = [
  351. 'prompt' => $description,
  352. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  353. ];
  354. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  355. $task_id = $task->id;
  356. if (!$task_id) {
  357. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  358. }
  359. $scene['task_id'] = $task_id;
  360. $scene['task_status'] = 'processing';
  361. } catch (\Exception $e) {
  362. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  363. Utils::throwError("20003:" . $e->getMessage());
  364. }
  365. }
  366. // 保存场景信息
  367. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  368. 'scenes' => json_encode($scenes, 256),
  369. 'generate_status' => '执行中',
  370. 'generate_at' => date('Y-m-d H:i:s'),
  371. 'updated_at' => date('Y-m-d H:i:s')
  372. ]);
  373. if (!$boolen) {
  374. Utils::throwError('20003:保存角色信息失败');
  375. }
  376. return $boolen;
  377. }
  378. public function editAnime($data) {
  379. $anime_id = getProp($data, 'anime_id');
  380. $anime_name = trim(getProp($data, 'anime_name'));
  381. // 确认对话名称唯一性
  382. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  383. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  384. }
  385. if (!$anime_id || !$anime_name) {
  386. Utils::throwError('20003:参数异常');
  387. }
  388. return DB::table('mp_animes')->where('id', $anime_id)->update([
  389. 'anime_name' => $anime_name,
  390. 'updated_at' => date('Y-m-d H:i:s')
  391. ]);
  392. // $script_arr =getProp($data, 'script', []);
  393. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  394. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  395. // $anime_id = getProp($data, 'anime_id');
  396. // try {
  397. // DB::beginTransaction();
  398. // $table_data = [
  399. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  400. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  401. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  402. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  403. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  404. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  405. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  406. // 'status' => 3,
  407. // 'start_episode_sequence' => $start_episode_sequence,
  408. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  409. // 'episode_num' => count($script_arr['episodes']),
  410. // 'updated_at' => date('Y-m-d H:i:s')
  411. // ];
  412. // // 保存剧本内容
  413. // if (!empty($anime_id)) {
  414. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  415. // if (!$boolen) {
  416. // dLog('anime')->info('对话保存失败', $table_data);
  417. // Utils::throwError('20003:对话保存失败');
  418. // }
  419. // }else {
  420. // $table['created_at'] = $table_data['updated_at'];
  421. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  422. // if (!$anime_id) {
  423. // dLog('anime')->info('对话保存失败', $table_data);
  424. // Utils::throwError('20003:对话保存失败');
  425. // }
  426. // }
  427. // // 保存分集内容
  428. // // 删除历史分集内容
  429. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  430. // $episodes = [];
  431. // $sequence = 1;
  432. // foreach ($script_arr['episodes'] as $episode) {
  433. // $segment_number = 1;
  434. // foreach($episode['segments'] as $segment) {
  435. // $episodes[] = [
  436. // 'anime_id' => $anime_id,
  437. // 'episode_number' => $episode['episode_number'],
  438. // 'title' => $episode['title'],
  439. // // 'content' => $episode['content'],
  440. // 'content' => '',
  441. // 'segment_number' => $segment_number,
  442. // 'segment_content' => $segment['segment_content'],
  443. // 'sequence' => $sequence,
  444. // 'created_at' => date('Y-m-d H:i:s'),
  445. // 'updated_at' => date('Y-m-d H:i:s')
  446. // ];
  447. // $sequence++;
  448. // $segment_number++;
  449. // }
  450. // }
  451. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  452. // if (!$boolen2) {
  453. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  454. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  455. // Utils::throwError('20003:分集内容保存失败');
  456. // }
  457. // } catch (\Exception $e) {
  458. // DB::rollBack();
  459. // Utils::throwError('20003:'.$e->getMessage());
  460. // }
  461. // DB::commit();
  462. // return true;
  463. }
  464. public function delAnime($data) {
  465. $anime_id = getProp($data, 'anime_id');
  466. if (!$anime_id) {
  467. Utils::throwError('20003:请选择剧本');
  468. }
  469. return DB::table('mp_animes')->where('id', $anime_id)->update([
  470. 'is_deleted' => 1,
  471. 'updated_at' => date('Y-m-d H:i:s')
  472. ]);
  473. }
  474. public function animeDetail($data) {
  475. $uid = Site::getUid();
  476. $anime_id = getProp($data, 'anime_id');
  477. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  478. ->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')->first();
  479. if (!$anime) Utils::throwError('20003:权限不足');
  480. $anime = (array)$anime;
  481. $anime['roles'] = json_decode($anime['roles']);
  482. $anime['scenes'] = json_decode($anime['scenes']);
  483. // 获取分集信息
  484. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  485. ->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"))
  486. ->orderBy('episode_number')->get()->map(function ($value) {
  487. return (array)$value;
  488. })->toArray();
  489. $anime['episodes'] = $episodes;
  490. return $anime;
  491. }
  492. public function episodeInfo($data) {
  493. $uid = Site::getUid();
  494. $anime_id = getProp($data, 'anime_id');
  495. $episode_id = getProp($data, 'episode_id');
  496. if (!$anime_id || !$episode_id) {
  497. Utils::throwError('1002:请选择剧集');
  498. }
  499. // 验证用户权限
  500. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  501. if (!$anime) Utils::throwError('20003:权限不足');
  502. $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();
  503. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  504. $episode = (array)$episode;
  505. $episode['roles'] = json_decode($episode['roles'], true);
  506. // foreach($episode['roles'] as &$item) {
  507. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  508. // }
  509. $episode['scenes'] = json_decode($episode['scenes'], true);
  510. // foreach($episode['scenes'] as &$item) {
  511. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  512. // }
  513. // 获取分镜信息
  514. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  515. ->select('*')->get()->map(function ($value) {
  516. return (array)$value;
  517. })->toArray();
  518. // 使用公共方法构建分镜结构
  519. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  520. $episode['acts'] = $segmentsStructure['acts'];
  521. $episode['total_duration'] = $segmentsStructure['total_duration'];
  522. return $episode;
  523. }
  524. public function episodeInfoForAce($data) {
  525. $anime_id = getProp($data, 'anime_id');
  526. $episode_id = getProp($data, 'episode_id');
  527. if (!$anime_id || !$episode_id) {
  528. Utils::throwError('1002:请选择剧集');
  529. }
  530. $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();
  531. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  532. $episode = (array)$episode;
  533. $episode['roles'] = json_decode($episode['roles'], true);
  534. // foreach($episode['roles'] as &$item) {
  535. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  536. // }
  537. $episode['scenes'] = json_decode($episode['scenes'], true);
  538. // foreach($episode['scenes'] as &$item) {
  539. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  540. // }
  541. // 获取分镜信息
  542. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  543. ->select('*')->get()->map(function ($value) {
  544. return (array)$value;
  545. })->toArray();
  546. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  547. $episode['acts'] = $segmentsStructure['acts'];
  548. $episode['total_duration'] = $segmentsStructure['total_duration'];
  549. return $episode;
  550. }
  551. public function segmentInfo($data) {
  552. $uid = Site::getUid();
  553. $segment_id = getProp($data, 'segment_id');
  554. if (!$segment_id) {
  555. Utils::throwError('1002:请选择分镜');
  556. }
  557. // 获取分镜信息
  558. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  559. // 验证用户权限
  560. if ($segment) {
  561. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  562. if (!$anime) Utils::throwError('20003:权限不足');
  563. }
  564. $result = [
  565. 'segment_id' => getProp($segment, 'segment_id'),
  566. 'segment_number' => getProp($segment, 'segment_number'),
  567. 'segment_content' => getProp($segment, 'segment_content'),
  568. 'description' => getProp($segment, 'description'),
  569. 'composition' => getProp($segment, 'composition'),
  570. 'camera_movement' => getProp($segment, 'camera_movement'),
  571. 'voice_actor' => getProp($segment, 'voice_actor'),
  572. 'dialogue' => getProp($segment, 'dialogue'),
  573. 'frame_type' => getProp($segment, 'frame_type'),
  574. 'scene' => getProp($segment, 'scene'),
  575. 'characters' => getProp($segment, 'characters'),
  576. 'tail_frame' => getProp($segment, 'tail_frame'),
  577. 'emotion' => getProp($segment, 'emotion'),
  578. 'emotion_type' => getProp($segment, 'emotion_type'),
  579. 'gender' => getProp($segment, 'gender'),
  580. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  581. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  582. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  583. 'pitch' => getProp($segment, 'pitch'),
  584. 'voice_name' => getProp($segment, 'voice_name'),
  585. 'voice_type' => getProp($segment, 'voice_type'),
  586. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  587. 'img_url' => getProp($segment, 'img_url'),
  588. 'video_url' => getProp($segment, 'video_url'),
  589. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  590. ];
  591. return $result;
  592. }
  593. public function copyEpisodeVersion($data) {
  594. $episode_id = getProp($data, 'episode_id');
  595. $uid = Site::getUid();
  596. $cpid = Site::getCpid();
  597. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  598. if (!$episode) Utils::throwError('20003:该剧集不存在');
  599. $episode = (array)$episode;
  600. $anime_id = $episode['anime_id'];
  601. $episode_number = $episode['episode_number'];
  602. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  603. $sequence = $count + 1;
  604. unset($episode['id']);
  605. $now = date('Y-m-d H:i:s');
  606. $episode['created_at'] = $now;
  607. $episode['updated_at'] = $now;
  608. $episode['is_default'] = 1;
  609. // 获取版本中含有"(副本"字样的个数
  610. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  611. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  612. $episode['sequence'] = $sequence;
  613. $episode['is_generated'] = 0;
  614. $episode['cpid'] = $cpid;
  615. // 获取ace_mode
  616. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  617. try {
  618. DB::beginTransaction();
  619. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  620. // 新增副本
  621. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  622. if (!$new_episode_id) {
  623. Utils::throwError('20003:创建副本失败!');
  624. }
  625. // 获取分镜数据并准备插入
  626. $segments_for_insert = DB::table('mp_episode_segments')
  627. ->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')
  628. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  629. $item = (array)$item;
  630. $item['episode_id'] = $new_episode_id;
  631. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  632. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  633. return $item;
  634. })->toArray();
  635. // 写入分镜数据
  636. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  637. if (!$boolen2) {
  638. Utils::throwError('20003:写入分镜数据失败!');
  639. }
  640. // 写入对话历史
  641. $records = [
  642. [
  643. 'uid' => $uid,
  644. 'anime_id' => $anime_id,
  645. 'role' => 'user',
  646. 'content' => '创建副本',
  647. 'sequence' => $episode_number,
  648. 'episode_id' => $new_episode_id,
  649. 'created_at' => $now,
  650. 'updated_at' => $now
  651. ],
  652. [
  653. 'uid' => $uid,
  654. 'anime_id' => $anime_id,
  655. 'role' => 'assistant',
  656. 'content' => '好的,已为您创建副本',
  657. 'sequence' => $episode_number,
  658. 'episode_id' => $new_episode_id,
  659. 'created_at' => $now,
  660. 'updated_at' => $now
  661. ]
  662. ];
  663. $boolen3 = DB::table('mp_anime_records')->insert($records);
  664. if (!$boolen3) {
  665. Utils::throwError('20003:对话记录保存失败');
  666. }
  667. }catch (\Exception $e) {
  668. DB::rollBack();
  669. Utils::throwError('20003:'.$e->getMessage());
  670. }
  671. DB::commit();
  672. // 构建与 episodeInfo 方法一致的返回数据结构
  673. $result = [
  674. 'episode_id' => $new_episode_id,
  675. 'anime_id' => $anime_id,
  676. 'episode_number' => $episode_number,
  677. 'title' => $episode['title'],
  678. 'intro' => $episode['intro'],
  679. 'art_style' => $episode['art_style'],
  680. 'roles' => json_decode($episode['roles'], true),
  681. 'scenes' => json_decode($episode['scenes'], true),
  682. 'is_generated' => (int)$episode['is_generated']
  683. ];
  684. if ((int)$ace_mode === 1) {
  685. // 获取分镜信息
  686. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  687. ->select('*')->get()->map(function ($value) {
  688. return (array)$value;
  689. })->toArray();
  690. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  691. }else {
  692. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  693. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  694. }
  695. $result['acts'] = $segmentsStructure['acts'];
  696. $result['total_duration'] = $segmentsStructure['total_duration'];
  697. return $result;
  698. }
  699. public function episodeVersions($data) {
  700. $anime_id = getProp($data, 'anime_id');
  701. $episode_id = getProp($data, 'episode_id');
  702. if (!$anime_id || !$episode_id) {
  703. Utils::throwError('1002:请选择剧集');
  704. }
  705. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  706. $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) {
  707. return (array)$value;
  708. })->toArray();
  709. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  710. foreach($episodes as &$episode) {
  711. $episode['version'] = 'V'.$episode['sequence'];
  712. $episode['roles'] = json_decode($episode['roles'], true);
  713. $episode['scenes'] = json_decode($episode['scenes'], true);
  714. // 获取分镜信息
  715. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  716. ->select('*')->get()->map(function ($value) {
  717. return (array)$value;
  718. })->toArray();
  719. // 使用公共方法构建分镜结构
  720. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  721. $episode['acts'] = $segmentsStructure['acts'];
  722. $episode['total_duration'] = $segmentsStructure['total_duration'];
  723. }
  724. return $episodes;
  725. }
  726. public function bindEpisodeVersion($data) {
  727. $episode_id = getProp($data, 'episode_id');
  728. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  729. if (!$episode) Utils::throwError('20003:该剧集不存在');
  730. $episode = (array)$episode;
  731. if ((int)$episode['is_default'] === 1) return true;
  732. try {
  733. DB::beginTransaction();
  734. // 移除is_default标志
  735. $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')]);
  736. if (!$boolen) {
  737. Utils::throwError('20003:更新失败!');
  738. }
  739. // 绑定副本
  740. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  741. if (!$boolen2) {
  742. Utils::throwError('20003:绑定失败!');
  743. }
  744. }catch (\Exception $e) {
  745. DB::rollBack();
  746. Utils::throwError('20003:'.$e->getMessage());
  747. }
  748. DB::commit();
  749. return true;
  750. }
  751. public function chatChangeImg($data) {
  752. $segment_id = getProp($data, 'segment_id');
  753. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  754. $prompt = getProp($data, 'prompt');
  755. if (!$prompt || !$segment_id) {
  756. Utils::throwError('1002:请输入提示词,并且选择分镜');
  757. }
  758. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  759. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  760. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  761. else $ref_img_url = '';
  762. // $ref_img_url = '';
  763. if (empty($prompt)) {
  764. if (empty($ref_img_url)) {
  765. $prompt = getProp($segment, 'segment_content');
  766. }else {
  767. $prompt = '请根据图片生成';
  768. }
  769. }
  770. $anime_id = getProp($segment, 'anime_id');
  771. $episode_id = getProp($segment, 'episode_id');
  772. $episode_number = getProp($segment, 'episode_number');
  773. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  774. $ratio = getProp($data, 'ratio');
  775. if (!$ratio) {
  776. $ratio = getProp($episode, 'ratio');
  777. if (!$ratio) $ratio = '9:16';
  778. }
  779. $art_style = getProp($episode, 'art_style');
  780. if ($art_style) {
  781. $prompt = "美术风格:{$art_style}\n{$prompt}";
  782. }
  783. $dimensions = $this->getRatioDimensions($ratio);
  784. $width = $dimensions['width'];
  785. $height = $dimensions['height'];
  786. try {
  787. $params = [
  788. 'alias_segment_id' => $segment_id,
  789. 'prompt' => $prompt,
  790. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  791. 'width' => $width,
  792. 'height' => $height
  793. ];
  794. // 优化提示词(不要生成字幕)
  795. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  796. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  797. $task_id = $task->id;
  798. if (!$task_id) {
  799. Utils::throwError("20003:生成图片失败");
  800. }
  801. // 更新任务ID
  802. $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')]);
  803. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  804. } catch (\Exception $e) {
  805. Utils::throwError("20003:" . $e->getMessage());
  806. }
  807. // 创建任务之后先暂停10s等待异步任务完成
  808. sleep(10);
  809. $img_url = $this->loopGetPicTaskResult($task_id);
  810. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  811. // 图片生成后新增对话记录
  812. try {
  813. $uid = Site::getUid();
  814. $now = date('Y-m-d H:i:s');
  815. // 使用AI反推图片提示词
  816. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  817. // 保存对话记录
  818. $records = [
  819. [
  820. 'uid' => $uid,
  821. 'anime_id' => $anime_id,
  822. 'sequence' => $episode_number,
  823. 'role' => 'user',
  824. 'content' => $prompt,
  825. 'segment_id' => $segment_id,
  826. 'image_url' => '',
  827. 'created_at' => $now,
  828. 'updated_at' => $now
  829. ],
  830. [
  831. 'uid' => $uid,
  832. 'anime_id' => $anime_id,
  833. 'sequence' => $episode_number,
  834. 'role' => 'assistant',
  835. 'content' => $pic_prompt,
  836. 'segment_id' => $segment_id,
  837. 'image_url' => $img_url,
  838. 'created_at' => $now,
  839. 'updated_at' => $now
  840. ]
  841. ];
  842. DB::table('mp_anime_records')->insert($records);
  843. } catch (\Exception $e) {
  844. // 记录日志但不影响主流程
  845. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  846. 'segment_id' => $segment_id,
  847. 'img_url' => $img_url
  848. ]);
  849. logDB('anime', 'error', '保存对话记录失败', [
  850. 'segment_id' => $segment_id,
  851. 'img_url' => $img_url,
  852. 'error' => $e->getMessage()
  853. ]);
  854. }
  855. return $img_url;
  856. }
  857. public function segmentChatHistory($data) {
  858. $segment_id = getProp($data, 'segment_id');
  859. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  860. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
  861. $chat = $query->orderBy('id')->get()->map(function ($value) {
  862. $value = (array)$value;
  863. $value['created_at'] = transDate($value['created_at']);
  864. return $value;
  865. })->toArray();
  866. // 获取历史图片
  867. $url = [];
  868. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  869. foreach($pic_history as $task) {
  870. $result_url = getProp($task, 'result_url');
  871. if (is_json($result_url)) {
  872. $url = array_merge($url, json_decode($result_url, true));
  873. }else {
  874. $url[] = $result_url;
  875. }
  876. }
  877. // 获取历史视频
  878. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  879. foreach($video_history as $task) {
  880. $result_url = getProp($task, 'compressed_url');
  881. if (is_json($result_url)) {
  882. $url = array_merge($url, json_decode($result_url, true));
  883. }else {
  884. $url[] = $result_url;
  885. }
  886. }
  887. return compact('chat', 'url');
  888. }
  889. public function changeEpisodeRoles($data) {
  890. $anime_id = getProp($data, 'anime_id');
  891. $episode_id = getProp($data, 'episode_id');
  892. $target_roles = getProp($data, 'roles');
  893. $is_deleted = getProp($data, 'is_deleted', 0);
  894. // 参数验证
  895. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  896. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  897. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  898. // 验证剧集是否存在
  899. $episode = DB::table('mp_anime_episodes')
  900. ->where('anime_id', $anime_id)
  901. ->where('id', $episode_id)
  902. ->first();
  903. if (!$episode) Utils::throwError('20003:该剧集不存在');
  904. $roles = json_decode(getProp($episode, 'roles'), true);
  905. // 获取anime信息,检查是否有关联的script_id
  906. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  907. if (!$anime) Utils::throwError('20003:动漫不存在');
  908. $script_id = getProp($anime, 'script_id');
  909. $episode_number = getProp($episode, 'episode_number', 1);
  910. $uid = Site::getUid();
  911. $cpid = Site::getCpid();
  912. try {
  913. $target_role_name = getProp($target_roles, 'role');
  914. // 如果是删除操作
  915. if ($is_deleted == 1) {
  916. // 从角色列表中移除该角色
  917. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  918. return getProp($role, 'role') !== $target_role_name;
  919. }));
  920. // 更新角色列表
  921. $result = DB::table('mp_anime_episodes')
  922. ->where('anime_id', $anime_id)
  923. ->where('id', $episode_id)
  924. ->update([
  925. 'roles' => json_encode($roles, 256),
  926. 'updated_at' => date('Y-m-d H:i:s')
  927. ]);
  928. if ($result === false) {
  929. Utils::throwError('20003:删除角色失败');
  930. }
  931. } else {
  932. // 新增或更新操作
  933. $role_found = false;
  934. $is_new_role = false;
  935. // 查找并更新已存在的角色
  936. foreach($roles as &$role) {
  937. if (getProp($role, 'role') === $target_role_name) {
  938. $role = $target_roles;
  939. $role_found = true;
  940. break;
  941. }
  942. }
  943. // 如果角色不存在,则新增
  944. if (!$role_found) {
  945. $roles[] = $target_roles;
  946. $is_new_role = true;
  947. }
  948. // 更新角色列表
  949. $result = DB::table('mp_anime_episodes')
  950. ->where('anime_id', $anime_id)
  951. ->where('id', $episode_id)
  952. ->update([
  953. 'roles' => json_encode($roles, 256),
  954. 'updated_at' => date('Y-m-d H:i:s')
  955. ]);
  956. if ($result === false) {
  957. Utils::throwError('20003:更新角色列表失败');
  958. }
  959. // 同步更新分镜表中对应主体的音色信息
  960. $voice_name = getProp($target_roles, 'voice_name');
  961. $voice_type = getProp($target_roles, 'voice_type');
  962. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  963. DB::table('mp_episode_segments')
  964. ->where('anime_id', $anime_id)
  965. ->where('episode_id', $episode_id)
  966. ->where('voice_actor', $target_role_name)
  967. ->update([
  968. 'voice_name' => $voice_name,
  969. 'voice_type' => $voice_type,
  970. 'voice_audio_url' => $voice_audio_url,
  971. 'updated_at' => date('Y-m-d H:i:s')
  972. ]);
  973. // 如果有关联的script_id,则同步到mp_products表
  974. if ($script_id) {
  975. // 查询剧本信息
  976. $script = DB::table('mp_scripts')
  977. ->where('id', $script_id)
  978. ->where('is_deleted', 0)
  979. ->first();
  980. if ($script) {
  981. $script_name = $script->script_name ?? 'script_' . $script_id;
  982. $product_name = getProp($target_roles, 'role');
  983. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  984. $url = getProp($target_roles, 'url', '');
  985. $product_type = 1; // 1=角色
  986. // 查找或创建以script_name命名的文件夹
  987. $folder = DB::table('mp_products')
  988. ->where('cpid', $cpid)
  989. ->where('type', 2) // 文件夹类型
  990. ->where('product', $product_type) // 角色类型
  991. ->where('product_name', $script_name)
  992. ->where('parent_id', 0)
  993. ->where('is_deleted', 0)
  994. ->first();
  995. if (!$folder) {
  996. // 创建文件夹
  997. $folder_id = DB::table('mp_products')->insertGetId([
  998. 'user_id' => $uid,
  999. 'cpid' => $cpid,
  1000. 'type' => 2, // 文件夹
  1001. 'product' => $product_type, // 角色类型
  1002. 'parent_id' => 0,
  1003. 'level' => 1,
  1004. 'product_name' => $script_name,
  1005. 'sort_order' => time(),
  1006. 'is_deleted' => 0,
  1007. 'created_at' => date('Y-m-d H:i:s'),
  1008. 'updated_at' => date('Y-m-d H:i:s')
  1009. ]);
  1010. } else {
  1011. $folder_id = $folder->id;
  1012. }
  1013. // 查找该文件夹下是否已存在同名资产
  1014. $existing_product = DB::table('mp_products')
  1015. ->where('cpid', $cpid)
  1016. ->where('type', 1) // 资产类型
  1017. ->where('product', $product_type)
  1018. ->where('parent_id', $folder_id)
  1019. ->where('product_name', $product_name)
  1020. ->where('is_deleted', 0)
  1021. ->first();
  1022. if ($existing_product) {
  1023. // 更新已存在的资产
  1024. $updateData = [
  1025. 'pic_task_status' => '生成成功',
  1026. ];
  1027. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1028. if ($url) $updateData['url'] = $url;
  1029. // 处理versions字段
  1030. $versions = getProp($target_roles, 'versions', []);
  1031. if ($versions && is_array($versions)) {
  1032. $updateData['versions'] = json_encode($versions, 256);
  1033. }
  1034. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1035. DB::table('mp_products')
  1036. ->where('id', $existing_product->id)
  1037. ->update($updateData);
  1038. $product_id = $existing_product->id;
  1039. } else {
  1040. // 创建新资产
  1041. $versions = getProp($target_roles, 'versions', []);
  1042. $product_id = DB::table('mp_products')->insertGetId([
  1043. 'user_id' => $uid,
  1044. 'cpid' => $cpid,
  1045. 'type' => 1, // 资产
  1046. 'product' => $product_type, // 角色
  1047. 'parent_id' => $folder_id,
  1048. 'level' => 2,
  1049. 'product_name' => $product_name,
  1050. 'url' => $url,
  1051. 'pic_prompt' => $pic_prompt,
  1052. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1053. 'sort_order' => time(),
  1054. 'is_deleted' => 0,
  1055. 'pic_task_status' => '生成成功',
  1056. 'created_at' => date('Y-m-d H:i:s'),
  1057. 'updated_at' => date('Y-m-d H:i:s')
  1058. ]);
  1059. }
  1060. // 建立或更新绑定关系
  1061. $existing_mapping = DB::table('mp_script_product_mappings')
  1062. ->where('script_id', $script_id)
  1063. ->where('product_id', $product_id)
  1064. ->where('episode_number', $episode_number)
  1065. ->first();
  1066. if (!$existing_mapping) {
  1067. // 创建绑定关系
  1068. DB::table('mp_script_product_mappings')->insert([
  1069. 'script_id' => $script_id,
  1070. 'product_id' => $product_id,
  1071. 'episode_number' => $episode_number,
  1072. 'created_at' => date('Y-m-d H:i:s'),
  1073. 'updated_at' => date('Y-m-d H:i:s')
  1074. ]);
  1075. }
  1076. }
  1077. }
  1078. }
  1079. } catch (\Exception $e) {
  1080. dLog('anime')->error('更新剧集角色失败', [
  1081. 'anime_id' => $anime_id,
  1082. 'episode_id' => $episode_id,
  1083. 'error' => $e->getMessage()
  1084. ]);
  1085. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1086. }
  1087. return true;
  1088. }
  1089. public function changeEpisodeScenes($data) {
  1090. $anime_id = getProp($data, 'anime_id');
  1091. $episode_id = getProp($data, 'episode_id');
  1092. $target_scenes = getProp($data, 'scenes');
  1093. $is_deleted = getProp($data, 'is_deleted', 0);
  1094. // 参数验证
  1095. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1096. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1097. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1098. // 验证剧集是否存在
  1099. $episode = DB::table('mp_anime_episodes')
  1100. ->where('anime_id', $anime_id)
  1101. ->where('id', $episode_id)
  1102. ->first();
  1103. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1104. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1105. // 获取anime信息,检查是否有关联的script_id
  1106. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1107. if (!$anime) Utils::throwError('20003:动漫不存在');
  1108. $script_id = getProp($anime, 'script_id');
  1109. $episode_number = getProp($episode, 'episode_number', 1);
  1110. $uid = Site::getUid();
  1111. $cpid = Site::getCpid();
  1112. try {
  1113. $target_scene_name = getProp($target_scenes, 'scene');
  1114. // 如果是删除操作
  1115. if ($is_deleted == 1) {
  1116. // 从场景列表中移除该场景
  1117. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1118. return getProp($scene, 'scene') !== $target_scene_name;
  1119. }));
  1120. // 更新场景列表
  1121. $result = DB::table('mp_anime_episodes')
  1122. ->where('anime_id', $anime_id)
  1123. ->where('id', $episode_id)
  1124. ->update([
  1125. 'scenes' => json_encode($scenes, 256),
  1126. 'updated_at' => date('Y-m-d H:i:s')
  1127. ]);
  1128. if ($result === false) {
  1129. Utils::throwError('20003:删除场景失败');
  1130. }
  1131. } else {
  1132. // 新增或更新操作
  1133. $scene_found = false;
  1134. $is_new_scene = false;
  1135. // 查找并更新已存在的场景
  1136. foreach($scenes as &$scene) {
  1137. if (getProp($scene, 'scene') === $target_scene_name) {
  1138. $scene = $target_scenes;
  1139. $scene_found = true;
  1140. break;
  1141. }
  1142. }
  1143. // 如果场景不存在,则新增
  1144. if (!$scene_found) {
  1145. $scenes[] = $target_scenes;
  1146. $is_new_scene = true;
  1147. }
  1148. // 更新场景列表
  1149. $result = DB::table('mp_anime_episodes')
  1150. ->where('anime_id', $anime_id)
  1151. ->where('id', $episode_id)
  1152. ->update([
  1153. 'scenes' => json_encode($scenes, 256),
  1154. 'updated_at' => date('Y-m-d H:i:s')
  1155. ]);
  1156. if ($result === false) {
  1157. Utils::throwError('20003:更新场景列表失败');
  1158. }
  1159. // 如果有关联的script_id,则同步到mp_products表
  1160. if ($script_id) {
  1161. // 查询剧本信息
  1162. $script = DB::table('mp_scripts')
  1163. ->where('id', $script_id)
  1164. ->where('is_deleted', 0)
  1165. ->first();
  1166. if ($script) {
  1167. $script_name = $script->script_name ?? 'script_' . $script_id;
  1168. $product_name = getProp($target_scenes, 'scene');
  1169. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1170. $url = getProp($target_scenes, 'url', '');
  1171. $product_type = 2; // 2=场景
  1172. // 查找或创建以script_name命名的文件夹
  1173. $folder = DB::table('mp_products')
  1174. ->where('cpid', $cpid)
  1175. ->where('type', 2) // 文件夹类型
  1176. ->where('product', $product_type) // 场景类型
  1177. ->where('product_name', $script_name)
  1178. ->where('parent_id', 0)
  1179. ->where('is_deleted', 0)
  1180. ->first();
  1181. if (!$folder) {
  1182. // 创建文件夹
  1183. $folder_id = DB::table('mp_products')->insertGetId([
  1184. 'user_id' => $uid,
  1185. 'cpid' => $cpid,
  1186. 'type' => 2, // 文件夹
  1187. 'product' => $product_type, // 场景类型
  1188. 'parent_id' => 0,
  1189. 'level' => 1,
  1190. 'product_name' => $script_name,
  1191. 'sort_order' => time(),
  1192. 'is_deleted' => 0,
  1193. 'created_at' => date('Y-m-d H:i:s'),
  1194. 'updated_at' => date('Y-m-d H:i:s')
  1195. ]);
  1196. } else {
  1197. $folder_id = $folder->id;
  1198. }
  1199. // 查找该文件夹下是否已存在同名资产
  1200. $existing_product = DB::table('mp_products')
  1201. ->where('cpid', $cpid)
  1202. ->where('type', 1) // 资产类型
  1203. ->where('product', $product_type)
  1204. ->where('parent_id', $folder_id)
  1205. ->where('product_name', $product_name)
  1206. ->where('is_deleted', 0)
  1207. ->first();
  1208. if ($existing_product) {
  1209. // 更新已存在的资产
  1210. $updateData = [
  1211. 'pic_task_status' => '生成成功'
  1212. ];
  1213. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1214. if ($url) $updateData['url'] = $url;
  1215. // 处理versions字段
  1216. $versions = getProp($target_scenes, 'versions', []);
  1217. if ($versions && is_array($versions)) {
  1218. $updateData['versions'] = json_encode($versions, 256);
  1219. }
  1220. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1221. DB::table('mp_products')
  1222. ->where('id', $existing_product->id)
  1223. ->update($updateData);
  1224. $product_id = $existing_product->id;
  1225. } else {
  1226. // 创建新资产
  1227. $versions = getProp($target_scenes, 'versions', []);
  1228. $product_id = DB::table('mp_products')->insertGetId([
  1229. 'user_id' => $uid,
  1230. 'cpid' => $cpid,
  1231. 'type' => 1, // 资产
  1232. 'product' => $product_type, // 场景
  1233. 'parent_id' => $folder_id,
  1234. 'level' => 2,
  1235. 'product_name' => $product_name,
  1236. 'url' => $url,
  1237. 'pic_prompt' => $pic_prompt,
  1238. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1239. 'sort_order' => time(),
  1240. 'is_deleted' => 0,
  1241. 'pic_task_status' => '生成成功',
  1242. 'created_at' => date('Y-m-d H:i:s'),
  1243. 'updated_at' => date('Y-m-d H:i:s')
  1244. ]);
  1245. }
  1246. // 建立或更新绑定关系
  1247. $existing_mapping = DB::table('mp_script_product_mappings')
  1248. ->where('script_id', $script_id)
  1249. ->where('product_id', $product_id)
  1250. ->where('episode_number', $episode_number)
  1251. ->first();
  1252. if (!$existing_mapping) {
  1253. // 创建绑定关系
  1254. DB::table('mp_script_product_mappings')->insert([
  1255. 'script_id' => $script_id,
  1256. 'product_id' => $product_id,
  1257. 'episode_number' => $episode_number,
  1258. 'created_at' => date('Y-m-d H:i:s'),
  1259. 'updated_at' => date('Y-m-d H:i:s')
  1260. ]);
  1261. }
  1262. }
  1263. }
  1264. }
  1265. } catch (\Exception $e) {
  1266. dLog('anime')->error('更新剧集场景失败', [
  1267. 'anime_id' => $anime_id,
  1268. 'episode_id' => $episode_id,
  1269. 'error' => $e->getMessage()
  1270. ]);
  1271. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1272. }
  1273. return true;
  1274. }
  1275. public function changeEpisodeProps($data) {
  1276. $anime_id = getProp($data, 'anime_id');
  1277. $episode_id = getProp($data, 'episode_id');
  1278. $target_props = getProp($data, 'props');
  1279. $is_deleted = getProp($data, 'is_deleted', 0);
  1280. // 参数验证
  1281. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1282. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1283. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1284. // 验证剧集是否存在
  1285. $episode = DB::table('mp_anime_episodes')
  1286. ->where('anime_id', $anime_id)
  1287. ->where('id', $episode_id)
  1288. ->first();
  1289. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1290. $props = json_decode(getProp($episode, 'props'), true);
  1291. // 获取anime信息,检查是否有关联的script_id
  1292. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1293. if (!$anime) Utils::throwError('20003:动漫不存在');
  1294. $script_id = getProp($anime, 'script_id');
  1295. $episode_number = getProp($episode, 'episode_number', 1);
  1296. $uid = Site::getUid();
  1297. $cpid = Site::getCpid();
  1298. try {
  1299. $target_prop_name = getProp($target_props, 'prop');
  1300. // 如果是删除操作
  1301. if ($is_deleted == 1) {
  1302. // 从道具列表中移除该道具
  1303. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1304. return getProp($prop, 'prop') !== $target_prop_name;
  1305. }));
  1306. // 更新道具列表
  1307. $result = DB::table('mp_anime_episodes')
  1308. ->where('anime_id', $anime_id)
  1309. ->where('id', $episode_id)
  1310. ->update([
  1311. 'props' => json_encode($props, 256),
  1312. 'updated_at' => date('Y-m-d H:i:s')
  1313. ]);
  1314. if ($result === false) {
  1315. Utils::throwError('20003:删除道具失败');
  1316. }
  1317. } else {
  1318. // 新增或更新操作
  1319. $prop_found = false;
  1320. $is_new_prop = false;
  1321. // 查找并更新已存在的道具
  1322. foreach($props as &$prop) {
  1323. if (getProp($prop, 'prop') === $target_prop_name) {
  1324. $prop = $target_props;
  1325. $prop_found = true;
  1326. break;
  1327. }
  1328. }
  1329. // 如果道具不存在,则新增
  1330. if (!$prop_found) {
  1331. $props[] = $target_props;
  1332. $is_new_prop = true;
  1333. }
  1334. // 更新道具列表
  1335. $result = DB::table('mp_anime_episodes')
  1336. ->where('anime_id', $anime_id)
  1337. ->where('id', $episode_id)
  1338. ->update([
  1339. 'props' => json_encode($props, 256),
  1340. 'updated_at' => date('Y-m-d H:i:s')
  1341. ]);
  1342. if ($result === false) {
  1343. Utils::throwError('20003:更新道具列表失败');
  1344. }
  1345. // 如果有关联的script_id,则同步到mp_products表
  1346. if ($script_id) {
  1347. // 查询剧本信息
  1348. $script = DB::table('mp_scripts')
  1349. ->where('id', $script_id)
  1350. ->where('is_deleted', 0)
  1351. ->first();
  1352. if ($script) {
  1353. $script_name = $script->script_name ?? 'script_' . $script_id;
  1354. $product_name = getProp($target_props, 'prop');
  1355. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1356. $url = getProp($target_props, 'url', '');
  1357. $product_type = 3; // 3=道具
  1358. // 查找或创建以script_name命名的文件夹
  1359. $folder = DB::table('mp_products')
  1360. ->where('cpid', $cpid)
  1361. ->where('type', 2) // 文件夹类型
  1362. ->where('product', $product_type) // 道具类型
  1363. ->where('product_name', $script_name)
  1364. ->where('parent_id', 0)
  1365. ->where('is_deleted', 0)
  1366. ->first();
  1367. if (!$folder) {
  1368. // 创建文件夹
  1369. $folder_id = DB::table('mp_products')->insertGetId([
  1370. 'user_id' => $uid,
  1371. 'cpid' => $cpid,
  1372. 'type' => 2, // 文件夹
  1373. 'product' => $product_type, // 道具类型
  1374. 'parent_id' => 0,
  1375. 'level' => 1,
  1376. 'product_name' => $script_name,
  1377. 'sort_order' => time(),
  1378. 'is_deleted' => 0,
  1379. 'created_at' => date('Y-m-d H:i:s'),
  1380. 'updated_at' => date('Y-m-d H:i:s')
  1381. ]);
  1382. } else {
  1383. $folder_id = $folder->id;
  1384. }
  1385. // 查找该文件夹下是否已存在同名资产
  1386. $existing_product = DB::table('mp_products')
  1387. ->where('cpid', $cpid)
  1388. ->where('type', 1) // 资产类型
  1389. ->where('product', $product_type)
  1390. ->where('parent_id', $folder_id)
  1391. ->where('product_name', $product_name)
  1392. ->where('is_deleted', 0)
  1393. ->first();
  1394. if ($existing_product) {
  1395. // 更新已存在的资产
  1396. $updateData = [
  1397. 'pic_task_status' => '生成成功'
  1398. ];
  1399. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1400. if ($url) $updateData['url'] = $url;
  1401. // 处理versions字段
  1402. $versions = getProp($target_props, 'versions', []);
  1403. if ($versions && is_array($versions)) {
  1404. $updateData['versions'] = json_encode($versions, 256);
  1405. }
  1406. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1407. DB::table('mp_products')
  1408. ->where('id', $existing_product->id)
  1409. ->update($updateData);
  1410. $product_id = $existing_product->id;
  1411. } else {
  1412. // 创建新资产
  1413. $versions = getProp($target_props, 'versions', []);
  1414. $product_id = DB::table('mp_products')->insertGetId([
  1415. 'user_id' => $uid,
  1416. 'cpid' => $cpid,
  1417. 'type' => 1, // 资产
  1418. 'product' => $product_type, // 道具
  1419. 'parent_id' => $folder_id,
  1420. 'level' => 2,
  1421. 'product_name' => $product_name,
  1422. 'url' => $url,
  1423. 'pic_prompt' => $pic_prompt,
  1424. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1425. 'sort_order' => time(),
  1426. 'is_deleted' => 0,
  1427. 'pic_task_status' => '生成成功',
  1428. 'created_at' => date('Y-m-d H:i:s'),
  1429. 'updated_at' => date('Y-m-d H:i:s')
  1430. ]);
  1431. }
  1432. // 建立或更新绑定关系
  1433. $existing_mapping = DB::table('mp_script_product_mappings')
  1434. ->where('script_id', $script_id)
  1435. ->where('product_id', $product_id)
  1436. ->where('episode_number', $episode_number)
  1437. ->first();
  1438. if (!$existing_mapping) {
  1439. // 创建绑定关系
  1440. DB::table('mp_script_product_mappings')->insert([
  1441. 'script_id' => $script_id,
  1442. 'product_id' => $product_id,
  1443. 'episode_number' => $episode_number,
  1444. 'created_at' => date('Y-m-d H:i:s'),
  1445. 'updated_at' => date('Y-m-d H:i:s')
  1446. ]);
  1447. }
  1448. }
  1449. }
  1450. }
  1451. } catch (\Exception $e) {
  1452. dLog('anime')->error('更新剧集道具失败', [
  1453. 'anime_id' => $anime_id,
  1454. 'episode_id' => $episode_id,
  1455. 'error' => $e->getMessage()
  1456. ]);
  1457. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1458. }
  1459. return true;
  1460. }
  1461. public function editSegment($data) {
  1462. $segment_id = getProp($data, 'segment_id');
  1463. $segment_content = getProp($data, 'segment_content');
  1464. $image_url = getProp($data, 'image_url');
  1465. $video_url = getProp($data, 'video_url');
  1466. // 参数验证
  1467. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1468. // 验证分镜是否存在
  1469. $segment = DB::table('mp_episode_segments')
  1470. ->where('segment_id', $segment_id)
  1471. ->first();
  1472. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1473. $dubTaskId = 0;
  1474. try {
  1475. DB::beginTransaction();
  1476. // 准备更新数据
  1477. $update_data = [
  1478. 'updated_at' => date('Y-m-d H:i:s')
  1479. ];
  1480. if ($segment_content) {
  1481. // 先将segment_content赋值到update_data
  1482. $update_data['segment_content'] = $segment_content;
  1483. // 使用现有方法分析segment_content,提取各个字段
  1484. $this->handleSegmentContent($update_data);
  1485. // 如果有对话内容,创建视频配音合成任务
  1486. $dialogue = getProp($update_data, 'dialogue');
  1487. if (!empty($dialogue)) {
  1488. $now = date('Y-m-d H:i:s');
  1489. $generate_json = [
  1490. 'text' => $dialogue,
  1491. 'role' => getProp($update_data, 'voice_actor'),
  1492. 'voice_type' => getProp($update_data, 'voice_type'),
  1493. 'voice_name' => getProp($update_data, 'voice_name'),
  1494. 'emotion' => getProp($update_data, 'emotion'),
  1495. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1496. 'gender' => getProp($update_data, 'gender'),
  1497. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1498. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1499. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1500. 'pitch' => getProp($update_data, 'pitch', 0),
  1501. ];
  1502. // 插入视频配音合成任务
  1503. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1504. 'alias_segment_id' => $segment_id,
  1505. 'generate_status' => '执行中',
  1506. 'audio_url' => '',
  1507. 'generate_json' => json_encode($generate_json, 256),
  1508. 'created_at' => $now,
  1509. 'updated_at' => $now,
  1510. ]);
  1511. if (!$dubTaskId) {
  1512. Utils::throwError('20003:创建配音任务失败!');
  1513. }
  1514. $update_data['audio_url'] = '';
  1515. } else {
  1516. // dialogue为空时,直接写入默认音频信息
  1517. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1518. $update_data['audio_duration'] = 2.0;
  1519. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1520. }
  1521. }
  1522. if ($image_url) {
  1523. $update_data['img_url'] = $image_url;
  1524. // 同时写入一个简单的图片生成任务
  1525. $pic_task = [
  1526. 'alias_segment_id' => $segment_id,
  1527. 'ref_img_url' => json_encode([]),
  1528. 'status' => 'success',
  1529. 'result_url' => json_encode([$image_url], 256),
  1530. 'model' => '',
  1531. 'created_at' => date('Y-m-d H:i:s'),
  1532. 'updated_at' => date('Y-m-d H:i:s'),
  1533. ];
  1534. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1535. }
  1536. if ($video_url) {
  1537. $update_data['origin_video_url'] = $video_url;
  1538. $compressed_video_url = compressVideo($video_url);
  1539. $update_data['current_type'] = 2;
  1540. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1541. // 同时写入一个简单的视频生成任务
  1542. $video_task = [
  1543. 'alias_segment_id' => $segment_id,
  1544. 'status' => 'success',
  1545. 'result_url' => $update_data['origin_video_url'],
  1546. 'compressed_url' => $update_data['video_url'],
  1547. 'created_at' => date('Y-m-d H:i:s'),
  1548. 'updated_at' => date('Y-m-d H:i:s'),
  1549. ];
  1550. DB::table('mp_generate_video_tasks')->insert($video_task);
  1551. }
  1552. // 更新分镜信息
  1553. $result = DB::table('mp_episode_segments')
  1554. ->where('segment_id', $segment_id)
  1555. ->update($update_data);
  1556. if ($result === false) {
  1557. Utils::throwError('20003:更新分镜剧本失败');
  1558. }
  1559. DB::commit();
  1560. // 如果有创建音频生成任务则调用API
  1561. if ($dubTaskId) {
  1562. // 请求远程服务器执行生成
  1563. $client = new Client(['timeout' => 300, 'verify' => false]);
  1564. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1565. $response = $result->getBody()->getContents();
  1566. $response_arr = json_decode($response, true);
  1567. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1568. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1569. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1570. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1571. Utils::throwError('20003:火山生成音频失败');
  1572. }
  1573. }
  1574. return true;
  1575. } catch (\Exception $e) {
  1576. DB::rollBack();
  1577. dLog('anime')->error('更新分镜剧本失败', [
  1578. 'segment_id' => $segment_id,
  1579. 'error' => $e->getMessage()
  1580. ]);
  1581. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1582. }
  1583. }
  1584. public function batchSetSegmentPics($data) {
  1585. $anime_id = getProp($data, 'anime_id');
  1586. $episode_id = getProp($data, 'episode_id');
  1587. $ratio = getProp($data, 'ratio');
  1588. $dimensions = $this->getRatioDimensions($ratio);
  1589. $width = $dimensions['width'];
  1590. $height = $dimensions['height'];
  1591. if (!$anime_id || !$episode_id) {
  1592. Utils::throwError('1002:请选择剧集');
  1593. }
  1594. // 获取剧集信息
  1595. $episode = DB::table('mp_anime_episodes')
  1596. ->where('anime_id', $anime_id)
  1597. ->where('id', $episode_id)
  1598. ->where('is_default', 1)
  1599. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1600. ->first();
  1601. if (!$episode) {
  1602. Utils::throwError('20003:该剧集不存在');
  1603. }
  1604. $model = getProp($data, 'model');
  1605. if (!$model) {
  1606. $model = getProp($episode, 'image_model');
  1607. if (!$model) {
  1608. // episode表也没有,使用默认值
  1609. $model = 'doubao-seedream-5-0-lite-260128';
  1610. }
  1611. }
  1612. // 验证模型是否在可用模型表中
  1613. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1614. $model = 'doubao-seedream-5-0-lite-260128';
  1615. }
  1616. $roles = json_decode(getProp($episode, 'roles'), true);
  1617. if (!$roles) {
  1618. Utils::throwError('20003:角色信息格式错误');
  1619. }
  1620. // 构建角色名称到参考图的映射
  1621. $role_map = [];
  1622. foreach ($roles as $role) {
  1623. $role_name = getProp($role, 'role');
  1624. $role_url = getProp($role, 'url');
  1625. if (!empty($role_name) && !empty($role_url)) {
  1626. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1627. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1628. // $role_map[$base_name] = $role_url;
  1629. // 同时保存完整名称的映射
  1630. $role_map[$role_name] = $role_url;
  1631. }
  1632. }
  1633. $scenes = json_decode(getProp($episode, 'roles'), true);
  1634. if (!$scenes) {
  1635. Utils::throwError('20003:场景信息格式错误');
  1636. }
  1637. // 构建角色名称到参考图的映射
  1638. $scene_map = [];
  1639. foreach ($scenes as $scene) {
  1640. $scene_name = getProp($scene, 'scene');
  1641. $scene_url = getProp($scene, 'url');
  1642. if (!empty($scene_name) && !empty($scene_url)) {
  1643. $scene_map[$scene_name] = $scene_url;
  1644. }
  1645. }
  1646. // 获取所有分镜信息
  1647. $segments = DB::table('mp_episode_segments')
  1648. ->where('anime_id', $anime_id)
  1649. ->where('episode_id', $episode_id)
  1650. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1651. ->orderBy('segment_number')
  1652. ->get()
  1653. ->toArray();
  1654. if (empty($segments)) {
  1655. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1656. }
  1657. // 保存图片比例
  1658. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1659. $updated_segments = [];
  1660. $failed_segments = [];
  1661. // 批量为每个分镜生成图片任务
  1662. foreach ($segments as $segment) {
  1663. $segment_id = $segment->segment_id;
  1664. $segment_content = $segment->segment_content;
  1665. if (empty($segment_content)) {
  1666. $failed_segments[] = [
  1667. 'segment_id' => $segment_id,
  1668. 'error' => '分镜内容为空'
  1669. ];
  1670. continue;
  1671. }
  1672. try {
  1673. $dubTaskId = 0;
  1674. // 解析分镜内容,提取画面描述作为主要提示词
  1675. $prompt = $segment_content;
  1676. $ref_img_urls = [];
  1677. // 分镜场景
  1678. $scene = getProp($segment, 'scene');
  1679. $matched_scene = '';
  1680. if (isset($scene_map[$scene])) {
  1681. $img_index = count($ref_img_urls) + 1;
  1682. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1683. $ref_img_urls[] = $scene_map[$scene];
  1684. $matched_scene = $scene;
  1685. }
  1686. // 分镜角色
  1687. $characters = getProp($segment, 'characters');
  1688. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1689. $roles = explode(',', $characters);
  1690. // 从分镜内容中提取涉及的角色
  1691. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1692. // 获取匹配角色的参考图
  1693. foreach ($segment_characters as $character) {
  1694. if (isset($role_map[$character])) {
  1695. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1696. $img_index = count($ref_img_urls) + 1;
  1697. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1698. $ref_img_urls[] = $role_map[$character];
  1699. }
  1700. }
  1701. // 如果没有找到匹配的角色参考图,不使用参考图
  1702. if (empty($ref_img_urls)) {
  1703. $ref_img_urls = [];
  1704. }
  1705. // 准备生成任务参数
  1706. $params = [
  1707. 'model' => $model,
  1708. 'alias_segment_id' => $segment_id,
  1709. 'prompt' => $prompt,
  1710. 'ref_img_urls' => $ref_img_urls,
  1711. 'width' => $width,
  1712. 'height' => $height,
  1713. ];
  1714. // 优化提示词(不要生成字幕)
  1715. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1716. // $task_id = mt_rand(100000, 999999);
  1717. // 调用AI图片生成服务
  1718. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1719. $task_id = $task->id;
  1720. if (!$task_id) {
  1721. $failed_segments[] = [
  1722. 'segment_id' => $segment_id,
  1723. 'error' => '创建生成任务失败'
  1724. ];
  1725. continue;
  1726. }
  1727. $update_data = [
  1728. 'pic_task_id' => $task_id,
  1729. 'pic_task_status' => '生成中',
  1730. 'audio_url' => '',
  1731. 'updated_at' => date('Y-m-d H:i:s')
  1732. ];
  1733. // 如果有对话内容,创建视频配音合成任务
  1734. $dialogue = getProp($segment, 'dialogue');
  1735. if (!empty($dialogue)) {
  1736. $now = date('Y-m-d H:i:s');
  1737. $generate_json = [
  1738. 'text' => $dialogue,
  1739. 'role' => getProp($segment, 'voice_actor'),
  1740. 'voice_type' => getProp($segment, 'voice_type'),
  1741. 'voice_name' => getProp($segment, 'voice_name'),
  1742. 'emotion' => getProp($segment, 'emotion'),
  1743. 'emotion_type' => getProp($segment, 'emotion_type'),
  1744. 'gender' => getProp($segment, 'gender'),
  1745. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1746. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1747. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1748. 'pitch' => getProp($segment, 'pitch', 0),
  1749. ];
  1750. // 插入视频配音合成任务
  1751. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1752. 'alias_segment_id' => $segment_id,
  1753. 'generate_status' => '执行中',
  1754. 'audio_url' => '',
  1755. 'generate_json' => json_encode($generate_json, 256),
  1756. 'created_at' => $now,
  1757. 'updated_at' => $now,
  1758. ]);
  1759. if (!$dubTaskId) {
  1760. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1761. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1762. // Utils::throwError('20003:创建配音任务失败!');
  1763. }
  1764. } else {
  1765. // dialogue为空时,直接写入默认音频信息到分镜表
  1766. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1767. $update_data['audio_duration'] = 2.0;
  1768. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1769. }
  1770. // 更新分镜的任务信息
  1771. $update_result = DB::table('mp_episode_segments')
  1772. ->where('segment_id', $segment_id)
  1773. ->update($update_data);
  1774. // 如果是第一集的首帧图片,则存入待更新数组
  1775. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1776. Redis::sadd('anime_first_frame_urls', $segment_id);
  1777. }
  1778. if ($update_result) {
  1779. $updated_segments[] = [
  1780. 'segment_id' => $segment_id,
  1781. 'task_id' => $task_id,
  1782. 'status' => '生成中',
  1783. 'matched_scenes' => $matched_scene,
  1784. 'matched_roles' => $segment_characters,
  1785. 'ref_urls_count' => count($ref_img_urls)
  1786. ];
  1787. } else {
  1788. $failed_segments[] = [
  1789. 'segment_id' => $segment_id,
  1790. 'error' => '更新分镜任务状态失败'
  1791. ];
  1792. }
  1793. if ($dubTaskId) {
  1794. sleep(1);
  1795. // 请求远程服务器执行生成
  1796. $client = new Client(['timeout' => 300, 'verify' => false]);
  1797. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1798. $response = $result->getBody()->getContents();
  1799. $response_arr = json_decode($response, true);
  1800. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1801. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1802. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1803. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1804. }
  1805. }
  1806. } catch (\Exception $e) {
  1807. $failed_segments[] = [
  1808. 'segment_id' => $segment_id,
  1809. 'error' => $e->getMessage()
  1810. ];
  1811. }
  1812. }
  1813. // 更新剧集生成状态
  1814. if (!empty($updated_segments)) {
  1815. DB::table('mp_anime_episodes')
  1816. ->where('id', $episode_id)
  1817. ->update([
  1818. 'is_generated' => 1,
  1819. 'updated_at' => date('Y-m-d H:i:s')
  1820. ]);
  1821. }
  1822. return [
  1823. 'success_count' => count($updated_segments),
  1824. 'failed_count' => count($failed_segments),
  1825. 'success_segments' => $updated_segments,
  1826. 'failed_segments' => $failed_segments,
  1827. 'total_segments' => count($segments)
  1828. ];
  1829. }
  1830. public function reGenerateSegment($data) {
  1831. $segment_id = getProp($data, 'segment_id');
  1832. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1833. $anime_id = getProp($segment, 'anime_id');
  1834. $episode_id = getProp($segment, 'episode_id');
  1835. $episode_number = getProp($segment, 'episode_number');
  1836. $segment_content = getProp($data, 'segment_content');
  1837. $ratio = getProp($data, 'ratio');
  1838. if (!$ratio) {
  1839. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1840. if (!$ratio) $ratio = '9:16';
  1841. }
  1842. $dimensions = $this->getRatioDimensions($ratio);
  1843. $width = $dimensions['width'];
  1844. $height = $dimensions['height'];
  1845. if (!$anime_id || !$episode_id) {
  1846. Utils::throwError('1002:请选择分镜');
  1847. }
  1848. // 使用文生文模型重新解析segment_content
  1849. if (!empty($segment_content)) {
  1850. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1851. }
  1852. // 获取动漫的角色信息(包含参考图)
  1853. $anime = DB::table('mp_animes')
  1854. ->where('id', $anime_id)
  1855. ->select('roles', 'scenes')
  1856. ->first();
  1857. if (!$anime || !$anime->roles) {
  1858. Utils::throwError('20003:未找到角色信息');
  1859. }
  1860. $roles = json_decode($anime->roles, true);
  1861. if (!$roles) {
  1862. Utils::throwError('20003:角色信息格式错误');
  1863. }
  1864. // 构建角色名称到参考图的映射
  1865. $role_map = [];
  1866. foreach ($roles as $role) {
  1867. $role_name = getProp($role, 'role');
  1868. $role_url = getProp($role, 'url');
  1869. if (!empty($role_name) && !empty($role_url)) {
  1870. $role_map[$role_name] = $role_url;
  1871. }
  1872. }
  1873. $scenes = json_decode($anime->scenes, true);
  1874. if (!$scenes) {
  1875. Utils::throwError('20003:角色信息格式错误');
  1876. }
  1877. // 构建角色名称到参考图的映射
  1878. $scene_map = [];
  1879. foreach ($scenes as $scene) {
  1880. $scene_name = getProp($scene, 'scene');
  1881. $scene_url = getProp($scene, 'url');
  1882. if (!empty($scene_name) && !empty($scene_url)) {
  1883. $scene_map[$scene_name] = $scene_url;
  1884. }
  1885. }
  1886. $segment_id = $segment->segment_id;
  1887. $original_segment_content = $segment->segment_content;
  1888. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1889. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1890. if (empty($final_segment_content)) {
  1891. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1892. }
  1893. try {
  1894. $dubTaskId = 0;
  1895. // 分镜剧本数组
  1896. $update_data = [
  1897. 'segment_content' => $final_segment_content,
  1898. 'pic_task_status' => '生成中',
  1899. 'updated_at' => date('Y-m-d H:i:s')
  1900. ];
  1901. // 解析分镜内容,提取画面描述作为主要提示词
  1902. $prompt = $final_segment_content;
  1903. $ref_img_urls = [];
  1904. // 分镜场景
  1905. $scene = getProp($data, 'scene');
  1906. if ($scene) {
  1907. $matched_scene = '';
  1908. if (isset($scene_map[$scene])) {
  1909. $img_index = count($ref_img_urls) + 1;
  1910. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1911. $ref_img_urls[] = $scene_map[$scene];
  1912. $matched_scene = $scene;
  1913. }
  1914. $update_data['scene'] = $scene;
  1915. }
  1916. // 分镜角色
  1917. $characters = getProp($data, 'characters');
  1918. if ($characters) {
  1919. $update_data['characters'] = $characters;
  1920. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1921. $characters = explode(',', $characters);
  1922. // 从分镜内容中提取涉及的角色
  1923. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1924. // 获取匹配角色的参考图
  1925. foreach ($segment_characters as $character) {
  1926. if (isset($role_map[$character])) {
  1927. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1928. $img_index = count($ref_img_urls) + 1;
  1929. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1930. $ref_img_urls[] = $role_map[$character];
  1931. }
  1932. }
  1933. }
  1934. // 如果没有找到匹配的角色参考图,不使用参考图
  1935. if (empty($ref_img_urls)) {
  1936. $ref_img_urls = [];
  1937. }
  1938. // 准备生成任务参数
  1939. $params = [
  1940. 'alias_segment_id' => $segment_id,
  1941. 'prompt' => $prompt,
  1942. 'ref_img_urls' => $ref_img_urls,
  1943. 'width' => $width,
  1944. 'height' => $height,
  1945. ];
  1946. // 优化提示词(不要生成字幕)
  1947. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1948. // 调用AI图片生成服务
  1949. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1950. $task_id = $task->id;
  1951. if (!$task_id) {
  1952. Utils::throwError('20003:创建生成任务失败!');
  1953. }
  1954. $update_data['pic_task_id'] = $task_id;
  1955. // 更新分镜剧本信息
  1956. $this->handleSegmentContent($update_data);
  1957. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1958. if ($segment_content) {
  1959. $dialogue = getProp($update_data, 'dialogue');
  1960. if (!empty($dialogue)) {
  1961. $now = date('Y-m-d H:i:s');
  1962. $generate_json = [
  1963. 'text' => $dialogue,
  1964. 'role' => getProp($update_data, 'voice_actor'),
  1965. 'voice_type' => getProp($update_data, 'voice_type'),
  1966. 'voice_name' => getProp($update_data, 'voice_name'),
  1967. 'emotion' => getProp($update_data, 'emotion'),
  1968. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1969. 'gender' => getProp($update_data, 'gender'),
  1970. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1971. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1972. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1973. 'pitch' => getProp($update_data, 'pitch', 0),
  1974. ];
  1975. // 插入视频配音合成任务
  1976. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1977. 'alias_segment_id' => $segment_id,
  1978. 'generate_status' => '执行中',
  1979. 'audio_url' => '',
  1980. 'generate_json' => json_encode($generate_json, 256),
  1981. 'created_at' => date('Y-m-d H:i:s'),
  1982. 'updated_at' => date('Y-m-d H:i:s'),
  1983. ]);
  1984. if (!$dubTaskId) {
  1985. Utils::throwError('20003:创建配音任务失败!');
  1986. }
  1987. $update_data['audio_url'] = '';
  1988. } else {
  1989. // dialogue为空时,直接写入默认音频信息
  1990. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1991. $update_data['audio_duration'] = 2.0;
  1992. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1993. }
  1994. }
  1995. $boolen = DB::table('mp_episode_segments')
  1996. ->where('segment_id', $segment_id)
  1997. ->update($update_data);
  1998. // 如果是第一集的首帧图片,则存入待更新数组
  1999. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2000. Redis::sadd('anime_first_frame_urls', $segment_id);
  2001. }
  2002. if ($dubTaskId) {
  2003. // 请求远程服务器执行生成
  2004. $client = new Client(['timeout' => 300, 'verify' => false]);
  2005. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2006. $response = $result->getBody()->getContents();
  2007. $response_arr = json_decode($response, true);
  2008. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2009. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2010. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2011. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2012. Utils::throwError('20003:火山生成音频失败');
  2013. }
  2014. }
  2015. } catch (\Exception $e) {
  2016. $failed_segments[] = [
  2017. 'segment_id' => $segment_id,
  2018. 'error' => $e->getMessage()
  2019. ];
  2020. }
  2021. // 创建任务之后先暂停10s等待异步任务完成
  2022. sleep(10);
  2023. $img_url = $this->loopGetPicTaskResult($task_id);
  2024. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2025. // 图片生成后新增对话记录
  2026. try {
  2027. $uid = Site::getUid();
  2028. $now = date('Y-m-d H:i:s');
  2029. // 使用AI反推图片提示词
  2030. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2031. // 保存对话记录
  2032. $records = [
  2033. [
  2034. 'uid' => $uid,
  2035. 'anime_id' => $anime_id,
  2036. 'sequence' => $episode_number,
  2037. 'role' => 'user',
  2038. 'content' => '重新生成',
  2039. 'segment_id' => $segment_id,
  2040. 'image_url' => '',
  2041. 'created_at' => $now,
  2042. 'updated_at' => $now
  2043. ],
  2044. [
  2045. 'uid' => $uid,
  2046. 'anime_id' => $anime_id,
  2047. 'sequence' => $episode_number,
  2048. 'role' => 'assistant',
  2049. 'content' => $pic_prompt,
  2050. 'segment_id' => $segment_id,
  2051. 'image_url' => $img_url,
  2052. 'created_at' => $now,
  2053. 'updated_at' => $now
  2054. ]
  2055. ];
  2056. DB::table('mp_anime_records')->insert($records);
  2057. } catch (\Exception $e) {
  2058. // 记录日志但不影响主流程
  2059. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2060. 'segment_id' => $segment_id,
  2061. 'img_url' => $img_url
  2062. ]);
  2063. }
  2064. return $img_url;
  2065. }
  2066. public function addSegment($data) {
  2067. $prev_segment_id = getProp($data, 'prev_segment_id');
  2068. $img_url = getProp($data, 'img_url');
  2069. $video_url = getProp($data, 'video_url');
  2070. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2071. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2072. $anime_id = getProp($segment, 'anime_id');
  2073. $episode_id = getProp($segment, 'episode_id');
  2074. $episode_number = getProp($segment, 'episode_number');
  2075. $segment_number = getProp($segment, 'segment_number');
  2076. $new_segment_number = $segment_number + 1;
  2077. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2078. // 分镜剧本数组
  2079. $insert_data = [
  2080. 'anime_id' => $anime_id,
  2081. 'episode_id' => $episode_id,
  2082. 'episode_number' => $episode_number,
  2083. 'act_number' => getProp($segment, 'act_number'),
  2084. 'act_title' => getProp($segment, 'act_title'),
  2085. 'segment_id' => $segment_id,
  2086. 'segment_number' => $new_segment_number,
  2087. 'segment_content' => '',
  2088. 'img_url' => '',
  2089. 'video_url' => '',
  2090. 'created_at' => date('Y-m-d H:i:s'),
  2091. 'updated_at' => date('Y-m-d H:i:s')
  2092. ];
  2093. if ($img_url) $insert_data['img_url'] = $img_url;
  2094. if ($video_url) {
  2095. $insert_data['origin_video_url'] = $video_url;
  2096. $insert_data['current_type'] = 2;
  2097. $compressed_video_url = compressVideo($video_url);
  2098. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2099. }
  2100. try {
  2101. DB::beginTransaction();
  2102. // 先更新序号
  2103. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2104. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2105. if (!$id) {
  2106. Utils::throwError('20003:新增分镜失败!');
  2107. }
  2108. }catch (\Exception $e) {
  2109. DB::rollBack();
  2110. Utils::throwError('20003:'.$e->getMessage());
  2111. }
  2112. DB::commit();
  2113. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2114. $segment = $segment ? (array)$segment : [];
  2115. return $segment;
  2116. // 以下代码暂弃用
  2117. $anime_id = getProp($segment, 'anime_id');
  2118. $episode_id = getProp($segment, 'episode_id');
  2119. $episode_number = getProp($segment, 'episode_number');
  2120. $segment_number = getProp($segment, 'segment_number');
  2121. $segment_content = getProp($data, 'segment_content');
  2122. $img_url = getProp($data, 'img_url');
  2123. $video_url = getProp($data, 'video_url');
  2124. $ratio = getProp($data, 'ratio');
  2125. $dimensions = $this->getRatioDimensions($ratio);
  2126. $width = $dimensions['width'];
  2127. $height = $dimensions['height'];
  2128. if (!$anime_id || !$episode_id) {
  2129. Utils::throwError('1002:请选择分镜');
  2130. }
  2131. // 使用文生文模型重新解析segment_content
  2132. if (!empty($segment_content)) {
  2133. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2134. }
  2135. // 获取动漫的角色信息(包含参考图)
  2136. $anime = DB::table('mp_animes')
  2137. ->where('id', $anime_id)
  2138. ->select('roles', 'scenes')
  2139. ->first();
  2140. if (!$anime || !$anime->roles) {
  2141. Utils::throwError('20003:未找到角色信息');
  2142. }
  2143. $roles = json_decode($anime->roles, true);
  2144. if (!$roles) {
  2145. Utils::throwError('20003:角色信息格式错误');
  2146. }
  2147. // 构建角色名称到参考图的映射
  2148. $role_map = [];
  2149. foreach ($roles as $role) {
  2150. $role_name = getProp($role, 'role');
  2151. $role_url = getProp($role, 'url');
  2152. if (!empty($role_name) && !empty($role_url)) {
  2153. $role_map[$role_name] = $role_url;
  2154. }
  2155. }
  2156. $scenes = json_decode($anime->scenes, true);
  2157. if (!$scenes) {
  2158. Utils::throwError('20003:角色信息格式错误');
  2159. }
  2160. // 构建角色名称到参考图的映射
  2161. $scene_map = [];
  2162. foreach ($scenes as $scene) {
  2163. $scene_name = getProp($scene, 'scene');
  2164. $scene_url = getProp($scene, 'url');
  2165. if (!empty($scene_name) && !empty($scene_url)) {
  2166. $scene_map[$scene_name] = $scene_url;
  2167. }
  2168. }
  2169. $segment_id = $segment->segment_id;
  2170. $original_segment_content = $segment->segment_content;
  2171. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2172. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2173. if (empty($final_segment_content)) {
  2174. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2175. }
  2176. try {
  2177. $dubTaskId = 0;
  2178. DB::beginTransaction();
  2179. $new_segment_number = $segment_number + 1;
  2180. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2181. // 分镜剧本数组
  2182. $insert_data = [
  2183. 'anime_id' => $anime_id,
  2184. 'episode_id' => $episode_id,
  2185. 'episode_number' => $episode_number,
  2186. 'act_number' => getProp($segment, 'act_number'),
  2187. 'act_title' => getProp($segment, 'act_title'),
  2188. 'segment_id' => $segment_id,
  2189. 'segment_number' => $new_segment_number,
  2190. 'segment_content' => $final_segment_content,
  2191. 'img_url' => $img_url,
  2192. 'video_url' => $video_url,
  2193. 'created_at' => date('Y-m-d H:i:s'),
  2194. 'updated_at' => date('Y-m-d H:i:s')
  2195. ];
  2196. // 更新分镜剧本信息
  2197. $this->handleSegmentContent($insert_data);
  2198. // 如果有对话内容,创建视频配音合成任务
  2199. $dialogue = getProp($insert_data, 'dialogue');
  2200. if (!empty($dialogue)) {
  2201. $now = date('Y-m-d H:i:s');
  2202. $generate_json = [
  2203. 'text' => $dialogue,
  2204. 'role' => getProp($insert_data, 'voice_actor'),
  2205. 'voice_type' => getProp($insert_data, 'voice_type'),
  2206. 'voice_name' => getProp($insert_data, 'voice_name'),
  2207. 'emotion' => getProp($insert_data, 'emotion'),
  2208. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2209. 'gender' => getProp($insert_data, 'gender'),
  2210. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2211. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2212. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2213. 'pitch' => getProp($insert_data, 'pitch', 0),
  2214. ];
  2215. // 插入视频配音合成任务
  2216. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2217. 'alias_segment_id' => $segment_id,
  2218. 'generate_status' => '执行中',
  2219. 'audio_url' => '',
  2220. 'generate_json' => json_encode($generate_json, 256),
  2221. 'created_at' => $now,
  2222. 'updated_at' => $now,
  2223. ]);
  2224. if (!$dubTaskId) {
  2225. Utils::throwError('20003:创建配音任务失败!');
  2226. }
  2227. $insert_data['audio_url'] = '';
  2228. } else {
  2229. // dialogue为空时,直接写入默认音频信息
  2230. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2231. $insert_data['audio_duration'] = 2.0;
  2232. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2233. }
  2234. // 如果没有上传图片则使用当前描述进行生成
  2235. if (!$img_url) {
  2236. // 解析分镜内容,提取画面描述作为主要提示词
  2237. $prompt = $final_segment_content;
  2238. $ref_img_urls = [];
  2239. // 分镜场景
  2240. $scene = getProp($insert_data, 'scene');
  2241. if ($scene) {
  2242. $matched_scene = '';
  2243. if (isset($scene_map[$scene])) {
  2244. $img_index = count($ref_img_urls) + 1;
  2245. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2246. $ref_img_urls[] = $scene_map[$scene];
  2247. $matched_scene = $scene;
  2248. }
  2249. $update_data['scene'] = $scene;
  2250. }
  2251. // 分镜角色
  2252. $characters = getProp($insert_data, 'characters');
  2253. if ($characters) {
  2254. $update_data['characters'] = $characters;
  2255. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2256. $characters = explode(',', $characters);
  2257. // 从分镜内容中提取涉及的角色
  2258. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2259. // 获取匹配角色的参考图
  2260. foreach ($segment_characters as $character) {
  2261. if (isset($role_map[$character])) {
  2262. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2263. $img_index = count($ref_img_urls) + 1;
  2264. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2265. $ref_img_urls[] = $role_map[$character];
  2266. }
  2267. }
  2268. }
  2269. // 如果没有找到匹配的角色参考图,不使用参考图
  2270. if (empty($ref_img_urls)) {
  2271. $ref_img_urls = [];
  2272. }
  2273. // 准备生成任务参数
  2274. $params = [
  2275. 'alias_segment_id' => $segment_id,
  2276. 'prompt' => $prompt,
  2277. 'ref_img_urls' => $ref_img_urls,
  2278. 'width' => $width,
  2279. 'height' => $height,
  2280. ];
  2281. // 调用AI图片生成服务
  2282. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2283. $task_id = $task->id;
  2284. // $task_id = 'whatever';
  2285. if (!$task_id) {
  2286. Utils::throwError('20003:创建生成任务失败!');
  2287. }
  2288. $insert_data['pic_task_status'] = '生成中';
  2289. $insert_data['pic_task_id'] = $task_id;
  2290. }
  2291. // 先更新序号
  2292. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2293. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2294. if (!$boolen) {
  2295. Utils::throwError('20003:新增分镜失败!');
  2296. }
  2297. // 如果是第一集的首帧图片,则存入待更新数组
  2298. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2299. Redis::sadd('anime_first_frame_urls', $segment_id);
  2300. }
  2301. if ($dubTaskId) {
  2302. // 请求远程服务器执行生成
  2303. $client = new Client(['timeout' => 300, 'verify' => false]);
  2304. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2305. $response = $result->getBody()->getContents();
  2306. $response_arr = json_decode($response, true);
  2307. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2308. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2309. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2310. Utils::throwError('20003:火山生成音频失败');
  2311. }
  2312. }
  2313. } catch (\Exception $e) {
  2314. DB::rollBack();
  2315. Utils::throwError('20003:'.$e->getMessage());
  2316. }
  2317. DB::commit();
  2318. // 创建任务之后先暂停10s等待异步任务完成
  2319. sleep(10);
  2320. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2321. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2322. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2323. $segment = $segment ? (array)$segment : [];
  2324. return $segment;
  2325. }
  2326. public function copySegment($data) {
  2327. $segment_id = getProp($data, 'segment_id');
  2328. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2329. if (!$segment) Utils::throwError('20003:请选择分镜');
  2330. $anime_id = getProp($segment, 'anime_id');
  2331. $episode_id = getProp($segment, 'episode_id');
  2332. $episode_number = getProp($segment, 'episode_number');
  2333. $segment_number = getProp($segment, 'segment_number');
  2334. $new_segment_id = 0;
  2335. try {
  2336. DB::beginTransaction();
  2337. $segment = (array)$segment;
  2338. unset($segment['id']);
  2339. $segment['segment_number'] += 1;
  2340. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2341. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2342. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2343. // 更新其他分镜序号
  2344. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2345. // 复制分镜
  2346. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2347. if (!$id) {
  2348. Utils::throwError('20003:复制分镜失败');
  2349. }
  2350. }catch (\Exception $e) {
  2351. DB::rollBack();
  2352. Utils::throwError('20003:'.$e->getMessage());
  2353. }
  2354. DB::commit();
  2355. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2356. $segment = $segment ? (array)$segment : [];
  2357. return $segment;
  2358. }
  2359. public function moveSegment($data) {
  2360. $segment_id = getProp($data, 'segment_id');
  2361. $target_segment_id = getProp($data, 'target_segment_id');
  2362. // 获取源分镜信息
  2363. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2364. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2365. // 获取目标分镜信息
  2366. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2367. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2368. $anime_id = getProp($source_segment, 'anime_id');
  2369. $episode_id = getProp($source_segment, 'episode_id');
  2370. $episode_number = getProp($source_segment, 'episode_number');
  2371. $source_segment_number = getProp($source_segment, 'segment_number');
  2372. $target_segment_number = getProp($target_segment, 'segment_number');
  2373. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2374. $target_anime_id = getProp($target_segment, 'anime_id');
  2375. $target_episode_number = getProp($target_segment, 'episode_number');
  2376. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2377. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2378. }
  2379. // 如果源分镜和目标分镜相同,无需移动
  2380. if ($source_segment_number == $target_segment_number) {
  2381. return true;
  2382. }
  2383. try {
  2384. DB::beginTransaction();
  2385. if ($source_segment_number < $target_segment_number) {
  2386. // 向后移动:源分镜移动到目标分镜之后
  2387. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2388. DB::table('mp_episode_segments')
  2389. ->where('anime_id', $anime_id)
  2390. ->where('episode_id', $episode_id)
  2391. ->where('segment_number', '>', $source_segment_number)
  2392. ->where('segment_number', '<=', $target_segment_number)
  2393. ->decrement('segment_number');
  2394. // 2. 将源分镜移动到目标分镜之后
  2395. $new_segment_number = $target_segment_number;
  2396. } else {
  2397. // 向前移动:源分镜移动到目标分镜之后
  2398. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2399. DB::table('mp_episode_segments')
  2400. ->where('anime_id', $anime_id)
  2401. ->where('episode_id', $episode_id)
  2402. ->where('segment_number', '>', $target_segment_number)
  2403. ->where('segment_number', '<', $source_segment_number)
  2404. ->increment('segment_number');
  2405. // 2. 将源分镜移动到目标分镜之后
  2406. $new_segment_number = $target_segment_number + 1;
  2407. }
  2408. // 3. 更新源分镜的序号
  2409. $update_result = DB::table('mp_episode_segments')
  2410. ->where('segment_id', $segment_id)
  2411. ->update([
  2412. 'segment_number' => $new_segment_number,
  2413. 'updated_at' => date('Y-m-d H:i:s')
  2414. ]);
  2415. if (!$update_result) {
  2416. Utils::throwError('20003:更新分镜序号失败');
  2417. }
  2418. DB::commit();
  2419. return true;
  2420. } catch (\Exception $e) {
  2421. DB::rollBack();
  2422. Utils::throwError('20003:' . $e->getMessage());
  2423. }
  2424. }
  2425. public function delSegment($data) {
  2426. $segment_id = getProp($data, 'segment_id');
  2427. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2428. if (!$segment) Utils::throwError('20003:请选择分镜');
  2429. $anime_id = getProp($segment, 'anime_id');
  2430. $episode_id = getProp($segment, 'episode_id');
  2431. $episode_number = getProp($segment, 'episode_number');
  2432. $segment_number = getProp($segment, 'segment_number');
  2433. try {
  2434. DB::beginTransaction();
  2435. // 删除分镜
  2436. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2437. if (!$boolen) {
  2438. Utils::throwError('20003:删除分镜失败');
  2439. }
  2440. // 更新其他分镜序号
  2441. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2442. }catch (\Exception $e) {
  2443. DB::rollBack();
  2444. Utils::throwError('20003:'.$e->getMessage());
  2445. }
  2446. DB::commit();
  2447. return true;
  2448. }
  2449. public function applySegment($data) {
  2450. $segment_id = getProp($data, 'segment_id');
  2451. $url = getProp($data, 'url');
  2452. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2453. if (!$url) Utils::throwError('20003:URL不能为空');
  2454. // 获取URL的文件扩展名
  2455. $urlPath = parse_url($url, PHP_URL_PATH);
  2456. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2457. // 定义图片和视频的扩展名
  2458. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2459. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2460. // 判断是图片还是视频
  2461. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2462. if (in_array($extension, $imageExtensions)) {
  2463. // 图片类型
  2464. $updateData['img_url'] = $url;
  2465. $updateData['current_type'] = 1;
  2466. } elseif (in_array($extension, $videoExtensions)) {
  2467. // 视频类型
  2468. $updateData['video_url'] = $url;
  2469. $updateData['current_type'] = 2;
  2470. } else {
  2471. Utils::throwError('20003:不支持的文件类型');
  2472. }
  2473. // 更新分镜表
  2474. $result = DB::table('mp_episode_segments')
  2475. ->where('segment_id', $segment_id)
  2476. ->update($updateData);
  2477. if (!$result) {
  2478. Utils::throwError('20003:更新分镜失败');
  2479. }
  2480. return true;
  2481. }
  2482. public function segmentHistory($data) {
  2483. $segment_id = getProp($data, 'segment_id');
  2484. // 获取历史图片
  2485. $pics = [];
  2486. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2487. foreach($pic_history as $task) {
  2488. $result_url = getProp($task, 'result_url');
  2489. if (is_json($result_url)) {
  2490. $pics = array_merge($pics, json_decode($result_url, true));
  2491. }else {
  2492. $pics[] = $result_url;
  2493. }
  2494. }
  2495. // 获取历史视频
  2496. $videos = [];
  2497. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2498. foreach($video_history as $task) {
  2499. $result_url = getProp($task, 'result_url');
  2500. if (is_json($result_url)) {
  2501. $videos = array_merge($videos, json_decode($result_url, true));
  2502. }else {
  2503. $videos[] = $result_url;
  2504. }
  2505. }
  2506. return compact('pics', 'videos');
  2507. }
  2508. public function addAct($data) {
  2509. $prev_act_id = getProp($data, 'prev_act_id');
  2510. $act_title = getProp($data, 'act_title', '');
  2511. $act_content = getProp($data, 'act_content', '');
  2512. $act_duration = getProp($data, 'act_duration', 5);
  2513. $video_url = getProp($data, 'video_url');
  2514. // 根据prev_act_id获取记录
  2515. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2516. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2517. $anime_id = getProp($prev_segment, 'anime_id');
  2518. $episode_id = getProp($prev_segment, 'episode_id');
  2519. $episode_number = getProp($prev_segment, 'episode_number');
  2520. $prev_act_number = getProp($prev_segment, 'act_number');
  2521. // 获取新的act_number
  2522. $new_act_number = $prev_act_number + 1;
  2523. try {
  2524. DB::beginTransaction();
  2525. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2526. DB::table('mp_episode_segments')
  2527. ->where('anime_id', $anime_id)
  2528. ->where('episode_id', $episode_id)
  2529. ->where('act_number', '>', $prev_act_number)
  2530. ->increment('act_number');
  2531. // 插入新片段记录
  2532. $insert_data = [
  2533. 'anime_id' => $anime_id,
  2534. 'episode_id' => $episode_id,
  2535. 'episode_number' => $episode_number,
  2536. 'act_number' => $new_act_number,
  2537. 'created_at' => date('Y-m-d H:i:s'),
  2538. 'updated_at' => date('Y-m-d H:i:s')
  2539. ];
  2540. if ($act_title) {
  2541. $insert_data['act_title'] = $act_title;
  2542. }
  2543. if ($act_content) {
  2544. $insert_data['act_content'] = $act_content;
  2545. }
  2546. if ($act_duration) {
  2547. $insert_data['act_duration'] = $act_duration;
  2548. }
  2549. if ($video_url) {
  2550. $insert_data['origin_video_url'] = $video_url;
  2551. $insert_data['current_type'] = 2;
  2552. $compressed_video_url = compressVideo($video_url);
  2553. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2554. }
  2555. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2556. if (!$id) {
  2557. Utils::throwError('20003:新增片段失败!');
  2558. }
  2559. DB::commit();
  2560. }catch (\Exception $e) {
  2561. DB::rollBack();
  2562. Utils::throwError('20003:'.$e->getMessage());
  2563. }
  2564. $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();
  2565. $segment = $segment ? (array)$segment : [];
  2566. return $segment;
  2567. }
  2568. public function editAct($data) {
  2569. $act_id = getProp($data, 'act_id');
  2570. $act_content = getProp($data, 'act_content');
  2571. $act_duration = getProp($data, 'act_duration');
  2572. $act_title = getProp($data, 'act_title');
  2573. $image_url = getProp($data, 'image_url');
  2574. $video_url = getProp($data, 'video_url');
  2575. // 参数验证
  2576. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2577. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2578. $segment = DB::table('mp_episode_segments')
  2579. ->where('id', $act_id)
  2580. ->first();
  2581. if (!$segment) Utils::throwError('20003:该片段不存在');
  2582. try {
  2583. DB::beginTransaction();
  2584. // 准备更新数据
  2585. $update_data = [
  2586. 'updated_at' => date('Y-m-d H:i:s')
  2587. ];
  2588. // 更新act相关字段
  2589. if (!empty($act_content)) {
  2590. $update_data['act_show_content'] = $act_content;
  2591. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2592. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2593. $shot_counter = 0;
  2594. $update_data['act_show_content'] = preg_replace_callback(
  2595. '/【(?:镜头|分镜)(\d+)】/u',
  2596. function($matches) use (&$shot_counter) {
  2597. $shot_counter++;
  2598. return '【镜头' . $shot_counter . '】';
  2599. },
  2600. $update_data['act_show_content']
  2601. );
  2602. }
  2603. if (!empty($act_duration)) {
  2604. $update_data['act_duration'] = $act_duration;
  2605. }
  2606. if (!empty($act_title)) {
  2607. $update_data['act_title'] = $act_title;
  2608. }
  2609. // 处理图片上传
  2610. if ($image_url) {
  2611. $update_data['img_url'] = $image_url;
  2612. $update_data['current_type'] = 1;
  2613. // 同时写入一个图片生成任务记录
  2614. if ($act_id) {
  2615. $pic_task = [
  2616. 'alias_act_id' => $act_id,
  2617. 'ref_img_url' => json_encode([]),
  2618. 'status' => 'success',
  2619. 'result_url' => json_encode([$image_url], 256),
  2620. 'model' => '',
  2621. 'created_at' => date('Y-m-d H:i:s'),
  2622. 'updated_at' => date('Y-m-d H:i:s'),
  2623. ];
  2624. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2625. }
  2626. }
  2627. // 处理视频上传
  2628. if ($video_url) {
  2629. $update_data['origin_video_url'] = $video_url;
  2630. $compressed_video_url = compressVideo($video_url);
  2631. $update_data['current_type'] = 2;
  2632. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2633. // 同时写入一个视频生成任务记录
  2634. if ($act_id) {
  2635. $video_task = [
  2636. 'alias_act_id' => $act_id,
  2637. 'status' => 'success',
  2638. 'result_url' => $update_data['origin_video_url'],
  2639. 'compressed_url' => $update_data['video_url'],
  2640. 'created_at' => date('Y-m-d H:i:s'),
  2641. 'updated_at' => date('Y-m-d H:i:s'),
  2642. ];
  2643. DB::table('mp_generate_video_tasks')->insert($video_task);
  2644. }
  2645. }
  2646. // 更新片段信息
  2647. $result = DB::table('mp_episode_segments')
  2648. ->where('id', $act_id)
  2649. ->update($update_data);
  2650. if ($result === false) {
  2651. Utils::throwError('20003:更新片段失败');
  2652. }
  2653. DB::commit();
  2654. // 返回新复制的记录
  2655. $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();
  2656. $new_segment = (array)$new_segment;
  2657. return $new_segment;
  2658. } catch (\Exception $e) {
  2659. DB::rollBack();
  2660. dLog('anime')->error('更新片段失败', [
  2661. 'act_id' => $act_id,
  2662. 'error' => $e->getMessage()
  2663. ]);
  2664. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2665. }
  2666. }
  2667. public function copyAct($data) {
  2668. $act_id = getProp($data, 'act_id');
  2669. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2670. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2671. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2672. $anime_id = getProp($source_segment, 'anime_id');
  2673. $episode_id = getProp($source_segment, 'episode_id');
  2674. $episode_number = getProp($source_segment, 'episode_number');
  2675. $act_number = getProp($source_segment, 'act_number');
  2676. try {
  2677. DB::beginTransaction();
  2678. // 新act的编号
  2679. $new_act_number = $act_number + 1;
  2680. // 更新后续所有act的act_number
  2681. DB::table('mp_episode_segments')
  2682. ->where('anime_id', $anime_id)
  2683. ->where('episode_id', $episode_id)
  2684. ->where('act_number', '>', $act_number)
  2685. ->increment('act_number');
  2686. // 复制该片段记录
  2687. $segment_data = (array)$source_segment;
  2688. unset($segment_data['id']);
  2689. $segment_data['video_url'] = '';
  2690. $segment_data['video_task_id'] = '';
  2691. $segment_data['video_task_status'] = '';
  2692. $segment_data['act_number'] = $new_act_number;
  2693. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2694. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2695. if (!$id) {
  2696. Utils::throwError('20003:复制片段失败');
  2697. }
  2698. DB::commit();
  2699. }catch (\Exception $e) {
  2700. DB::rollBack();
  2701. Utils::throwError('20003:'.$e->getMessage());
  2702. }
  2703. // 返回新复制的记录
  2704. $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();
  2705. $new_segment = $new_segment ? (array)$new_segment : [];
  2706. $new_segment['act_id'] = $id;
  2707. return $new_segment;
  2708. }
  2709. public function moveAct($data) {
  2710. $act_id = getProp($data, 'act_id');
  2711. $target_act_id = getProp($data, 'target_act_id');
  2712. // 获取源片段信息
  2713. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2714. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2715. // 获取目标片段信息
  2716. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2717. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2718. $anime_id = getProp($source_segment, 'anime_id');
  2719. $episode_id = getProp($source_segment, 'episode_id');
  2720. $source_act_number = getProp($source_segment, 'act_number');
  2721. $target_act_number = getProp($target_segment, 'act_number');
  2722. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2723. $target_anime_id = getProp($target_segment, 'anime_id');
  2724. $target_episode_id = getProp($target_segment, 'episode_id');
  2725. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2726. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2727. }
  2728. // 如果源片段和目标片段相同,无需移动
  2729. if ($source_act_number == $target_act_number) {
  2730. return true;
  2731. }
  2732. try {
  2733. DB::beginTransaction();
  2734. if ($source_act_number < $target_act_number) {
  2735. // 向后移动:源片段移动到目标片段之后
  2736. // 1. 将源片段和目标片段之间的所有片段编号减1
  2737. DB::table('mp_episode_segments')
  2738. ->where('anime_id', $anime_id)
  2739. ->where('episode_id', $episode_id)
  2740. ->where('act_number', '>', $source_act_number)
  2741. ->where('act_number', '<=', $target_act_number)
  2742. ->decrement('act_number');
  2743. // 2. 将源片段移动到目标片段之后
  2744. $new_act_number = $target_act_number;
  2745. } else {
  2746. // 向前移动:源片段移动到目标片段之后
  2747. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2748. DB::table('mp_episode_segments')
  2749. ->where('anime_id', $anime_id)
  2750. ->where('episode_id', $episode_id)
  2751. ->where('act_number', '>', $target_act_number)
  2752. ->where('act_number', '<', $source_act_number)
  2753. ->increment('act_number');
  2754. // 2. 将源片段移动到目标片段之后
  2755. $new_act_number = $target_act_number + 1;
  2756. }
  2757. // 3. 更新源片段的编号
  2758. $update_result = DB::table('mp_episode_segments')
  2759. ->where('id', $act_id)
  2760. ->update([
  2761. 'act_number' => $new_act_number,
  2762. 'updated_at' => date('Y-m-d H:i:s')
  2763. ]);
  2764. if (!$update_result) {
  2765. Utils::throwError('20003:更新片段编号失败');
  2766. }
  2767. DB::commit();
  2768. return true;
  2769. } catch (\Exception $e) {
  2770. DB::rollBack();
  2771. Utils::throwError('20003:' . $e->getMessage());
  2772. }
  2773. }
  2774. public function delAct($data) {
  2775. $act_id = getProp($data, 'act_id');
  2776. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2777. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2778. if (!$segment) Utils::throwError('20003:请选择片段');
  2779. $anime_id = getProp($segment, 'anime_id');
  2780. $episode_id = getProp($segment, 'episode_id');
  2781. $act_number = getProp($segment, 'act_number');
  2782. try {
  2783. DB::beginTransaction();
  2784. // 删除该片段记录
  2785. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2786. if (!$deleted) {
  2787. Utils::throwError('20003:删除片段失败');
  2788. }
  2789. // 更新后续act的编号
  2790. DB::table('mp_episode_segments')
  2791. ->where('anime_id', $anime_id)
  2792. ->where('episode_id', $episode_id)
  2793. ->where('act_number', '>', $act_number)
  2794. ->decrement('act_number');
  2795. DB::commit();
  2796. }catch (\Exception $e) {
  2797. DB::rollBack();
  2798. Utils::throwError('20003:'.$e->getMessage());
  2799. }
  2800. return true;
  2801. }
  2802. public function applyAct($data) {
  2803. $act_id = getProp($data, 'act_id');
  2804. $url = getProp($data, 'url');
  2805. if (!$act_id) Utils::throwError('20003:请选择片段');
  2806. if (!$url) Utils::throwError('20003:URL不能为空');
  2807. // 获取URL的文件扩展名
  2808. $urlPath = parse_url($url, PHP_URL_PATH);
  2809. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2810. // 定义图片和视频的扩展名
  2811. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2812. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2813. // 判断是图片还是视频
  2814. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2815. if (in_array($extension, $imageExtensions)) {
  2816. // 图片类型
  2817. $updateData['img_url'] = $url;
  2818. $updateData['current_type'] = 1;
  2819. } elseif (in_array($extension, $videoExtensions)) {
  2820. // 视频类型
  2821. $updateData['video_url'] = $url;
  2822. $updateData['current_type'] = 2;
  2823. } else {
  2824. Utils::throwError('20003:不支持的文件类型');
  2825. }
  2826. // 更新片段记录(全能模式下每个act只有一条记录)
  2827. $result = DB::table('mp_episode_segments')
  2828. ->where('id', $act_id)
  2829. ->update($updateData);
  2830. if (!$result) {
  2831. Utils::throwError('20003:更新片段失败');
  2832. }
  2833. return true;
  2834. }
  2835. public function actChatHistory($data) {
  2836. $act_id = getProp($data, 'act_id');
  2837. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2838. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2839. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2840. $value = (array)$value;
  2841. $value['created_at'] = transDate($value['created_at']);
  2842. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2843. else $value['reference_images'] = [];
  2844. return $value;
  2845. })->toArray();
  2846. // 获取历史图片
  2847. $url = [];
  2848. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2849. foreach($pic_history as $task) {
  2850. $result_url = getProp($task, 'result_url');
  2851. if (is_json($result_url)) {
  2852. $url = array_merge($url, json_decode($result_url, true));
  2853. }else {
  2854. $url[] = $result_url;
  2855. }
  2856. }
  2857. // 获取历史视频
  2858. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2859. foreach($video_history as $task) {
  2860. $result_url = getProp($task, 'result_url');
  2861. if (is_json($result_url)) {
  2862. $url = array_merge($url, json_decode($result_url, true));
  2863. }else {
  2864. $url[] = $result_url;
  2865. }
  2866. }
  2867. // 获取资产库
  2868. $products = [];
  2869. // 通过act_id查询片段信息获取episode_id
  2870. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2871. if ($segment) {
  2872. $episode_id = getProp($segment, 'episode_id');
  2873. // 查询剧集信息获取roles、scenes和extra_products
  2874. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2875. if ($episode) {
  2876. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2877. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2878. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2879. // 先合并roles和scenes
  2880. // 处理角色数组
  2881. foreach ($roles as $role) {
  2882. $product = $role;
  2883. // 将role字段重命名为product_name
  2884. if (isset($product['role'])) {
  2885. $product['product_name'] = $product['role'];
  2886. unset($product['role']);
  2887. }
  2888. $product['product'] = 1; // 标记类型为角色
  2889. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2890. }
  2891. // 处理场景数组
  2892. foreach ($scenes as $scene) {
  2893. $product = $scene;
  2894. // 将scene字段重命名为product_name
  2895. if (isset($product['scene'])) {
  2896. $product['product_name'] = $product['scene'];
  2897. unset($product['scene']);
  2898. }
  2899. $product['product'] = 2; // 标记类型为场景
  2900. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2901. }
  2902. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2903. foreach ($extra_products as $extra_product) {
  2904. $product_name = getProp($extra_product, 'product_name');
  2905. if ($product_name) {
  2906. $products[$product_name] = $extra_product; // 覆盖同名数据
  2907. }
  2908. }
  2909. // 重新索引数组(去除key)
  2910. $products = array_values($products);
  2911. }
  2912. }
  2913. // 获取执行中的任务
  2914. $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) {
  2915. $value = (array)$value;
  2916. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2917. else $value['ref_image_url'] = [];
  2918. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2919. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2920. if (!empty($value['prompt'])) {
  2921. $prompt = $value['prompt'];
  2922. // 查找第一个【镜头】的位置
  2923. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2924. // 从【镜头】开始截取
  2925. $prompt = substr($prompt, $matches[0][1]);
  2926. }
  2927. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2928. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2929. $value['prompt'] = $prompt;
  2930. }
  2931. return $value;
  2932. })->toArray();
  2933. return compact('chat', 'url', 'products', 'tasks');
  2934. }
  2935. public function applyAudioData($data) {
  2936. $segment_id = getProp($data, 'segment_id');
  2937. $global_data = getProp($data, 'global_data');
  2938. $segment_data = getProp($data, 'segment_data');
  2939. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2940. $global_data = is_array($global_data) ? $global_data : [];
  2941. $segment_data = is_array($segment_data) ? $segment_data : [];
  2942. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2943. $dialogue_item = null;
  2944. foreach ($global_data as $key => $item) {
  2945. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2946. $dialogue_item = $item;
  2947. unset($global_data[$key]);
  2948. break;
  2949. }
  2950. }
  2951. if ($dialogue_item) {
  2952. $segment_data[] = $dialogue_item;
  2953. }
  2954. // 特殊参数: audio_url,audio_duration,subtitle_info
  2955. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2956. // 如果不是全部存在,则仍需创建音频任务
  2957. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2958. $special_update_data = [];
  2959. $has_all_special_params = false;
  2960. // 从segment_data中提取特殊参数
  2961. $filtered_segment_data = [];
  2962. foreach ($segment_data as $item) {
  2963. $field_name = trim((string)getProp($item, 'name'));
  2964. if (in_array($field_name, $special_fields)) {
  2965. $special_update_data[$field_name] = getProp($item, 'value');
  2966. } else {
  2967. // 非特殊参数保留,继续后续处理
  2968. $filtered_segment_data[] = $item;
  2969. }
  2970. }
  2971. // 检查是否三个特殊参数都存在
  2972. if (count($special_update_data) === 3 &&
  2973. isset($special_update_data['audio_url']) &&
  2974. isset($special_update_data['audio_duration']) &&
  2975. isset($special_update_data['subtitle_info'])) {
  2976. $has_all_special_params = true;
  2977. // 立即更新到当前分镜
  2978. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  2979. DB::table('mp_episode_segments')
  2980. ->where('segment_id', $segment_id)
  2981. ->update($special_update_data);
  2982. }
  2983. // 使用过滤后的segment_data继续处理其他参数
  2984. $segment_data = $filtered_segment_data;
  2985. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  2986. $global_update_data = [];
  2987. $segment_update_data = [];
  2988. $global_voice_type = '';
  2989. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2990. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  2991. $episode_id = getProp($target_segment, 'episode_id');
  2992. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  2993. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2994. if (!$episode) Utils::throwError('20003:分集不存在');
  2995. foreach ($global_data as $item) {
  2996. $field_name = trim((string)getProp($item, 'name'));
  2997. if (!$field_name || !in_array($field_name, $allow_fields)) {
  2998. continue;
  2999. }
  3000. $global_update_data[$field_name] = getProp($item, 'value');
  3001. if ($field_name === 'voice_type') {
  3002. $global_voice_type = trim((string)getProp($item, 'value'));
  3003. }
  3004. }
  3005. foreach ($segment_data as $item) {
  3006. $field_name = trim((string)getProp($item, 'name'));
  3007. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3008. continue;
  3009. }
  3010. $segment_update_data[$field_name] = getProp($item, 'value');
  3011. }
  3012. if ($global_voice_type) {
  3013. $timbre_info = DB::table('mp_timbres')
  3014. ->where('timbre_type', $global_voice_type)
  3015. ->select('audio_url', 'timbre_name')
  3016. ->first();
  3017. if ($timbre_info) {
  3018. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3019. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3020. }
  3021. }
  3022. try {
  3023. DB::beginTransaction();
  3024. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3025. $segment_ids_to_create_task = [];
  3026. $segments_data = [];
  3027. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3028. if (!empty($global_update_data)) {
  3029. // 如果角色不存在,则只更新当前分镜
  3030. if (!$target_voice_actor) {
  3031. // 只处理当前分镜
  3032. $affected_segments = DB::table('mp_episode_segments')
  3033. ->where('segment_id', $segment_id)
  3034. ->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')
  3035. ->get();
  3036. } else {
  3037. // 获取该角色的所有分镜
  3038. $affected_segments = DB::table('mp_episode_segments')
  3039. ->where('episode_id', $episode_id)
  3040. ->where('voice_actor', $target_voice_actor)
  3041. ->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')
  3042. ->get();
  3043. }
  3044. foreach ($affected_segments as $seg) {
  3045. $seg = (array)$seg;
  3046. $sid = getProp($seg, 'segment_id');
  3047. // 检查参数是否发生变化
  3048. $has_changed = false;
  3049. foreach ($global_update_data as $field => $new_value) {
  3050. $old_value = getProp($seg, $field);
  3051. if ($old_value != $new_value) {
  3052. $has_changed = true;
  3053. break;
  3054. }
  3055. }
  3056. if ($has_changed) {
  3057. $segment_ids_to_create_task[] = $sid;
  3058. $segments_data[$sid] = $seg;
  3059. }
  3060. }
  3061. // 只有在有变化的分镜时才更新
  3062. if (!empty($segment_ids_to_create_task)) {
  3063. $global_segment_update_data = $global_update_data;
  3064. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3065. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3066. DB::table('mp_episode_segments')
  3067. ->where('episode_id', $episode_id)
  3068. ->where('voice_actor', $target_voice_actor)
  3069. ->whereIn('segment_id', $segment_ids_to_create_task)
  3070. ->update($global_segment_update_data);
  3071. }
  3072. if ($global_voice_type) {
  3073. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3074. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3075. $roles_updated = false;
  3076. foreach ($episode_roles as &$role) {
  3077. // 通过 role 字段匹配角色名,而不是 voice_name
  3078. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3079. continue;
  3080. }
  3081. $role['voice_type'] = $global_voice_type;
  3082. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3083. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3084. $roles_updated = true;
  3085. }
  3086. unset($role);
  3087. if ($roles_updated) {
  3088. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3089. 'roles' => json_encode($episode_roles, 256),
  3090. 'updated_at' => date('Y-m-d H:i:s'),
  3091. ]);
  3092. }
  3093. }
  3094. }
  3095. // 如果有单个分镜更新,检查是否有变化
  3096. if (!empty($segment_update_data)) {
  3097. // 获取当前分镜数据
  3098. $current_segment = DB::table('mp_episode_segments')
  3099. ->where('segment_id', $segment_id)
  3100. ->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')
  3101. ->first();
  3102. if ($current_segment) {
  3103. $current_segment = (array)$current_segment;
  3104. // 检查参数是否发生变化
  3105. $has_changed = false;
  3106. foreach ($segment_update_data as $field => $new_value) {
  3107. $old_value = getProp($current_segment, $field);
  3108. if ($old_value != $new_value) {
  3109. $has_changed = true;
  3110. break;
  3111. }
  3112. }
  3113. if ($has_changed) {
  3114. // 如果该分镜还未在列表中,添加进去
  3115. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3116. $segment_ids_to_create_task[] = $segment_id;
  3117. $segments_data[$segment_id] = $current_segment;
  3118. }
  3119. // 更新分镜数据并清空音频URL
  3120. $segment_update_data['audio_url'] = '';
  3121. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3122. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3123. }
  3124. }
  3125. }
  3126. // 为所有有变化的分镜创建音频合成任务
  3127. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3128. if (!empty($segment_ids_to_create_task)) {
  3129. foreach ($segment_ids_to_create_task as $sid) {
  3130. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3131. if ($sid === $segment_id && $has_all_special_params) {
  3132. continue;
  3133. }
  3134. // 重新获取更新后的分镜数据
  3135. $updated_segment = DB::table('mp_episode_segments')
  3136. ->where('segment_id', $sid)
  3137. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3138. ->first();
  3139. if (!$updated_segment) continue;
  3140. $updated_segment = (array)$updated_segment;
  3141. // 检查dialogue是否为空
  3142. $dialogue = getProp($updated_segment, 'dialogue');
  3143. if (empty($dialogue)) {
  3144. // dialogue为空时,直接写入默认音频信息
  3145. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3146. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3147. 'audio_duration' => 2.0,
  3148. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3149. 'updated_at' => date('Y-m-d H:i:s')
  3150. ]);
  3151. continue;
  3152. }
  3153. $generate_json = [
  3154. 'text' => $dialogue,
  3155. 'role' => getProp($updated_segment, 'voice_actor'),
  3156. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3157. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3158. 'emotion' => getProp($updated_segment, 'emotion'),
  3159. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3160. 'gender' => getProp($updated_segment, 'gender'),
  3161. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3162. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3163. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3164. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3165. ];
  3166. // 插入视频配音合成任务
  3167. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3168. 'alias_segment_id' => $sid,
  3169. 'generate_status' => '执行中',
  3170. 'audio_url' => '',
  3171. 'generate_json' => json_encode($generate_json, 256),
  3172. 'created_at' => date('Y-m-d H:i:s'),
  3173. 'updated_at' => date('Y-m-d H:i:s'),
  3174. ]);
  3175. if (!$dubTaskId) {
  3176. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3177. continue;
  3178. }
  3179. // 将任务ID添加到Redis列表中
  3180. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3181. // 请求远程服务器执行生成
  3182. try {
  3183. sleep(1);
  3184. $client = new Client(['timeout' => 300, 'verify' => false]);
  3185. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3186. $response = $result->getBody()->getContents();
  3187. $response_arr = json_decode($response, true);
  3188. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3189. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3190. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3191. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3192. }
  3193. } catch (\Exception $e) {
  3194. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3195. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3196. }
  3197. }
  3198. }
  3199. DB::commit();
  3200. } catch (\Exception $e) {
  3201. DB::rollBack();
  3202. Utils::throwError('20003:'.$e->getMessage());
  3203. }
  3204. return true;
  3205. }
  3206. public function episodePicsInfo($data) {
  3207. $anime_id = getProp($data, 'anime_id');
  3208. $episode_id = getProp($data, 'episode_id');
  3209. // 参数验证
  3210. if (!$anime_id && !$episode_id) {
  3211. Utils::throwError('20003:请提供动漫ID或分集ID');
  3212. }
  3213. // 根据参数获取数据源
  3214. if ($episode_id) {
  3215. // 从剧集表获取
  3216. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3217. if (!$source) Utils::throwError('20003:该剧集不存在');
  3218. $table_name = 'mp_anime_episodes';
  3219. $id_field = 'id';
  3220. $id_value = $episode_id;
  3221. // 获取剧集的anime_id用于继承全局数据
  3222. $anime_id = getProp($source, 'anime_id');
  3223. } else {
  3224. // 从动漫表获取
  3225. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3226. if (!$source) Utils::throwError('20003:该动漫不存在');
  3227. $table_name = 'mp_animes';
  3228. $id_field = 'id';
  3229. $id_value = $anime_id;
  3230. }
  3231. $source = (array)$source;
  3232. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3233. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3234. // 如果是分集数据,需要处理继承和任务创建逻辑
  3235. if ($episode_id) {
  3236. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3237. }
  3238. // 返回生成器函数,用于 SSE 流式输出
  3239. return function() use ($roles, $scenes, $table_name, $id_field, $id_value) {
  3240. $startTime = time();
  3241. $maxDuration = 600; // 10分钟超时
  3242. $checkInterval = 3; // 每3秒检查一次
  3243. // Redis 缓存键
  3244. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3245. // 生成当前数据的哈希值用于比较
  3246. $generateHash = function($roles, $scenes) {
  3247. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes], JSON_UNESCAPED_UNICODE));
  3248. };
  3249. // 发送初始数据
  3250. $currentHash = $generateHash($roles, $scenes);
  3251. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3252. echo "data: " . json_encode([
  3253. 'type' => 'init',
  3254. 'data' => [
  3255. 'roles' => $roles,
  3256. 'scenes' => $scenes,
  3257. 'start_time' => $startTime
  3258. ]
  3259. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3260. ob_flush();
  3261. flush();
  3262. // 持续轮询任务状态
  3263. while (time() - $startTime < $maxDuration) {
  3264. $hasProcessing = false;
  3265. $updated = false;
  3266. // 检查角色任务状态
  3267. foreach ($roles as $index => &$role) {
  3268. $task_id = getProp($role, 'task_id');
  3269. $task_status = getProp($role, 'task_status');
  3270. $existing_url = getProp($role, 'url');
  3271. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3272. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3273. $hasProcessing = ($task_status === 'processing');
  3274. // 查询任务状态
  3275. $task = DB::table('mp_generate_pic_tasks')
  3276. ->where('id', $task_id)
  3277. ->select('id', 'status', 'result_url', 'error_message')
  3278. ->first();
  3279. if ($task) {
  3280. $task = (array)$task;
  3281. $status = getProp($task, 'status');
  3282. // 如果任务完成或失败
  3283. if (in_array($status, ['success', 'failed'])) {
  3284. $role['task_status'] = $status;
  3285. if ($status === 'success') {
  3286. $result_url = getProp($task, 'result_url');
  3287. if ($result_url) {
  3288. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3289. if (is_array($result_urls) && !empty($result_urls[0])) {
  3290. $role['url'] = $result_urls[0];
  3291. }
  3292. }
  3293. }
  3294. $updated = true;
  3295. } else if ($status === 'processing') {
  3296. $hasProcessing = true;
  3297. }
  3298. }
  3299. }
  3300. }
  3301. // 检查场景任务状态
  3302. foreach ($scenes as $index => &$scene) {
  3303. $task_id = getProp($scene, 'task_id');
  3304. $task_status = getProp($scene, 'task_status');
  3305. $existing_url = getProp($scene, 'url');
  3306. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3307. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3308. $hasProcessing = ($task_status === 'processing');
  3309. // 查询任务状态
  3310. $task = DB::table('mp_generate_pic_tasks')
  3311. ->where('id', $task_id)
  3312. ->select('id', 'status', 'result_url', 'error_message')
  3313. ->first();
  3314. if ($task) {
  3315. $task = (array)$task;
  3316. $status = getProp($task, 'status');
  3317. // 如果任务完成或失败
  3318. if (in_array($status, ['success', 'failed'])) {
  3319. $scene['task_status'] = $status;
  3320. if ($status === 'success') {
  3321. $result_url = getProp($task, 'result_url');
  3322. if ($result_url) {
  3323. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3324. if (is_array($result_urls) && !empty($result_urls[0])) {
  3325. $scene['url'] = $result_urls[0];
  3326. }
  3327. }
  3328. }
  3329. $updated = true;
  3330. } else if ($status === 'processing') {
  3331. $hasProcessing = true;
  3332. }
  3333. }
  3334. }
  3335. }
  3336. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3337. if ($updated) {
  3338. $newHash = $generateHash($roles, $scenes);
  3339. $cachedHash = Redis::get($cacheKey);
  3340. // 只有当数据真正变化时才更新数据库和发送事件
  3341. if ($newHash !== $cachedHash) {
  3342. try {
  3343. // 更新数据库
  3344. DB::table($table_name)->where($id_field, $id_value)->update([
  3345. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3346. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3347. 'updated_at' => date('Y-m-d H:i:s')
  3348. ]);
  3349. // 更新缓存
  3350. Redis::setex($cacheKey, 600, $newHash);
  3351. // 发送更新事件
  3352. echo "data: " . json_encode([
  3353. 'type' => 'update',
  3354. 'data' => [
  3355. 'roles' => $roles,
  3356. 'scenes' => $scenes,
  3357. 'elapsed_time' => time() - $startTime
  3358. ]
  3359. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3360. ob_flush();
  3361. flush();
  3362. } catch (\Exception $e) {
  3363. dLog('anime')->error('更新角色/场景信息失败: ' . $e->getMessage());
  3364. }
  3365. } else {
  3366. // 即使哈希相同,如果有URL更新也要发送事件
  3367. $hasUrlUpdate = false;
  3368. foreach ($roles as $role) {
  3369. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3370. $hasUrlUpdate = true;
  3371. break;
  3372. }
  3373. }
  3374. if (!$hasUrlUpdate) {
  3375. foreach ($scenes as $scene) {
  3376. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3377. $hasUrlUpdate = true;
  3378. break;
  3379. }
  3380. }
  3381. }
  3382. if ($hasUrlUpdate) {
  3383. // 强制更新数据库和发送事件
  3384. try {
  3385. DB::table($table_name)->where($id_field, $id_value)->update([
  3386. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3387. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3388. 'updated_at' => date('Y-m-d H:i:s')
  3389. ]);
  3390. // 更新缓存
  3391. Redis::setex($cacheKey, 600, $newHash);
  3392. // 发送更新事件
  3393. echo "data: " . json_encode([
  3394. 'type' => 'update',
  3395. 'data' => [
  3396. 'roles' => $roles,
  3397. 'scenes' => $scenes,
  3398. 'elapsed_time' => time() - $startTime
  3399. ]
  3400. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3401. ob_flush();
  3402. flush();
  3403. } catch (\Exception $e) {
  3404. dLog('anime')->error('强制更新角色/场景信息失败: ' . $e->getMessage());
  3405. }
  3406. }
  3407. }
  3408. }
  3409. // 如果所有任务都已完成,发送完成事件并退出
  3410. if (!$hasProcessing) {
  3411. // 查询数据库中的最终数据,确保返回最新的完整数据
  3412. try {
  3413. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3414. if ($finalSource) {
  3415. $finalSource = (array)$finalSource;
  3416. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3417. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3418. // 使用数据库中的最终数据
  3419. $roles = $finalRoles;
  3420. $scenes = $finalScenes;
  3421. }
  3422. } catch (\Exception $e) {
  3423. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3424. // 如果查询失败,继续使用内存中的数据
  3425. }
  3426. // 清理缓存
  3427. Redis::del($cacheKey);
  3428. echo "data: " . json_encode([
  3429. 'type' => 'completed',
  3430. 'data' => [
  3431. 'roles' => $roles,
  3432. 'scenes' => $scenes,
  3433. 'total_time' => time() - $startTime
  3434. ]
  3435. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3436. ob_flush();
  3437. flush();
  3438. break;
  3439. }
  3440. // 等待下次检查
  3441. sleep($checkInterval);
  3442. }
  3443. // 超时处理
  3444. if (time() - $startTime >= $maxDuration) {
  3445. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3446. try {
  3447. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3448. if ($finalSource) {
  3449. $finalSource = (array)$finalSource;
  3450. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3451. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3452. // 使用数据库中的最终数据
  3453. $roles = $finalRoles;
  3454. $scenes = $finalScenes;
  3455. }
  3456. } catch (\Exception $e) {
  3457. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3458. // 如果查询失败,继续使用内存中的数据
  3459. }
  3460. // 清理缓存
  3461. Redis::del($cacheKey);
  3462. echo "data: " . json_encode([
  3463. 'type' => 'timeout',
  3464. 'message' => '轮询超时,请刷新页面查看最新状态',
  3465. 'data' => [
  3466. 'roles' => $roles,
  3467. 'scenes' => $scenes
  3468. ]
  3469. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3470. ob_flush();
  3471. flush();
  3472. }
  3473. };
  3474. }
  3475. public function clipSegmentVideo($data) {
  3476. $segment_id = getProp($data, 'segment_id');
  3477. $video_time_point_start = getProp($data, 'video_time_point_start');
  3478. $video_time_point_end = getProp($data, 'video_time_point_end');
  3479. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3480. Utils::throwError('20003:参数异常');
  3481. }
  3482. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3483. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3484. }
  3485. $video_duration = $video_time_point_end - $video_time_point_start;
  3486. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3487. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3488. 'video_duration' => $video_duration,
  3489. 'video_time_point_start' => $video_time_point_start,
  3490. 'video_time_point_end' => $video_time_point_end,
  3491. 'updated_at' => date('Y-m-d H:i:s')
  3492. ]);
  3493. }
  3494. // 轮训获取图片任务结果
  3495. private function loopGetPicTaskResult($task_id) {
  3496. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3497. if (!$task) {
  3498. return '';
  3499. }
  3500. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3501. $model = getProp($task, 'model');
  3502. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3503. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3504. $isSyncModel = $isVolcModel || $isGptModel;
  3505. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3506. $start_count = 0;
  3507. $img_url = '';
  3508. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3509. sleep(3);
  3510. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3511. // 如果任务已经完成,直接返回结果
  3512. if ($task->status === 'success' && $task->result_url) {
  3513. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3514. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3515. }
  3516. // 如果任务已失败,返回空
  3517. if ($task->status === 'failed') {
  3518. return '';
  3519. }
  3520. if ($isSyncModel) continue;
  3521. // 查询任务状态
  3522. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3523. if ($statusInfo['status'] === 'success') {
  3524. $task->updateStatus('success', [
  3525. 'result_url' => $statusInfo['result_url'],
  3526. 'result_json' => $statusInfo['result_json'] ?? []
  3527. ]);
  3528. // 同步调整分镜图片状态和结果
  3529. if (getProp($task, 'alias_segment_id')) {
  3530. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3531. 'img_url' => $statusInfo['result_url'][0],
  3532. 'pic_task_status' => '已完成',
  3533. ]);
  3534. }
  3535. $img_url = $statusInfo['result_url'][0];
  3536. break;
  3537. } elseif ($statusInfo['status'] === 'failed') {
  3538. $task->updateStatus('failed', [
  3539. 'error_message' => $statusInfo['error_message'],
  3540. 'result_json' => $statusInfo['result_json'] ?? []
  3541. ]);
  3542. if (getProp($task, 'alias_segment_id')) {
  3543. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3544. 'pic_task_status' => '失败',
  3545. ]);
  3546. }
  3547. break;
  3548. }
  3549. $start_count++;
  3550. }
  3551. return $img_url;
  3552. }
  3553. /**
  3554. * 从分镜内容中提取涉及的角色
  3555. */
  3556. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3557. $found_characters = [];
  3558. foreach ($available_characters as $character) {
  3559. // 检查角色名称是否在分镜内容中出现
  3560. if (strpos($segment_content, $character) !== false) {
  3561. $found_characters[] = $character;
  3562. }
  3563. }
  3564. if (!$found_characters) {
  3565. foreach ($roles as $character) {
  3566. // 检查角色名称是否在分镜内容中出现
  3567. if (strpos($segment_content, $character) !== false) {
  3568. $found_characters[] = $character;
  3569. }
  3570. }
  3571. }
  3572. return array_unique($found_characters);
  3573. }
  3574. // 从分镜剧本中提取关键字段
  3575. private function handleSegmentContent(&$data) {
  3576. $segmentContent = getProp($data, 'segment_content');
  3577. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3578. $segmentData = [
  3579. 'description' => '',
  3580. 'composition' => '',
  3581. 'camera_movement' => '',
  3582. 'voice_actor' => '',
  3583. 'dialogue' => '',
  3584. 'frame_type' => '',
  3585. 'scene' => '', // 场景
  3586. 'characters' => '', // 出镜角色
  3587. 'tail_frame' => '', // 尾帧描述
  3588. 'emotion' => '中性', // 情感
  3589. 'gender' => '0', // 性别(0未知,1男,2女)
  3590. 'speed_ratio' => 0, // 语速
  3591. 'loudness_ratio' => 0, // 音量
  3592. 'emotion_scale' => 4, // 情感强度
  3593. 'pitch' => 0, // 音调
  3594. ];
  3595. // 用于存储需要从 segment_content 中移除的匹配项
  3596. $replaceEmptyArr = [];
  3597. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3598. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3599. $segmentData['description'] = trim($descMatch[1]);
  3600. $data['description'] = trim($descMatch[1]);
  3601. }
  3602. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3603. $segmentData['composition'] = trim($compMatch[1]);
  3604. $data['composition'] = trim($compMatch[1]);
  3605. }
  3606. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3607. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3608. $data['camera_movement'] = trim($cameraMatch[1]);
  3609. }
  3610. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3611. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3612. $data['voice_actor'] = trim($voiceMatch[1]);
  3613. }
  3614. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3615. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3616. $data['dialogue'] = trim($dialogueMatch[1]);
  3617. }
  3618. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3619. $segmentData['frame_type'] = trim($frameMatch[1]);
  3620. $data['frame_type'] = trim($frameMatch[1]);
  3621. }
  3622. // 场景字段
  3623. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3624. $segmentData['scene'] = trim($sceneMatch[1]);
  3625. $data['scene'] = trim($sceneMatch[1]);
  3626. }
  3627. // 出镜角色字段
  3628. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3629. $segmentData['characters'] = trim($charactersMatch[1]);
  3630. $data['characters'] = trim($charactersMatch[1]);
  3631. }
  3632. // 尾帧描述字段
  3633. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3634. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3635. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3636. }
  3637. // 情感字段
  3638. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3639. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3640. $segmentData['emotion'] = trim($emotionMatch[1]);
  3641. $data['emotion'] = trim($emotionMatch[1]);
  3642. }
  3643. // 性别字段
  3644. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3645. $replaceEmptyArr[] = trim($genderMatch[0]);
  3646. $genderStr = trim($genderMatch[1]);
  3647. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3648. $segmentData['gender'] = '1';
  3649. $data['gender'] = '1';
  3650. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3651. $segmentData['gender'] = '2';
  3652. $data['gender'] = '2';
  3653. } else {
  3654. $segmentData['gender'] = '0';
  3655. $data['gender'] = '0';
  3656. }
  3657. }
  3658. // 语速字段
  3659. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3660. $replaceEmptyArr[] = trim($speedMatch[0]);
  3661. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3662. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3663. }
  3664. // 音量字段
  3665. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3666. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3667. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3668. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3669. }
  3670. // 情感强度字段
  3671. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3672. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3673. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3674. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3675. }
  3676. // 音调字段
  3677. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3678. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3679. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3680. $data['pitch'] = (int)trim($pitchMatch[1]);
  3681. }
  3682. // 从 segment_content 中移除已提取的配音参数字段
  3683. if (!empty($replaceEmptyArr)) {
  3684. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3685. }
  3686. // 如果有配音角色,查询音色信息并验证情感
  3687. $voice_actor = $segmentData['voice_actor'];
  3688. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3689. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3690. $anime_id = getProp($data, 'anime_id');
  3691. $episode_id = getProp($data, 'episode_id');
  3692. // 优先从剧集的角色列表中查找
  3693. $roles = [];
  3694. if ($episode_id) {
  3695. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3696. if ($episode && getProp($episode, 'roles')) {
  3697. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3698. }
  3699. }
  3700. // 如果剧集中没有,从动漫的角色列表中查找
  3701. if (empty($roles) && $anime_id) {
  3702. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3703. if ($anime && getProp($anime, 'roles')) {
  3704. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3705. }
  3706. }
  3707. // 查找匹配的角色音色信息
  3708. $timbre_info = null;
  3709. foreach ($roles as $role) {
  3710. if (getProp($role, 'role') === $voice_actor) {
  3711. $timbre_info = $role;
  3712. break;
  3713. }
  3714. }
  3715. // 如果找到音色信息,添加到数据中
  3716. if ($timbre_info) {
  3717. $voice_type = getProp($timbre_info, 'voice_type');
  3718. $voice_name = getProp($timbre_info, 'voice_name');
  3719. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3720. if ($voice_type) {
  3721. $data['voice_type'] = $voice_type;
  3722. $segmentData['voice_type'] = $voice_type;
  3723. }
  3724. if ($voice_name) {
  3725. $data['voice_name'] = $voice_name;
  3726. $segmentData['voice_name'] = $voice_name;
  3727. }
  3728. if ($voice_audio_url) {
  3729. $data['voice_audio_url'] = $voice_audio_url;
  3730. $segmentData['voice_audio_url'] = $voice_audio_url;
  3731. }
  3732. // 验证情感是否在音色支持的情感列表中
  3733. if ($voice_type) {
  3734. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3735. if ($timbre_emotion) {
  3736. $timbre_emotion = explode(',', $timbre_emotion);
  3737. } else {
  3738. $timbre_emotion = [];
  3739. }
  3740. $emotion = getProp($segmentData, 'emotion', '中性');
  3741. if (!in_array($emotion, $timbre_emotion)) {
  3742. $emotion = '中性';
  3743. }
  3744. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3745. $emotion_list = array_flip($emotion_list);
  3746. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3747. $data['emotion_type'] = $emotion_type;
  3748. $segmentData['emotion_type'] = $emotion_type;
  3749. }
  3750. }
  3751. }
  3752. return $segmentData;
  3753. }
  3754. public function createSegmentVideoTask($data) {
  3755. $segment_id = getProp($data, 'segment_id');
  3756. $tail_frame = getProp($data, 'tail_frame');
  3757. $first_frame_url = getProp($data, 'first_frame_url');
  3758. $tail_frame_url = getProp($data, 'tail_frame_url');
  3759. $generate_audio = getProp($data, 'generate_audio', 0);
  3760. if (!$segment_id) {
  3761. Utils::throwError('1002:分镜ID不能为空');
  3762. }
  3763. // 获取分镜信息
  3764. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3765. if (!$segment) {
  3766. Utils::throwError('20003:分镜不存在');
  3767. }
  3768. $segment = (array)$segment;
  3769. $episode_id = getProp($segment, 'episode_id');
  3770. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3771. if (!$ratio) $ratio = '9:16';
  3772. // 获取分镜内容
  3773. $segmentContent = getProp($segment, 'segment_content', '');
  3774. // 检查 $segmentContent 中是否已有尾帧描述
  3775. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3776. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3777. $finalTailFrame = '';
  3778. if ($tail_frame) {
  3779. // 用户输入了尾帧描述,优先使用
  3780. $finalTailFrame = $tail_frame;
  3781. // 如果 segmentContent 中已有尾帧描述,需要替换
  3782. if ($contentHasTailFrame) {
  3783. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3784. }
  3785. } elseif ($contentHasTailFrame) {
  3786. // segmentContent 中有尾帧描述,使用它
  3787. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3788. } else {
  3789. // 两者都没有,使用分镜表中的尾帧描述
  3790. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3791. }
  3792. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3793. $hasDialogue = false;
  3794. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3795. $dialogue = trim($dialogueMatch[1]);
  3796. // 如果台词不为空且不是"无"
  3797. if (!empty($dialogue) && $dialogue !== '无') {
  3798. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3799. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3800. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3801. $hasDialogue = true;
  3802. }
  3803. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3804. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3805. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3806. if (!preg_match('/^[“]/', $dialogue)) {
  3807. $dialogue = '“' . $dialogue;
  3808. }
  3809. if (!preg_match('/[”]$/', $dialogue)) {
  3810. $dialogue .= '”';
  3811. }
  3812. // 将修改后的台词替换回 $segmentContent
  3813. $originalDialogue = $dialogueMatch[1];
  3814. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3815. }
  3816. }
  3817. // 构建完整的提示词
  3818. $fullPrompt = $segmentContent;
  3819. if ($finalTailFrame && !$contentHasTailFrame) {
  3820. // 只有当 segmentContent 中没有尾帧描述时才追加
  3821. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3822. }
  3823. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3824. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3825. $fullPrompt = trim($fullPrompt);
  3826. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3827. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3828. // 智能选择视频时长
  3829. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3830. $videoDuration = -1;
  3831. // 处理视频模型
  3832. $model = getProp($data, 'model');
  3833. if (!$model) {
  3834. // 用户没有输入,从episode表获取
  3835. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3836. $model = getProp($episode, 'video_model');
  3837. if (!$model) {
  3838. // episode表也没有,使用默认值
  3839. $model = 'doubao-seedance-1-5-pro-251215';
  3840. }
  3841. }
  3842. // 验证模型是否在可用模型表中
  3843. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3844. $model = 'doubao-seedance-1-5-pro-251215';
  3845. }
  3846. // 保存到episode表
  3847. $episode_id = getProp($segment, 'episode_id');
  3848. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3849. 'video_model' => $model,
  3850. 'updated_at' => date('Y-m-d H:i:s')
  3851. ]);
  3852. // 构建视频生成参数
  3853. $videoParams = [
  3854. 'model' => $model,
  3855. 'alias_segment_id' => $segment_id,
  3856. 'prompt' => trim($fullPrompt),
  3857. 'video_duration' => $videoDuration,
  3858. 'video_resolution' => '720P',
  3859. 'seed' => -1,
  3860. 'ratio' => $ratio,
  3861. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3862. 'draft' => false,
  3863. 'watermark' => false,
  3864. 'camera_fixed' => false,
  3865. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3866. ];
  3867. // 如果分镜有图片,作为首帧
  3868. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3869. $hasVideo = !empty(getProp($segment, 'video_url'));
  3870. if ($hasImage) {
  3871. if ($first_frame_url) {
  3872. $videoParams['first_frame_url'] = $first_frame_url;
  3873. }else {
  3874. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3875. }
  3876. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3877. }
  3878. // 构建content数组
  3879. $videoParams['content'] = [
  3880. [
  3881. 'type' => 'text',
  3882. 'text' => $videoParams['prompt'],
  3883. ]
  3884. ];
  3885. // 如果有首帧图片,添加到content中
  3886. if ($hasImage) {
  3887. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3888. $videoParams['content'][] = [
  3889. 'type' => 'image_url',
  3890. 'image_url' => [
  3891. 'url' => $videoParams['first_frame_url'],
  3892. ],
  3893. 'role' => 'reference_image',
  3894. ];
  3895. if (isset($videoParams['tail_frame_url'])) {
  3896. $videoParams['content'][] = [
  3897. 'type' => 'image_url',
  3898. 'image_url' => [
  3899. 'url' => $videoParams['tail_frame_url'],
  3900. ],
  3901. 'role' => 'reference_image',
  3902. ];
  3903. }
  3904. }else {
  3905. $videoParams['content'][] = [
  3906. 'type' => 'image_url',
  3907. 'image_url' => [
  3908. 'url' => $videoParams['first_frame_url'],
  3909. ],
  3910. 'role' => 'first_frame',
  3911. ];
  3912. if (isset($videoParams['tail_frame_url'])) {
  3913. $videoParams['content'][] = [
  3914. 'type' => 'image_url',
  3915. 'image_url' => [
  3916. 'url' => $videoParams['tail_frame_url'],
  3917. ],
  3918. 'role' => 'last_frame',
  3919. ];
  3920. }
  3921. }
  3922. }
  3923. // 获取配音音频URL
  3924. $audioUrl = getProp($segment, 'audio_url');
  3925. $audioDuration = getProp($segment, 'audio_duration');
  3926. // 音频传入的前提:必须有至少一张图片或一个视频
  3927. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  3928. // dd($videoParams);
  3929. // 根据模型选择不同的视频生成方法
  3930. if (strpos($model, 'jimeng') !== false) {
  3931. // 即梦模型参数调整
  3932. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  3933. unset($videoParams['content']); // 即梦不使用content格式
  3934. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  3935. } elseif (strpos($model, 'kling') !== false) {
  3936. // Keling模型参数调整
  3937. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  3938. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  3939. unset($videoParams['ratio']);
  3940. unset($videoParams['content']); // Keling不使用content格式
  3941. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  3942. } elseif (strpos($model, 'zhizhen') !== false) {
  3943. // 智帧20等新模型使用统一API
  3944. // 构建统一API参数
  3945. $unifiedParams = [
  3946. 'model_code' => $model,
  3947. 'alias_segment_id' => $segment_id,
  3948. 'prompt' => trim($fullPrompt),
  3949. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  3950. 'video_resolution' => strtolower($videoParams['video_resolution']),
  3951. 'video_ratio' => $ratio,
  3952. 'seed' => -1,
  3953. ];
  3954. // 构建parameters参数
  3955. $parameters = [
  3956. 'seconds' => $unifiedParams['video_duration'],
  3957. 'resolution' => $unifiedParams['video_resolution'],
  3958. 'ratio' => $ratio,
  3959. // 'video_mode' => 'multi_image',
  3960. // 'mode' => 'multi_image',
  3961. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  3962. ];
  3963. $hasImage = false;
  3964. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  3965. if ($hasImage) {
  3966. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  3967. if (isset($videoParams['tail_frame_url'])) {
  3968. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  3969. }
  3970. // 只有在有图片的情况下才能添加参考音频
  3971. if ($audioUrl) {
  3972. // $parameters['reference_audios'] = [$audioUrl];
  3973. }
  3974. } else {
  3975. // 没有图片时,记录错误日志
  3976. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  3977. 'segment_id' => $segment_id,
  3978. 'model' => $model
  3979. ]);
  3980. }
  3981. $unifiedParams['parameters'] = $parameters;
  3982. // 调用统一API创建任务
  3983. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  3984. } else {
  3985. // Seedance模型(默认)
  3986. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  3987. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3988. // 添加配音音频到content中
  3989. $videoParams['content'][] = [
  3990. 'type' => 'audio_url',
  3991. 'audio_url' => [
  3992. 'url' => $audioUrl,
  3993. ],
  3994. 'role' => 'reference_audio',
  3995. ];
  3996. // 优化提示词,增加音频相关描述
  3997. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  3998. $videoParams['prompt'] = $audioPrompt;
  3999. $videoParams['content'][0]['text'] = $audioPrompt;
  4000. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4001. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4002. }
  4003. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4004. }
  4005. // 更新分镜表的视频任务信息
  4006. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4007. 'video_task_id' => $task->id,
  4008. 'video_task_status' => '生成中',
  4009. 'generate_audio' => $generate_audio,
  4010. 'updated_at' => date('Y-m-d H:i:s')
  4011. ]);
  4012. return [
  4013. 'task_id' => $task->id,
  4014. 'status' => $task->status,
  4015. 'segment_id' => $segment_id,
  4016. 'video_duration' => $videoDuration
  4017. ];
  4018. }
  4019. public function createActVideoTask($data) {
  4020. $act_id = getProp($data, 'act_id');
  4021. $first_frame_url = getProp($data, 'first_frame_url');
  4022. $tail_frame_url = getProp($data, 'tail_frame_url');
  4023. $generate_audio = getProp($data, 'generate_audio', 1);
  4024. $video_duration = getProp($data, 'video_duration');
  4025. $video_resolution = getProp($data, 'video_resolution');
  4026. $ratio = getProp($data, 'ratio');
  4027. $products = getProp($data, 'products', []);
  4028. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4029. if (!is_array($reference_images) || !is_array($products)) {
  4030. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4031. }
  4032. if (!$act_id) {
  4033. Utils::throwError('1002:片段ID不能为空');
  4034. }
  4035. // 获取片段信息
  4036. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4037. if (!$act) {
  4038. Utils::throwError('20003:片段不存在');
  4039. }
  4040. $act = (array)$act;
  4041. $anime_id = getProp($act, 'anime_id');
  4042. $episode_id = getProp($act, 'episode_id');
  4043. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4044. $ace_mode = getProp($anime, 'ace_mode');
  4045. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4046. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4047. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4048. // 将资产中新出现的资产放到extra_products中
  4049. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles和scenes做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4050. if (!empty($products) && $episode) {
  4051. // 获取剧集中的角色和场景列表
  4052. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4053. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4054. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4055. // 构建角色名称列表
  4056. $role_names = array_column($roles, 'role');
  4057. // 构建场景名称列表
  4058. $scene_names = array_column($scenes, 'scene');
  4059. // 遍历传入的products
  4060. foreach ($products as $product) {
  4061. $product_name = getProp($product, 'product_name');
  4062. // 如果product_name不在roles和scenes中
  4063. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names)) {
  4064. // 查找是否在extra_products中存在同名的
  4065. $found = false;
  4066. foreach ($extra_products as $key => $extra_product) {
  4067. if (getProp($extra_product, 'product_name') === $product_name) {
  4068. // 有同名的则覆盖
  4069. $extra_products[$key] = $product;
  4070. $found = true;
  4071. break;
  4072. }
  4073. }
  4074. // 没有则新增
  4075. if (!$found) {
  4076. $extra_products[] = $product;
  4077. }
  4078. }
  4079. }
  4080. if ($extra_products) {
  4081. // 保存到数据库
  4082. DB::table('mp_anime_episodes')
  4083. ->where('id', $episode_id)
  4084. ->update([
  4085. 'extra_products' => json_encode($extra_products, 256),
  4086. 'updated_at' => date('Y-m-d H:i:s')
  4087. ]);
  4088. }
  4089. }
  4090. // 获取分镜内容
  4091. $actContent = getProp($act, 'act_show_content', '');
  4092. // 音效同出(默认使用)
  4093. $current_generate_audio = $generate_audio ? 1 : 0;
  4094. // 构建完整的提示词
  4095. $processResult = $this->processActContentWithProducts($actContent, $products);
  4096. $fullPrompt = $processResult['content'];
  4097. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4098. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4099. // 处理视频模型
  4100. $model = getProp($data, 'model');
  4101. if (!$model) {
  4102. $model = getProp($episode, 'video_model');
  4103. if (!$model) {
  4104. // episode表也没有,使用默认值
  4105. $model = 'zhizhen-20';
  4106. }
  4107. }
  4108. // 验证模型是否在可用模型表中
  4109. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4110. $model = 'zhizhen-20';
  4111. }
  4112. // 保存到episode表
  4113. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4114. 'video_model' => $model,
  4115. 'updated_at' => date('Y-m-d H:i:s')
  4116. ]);
  4117. // 构建视频生成参数
  4118. $videoParams = [
  4119. 'model' => $model,
  4120. 'alias_act_id' => $act_id,
  4121. 'prompt' => trim($fullPrompt),
  4122. 'video_duration' => $videoDuration,
  4123. 'video_resolution' => $video_resolution,
  4124. 'seed' => -1,
  4125. 'ratio' => $ratio,
  4126. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4127. 'draft' => false,
  4128. 'watermark' => false,
  4129. 'camera_fixed' => false,
  4130. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4131. ];
  4132. // 如果分镜有图片,作为首帧
  4133. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4134. $hasVideo = !empty(getProp($act, 'video_url'));
  4135. if ($hasImage) {
  4136. if ($first_frame_url) {
  4137. $videoParams['first_frame_url'] = $first_frame_url;
  4138. }else {
  4139. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4140. }
  4141. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4142. }
  4143. // 构建content数组
  4144. $videoParams['content'] = [
  4145. [
  4146. 'type' => 'text',
  4147. 'text' => $videoParams['prompt'],
  4148. ]
  4149. ];
  4150. // 如果有首帧图片,添加到content中
  4151. if ($hasImage) {
  4152. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4153. $videoParams['content'][] = [
  4154. 'type' => 'image_url',
  4155. 'image_url' => [
  4156. 'url' => $videoParams['first_frame_url'],
  4157. ],
  4158. 'role' => 'reference_image',
  4159. ];
  4160. if (isset($videoParams['tail_frame_url'])) {
  4161. $videoParams['content'][] = [
  4162. 'type' => 'image_url',
  4163. 'image_url' => [
  4164. 'url' => $videoParams['tail_frame_url'],
  4165. ],
  4166. 'role' => 'reference_image',
  4167. ];
  4168. }
  4169. }else {
  4170. $videoParams['content'][] = [
  4171. 'type' => 'image_url',
  4172. 'image_url' => [
  4173. 'url' => $videoParams['first_frame_url'],
  4174. ],
  4175. 'role' => 'first_frame',
  4176. ];
  4177. if (isset($videoParams['tail_frame_url'])) {
  4178. $videoParams['content'][] = [
  4179. 'type' => 'image_url',
  4180. 'image_url' => [
  4181. 'url' => $videoParams['tail_frame_url'],
  4182. ],
  4183. 'role' => 'last_frame',
  4184. ];
  4185. }
  4186. }
  4187. }
  4188. // dd($videoParams);
  4189. // 根据模型选择不同的视频生成方法
  4190. if (strpos($model, 'jimeng') !== false) {
  4191. // 即梦模型参数调整
  4192. unset($videoParams['content']); // 即梦不使用content格式
  4193. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4194. } elseif (strpos($model, 'kling') !== false) {
  4195. // Keling模型参数调整
  4196. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4197. unset($videoParams['ratio']);
  4198. unset($videoParams['content']); // Keling不使用content格式
  4199. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4200. } elseif (strpos($model, 'zhizhen') !== false) {
  4201. // 智帧20等新模型使用统一API
  4202. // 构建统一API参数
  4203. $unifiedParams = [
  4204. 'model_code' => $model,
  4205. 'alias_act_id' => $act_id,
  4206. 'prompt' => trim($fullPrompt),
  4207. 'video_duration' => $videoDuration,
  4208. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4209. 'video_ratio' => $ratio,
  4210. 'seed' => -1,
  4211. ];
  4212. // 构建parameters参数
  4213. $parameters = [
  4214. 'seconds' => $unifiedParams['video_duration'],
  4215. 'resolution' => $unifiedParams['video_resolution'],
  4216. 'ratio' => $ratio,
  4217. // 'video_mode' => 'multi_image',
  4218. // 'mode' => 'multi_image',
  4219. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4220. ];
  4221. $hasImage = false;
  4222. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4223. if ($hasImage) {
  4224. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4225. if (isset($videoParams['tail_frame_url'])) {
  4226. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4227. }
  4228. } else {
  4229. // 没有图片时,记录错误日志
  4230. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4231. 'act_id' => $act_id,
  4232. 'model' => $model
  4233. ]);
  4234. }
  4235. if ($reference_images) {
  4236. // 限制只传入9张参考图
  4237. $reference_images = array_slice($reference_images, 0, 9);
  4238. // 在处理之前先保存原始reference_images到任务参数中
  4239. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4240. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4241. $parameters['reference_images'] = $reference_images;
  4242. $parameters['video_mode'] = 'multi_image';
  4243. $parameters['mode'] = 'multi_image';
  4244. }
  4245. $unifiedParams['parameters'] = $parameters;
  4246. // 调用统一API创建任务
  4247. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4248. } else {
  4249. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4250. }
  4251. // 更新分镜表的视频任务信息
  4252. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4253. 'video_task_id' => $task->id,
  4254. 'video_task_status' => '生成中',
  4255. 'generate_audio' => $generate_audio,
  4256. 'updated_at' => date('Y-m-d H:i:s')
  4257. ]);
  4258. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4259. $episode_number = getProp($act, 'episode_number');
  4260. $act_number = getProp($act, 'act_number');
  4261. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4262. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4263. }
  4264. return [
  4265. 'task_id' => $task->id,
  4266. 'status' => $task->status,
  4267. 'act_id' => $act_id,
  4268. 'video_duration' => $videoDuration
  4269. ];
  4270. }
  4271. /**
  4272. * 根据提示词内容智能计算最优视频时长
  4273. *
  4274. * @param string $segmentContent 分镜内容
  4275. * @param string $tailFrame 尾帧描述
  4276. * @return int 视频时长(2-12秒)
  4277. */
  4278. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4279. // 合并所有文本内容
  4280. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4281. // 如果没有内容,返回默认时长
  4282. if (empty($fullText)) {
  4283. return 5;
  4284. }
  4285. // 计算文本长度(中文字符按2个字符计算)
  4286. $textLength = mb_strlen($fullText, 'UTF-8');
  4287. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4288. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4289. // 分析内容复杂度
  4290. $complexityScore = $this->analyzeContentComplexity($fullText);
  4291. // 基础时长计算(根据文本长度)
  4292. $baseDuration = 3; // 默认2秒
  4293. // if ($adjustedLength <= 20) {
  4294. // $baseDuration = 3;
  4295. // } elseif ($adjustedLength <= 40) {
  4296. // $baseDuration = 4;
  4297. // } elseif ($adjustedLength <= 60) {
  4298. // $baseDuration = 5;
  4299. // } elseif ($adjustedLength <= 80) {
  4300. // $baseDuration = 6;
  4301. // } elseif ($adjustedLength <= 100) {
  4302. // $baseDuration = 7;
  4303. // } elseif ($adjustedLength <= 120) {
  4304. // $baseDuration = 8;
  4305. // } else {
  4306. // $baseDuration = 9;
  4307. // }
  4308. // 根据内容复杂度调整时长
  4309. $finalDuration = $baseDuration + $complexityScore;
  4310. // 确保时长在2-12秒范围内
  4311. return max(4, min(12, $finalDuration));
  4312. }
  4313. /**
  4314. * 分析内容复杂度,返回时长调整值
  4315. *
  4316. * @param string $text 文本内容
  4317. * @return int 调整值(-2到+3)
  4318. */
  4319. private function analyzeContentComplexity($text) {
  4320. $score = 0;
  4321. // 动作关键词(需要更长时间展现)
  4322. $actionKeywords = [
  4323. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4324. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4325. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4326. ];
  4327. // 静态关键词(可以用较短时间)
  4328. $staticKeywords = [
  4329. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4330. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4331. ];
  4332. // 复杂场景关键词(需要更长时间)
  4333. $complexSceneKeywords = [
  4334. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4335. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4336. ];
  4337. // 情感关键词(需要适中时间表现)
  4338. $emotionKeywords = [
  4339. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4340. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4341. ];
  4342. // 检查动作关键词
  4343. foreach ($actionKeywords as $keyword) {
  4344. if (strpos($text, $keyword) !== false) {
  4345. $score += 1;
  4346. break; // 避免重复加分
  4347. }
  4348. }
  4349. // 检查静态关键词
  4350. foreach ($staticKeywords as $keyword) {
  4351. if (strpos($text, $keyword) !== false) {
  4352. $score -= 1;
  4353. break;
  4354. }
  4355. }
  4356. // 检查复杂场景关键词
  4357. foreach ($complexSceneKeywords as $keyword) {
  4358. if (strpos($text, $keyword) !== false) {
  4359. $score += 1;
  4360. break;
  4361. }
  4362. }
  4363. // 检查情感关键词
  4364. foreach ($emotionKeywords as $keyword) {
  4365. if (strpos($text, $keyword) !== false) {
  4366. $score += 1;
  4367. break;
  4368. }
  4369. }
  4370. // 检查时间相关词汇
  4371. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4372. $score += 1;
  4373. }
  4374. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4375. $score -= 1;
  4376. }
  4377. // 检查转场词汇
  4378. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4379. $score += 1;
  4380. }
  4381. // 检查环境描述(复杂环境需要更多时间)
  4382. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4383. $score += 1;
  4384. }
  4385. // 检查对话内容(对话需要更多时间)
  4386. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4387. $score += 1;
  4388. }
  4389. // 限制调整范围
  4390. return max(-1, min(4, $score));
  4391. }
  4392. /**
  4393. * 创建完整视频合成任务
  4394. *
  4395. * @param array $data
  4396. * @return array
  4397. */
  4398. public function createCompleteVideoTask($data)
  4399. {
  4400. $animeId = getProp($data, 'anime_id');
  4401. $episodeId = getProp($data, 'episode_id');
  4402. // 验证参数
  4403. if (!$animeId || !$episodeId) {
  4404. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4405. }
  4406. // 检查是否已存在处理中的任务
  4407. $existingTask = DB::table('mp_complete_video_tasks')
  4408. ->where('anime_id', $animeId)
  4409. ->where('episode_id', $episodeId)
  4410. ->whereIn('generate_status', ['执行中'])
  4411. ->first();
  4412. if ($existingTask) {
  4413. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4414. }
  4415. // 获取全能模式状态
  4416. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4417. if ((int)$ace_mode === 1) {
  4418. // 获取所有片段的配音视频,按 act_number 排序
  4419. $segments = DB::table('mp_episode_segments')
  4420. ->where('anime_id', $animeId)
  4421. ->where('episode_id', $episodeId)
  4422. ->orderBy('segment_number')
  4423. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4424. ->get();
  4425. // 检查是否所有片段都有视频
  4426. $missingVideos = $segments->filter(function($segment) {
  4427. return empty($segment->video_url);
  4428. });
  4429. if ($missingVideos->isNotEmpty()) {
  4430. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4431. }
  4432. }else {
  4433. // 获取所有分镜的配音视频,按 segment_number 排序
  4434. $segments = DB::table('mp_episode_segments')
  4435. ->where('anime_id', $animeId)
  4436. ->where('episode_id', $episodeId)
  4437. ->orderBy('segment_number')
  4438. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4439. ->get();
  4440. // 检查是否所有分镜都有配音和视频
  4441. $missingVideos = $segments->filter(function($segment) {
  4442. return empty($segment->audio_url) || empty($segment->video_url);
  4443. });
  4444. if ($missingVideos->isNotEmpty()) {
  4445. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4446. }
  4447. }
  4448. if ($segments->isEmpty()) {
  4449. Utils::throwError('20003:未找到该剧集的分镜数据');
  4450. }
  4451. // 获取当前完整视频url
  4452. $completeVideoUrl = DB::table('mp_anime_episodes')
  4453. ->where('anime_id', $animeId)
  4454. ->where('id', $episodeId)
  4455. ->value('complete_video_url');
  4456. // 构建 generate_json
  4457. $generateJson = [];
  4458. $sequence = 1;
  4459. foreach ($segments as $segment) {
  4460. if ((int)$ace_mode === 1) {
  4461. $generateJson[] = [
  4462. 'sequence' => $sequence++,
  4463. 'video_url' => $segment->video_url,
  4464. 'video_time_point_start' => $segment->video_time_point_start,
  4465. 'video_time_point_end' => $segment->video_time_point_end
  4466. ];
  4467. }else {
  4468. $generateJson[] = [
  4469. 'sequence' => $sequence++,
  4470. 'video_url' => $segment->video_url,
  4471. 'audio_url' => $segment->audio_url,
  4472. 'video_time_point_start' => $segment->video_time_point_start,
  4473. 'video_time_point_end' => $segment->video_time_point_end
  4474. ];
  4475. }
  4476. }
  4477. // 创建任务
  4478. $now = date('Y-m-d H:i:s');
  4479. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4480. 'anime_id' => $animeId,
  4481. 'episode_id' => $episodeId,
  4482. 'generate_json' => json_encode($generateJson, 256),
  4483. 'generate_status' => '执行中',
  4484. 'complete_video_url' => '',
  4485. 'created_at' => $now,
  4486. 'updated_at' => $now
  4487. ]);
  4488. if (!$taskId) {
  4489. Utils::throwError('20003:创建任务失败');
  4490. }
  4491. // 更新剧集表的任务ID和状态
  4492. $boolen = DB::table('mp_anime_episodes')
  4493. ->where('anime_id', $animeId)
  4494. ->where('id', $episodeId)
  4495. ->update([
  4496. 'complete_video_task_id' => $taskId,
  4497. 'complete_video_task_status' => '执行中',
  4498. 'updated_at' => $now
  4499. ]);
  4500. if (!$boolen) {
  4501. Utils::throwError('20003:更新剧集表失败');
  4502. }
  4503. dLog('anime')->info('创建完整视频合成任务', [
  4504. 'task_id' => $taskId,
  4505. 'anime_id' => $animeId,
  4506. 'episode_id' => $episodeId,
  4507. 'segment_count' => count($generateJson)
  4508. ]);
  4509. // 请求远程服务器执行生成
  4510. $client = new Client(['timeout' => 600, 'verify' => false]);
  4511. try {
  4512. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4513. $response = $result->getBody()->getContents();
  4514. $response_arr = json_decode($response, true);
  4515. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4516. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4517. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4518. // // 更新任务状态为失败
  4519. // DB::table('mp_complete_video_tasks')
  4520. // ->where('id', $taskId)
  4521. // ->update([
  4522. // 'generate_status' => '执行失败',
  4523. // 'error_message' => $error_msg,
  4524. // 'updated_at' => date('Y-m-d H:i:s')
  4525. // ]);
  4526. // // 同步更新剧集表状态
  4527. // DB::table('mp_anime_episodes')
  4528. // ->where('complete_video_task_id', $taskId)
  4529. // ->update([
  4530. // 'complete_video_task_status' => '执行失败',
  4531. // 'updated_at' => date('Y-m-d H:i:s')
  4532. // ]);
  4533. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4534. }
  4535. } catch (\Exception $e) {
  4536. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4537. // 更新任务状态为失败
  4538. DB::table('mp_complete_video_tasks')
  4539. ->where('id', $taskId)
  4540. ->update([
  4541. 'generate_status' => '执行失败',
  4542. 'error_message' => $e->getMessage(),
  4543. 'updated_at' => date('Y-m-d H:i:s')
  4544. ]);
  4545. // 同步更新剧集表状态
  4546. DB::table('mp_anime_episodes')
  4547. ->where('complete_video_task_id', $taskId)
  4548. ->update([
  4549. 'complete_video_task_status' => '执行失败',
  4550. 'updated_at' => date('Y-m-d H:i:s')
  4551. ]);
  4552. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4553. }
  4554. // 开始轮询任务状态
  4555. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4556. $pollInterval = 5; // 每5秒轮询一次
  4557. $attempt = 0;
  4558. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4559. while ($attempt < $maxAttempts) {
  4560. sleep($pollInterval);
  4561. $attempt++;
  4562. // 查询任务状态
  4563. $task = DB::table('mp_complete_video_tasks')
  4564. ->where('id', $taskId)
  4565. ->first();
  4566. if (!$task) {
  4567. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4568. Utils::throwError('20003:任务不存在');
  4569. }
  4570. dLog('anime')->info('轮询任务状态', [
  4571. 'task_id' => $taskId,
  4572. 'attempt' => $attempt,
  4573. 'status' => $task->generate_status
  4574. ]);
  4575. // 检查任务是否完成
  4576. if ($task->generate_status === '执行成功') {
  4577. // 同步更新剧集表状态
  4578. $boolen3 = DB::table('mp_anime_episodes')
  4579. ->where('anime_id', $animeId)
  4580. ->where('id', $episodeId)
  4581. ->update([
  4582. 'complete_video_url' => $task->complete_video_url,
  4583. 'complete_video_task_status' => '执行成功',
  4584. 'updated_at' => date('Y-m-d H:i:s')
  4585. ]);
  4586. dLog('anime')->info('视频合成任务完成', [
  4587. 'task_id' => $taskId,
  4588. 'video_url' => $task->complete_video_url,
  4589. 'attempts' => $attempt
  4590. ]);
  4591. // 如果更新成功则远程删除之前的文件
  4592. if ($boolen3 && $completeVideoUrl) {
  4593. $encode_url = urlencode($completeVideoUrl);
  4594. $client = new Client(['timeout' => 300, 'verify' => false]);
  4595. // 根据ID通过API通知合成音频
  4596. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4597. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4598. $response = $result->getBody()->getContents();
  4599. $response_arr = json_decode($response, true);
  4600. Log::info('火山删除音频返回: '.$response);
  4601. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4602. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4603. Log::info('火山删除音频失败: '.$error_msg);
  4604. // Utils::throwError('20003:火山删除音频失败');
  4605. }
  4606. }
  4607. return [
  4608. 'task_id' => $taskId,
  4609. 'anime_id' => $animeId,
  4610. 'episode_id' => $episodeId,
  4611. 'segment_count' => count($generateJson),
  4612. 'generate_status' => '执行成功',
  4613. 'complete_video_url' => $task->complete_video_url,
  4614. ];
  4615. }
  4616. // 检查任务是否失败
  4617. if ($task->generate_status === '执行失败') {
  4618. // 同步更新剧集表状态
  4619. DB::table('mp_anime_episodes')
  4620. ->where('anime_id', $animeId)
  4621. ->where('id', $episodeId)
  4622. ->update([
  4623. 'complete_video_task_status' => '执行失败',
  4624. 'updated_at' => date('Y-m-d H:i:s')
  4625. ]);
  4626. $errorMessage = $task->error_message ?? '未知错误';
  4627. dLog('anime')->error('视频合成任务失败', [
  4628. 'task_id' => $taskId,
  4629. 'error' => $errorMessage,
  4630. 'attempts' => $attempt
  4631. ]);
  4632. return [
  4633. 'task_id' => $taskId,
  4634. 'anime_id' => $animeId,
  4635. 'episode_id' => $episodeId,
  4636. 'segment_count' => count($generateJson),
  4637. 'generate_status' => '执行失败',
  4638. 'error_message' => $errorMessage
  4639. ];
  4640. }
  4641. }
  4642. // 超时处理
  4643. dLog('anime')->warning('视频合成任务超时', [
  4644. 'task_id' => $taskId,
  4645. 'max_attempts' => $maxAttempts,
  4646. 'timeout_seconds' => $maxAttempts * $pollInterval
  4647. ]);
  4648. // 更新任务状态为超时
  4649. DB::table('mp_complete_video_tasks')
  4650. ->where('id', $taskId)
  4651. ->update([
  4652. 'generate_status' => '超时',
  4653. 'error_message' => '任务执行超时(5分钟)',
  4654. 'updated_at' => date('Y-m-d H:i:s')
  4655. ]);
  4656. return [
  4657. 'task_id' => $taskId,
  4658. 'anime_id' => $animeId,
  4659. 'episode_id' => $episodeId,
  4660. 'segment_count' => count($generateJson),
  4661. 'generate_status' => '超时',
  4662. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4663. ];
  4664. }
  4665. public function generateImg($data) {
  4666. $prompt = getProp($data, 'prompt');
  4667. $episode_id = getProp($data, 'episode_id');
  4668. $ref_img_urls = getProp($data, 'ref_img_urls');
  4669. $ratio = getProp($data, 'ratio', '9:16');
  4670. $resolution = getProp($data, 'resolution', '2k');
  4671. // 定义分辨率和宽高比对应的尺寸映射表
  4672. $sizeMap = [
  4673. '2k' => [
  4674. '1:1' => ['width' => 2048, 'height' => 2048],
  4675. '4:3' => ['width' => 2304, 'height' => 1728],
  4676. '3:4' => ['width' => 1728, 'height' => 2304],
  4677. '16:9' => ['width' => 2848, 'height' => 1600],
  4678. '9:16' => ['width' => 1600, 'height' => 2848],
  4679. '3:2' => ['width' => 2496, 'height' => 1664],
  4680. '2:3' => ['width' => 1664, 'height' => 2496],
  4681. '21:9' => ['width' => 3136, 'height' => 1344],
  4682. ],
  4683. '3k' => [
  4684. '1:1' => ['width' => 3072, 'height' => 3072],
  4685. '4:3' => ['width' => 3456, 'height' => 2592],
  4686. '3:4' => ['width' => 2592, 'height' => 3456],
  4687. '16:9' => ['width' => 4096, 'height' => 2304],
  4688. '9:16' => ['width' => 2304, 'height' => 4096],
  4689. '2:3' => ['width' => 2496, 'height' => 3744],
  4690. '3:2' => ['width' => 3744, 'height' => 2496],
  4691. '21:9' => ['width' => 4704, 'height' => 2016],
  4692. ],
  4693. '4k' => [
  4694. '1:1' => ['width' => 4096, 'height' => 4096],
  4695. '3:4' => ['width' => 3520, 'height' => 4704],
  4696. '4:3' => ['width' => 4704, 'height' => 3520],
  4697. '16:9' => ['width' => 5504, 'height' => 3040],
  4698. '9:16' => ['width' => 3040, 'height' => 5504],
  4699. '2:3' => ['width' => 3328, 'height' => 4992],
  4700. '3:2' => ['width' => 4992, 'height' => 3328],
  4701. '21:9' => ['width' => 6240, 'height' => 2656],
  4702. ],
  4703. ];
  4704. // 参数验证
  4705. $resolution = strtolower($resolution);
  4706. if (!isset($sizeMap[$resolution])) {
  4707. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  4708. }
  4709. if (!isset($sizeMap[$resolution][$ratio])) {
  4710. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  4711. }
  4712. // 根据 ratio 和 resolution 确定宽高
  4713. $width = $sizeMap[$resolution][$ratio]['width'];
  4714. $height = $sizeMap[$resolution][$ratio]['height'];
  4715. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  4716. if (is_json($ref_img_urls)) {
  4717. $ref_img_urls = json_decode($ref_img_urls, true);
  4718. }else {
  4719. $ref_img_urls = explode(',', $ref_img_urls);
  4720. }
  4721. }
  4722. // 处理图片模型
  4723. $model = getProp($data, 'model');
  4724. if (!$model) {
  4725. // 用户没有输入,从episode表获取
  4726. if ($episode_id) {
  4727. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4728. $model = getProp($episode, 'image_model');
  4729. }
  4730. if (!$model) {
  4731. // episode表也没有,使用默认值
  4732. $model = 'doubao-seedream-5-0-lite-260128';
  4733. }
  4734. }
  4735. // 验证模型是否在可用模型表中
  4736. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4737. // $model = 'doubao-seedream-5-0-lite-260128';
  4738. Utils::throwError('20003:该模型已不可用,请更换!');
  4739. }
  4740. // 保存到episode表
  4741. if ($episode_id) {
  4742. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4743. 'image_model' => $model,
  4744. 'updated_at' => date('Y-m-d H:i:s')
  4745. ]);
  4746. }
  4747. // 参数验证
  4748. if (!$prompt) Utils::throwError('20003:请提供提示词');
  4749. try {
  4750. // 创建图片生成任务
  4751. $params = [
  4752. 'prompt' => $prompt,
  4753. 'model' => $model,
  4754. 'ref_img_urls' => '',
  4755. 'width' => $width,
  4756. 'height' => $height
  4757. ];
  4758. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  4759. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4760. $task_id = $task->id;
  4761. if (!$task_id) {
  4762. Utils::throwError('20003:创建图片生成任务失败');
  4763. }
  4764. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  4765. $model = getProp($task, 'model');
  4766. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  4767. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  4768. $isSyncModel = $isVolcModel || $isGptModel;
  4769. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  4770. $start_time = time();
  4771. $timeout = 300; // 5分钟
  4772. $img_url = '';
  4773. while (time() - $start_time < $timeout) {
  4774. sleep(3);
  4775. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  4776. if ($isSyncModel) {
  4777. // 刷新任务状态
  4778. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4779. if ($task->status === 'success' && $task->result_url) {
  4780. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  4781. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  4782. break;
  4783. } elseif ($task->status === 'failed') {
  4784. $errorMsg = mapErrorMessage($task->error_message ?? '');
  4785. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4786. }
  4787. // // 如果还在处理中,提示用户稍后查看
  4788. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  4789. }else {
  4790. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4791. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  4792. if ($statusInfo['status'] === 'success') {
  4793. $task->updateStatus('success', [
  4794. 'result_url' => $statusInfo['result_url'],
  4795. 'result_json' => $statusInfo['result_json'] ?? []
  4796. ]);
  4797. $img_url = $statusInfo['result_url'][0];
  4798. break;
  4799. } elseif ($statusInfo['status'] === 'failed') {
  4800. $task->updateStatus('failed', [
  4801. 'error_message' => $statusInfo['error_message'],
  4802. 'result_json' => $statusInfo['result_json'] ?? []
  4803. ]);
  4804. dLog('anime')->error('图片生成失败,', [
  4805. 'error' => $statusInfo['error_message'] ?? '未知错误'
  4806. ]);
  4807. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  4808. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4809. }
  4810. }
  4811. }
  4812. if (empty($img_url)) {
  4813. Utils::throwError('20003:图片生成超时,请稍后重试');
  4814. }
  4815. return $img_url;
  4816. } catch (\Exception $e) {
  4817. dLog('anime')->error('更新角色或场景失败', [
  4818. 'error' => $e->getMessage()
  4819. ]);
  4820. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  4821. Utils::throwError('20003:' . $e->getMessage());
  4822. }
  4823. }
  4824. /**
  4825. * 使用文生文模型解析分镜内容
  4826. */
  4827. private function parseSegmentContentWithAI($segment_content) {
  4828. try {
  4829. // 使用DeepSeek服务的公开方法解析分镜内容
  4830. return $this->DeepSeekService->parseSegmentContent($segment_content);
  4831. } catch (\Exception $e) {
  4832. // 如果AI解析失败,记录日志并返回原内容
  4833. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  4834. return $segment_content;
  4835. }
  4836. }
  4837. /**
  4838. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  4839. *
  4840. * @param int $episode_id 分集ID
  4841. * @param int $anime_id 动漫ID
  4842. * @param array $roles 分集角色数组(引用传递)
  4843. * @param array $scenes 分集场景数组(引用传递)
  4844. * @param array $episode 分集数据
  4845. */
  4846. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  4847. // 获取全局动漫的角色和场景数据
  4848. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4849. if (!$anime) return;
  4850. $art_style_type = getProp($anime, 'art_style_type');
  4851. $character_prefix = '';
  4852. $scene_prefix = '';
  4853. if ($art_style_type) {
  4854. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  4855. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  4856. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  4857. }
  4858. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  4859. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  4860. $roles_updated = false;
  4861. $scenes_updated = false;
  4862. // 处理角色
  4863. foreach ($roles as &$role) {
  4864. $role_name = getProp($role, 'role');
  4865. $role_description = getProp($role, 'description');
  4866. $role_pic_prompt = getProp($role, 'pic_prompt');
  4867. $role_url = getProp($role, 'url');
  4868. $role_task_id = getProp($role, 'task_id');
  4869. // 如果已有URL或已有任务ID,跳过
  4870. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  4871. continue;
  4872. }
  4873. $url_inherited = false;
  4874. // 尝试从全局数据中继承
  4875. foreach ($global_roles as $global_role) {
  4876. $global_role_name = getProp($global_role, 'role');
  4877. $global_role_description = getProp($global_role, 'description');
  4878. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  4879. $global_role_url = getProp($global_role, 'url');
  4880. $global_role_task_id = getProp($global_role, 'task_id');
  4881. $global_role_task_status = getProp($global_role, 'task_status');
  4882. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  4883. if ($role_name === $global_role_name
  4884. && $role_description === $global_role_description
  4885. && $role_pic_prompt === $global_role_pic_prompt
  4886. && !empty($global_role_url)) {
  4887. // 继承 task_id、task_status 和 url
  4888. $role['task_id'] = $global_role_task_id;
  4889. $role['task_status'] = $global_role_task_status;
  4890. $role['url'] = $global_role_url;
  4891. $roles_updated = true;
  4892. $url_inherited = true;
  4893. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  4894. break;
  4895. }
  4896. }
  4897. // 如果无法继承且没有任务ID,创建新任务
  4898. if (!$url_inherited && empty($role_task_id)) {
  4899. try {
  4900. $art_style = getProp($episode, 'art_style');
  4901. // 优先使用 pic_prompt,如果没有则使用 description
  4902. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  4903. // if ($art_style) {
  4904. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4905. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4906. // }
  4907. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  4908. $params = [
  4909. 'prompt' => $description,
  4910. 'ref_img_urls' => []
  4911. ];
  4912. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4913. $task_id = $task->id;
  4914. if ($task_id) {
  4915. $role['task_id'] = $task_id;
  4916. $role['task_status'] = 'processing';
  4917. $roles_updated = true;
  4918. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  4919. }
  4920. } catch (\Exception $e) {
  4921. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  4922. }
  4923. }
  4924. }
  4925. // 处理场景
  4926. foreach ($scenes as &$scene) {
  4927. $scene_name = getProp($scene, 'scene');
  4928. $scene_description = getProp($scene, 'description');
  4929. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  4930. $scene_url = getProp($scene, 'url');
  4931. $scene_task_id = getProp($scene, 'task_id');
  4932. // 如果已有URL或已有任务ID,跳过
  4933. if (!empty($scene_url) || !empty($scene_task_id)) {
  4934. continue;
  4935. }
  4936. $url_inherited = false;
  4937. // 尝试从全局数据中继承
  4938. foreach ($global_scenes as $global_scene) {
  4939. $global_scene_name = getProp($global_scene, 'scene');
  4940. $global_scene_description = getProp($global_scene, 'description');
  4941. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  4942. $global_scene_url = getProp($global_scene, 'url');
  4943. $global_scene_task_id = getProp($global_scene, 'task_id');
  4944. $global_scene_task_status = getProp($global_scene, 'task_status');
  4945. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  4946. if ($scene_name === $global_scene_name
  4947. && $scene_description === $global_scene_description
  4948. && $scene_pic_prompt === $global_scene_pic_prompt
  4949. && !empty($global_scene_url)) {
  4950. // 继承 task_id、task_status 和 url
  4951. $scene['task_id'] = $global_scene_task_id;
  4952. $scene['task_status'] = $global_scene_task_status;
  4953. $scene['url'] = $global_scene_url;
  4954. $scenes_updated = true;
  4955. $url_inherited = true;
  4956. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  4957. break;
  4958. }
  4959. }
  4960. // 如果无法继承且没有任务ID,创建新任务
  4961. if (!$url_inherited && empty($scene_task_id)) {
  4962. try {
  4963. $art_style = getProp($episode, 'art_style');
  4964. // 优先使用 pic_prompt,如果没有则使用 description
  4965. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  4966. // if ($art_style) {
  4967. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  4968. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  4969. // }
  4970. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  4971. $params = [
  4972. 'prompt' => $description,
  4973. 'ref_img_urls' => []
  4974. ];
  4975. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4976. $task_id = $task->id;
  4977. if ($task_id) {
  4978. $scene['task_id'] = $task_id;
  4979. $scene['task_status'] = 'processing';
  4980. $scenes_updated = true;
  4981. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  4982. }
  4983. } catch (\Exception $e) {
  4984. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  4985. }
  4986. }
  4987. }
  4988. // 如果有更新,保存到数据库
  4989. if ($roles_updated || $scenes_updated) {
  4990. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  4991. if ($roles_updated) {
  4992. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  4993. }
  4994. if ($scenes_updated) {
  4995. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  4996. }
  4997. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  4998. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  4999. }
  5000. }
  5001. /**
  5002. * 根据图片URL使用AI反推图片提示词
  5003. *
  5004. * @param string $img_url 图片URL
  5005. * @return string 反推的提示词
  5006. */
  5007. private function generateImagePromptFromUrl($img_url) {
  5008. try {
  5009. // 获取默认模型
  5010. $model = 'doubao-seed-2-0-mini-260215';
  5011. // 构建messages参数
  5012. $messages = [
  5013. [
  5014. 'role' => 'user',
  5015. 'content' => [
  5016. [
  5017. 'type' => 'text',
  5018. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5019. ],
  5020. [
  5021. 'type' => 'image_url',
  5022. 'image_url' => [
  5023. 'url' => $img_url
  5024. ]
  5025. ]
  5026. ]
  5027. ]
  5028. ];
  5029. // 构建请求参数
  5030. $params = [
  5031. 'model' => $model,
  5032. 'messages' => $messages,
  5033. 'stream' => false,
  5034. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5035. ];
  5036. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5037. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5038. // 返回生成的内容
  5039. return getProp($result, 'fullContent', '图片描述生成失败');
  5040. } catch (\Exception $e) {
  5041. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5042. 'img_url' => $img_url
  5043. ]);
  5044. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5045. 'error' => $e->getMessage(),
  5046. 'img_url' => $img_url
  5047. ]);
  5048. return '图片描述生成失败: ' . $e->getMessage();
  5049. }
  5050. }
  5051. /**
  5052. * 音频试听接口
  5053. * 创建音频任务并轮询获取结果
  5054. *
  5055. * @param array $data 参数数组
  5056. * @return array 返回音频URL或错误信息
  5057. */
  5058. public function previewAudio($data) {
  5059. $dialogue = getProp($data, 'dialogue');
  5060. // 必填参数验证
  5061. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5062. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5063. $voice_type = getProp($data, 'voice_type');
  5064. $voice_name = getProp($data, 'voice_name');
  5065. $voice_actor = getProp($data, 'voice_actor');
  5066. $emotion_type = getProp($data, 'emotion_type');
  5067. $gender = getProp($data, 'gender', 0);
  5068. $emotion = getProp($data, 'emotion');
  5069. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5070. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5071. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5072. $pitch = getProp($data, 'pitch', 0);
  5073. try {
  5074. $now = date('Y-m-d H:i:s');
  5075. // 构建生成参数
  5076. $generate_json = json_encode([
  5077. 'text' => $dialogue,
  5078. 'role' => $voice_actor,
  5079. 'voice_type' => $voice_type,
  5080. 'voice_name' => $voice_name,
  5081. 'emotion' => $emotion,
  5082. 'emotion_type' => $emotion_type,
  5083. 'gender' => $gender,
  5084. 'speed_ratio' => $speed_ratio,
  5085. 'loudness_ratio' => $loudness_ratio,
  5086. 'emotion_scale' => $emotion_scale,
  5087. 'pitch' => $pitch,
  5088. ], 256);
  5089. // 请求远程服务器执行生成
  5090. $client = new Client(['timeout' => 600, 'verify' => false]);
  5091. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5092. $response = $result->getBody()->getContents();
  5093. $response_arr = json_decode($response, true);
  5094. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5095. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5096. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5097. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5098. }
  5099. $arr = $response_arr['data'];
  5100. $subtitle_info = $arr['subtitle_info'];
  5101. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5102. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5103. return [
  5104. 'audio_url' => $arr['url'],
  5105. 'subtitle_info' => $subtitle_info,
  5106. 'audio_duration' => round($audio_duration, 2)
  5107. ];
  5108. } catch (\Exception $e) {
  5109. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5110. Utils::throwError('20003:' . $e->getMessage());
  5111. }
  5112. }
  5113. /**
  5114. * 获取角色库列表(支持文件夹递归查询)
  5115. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5116. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5117. */
  5118. public function globalProducts($data) {
  5119. $uid = Site::getUid();
  5120. $cpid = Site::getCpid();
  5121. $role = Site::getRole();
  5122. $id = getProp($data, 'id', 0);
  5123. $parent_id = getProp($data, 'parent_id', 0);
  5124. $product_name = getProp($data, 'product_name');
  5125. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5126. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5127. if (!$product) {
  5128. Utils::throwError('20003:请选择产品类型');
  5129. }
  5130. // 根据角色和is_public参数确定查询范围
  5131. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5132. // user角色:根据is_public参数筛选
  5133. $query_user_ids = [];
  5134. if ($role === 'admin') {
  5135. // admin获取所有个人库和公共库
  5136. $query_user_ids = [$uid, 0];
  5137. } else {
  5138. // user角色根据is_public参数筛选
  5139. if ($is_public == 2) {
  5140. // 个人库+公共库
  5141. $query_user_ids = [$uid, 0];
  5142. } elseif ($is_public == 0) {
  5143. // 仅个人库
  5144. $query_user_ids = [$uid];
  5145. } elseif ($is_public == 1) {
  5146. // 仅公共库
  5147. $query_user_ids = [0];
  5148. }
  5149. }
  5150. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5151. if ($id || $product_name) {
  5152. $query = DB::table('mp_products')
  5153. ->where('cpid', $cpid)
  5154. ->whereIn('user_id', $query_user_ids)
  5155. ->where('is_deleted', 0);
  5156. // 如果指定了 id,按 id 精确查询
  5157. if ($id) {
  5158. $query->where('id', $id);
  5159. }
  5160. // 如果指定了 product_name,按名称模糊查询
  5161. if ($product_name) {
  5162. $query->where('product_name', 'like', "%{$product_name}%");
  5163. }
  5164. // 如果指定了 product,添加筛选条件
  5165. if ($product) {
  5166. $query->where('product', $product);
  5167. }
  5168. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5169. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5170. ->get()
  5171. ->map(function($value) {
  5172. $value = (array)$value;
  5173. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5174. $value['type'] = (int)$value['type'];
  5175. $value['parent_id'] = (int)$value['parent_id'];
  5176. $value['level'] = (int)$value['level'];
  5177. $value['product'] = (int)($value['product'] ?? 1);
  5178. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5179. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5180. unset($value['user_id']);
  5181. return $value;
  5182. })
  5183. ->toArray();
  5184. return $result;
  5185. }
  5186. // 递归获取所有子目录和角色
  5187. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5188. }
  5189. /**
  5190. * 递归获取指定目录下的所有子目录和角色
  5191. * @param int $cpid 公司ID
  5192. * @param int $parent_id 父目录ID
  5193. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5194. * @param array $query_user_ids 用户ID数组(支持多个)
  5195. * @param int $current_uid 当前用户ID(用于排序)
  5196. * @return array
  5197. */
  5198. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5199. // 查询当前层级的所有项(文件夹和角色)
  5200. $query = DB::table('mp_products')
  5201. ->where('cpid', $cpid)
  5202. ->where('is_deleted', 0)
  5203. ->where('parent_id', $parent_id);
  5204. // 添加用户ID验证(支持多个user_id)
  5205. if (!empty($query_user_ids)) {
  5206. $query->whereIn('user_id', $query_user_ids);
  5207. }
  5208. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5209. if ($product) {
  5210. $query->where('product', $product);
  5211. }
  5212. // 排序规则:
  5213. // 1. 文件夹在前(type DESC)
  5214. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5215. // 3. 其他排序规则
  5216. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5217. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5218. ->get();
  5219. $result = [];
  5220. foreach ($items as $item) {
  5221. $itemArray = [
  5222. 'id' => $item->id,
  5223. 'type' => (int)$item->type,
  5224. 'parent_id' => (int)$item->parent_id,
  5225. 'level' => (int)$item->level,
  5226. 'product_name' => $item->product_name,
  5227. 'url' => $item->url,
  5228. 'pic_prompt' => $item->pic_prompt ?? '',
  5229. 'three_view_image_url' => $item->three_view_image_url,
  5230. 'product' => (int)($item->product ?? 1),
  5231. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5232. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5233. ];
  5234. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5235. // 如果是文件夹,递归获取其子项
  5236. if ($item->type == 2) {
  5237. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5238. if (!empty($children)) {
  5239. $itemArray['children'] = $children;
  5240. }
  5241. }
  5242. $result[] = $itemArray;
  5243. }
  5244. return $result;
  5245. }
  5246. /**
  5247. * 创建文件夹
  5248. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5249. * @return int 返回新建文件夹ID
  5250. */
  5251. public function createFolder($data) {
  5252. $uid = Site::getUid();
  5253. $cpid = Site::getCpid();
  5254. $role = Site::getRole();
  5255. $parent_id = getProp($data, 'parent_id', 0);
  5256. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5257. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5258. // 如果是公共库操作,需要admin权限
  5259. if ($is_public && $role !== 'admin') {
  5260. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5261. }
  5262. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5263. $store_uid = $is_public ? 0 : $uid;
  5264. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5265. $product = getProp($data, 'product');
  5266. if (!in_array($product, [1, 2, 3])) {
  5267. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5268. }
  5269. // 验证父文件夹
  5270. $parent_level = 0;
  5271. if ($parent_id > 0) {
  5272. $parent = DB::table('mp_products')
  5273. ->where('id', $parent_id)
  5274. ->where('cpid', $cpid)
  5275. ->where('user_id', $store_uid)
  5276. ->where('type', 2)
  5277. ->where('is_deleted', 0)
  5278. ->first();
  5279. if (!$parent) {
  5280. Utils::throwError('20003:父文件夹不存在');
  5281. }
  5282. // 检查父文件夹的 product 类型是否一致
  5283. if ($parent->product != $product) {
  5284. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5285. }
  5286. $parent_level = $parent->level;
  5287. // 检查层级限制(最多3层)
  5288. if ($parent_level >= 3) {
  5289. Utils::throwError('20003:文件夹层级不能超过3层');
  5290. }
  5291. }
  5292. // 检查当前目录下是否已存在空白文件夹
  5293. $empty_folder_exists = DB::table('mp_products')
  5294. ->where('parent_id', $parent_id)
  5295. ->where('cpid', $cpid)
  5296. ->where('user_id', $store_uid)
  5297. ->where('type', 2)
  5298. ->where('product', $product)
  5299. ->where('product_name', '新建文件夹')
  5300. ->where('is_deleted', 0)
  5301. ->exists();
  5302. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5303. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5304. }
  5305. // 创建文件夹
  5306. $folder_id = DB::table('mp_products')->insertGetId([
  5307. 'user_id' => $store_uid,
  5308. 'cpid' => $cpid,
  5309. 'type' => 2,
  5310. 'parent_id' => $parent_id,
  5311. 'level' => $parent_level + 1,
  5312. 'product_name' => $folder_name,
  5313. 'product' => $product,
  5314. 'sort_order' => time(), // 使用时间戳作为排序权重
  5315. 'is_deleted' => 0,
  5316. 'created_at' => date('Y-m-d H:i:s'),
  5317. 'updated_at' => date('Y-m-d H:i:s')
  5318. ]);
  5319. return [
  5320. 'id' => $folder_id,
  5321. 'type' => 2,
  5322. 'parent_id' => $parent_id,
  5323. 'level' => $parent_level + 1,
  5324. 'product_name' => $folder_name,
  5325. 'product' => $product,
  5326. ];
  5327. }
  5328. /**
  5329. * 重命名文件夹或角色
  5330. * @param array $data 包含 id、product_name(新名称)
  5331. * @return bool
  5332. */
  5333. public function renameFolder($data) {
  5334. $uid = Site::getUid();
  5335. $cpid = Site::getCpid();
  5336. $role = Site::getRole();
  5337. $id = getProp($data, 'id');
  5338. $new_name = getProp($data, 'product_name');
  5339. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5340. if (!$id || !$new_name) {
  5341. Utils::throwError('20003:参数不完整');
  5342. }
  5343. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5344. $query_uid = $is_public ? 0 : $uid;
  5345. // 如果是公共库操作,需要admin权限
  5346. if ($is_public && $role !== 'admin') {
  5347. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5348. }
  5349. // 检查是否存在
  5350. $item = DB::table('mp_products')
  5351. ->where('id', $id)
  5352. ->where('cpid', $cpid)
  5353. ->where('user_id', $query_uid)
  5354. ->where('is_deleted', 0)
  5355. ->first();
  5356. if (!$item) {
  5357. Utils::throwError('20003:项目不存在');
  5358. }
  5359. return DB::table('mp_products')
  5360. ->where('id', $id)
  5361. ->where('cpid', $cpid)
  5362. ->where('user_id', $query_uid)
  5363. ->update([
  5364. 'product_name' => $new_name,
  5365. 'updated_at' => date('Y-m-d H:i:s')
  5366. ]);
  5367. }
  5368. /**
  5369. * 移动角色或文件夹到指定文件夹
  5370. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5371. * @return bool
  5372. */
  5373. public function moveProductOrFolder($data) {
  5374. $uid = Site::getUid();
  5375. $cpid = Site::getCpid();
  5376. $role = Site::getRole();
  5377. $id = getProp($data, 'id');
  5378. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5379. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5380. if (!$id) {
  5381. Utils::throwError('20003:请选择要移动的项目');
  5382. }
  5383. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5384. $query_uid = $is_public ? 0 : $uid;
  5385. // 如果是公共库操作,需要admin权限
  5386. if ($is_public && $role !== 'admin') {
  5387. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5388. }
  5389. // 检查要移动的项目
  5390. $item = DB::table('mp_products')
  5391. ->where('id', $id)
  5392. ->where('cpid', $cpid)
  5393. ->where('user_id', $query_uid)
  5394. ->where('is_deleted', 0)
  5395. ->first();
  5396. if (!$item) {
  5397. Utils::throwError('20003:项目不存在');
  5398. }
  5399. // 验证目标文件夹
  5400. $target_level = 0;
  5401. $target_product = $item->product; // 默认使用当前项目的 product
  5402. if ($target_parent_id > 0) {
  5403. $target_parent = DB::table('mp_products')
  5404. ->where('id', $target_parent_id)
  5405. ->where('cpid', $cpid)
  5406. ->where('user_id', $query_uid)
  5407. ->where('type', 2)
  5408. ->where('is_deleted', 0)
  5409. ->first();
  5410. if (!$target_parent) {
  5411. Utils::throwError('20003:目标文件夹不存在');
  5412. }
  5413. // 检查 product 类型是否一致
  5414. if ($target_parent->product != $item->product) {
  5415. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5416. }
  5417. $target_level = $target_parent->level;
  5418. $target_product = $target_parent->product;
  5419. // 如果移动的是文件夹,需要检查层级
  5420. if ($item->type == 2) {
  5421. // 计算移动后的最大层级
  5422. $max_child_level = $this->getMaxChildLevel($id);
  5423. $depth = $max_child_level - $item->level;
  5424. if ($target_level + 1 + $depth > 3) {
  5425. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5426. }
  5427. // 不能移动到自己或自己的子文件夹下
  5428. if ($this->isDescendant($target_parent_id, $id)) {
  5429. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5430. }
  5431. }
  5432. }
  5433. // 更新父文件夹和层级
  5434. $new_level = $target_level + 1;
  5435. DB::table('mp_products')
  5436. ->where('id', $id)
  5437. ->update([
  5438. 'parent_id' => $target_parent_id,
  5439. 'level' => $new_level,
  5440. 'updated_at' => date('Y-m-d H:i:s')
  5441. ]);
  5442. // 如果是文件夹,需要递归更新所有子项的层级
  5443. if ($item->type == 2) {
  5444. $this->updateChildrenLevel($id, $new_level);
  5445. }
  5446. return true;
  5447. }
  5448. /**
  5449. * 获取文件夹下最大子层级
  5450. * @param int $folder_id
  5451. * @return int
  5452. */
  5453. private function getMaxChildLevel($folder_id) {
  5454. $max_level = DB::table('mp_products')
  5455. ->where('parent_id', $folder_id)
  5456. ->where('is_deleted', 0)
  5457. ->max('level');
  5458. if (!$max_level) {
  5459. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5460. }
  5461. // 递归查找子文件夹
  5462. $children = DB::table('mp_products')
  5463. ->where('parent_id', $folder_id)
  5464. ->where('type', 2)
  5465. ->where('is_deleted', 0)
  5466. ->pluck('id');
  5467. foreach ($children as $child_id) {
  5468. $child_max = $this->getMaxChildLevel($child_id);
  5469. if ($child_max > $max_level) {
  5470. $max_level = $child_max;
  5471. }
  5472. }
  5473. return $max_level;
  5474. }
  5475. /**
  5476. * 检查 target_id 是否是 folder_id 的后代
  5477. * @param int $target_id
  5478. * @param int $folder_id
  5479. * @return bool
  5480. */
  5481. private function isDescendant($target_id, $folder_id) {
  5482. if ($target_id == $folder_id) {
  5483. return true;
  5484. }
  5485. $parent = DB::table('mp_products')
  5486. ->where('id', $target_id)
  5487. ->where('is_deleted', 0)
  5488. ->first();
  5489. if (!$parent || $parent->parent_id == 0) {
  5490. return false;
  5491. }
  5492. return $this->isDescendant($parent->parent_id, $folder_id);
  5493. }
  5494. /**
  5495. * 递归更新子项层级
  5496. * @param int $parent_id
  5497. * @param int $parent_level
  5498. */
  5499. private function updateChildrenLevel($parent_id, $parent_level) {
  5500. $children = DB::table('mp_products')
  5501. ->where('parent_id', $parent_id)
  5502. ->where('is_deleted', 0)
  5503. ->get();
  5504. foreach ($children as $child) {
  5505. $new_level = $parent_level + 1;
  5506. DB::table('mp_products')
  5507. ->where('id', $child->id)
  5508. ->update([
  5509. 'level' => $new_level,
  5510. 'updated_at' => date('Y-m-d H:i:s')
  5511. ]);
  5512. // 如果是文件夹,继续递归
  5513. if ($child->type == 2) {
  5514. $this->updateChildrenLevel($child->id, $new_level);
  5515. }
  5516. }
  5517. }
  5518. /**
  5519. * 获取文件夹路径(面包屑导航)
  5520. * @param array $data 包含 folder_id
  5521. * @return array 返回路径数组
  5522. */
  5523. public function getFolderPath($data) {
  5524. $uid = Site::getUid();
  5525. $cpid = Site::getCpid();
  5526. $folder_id = getProp($data, 'id', 0);
  5527. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5528. if ($folder_id == 0) {
  5529. return [
  5530. ['id' => 0, 'name' => '根目录']
  5531. ];
  5532. }
  5533. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5534. $query_uid = $is_public ? 0 : $uid;
  5535. $path = [];
  5536. $current_id = $folder_id;
  5537. while ($current_id > 0) {
  5538. $folder = DB::table('mp_products')
  5539. ->where('id', $current_id)
  5540. ->where('cpid', $cpid)
  5541. ->where('user_id', $query_uid)
  5542. ->where('type', 2)
  5543. ->where('is_deleted', 0)
  5544. ->first();
  5545. if (!$folder) {
  5546. break;
  5547. }
  5548. array_unshift($path, [
  5549. 'id' => $folder->id,
  5550. 'name' => $folder->product_name
  5551. ]);
  5552. $current_id = $folder->parent_id;
  5553. }
  5554. // 添加根目录
  5555. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5556. return $path;
  5557. }
  5558. public function createProduct($data) {
  5559. $uid = Site::getUid();
  5560. $cpid = Site::getCpid();
  5561. $role = Site::getRole();
  5562. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5563. // 如果是公共库操作,需要admin权限
  5564. if ($is_public && $role !== 'admin') {
  5565. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5566. }
  5567. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5568. $store_uid = $is_public ? 0 : $uid;
  5569. $product_name = trim(getProp($data, 'product_name'));
  5570. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5571. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5572. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5573. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5574. $url = trim(getProp($data, 'url'));
  5575. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5576. $versions = getProp($data, 'versions');
  5577. // 检查是否是正确的图片格式
  5578. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5579. $urlPath = parse_url($url, PHP_URL_PATH);
  5580. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5581. if (!in_array($extension, $allowedExtensions)) {
  5582. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5583. }
  5584. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5585. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5586. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5587. $product = getProp($data, 'product');
  5588. if (!in_array($product, [1, 2, 3])) {
  5589. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5590. }
  5591. // 获取父文件夹ID和层级
  5592. $parent_id = getProp($data, 'parent_id', 0);
  5593. $parent_level = 0;
  5594. if ($parent_id > 0) {
  5595. $parent = DB::table('mp_products')
  5596. ->where('id', $parent_id)
  5597. ->where('cpid', $cpid)
  5598. ->where('user_id', $store_uid)
  5599. ->where('type', 2)
  5600. ->where('is_deleted', 0)
  5601. ->first();
  5602. if (!$parent) {
  5603. Utils::throwError('20003:父文件夹不存在');
  5604. }
  5605. $parent_level = $parent->level;
  5606. }
  5607. $id = DB::table('mp_products')->insertGetId([
  5608. 'user_id' => $store_uid,
  5609. 'cpid' => $cpid,
  5610. 'type' => 1, // 1=角色图片
  5611. 'parent_id' => $parent_id,
  5612. 'level' => $parent_level + 1,
  5613. 'product_name' => $product_name,
  5614. 'url' => $url,
  5615. 'pic_prompt' => $pic_prompt,
  5616. 'product' => $product,
  5617. 'versions' => json_encode($versions, 256),
  5618. 'sort_order' => time(), // 使用时间戳作为排序权重
  5619. 'created_at' => date('Y-m-d H:i:s'),
  5620. 'updated_at' => date('Y-m-d H:i:s')
  5621. ]);
  5622. if (!$id) Utils::throwError('20003:创建失败');
  5623. return [
  5624. 'id' => $id,
  5625. 'type' => 1,
  5626. 'parent_id' => $parent_id,
  5627. 'level' => $parent_level + 1,
  5628. 'product_name' => $product_name,
  5629. 'url' => $url,
  5630. 'pic_prompt' => $pic_prompt,
  5631. 'product' => $product,
  5632. 'versions' => $versions
  5633. ];
  5634. }
  5635. public function editProduct($data) {
  5636. $uid = Site::getUid();
  5637. $cpid = Site::getCpid();
  5638. $role = Site::getRole();
  5639. $id = getProp($data, 'id');
  5640. if (!$id) Utils::throwError('20003:ID不能为空');
  5641. $versions = getProp($data, 'versions');
  5642. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5643. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5644. $query_uid = $is_public ? 0 : $uid;
  5645. // 如果是公共库操作,需要admin权限
  5646. if ($is_public && $role !== 'admin') {
  5647. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5648. }
  5649. // 检查是否存在且属于当前用户或公共库
  5650. $role = DB::table('mp_products')
  5651. ->where('id', $id)
  5652. ->where('cpid', $cpid)
  5653. ->where('user_id', $query_uid)
  5654. ->where('type', 1)->first();
  5655. if (!$role) Utils::throwError('20003:记录不存在');
  5656. $updateData = [];
  5657. // $needVersionRecord = false; // 是否需要记录版本
  5658. // 名称
  5659. $product_name = trim(getProp($data, 'product_name'));
  5660. if ($product_name) {
  5661. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5662. $updateData['product_name'] = $product_name;
  5663. }
  5664. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5665. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5666. // 图片地址
  5667. $url = trim(getProp($data, 'url'));
  5668. if ($url) {
  5669. // 检查是否是正确的图片格式
  5670. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5671. $urlPath = parse_url($url, PHP_URL_PATH);
  5672. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5673. if (!in_array($extension, $allowedExtensions)) {
  5674. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5675. }
  5676. // // 如果 url 有变更,记录版本
  5677. // if ($url !== $role->url) {
  5678. // $needVersionRecord = true;
  5679. // }
  5680. $updateData['url'] = $url;
  5681. }
  5682. // 提示词
  5683. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5684. if ($pic_prompt) {
  5685. // // 如果 pic_prompt 有变更,记录版本
  5686. // if ($pic_prompt !== $role->pic_prompt) {
  5687. // $needVersionRecord = true;
  5688. // }
  5689. $updateData['pic_prompt'] = $pic_prompt;
  5690. }
  5691. if (empty($updateData)) {
  5692. Utils::throwError('20003:没有需要更新的数据');
  5693. }
  5694. // // 如果需要记录版本,将数据添加到 versions 数组
  5695. // if ($needVersionRecord) {
  5696. // // 获取现有的 versions 数据
  5697. // $versions = json_decode($role->versions, true) ?: [];
  5698. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  5699. // // 如果是第一次记录版本,先添加旧版本(变更前)
  5700. // if ($isFirstVersion) {
  5701. // $oldVersion = [
  5702. // 'url' => $role->url,
  5703. // 'description' => $role->pic_prompt,
  5704. // ];
  5705. // // 旧版本添加到数组末尾
  5706. // $versions[] = $oldVersion;
  5707. // }
  5708. // // 构建新版本(变更后)
  5709. // $newVersion = [
  5710. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  5711. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  5712. // ];
  5713. // // 检查新版本是否已存在于历史版本中
  5714. // $existingIndex = -1;
  5715. // foreach ($versions as $index => $version) {
  5716. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  5717. // $existingIndex = $index;
  5718. // break;
  5719. // }
  5720. // }
  5721. // if ($existingIndex !== -1) {
  5722. // // 如果已存在,移除旧的位置
  5723. // array_splice($versions, $existingIndex, 1);
  5724. // }
  5725. // // 新版本添加到数组开头(最新的在前)
  5726. // array_unshift($versions, $newVersion);
  5727. // // // 限制版本数量(可选,例如只保留最近10个版本)
  5728. // // if (count($versions) > 10) {
  5729. // // $versions = array_slice($versions, 0, 10);
  5730. // // }
  5731. // $updateData['versions'] = json_encode($versions, 256);
  5732. // }
  5733. if ($versions) {
  5734. $updateData['versions'] = json_encode($versions, 256);
  5735. }
  5736. $updateData['updated_at'] = date('Y-m-d H:i:s');
  5737. return DB::table('mp_products')
  5738. ->where('cpid', $cpid)
  5739. ->where('id', $id)->update($updateData);
  5740. }
  5741. /**
  5742. * 获取角色版本历史
  5743. * @param array $data 包含 id(角色ID)
  5744. * @return array 返回版本历史列表
  5745. */
  5746. public function getProductVersions($data) {
  5747. $cpid = Site::getCpid();
  5748. $id = getProp($data, 'id');
  5749. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5750. $role = DB::table('mp_products')
  5751. ->where('id', $id)
  5752. ->where('cpid', $cpid)
  5753. ->where('type', 1)
  5754. ->first();
  5755. if (!$role) Utils::throwError('20003:角色不存在');
  5756. // 获取版本历史
  5757. $versions = json_decode($role->versions, true) ?: [];
  5758. // 添加当前版本作为最新版本
  5759. $currentVersion = [
  5760. 'version' => 0, // 0 表示当前版本
  5761. 'url' => $role->url,
  5762. 'pic_prompt' => $role->pic_prompt,
  5763. 'updated_at' => $role->updated_at,
  5764. 'is_current' => true
  5765. ];
  5766. array_unshift($versions, $currentVersion);
  5767. return $versions;
  5768. }
  5769. /**
  5770. * 恢复到指定版本
  5771. * @param array $data 包含 id(角色ID)、version(版本号)
  5772. * @return bool
  5773. */
  5774. public function restoreProductVersion($data) {
  5775. $uid = Site::getUid();
  5776. $cpid = Site::getCpid();
  5777. $id = getProp($data, 'id');
  5778. $version = getProp($data, 'version');
  5779. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5780. if (!$version) Utils::throwError('20003:版本号不能为空');
  5781. $role = DB::table('mp_products')
  5782. ->where('id', $id)
  5783. ->where('cpid', $cpid)
  5784. ->where('type', 1)
  5785. ->first();
  5786. if (!$role) Utils::throwError('20003:角色不存在');
  5787. // 获取版本历史
  5788. $versions = json_decode($role->versions, true) ?: [];
  5789. // 查找指定版本
  5790. $targetVersion = null;
  5791. foreach ($versions as $v) {
  5792. if ($v['version'] == $version) {
  5793. $targetVersion = $v;
  5794. break;
  5795. }
  5796. }
  5797. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  5798. // 先将当前版本保存到历史
  5799. $newVersion = [
  5800. 'version' => count($versions) + 1,
  5801. 'url' => $role->url,
  5802. 'pic_prompt' => $role->pic_prompt,
  5803. 'updated_at' => date('Y-m-d H:i:s'),
  5804. 'updated_by' => $uid
  5805. ];
  5806. array_unshift($versions, $newVersion);
  5807. // 限制版本数量
  5808. if (count($versions) > 10) {
  5809. $versions = array_slice($versions, 0, 10);
  5810. }
  5811. // 恢复到指定版本
  5812. return DB::table('mp_products')
  5813. ->where('id', $id)
  5814. ->where('cpid', $cpid)
  5815. ->update([
  5816. 'url' => $targetVersion['url'],
  5817. 'pic_prompt' => $targetVersion['pic_prompt'],
  5818. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  5819. 'updated_at' => date('Y-m-d H:i:s')
  5820. ]);
  5821. }
  5822. public function deleteProduct($data) {
  5823. $uid = Site::getUid();
  5824. $cpid = Site::getCpid();
  5825. $role = Site::getRole();
  5826. $id = getProp($data, 'id');
  5827. if (!$id) Utils::throwError('20003:ID不能为空');
  5828. $ids = explode(',', $id);
  5829. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5830. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5831. $query_uid = $is_public ? 0 : $uid;
  5832. // 如果是公共库操作,需要admin权限
  5833. if ($is_public && $role !== 'admin') {
  5834. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5835. }
  5836. // 检查是否存在且属于当前用户或公共库
  5837. $role = DB::table('mp_products')
  5838. ->whereIn('id', $ids)
  5839. ->where('cpid', $cpid)
  5840. ->where('user_id', $query_uid)
  5841. ->get();
  5842. if (!$role) Utils::throwError('20003:记录不存在');
  5843. return DB::table('mp_products')
  5844. ->where('cpid', $cpid)
  5845. ->where('user_id', $query_uid)
  5846. ->whereIn('id', $ids)
  5847. ->update([
  5848. 'is_deleted' => 1,
  5849. 'updated_at' => date('Y-m-d H:i:s')
  5850. ]);
  5851. }
  5852. public function generateThreeView($data) {
  5853. $uid = Site::getUid();
  5854. $cpid = Site::getCpid();
  5855. $role = Site::getRole();
  5856. $id = getProp($data, 'id');
  5857. if (!$id) Utils::throwError('20003:ID不能为空');
  5858. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5859. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5860. $query_uid = $is_public ? 0 : $uid;
  5861. // 如果是公共库操作,需要admin权限
  5862. if ($is_public && $role !== 'admin') {
  5863. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5864. }
  5865. // 检查是否存在且属于当前用户或公共库
  5866. $product = DB::table('mp_products')
  5867. ->where('id', $id)
  5868. ->where('cpid', $cpid)
  5869. ->where('user_id', $query_uid)
  5870. ->where('type', 1)->first();
  5871. if (!$product) Utils::throwError('20003:资产不存在');
  5872. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  5873. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  5874. if (!$ref_img_url) {
  5875. // 如果没有传入参考图,使用角色表中的图片
  5876. $ref_img_url = $product->url ?? '';
  5877. if (!$ref_img_url) {
  5878. Utils::throwError('20003:参考图不能为空');
  5879. }
  5880. }
  5881. $pic_prompt = getProp($product, 'pic_prompt');
  5882. if ($pic_prompt) {
  5883. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  5884. }
  5885. // 检查参考图是否是正确的图片格式
  5886. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5887. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  5888. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5889. if (!in_array($extension, $allowedExtensions)) {
  5890. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5891. }
  5892. // 处理图片模型
  5893. $model = getProp($data, 'model');
  5894. if (!$model) {
  5895. // 使用默认模型
  5896. $model = 'doubao-seedream-5-0-lite-260128';
  5897. }
  5898. // 验证模型是否在可用模型表中
  5899. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5900. Utils::throwError('20003:该模型已不可用,请更换!');
  5901. }
  5902. $ratio = getProp($data, 'ratio', '16:9');
  5903. $resolution = getProp($data, 'resolution', '2k');
  5904. // 定义分辨率和宽高比对应的尺寸映射表
  5905. $sizeMap = [
  5906. '2k' => [
  5907. '1:1' => ['width' => 2048, 'height' => 2048],
  5908. '4:3' => ['width' => 2304, 'height' => 1728],
  5909. '3:4' => ['width' => 1728, 'height' => 2304],
  5910. '16:9' => ['width' => 2848, 'height' => 1600],
  5911. '9:16' => ['width' => 1600, 'height' => 2848],
  5912. '3:2' => ['width' => 2496, 'height' => 1664],
  5913. '2:3' => ['width' => 1664, 'height' => 2496],
  5914. '21:9' => ['width' => 3136, 'height' => 1344],
  5915. ],
  5916. '3k' => [
  5917. '1:1' => ['width' => 3072, 'height' => 3072],
  5918. '4:3' => ['width' => 3456, 'height' => 2592],
  5919. '3:4' => ['width' => 2592, 'height' => 3456],
  5920. '16:9' => ['width' => 4096, 'height' => 2304],
  5921. '9:16' => ['width' => 2304, 'height' => 4096],
  5922. '2:3' => ['width' => 2496, 'height' => 3744],
  5923. '3:2' => ['width' => 3744, 'height' => 2496],
  5924. '21:9' => ['width' => 4704, 'height' => 2016],
  5925. ],
  5926. '4k' => [
  5927. '1:1' => ['width' => 4096, 'height' => 4096],
  5928. '3:4' => ['width' => 3520, 'height' => 4704],
  5929. '4:3' => ['width' => 4704, 'height' => 3520],
  5930. '16:9' => ['width' => 5504, 'height' => 3040],
  5931. '9:16' => ['width' => 3040, 'height' => 5504],
  5932. '2:3' => ['width' => 3328, 'height' => 4992],
  5933. '3:2' => ['width' => 4992, 'height' => 3328],
  5934. '21:9' => ['width' => 6240, 'height' => 2656],
  5935. ],
  5936. ];
  5937. // 参数验证
  5938. $resolution = strtolower($resolution);
  5939. if (!isset($sizeMap[$resolution])) {
  5940. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5941. }
  5942. if (!isset($sizeMap[$resolution][$ratio])) {
  5943. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5944. }
  5945. // 根据 ratio 和 resolution 确定宽高
  5946. $width = $sizeMap[$resolution][$ratio]['width'];
  5947. $height = $sizeMap[$resolution][$ratio]['height'];
  5948. try {
  5949. // 创建图片生成任务
  5950. $params = [
  5951. 'prompt' => $prompt,
  5952. 'model' => $model,
  5953. 'ref_img_urls' => [$ref_img_url],
  5954. 'width' => $width,
  5955. 'height' => $height
  5956. ];
  5957. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5958. $task_id = $task->id;
  5959. if (!$task_id) {
  5960. Utils::throwError('20003:创建图片生成任务失败');
  5961. }
  5962. // 轮询获取结果
  5963. // 只查询数据库,不调用API,不更新任务表
  5964. $start_time = time();
  5965. $timeout = 1800;
  5966. $img_url = '';
  5967. while (time() - $start_time < $timeout) {
  5968. sleep(5);
  5969. // 只查询数据库中的任务状态,不调用API,不更新任务表
  5970. $task = DB::table('mp_generate_pic_tasks')
  5971. ->where('id', $task_id)
  5972. ->first();
  5973. if (!$task) {
  5974. Utils::throwError('20003:任务不存在');
  5975. }
  5976. if ($task->status === 'success' && $task->result_url) {
  5977. $result_urls = is_string($task->result_url)
  5978. ? json_decode($task->result_url, true)
  5979. : $task->result_url;
  5980. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  5981. break;
  5982. } elseif ($task->status === 'failed') {
  5983. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  5984. }
  5985. // 其他状态继续轮询
  5986. }
  5987. if (empty($img_url)) {
  5988. Utils::throwError('20003:三视图生成超时,请稍后重试');
  5989. }
  5990. // 更新 mp_products 表(不是任务表)
  5991. DB::table('mp_products')
  5992. ->where('id', $id)
  5993. ->where('cpid', $cpid)
  5994. ->update([
  5995. 'three_view_image_url' => $img_url,
  5996. 'updated_at' => date('Y-m-d H:i:s')
  5997. ]);
  5998. return ['three_view_image_url' => $img_url];
  5999. } catch (\Exception $e) {
  6000. dLog('anime')->error('生成三视图失败', [
  6001. 'error' => $e->getMessage()
  6002. ]);
  6003. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6004. Utils::throwError('20003:' . $e->getMessage());
  6005. }
  6006. }
  6007. /**
  6008. * 推送(复制)资产或文件夹到目标位置
  6009. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6010. * @return array 返回推送结果
  6011. */
  6012. public function pushProductOrFolder($data) {
  6013. $uid = Site::getUid();
  6014. $cpid = Site::getCpid();
  6015. $role = Site::getRole();
  6016. $product_id = getProp($data, 'product_id');
  6017. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6018. if (!$product_id) {
  6019. Utils::throwError('20003:请选择要推送的项目');
  6020. }
  6021. // 查询源项目(只通过cpid查询,不限制user_id)
  6022. $sourceItem = DB::table('mp_products')
  6023. ->where('id', $product_id)
  6024. ->where('cpid', $cpid)
  6025. ->where('is_deleted', 0)
  6026. ->first();
  6027. if (!$sourceItem) {
  6028. Utils::throwError('20003:要推送的项目不存在');
  6029. }
  6030. // 通过user_id判断源是公共库还是个人库
  6031. $source_uid = $sourceItem->user_id;
  6032. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6033. // 验证目标文件夹并确定目标是公共库还是个人库
  6034. $target_level = 0;
  6035. $target_uid = $uid; // 默认推送到个人库
  6036. $target_is_public = 0;
  6037. if ($target_parent_id > 0) {
  6038. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6039. $targetParent = DB::table('mp_products')
  6040. ->where('id', $target_parent_id)
  6041. ->where('cpid', $cpid)
  6042. ->where('type', 2)
  6043. ->where('is_deleted', 0)
  6044. ->first();
  6045. if (!$targetParent) {
  6046. Utils::throwError('20003:目标文件夹不存在');
  6047. }
  6048. // 检查 product 类型是否一致
  6049. if ($targetParent->product != $sourceItem->product) {
  6050. Utils::throwError('20003:不能推送到不同类型的文件夹下');
  6051. }
  6052. // 通过user_id判断目标是公共库还是个人库
  6053. $target_level = $targetParent->level;
  6054. $target_uid = $targetParent->user_id;
  6055. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6056. }
  6057. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6058. else {
  6059. $push_to_public = getProp($data, 'push_to_public');
  6060. if ($push_to_public === '') Utils::throwError('20003:请选择是否推送到公共库');
  6061. if ($push_to_public) {
  6062. $target_uid = 0;
  6063. $target_is_public = 1;
  6064. }
  6065. }
  6066. // 如果目标是公共库,需要admin权限
  6067. if ($target_is_public && $role !== 'admin') {
  6068. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6069. }
  6070. // 权限验证:验证是否符合允许的推送规则
  6071. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6072. try {
  6073. DB::beginTransaction();
  6074. // 如果是资产,直接复制
  6075. if ($sourceItem->type == 1) {
  6076. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid);
  6077. DB::commit();
  6078. return [
  6079. 'product_id' => $newId,
  6080. ];
  6081. }
  6082. // 如果是文件夹,递归复制
  6083. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid);
  6084. DB::commit();
  6085. return [
  6086. 'product_id' => $newFolderId,
  6087. ];
  6088. } catch (\Exception $e) {
  6089. DB::rollBack();
  6090. dLog('anime')->error('推送失败', [
  6091. 'error' => $e->getMessage(),
  6092. 'product_id' => $product_id
  6093. ]);
  6094. Utils::throwError('20003:' . $e->getMessage());
  6095. }
  6096. }
  6097. /**
  6098. * 验证推送权限
  6099. * 允许的推送规则:
  6100. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6101. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6102. * 3. 公共库推送给公共库(公共库 → 公共库)
  6103. *
  6104. * @param int $source_uid 源的user_id
  6105. * @param int $target_uid 目标的user_id
  6106. * @param int $current_uid 当前用户ID
  6107. * @throws \Exception
  6108. */
  6109. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6110. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6111. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6112. return; // 允许
  6113. }
  6114. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6115. if ($source_uid == 0 && $target_uid == $current_uid) {
  6116. return; // 允许
  6117. }
  6118. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6119. if ($source_uid == 0 && $target_uid == 0) {
  6120. return; // 允许
  6121. }
  6122. // 其他情况都不允许
  6123. if ($source_uid != 0 && $source_uid != $current_uid) {
  6124. // 源是别人的个人库
  6125. Utils::throwError('20003:无权限访问该资产');
  6126. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6127. // 个人库推送给公共库(不允许)
  6128. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6129. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6130. // 不同用户的个人库之间推送(不允许)
  6131. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6132. } else {
  6133. // 其他未知情况
  6134. Utils::throwError('20003:不允许的推送操作');
  6135. }
  6136. }
  6137. /**
  6138. * 复制单个资产
  6139. * @param object $sourceProduct 源资产对象
  6140. * @param int $targetParentId 目标父文件夹ID
  6141. * @param int $targetLevel 目标层级
  6142. * @param int $cpid 公司ID
  6143. * @param int $targetUid 目标用户ID
  6144. * @return int 返回新资产ID
  6145. */
  6146. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid) {
  6147. $newProductData = [
  6148. 'user_id' => $targetUid,
  6149. 'cpid' => $cpid,
  6150. 'type' => 1,
  6151. 'parent_id' => $targetParentId,
  6152. 'level' => $targetLevel,
  6153. 'product_name' => $sourceProduct->product_name,
  6154. 'url' => $sourceProduct->url,
  6155. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6156. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6157. 'product' => $sourceProduct->product,
  6158. 'versions' => $sourceProduct->versions ?? '',
  6159. 'sort_order' => time(),
  6160. 'is_deleted' => 0,
  6161. 'created_at' => date('Y-m-d H:i:s'),
  6162. 'updated_at' => date('Y-m-d H:i:s')
  6163. ];
  6164. return DB::table('mp_products')->insertGetId($newProductData);
  6165. }
  6166. /**
  6167. * 递归复制文件夹及其子项
  6168. * @param object $sourceFolder 源文件夹对象
  6169. * @param int $targetParentId 目标父文件夹ID
  6170. * @param int $targetLevel 目标层级
  6171. * @param int $cpid 公司ID
  6172. * @param int $targetUid 目标用户ID
  6173. * @param int $sourceUid 源用户ID
  6174. * @return int 返回新文件夹ID
  6175. */
  6176. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid) {
  6177. // 创建新文件夹
  6178. $newFolderData = [
  6179. 'user_id' => $targetUid,
  6180. 'cpid' => $cpid,
  6181. 'type' => 2,
  6182. 'parent_id' => $targetParentId,
  6183. 'level' => $targetLevel,
  6184. 'product_name' => $sourceFolder->product_name,
  6185. 'product' => $sourceFolder->product,
  6186. 'sort_order' => time(),
  6187. 'is_deleted' => 0,
  6188. 'created_at' => date('Y-m-d H:i:s'),
  6189. 'updated_at' => date('Y-m-d H:i:s')
  6190. ];
  6191. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6192. // 获取源文件夹下的所有子项
  6193. $children = DB::table('mp_products')
  6194. ->where('parent_id', $sourceFolder->id)
  6195. ->where('cpid', $cpid)
  6196. ->where('user_id', $sourceUid)
  6197. ->where('is_deleted', 0)
  6198. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6199. ->get();
  6200. // 递归复制子项
  6201. foreach ($children as $child) {
  6202. if ($child->type == 1) {
  6203. // 资产
  6204. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid);
  6205. } else {
  6206. // 文件夹
  6207. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid);
  6208. }
  6209. }
  6210. return $newFolderId;
  6211. }
  6212. /**
  6213. * 保存剧本资产关联关系
  6214. * @param array $data 请求参数
  6215. * @return bool
  6216. */
  6217. public function saveScriptProducts($data) {
  6218. $uid = Site::getUid();
  6219. $cpid = Site::getCpid();
  6220. $script_id = getProp($data, 'script_id');
  6221. $products = getProp($data, 'products', []);
  6222. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6223. if (!$script_id) {
  6224. Utils::throwError('20003:请提供剧本ID');
  6225. }
  6226. // 验证剧本是否存在
  6227. $script = DB::table('mp_scripts')
  6228. ->where('id', $script_id)
  6229. ->where('is_deleted', 0)
  6230. ->first();
  6231. if (!$script) {
  6232. Utils::throwError('20003:剧本不存在');
  6233. }
  6234. // 处理图片模型
  6235. $model = getProp($data, 'model');
  6236. if (!$model) {
  6237. // 使用默认模型
  6238. $model = 'doubao-seedream-5-0-lite-260128';
  6239. }
  6240. // 验证模型是否在可用模型表中
  6241. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6242. Utils::throwError('20003:该模型已不可用,请更换!');
  6243. }
  6244. $ratio = getProp($data, 'ratio', '9:16');
  6245. $resolution = getProp($data, 'resolution', '2k');
  6246. // 定义分辨率和宽高比对应的尺寸映射表
  6247. $sizeMap = [
  6248. '2k' => [
  6249. '1:1' => ['width' => 2048, 'height' => 2048],
  6250. '4:3' => ['width' => 2304, 'height' => 1728],
  6251. '3:4' => ['width' => 1728, 'height' => 2304],
  6252. '16:9' => ['width' => 2848, 'height' => 1600],
  6253. '9:16' => ['width' => 1600, 'height' => 2848],
  6254. '3:2' => ['width' => 2496, 'height' => 1664],
  6255. '2:3' => ['width' => 1664, 'height' => 2496],
  6256. '21:9' => ['width' => 3136, 'height' => 1344],
  6257. ],
  6258. '3k' => [
  6259. '1:1' => ['width' => 3072, 'height' => 3072],
  6260. '4:3' => ['width' => 3456, 'height' => 2592],
  6261. '3:4' => ['width' => 2592, 'height' => 3456],
  6262. '16:9' => ['width' => 4096, 'height' => 2304],
  6263. '9:16' => ['width' => 2304, 'height' => 4096],
  6264. '2:3' => ['width' => 2496, 'height' => 3744],
  6265. '3:2' => ['width' => 3744, 'height' => 2496],
  6266. '21:9' => ['width' => 4704, 'height' => 2016],
  6267. ],
  6268. '4k' => [
  6269. '1:1' => ['width' => 4096, 'height' => 4096],
  6270. '3:4' => ['width' => 3520, 'height' => 4704],
  6271. '4:3' => ['width' => 4704, 'height' => 3520],
  6272. '16:9' => ['width' => 5504, 'height' => 3040],
  6273. '9:16' => ['width' => 3040, 'height' => 5504],
  6274. '2:3' => ['width' => 3328, 'height' => 4992],
  6275. '3:2' => ['width' => 4992, 'height' => 3328],
  6276. '21:9' => ['width' => 6240, 'height' => 2656],
  6277. ],
  6278. ];
  6279. // 参数验证
  6280. $resolution = strtolower($resolution);
  6281. if (!isset($sizeMap[$resolution])) {
  6282. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6283. }
  6284. if (!isset($sizeMap[$resolution][$ratio])) {
  6285. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6286. }
  6287. // 根据 ratio 和 resolution 确定宽高
  6288. $width = $sizeMap[$resolution][$ratio]['width'];
  6289. $height = $sizeMap[$resolution][$ratio]['height'];
  6290. $script_name = $script->script_name ?? 'script_' . $script_id;
  6291. // 检查是否已经有该剧本的资产数据
  6292. $existingMappings = DB::table('mp_script_product_mappings')
  6293. ->where('script_id', $script_id)
  6294. ->get();
  6295. if ($existingMappings->isNotEmpty()) {
  6296. // 已存在资产映射,检查是否所有资产都有图片生成任务
  6297. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  6298. // 查询这些资产的图片生成任务状态
  6299. $productsWithTasks = DB::table('mp_products')
  6300. ->whereIn('id', $productIds)
  6301. ->where('is_deleted', 0)
  6302. ->get();
  6303. $productTaskMap = [];
  6304. $typeFolderIds = [];
  6305. $hasAllTasks = true;
  6306. foreach ($productsWithTasks as $product) {
  6307. // 收集类型文件夹ID
  6308. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  6309. $parentFolder = DB::table('mp_products')
  6310. ->where('id', $product->parent_id)
  6311. ->where('type', 2)
  6312. ->first();
  6313. if ($parentFolder) {
  6314. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  6315. }
  6316. }
  6317. // 检查是否有图片生成任务
  6318. if (!empty($product->pic_task_id)) {
  6319. $productTaskMap[$product->id] = $product->pic_task_id;
  6320. } else if($product->url && $product->pic_task_status == '生成成功') {
  6321. continue;
  6322. } else {
  6323. // 有资产没有图片任务
  6324. $hasAllTasks = false;
  6325. }
  6326. }
  6327. // 如果所有资产都有任务ID,直接轮询返回结果
  6328. if ($hasAllTasks && !empty($productTaskMap)) {
  6329. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  6330. 'script_id' => $script_id,
  6331. 'script_name' => $script_name,
  6332. 'product_count' => count($productTaskMap)
  6333. ]);
  6334. // 直接返回 SSE 流轮询结果
  6335. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6336. }
  6337. // 如果部分资产没有任务ID,只为这些资产创建任务
  6338. if (!$hasAllTasks && $auto_generate_images) {
  6339. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  6340. 'script_id' => $script_id,
  6341. 'script_name' => $script_name
  6342. ]);
  6343. // 开启事务
  6344. DB::beginTransaction();
  6345. try {
  6346. foreach ($productsWithTasks as $product) {
  6347. // 跳过已有任务的资产
  6348. if (!empty($product->pic_task_id)) {
  6349. continue;
  6350. }
  6351. // 跳过没有提示词的资产
  6352. if (empty($product->pic_prompt)) {
  6353. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6354. 'product_id' => $product->id,
  6355. 'product_name' => $product->product_name
  6356. ]);
  6357. continue;
  6358. }
  6359. try {
  6360. // 创建图片生成任务
  6361. $params = [
  6362. 'prompt' => $product->pic_prompt,
  6363. 'model' => $model,
  6364. 'ref_img_urls' => [],
  6365. 'width' => $width,
  6366. 'height' => $height
  6367. ];
  6368. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6369. $task_id = $task->id;
  6370. if ($task_id) {
  6371. $productTaskMap[$product->id] = $task_id;
  6372. // 在事务中更新资产表的任务ID和状态
  6373. DB::table('mp_products')
  6374. ->where('id', $product->id)
  6375. ->update([
  6376. 'pic_task_id' => $task_id,
  6377. 'pic_task_status' => '生成中',
  6378. 'updated_at' => now()
  6379. ]);
  6380. dLog('anime')->info('为已存在资产创建图片生成任务', [
  6381. 'product_id' => $product->id,
  6382. 'task_id' => $task_id
  6383. ]);
  6384. }
  6385. } catch (\Exception $e) {
  6386. dLog('anime')->error('创建资产图片生成任务失败', [
  6387. 'product_id' => $product->id,
  6388. 'error' => $e->getMessage()
  6389. ]);
  6390. // 标记为失败(仍在事务中)
  6391. DB::table('mp_products')
  6392. ->where('id', $product->id)
  6393. ->update([
  6394. 'pic_task_status' => '生成失败',
  6395. 'updated_at' => now()
  6396. ]);
  6397. }
  6398. }
  6399. // 提交事务
  6400. DB::commit();
  6401. // 如果有新创建的任务,返回 SSE 流
  6402. if (!empty($productTaskMap)) {
  6403. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6404. }
  6405. } catch (\Exception $e) {
  6406. // 回滚事务
  6407. DB::rollback();
  6408. dLog('anime')->error('为已存在资产创建图片任务失败', [
  6409. 'script_id' => $script_id,
  6410. 'error' => $e->getMessage()
  6411. ]);
  6412. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  6413. }
  6414. }
  6415. // 如果不需要生成图片,返回已存在的信息
  6416. return [
  6417. 'success' => true,
  6418. 'message' => '剧本资产已存在',
  6419. 'script_id' => $script_id,
  6420. 'script_name' => $script_name,
  6421. 'type_folder_ids' => $typeFolderIds,
  6422. 'existing_products' => count($productIds),
  6423. 'tasks_count' => count($productTaskMap)
  6424. ];
  6425. }
  6426. // 解析 products(可能是 JSON 字符串或数组)
  6427. if (is_string($products)) {
  6428. $products = json_decode($products, true);
  6429. if (json_last_error() !== JSON_ERROR_NONE) {
  6430. Utils::throwError('20003:产品数据格式错误');
  6431. }
  6432. }
  6433. if (!is_array($products) || empty($products)) {
  6434. Utils::throwError('20003:产品数据不能为空');
  6435. }
  6436. // 以下是原有的创建逻辑...
  6437. // 开启事务
  6438. DB::beginTransaction();
  6439. try {
  6440. $now = now();
  6441. $mappingRecords = [];
  6442. $createdProductIds = []; // 记录所有创建的资产ID
  6443. // 获取剧本名称
  6444. $script_name = $script->script_name ?? 'script_' . $script_id;
  6445. // 存储每个类型的根文件夹ID
  6446. $typeFolderIds = [];
  6447. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  6448. foreach ($products as $productGroup) {
  6449. $type = getProp($productGroup, 'type');
  6450. $title = getProp($productGroup, 'title', '');
  6451. $content = getProp($productGroup, 'content', []);
  6452. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  6453. continue;
  6454. }
  6455. // 为当前类型创建根文件夹(如果还未创建)
  6456. if (!isset($typeFolderIds[$type])) {
  6457. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  6458. 'user_id' => $uid,
  6459. 'cpid' => $cpid,
  6460. 'type' => 2, // 1.资产 2文件夹
  6461. 'product' => $type, // 1.主体 2.场景 3.道具
  6462. 'parent_id' => 0, // 根文件夹,parent_id=0
  6463. 'level' => 1, // 第一层级
  6464. 'product_name' => $script_name,
  6465. 'sort_order' => time() + $type,
  6466. 'is_deleted' => 0,
  6467. 'created_at' => $now,
  6468. 'updated_at' => $now
  6469. ]);
  6470. }
  6471. $folder_id = $typeFolderIds[$type];
  6472. // 获取表头(第一行)并查找关键列的位置
  6473. $headers = $content[0];
  6474. $nameColumnIndex = -1; // 资产名称列索引
  6475. $sequenceColumnIndex = -1; // 使用范围列索引
  6476. $promptColumnIndex = -1; // 参考提示词列索引
  6477. foreach ($headers as $index => $header) {
  6478. // 查找"资产名称"列
  6479. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  6480. $nameColumnIndex = $index;
  6481. }
  6482. // 查找"使用范围"列
  6483. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  6484. $sequenceColumnIndex = $index;
  6485. }
  6486. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  6487. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  6488. $promptColumnIndex = $index;
  6489. }
  6490. }
  6491. // 验证必要的列是否都找到了
  6492. if ($nameColumnIndex === -1) {
  6493. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  6494. continue;
  6495. }
  6496. if ($sequenceColumnIndex === -1) {
  6497. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  6498. continue;
  6499. }
  6500. // 跳过表头,解析每一行数据
  6501. for ($i = 1; $i < count($content); $i++) {
  6502. $row = $content[$i];
  6503. // 确保行数据有效
  6504. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  6505. continue;
  6506. }
  6507. // 根据动态查找的列索引提取数据
  6508. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  6509. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6510. $pic_prompt = '';
  6511. // 提取参考提示词(如果找到了该列)
  6512. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6513. $pic_prompt = trim($row[$promptColumnIndex]);
  6514. }
  6515. // 解析使用范围(逗号分隔的序号)
  6516. $sequences = [];
  6517. if (!empty($sequence_str)) {
  6518. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  6519. foreach ($sequenceParts as $part) {
  6520. if (is_numeric($part)) {
  6521. $sequences[] = (int)$part;
  6522. }
  6523. }
  6524. }
  6525. if (empty($product_name)) {
  6526. continue;
  6527. }
  6528. // 处理product_name两边的符号
  6529. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6530. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  6531. $product_id = DB::table('mp_products')->insertGetId([
  6532. 'product_name' => $product_name,
  6533. 'type' => 1, // 1=资产 2.文件夹
  6534. 'product' => $type, // 1=角色, 2=场景, 3=道具
  6535. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  6536. 'level' => 2, // 第二层级
  6537. 'pic_prompt' => $pic_prompt,
  6538. 'user_id' => $uid,
  6539. 'cpid' => $cpid,
  6540. 'sort_order' => time(),
  6541. 'is_deleted' => 0,
  6542. 'created_at' => $now,
  6543. 'updated_at' => $now,
  6544. ]);
  6545. // 记录创建的资产ID
  6546. $createdProductIds[] = $product_id;
  6547. // 为每个序号创建映射记录
  6548. if (!empty($sequences)) {
  6549. foreach ($sequences as $sequence) {
  6550. $mappingRecords[] = [
  6551. 'script_id' => $script_id,
  6552. 'product_id' => $product_id,
  6553. 'episode_number' => $sequence,
  6554. 'created_at' => $now,
  6555. 'updated_at' => $now,
  6556. ];
  6557. }
  6558. } else {
  6559. // 如果没有指定序号,创建一个默认映射(序号为0)
  6560. $mappingRecords[] = [
  6561. 'script_id' => $script_id,
  6562. 'product_id' => $product_id,
  6563. 'episode_number' => 0,
  6564. 'created_at' => $now,
  6565. 'updated_at' => $now,
  6566. ];
  6567. }
  6568. }
  6569. }
  6570. if (empty($mappingRecords)) {
  6571. Utils::throwError('20003:没有有效的产品数据');
  6572. }
  6573. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  6574. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  6575. // 如果需要自动生成图片,在事务中创建图片生成任务
  6576. $productTaskMap = [];
  6577. if ($auto_generate_images && !empty($createdProductIds)) {
  6578. // 查询所有创建的资产
  6579. $productsToGenerate = DB::table('mp_products')
  6580. ->whereIn('id', $createdProductIds)
  6581. ->where('is_deleted', 0)
  6582. ->get();
  6583. foreach ($productsToGenerate as $product) {
  6584. if (empty($product->pic_prompt)) {
  6585. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6586. 'product_id' => $product->id,
  6587. 'product_name' => $product->product_name
  6588. ]);
  6589. continue;
  6590. }
  6591. try {
  6592. // 创建图片生成任务
  6593. $params = [
  6594. 'prompt' => $product->pic_prompt,
  6595. 'model' => $model,
  6596. 'ref_img_urls' => [],
  6597. 'width' => $width,
  6598. 'height' => $height
  6599. ];
  6600. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6601. $task_id = $task->id;
  6602. if ($task_id) {
  6603. $productTaskMap[$product->id] = $task_id;
  6604. // 在事务中更新资产表的任务ID和状态
  6605. DB::table('mp_products')
  6606. ->where('id', $product->id)
  6607. ->update([
  6608. 'pic_task_id' => $task_id,
  6609. 'pic_task_status' => '生成中',
  6610. 'updated_at' => now()
  6611. ]);
  6612. dLog('anime')->info('创建资产图片生成任务', [
  6613. 'product_id' => $product->id,
  6614. 'task_id' => $task_id
  6615. ]);
  6616. }
  6617. } catch (\Exception $e) {
  6618. dLog('anime')->error('创建资产图片生成任务失败', [
  6619. 'product_id' => $product->id,
  6620. 'error' => $e->getMessage()
  6621. ]);
  6622. // 标记为失败(仍在事务中)
  6623. DB::table('mp_products')
  6624. ->where('id', $product->id)
  6625. ->update([
  6626. 'pic_task_status' => '生成失败',
  6627. 'updated_at' => now()
  6628. ]);
  6629. }
  6630. }
  6631. }
  6632. // 提交事务
  6633. DB::commit();
  6634. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6635. if ($auto_generate_images && !empty($productTaskMap)) {
  6636. // 返回 SSE 流(事务外轮询)
  6637. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6638. }
  6639. // 如果不需要生成图片,返回普通结果
  6640. return [
  6641. 'success' => true,
  6642. 'type_folder_ids' => $typeFolderIds,
  6643. 'inserted_count' => $insertedCount,
  6644. 'total_records' => count($mappingRecords),
  6645. 'created_products' => count($createdProductIds),
  6646. 'image_tasks_created' => count($productTaskMap)
  6647. ];
  6648. } catch (\Exception $e) {
  6649. // 回滚事务
  6650. DB::rollback();
  6651. // 记录错误日志
  6652. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6653. 'script_id' => $script_id,
  6654. 'error' => $e->getMessage(),
  6655. 'trace' => $e->getTraceAsString()
  6656. ]);
  6657. // 统一使用 Utils::throwError 抛出错误
  6658. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6659. }
  6660. }
  6661. /**
  6662. * 批量为剧本资产生成图片
  6663. *
  6664. * @param array $data 请求参数
  6665. * @return \Generator 返回 SSE 流
  6666. */
  6667. public function batchGenerateProductImages($data) {
  6668. $script_id = getProp($data, 'script_id');
  6669. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  6670. if (!$script_id) {
  6671. Utils::throwError('20003:请提供剧本ID');
  6672. }
  6673. // 验证剧本是否存在
  6674. $script = DB::table('mp_scripts')
  6675. ->where('id', $script_id)
  6676. ->where('is_deleted', 0)
  6677. ->first();
  6678. if (!$script) {
  6679. Utils::throwError('20003:剧本不存在');
  6680. }
  6681. $script_name = $script->script_name ?? 'script_' . $script_id;
  6682. // 获取需要生成图片的所有资产
  6683. $products = DB::table('mp_products')
  6684. ->whereIn('parent_id', array_values($type_folder_ids))
  6685. ->where('is_deleted', 0)
  6686. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  6687. ->get();
  6688. if ($products->isEmpty()) {
  6689. Utils::throwError('20003:没有找到需要生成图片的资产');
  6690. }
  6691. // 默认参数
  6692. $model = 'doubao-seedream-5-0-lite-260128';
  6693. $width = 1600;
  6694. $height = 2848;
  6695. // 开始为每个资产创建图片生成任务
  6696. $taskIds = [];
  6697. $productTaskMap = []; // 资产ID到任务ID的映射
  6698. foreach ($products as $product) {
  6699. if (empty($product->pic_prompt)) {
  6700. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  6701. continue;
  6702. }
  6703. try {
  6704. // 创建图片生成任务
  6705. $params = [
  6706. 'prompt' => $product->pic_prompt,
  6707. 'model' => $model,
  6708. 'ref_img_urls' => [],
  6709. 'width' => $width,
  6710. 'height' => $height
  6711. ];
  6712. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6713. $task_id = $task->id;
  6714. if ($task_id) {
  6715. $taskIds[] = $task_id;
  6716. $productTaskMap[$product->id] = $task_id;
  6717. // 更新资产表的任务ID和状态
  6718. DB::table('mp_products')
  6719. ->where('id', $product->id)
  6720. ->update([
  6721. 'pic_task_id' => $task_id,
  6722. 'pic_task_status' => '生成中',
  6723. 'updated_at' => now()
  6724. ]);
  6725. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  6726. }
  6727. } catch (\Exception $e) {
  6728. dLog('anime')->error('创建资产图片生成任务失败', [
  6729. 'product_id' => $product->id,
  6730. 'error' => $e->getMessage()
  6731. ]);
  6732. // 标记为失败
  6733. DB::table('mp_products')
  6734. ->where('id', $product->id)
  6735. ->update([
  6736. 'pic_task_status' => '生成失败',
  6737. 'updated_at' => now()
  6738. ]);
  6739. }
  6740. }
  6741. if (empty($taskIds)) {
  6742. Utils::throwError('20003:没有成功创建任何图片生成任务');
  6743. }
  6744. // 返回 SSE 流
  6745. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  6746. }
  6747. /**
  6748. * 轮询资产图片生成任务状态(SSE流式返回)
  6749. * 只通过查询数据库获取任务状态,不主动调用API
  6750. *
  6751. * @param int $script_id 剧本ID
  6752. * @param string $script_name 剧本名称
  6753. * @param array $productTaskMap 资产ID到任务ID的映射
  6754. * @param array $type_folder_ids 类型文件夹ID映射
  6755. * @return \Generator
  6756. */
  6757. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  6758. $startTime = time();
  6759. $timeout = 1800; // 30分钟超时
  6760. $pollInterval = 10; // 10秒轮询一次
  6761. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  6762. // 定义类型名称映射
  6763. $typeNames = [
  6764. 1 => 'roles', // 角色
  6765. 2 => 'scenes', // 场景
  6766. 3 => 'props' // 道具
  6767. ];
  6768. while (time() - $startTime < $timeout) {
  6769. sleep($pollInterval);
  6770. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  6771. $mappings = DB::table('mp_script_product_mappings')
  6772. ->where('script_id', $script_id)
  6773. ->pluck('product_id')
  6774. ->unique()
  6775. ->toArray();
  6776. if (empty($mappings)) {
  6777. dLog('anime')->warning('该剧本没有关联的资产', [
  6778. 'script_id' => $script_id,
  6779. 'script_name' => $script_name
  6780. ]);
  6781. break;
  6782. }
  6783. // 查询所有资产的当前状态
  6784. $products = DB::table('mp_products')
  6785. ->whereIn('id', $mappings)
  6786. ->where('is_deleted', 0)
  6787. ->get();
  6788. // 统计各类型的状态(使用类型名称作为键名)
  6789. $stats = [
  6790. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  6791. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  6792. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  6793. ];
  6794. $allCompleted = true;
  6795. $hasStatusChange = false;
  6796. foreach ($products as $product) {
  6797. $type = $product->product;
  6798. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  6799. // 如果类型名称不在 stats 中,初始化
  6800. if (!isset($stats[$typeName])) {
  6801. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  6802. }
  6803. $stats[$typeName]['total']++;
  6804. $task_id = $product->pic_task_id;
  6805. $currentStatus = $product->pic_task_status;
  6806. // 检查状态是否有变化
  6807. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  6808. $hasStatusChange = true;
  6809. $lastStatus[$product->id] = $currentStatus;
  6810. }
  6811. // 如果是生成中,查询任务表状态
  6812. if ($currentStatus === '生成中' && $task_id) {
  6813. // 只查询数据库,不调用API
  6814. $task = DB::table('mp_generate_pic_tasks')
  6815. ->where('id', $task_id)
  6816. ->first();
  6817. if ($task) {
  6818. // 检查任务状态
  6819. if ($task->status === 'success' && $task->result_url) {
  6820. // 解析图片URL
  6821. $result_urls = $task->result_url;
  6822. if (is_string($result_urls)) {
  6823. $result_urls = json_decode($result_urls, true);
  6824. }
  6825. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6826. // 更新资产表状态
  6827. DB::table('mp_products')
  6828. ->where('id', $product->id)
  6829. ->update([
  6830. 'pic_task_status' => '生成成功',
  6831. 'url' => $img_url,
  6832. 'updated_at' => now()
  6833. ]);
  6834. $stats[$typeName]['success']++;
  6835. $stats[$typeName]['completed']++;
  6836. $hasStatusChange = true;
  6837. dLog('anime')->info('资产图片生成成功', [
  6838. 'product_id' => $product->id,
  6839. 'task_id' => $task_id,
  6840. 'img_url' => $img_url
  6841. ]);
  6842. } elseif ($task->status === 'failed') {
  6843. // 更新资产表状态
  6844. DB::table('mp_products')
  6845. ->where('id', $product->id)
  6846. ->update([
  6847. 'pic_task_status' => '生成失败',
  6848. 'updated_at' => now()
  6849. ]);
  6850. $stats[$typeName]['completed']++;
  6851. $hasStatusChange = true;
  6852. dLog('anime')->warning('资产图片生成失败', [
  6853. 'product_id' => $product->id,
  6854. 'task_id' => $task_id,
  6855. 'error' => $task->error_message ?? '未知错误'
  6856. ]);
  6857. } else {
  6858. // 任务还在处理中
  6859. $allCompleted = false;
  6860. }
  6861. } else {
  6862. // 任务不存在,标记为失败
  6863. DB::table('mp_products')
  6864. ->where('id', $product->id)
  6865. ->update([
  6866. 'pic_task_status' => '生成失败',
  6867. 'updated_at' => now()
  6868. ]);
  6869. $stats[$type]['completed']++;
  6870. $hasStatusChange = true;
  6871. dLog('anime')->error('图片生成任务不存在', [
  6872. 'product_id' => $product->id,
  6873. 'task_id' => $task_id
  6874. ]);
  6875. }
  6876. } elseif ($currentStatus === '生成成功') {
  6877. $stats[$typeName]['success']++;
  6878. $stats[$typeName]['completed']++;
  6879. } elseif ($currentStatus === '生成失败') {
  6880. $stats[$typeName]['completed']++;
  6881. } else {
  6882. // 其他状态也认为未完成
  6883. $allCompleted = false;
  6884. }
  6885. }
  6886. // 移除没有数据的类型(total=0)
  6887. foreach ($stats as $typeName => $stat) {
  6888. if ($stat['total'] === 0) {
  6889. unset($stats[$typeName]);
  6890. }
  6891. }
  6892. // 如果有状态变化,发送 SSE 更新
  6893. if ($hasStatusChange) {
  6894. $eventType = $allCompleted ? 'complete' : 'update';
  6895. $response = [
  6896. 'type' => $eventType,
  6897. 'script_id' => $script_id,
  6898. 'script_name' => $script_name,
  6899. 'stats' => $stats,
  6900. 'timestamp' => date('Y-m-d H:i:s')
  6901. ];
  6902. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  6903. dLog('anime')->info('SSE更新', [
  6904. 'event_type' => $eventType,
  6905. 'script_id' => $script_id,
  6906. 'script_name' => $script_name,
  6907. 'stats' => $stats
  6908. ]);
  6909. if ($allCompleted) {
  6910. dLog('anime')->info('所有资产图片生成任务已完成', [
  6911. 'script_id' => $script_id,
  6912. 'script_name' => $script_name,
  6913. 'stats' => $stats
  6914. ]);
  6915. break;
  6916. }
  6917. }
  6918. }
  6919. // 超时处理
  6920. if (time() - $startTime >= $timeout && !$allCompleted) {
  6921. $response = [
  6922. 'type' => 'timeout',
  6923. 'message' => '部分任务超时,请稍后查看结果',
  6924. 'script_id' => $script_id,
  6925. 'script_name' => $script_name,
  6926. 'timestamp' => date('Y-m-d H:i:s')
  6927. ];
  6928. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  6929. dLog('anime')->warning('资产图片生成任务超时', [
  6930. 'script_id' => $script_id,
  6931. 'script_name' => $script_name,
  6932. 'timeout' => $timeout
  6933. ]);
  6934. }
  6935. }
  6936. /**
  6937. * 获取剧本关联的资产列表
  6938. * @param array $data 请求参数
  6939. * @return array
  6940. */
  6941. public function getScriptProducts($data) {
  6942. $uid = Site::getUid();
  6943. $cpid = Site::getCpid();
  6944. $script_id = getProp($data, 'script_id');
  6945. $episode_number = getProp($data, 'episode_number');
  6946. if (!$script_id) {
  6947. Utils::throwError('20003:请提供剧本ID');
  6948. }
  6949. // 验证剧本是否存在
  6950. $script = DB::table('mp_scripts')
  6951. ->where('id', $script_id)
  6952. ->where('is_deleted', 0)
  6953. ->first();
  6954. if (!$script) {
  6955. Utils::throwError('20003:剧本不存在');
  6956. }
  6957. // 联表查询资产信息
  6958. $query = DB::table('mp_script_product_mappings as mapping')
  6959. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6960. ->where('mapping.script_id', $script_id)
  6961. ->where('product.cpid', $cpid)
  6962. ->where('product.is_deleted', 0);
  6963. // 如果提供了 episode_number,则过滤指定集数
  6964. if ($episode_number !== null && $episode_number !== '') {
  6965. $query->where('mapping.episode_number', $episode_number);
  6966. }
  6967. $mappings = $query->select(
  6968. 'mapping.script_id',
  6969. 'mapping.product_id',
  6970. 'mapping.episode_number',
  6971. 'product.product_name',
  6972. 'product.type',
  6973. 'product.product',
  6974. 'product.pic_prompt',
  6975. 'product.url',
  6976. 'product.pic_task_id',
  6977. 'product.pic_task_status',
  6978. 'product.three_view_image_url',
  6979. 'mapping.created_at'
  6980. )
  6981. ->orderBy('mapping.product_id', 'asc')
  6982. ->orderBy('mapping.episode_number', 'asc')
  6983. ->get();
  6984. // 按 product_id 分组,合并 episode_number
  6985. $productMap = [];
  6986. foreach ($mappings as $item) {
  6987. $product_id = $item->product_id;
  6988. if (!isset($productMap[$product_id])) {
  6989. $productMap[$product_id] = [
  6990. 'product_id' => $product_id,
  6991. 'product_name' => $item->product_name,
  6992. 'type' => (int)$item->type,
  6993. 'product' => (int)$item->product,
  6994. 'pic_prompt' => $item->pic_prompt,
  6995. 'url' => $item->url,
  6996. 'pic_task_id' => $item->pic_task_id,
  6997. 'pic_task_status' => $item->pic_task_status,
  6998. 'episode_numbers' => [],
  6999. 'created_at' => $item->created_at,
  7000. ];
  7001. }
  7002. // 添加 episode_number(去重)
  7003. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7004. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7005. }
  7006. }
  7007. // 按类型分组
  7008. $roles = []; // type=1 角色/主体
  7009. $scenes = []; // type=2 场景
  7010. $props = []; // type=3 道具
  7011. foreach ($productMap as $product) {
  7012. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7013. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7014. // 构造返回数据
  7015. $productData = [
  7016. 'product_id' => $product['product_id'],
  7017. 'product_name' => $product['product_name'],
  7018. 'product' => $product['product'],
  7019. 'pic_prompt' => $product['pic_prompt'],
  7020. 'url' => $product['url'],
  7021. 'pic_task_id' => $product['pic_task_id'],
  7022. 'pic_task_status' => $product['pic_task_status'],
  7023. 'episode_numbers' => $episodeNumbersStr,
  7024. 'created_at' => $product['created_at'],
  7025. ];
  7026. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7027. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7028. switch ($product['product']) {
  7029. case 1:
  7030. $roles[] = $productData;
  7031. break;
  7032. case 2:
  7033. $scenes[] = $productData;
  7034. break;
  7035. case 3:
  7036. $props[] = $productData;
  7037. break;
  7038. }
  7039. }
  7040. return [
  7041. 'script_id' => $script_id,
  7042. 'script_name' => $script->script_name ?? '',
  7043. 'roles' => $roles, // 主体
  7044. 'scenes' => $scenes, // 场景
  7045. 'props' => $props, // 道具
  7046. ];
  7047. }
  7048. /**
  7049. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7050. * @param string $actContent 原始内容
  7051. * @param array $products 产品数组(包含product_name和url)
  7052. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7053. */
  7054. public function processActContentWithProducts($actContent, $products) {
  7055. if (empty($actContent) || empty($products)) {
  7056. return [
  7057. 'content' => $actContent,
  7058. 'reference_images' => []
  7059. ];
  7060. }
  7061. // 构建产品名称到产品信息的映射
  7062. $product_dict = [];
  7063. foreach ($products as $product) {
  7064. $product_name = getProp($product, 'product_name');
  7065. if ($product_name) {
  7066. $product_dict[$product_name] = [
  7067. 'url' => getProp($product, 'url'),
  7068. 'voice_prompt' => getProp($product, 'voice_prompt')
  7069. ];
  7070. }
  7071. }
  7072. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7073. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7074. $reference_images = [];
  7075. $product_index_map = []; // 产品名称 => 图片序号的映射
  7076. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7077. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7078. $current_index = 1;
  7079. if (!empty($matches[1])) {
  7080. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7081. $seen_products = []; // 用于去重
  7082. foreach ($matches[1] as $product_name) {
  7083. // 跳过已处理的产品
  7084. if (isset($seen_products[$product_name])) {
  7085. continue;
  7086. }
  7087. $seen_products[$product_name] = true;
  7088. // 检查产品是否在字典中
  7089. if (isset($product_dict[$product_name])) {
  7090. $url = $product_dict[$product_name]['url'];
  7091. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7092. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7093. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7094. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7095. }
  7096. // 只有URL非空才分配序号和添加到参考图片
  7097. if (!empty($url)) {
  7098. // 检查URL是否已经在reference_images中(去重)
  7099. if (!in_array($url, $reference_images)) {
  7100. $reference_images[] = $url;
  7101. $product_index_map[$product_name] = $current_index;
  7102. $current_index++;
  7103. } else {
  7104. // URL重复,找到已有的序号
  7105. $existing_index = array_search($url, $reference_images) + 1;
  7106. $product_index_map[$product_name] = $existing_index;
  7107. }
  7108. } else {
  7109. // URL为空,不分配序号(后续直接去掉{})
  7110. $product_index_map[$product_name] = 0;
  7111. }
  7112. } else {
  7113. // 产品不在字典中,不分配序号
  7114. $product_index_map[$product_name] = 0;
  7115. }
  7116. }
  7117. }
  7118. // 第二步:替换内容中的 {产品名称}
  7119. $processedContent = $actContent;
  7120. foreach ($product_index_map as $product_name => $index) {
  7121. $escaped_name = preg_quote($product_name, '/');
  7122. if ($index > 0) {
  7123. // 有图片,替换为:产品名称(图X)
  7124. $replacement = $product_name . '<图片' . $index . '>';
  7125. } else {
  7126. // 无图片,只保留产品名称
  7127. $replacement = $product_name;
  7128. }
  7129. // 替换所有 {产品名称} 为处理后的格式
  7130. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7131. }
  7132. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7133. foreach ($products as $product) {
  7134. $product_name = getProp($product, 'product_name');
  7135. $voice_prompt = getProp($product, 'voice_prompt');
  7136. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7137. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7138. break; // 找到旁白后退出循环
  7139. }
  7140. }
  7141. // 第四步:将voice_prompt信息添加到内容最前面
  7142. $voice_prompt_prefix = '';
  7143. if (!empty($voice_prompts)) {
  7144. $voice_prompt_prefix .= implode('', $voice_prompts);
  7145. }
  7146. // 旁白的voice_prompt放在最后
  7147. if (!empty($narrator_voice_prompt)) {
  7148. $voice_prompt_prefix .= $narrator_voice_prompt;
  7149. }
  7150. // 如果有voice_prompt信息,添加到内容开头
  7151. if (!empty($voice_prompt_prefix)) {
  7152. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7153. }
  7154. return [
  7155. 'content' => $processedContent,
  7156. 'reference_images' => $reference_images
  7157. ];
  7158. }
  7159. public function saveActVideoGenerateParams($data) {
  7160. $episode_id = getProp($data, 'episode_id');
  7161. $model = getProp($data, 'video_model');
  7162. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7163. Utils::throwError('20003:该模型不可用');
  7164. }
  7165. if (!$model) {
  7166. // 使用默认模型
  7167. $model = 'zhizhen-20';
  7168. }
  7169. // 验证模型是否在可用模型表中
  7170. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7171. Utils::throwError('20003:该模型已不可用,请更换!');
  7172. }
  7173. $video_resolution = getProp($data, 'video_resolution', '720p');
  7174. $ratio = getProp($data, 'ratio');
  7175. if (!$ratio) $ratio = '9:16';
  7176. return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7177. 'video_model' => $model,
  7178. 'video_resolution' => $video_resolution,
  7179. 'ratio' => $ratio,
  7180. 'updated_at' => date('Y-m-d H:i:s')
  7181. ]);
  7182. }
  7183. public function confirmActs($data) {
  7184. $episode_id = getProp($data, 'episode_id');
  7185. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7186. if (!$episode) {
  7187. Utils::throwError('20003:分集不存在');
  7188. }
  7189. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7190. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7191. // 获取所有片段数据
  7192. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7193. // 构建角色和场景名称数组
  7194. $role_names = [];
  7195. $scene_names = [];
  7196. foreach ($roles as $role) {
  7197. $role_name = getProp($role, 'role');
  7198. if ($role_name && $role_name != '旁白') {
  7199. $role_names[] = $role_name;
  7200. }
  7201. }
  7202. foreach ($scenes as $scene) {
  7203. $scene_name = getProp($scene, 'scene');
  7204. if ($scene_name) {
  7205. $scene_names[] = $scene_name;
  7206. }
  7207. }
  7208. // 按照字符长度降序排序,确保先匹配长的名称(避免部分匹配问题)
  7209. usort($role_names, function($a, $b) {
  7210. return mb_strlen($b) - mb_strlen($a);
  7211. });
  7212. usort($scene_names, function($a, $b) {
  7213. return mb_strlen($b) - mb_strlen($a);
  7214. });
  7215. try {
  7216. DB::beginTransaction();
  7217. // 处理每个片段
  7218. foreach ($acts as $act) {
  7219. $act_content = getProp($act, 'act_content');
  7220. if (!$act_content) continue;
  7221. $processed_content = $act_content;
  7222. // 标记已处理的位置,避免重复标记
  7223. $marked_positions = [];
  7224. // 先匹配场景(在"场景:"后面)
  7225. foreach ($scene_names as $scene_name) {
  7226. // 转义特殊字符
  7227. $escaped_scene = preg_quote($scene_name, '/');
  7228. // 匹配场景:后面的场景名称(可能换行,也可能不换行)
  7229. $pattern = '/(场景:[\s\r\n]*)(' . $escaped_scene . ')/u';
  7230. $processed_content = preg_replace_callback($pattern, function($matches) use (&$marked_positions) {
  7231. $full_match = $matches[0];
  7232. $prefix = $matches[1];
  7233. $scene_name = $matches[2];
  7234. // 检查是否已经被标记
  7235. if (strpos($scene_name, '{') === false && strpos($scene_name, '}') === false) {
  7236. return $prefix . '{' . $scene_name . '}';
  7237. }
  7238. return $full_match;
  7239. }, $processed_content);
  7240. }
  7241. // 再匹配角色名称(只在"画面:"部分)
  7242. foreach ($role_names as $role_name) {
  7243. // 转义特殊字符
  7244. $escaped_role = preg_quote($role_name, '/');
  7245. // 只匹配"画面:"开始到换行之前的内容
  7246. $pattern = '/(画面:[^\n]*)/u';
  7247. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
  7248. $line = $matches[1]; // 整行"画面:xxxxx"
  7249. // 在这一行中匹配所有角色名(避免重复标记)
  7250. $new_line = preg_replace(
  7251. '/(?<![{])(' . $escaped_role . ')(?![}])/u',
  7252. '{$1}',
  7253. $line
  7254. );
  7255. return $new_line;
  7256. }, $processed_content);
  7257. }
  7258. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7259. $shot_counter = 0;
  7260. $processed_content = preg_replace_callback(
  7261. '/【(?:镜头|分镜)(\d+)】/u',
  7262. function($matches) use (&$shot_counter) {
  7263. $shot_counter++;
  7264. return '【镜头' . $shot_counter . '】';
  7265. },
  7266. $processed_content
  7267. );
  7268. // 更新数据库
  7269. $boolen = DB::table('mp_episode_segments')
  7270. ->where('id', $act->id)
  7271. ->update([
  7272. 'act_show_content' => $processed_content,
  7273. 'updated_at' => date('Y-m-d H:i:s')
  7274. ]);
  7275. if (!$boolen) {
  7276. Utils::throwError('20003:片段处理失败');
  7277. }
  7278. }
  7279. }catch (\Exception $e) {
  7280. DB::rollBack();
  7281. Utils::throwError('20003:'.$e->getMessage());
  7282. }
  7283. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7284. 'is_generated' => 1,
  7285. 'updated_at' => date('Y-m-d H:i:s')
  7286. ]);
  7287. if (!$boolen1) {
  7288. DB::rollBack();
  7289. Utils::throwError('20003:分集处理失败!');
  7290. }
  7291. DB::commit();
  7292. // 重新查询更新后的片段数据
  7293. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7294. // 合并角色、场景和extra_products作为products,统一字段名为product_name
  7295. // extra_products优先级更高,会覆盖同名的roles和scenes
  7296. $products = [];
  7297. // 先处理角色数组
  7298. foreach ($roles as $role) {
  7299. $product = $role;
  7300. // 将role字段重命名为product_name
  7301. if (isset($product['role'])) {
  7302. $product['product_name'] = $product['role'];
  7303. unset($product['role']);
  7304. }
  7305. $product['product'] = 1; // 标记类型为角色
  7306. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7307. }
  7308. // 处理场景数组
  7309. foreach ($scenes as $scene) {
  7310. $product = $scene;
  7311. // 将scene字段重命名为product_name
  7312. if (isset($product['scene'])) {
  7313. $product['product_name'] = $product['scene'];
  7314. unset($product['scene']);
  7315. }
  7316. $product['product'] = 2; // 标记类型为场景
  7317. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7318. }
  7319. // extra_products优先级更高,直接覆盖同名的roles和scenes
  7320. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  7321. foreach ($extra_products as $extra_product) {
  7322. $product_name = getProp($extra_product, 'product_name');
  7323. if ($product_name) {
  7324. $products[$product_name] = $extra_product; // 覆盖同名数据
  7325. }
  7326. }
  7327. // 重新索引数组(去除key)
  7328. $products = array_values($products);
  7329. // 构建返回的acts数组
  7330. $return_acts = [];
  7331. foreach ($acts as $act) {
  7332. $return_acts[] = [
  7333. 'act_id' => getProp($act, 'id'),
  7334. 'act_number' => getProp($act, 'act_number'),
  7335. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  7336. 'act_show_content' => getProp($act, 'act_show_content'),
  7337. 'video_url' => getProp($act, 'video_url'),
  7338. 'video_duration' => getProp($act, 'video_duration'),
  7339. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  7340. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  7341. ];
  7342. }
  7343. return [
  7344. 'anime_id' => getProp($episode, 'anime_id'),
  7345. 'episode_id' => $episode_id,
  7346. 'title' => getProp($episode, 'title'),
  7347. 'episode_number' => getProp($episode, 'episode_number'),
  7348. 'is_generated' => getProp($episode, 'is_generated'),
  7349. 'products' => $products,
  7350. 'acts' => $return_acts
  7351. ];
  7352. }
  7353. }