AnimeService.php 385 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Services\AIGeneration\AIImageGenerationService;
  9. use App\Services\AIGeneration\AIVideoGenerationService;
  10. use App\Services\DeepSeek\DeepSeekService;
  11. use App\Services\PointsService;
  12. use Dflydev\DotAccessData\Util;
  13. use GuzzleHttp\Client;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Log;
  16. use Illuminate\Support\Facades\Redis;
  17. use OSS\Core\OssException;
  18. use OSS\OssClient;
  19. class AnimeService
  20. {
  21. protected $aiImageGenerationService;
  22. protected $aiVideoGenerationService;
  23. protected $DeepSeekService;
  24. protected $pointsService;
  25. private $url;
  26. private $api_key;
  27. private $headers;
  28. public function __construct(
  29. AIImageGenerationService $aiImageGenerationService,
  30. AIVideoGenerationService $aiVideoGenerationService,
  31. DeepSeekService $DeepSeekService,
  32. PointsService $pointsService
  33. ) {
  34. $this->aiImageGenerationService = $aiImageGenerationService;
  35. $this->aiVideoGenerationService = $aiVideoGenerationService;
  36. $this->DeepSeekService = $DeepSeekService;
  37. $this->pointsService = $pointsService;
  38. $this->url = 'https://api.deepseek.com/chat/completions';
  39. $this->api_key = env('DEEPSEEK_API_KEY');
  40. $this->headers = [
  41. 'Authorization' => 'Bearer '.$this->api_key,
  42. 'Content-Type' => 'application/json; charset=UTF-8'
  43. ];
  44. }
  45. /**
  46. * 构建统一的分镜数据结构(episodeInfo格式)
  47. * @param array $segments 分镜数据数组
  48. * @return array 返回包含acts和total_duration的数组
  49. */
  50. public function buildEpisodeSegmentsStructure($segments) {
  51. $acts = [];
  52. $totalDuration = 0; // 初始化总时长
  53. foreach($segments as $segment) {
  54. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  55. $videoDuration = getProp($segment, 'video_duration');
  56. $audioDuration = getProp($segment, 'audio_duration');
  57. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  58. $totalDuration += floatval($videoDuration);
  59. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  60. $totalDuration += floatval($audioDuration);
  61. } else {
  62. $totalDuration += 5; // 默认5秒
  63. }
  64. $segment_content = getProp($segment, 'segment_content');
  65. // 判断是否有尾帧描述,如果有则去掉这部分内容
  66. if (strpos($segment_content, '尾帧') !== false) {
  67. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  68. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  69. }
  70. // 构建分镜信息
  71. $segmentInfo = [
  72. 'segment_id' => getProp($segment, 'segment_id'),
  73. 'segment_number' => getProp($segment, 'segment_number'),
  74. 'segment_content' => $segment_content,
  75. 'description' => getProp($segment, 'description'),
  76. 'composition' => getProp($segment, 'composition'),
  77. 'camera_movement' => getProp($segment, 'camera_movement'),
  78. 'voice_actor' => getProp($segment, 'voice_actor'),
  79. 'dialogue' => getProp($segment, 'dialogue'),
  80. 'frame_type' => getProp($segment, 'frame_type'),
  81. 'scene' => getProp($segment, 'scene'),
  82. 'characters' => getProp($segment, 'characters'),
  83. 'tail_frame' => getProp($segment, 'tail_frame'),
  84. 'emotion' => getProp($segment, 'emotion'),
  85. 'emotion_type' => getProp($segment, 'emotion_type'),
  86. 'gender' => getProp($segment, 'gender'),
  87. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  88. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  89. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  90. 'pitch' => getProp($segment, 'pitch'),
  91. 'voice_name' => getProp($segment, 'voice_name'),
  92. 'voice_type' => getProp($segment, 'voice_type'),
  93. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  94. 'img_url' => getProp($segment, 'img_url'),
  95. 'audio_url' => getProp($segment, 'audio_url'),
  96. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  97. 'video_url' => getProp($segment, 'video_url'),
  98. 'video_duration' => getProp($segment, 'video_duration', 0),
  99. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  100. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  101. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  102. 'current_type' => getProp($segment, 'current_type'),
  103. ];
  104. $actNumber = getProp($segment, 'act_number');
  105. if (isset($acts[$actNumber])) {
  106. $acts[$actNumber]['segments'][] = $segmentInfo;
  107. } else {
  108. $acts[$actNumber] = [
  109. 'act_number' => $actNumber,
  110. 'act_title' => getProp($segment, 'act_title'),
  111. 'act_duration' => getProp($segment, 'act_duration'),
  112. 'segments' => [$segmentInfo]
  113. ];
  114. }
  115. }
  116. return [
  117. 'acts' => array_values($acts),
  118. 'total_duration' => intval(round($totalDuration))
  119. ];
  120. }
  121. /**
  122. * 构建统一的分段数据结构(episodeInfoForAce格式)
  123. * @param array $segments 分段数据数组
  124. * @return array 返回包含acts和total_duration的数组
  125. */
  126. public function buildEpisodeActsStructureForAce($segments) {
  127. $acts = [];
  128. $totalDuration = 0; // 初始化总时长
  129. foreach($segments as $segment) {
  130. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  131. $videoDuration = getProp($segment, 'video_duration');
  132. $actDuration = getProp($segment, 'act_duration');
  133. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  134. $totalDuration += floatval($videoDuration);
  135. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  136. $totalDuration += floatval($actDuration);
  137. } else {
  138. $totalDuration += 5; // 默认5秒
  139. }
  140. // 构建分镜信息
  141. $segmentInfo = [
  142. 'act_id' => getProp($segment, 'id'),
  143. 'act_number' => getProp($segment, 'act_number'),
  144. 'act_title' => getProp($segment, 'act_title'),
  145. 'act_duration' => getProp($segment, 'act_duration'),
  146. 'act_content' => getProp($segment, 'act_content'),
  147. 'video_url' => getProp($segment, 'video_url'),
  148. 'video_duration' => getProp($segment, 'video_duration', 0),
  149. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  150. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  151. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  152. 'current_type' => getProp($segment, 'current_type'),
  153. ];
  154. $acts[] = $segmentInfo;
  155. }
  156. return [
  157. 'acts' => array_values($acts),
  158. 'total_duration' => intval(round($totalDuration))
  159. ];
  160. }
  161. /**
  162. * 验证画面比例是否有效
  163. * @param string $ratio 画面比例
  164. * @return bool
  165. */
  166. public function validateRatio($ratio) {
  167. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  168. }
  169. /**
  170. * 获取画面比例对应的宽高
  171. * @param string $ratio 画面比例
  172. * @return array ['width' => int, 'height' => int]
  173. * @throws \Exception
  174. */
  175. private function getRatioDimensions($ratio) {
  176. if ($ratio && !$this->validateRatio($ratio)) {
  177. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  178. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  179. }
  180. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  181. }
  182. public function createAnime($data) {
  183. $uid = Site::getUid();
  184. $input_art_style = getProp($data, 'art_style');
  185. $file = getProp($data, 'file');
  186. $content = getProp($data, 'content', '');
  187. $bid = getProp($data, 'bid', 0);
  188. $script_id = getProp($data, 'script_id', 0);
  189. $ace_mode = getProp($data, 'ace_mode', 0);
  190. $extra_products = getProp($data, 'products', []);
  191. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  192. if (!is_array($extra_products)) {
  193. Utils::throwError('20003:传入的资产格式不正确');
  194. }
  195. // 替换美术风格
  196. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  197. // 提取文件内容
  198. if ($file) {
  199. $content = $this->DeepSeekService->extractFileContent($file);
  200. if (!$content) {
  201. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  202. }
  203. } elseif ($script_id) {
  204. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  205. if (!$content) {
  206. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  207. }
  208. } elseif ($bid) {
  209. $content = $this->DeepSeekService->getContentByBid($bid);
  210. if (!$content) {
  211. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  212. }
  213. } elseif ($content) {
  214. $content = filterContent($content);
  215. }else {
  216. $content = '';
  217. }
  218. $anime_data = [
  219. 'user_id' => $uid,
  220. 'anime_name' => '新剧本策划',
  221. 'is_multi' => getProp($data, 'is_multi', 1),
  222. 'content' => $content,
  223. 'art_style_type' => $input_art_style,
  224. 'ace_mode' => $ace_mode,
  225. 'script_id' => $script_id,
  226. 'extra_products' => json_encode($extra_products, 256),
  227. 'created_at' => date('Y-m-d H:i:s'),
  228. 'updated_at' => date('Y-m-d H:i:s'),
  229. ];
  230. // 处理文本模型
  231. $model = getProp($data, 'model');
  232. if (!$model) {
  233. // 用户没有输入,使用默认值
  234. $model = 'deepseek-v4-pro';
  235. }
  236. // 验证模型是否在可用模型表中
  237. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  238. $model = 'deepseek-v4-pro';
  239. }
  240. $anime_data['model'] = $model;
  241. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  242. return DB::table('mp_animes')->insertGetId($anime_data);
  243. }
  244. public function chatList($data) {
  245. $uid = Site::getUid();
  246. $anime_name = getProp($data, 'anime_name');
  247. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  248. if ($anime_name) {
  249. $query->where('anime_name', 'like', "%$anime_name%");
  250. }
  251. return $query->orderBy('id', 'desc')->paginate();
  252. }
  253. public function chatHistory($data) {
  254. $anime_id = getProp($data, 'anime_id');
  255. $sequence = getProp($data, 'sequence', 0);
  256. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  257. $query = DB::table('mp_anime_records as ar')->leftJoin('mp_anime_episodes as ae', 'ar.episode_id', '=', 'ae.id')->where('ar.anime_id', $anime_id)
  258. ->where('ar.sequence', $sequence)->where('segment_id', 0)->where('act_id', 0)->select('ar.role', 'ar.content', 'ar.created_at', 'ar.episode_id', 'ae.title as episode_title', 'ae.created_at as episode_created_at');
  259. return $query->orderBy('ar.id')->get()->map(function ($value) {
  260. $value = (array)$value;
  261. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  262. $value['created_at'] = transDate($value['created_at']);
  263. $value['episode_created_at'] = transDate($value['episode_created_at']);
  264. return $value;
  265. })->toArray();
  266. }
  267. public function batchSetRoleImg($data) {
  268. $episode_id = getProp($data, 'episode_id');
  269. if (!$episode_id) Utils::throwError('1002:请选择分集');
  270. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  271. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  272. $art_style = getProp($episode, 'art_style');
  273. $anime_id = getProp($episode, 'anime_id');
  274. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  275. $art_style_type = getProp($anime, 'art_style_type');
  276. $character_prefix = '';
  277. $scene_prefix = '';
  278. if ($art_style_type) {
  279. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  280. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  281. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  282. }
  283. foreach ($roles as &$role) {
  284. $role_name = getProp($role, 'role');
  285. if ($role_name == '旁白') continue;
  286. // 优先使用 pic_prompt,如果没有则使用 description
  287. $pic_prompt = getProp($role, 'pic_prompt');
  288. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  289. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  290. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  291. // 参考图地址
  292. $ref_img_url = getProp($role, 'url');
  293. if ($ref_img_url) continue; // 已有图片则跳过
  294. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  295. try {
  296. $params = [
  297. 'prompt' => $description,
  298. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  299. ];
  300. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  301. $task_id = $task->id;
  302. if (!$task_id) {
  303. Utils::throwError("20003:角色({$role_name})生成图片失败");
  304. }
  305. $role['task_id'] = $task_id;
  306. $role['task_status'] = 'processing';
  307. } catch (\Exception $e) {
  308. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  309. Utils::throwError("20003:" . $e->getMessage());
  310. }
  311. }
  312. // 保存角色信息
  313. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  314. 'roles' => json_encode($roles, 256),
  315. 'generate_status' => '执行中',
  316. 'generate_at' => date('Y-m-d H:i:s'),
  317. 'updated_at' => date('Y-m-d H:i:s')
  318. ]);
  319. if (!$boolen) {
  320. Utils::throwError('20003:保存角色信息失败');
  321. }
  322. return $boolen;
  323. }
  324. public function batchSetSceneImg($data) {
  325. $episode_id = getProp($data, 'episode_id');
  326. if (!$episode_id) Utils::throwError('1002:请选择分集');
  327. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  328. $scenes = json_decode(getProp($episode, 'scenes'), true);
  329. $art_style = getProp($episode, 'art_style');
  330. $target_scene = getProp($data, 'target_scene');
  331. $anime_id = getProp($episode, 'anime_id');
  332. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  333. $art_style_type = getProp($anime, 'art_style_type');
  334. $character_prefix = '';
  335. $scene_prefix = '';
  336. if ($art_style_type) {
  337. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  338. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  339. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  340. }
  341. foreach ($scenes as &$scene) {
  342. $scene_name = getProp($scene, 'scene');
  343. if ($scene_name != $target_scene) continue;
  344. // 优先使用 pic_prompt,如果没有则使用 description
  345. $pic_prompt = getProp($scene, 'pic_prompt');
  346. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  347. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  348. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  349. // 参考图地址
  350. $ref_img_url = getProp($scene, 'url');
  351. if ($ref_img_url) continue; // 已有图片则跳过
  352. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  353. try {
  354. $params = [
  355. 'prompt' => $description,
  356. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  357. ];
  358. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  359. $task_id = $task->id;
  360. if (!$task_id) {
  361. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  362. }
  363. $scene['task_id'] = $task_id;
  364. $scene['task_status'] = 'processing';
  365. } catch (\Exception $e) {
  366. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  367. Utils::throwError("20003:" . $e->getMessage());
  368. }
  369. }
  370. // 保存场景信息
  371. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  372. 'scenes' => json_encode($scenes, 256),
  373. 'generate_status' => '执行中',
  374. 'generate_at' => date('Y-m-d H:i:s'),
  375. 'updated_at' => date('Y-m-d H:i:s')
  376. ]);
  377. if (!$boolen) {
  378. Utils::throwError('20003:保存角色信息失败');
  379. }
  380. return $boolen;
  381. }
  382. public function editAnime($data) {
  383. $anime_id = getProp($data, 'anime_id');
  384. $anime_name = trim(getProp($data, 'anime_name'));
  385. // 确认对话名称唯一性
  386. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  387. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  388. }
  389. if (!$anime_id || !$anime_name) {
  390. Utils::throwError('20003:参数异常');
  391. }
  392. return DB::table('mp_animes')->where('id', $anime_id)->update([
  393. 'anime_name' => $anime_name,
  394. 'updated_at' => date('Y-m-d H:i:s')
  395. ]);
  396. // $script_arr =getProp($data, 'script', []);
  397. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  398. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  399. // $anime_id = getProp($data, 'anime_id');
  400. // try {
  401. // DB::beginTransaction();
  402. // $table_data = [
  403. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  404. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  405. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  406. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  407. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  408. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  409. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  410. // 'status' => 3,
  411. // 'start_episode_sequence' => $start_episode_sequence,
  412. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  413. // 'episode_num' => count($script_arr['episodes']),
  414. // 'updated_at' => date('Y-m-d H:i:s')
  415. // ];
  416. // // 保存剧本内容
  417. // if (!empty($anime_id)) {
  418. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  419. // if (!$boolen) {
  420. // dLog('anime')->info('对话保存失败', $table_data);
  421. // Utils::throwError('20003:对话保存失败');
  422. // }
  423. // }else {
  424. // $table['created_at'] = $table_data['updated_at'];
  425. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  426. // if (!$anime_id) {
  427. // dLog('anime')->info('对话保存失败', $table_data);
  428. // Utils::throwError('20003:对话保存失败');
  429. // }
  430. // }
  431. // // 保存分集内容
  432. // // 删除历史分集内容
  433. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  434. // $episodes = [];
  435. // $sequence = 1;
  436. // foreach ($script_arr['episodes'] as $episode) {
  437. // $segment_number = 1;
  438. // foreach($episode['segments'] as $segment) {
  439. // $episodes[] = [
  440. // 'anime_id' => $anime_id,
  441. // 'episode_number' => $episode['episode_number'],
  442. // 'title' => $episode['title'],
  443. // // 'content' => $episode['content'],
  444. // 'content' => '',
  445. // 'segment_number' => $segment_number,
  446. // 'segment_content' => $segment['segment_content'],
  447. // 'sequence' => $sequence,
  448. // 'created_at' => date('Y-m-d H:i:s'),
  449. // 'updated_at' => date('Y-m-d H:i:s')
  450. // ];
  451. // $sequence++;
  452. // $segment_number++;
  453. // }
  454. // }
  455. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  456. // if (!$boolen2) {
  457. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  458. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  459. // Utils::throwError('20003:分集内容保存失败');
  460. // }
  461. // } catch (\Exception $e) {
  462. // DB::rollBack();
  463. // Utils::throwError('20003:'.$e->getMessage());
  464. // }
  465. // DB::commit();
  466. // return true;
  467. }
  468. public function delAnime($data) {
  469. $anime_id = getProp($data, 'anime_id');
  470. if (!$anime_id) {
  471. Utils::throwError('20003:请选择剧本');
  472. }
  473. return DB::table('mp_animes')->where('id', $anime_id)->update([
  474. 'is_deleted' => 1,
  475. 'updated_at' => date('Y-m-d H:i:s')
  476. ]);
  477. }
  478. public function animeDetail($data) {
  479. $uid = Site::getUid();
  480. $anime_id = getProp($data, 'anime_id');
  481. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  482. ->selectRaw('id as anime_id, anime_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, remark, generate_status, created_at, ace_mode, end_episode_sequence')->first();
  483. if (!$anime) Utils::throwError('20003:权限不足');
  484. $anime = (array)$anime;
  485. $anime['roles'] = json_decode($anime['roles']);
  486. $anime['scenes'] = json_decode($anime['scenes']);
  487. // 获取分集信息
  488. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  489. ->select('id as episode_id', 'episode_number', 'title', 'is_generated', DB::raw("(select es.img_url from mp_episode_segments as es where es.episode_id = mp_anime_episodes.id order by es.segment_number limit 1) as first_frame_url"))
  490. ->orderBy('episode_number')->get()->map(function ($value) {
  491. return (array)$value;
  492. })->toArray();
  493. $anime['episodes'] = $episodes;
  494. return $anime;
  495. }
  496. public function episodeInfo($data) {
  497. $uid = Site::getUid();
  498. $anime_id = getProp($data, 'anime_id');
  499. $episode_id = getProp($data, 'episode_id');
  500. if (!$anime_id || !$episode_id) {
  501. Utils::throwError('1002:请选择剧集');
  502. }
  503. // 验证用户权限
  504. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  505. if (!$anime) Utils::throwError('20003:权限不足');
  506. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->first();
  507. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  508. $episode = (array)$episode;
  509. $episode['roles'] = json_decode($episode['roles'], true);
  510. // foreach($episode['roles'] as &$item) {
  511. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  512. // }
  513. $episode['scenes'] = json_decode($episode['scenes'], true);
  514. // foreach($episode['scenes'] as &$item) {
  515. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  516. // }
  517. // 获取分镜信息
  518. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  519. ->select('*')->get()->map(function ($value) {
  520. return (array)$value;
  521. })->toArray();
  522. // 使用公共方法构建分镜结构
  523. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  524. $episode['acts'] = $segmentsStructure['acts'];
  525. $episode['total_duration'] = $segmentsStructure['total_duration'];
  526. return $episode;
  527. }
  528. public function episodeInfoForAce($data) {
  529. $anime_id = getProp($data, 'anime_id');
  530. $episode_id = getProp($data, 'episode_id');
  531. if (!$anime_id || !$episode_id) {
  532. Utils::throwError('1002:请选择剧集');
  533. }
  534. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'props', 'is_generated')->first();
  535. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  536. $episode = (array)$episode;
  537. $episode['roles'] = json_decode($episode['roles'], true);
  538. // foreach($episode['roles'] as &$item) {
  539. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  540. // }
  541. $episode['scenes'] = json_decode($episode['scenes'], true);
  542. // foreach($episode['scenes'] as &$item) {
  543. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  544. // }
  545. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  546. // 获取分镜信息
  547. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  548. ->select('*')->get()->map(function ($value) {
  549. return (array)$value;
  550. })->toArray();
  551. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  552. $episode['acts'] = $segmentsStructure['acts'];
  553. $episode['total_duration'] = $segmentsStructure['total_duration'];
  554. return $episode;
  555. }
  556. public function segmentInfo($data) {
  557. $uid = Site::getUid();
  558. $segment_id = getProp($data, 'segment_id');
  559. if (!$segment_id) {
  560. Utils::throwError('1002:请选择分镜');
  561. }
  562. // 获取分镜信息
  563. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  564. // 验证用户权限
  565. if ($segment) {
  566. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  567. if (!$anime) Utils::throwError('20003:权限不足');
  568. }
  569. $result = [
  570. 'segment_id' => getProp($segment, 'segment_id'),
  571. 'segment_number' => getProp($segment, 'segment_number'),
  572. 'segment_content' => getProp($segment, 'segment_content'),
  573. 'description' => getProp($segment, 'description'),
  574. 'composition' => getProp($segment, 'composition'),
  575. 'camera_movement' => getProp($segment, 'camera_movement'),
  576. 'voice_actor' => getProp($segment, 'voice_actor'),
  577. 'dialogue' => getProp($segment, 'dialogue'),
  578. 'frame_type' => getProp($segment, 'frame_type'),
  579. 'scene' => getProp($segment, 'scene'),
  580. 'characters' => getProp($segment, 'characters'),
  581. 'tail_frame' => getProp($segment, 'tail_frame'),
  582. 'emotion' => getProp($segment, 'emotion'),
  583. 'emotion_type' => getProp($segment, 'emotion_type'),
  584. 'gender' => getProp($segment, 'gender'),
  585. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  586. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  587. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  588. 'pitch' => getProp($segment, 'pitch'),
  589. 'voice_name' => getProp($segment, 'voice_name'),
  590. 'voice_type' => getProp($segment, 'voice_type'),
  591. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  592. 'img_url' => getProp($segment, 'img_url'),
  593. 'video_url' => getProp($segment, 'video_url'),
  594. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  595. ];
  596. return $result;
  597. }
  598. public function copyEpisodeVersion($data) {
  599. $episode_id = getProp($data, 'episode_id');
  600. $uid = Site::getUid();
  601. $cpid = Site::getCpid();
  602. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  603. if (!$episode) Utils::throwError('20003:该剧集不存在');
  604. $episode = (array)$episode;
  605. $anime_id = $episode['anime_id'];
  606. $episode_number = $episode['episode_number'];
  607. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  608. $sequence = $count + 1;
  609. unset($episode['id']);
  610. $now = date('Y-m-d H:i:s');
  611. $episode['created_at'] = $now;
  612. $episode['updated_at'] = $now;
  613. $episode['is_default'] = 1;
  614. // 获取版本中含有"(副本"字样的个数
  615. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  616. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  617. $episode['sequence'] = $sequence;
  618. $episode['is_generated'] = 0;
  619. $episode['cpid'] = $cpid;
  620. // 获取ace_mode
  621. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  622. try {
  623. DB::beginTransaction();
  624. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  625. // 新增副本
  626. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  627. if (!$new_episode_id) {
  628. Utils::throwError('20003:创建副本失败!');
  629. }
  630. // 获取分镜数据并准备插入
  631. $segments_for_insert = DB::table('mp_episode_segments')
  632. ->select('anime_id', 'episode_number', 'act_number', 'act_title', 'act_duration', 'act_content', 'segment_number', 'segment_content', 'description', 'composition', 'camera_movement', 'voice_actor', 'dialogue', 'frame_type', 'scene', 'characters', 'tail_frame', 'voice_name', 'voice_type', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  633. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  634. $item = (array)$item;
  635. $item['episode_id'] = $new_episode_id;
  636. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  637. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  638. return $item;
  639. })->toArray();
  640. // 写入分镜数据
  641. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  642. if (!$boolen2) {
  643. Utils::throwError('20003:写入分镜数据失败!');
  644. }
  645. // 写入对话历史
  646. $records = [
  647. [
  648. 'uid' => $uid,
  649. 'anime_id' => $anime_id,
  650. 'role' => 'user',
  651. 'content' => '创建副本',
  652. 'sequence' => $episode_number,
  653. 'episode_id' => $new_episode_id,
  654. 'created_at' => $now,
  655. 'updated_at' => $now
  656. ],
  657. [
  658. 'uid' => $uid,
  659. 'anime_id' => $anime_id,
  660. 'role' => 'assistant',
  661. 'content' => '好的,已为您创建副本',
  662. 'sequence' => $episode_number,
  663. 'episode_id' => $new_episode_id,
  664. 'created_at' => $now,
  665. 'updated_at' => $now
  666. ]
  667. ];
  668. $boolen3 = DB::table('mp_anime_records')->insert($records);
  669. if (!$boolen3) {
  670. Utils::throwError('20003:对话记录保存失败');
  671. }
  672. }catch (\Exception $e) {
  673. DB::rollBack();
  674. Utils::throwError('20003:'.$e->getMessage());
  675. }
  676. DB::commit();
  677. // 构建与 episodeInfo 方法一致的返回数据结构
  678. $result = [
  679. 'episode_id' => $new_episode_id,
  680. 'anime_id' => $anime_id,
  681. 'episode_number' => $episode_number,
  682. 'title' => $episode['title'],
  683. 'intro' => $episode['intro'],
  684. 'art_style' => $episode['art_style'],
  685. 'roles' => json_decode($episode['roles'], true),
  686. 'scenes' => json_decode($episode['scenes'], true),
  687. 'is_generated' => (int)$episode['is_generated']
  688. ];
  689. if ((int)$ace_mode === 1) {
  690. // 获取分镜信息
  691. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  692. ->select('*')->get()->map(function ($value) {
  693. return (array)$value;
  694. })->toArray();
  695. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  696. }else {
  697. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  698. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  699. }
  700. $result['acts'] = $segmentsStructure['acts'];
  701. $result['total_duration'] = $segmentsStructure['total_duration'];
  702. return $result;
  703. }
  704. public function episodeVersions($data) {
  705. $anime_id = getProp($data, 'anime_id');
  706. $episode_id = getProp($data, 'episode_id');
  707. if (!$anime_id || !$episode_id) {
  708. Utils::throwError('1002:请选择剧集');
  709. }
  710. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  711. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->select('id as episode_id', 'anime_id', 'episode_number', 'sequence', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->orderBy('sequence', 'desc')->get()->map(function($value) {
  712. return (array)$value;
  713. })->toArray();
  714. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  715. foreach($episodes as &$episode) {
  716. $episode['version'] = 'V'.$episode['sequence'];
  717. $episode['roles'] = json_decode($episode['roles'], true);
  718. $episode['scenes'] = json_decode($episode['scenes'], true);
  719. // 获取分镜信息
  720. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  721. ->select('*')->get()->map(function ($value) {
  722. return (array)$value;
  723. })->toArray();
  724. // 使用公共方法构建分镜结构
  725. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  726. $episode['acts'] = $segmentsStructure['acts'];
  727. $episode['total_duration'] = $segmentsStructure['total_duration'];
  728. }
  729. return $episodes;
  730. }
  731. public function bindEpisodeVersion($data) {
  732. $episode_id = getProp($data, 'episode_id');
  733. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  734. if (!$episode) Utils::throwError('20003:该剧集不存在');
  735. $episode = (array)$episode;
  736. if ((int)$episode['is_default'] === 1) return true;
  737. try {
  738. DB::beginTransaction();
  739. // 移除is_default标志
  740. $boolen = DB::table('mp_anime_episodes')->where('anime_id', $episode['anime_id'])->where('episode_number', $episode['episode_number'])->update(['is_default' => 0, 'updated_at'=>date('Y-m-d H:i:s')]);
  741. if (!$boolen) {
  742. Utils::throwError('20003:更新失败!');
  743. }
  744. // 绑定副本
  745. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  746. if (!$boolen2) {
  747. Utils::throwError('20003:绑定失败!');
  748. }
  749. }catch (\Exception $e) {
  750. DB::rollBack();
  751. Utils::throwError('20003:'.$e->getMessage());
  752. }
  753. DB::commit();
  754. return true;
  755. }
  756. public function chatChangeImg($data) {
  757. $segment_id = getProp($data, 'segment_id');
  758. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  759. $prompt = getProp($data, 'prompt');
  760. if (!$prompt || !$segment_id) {
  761. Utils::throwError('1002:请输入提示词,并且选择分镜');
  762. }
  763. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  764. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  765. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  766. else $ref_img_url = '';
  767. // $ref_img_url = '';
  768. if (empty($prompt)) {
  769. if (empty($ref_img_url)) {
  770. $prompt = getProp($segment, 'segment_content');
  771. }else {
  772. $prompt = '请根据图片生成';
  773. }
  774. }
  775. $anime_id = getProp($segment, 'anime_id');
  776. $episode_id = getProp($segment, 'episode_id');
  777. $episode_number = getProp($segment, 'episode_number');
  778. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  779. $ratio = getProp($data, 'ratio');
  780. if (!$ratio) {
  781. $ratio = getProp($episode, 'ratio');
  782. if (!$ratio) $ratio = '9:16';
  783. }
  784. $art_style = getProp($episode, 'art_style');
  785. if ($art_style) {
  786. $prompt = "美术风格:{$art_style}\n{$prompt}";
  787. }
  788. $dimensions = $this->getRatioDimensions($ratio);
  789. $width = $dimensions['width'];
  790. $height = $dimensions['height'];
  791. try {
  792. $params = [
  793. 'alias_segment_id' => $segment_id,
  794. 'prompt' => $prompt,
  795. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  796. 'width' => $width,
  797. 'height' => $height
  798. ];
  799. // 优化提示词(不要生成字幕)
  800. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  801. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  802. $task_id = $task->id;
  803. if (!$task_id) {
  804. Utils::throwError("20003:生成图片失败");
  805. }
  806. // 更新任务ID
  807. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update(['pic_task_id' => $task_id, 'pic_task_status' => '生成中', 'updated_at' => date('Y-m-d H:i:s')]);
  808. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  809. } catch (\Exception $e) {
  810. Utils::throwError("20003:" . $e->getMessage());
  811. }
  812. // 创建任务之后先暂停10s等待异步任务完成
  813. sleep(10);
  814. $img_url = $this->loopGetPicTaskResult($task_id);
  815. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  816. // 图片生成后新增对话记录
  817. try {
  818. $uid = Site::getUid();
  819. $now = date('Y-m-d H:i:s');
  820. // 使用AI反推图片提示词
  821. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  822. // 保存对话记录
  823. $records = [
  824. [
  825. 'uid' => $uid,
  826. 'anime_id' => $anime_id,
  827. 'sequence' => $episode_number,
  828. 'role' => 'user',
  829. 'content' => $prompt,
  830. 'segment_id' => $segment_id,
  831. 'image_url' => '',
  832. 'created_at' => $now,
  833. 'updated_at' => $now
  834. ],
  835. [
  836. 'uid' => $uid,
  837. 'anime_id' => $anime_id,
  838. 'sequence' => $episode_number,
  839. 'role' => 'assistant',
  840. 'content' => $pic_prompt,
  841. 'segment_id' => $segment_id,
  842. 'image_url' => $img_url,
  843. 'created_at' => $now,
  844. 'updated_at' => $now
  845. ]
  846. ];
  847. DB::table('mp_anime_records')->insert($records);
  848. } catch (\Exception $e) {
  849. // 记录日志但不影响主流程
  850. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  851. 'segment_id' => $segment_id,
  852. 'img_url' => $img_url
  853. ]);
  854. logDB('anime', 'error', '保存对话记录失败', [
  855. 'segment_id' => $segment_id,
  856. 'img_url' => $img_url,
  857. 'error' => $e->getMessage()
  858. ]);
  859. }
  860. return $img_url;
  861. }
  862. public function segmentChatHistory($data) {
  863. $segment_id = getProp($data, 'segment_id');
  864. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  865. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
  866. $chat = $query->orderBy('id')->get()->map(function ($value) {
  867. $value = (array)$value;
  868. $value['created_at'] = transDate($value['created_at']);
  869. return $value;
  870. })->toArray();
  871. // 获取历史图片
  872. $url = [];
  873. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  874. foreach($pic_history as $task) {
  875. $result_url = getProp($task, 'result_url');
  876. if (is_json($result_url)) {
  877. $url = array_merge($url, json_decode($result_url, true));
  878. }else {
  879. $url[] = $result_url;
  880. }
  881. }
  882. // 获取历史视频
  883. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  884. foreach($video_history as $task) {
  885. $result_url = getProp($task, 'compressed_url');
  886. if (is_json($result_url)) {
  887. $url = array_merge($url, json_decode($result_url, true));
  888. }else {
  889. $url[] = $result_url;
  890. }
  891. }
  892. return compact('chat', 'url');
  893. }
  894. public function changeEpisodeRoles($data) {
  895. $anime_id = getProp($data, 'anime_id');
  896. $episode_id = getProp($data, 'episode_id');
  897. $target_roles = getProp($data, 'roles');
  898. $is_deleted = getProp($data, 'is_deleted', 0);
  899. // 参数验证
  900. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  901. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  902. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  903. // 验证剧集是否存在
  904. $episode = DB::table('mp_anime_episodes')
  905. ->where('anime_id', $anime_id)
  906. ->where('id', $episode_id)
  907. ->first();
  908. if (!$episode) Utils::throwError('20003:该剧集不存在');
  909. $roles = json_decode(getProp($episode, 'roles'), true);
  910. // 获取anime信息,检查是否有关联的script_id
  911. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  912. if (!$anime) Utils::throwError('20003:动漫不存在');
  913. $script_id = getProp($anime, 'script_id');
  914. $episode_number = getProp($episode, 'episode_number', 1);
  915. $uid = Site::getUid();
  916. $cpid = Site::getCpid();
  917. try {
  918. $target_role_name = getProp($target_roles, 'role');
  919. // 如果是删除操作
  920. if ($is_deleted == 1) {
  921. // 从角色列表中移除该角色
  922. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  923. return getProp($role, 'role') !== $target_role_name;
  924. }));
  925. // 更新角色列表
  926. $result = DB::table('mp_anime_episodes')
  927. ->where('anime_id', $anime_id)
  928. ->where('id', $episode_id)
  929. ->update([
  930. 'roles' => json_encode($roles, 256),
  931. 'updated_at' => date('Y-m-d H:i:s')
  932. ]);
  933. if ($result === false) {
  934. Utils::throwError('20003:删除角色失败');
  935. }
  936. } else {
  937. // 新增或更新操作
  938. $role_found = false;
  939. $is_new_role = false;
  940. // 查找并更新已存在的角色
  941. foreach($roles as &$role) {
  942. if (getProp($role, 'role') === $target_role_name) {
  943. $role = $target_roles;
  944. $role_found = true;
  945. break;
  946. }
  947. }
  948. // 如果角色不存在,则新增
  949. if (!$role_found) {
  950. $roles[] = $target_roles;
  951. $is_new_role = true;
  952. }
  953. // 更新角色列表
  954. $result = DB::table('mp_anime_episodes')
  955. ->where('anime_id', $anime_id)
  956. ->where('id', $episode_id)
  957. ->update([
  958. 'roles' => json_encode($roles, 256),
  959. 'updated_at' => date('Y-m-d H:i:s')
  960. ]);
  961. if ($result === false) {
  962. Utils::throwError('20003:更新角色列表失败');
  963. }
  964. // 同步更新分镜表中对应主体的音色信息
  965. $voice_name = getProp($target_roles, 'voice_name');
  966. $voice_type = getProp($target_roles, 'voice_type');
  967. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  968. DB::table('mp_episode_segments')
  969. ->where('anime_id', $anime_id)
  970. ->where('episode_id', $episode_id)
  971. ->where('voice_actor', $target_role_name)
  972. ->update([
  973. 'voice_name' => $voice_name,
  974. 'voice_type' => $voice_type,
  975. 'voice_audio_url' => $voice_audio_url,
  976. 'updated_at' => date('Y-m-d H:i:s')
  977. ]);
  978. // 如果有关联的script_id,则同步到mp_products表
  979. if ($script_id) {
  980. // 查询剧本信息
  981. $script = DB::table('mp_scripts')
  982. ->where('id', $script_id)
  983. ->where('is_deleted', 0)
  984. ->first();
  985. if ($script) {
  986. $script_name = $script->script_name ?? 'script_' . $script_id;
  987. $product_name = getProp($target_roles, 'role');
  988. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  989. $url = getProp($target_roles, 'url', '');
  990. $product_type = 1; // 1=角色
  991. // 查找或创建以script_name命名的文件夹
  992. $folder = DB::table('mp_products')
  993. ->where('cpid', $cpid)
  994. ->where('type', 2) // 文件夹类型
  995. ->where('product', $product_type) // 角色类型
  996. ->where('product_name', $script_name)
  997. ->where('parent_id', 0)
  998. ->where('is_deleted', 0)
  999. ->first();
  1000. if (!$folder) {
  1001. // 创建文件夹
  1002. $folder_id = DB::table('mp_products')->insertGetId([
  1003. 'user_id' => $uid,
  1004. 'cpid' => $cpid,
  1005. 'type' => 2, // 文件夹
  1006. 'product' => $product_type, // 角色类型
  1007. 'parent_id' => 0,
  1008. 'level' => 1,
  1009. 'product_name' => $script_name,
  1010. 'sort_order' => time(),
  1011. 'is_deleted' => 0,
  1012. 'created_at' => date('Y-m-d H:i:s'),
  1013. 'updated_at' => date('Y-m-d H:i:s')
  1014. ]);
  1015. } else {
  1016. $folder_id = $folder->id;
  1017. }
  1018. // 查找该文件夹下是否已存在同名资产
  1019. $existing_product = DB::table('mp_products')
  1020. ->where('cpid', $cpid)
  1021. ->where('type', 1) // 资产类型
  1022. ->where('product', $product_type)
  1023. ->where('parent_id', $folder_id)
  1024. ->where('product_name', $product_name)
  1025. ->where('is_deleted', 0)
  1026. ->first();
  1027. if ($existing_product) {
  1028. // 更新已存在的资产
  1029. $updateData = [
  1030. 'pic_task_status' => '生成成功',
  1031. ];
  1032. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1033. if ($url) $updateData['url'] = $url;
  1034. // 处理versions字段
  1035. $versions = getProp($target_roles, 'versions', []);
  1036. if ($versions && is_array($versions)) {
  1037. $updateData['versions'] = json_encode($versions, 256);
  1038. }
  1039. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1040. DB::table('mp_products')
  1041. ->where('id', $existing_product->id)
  1042. ->update($updateData);
  1043. $product_id = $existing_product->id;
  1044. } else {
  1045. // 创建新资产
  1046. $versions = getProp($target_roles, 'versions', []);
  1047. $product_id = DB::table('mp_products')->insertGetId([
  1048. 'user_id' => $uid,
  1049. 'cpid' => $cpid,
  1050. 'type' => 1, // 资产
  1051. 'product' => $product_type, // 角色
  1052. 'parent_id' => $folder_id,
  1053. 'level' => 2,
  1054. 'product_name' => $product_name,
  1055. 'url' => $url,
  1056. 'pic_prompt' => $pic_prompt,
  1057. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1058. 'sort_order' => time(),
  1059. 'is_deleted' => 0,
  1060. 'pic_task_status' => '生成成功',
  1061. 'created_at' => date('Y-m-d H:i:s'),
  1062. 'updated_at' => date('Y-m-d H:i:s')
  1063. ]);
  1064. }
  1065. // 建立或更新绑定关系
  1066. $existing_mapping = DB::table('mp_script_product_mappings')
  1067. ->where('script_id', $script_id)
  1068. ->where('product_id', $product_id)
  1069. ->where('episode_number', $episode_number)
  1070. ->first();
  1071. if (!$existing_mapping) {
  1072. // 创建绑定关系
  1073. DB::table('mp_script_product_mappings')->insert([
  1074. 'script_id' => $script_id,
  1075. 'product_id' => $product_id,
  1076. 'episode_number' => $episode_number,
  1077. 'created_at' => date('Y-m-d H:i:s'),
  1078. 'updated_at' => date('Y-m-d H:i:s')
  1079. ]);
  1080. }
  1081. }
  1082. }
  1083. }
  1084. } catch (\Exception $e) {
  1085. dLog('anime')->error('更新剧集角色失败', [
  1086. 'anime_id' => $anime_id,
  1087. 'episode_id' => $episode_id,
  1088. 'error' => $e->getMessage()
  1089. ]);
  1090. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1091. }
  1092. return true;
  1093. }
  1094. public function changeEpisodeScenes($data) {
  1095. $anime_id = getProp($data, 'anime_id');
  1096. $episode_id = getProp($data, 'episode_id');
  1097. $target_scenes = getProp($data, 'scenes');
  1098. $is_deleted = getProp($data, 'is_deleted', 0);
  1099. // 参数验证
  1100. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1101. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1102. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1103. // 验证剧集是否存在
  1104. $episode = DB::table('mp_anime_episodes')
  1105. ->where('anime_id', $anime_id)
  1106. ->where('id', $episode_id)
  1107. ->first();
  1108. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1109. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1110. // 获取anime信息,检查是否有关联的script_id
  1111. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1112. if (!$anime) Utils::throwError('20003:动漫不存在');
  1113. $script_id = getProp($anime, 'script_id');
  1114. $episode_number = getProp($episode, 'episode_number', 1);
  1115. $uid = Site::getUid();
  1116. $cpid = Site::getCpid();
  1117. try {
  1118. $target_scene_name = getProp($target_scenes, 'scene');
  1119. // 如果是删除操作
  1120. if ($is_deleted == 1) {
  1121. // 从场景列表中移除该场景
  1122. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1123. return getProp($scene, 'scene') !== $target_scene_name;
  1124. }));
  1125. // 更新场景列表
  1126. $result = DB::table('mp_anime_episodes')
  1127. ->where('anime_id', $anime_id)
  1128. ->where('id', $episode_id)
  1129. ->update([
  1130. 'scenes' => json_encode($scenes, 256),
  1131. 'updated_at' => date('Y-m-d H:i:s')
  1132. ]);
  1133. if ($result === false) {
  1134. Utils::throwError('20003:删除场景失败');
  1135. }
  1136. } else {
  1137. // 新增或更新操作
  1138. $scene_found = false;
  1139. $is_new_scene = false;
  1140. // 查找并更新已存在的场景
  1141. foreach($scenes as &$scene) {
  1142. if (getProp($scene, 'scene') === $target_scene_name) {
  1143. $scene = $target_scenes;
  1144. $scene_found = true;
  1145. break;
  1146. }
  1147. }
  1148. // 如果场景不存在,则新增
  1149. if (!$scene_found) {
  1150. $scenes[] = $target_scenes;
  1151. $is_new_scene = true;
  1152. }
  1153. // 更新场景列表
  1154. $result = DB::table('mp_anime_episodes')
  1155. ->where('anime_id', $anime_id)
  1156. ->where('id', $episode_id)
  1157. ->update([
  1158. 'scenes' => json_encode($scenes, 256),
  1159. 'updated_at' => date('Y-m-d H:i:s')
  1160. ]);
  1161. if ($result === false) {
  1162. Utils::throwError('20003:更新场景列表失败');
  1163. }
  1164. // 如果有关联的script_id,则同步到mp_products表
  1165. if ($script_id) {
  1166. // 查询剧本信息
  1167. $script = DB::table('mp_scripts')
  1168. ->where('id', $script_id)
  1169. ->where('is_deleted', 0)
  1170. ->first();
  1171. if ($script) {
  1172. $script_name = $script->script_name ?? 'script_' . $script_id;
  1173. $product_name = getProp($target_scenes, 'scene');
  1174. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1175. $url = getProp($target_scenes, 'url', '');
  1176. $product_type = 2; // 2=场景
  1177. // 查找或创建以script_name命名的文件夹
  1178. $folder = DB::table('mp_products')
  1179. ->where('cpid', $cpid)
  1180. ->where('type', 2) // 文件夹类型
  1181. ->where('product', $product_type) // 场景类型
  1182. ->where('product_name', $script_name)
  1183. ->where('parent_id', 0)
  1184. ->where('is_deleted', 0)
  1185. ->first();
  1186. if (!$folder) {
  1187. // 创建文件夹
  1188. $folder_id = DB::table('mp_products')->insertGetId([
  1189. 'user_id' => $uid,
  1190. 'cpid' => $cpid,
  1191. 'type' => 2, // 文件夹
  1192. 'product' => $product_type, // 场景类型
  1193. 'parent_id' => 0,
  1194. 'level' => 1,
  1195. 'product_name' => $script_name,
  1196. 'sort_order' => time(),
  1197. 'is_deleted' => 0,
  1198. 'created_at' => date('Y-m-d H:i:s'),
  1199. 'updated_at' => date('Y-m-d H:i:s')
  1200. ]);
  1201. } else {
  1202. $folder_id = $folder->id;
  1203. }
  1204. // 查找该文件夹下是否已存在同名资产
  1205. $existing_product = DB::table('mp_products')
  1206. ->where('cpid', $cpid)
  1207. ->where('type', 1) // 资产类型
  1208. ->where('product', $product_type)
  1209. ->where('parent_id', $folder_id)
  1210. ->where('product_name', $product_name)
  1211. ->where('is_deleted', 0)
  1212. ->first();
  1213. if ($existing_product) {
  1214. // 更新已存在的资产
  1215. $updateData = [
  1216. 'pic_task_status' => '生成成功'
  1217. ];
  1218. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1219. if ($url) $updateData['url'] = $url;
  1220. // 处理versions字段
  1221. $versions = getProp($target_scenes, 'versions', []);
  1222. if ($versions && is_array($versions)) {
  1223. $updateData['versions'] = json_encode($versions, 256);
  1224. }
  1225. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1226. DB::table('mp_products')
  1227. ->where('id', $existing_product->id)
  1228. ->update($updateData);
  1229. $product_id = $existing_product->id;
  1230. } else {
  1231. // 创建新资产
  1232. $versions = getProp($target_scenes, 'versions', []);
  1233. $product_id = DB::table('mp_products')->insertGetId([
  1234. 'user_id' => $uid,
  1235. 'cpid' => $cpid,
  1236. 'type' => 1, // 资产
  1237. 'product' => $product_type, // 场景
  1238. 'parent_id' => $folder_id,
  1239. 'level' => 2,
  1240. 'product_name' => $product_name,
  1241. 'url' => $url,
  1242. 'pic_prompt' => $pic_prompt,
  1243. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1244. 'sort_order' => time(),
  1245. 'is_deleted' => 0,
  1246. 'pic_task_status' => '生成成功',
  1247. 'created_at' => date('Y-m-d H:i:s'),
  1248. 'updated_at' => date('Y-m-d H:i:s')
  1249. ]);
  1250. }
  1251. // 建立或更新绑定关系
  1252. $existing_mapping = DB::table('mp_script_product_mappings')
  1253. ->where('script_id', $script_id)
  1254. ->where('product_id', $product_id)
  1255. ->where('episode_number', $episode_number)
  1256. ->first();
  1257. if (!$existing_mapping) {
  1258. // 创建绑定关系
  1259. DB::table('mp_script_product_mappings')->insert([
  1260. 'script_id' => $script_id,
  1261. 'product_id' => $product_id,
  1262. 'episode_number' => $episode_number,
  1263. 'created_at' => date('Y-m-d H:i:s'),
  1264. 'updated_at' => date('Y-m-d H:i:s')
  1265. ]);
  1266. }
  1267. }
  1268. }
  1269. }
  1270. } catch (\Exception $e) {
  1271. dLog('anime')->error('更新剧集场景失败', [
  1272. 'anime_id' => $anime_id,
  1273. 'episode_id' => $episode_id,
  1274. 'error' => $e->getMessage()
  1275. ]);
  1276. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1277. }
  1278. return true;
  1279. }
  1280. public function changeEpisodeProps($data) {
  1281. $anime_id = getProp($data, 'anime_id');
  1282. $episode_id = getProp($data, 'episode_id');
  1283. $target_props = getProp($data, 'props');
  1284. $is_deleted = getProp($data, 'is_deleted', 0);
  1285. // 参数验证
  1286. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1287. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1288. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1289. // 验证剧集是否存在
  1290. $episode = DB::table('mp_anime_episodes')
  1291. ->where('anime_id', $anime_id)
  1292. ->where('id', $episode_id)
  1293. ->first();
  1294. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1295. $props = json_decode(getProp($episode, 'props'), true);
  1296. // 获取anime信息,检查是否有关联的script_id
  1297. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1298. if (!$anime) Utils::throwError('20003:动漫不存在');
  1299. $script_id = getProp($anime, 'script_id');
  1300. $episode_number = getProp($episode, 'episode_number', 1);
  1301. $uid = Site::getUid();
  1302. $cpid = Site::getCpid();
  1303. try {
  1304. $target_prop_name = getProp($target_props, 'prop');
  1305. // 如果是删除操作
  1306. if ($is_deleted == 1) {
  1307. // 从道具列表中移除该道具
  1308. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1309. return getProp($prop, 'prop') !== $target_prop_name;
  1310. }));
  1311. // 更新道具列表
  1312. $result = DB::table('mp_anime_episodes')
  1313. ->where('anime_id', $anime_id)
  1314. ->where('id', $episode_id)
  1315. ->update([
  1316. 'props' => json_encode($props, 256),
  1317. 'updated_at' => date('Y-m-d H:i:s')
  1318. ]);
  1319. if ($result === false) {
  1320. Utils::throwError('20003:删除道具失败');
  1321. }
  1322. } else {
  1323. // 新增或更新操作
  1324. $prop_found = false;
  1325. $is_new_prop = false;
  1326. // 查找并更新已存在的道具
  1327. foreach($props as &$prop) {
  1328. if (getProp($prop, 'prop') === $target_prop_name) {
  1329. $prop = $target_props;
  1330. $prop_found = true;
  1331. break;
  1332. }
  1333. }
  1334. // 如果道具不存在,则新增
  1335. if (!$prop_found) {
  1336. $props[] = $target_props;
  1337. $is_new_prop = true;
  1338. }
  1339. // 更新道具列表
  1340. $result = DB::table('mp_anime_episodes')
  1341. ->where('anime_id', $anime_id)
  1342. ->where('id', $episode_id)
  1343. ->update([
  1344. 'props' => json_encode($props, 256),
  1345. 'updated_at' => date('Y-m-d H:i:s')
  1346. ]);
  1347. if ($result === false) {
  1348. Utils::throwError('20003:更新道具列表失败');
  1349. }
  1350. // 如果有关联的script_id,则同步到mp_products表
  1351. if ($script_id) {
  1352. // 查询剧本信息
  1353. $script = DB::table('mp_scripts')
  1354. ->where('id', $script_id)
  1355. ->where('is_deleted', 0)
  1356. ->first();
  1357. if ($script) {
  1358. $script_name = $script->script_name ?? 'script_' . $script_id;
  1359. $product_name = getProp($target_props, 'prop');
  1360. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1361. $url = getProp($target_props, 'url', '');
  1362. $product_type = 3; // 3=道具
  1363. // 查找或创建以script_name命名的文件夹
  1364. $folder = DB::table('mp_products')
  1365. ->where('cpid', $cpid)
  1366. ->where('type', 2) // 文件夹类型
  1367. ->where('product', $product_type) // 道具类型
  1368. ->where('product_name', $script_name)
  1369. ->where('parent_id', 0)
  1370. ->where('is_deleted', 0)
  1371. ->first();
  1372. if (!$folder) {
  1373. // 创建文件夹
  1374. $folder_id = DB::table('mp_products')->insertGetId([
  1375. 'user_id' => $uid,
  1376. 'cpid' => $cpid,
  1377. 'type' => 2, // 文件夹
  1378. 'product' => $product_type, // 道具类型
  1379. 'parent_id' => 0,
  1380. 'level' => 1,
  1381. 'product_name' => $script_name,
  1382. 'sort_order' => time(),
  1383. 'is_deleted' => 0,
  1384. 'created_at' => date('Y-m-d H:i:s'),
  1385. 'updated_at' => date('Y-m-d H:i:s')
  1386. ]);
  1387. } else {
  1388. $folder_id = $folder->id;
  1389. }
  1390. // 查找该文件夹下是否已存在同名资产
  1391. $existing_product = DB::table('mp_products')
  1392. ->where('cpid', $cpid)
  1393. ->where('type', 1) // 资产类型
  1394. ->where('product', $product_type)
  1395. ->where('parent_id', $folder_id)
  1396. ->where('product_name', $product_name)
  1397. ->where('is_deleted', 0)
  1398. ->first();
  1399. if ($existing_product) {
  1400. // 更新已存在的资产
  1401. $updateData = [
  1402. 'pic_task_status' => '生成成功'
  1403. ];
  1404. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1405. if ($url) $updateData['url'] = $url;
  1406. // 处理versions字段
  1407. $versions = getProp($target_props, 'versions', []);
  1408. if ($versions && is_array($versions)) {
  1409. $updateData['versions'] = json_encode($versions, 256);
  1410. }
  1411. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1412. DB::table('mp_products')
  1413. ->where('id', $existing_product->id)
  1414. ->update($updateData);
  1415. $product_id = $existing_product->id;
  1416. } else {
  1417. // 创建新资产
  1418. $versions = getProp($target_props, 'versions', []);
  1419. $product_id = DB::table('mp_products')->insertGetId([
  1420. 'user_id' => $uid,
  1421. 'cpid' => $cpid,
  1422. 'type' => 1, // 资产
  1423. 'product' => $product_type, // 道具
  1424. 'parent_id' => $folder_id,
  1425. 'level' => 2,
  1426. 'product_name' => $product_name,
  1427. 'url' => $url,
  1428. 'pic_prompt' => $pic_prompt,
  1429. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1430. 'sort_order' => time(),
  1431. 'is_deleted' => 0,
  1432. 'pic_task_status' => '生成成功',
  1433. 'created_at' => date('Y-m-d H:i:s'),
  1434. 'updated_at' => date('Y-m-d H:i:s')
  1435. ]);
  1436. }
  1437. // 建立或更新绑定关系
  1438. $existing_mapping = DB::table('mp_script_product_mappings')
  1439. ->where('script_id', $script_id)
  1440. ->where('product_id', $product_id)
  1441. ->where('episode_number', $episode_number)
  1442. ->first();
  1443. if (!$existing_mapping) {
  1444. // 创建绑定关系
  1445. DB::table('mp_script_product_mappings')->insert([
  1446. 'script_id' => $script_id,
  1447. 'product_id' => $product_id,
  1448. 'episode_number' => $episode_number,
  1449. 'created_at' => date('Y-m-d H:i:s'),
  1450. 'updated_at' => date('Y-m-d H:i:s')
  1451. ]);
  1452. }
  1453. }
  1454. }
  1455. }
  1456. } catch (\Exception $e) {
  1457. dLog('anime')->error('更新剧集道具失败', [
  1458. 'anime_id' => $anime_id,
  1459. 'episode_id' => $episode_id,
  1460. 'error' => $e->getMessage()
  1461. ]);
  1462. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1463. }
  1464. return true;
  1465. }
  1466. public function editSegment($data) {
  1467. $segment_id = getProp($data, 'segment_id');
  1468. $segment_content = getProp($data, 'segment_content');
  1469. $image_url = getProp($data, 'image_url');
  1470. $video_url = getProp($data, 'video_url');
  1471. // 参数验证
  1472. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1473. // 验证分镜是否存在
  1474. $segment = DB::table('mp_episode_segments')
  1475. ->where('segment_id', $segment_id)
  1476. ->first();
  1477. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1478. $dubTaskId = 0;
  1479. try {
  1480. DB::beginTransaction();
  1481. // 准备更新数据
  1482. $update_data = [
  1483. 'updated_at' => date('Y-m-d H:i:s')
  1484. ];
  1485. if ($segment_content) {
  1486. // 先将segment_content赋值到update_data
  1487. $update_data['segment_content'] = $segment_content;
  1488. // 使用现有方法分析segment_content,提取各个字段
  1489. $this->handleSegmentContent($update_data);
  1490. // 如果有对话内容,创建视频配音合成任务
  1491. $dialogue = getProp($update_data, 'dialogue');
  1492. if (!empty($dialogue)) {
  1493. $now = date('Y-m-d H:i:s');
  1494. $generate_json = [
  1495. 'text' => $dialogue,
  1496. 'role' => getProp($update_data, 'voice_actor'),
  1497. 'voice_type' => getProp($update_data, 'voice_type'),
  1498. 'voice_name' => getProp($update_data, 'voice_name'),
  1499. 'emotion' => getProp($update_data, 'emotion'),
  1500. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1501. 'gender' => getProp($update_data, 'gender'),
  1502. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1503. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1504. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1505. 'pitch' => getProp($update_data, 'pitch', 0),
  1506. ];
  1507. // 插入视频配音合成任务
  1508. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1509. 'alias_segment_id' => $segment_id,
  1510. 'generate_status' => '执行中',
  1511. 'audio_url' => '',
  1512. 'generate_json' => json_encode($generate_json, 256),
  1513. 'created_at' => $now,
  1514. 'updated_at' => $now,
  1515. ]);
  1516. if (!$dubTaskId) {
  1517. Utils::throwError('20003:创建配音任务失败!');
  1518. }
  1519. $update_data['audio_url'] = '';
  1520. } else {
  1521. // dialogue为空时,直接写入默认音频信息
  1522. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1523. $update_data['audio_duration'] = 2.0;
  1524. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1525. }
  1526. }
  1527. if ($image_url) {
  1528. $update_data['img_url'] = $image_url;
  1529. // 同时写入一个简单的图片生成任务
  1530. $pic_task = [
  1531. 'alias_segment_id' => $segment_id,
  1532. 'ref_img_url' => json_encode([]),
  1533. 'status' => 'success',
  1534. 'result_url' => json_encode([$image_url], 256),
  1535. 'model' => '',
  1536. 'created_at' => date('Y-m-d H:i:s'),
  1537. 'updated_at' => date('Y-m-d H:i:s'),
  1538. ];
  1539. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1540. }
  1541. if ($video_url) {
  1542. $update_data['origin_video_url'] = $video_url;
  1543. $compressed_video_url = compressVideo($video_url);
  1544. $update_data['current_type'] = 2;
  1545. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1546. // 同时写入一个简单的视频生成任务
  1547. $video_task = [
  1548. 'alias_segment_id' => $segment_id,
  1549. 'status' => 'success',
  1550. 'result_url' => $update_data['origin_video_url'],
  1551. 'compressed_url' => $update_data['video_url'],
  1552. 'created_at' => date('Y-m-d H:i:s'),
  1553. 'updated_at' => date('Y-m-d H:i:s'),
  1554. ];
  1555. DB::table('mp_generate_video_tasks')->insert($video_task);
  1556. }
  1557. // 更新分镜信息
  1558. $result = DB::table('mp_episode_segments')
  1559. ->where('segment_id', $segment_id)
  1560. ->update($update_data);
  1561. if ($result === false) {
  1562. Utils::throwError('20003:更新分镜剧本失败');
  1563. }
  1564. DB::commit();
  1565. // 如果有创建音频生成任务则调用API
  1566. if ($dubTaskId) {
  1567. // 请求远程服务器执行生成
  1568. $client = new Client(['timeout' => 300, 'verify' => false]);
  1569. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1570. $response = $result->getBody()->getContents();
  1571. $response_arr = json_decode($response, true);
  1572. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1573. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1574. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1575. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1576. Utils::throwError('20003:火山生成音频失败');
  1577. }
  1578. }
  1579. return true;
  1580. } catch (\Exception $e) {
  1581. DB::rollBack();
  1582. dLog('anime')->error('更新分镜剧本失败', [
  1583. 'segment_id' => $segment_id,
  1584. 'error' => $e->getMessage()
  1585. ]);
  1586. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1587. }
  1588. }
  1589. public function batchSetSegmentPics($data) {
  1590. $anime_id = getProp($data, 'anime_id');
  1591. $episode_id = getProp($data, 'episode_id');
  1592. $ratio = getProp($data, 'ratio');
  1593. $dimensions = $this->getRatioDimensions($ratio);
  1594. $width = $dimensions['width'];
  1595. $height = $dimensions['height'];
  1596. if (!$anime_id || !$episode_id) {
  1597. Utils::throwError('1002:请选择剧集');
  1598. }
  1599. // 获取剧集信息
  1600. $episode = DB::table('mp_anime_episodes')
  1601. ->where('anime_id', $anime_id)
  1602. ->where('id', $episode_id)
  1603. ->where('is_default', 1)
  1604. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1605. ->first();
  1606. if (!$episode) {
  1607. Utils::throwError('20003:该剧集不存在');
  1608. }
  1609. $model = getProp($data, 'model');
  1610. if (!$model) {
  1611. $model = getProp($episode, 'image_model');
  1612. if (!$model) {
  1613. // episode表也没有,使用默认值
  1614. $model = 'doubao-seedream-5-0-lite-260128';
  1615. }
  1616. }
  1617. // 验证模型是否在可用模型表中
  1618. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1619. $model = 'doubao-seedream-5-0-lite-260128';
  1620. }
  1621. $roles = json_decode(getProp($episode, 'roles'), true);
  1622. if (!$roles) {
  1623. Utils::throwError('20003:角色信息格式错误');
  1624. }
  1625. // 构建角色名称到参考图的映射
  1626. $role_map = [];
  1627. foreach ($roles as $role) {
  1628. $role_name = getProp($role, 'role');
  1629. $role_url = getProp($role, 'url');
  1630. if (!empty($role_name) && !empty($role_url)) {
  1631. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1632. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1633. // $role_map[$base_name] = $role_url;
  1634. // 同时保存完整名称的映射
  1635. $role_map[$role_name] = $role_url;
  1636. }
  1637. }
  1638. $scenes = json_decode(getProp($episode, 'roles'), true);
  1639. if (!$scenes) {
  1640. Utils::throwError('20003:场景信息格式错误');
  1641. }
  1642. // 构建角色名称到参考图的映射
  1643. $scene_map = [];
  1644. foreach ($scenes as $scene) {
  1645. $scene_name = getProp($scene, 'scene');
  1646. $scene_url = getProp($scene, 'url');
  1647. if (!empty($scene_name) && !empty($scene_url)) {
  1648. $scene_map[$scene_name] = $scene_url;
  1649. }
  1650. }
  1651. // 获取所有分镜信息
  1652. $segments = DB::table('mp_episode_segments')
  1653. ->where('anime_id', $anime_id)
  1654. ->where('episode_id', $episode_id)
  1655. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1656. ->orderBy('segment_number')
  1657. ->get()
  1658. ->toArray();
  1659. if (empty($segments)) {
  1660. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1661. }
  1662. // 保存图片比例
  1663. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1664. $updated_segments = [];
  1665. $failed_segments = [];
  1666. // 批量为每个分镜生成图片任务
  1667. foreach ($segments as $segment) {
  1668. $segment_id = $segment->segment_id;
  1669. $segment_content = $segment->segment_content;
  1670. if (empty($segment_content)) {
  1671. $failed_segments[] = [
  1672. 'segment_id' => $segment_id,
  1673. 'error' => '分镜内容为空'
  1674. ];
  1675. continue;
  1676. }
  1677. try {
  1678. $dubTaskId = 0;
  1679. // 解析分镜内容,提取画面描述作为主要提示词
  1680. $prompt = $segment_content;
  1681. $ref_img_urls = [];
  1682. // 分镜场景
  1683. $scene = getProp($segment, 'scene');
  1684. $matched_scene = '';
  1685. if (isset($scene_map[$scene])) {
  1686. $img_index = count($ref_img_urls) + 1;
  1687. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1688. $ref_img_urls[] = $scene_map[$scene];
  1689. $matched_scene = $scene;
  1690. }
  1691. // 分镜角色
  1692. $characters = getProp($segment, 'characters');
  1693. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1694. $roles = explode(',', $characters);
  1695. // 从分镜内容中提取涉及的角色
  1696. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1697. // 获取匹配角色的参考图
  1698. foreach ($segment_characters as $character) {
  1699. if (isset($role_map[$character])) {
  1700. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1701. $img_index = count($ref_img_urls) + 1;
  1702. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1703. $ref_img_urls[] = $role_map[$character];
  1704. }
  1705. }
  1706. // 如果没有找到匹配的角色参考图,不使用参考图
  1707. if (empty($ref_img_urls)) {
  1708. $ref_img_urls = [];
  1709. }
  1710. // 准备生成任务参数
  1711. $params = [
  1712. 'model' => $model,
  1713. 'alias_segment_id' => $segment_id,
  1714. 'prompt' => $prompt,
  1715. 'ref_img_urls' => $ref_img_urls,
  1716. 'width' => $width,
  1717. 'height' => $height,
  1718. ];
  1719. // 优化提示词(不要生成字幕)
  1720. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1721. // $task_id = mt_rand(100000, 999999);
  1722. // 调用AI图片生成服务
  1723. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1724. $task_id = $task->id;
  1725. if (!$task_id) {
  1726. $failed_segments[] = [
  1727. 'segment_id' => $segment_id,
  1728. 'error' => '创建生成任务失败'
  1729. ];
  1730. continue;
  1731. }
  1732. $update_data = [
  1733. 'pic_task_id' => $task_id,
  1734. 'pic_task_status' => '生成中',
  1735. 'audio_url' => '',
  1736. 'updated_at' => date('Y-m-d H:i:s')
  1737. ];
  1738. // 如果有对话内容,创建视频配音合成任务
  1739. $dialogue = getProp($segment, 'dialogue');
  1740. if (!empty($dialogue)) {
  1741. $now = date('Y-m-d H:i:s');
  1742. $generate_json = [
  1743. 'text' => $dialogue,
  1744. 'role' => getProp($segment, 'voice_actor'),
  1745. 'voice_type' => getProp($segment, 'voice_type'),
  1746. 'voice_name' => getProp($segment, 'voice_name'),
  1747. 'emotion' => getProp($segment, 'emotion'),
  1748. 'emotion_type' => getProp($segment, 'emotion_type'),
  1749. 'gender' => getProp($segment, 'gender'),
  1750. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1751. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1752. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1753. 'pitch' => getProp($segment, 'pitch', 0),
  1754. ];
  1755. // 插入视频配音合成任务
  1756. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1757. 'alias_segment_id' => $segment_id,
  1758. 'generate_status' => '执行中',
  1759. 'audio_url' => '',
  1760. 'generate_json' => json_encode($generate_json, 256),
  1761. 'created_at' => $now,
  1762. 'updated_at' => $now,
  1763. ]);
  1764. if (!$dubTaskId) {
  1765. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1766. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1767. // Utils::throwError('20003:创建配音任务失败!');
  1768. }
  1769. } else {
  1770. // dialogue为空时,直接写入默认音频信息到分镜表
  1771. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1772. $update_data['audio_duration'] = 2.0;
  1773. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1774. }
  1775. // 更新分镜的任务信息
  1776. $update_result = DB::table('mp_episode_segments')
  1777. ->where('segment_id', $segment_id)
  1778. ->update($update_data);
  1779. // 如果是第一集的首帧图片,则存入待更新数组
  1780. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1781. Redis::sadd('anime_first_frame_urls', $segment_id);
  1782. }
  1783. if ($update_result) {
  1784. $updated_segments[] = [
  1785. 'segment_id' => $segment_id,
  1786. 'task_id' => $task_id,
  1787. 'status' => '生成中',
  1788. 'matched_scenes' => $matched_scene,
  1789. 'matched_roles' => $segment_characters,
  1790. 'ref_urls_count' => count($ref_img_urls)
  1791. ];
  1792. } else {
  1793. $failed_segments[] = [
  1794. 'segment_id' => $segment_id,
  1795. 'error' => '更新分镜任务状态失败'
  1796. ];
  1797. }
  1798. if ($dubTaskId) {
  1799. sleep(1);
  1800. // 请求远程服务器执行生成
  1801. $client = new Client(['timeout' => 300, 'verify' => false]);
  1802. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1803. $response = $result->getBody()->getContents();
  1804. $response_arr = json_decode($response, true);
  1805. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1806. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1807. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1808. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1809. }
  1810. }
  1811. } catch (\Exception $e) {
  1812. $failed_segments[] = [
  1813. 'segment_id' => $segment_id,
  1814. 'error' => $e->getMessage()
  1815. ];
  1816. }
  1817. }
  1818. // 更新剧集生成状态
  1819. if (!empty($updated_segments)) {
  1820. DB::table('mp_anime_episodes')
  1821. ->where('id', $episode_id)
  1822. ->update([
  1823. 'is_generated' => 1,
  1824. 'updated_at' => date('Y-m-d H:i:s')
  1825. ]);
  1826. }
  1827. return [
  1828. 'success_count' => count($updated_segments),
  1829. 'failed_count' => count($failed_segments),
  1830. 'success_segments' => $updated_segments,
  1831. 'failed_segments' => $failed_segments,
  1832. 'total_segments' => count($segments)
  1833. ];
  1834. }
  1835. public function reGenerateSegment($data) {
  1836. $segment_id = getProp($data, 'segment_id');
  1837. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1838. $anime_id = getProp($segment, 'anime_id');
  1839. $episode_id = getProp($segment, 'episode_id');
  1840. $episode_number = getProp($segment, 'episode_number');
  1841. $segment_content = getProp($data, 'segment_content');
  1842. $ratio = getProp($data, 'ratio');
  1843. if (!$ratio) {
  1844. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1845. if (!$ratio) $ratio = '9:16';
  1846. }
  1847. $dimensions = $this->getRatioDimensions($ratio);
  1848. $width = $dimensions['width'];
  1849. $height = $dimensions['height'];
  1850. if (!$anime_id || !$episode_id) {
  1851. Utils::throwError('1002:请选择分镜');
  1852. }
  1853. // 使用文生文模型重新解析segment_content
  1854. if (!empty($segment_content)) {
  1855. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1856. }
  1857. // 获取动漫的角色信息(包含参考图)
  1858. $anime = DB::table('mp_animes')
  1859. ->where('id', $anime_id)
  1860. ->select('roles', 'scenes')
  1861. ->first();
  1862. if (!$anime || !$anime->roles) {
  1863. Utils::throwError('20003:未找到角色信息');
  1864. }
  1865. $roles = json_decode($anime->roles, true);
  1866. if (!$roles) {
  1867. Utils::throwError('20003:角色信息格式错误');
  1868. }
  1869. // 构建角色名称到参考图的映射
  1870. $role_map = [];
  1871. foreach ($roles as $role) {
  1872. $role_name = getProp($role, 'role');
  1873. $role_url = getProp($role, 'url');
  1874. if (!empty($role_name) && !empty($role_url)) {
  1875. $role_map[$role_name] = $role_url;
  1876. }
  1877. }
  1878. $scenes = json_decode($anime->scenes, true);
  1879. if (!$scenes) {
  1880. Utils::throwError('20003:角色信息格式错误');
  1881. }
  1882. // 构建角色名称到参考图的映射
  1883. $scene_map = [];
  1884. foreach ($scenes as $scene) {
  1885. $scene_name = getProp($scene, 'scene');
  1886. $scene_url = getProp($scene, 'url');
  1887. if (!empty($scene_name) && !empty($scene_url)) {
  1888. $scene_map[$scene_name] = $scene_url;
  1889. }
  1890. }
  1891. $segment_id = $segment->segment_id;
  1892. $original_segment_content = $segment->segment_content;
  1893. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1894. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1895. if (empty($final_segment_content)) {
  1896. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1897. }
  1898. try {
  1899. $dubTaskId = 0;
  1900. // 分镜剧本数组
  1901. $update_data = [
  1902. 'segment_content' => $final_segment_content,
  1903. 'pic_task_status' => '生成中',
  1904. 'updated_at' => date('Y-m-d H:i:s')
  1905. ];
  1906. // 解析分镜内容,提取画面描述作为主要提示词
  1907. $prompt = $final_segment_content;
  1908. $ref_img_urls = [];
  1909. // 分镜场景
  1910. $scene = getProp($data, 'scene');
  1911. if ($scene) {
  1912. $matched_scene = '';
  1913. if (isset($scene_map[$scene])) {
  1914. $img_index = count($ref_img_urls) + 1;
  1915. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1916. $ref_img_urls[] = $scene_map[$scene];
  1917. $matched_scene = $scene;
  1918. }
  1919. $update_data['scene'] = $scene;
  1920. }
  1921. // 分镜角色
  1922. $characters = getProp($data, 'characters');
  1923. if ($characters) {
  1924. $update_data['characters'] = $characters;
  1925. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1926. $characters = explode(',', $characters);
  1927. // 从分镜内容中提取涉及的角色
  1928. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1929. // 获取匹配角色的参考图
  1930. foreach ($segment_characters as $character) {
  1931. if (isset($role_map[$character])) {
  1932. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1933. $img_index = count($ref_img_urls) + 1;
  1934. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1935. $ref_img_urls[] = $role_map[$character];
  1936. }
  1937. }
  1938. }
  1939. // 如果没有找到匹配的角色参考图,不使用参考图
  1940. if (empty($ref_img_urls)) {
  1941. $ref_img_urls = [];
  1942. }
  1943. // 准备生成任务参数
  1944. $params = [
  1945. 'alias_segment_id' => $segment_id,
  1946. 'prompt' => $prompt,
  1947. 'ref_img_urls' => $ref_img_urls,
  1948. 'width' => $width,
  1949. 'height' => $height,
  1950. ];
  1951. // 优化提示词(不要生成字幕)
  1952. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1953. // 调用AI图片生成服务
  1954. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1955. $task_id = $task->id;
  1956. if (!$task_id) {
  1957. Utils::throwError('20003:创建生成任务失败!');
  1958. }
  1959. $update_data['pic_task_id'] = $task_id;
  1960. // 更新分镜剧本信息
  1961. $this->handleSegmentContent($update_data);
  1962. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1963. if ($segment_content) {
  1964. $dialogue = getProp($update_data, 'dialogue');
  1965. if (!empty($dialogue)) {
  1966. $now = date('Y-m-d H:i:s');
  1967. $generate_json = [
  1968. 'text' => $dialogue,
  1969. 'role' => getProp($update_data, 'voice_actor'),
  1970. 'voice_type' => getProp($update_data, 'voice_type'),
  1971. 'voice_name' => getProp($update_data, 'voice_name'),
  1972. 'emotion' => getProp($update_data, 'emotion'),
  1973. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1974. 'gender' => getProp($update_data, 'gender'),
  1975. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1976. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1977. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1978. 'pitch' => getProp($update_data, 'pitch', 0),
  1979. ];
  1980. // 插入视频配音合成任务
  1981. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1982. 'alias_segment_id' => $segment_id,
  1983. 'generate_status' => '执行中',
  1984. 'audio_url' => '',
  1985. 'generate_json' => json_encode($generate_json, 256),
  1986. 'created_at' => date('Y-m-d H:i:s'),
  1987. 'updated_at' => date('Y-m-d H:i:s'),
  1988. ]);
  1989. if (!$dubTaskId) {
  1990. Utils::throwError('20003:创建配音任务失败!');
  1991. }
  1992. $update_data['audio_url'] = '';
  1993. } else {
  1994. // dialogue为空时,直接写入默认音频信息
  1995. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1996. $update_data['audio_duration'] = 2.0;
  1997. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1998. }
  1999. }
  2000. $boolen = DB::table('mp_episode_segments')
  2001. ->where('segment_id', $segment_id)
  2002. ->update($update_data);
  2003. // 如果是第一集的首帧图片,则存入待更新数组
  2004. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2005. Redis::sadd('anime_first_frame_urls', $segment_id);
  2006. }
  2007. if ($dubTaskId) {
  2008. // 请求远程服务器执行生成
  2009. $client = new Client(['timeout' => 300, 'verify' => false]);
  2010. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2011. $response = $result->getBody()->getContents();
  2012. $response_arr = json_decode($response, true);
  2013. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2014. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2015. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2016. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2017. Utils::throwError('20003:火山生成音频失败');
  2018. }
  2019. }
  2020. } catch (\Exception $e) {
  2021. $failed_segments[] = [
  2022. 'segment_id' => $segment_id,
  2023. 'error' => $e->getMessage()
  2024. ];
  2025. }
  2026. // 创建任务之后先暂停10s等待异步任务完成
  2027. sleep(10);
  2028. $img_url = $this->loopGetPicTaskResult($task_id);
  2029. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2030. // 图片生成后新增对话记录
  2031. try {
  2032. $uid = Site::getUid();
  2033. $now = date('Y-m-d H:i:s');
  2034. // 使用AI反推图片提示词
  2035. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2036. // 保存对话记录
  2037. $records = [
  2038. [
  2039. 'uid' => $uid,
  2040. 'anime_id' => $anime_id,
  2041. 'sequence' => $episode_number,
  2042. 'role' => 'user',
  2043. 'content' => '重新生成',
  2044. 'segment_id' => $segment_id,
  2045. 'image_url' => '',
  2046. 'created_at' => $now,
  2047. 'updated_at' => $now
  2048. ],
  2049. [
  2050. 'uid' => $uid,
  2051. 'anime_id' => $anime_id,
  2052. 'sequence' => $episode_number,
  2053. 'role' => 'assistant',
  2054. 'content' => $pic_prompt,
  2055. 'segment_id' => $segment_id,
  2056. 'image_url' => $img_url,
  2057. 'created_at' => $now,
  2058. 'updated_at' => $now
  2059. ]
  2060. ];
  2061. DB::table('mp_anime_records')->insert($records);
  2062. } catch (\Exception $e) {
  2063. // 记录日志但不影响主流程
  2064. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2065. 'segment_id' => $segment_id,
  2066. 'img_url' => $img_url
  2067. ]);
  2068. }
  2069. return $img_url;
  2070. }
  2071. public function addSegment($data) {
  2072. $prev_segment_id = getProp($data, 'prev_segment_id');
  2073. $img_url = getProp($data, 'img_url');
  2074. $video_url = getProp($data, 'video_url');
  2075. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2076. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2077. $anime_id = getProp($segment, 'anime_id');
  2078. $episode_id = getProp($segment, 'episode_id');
  2079. $episode_number = getProp($segment, 'episode_number');
  2080. $segment_number = getProp($segment, 'segment_number');
  2081. $new_segment_number = $segment_number + 1;
  2082. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2083. // 分镜剧本数组
  2084. $insert_data = [
  2085. 'anime_id' => $anime_id,
  2086. 'episode_id' => $episode_id,
  2087. 'episode_number' => $episode_number,
  2088. 'act_number' => getProp($segment, 'act_number'),
  2089. 'act_title' => getProp($segment, 'act_title'),
  2090. 'segment_id' => $segment_id,
  2091. 'segment_number' => $new_segment_number,
  2092. 'segment_content' => '',
  2093. 'img_url' => '',
  2094. 'video_url' => '',
  2095. 'created_at' => date('Y-m-d H:i:s'),
  2096. 'updated_at' => date('Y-m-d H:i:s')
  2097. ];
  2098. if ($img_url) $insert_data['img_url'] = $img_url;
  2099. if ($video_url) {
  2100. $insert_data['origin_video_url'] = $video_url;
  2101. $insert_data['current_type'] = 2;
  2102. $compressed_video_url = compressVideo($video_url);
  2103. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2104. }
  2105. try {
  2106. DB::beginTransaction();
  2107. // 先更新序号
  2108. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2109. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2110. if (!$id) {
  2111. Utils::throwError('20003:新增分镜失败!');
  2112. }
  2113. }catch (\Exception $e) {
  2114. DB::rollBack();
  2115. Utils::throwError('20003:'.$e->getMessage());
  2116. }
  2117. DB::commit();
  2118. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2119. $segment = $segment ? (array)$segment : [];
  2120. return $segment;
  2121. // 以下代码暂弃用
  2122. $anime_id = getProp($segment, 'anime_id');
  2123. $episode_id = getProp($segment, 'episode_id');
  2124. $episode_number = getProp($segment, 'episode_number');
  2125. $segment_number = getProp($segment, 'segment_number');
  2126. $segment_content = getProp($data, 'segment_content');
  2127. $img_url = getProp($data, 'img_url');
  2128. $video_url = getProp($data, 'video_url');
  2129. $ratio = getProp($data, 'ratio');
  2130. $dimensions = $this->getRatioDimensions($ratio);
  2131. $width = $dimensions['width'];
  2132. $height = $dimensions['height'];
  2133. if (!$anime_id || !$episode_id) {
  2134. Utils::throwError('1002:请选择分镜');
  2135. }
  2136. // 使用文生文模型重新解析segment_content
  2137. if (!empty($segment_content)) {
  2138. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2139. }
  2140. // 获取动漫的角色信息(包含参考图)
  2141. $anime = DB::table('mp_animes')
  2142. ->where('id', $anime_id)
  2143. ->select('roles', 'scenes')
  2144. ->first();
  2145. if (!$anime || !$anime->roles) {
  2146. Utils::throwError('20003:未找到角色信息');
  2147. }
  2148. $roles = json_decode($anime->roles, true);
  2149. if (!$roles) {
  2150. Utils::throwError('20003:角色信息格式错误');
  2151. }
  2152. // 构建角色名称到参考图的映射
  2153. $role_map = [];
  2154. foreach ($roles as $role) {
  2155. $role_name = getProp($role, 'role');
  2156. $role_url = getProp($role, 'url');
  2157. if (!empty($role_name) && !empty($role_url)) {
  2158. $role_map[$role_name] = $role_url;
  2159. }
  2160. }
  2161. $scenes = json_decode($anime->scenes, true);
  2162. if (!$scenes) {
  2163. Utils::throwError('20003:角色信息格式错误');
  2164. }
  2165. // 构建角色名称到参考图的映射
  2166. $scene_map = [];
  2167. foreach ($scenes as $scene) {
  2168. $scene_name = getProp($scene, 'scene');
  2169. $scene_url = getProp($scene, 'url');
  2170. if (!empty($scene_name) && !empty($scene_url)) {
  2171. $scene_map[$scene_name] = $scene_url;
  2172. }
  2173. }
  2174. $segment_id = $segment->segment_id;
  2175. $original_segment_content = $segment->segment_content;
  2176. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2177. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2178. if (empty($final_segment_content)) {
  2179. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2180. }
  2181. try {
  2182. $dubTaskId = 0;
  2183. DB::beginTransaction();
  2184. $new_segment_number = $segment_number + 1;
  2185. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2186. // 分镜剧本数组
  2187. $insert_data = [
  2188. 'anime_id' => $anime_id,
  2189. 'episode_id' => $episode_id,
  2190. 'episode_number' => $episode_number,
  2191. 'act_number' => getProp($segment, 'act_number'),
  2192. 'act_title' => getProp($segment, 'act_title'),
  2193. 'segment_id' => $segment_id,
  2194. 'segment_number' => $new_segment_number,
  2195. 'segment_content' => $final_segment_content,
  2196. 'img_url' => $img_url,
  2197. 'video_url' => $video_url,
  2198. 'created_at' => date('Y-m-d H:i:s'),
  2199. 'updated_at' => date('Y-m-d H:i:s')
  2200. ];
  2201. // 更新分镜剧本信息
  2202. $this->handleSegmentContent($insert_data);
  2203. // 如果有对话内容,创建视频配音合成任务
  2204. $dialogue = getProp($insert_data, 'dialogue');
  2205. if (!empty($dialogue)) {
  2206. $now = date('Y-m-d H:i:s');
  2207. $generate_json = [
  2208. 'text' => $dialogue,
  2209. 'role' => getProp($insert_data, 'voice_actor'),
  2210. 'voice_type' => getProp($insert_data, 'voice_type'),
  2211. 'voice_name' => getProp($insert_data, 'voice_name'),
  2212. 'emotion' => getProp($insert_data, 'emotion'),
  2213. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2214. 'gender' => getProp($insert_data, 'gender'),
  2215. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2216. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2217. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2218. 'pitch' => getProp($insert_data, 'pitch', 0),
  2219. ];
  2220. // 插入视频配音合成任务
  2221. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2222. 'alias_segment_id' => $segment_id,
  2223. 'generate_status' => '执行中',
  2224. 'audio_url' => '',
  2225. 'generate_json' => json_encode($generate_json, 256),
  2226. 'created_at' => $now,
  2227. 'updated_at' => $now,
  2228. ]);
  2229. if (!$dubTaskId) {
  2230. Utils::throwError('20003:创建配音任务失败!');
  2231. }
  2232. $insert_data['audio_url'] = '';
  2233. } else {
  2234. // dialogue为空时,直接写入默认音频信息
  2235. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2236. $insert_data['audio_duration'] = 2.0;
  2237. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2238. }
  2239. // 如果没有上传图片则使用当前描述进行生成
  2240. if (!$img_url) {
  2241. // 解析分镜内容,提取画面描述作为主要提示词
  2242. $prompt = $final_segment_content;
  2243. $ref_img_urls = [];
  2244. // 分镜场景
  2245. $scene = getProp($insert_data, 'scene');
  2246. if ($scene) {
  2247. $matched_scene = '';
  2248. if (isset($scene_map[$scene])) {
  2249. $img_index = count($ref_img_urls) + 1;
  2250. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2251. $ref_img_urls[] = $scene_map[$scene];
  2252. $matched_scene = $scene;
  2253. }
  2254. $update_data['scene'] = $scene;
  2255. }
  2256. // 分镜角色
  2257. $characters = getProp($insert_data, 'characters');
  2258. if ($characters) {
  2259. $update_data['characters'] = $characters;
  2260. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2261. $characters = explode(',', $characters);
  2262. // 从分镜内容中提取涉及的角色
  2263. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2264. // 获取匹配角色的参考图
  2265. foreach ($segment_characters as $character) {
  2266. if (isset($role_map[$character])) {
  2267. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2268. $img_index = count($ref_img_urls) + 1;
  2269. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2270. $ref_img_urls[] = $role_map[$character];
  2271. }
  2272. }
  2273. }
  2274. // 如果没有找到匹配的角色参考图,不使用参考图
  2275. if (empty($ref_img_urls)) {
  2276. $ref_img_urls = [];
  2277. }
  2278. // 准备生成任务参数
  2279. $params = [
  2280. 'alias_segment_id' => $segment_id,
  2281. 'prompt' => $prompt,
  2282. 'ref_img_urls' => $ref_img_urls,
  2283. 'width' => $width,
  2284. 'height' => $height,
  2285. ];
  2286. // 调用AI图片生成服务
  2287. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2288. $task_id = $task->id;
  2289. // $task_id = 'whatever';
  2290. if (!$task_id) {
  2291. Utils::throwError('20003:创建生成任务失败!');
  2292. }
  2293. $insert_data['pic_task_status'] = '生成中';
  2294. $insert_data['pic_task_id'] = $task_id;
  2295. }
  2296. // 先更新序号
  2297. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2298. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2299. if (!$boolen) {
  2300. Utils::throwError('20003:新增分镜失败!');
  2301. }
  2302. // 如果是第一集的首帧图片,则存入待更新数组
  2303. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2304. Redis::sadd('anime_first_frame_urls', $segment_id);
  2305. }
  2306. if ($dubTaskId) {
  2307. // 请求远程服务器执行生成
  2308. $client = new Client(['timeout' => 300, 'verify' => false]);
  2309. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2310. $response = $result->getBody()->getContents();
  2311. $response_arr = json_decode($response, true);
  2312. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2313. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2314. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2315. Utils::throwError('20003:火山生成音频失败');
  2316. }
  2317. }
  2318. } catch (\Exception $e) {
  2319. DB::rollBack();
  2320. Utils::throwError('20003:'.$e->getMessage());
  2321. }
  2322. DB::commit();
  2323. // 创建任务之后先暂停10s等待异步任务完成
  2324. sleep(10);
  2325. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2326. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2327. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2328. $segment = $segment ? (array)$segment : [];
  2329. return $segment;
  2330. }
  2331. public function copySegment($data) {
  2332. $segment_id = getProp($data, 'segment_id');
  2333. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2334. if (!$segment) Utils::throwError('20003:请选择分镜');
  2335. $anime_id = getProp($segment, 'anime_id');
  2336. $episode_id = getProp($segment, 'episode_id');
  2337. $episode_number = getProp($segment, 'episode_number');
  2338. $segment_number = getProp($segment, 'segment_number');
  2339. $new_segment_id = 0;
  2340. try {
  2341. DB::beginTransaction();
  2342. $segment = (array)$segment;
  2343. unset($segment['id']);
  2344. $segment['segment_number'] += 1;
  2345. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2346. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2347. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2348. // 更新其他分镜序号
  2349. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2350. // 复制分镜
  2351. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2352. if (!$id) {
  2353. Utils::throwError('20003:复制分镜失败');
  2354. }
  2355. }catch (\Exception $e) {
  2356. DB::rollBack();
  2357. Utils::throwError('20003:'.$e->getMessage());
  2358. }
  2359. DB::commit();
  2360. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2361. $segment = $segment ? (array)$segment : [];
  2362. return $segment;
  2363. }
  2364. public function moveSegment($data) {
  2365. $segment_id = getProp($data, 'segment_id');
  2366. $target_segment_id = getProp($data, 'target_segment_id');
  2367. // 获取源分镜信息
  2368. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2369. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2370. // 获取目标分镜信息
  2371. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2372. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2373. $anime_id = getProp($source_segment, 'anime_id');
  2374. $episode_id = getProp($source_segment, 'episode_id');
  2375. $episode_number = getProp($source_segment, 'episode_number');
  2376. $source_segment_number = getProp($source_segment, 'segment_number');
  2377. $target_segment_number = getProp($target_segment, 'segment_number');
  2378. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2379. $target_anime_id = getProp($target_segment, 'anime_id');
  2380. $target_episode_number = getProp($target_segment, 'episode_number');
  2381. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2382. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2383. }
  2384. // 如果源分镜和目标分镜相同,无需移动
  2385. if ($source_segment_number == $target_segment_number) {
  2386. return true;
  2387. }
  2388. try {
  2389. DB::beginTransaction();
  2390. if ($source_segment_number < $target_segment_number) {
  2391. // 向后移动:源分镜移动到目标分镜之后
  2392. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2393. DB::table('mp_episode_segments')
  2394. ->where('anime_id', $anime_id)
  2395. ->where('episode_id', $episode_id)
  2396. ->where('segment_number', '>', $source_segment_number)
  2397. ->where('segment_number', '<=', $target_segment_number)
  2398. ->decrement('segment_number');
  2399. // 2. 将源分镜移动到目标分镜之后
  2400. $new_segment_number = $target_segment_number;
  2401. } else {
  2402. // 向前移动:源分镜移动到目标分镜之后
  2403. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2404. DB::table('mp_episode_segments')
  2405. ->where('anime_id', $anime_id)
  2406. ->where('episode_id', $episode_id)
  2407. ->where('segment_number', '>', $target_segment_number)
  2408. ->where('segment_number', '<', $source_segment_number)
  2409. ->increment('segment_number');
  2410. // 2. 将源分镜移动到目标分镜之后
  2411. $new_segment_number = $target_segment_number + 1;
  2412. }
  2413. // 3. 更新源分镜的序号
  2414. $update_result = DB::table('mp_episode_segments')
  2415. ->where('segment_id', $segment_id)
  2416. ->update([
  2417. 'segment_number' => $new_segment_number,
  2418. 'updated_at' => date('Y-m-d H:i:s')
  2419. ]);
  2420. if (!$update_result) {
  2421. Utils::throwError('20003:更新分镜序号失败');
  2422. }
  2423. DB::commit();
  2424. return true;
  2425. } catch (\Exception $e) {
  2426. DB::rollBack();
  2427. Utils::throwError('20003:' . $e->getMessage());
  2428. }
  2429. }
  2430. public function delSegment($data) {
  2431. $segment_id = getProp($data, 'segment_id');
  2432. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2433. if (!$segment) Utils::throwError('20003:请选择分镜');
  2434. $anime_id = getProp($segment, 'anime_id');
  2435. $episode_id = getProp($segment, 'episode_id');
  2436. $episode_number = getProp($segment, 'episode_number');
  2437. $segment_number = getProp($segment, 'segment_number');
  2438. try {
  2439. DB::beginTransaction();
  2440. // 删除分镜
  2441. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2442. if (!$boolen) {
  2443. Utils::throwError('20003:删除分镜失败');
  2444. }
  2445. // 更新其他分镜序号
  2446. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2447. }catch (\Exception $e) {
  2448. DB::rollBack();
  2449. Utils::throwError('20003:'.$e->getMessage());
  2450. }
  2451. DB::commit();
  2452. return true;
  2453. }
  2454. public function applySegment($data) {
  2455. $segment_id = getProp($data, 'segment_id');
  2456. $url = getProp($data, 'url');
  2457. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2458. if (!$url) Utils::throwError('20003:URL不能为空');
  2459. // 获取URL的文件扩展名
  2460. $urlPath = parse_url($url, PHP_URL_PATH);
  2461. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2462. // 定义图片和视频的扩展名
  2463. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2464. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2465. // 判断是图片还是视频
  2466. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2467. if (in_array($extension, $imageExtensions)) {
  2468. // 图片类型
  2469. $updateData['img_url'] = $url;
  2470. $updateData['current_type'] = 1;
  2471. } elseif (in_array($extension, $videoExtensions)) {
  2472. // 视频类型
  2473. $updateData['video_url'] = $url;
  2474. $updateData['current_type'] = 2;
  2475. } else {
  2476. Utils::throwError('20003:不支持的文件类型');
  2477. }
  2478. // 更新分镜表
  2479. $result = DB::table('mp_episode_segments')
  2480. ->where('segment_id', $segment_id)
  2481. ->update($updateData);
  2482. if (!$result) {
  2483. Utils::throwError('20003:更新分镜失败');
  2484. }
  2485. return true;
  2486. }
  2487. public function segmentHistory($data) {
  2488. $segment_id = getProp($data, 'segment_id');
  2489. // 获取历史图片
  2490. $pics = [];
  2491. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2492. foreach($pic_history as $task) {
  2493. $result_url = getProp($task, 'result_url');
  2494. if (is_json($result_url)) {
  2495. $pics = array_merge($pics, json_decode($result_url, true));
  2496. }else {
  2497. $pics[] = $result_url;
  2498. }
  2499. }
  2500. // 获取历史视频
  2501. $videos = [];
  2502. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2503. foreach($video_history as $task) {
  2504. $result_url = getProp($task, 'result_url');
  2505. if (is_json($result_url)) {
  2506. $videos = array_merge($videos, json_decode($result_url, true));
  2507. }else {
  2508. $videos[] = $result_url;
  2509. }
  2510. }
  2511. return compact('pics', 'videos');
  2512. }
  2513. public function addAct($data) {
  2514. $prev_act_id = getProp($data, 'prev_act_id');
  2515. $act_title = getProp($data, 'act_title', '');
  2516. $act_content = getProp($data, 'act_content', '');
  2517. $act_duration = getProp($data, 'act_duration', 5);
  2518. $video_url = getProp($data, 'video_url');
  2519. // 根据prev_act_id获取记录
  2520. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2521. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2522. $anime_id = getProp($prev_segment, 'anime_id');
  2523. $episode_id = getProp($prev_segment, 'episode_id');
  2524. $episode_number = getProp($prev_segment, 'episode_number');
  2525. $prev_act_number = getProp($prev_segment, 'act_number');
  2526. // 获取新的act_number
  2527. $new_act_number = $prev_act_number + 1;
  2528. try {
  2529. DB::beginTransaction();
  2530. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2531. DB::table('mp_episode_segments')
  2532. ->where('anime_id', $anime_id)
  2533. ->where('episode_id', $episode_id)
  2534. ->where('act_number', '>', $prev_act_number)
  2535. ->increment('act_number');
  2536. // 插入新片段记录
  2537. $insert_data = [
  2538. 'anime_id' => $anime_id,
  2539. 'episode_id' => $episode_id,
  2540. 'episode_number' => $episode_number,
  2541. 'act_number' => $new_act_number,
  2542. 'created_at' => date('Y-m-d H:i:s'),
  2543. 'updated_at' => date('Y-m-d H:i:s')
  2544. ];
  2545. if ($act_title) {
  2546. $insert_data['act_title'] = $act_title;
  2547. }
  2548. if ($act_content) {
  2549. $insert_data['act_content'] = $act_content;
  2550. }
  2551. if ($act_duration) {
  2552. $insert_data['act_duration'] = $act_duration;
  2553. }
  2554. if ($video_url) {
  2555. $insert_data['origin_video_url'] = $video_url;
  2556. $insert_data['current_type'] = 2;
  2557. $compressed_video_url = compressVideo($video_url);
  2558. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2559. }
  2560. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2561. if (!$id) {
  2562. Utils::throwError('20003:新增片段失败!');
  2563. }
  2564. DB::commit();
  2565. }catch (\Exception $e) {
  2566. DB::rollBack();
  2567. Utils::throwError('20003:'.$e->getMessage());
  2568. }
  2569. $segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
  2570. $segment = $segment ? (array)$segment : [];
  2571. return $segment;
  2572. }
  2573. public function editAct($data) {
  2574. $act_id = getProp($data, 'act_id');
  2575. $act_content = getProp($data, 'act_content');
  2576. $act_duration = getProp($data, 'act_duration');
  2577. $act_title = getProp($data, 'act_title');
  2578. $image_url = getProp($data, 'image_url');
  2579. $video_url = getProp($data, 'video_url');
  2580. // 参数验证
  2581. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2582. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2583. $segment = DB::table('mp_episode_segments')
  2584. ->where('id', $act_id)
  2585. ->first();
  2586. if (!$segment) Utils::throwError('20003:该片段不存在');
  2587. try {
  2588. DB::beginTransaction();
  2589. // 准备更新数据
  2590. $update_data = [
  2591. 'updated_at' => date('Y-m-d H:i:s')
  2592. ];
  2593. // 更新act相关字段
  2594. if (!empty($act_content)) {
  2595. $update_data['act_show_content'] = $act_content;
  2596. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2597. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2598. $shot_counter = 0;
  2599. $update_data['act_show_content'] = preg_replace_callback(
  2600. '/【(?:镜头|分镜)(\d+)】/u',
  2601. function($matches) use (&$shot_counter) {
  2602. $shot_counter++;
  2603. return '【镜头' . $shot_counter . '】';
  2604. },
  2605. $update_data['act_show_content']
  2606. );
  2607. }
  2608. if (!empty($act_duration)) {
  2609. $update_data['act_duration'] = $act_duration;
  2610. }
  2611. if (!empty($act_title)) {
  2612. $update_data['act_title'] = $act_title;
  2613. }
  2614. // 处理图片上传
  2615. if ($image_url) {
  2616. $update_data['img_url'] = $image_url;
  2617. $update_data['current_type'] = 1;
  2618. // 同时写入一个图片生成任务记录
  2619. if ($act_id) {
  2620. $pic_task = [
  2621. 'alias_act_id' => $act_id,
  2622. 'ref_img_url' => json_encode([]),
  2623. 'status' => 'success',
  2624. 'result_url' => json_encode([$image_url], 256),
  2625. 'model' => '',
  2626. 'created_at' => date('Y-m-d H:i:s'),
  2627. 'updated_at' => date('Y-m-d H:i:s'),
  2628. ];
  2629. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2630. }
  2631. }
  2632. // 处理视频上传
  2633. if ($video_url) {
  2634. $update_data['origin_video_url'] = $video_url;
  2635. $compressed_video_url = compressVideo($video_url);
  2636. $update_data['current_type'] = 2;
  2637. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2638. // 同时写入一个视频生成任务记录
  2639. if ($act_id) {
  2640. $video_task = [
  2641. 'alias_act_id' => $act_id,
  2642. 'status' => 'success',
  2643. 'result_url' => $update_data['origin_video_url'],
  2644. 'compressed_url' => $update_data['video_url'],
  2645. 'created_at' => date('Y-m-d H:i:s'),
  2646. 'updated_at' => date('Y-m-d H:i:s'),
  2647. ];
  2648. DB::table('mp_generate_video_tasks')->insert($video_task);
  2649. }
  2650. }
  2651. // 更新片段信息
  2652. $result = DB::table('mp_episode_segments')
  2653. ->where('id', $act_id)
  2654. ->update($update_data);
  2655. if ($result === false) {
  2656. Utils::throwError('20003:更新片段失败');
  2657. }
  2658. DB::commit();
  2659. // 返回新复制的记录
  2660. $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,act_show_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $act_id)->first();
  2661. $new_segment = (array)$new_segment;
  2662. return $new_segment;
  2663. } catch (\Exception $e) {
  2664. DB::rollBack();
  2665. dLog('anime')->error('更新片段失败', [
  2666. 'act_id' => $act_id,
  2667. 'error' => $e->getMessage()
  2668. ]);
  2669. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2670. }
  2671. }
  2672. public function copyAct($data) {
  2673. $act_id = getProp($data, 'act_id');
  2674. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2675. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2676. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2677. $anime_id = getProp($source_segment, 'anime_id');
  2678. $episode_id = getProp($source_segment, 'episode_id');
  2679. $episode_number = getProp($source_segment, 'episode_number');
  2680. $act_number = getProp($source_segment, 'act_number');
  2681. try {
  2682. DB::beginTransaction();
  2683. // 新act的编号
  2684. $new_act_number = $act_number + 1;
  2685. // 更新后续所有act的act_number
  2686. DB::table('mp_episode_segments')
  2687. ->where('anime_id', $anime_id)
  2688. ->where('episode_id', $episode_id)
  2689. ->where('act_number', '>', $act_number)
  2690. ->increment('act_number');
  2691. // 复制该片段记录
  2692. $segment_data = (array)$source_segment;
  2693. unset($segment_data['id']);
  2694. $segment_data['video_url'] = '';
  2695. $segment_data['video_task_id'] = '';
  2696. $segment_data['video_task_status'] = '';
  2697. $segment_data['act_number'] = $new_act_number;
  2698. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2699. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2700. if (!$id) {
  2701. Utils::throwError('20003:复制片段失败');
  2702. }
  2703. DB::commit();
  2704. }catch (\Exception $e) {
  2705. DB::rollBack();
  2706. Utils::throwError('20003:'.$e->getMessage());
  2707. }
  2708. // 返回新复制的记录
  2709. $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,act_show_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
  2710. $new_segment = $new_segment ? (array)$new_segment : [];
  2711. $new_segment['act_id'] = $id;
  2712. return $new_segment;
  2713. }
  2714. public function moveAct($data) {
  2715. $act_id = getProp($data, 'act_id');
  2716. $target_act_id = getProp($data, 'target_act_id');
  2717. // 获取源片段信息
  2718. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2719. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2720. // 获取目标片段信息
  2721. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2722. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2723. $anime_id = getProp($source_segment, 'anime_id');
  2724. $episode_id = getProp($source_segment, 'episode_id');
  2725. $source_act_number = getProp($source_segment, 'act_number');
  2726. $target_act_number = getProp($target_segment, 'act_number');
  2727. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2728. $target_anime_id = getProp($target_segment, 'anime_id');
  2729. $target_episode_id = getProp($target_segment, 'episode_id');
  2730. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2731. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2732. }
  2733. // 如果源片段和目标片段相同,无需移动
  2734. if ($source_act_number == $target_act_number) {
  2735. return true;
  2736. }
  2737. try {
  2738. DB::beginTransaction();
  2739. if ($source_act_number < $target_act_number) {
  2740. // 向后移动:源片段移动到目标片段之后
  2741. // 1. 将源片段和目标片段之间的所有片段编号减1
  2742. DB::table('mp_episode_segments')
  2743. ->where('anime_id', $anime_id)
  2744. ->where('episode_id', $episode_id)
  2745. ->where('act_number', '>', $source_act_number)
  2746. ->where('act_number', '<=', $target_act_number)
  2747. ->decrement('act_number');
  2748. // 2. 将源片段移动到目标片段之后
  2749. $new_act_number = $target_act_number;
  2750. } else {
  2751. // 向前移动:源片段移动到目标片段之后
  2752. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2753. DB::table('mp_episode_segments')
  2754. ->where('anime_id', $anime_id)
  2755. ->where('episode_id', $episode_id)
  2756. ->where('act_number', '>', $target_act_number)
  2757. ->where('act_number', '<', $source_act_number)
  2758. ->increment('act_number');
  2759. // 2. 将源片段移动到目标片段之后
  2760. $new_act_number = $target_act_number + 1;
  2761. }
  2762. // 3. 更新源片段的编号
  2763. $update_result = DB::table('mp_episode_segments')
  2764. ->where('id', $act_id)
  2765. ->update([
  2766. 'act_number' => $new_act_number,
  2767. 'updated_at' => date('Y-m-d H:i:s')
  2768. ]);
  2769. if (!$update_result) {
  2770. Utils::throwError('20003:更新片段编号失败');
  2771. }
  2772. DB::commit();
  2773. return true;
  2774. } catch (\Exception $e) {
  2775. DB::rollBack();
  2776. Utils::throwError('20003:' . $e->getMessage());
  2777. }
  2778. }
  2779. public function delAct($data) {
  2780. $act_id = getProp($data, 'act_id');
  2781. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2782. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2783. if (!$segment) Utils::throwError('20003:请选择片段');
  2784. $anime_id = getProp($segment, 'anime_id');
  2785. $episode_id = getProp($segment, 'episode_id');
  2786. $act_number = getProp($segment, 'act_number');
  2787. try {
  2788. DB::beginTransaction();
  2789. // 删除该片段记录
  2790. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2791. if (!$deleted) {
  2792. Utils::throwError('20003:删除片段失败');
  2793. }
  2794. // 更新后续act的编号
  2795. DB::table('mp_episode_segments')
  2796. ->where('anime_id', $anime_id)
  2797. ->where('episode_id', $episode_id)
  2798. ->where('act_number', '>', $act_number)
  2799. ->decrement('act_number');
  2800. DB::commit();
  2801. }catch (\Exception $e) {
  2802. DB::rollBack();
  2803. Utils::throwError('20003:'.$e->getMessage());
  2804. }
  2805. return true;
  2806. }
  2807. public function applyAct($data) {
  2808. $act_id = getProp($data, 'act_id');
  2809. $url = getProp($data, 'url');
  2810. if (!$act_id) Utils::throwError('20003:请选择片段');
  2811. if (!$url) Utils::throwError('20003:URL不能为空');
  2812. // 获取URL的文件扩展名
  2813. $urlPath = parse_url($url, PHP_URL_PATH);
  2814. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2815. // 定义图片和视频的扩展名
  2816. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2817. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2818. // 判断是图片还是视频
  2819. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2820. if (in_array($extension, $imageExtensions)) {
  2821. // 图片类型
  2822. $updateData['img_url'] = $url;
  2823. $updateData['current_type'] = 1;
  2824. } elseif (in_array($extension, $videoExtensions)) {
  2825. // 视频类型
  2826. $updateData['video_url'] = $url;
  2827. $updateData['current_type'] = 2;
  2828. } else {
  2829. Utils::throwError('20003:不支持的文件类型');
  2830. }
  2831. // 更新片段记录(全能模式下每个act只有一条记录)
  2832. $result = DB::table('mp_episode_segments')
  2833. ->where('id', $act_id)
  2834. ->update($updateData);
  2835. if (!$result) {
  2836. Utils::throwError('20003:更新片段失败');
  2837. }
  2838. return true;
  2839. }
  2840. public function actChatHistory($data) {
  2841. $act_id = getProp($data, 'act_id');
  2842. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2843. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2844. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2845. $value = (array)$value;
  2846. $value['created_at'] = transDate($value['created_at']);
  2847. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2848. else $value['reference_images'] = [];
  2849. return $value;
  2850. })->toArray();
  2851. // 获取历史图片
  2852. $url = [];
  2853. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2854. foreach($pic_history as $task) {
  2855. $result_url = getProp($task, 'result_url');
  2856. if (is_json($result_url)) {
  2857. $url = array_merge($url, json_decode($result_url, true));
  2858. }else {
  2859. $url[] = $result_url;
  2860. }
  2861. }
  2862. // 获取历史视频
  2863. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2864. foreach($video_history as $task) {
  2865. $result_url = getProp($task, 'result_url');
  2866. if (is_json($result_url)) {
  2867. $url = array_merge($url, json_decode($result_url, true));
  2868. }else {
  2869. $url[] = $result_url;
  2870. }
  2871. }
  2872. // 获取资产库
  2873. $products = [];
  2874. // 通过act_id查询片段信息获取episode_id
  2875. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2876. if ($segment) {
  2877. $episode_id = getProp($segment, 'episode_id');
  2878. // 查询剧集信息获取roles、scenes和extra_products
  2879. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2880. if ($episode) {
  2881. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2882. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2883. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2884. // 先合并roles和scenes
  2885. // 处理角色数组
  2886. foreach ($roles as $role) {
  2887. $product = $role;
  2888. // 将role字段重命名为product_name
  2889. if (isset($product['role'])) {
  2890. $product['product_name'] = $product['role'];
  2891. unset($product['role']);
  2892. }
  2893. $product['product'] = 1; // 标记类型为角色
  2894. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2895. }
  2896. // 处理场景数组
  2897. foreach ($scenes as $scene) {
  2898. $product = $scene;
  2899. // 将scene字段重命名为product_name
  2900. if (isset($product['scene'])) {
  2901. $product['product_name'] = $product['scene'];
  2902. unset($product['scene']);
  2903. }
  2904. $product['product'] = 2; // 标记类型为场景
  2905. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2906. }
  2907. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2908. foreach ($extra_products as $extra_product) {
  2909. $product_name = getProp($extra_product, 'product_name');
  2910. if ($product_name) {
  2911. $products[$product_name] = $extra_product; // 覆盖同名数据
  2912. }
  2913. }
  2914. // 重新索引数组(去除key)
  2915. $products = array_values($products);
  2916. }
  2917. }
  2918. // 获取执行中的任务
  2919. $tasks = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->whereNotIn('status', ['success', 'failed'])->select('id as task_id', 'alias_act_id', 'prompt', 'ref_image_url', 'status')->orderBy('id')->get()->map(function($value) {
  2920. $value = (array)$value;
  2921. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2922. else $value['ref_image_url'] = [];
  2923. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2924. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2925. if (!empty($value['prompt'])) {
  2926. $prompt = $value['prompt'];
  2927. // 查找第一个【镜头】的位置
  2928. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2929. // 从【镜头】开始截取
  2930. $prompt = substr($prompt, $matches[0][1]);
  2931. }
  2932. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2933. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2934. $value['prompt'] = $prompt;
  2935. }
  2936. return $value;
  2937. })->toArray();
  2938. return compact('chat', 'url', 'products', 'tasks');
  2939. }
  2940. public function applyAudioData($data) {
  2941. $segment_id = getProp($data, 'segment_id');
  2942. $global_data = getProp($data, 'global_data');
  2943. $segment_data = getProp($data, 'segment_data');
  2944. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2945. $global_data = is_array($global_data) ? $global_data : [];
  2946. $segment_data = is_array($segment_data) ? $segment_data : [];
  2947. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2948. $dialogue_item = null;
  2949. foreach ($global_data as $key => $item) {
  2950. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2951. $dialogue_item = $item;
  2952. unset($global_data[$key]);
  2953. break;
  2954. }
  2955. }
  2956. if ($dialogue_item) {
  2957. $segment_data[] = $dialogue_item;
  2958. }
  2959. // 特殊参数: audio_url,audio_duration,subtitle_info
  2960. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2961. // 如果不是全部存在,则仍需创建音频任务
  2962. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2963. $special_update_data = [];
  2964. $has_all_special_params = false;
  2965. // 从segment_data中提取特殊参数
  2966. $filtered_segment_data = [];
  2967. foreach ($segment_data as $item) {
  2968. $field_name = trim((string)getProp($item, 'name'));
  2969. if (in_array($field_name, $special_fields)) {
  2970. $special_update_data[$field_name] = getProp($item, 'value');
  2971. } else {
  2972. // 非特殊参数保留,继续后续处理
  2973. $filtered_segment_data[] = $item;
  2974. }
  2975. }
  2976. // 检查是否三个特殊参数都存在
  2977. if (count($special_update_data) === 3 &&
  2978. isset($special_update_data['audio_url']) &&
  2979. isset($special_update_data['audio_duration']) &&
  2980. isset($special_update_data['subtitle_info'])) {
  2981. $has_all_special_params = true;
  2982. // 立即更新到当前分镜
  2983. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  2984. DB::table('mp_episode_segments')
  2985. ->where('segment_id', $segment_id)
  2986. ->update($special_update_data);
  2987. }
  2988. // 使用过滤后的segment_data继续处理其他参数
  2989. $segment_data = $filtered_segment_data;
  2990. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  2991. $global_update_data = [];
  2992. $segment_update_data = [];
  2993. $global_voice_type = '';
  2994. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2995. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  2996. $episode_id = getProp($target_segment, 'episode_id');
  2997. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  2998. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2999. if (!$episode) Utils::throwError('20003:分集不存在');
  3000. foreach ($global_data as $item) {
  3001. $field_name = trim((string)getProp($item, 'name'));
  3002. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3003. continue;
  3004. }
  3005. $global_update_data[$field_name] = getProp($item, 'value');
  3006. if ($field_name === 'voice_type') {
  3007. $global_voice_type = trim((string)getProp($item, 'value'));
  3008. }
  3009. }
  3010. foreach ($segment_data as $item) {
  3011. $field_name = trim((string)getProp($item, 'name'));
  3012. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3013. continue;
  3014. }
  3015. $segment_update_data[$field_name] = getProp($item, 'value');
  3016. }
  3017. if ($global_voice_type) {
  3018. $timbre_info = DB::table('mp_timbres')
  3019. ->where('timbre_type', $global_voice_type)
  3020. ->select('audio_url', 'timbre_name')
  3021. ->first();
  3022. if ($timbre_info) {
  3023. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3024. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3025. }
  3026. }
  3027. try {
  3028. DB::beginTransaction();
  3029. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3030. $segment_ids_to_create_task = [];
  3031. $segments_data = [];
  3032. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3033. if (!empty($global_update_data)) {
  3034. // 如果角色不存在,则只更新当前分镜
  3035. if (!$target_voice_actor) {
  3036. // 只处理当前分镜
  3037. $affected_segments = DB::table('mp_episode_segments')
  3038. ->where('segment_id', $segment_id)
  3039. ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3040. ->get();
  3041. } else {
  3042. // 获取该角色的所有分镜
  3043. $affected_segments = DB::table('mp_episode_segments')
  3044. ->where('episode_id', $episode_id)
  3045. ->where('voice_actor', $target_voice_actor)
  3046. ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3047. ->get();
  3048. }
  3049. foreach ($affected_segments as $seg) {
  3050. $seg = (array)$seg;
  3051. $sid = getProp($seg, 'segment_id');
  3052. // 检查参数是否发生变化
  3053. $has_changed = false;
  3054. foreach ($global_update_data as $field => $new_value) {
  3055. $old_value = getProp($seg, $field);
  3056. if ($old_value != $new_value) {
  3057. $has_changed = true;
  3058. break;
  3059. }
  3060. }
  3061. if ($has_changed) {
  3062. $segment_ids_to_create_task[] = $sid;
  3063. $segments_data[$sid] = $seg;
  3064. }
  3065. }
  3066. // 只有在有变化的分镜时才更新
  3067. if (!empty($segment_ids_to_create_task)) {
  3068. $global_segment_update_data = $global_update_data;
  3069. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3070. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3071. DB::table('mp_episode_segments')
  3072. ->where('episode_id', $episode_id)
  3073. ->where('voice_actor', $target_voice_actor)
  3074. ->whereIn('segment_id', $segment_ids_to_create_task)
  3075. ->update($global_segment_update_data);
  3076. }
  3077. if ($global_voice_type) {
  3078. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3079. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3080. $roles_updated = false;
  3081. foreach ($episode_roles as &$role) {
  3082. // 通过 role 字段匹配角色名,而不是 voice_name
  3083. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3084. continue;
  3085. }
  3086. $role['voice_type'] = $global_voice_type;
  3087. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3088. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3089. $roles_updated = true;
  3090. }
  3091. unset($role);
  3092. if ($roles_updated) {
  3093. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3094. 'roles' => json_encode($episode_roles, 256),
  3095. 'updated_at' => date('Y-m-d H:i:s'),
  3096. ]);
  3097. }
  3098. }
  3099. }
  3100. // 如果有单个分镜更新,检查是否有变化
  3101. if (!empty($segment_update_data)) {
  3102. // 获取当前分镜数据
  3103. $current_segment = DB::table('mp_episode_segments')
  3104. ->where('segment_id', $segment_id)
  3105. ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3106. ->first();
  3107. if ($current_segment) {
  3108. $current_segment = (array)$current_segment;
  3109. // 检查参数是否发生变化
  3110. $has_changed = false;
  3111. foreach ($segment_update_data as $field => $new_value) {
  3112. $old_value = getProp($current_segment, $field);
  3113. if ($old_value != $new_value) {
  3114. $has_changed = true;
  3115. break;
  3116. }
  3117. }
  3118. if ($has_changed) {
  3119. // 如果该分镜还未在列表中,添加进去
  3120. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3121. $segment_ids_to_create_task[] = $segment_id;
  3122. $segments_data[$segment_id] = $current_segment;
  3123. }
  3124. // 更新分镜数据并清空音频URL
  3125. $segment_update_data['audio_url'] = '';
  3126. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3127. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3128. }
  3129. }
  3130. }
  3131. // 为所有有变化的分镜创建音频合成任务
  3132. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3133. if (!empty($segment_ids_to_create_task)) {
  3134. foreach ($segment_ids_to_create_task as $sid) {
  3135. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3136. if ($sid === $segment_id && $has_all_special_params) {
  3137. continue;
  3138. }
  3139. // 重新获取更新后的分镜数据
  3140. $updated_segment = DB::table('mp_episode_segments')
  3141. ->where('segment_id', $sid)
  3142. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3143. ->first();
  3144. if (!$updated_segment) continue;
  3145. $updated_segment = (array)$updated_segment;
  3146. // 检查dialogue是否为空
  3147. $dialogue = getProp($updated_segment, 'dialogue');
  3148. if (empty($dialogue)) {
  3149. // dialogue为空时,直接写入默认音频信息
  3150. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3151. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3152. 'audio_duration' => 2.0,
  3153. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3154. 'updated_at' => date('Y-m-d H:i:s')
  3155. ]);
  3156. continue;
  3157. }
  3158. $generate_json = [
  3159. 'text' => $dialogue,
  3160. 'role' => getProp($updated_segment, 'voice_actor'),
  3161. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3162. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3163. 'emotion' => getProp($updated_segment, 'emotion'),
  3164. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3165. 'gender' => getProp($updated_segment, 'gender'),
  3166. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3167. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3168. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3169. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3170. ];
  3171. // 插入视频配音合成任务
  3172. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3173. 'alias_segment_id' => $sid,
  3174. 'generate_status' => '执行中',
  3175. 'audio_url' => '',
  3176. 'generate_json' => json_encode($generate_json, 256),
  3177. 'created_at' => date('Y-m-d H:i:s'),
  3178. 'updated_at' => date('Y-m-d H:i:s'),
  3179. ]);
  3180. if (!$dubTaskId) {
  3181. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3182. continue;
  3183. }
  3184. // 将任务ID添加到Redis列表中
  3185. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3186. // 请求远程服务器执行生成
  3187. try {
  3188. sleep(1);
  3189. $client = new Client(['timeout' => 300, 'verify' => false]);
  3190. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3191. $response = $result->getBody()->getContents();
  3192. $response_arr = json_decode($response, true);
  3193. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3194. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3195. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3196. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3197. }
  3198. } catch (\Exception $e) {
  3199. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3200. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3201. }
  3202. }
  3203. }
  3204. DB::commit();
  3205. } catch (\Exception $e) {
  3206. DB::rollBack();
  3207. Utils::throwError('20003:'.$e->getMessage());
  3208. }
  3209. return true;
  3210. }
  3211. public function episodePicsInfo($data) {
  3212. $anime_id = getProp($data, 'anime_id');
  3213. $episode_id = getProp($data, 'episode_id');
  3214. // 参数验证
  3215. if (!$anime_id && !$episode_id) {
  3216. Utils::throwError('20003:请提供动漫ID或分集ID');
  3217. }
  3218. // 根据参数获取数据源
  3219. if ($episode_id) {
  3220. // 从剧集表获取
  3221. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3222. if (!$source) Utils::throwError('20003:该剧集不存在');
  3223. $table_name = 'mp_anime_episodes';
  3224. $id_field = 'id';
  3225. $id_value = $episode_id;
  3226. // 获取剧集的anime_id用于继承全局数据
  3227. $anime_id = getProp($source, 'anime_id');
  3228. } else {
  3229. // 从动漫表获取
  3230. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3231. if (!$source) Utils::throwError('20003:该动漫不存在');
  3232. $table_name = 'mp_animes';
  3233. $id_field = 'id';
  3234. $id_value = $anime_id;
  3235. }
  3236. $source = (array)$source;
  3237. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3238. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3239. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3240. // 如果是分集数据,需要处理继承和任务创建逻辑
  3241. if ($episode_id) {
  3242. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3243. }
  3244. // 返回生成器函数,用于 SSE 流式输出
  3245. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3246. $startTime = time();
  3247. $maxDuration = 600; // 10分钟超时
  3248. $checkInterval = 3; // 每3秒检查一次
  3249. // Redis 缓存键
  3250. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3251. // 生成当前数据的哈希值用于比较
  3252. $generateHash = function($roles, $scenes, $props) {
  3253. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3254. };
  3255. // 发送初始数据
  3256. $currentHash = $generateHash($roles, $scenes, $props);
  3257. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3258. echo "data: " . json_encode([
  3259. 'type' => 'init',
  3260. 'data' => [
  3261. 'roles' => $roles,
  3262. 'scenes' => $scenes,
  3263. 'props' => $props,
  3264. 'start_time' => $startTime
  3265. ]
  3266. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3267. if (ob_get_level() > 0) {
  3268. ob_flush();
  3269. }
  3270. flush();
  3271. // 持续轮询任务状态
  3272. while (time() - $startTime < $maxDuration) {
  3273. $hasProcessing = false;
  3274. $updated = false;
  3275. // 检查角色任务状态
  3276. foreach ($roles as $index => &$role) {
  3277. $task_id = getProp($role, 'task_id');
  3278. $task_status = getProp($role, 'task_status');
  3279. $existing_url = getProp($role, 'url');
  3280. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3281. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3282. $hasProcessing = ($task_status === 'processing');
  3283. // 查询任务状态
  3284. $task = DB::table('mp_generate_pic_tasks')
  3285. ->where('id', $task_id)
  3286. ->select('id', 'status', 'result_url', 'error_message')
  3287. ->first();
  3288. if ($task) {
  3289. $task = (array)$task;
  3290. $status = getProp($task, 'status');
  3291. // 如果任务完成或失败
  3292. if (in_array($status, ['success', 'failed'])) {
  3293. $role['task_status'] = $status;
  3294. if ($status === 'success') {
  3295. $result_url = getProp($task, 'result_url');
  3296. if ($result_url) {
  3297. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3298. if (is_array($result_urls) && !empty($result_urls[0])) {
  3299. $role['url'] = $result_urls[0];
  3300. }
  3301. }
  3302. }
  3303. $updated = true;
  3304. } else if ($status === 'processing') {
  3305. $hasProcessing = true;
  3306. }
  3307. }
  3308. }
  3309. }
  3310. // 检查场景任务状态
  3311. foreach ($scenes as $index => &$scene) {
  3312. $task_id = getProp($scene, 'task_id');
  3313. $task_status = getProp($scene, 'task_status');
  3314. $existing_url = getProp($scene, 'url');
  3315. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3316. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3317. $hasProcessing = ($task_status === 'processing');
  3318. // 查询任务状态
  3319. $task = DB::table('mp_generate_pic_tasks')
  3320. ->where('id', $task_id)
  3321. ->select('id', 'status', 'result_url', 'error_message')
  3322. ->first();
  3323. if ($task) {
  3324. $task = (array)$task;
  3325. $status = getProp($task, 'status');
  3326. // 如果任务完成或失败
  3327. if (in_array($status, ['success', 'failed'])) {
  3328. $scene['task_status'] = $status;
  3329. if ($status === 'success') {
  3330. $result_url = getProp($task, 'result_url');
  3331. if ($result_url) {
  3332. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3333. if (is_array($result_urls) && !empty($result_urls[0])) {
  3334. $scene['url'] = $result_urls[0];
  3335. }
  3336. }
  3337. }
  3338. $updated = true;
  3339. } else if ($status === 'processing') {
  3340. $hasProcessing = true;
  3341. }
  3342. }
  3343. }
  3344. }
  3345. // 检查道具任务状态
  3346. foreach ($props as $index => &$prop) {
  3347. $task_id = getProp($prop, 'task_id');
  3348. $task_status = getProp($prop, 'task_status');
  3349. $existing_url = getProp($prop, 'url');
  3350. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3351. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3352. $hasProcessing = ($task_status === 'processing');
  3353. // 查询任务状态
  3354. $task = DB::table('mp_generate_pic_tasks')
  3355. ->where('id', $task_id)
  3356. ->select('id', 'status', 'result_url', 'error_message')
  3357. ->first();
  3358. if ($task) {
  3359. $task = (array)$task;
  3360. $status = getProp($task, 'status');
  3361. // 如果任务完成或失败
  3362. if (in_array($status, ['success', 'failed'])) {
  3363. $prop['task_status'] = $status;
  3364. if ($status === 'success') {
  3365. $result_url = getProp($task, 'result_url');
  3366. if ($result_url) {
  3367. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3368. if (is_array($result_urls) && !empty($result_urls[0])) {
  3369. $prop['url'] = $result_urls[0];
  3370. }
  3371. }
  3372. }
  3373. $updated = true;
  3374. } else if ($status === 'processing') {
  3375. $hasProcessing = true;
  3376. }
  3377. }
  3378. }
  3379. }
  3380. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3381. if ($updated) {
  3382. $newHash = $generateHash($roles, $scenes, $props);
  3383. $cachedHash = Redis::get($cacheKey);
  3384. // 只有当数据真正变化时才更新数据库和发送事件
  3385. if ($newHash !== $cachedHash) {
  3386. try {
  3387. // 更新数据库
  3388. DB::table($table_name)->where($id_field, $id_value)->update([
  3389. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3390. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3391. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3392. 'updated_at' => date('Y-m-d H:i:s')
  3393. ]);
  3394. // 更新缓存
  3395. Redis::setex($cacheKey, 600, $newHash);
  3396. // 发送更新事件
  3397. echo "data: " . json_encode([
  3398. 'type' => 'update',
  3399. 'data' => [
  3400. 'roles' => $roles,
  3401. 'scenes' => $scenes,
  3402. 'props' => $props,
  3403. 'elapsed_time' => time() - $startTime
  3404. ]
  3405. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3406. if (ob_get_level() > 0) {
  3407. ob_flush();
  3408. }
  3409. flush();
  3410. } catch (\Exception $e) {
  3411. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3412. }
  3413. } else {
  3414. // 即使哈希相同,如果有URL更新也要发送事件
  3415. $hasUrlUpdate = false;
  3416. foreach ($roles as $role) {
  3417. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3418. $hasUrlUpdate = true;
  3419. break;
  3420. }
  3421. }
  3422. if (!$hasUrlUpdate) {
  3423. foreach ($scenes as $scene) {
  3424. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3425. $hasUrlUpdate = true;
  3426. break;
  3427. }
  3428. }
  3429. }
  3430. if (!$hasUrlUpdate) {
  3431. foreach ($props as $prop) {
  3432. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3433. $hasUrlUpdate = true;
  3434. break;
  3435. }
  3436. }
  3437. }
  3438. if ($hasUrlUpdate) {
  3439. // 强制更新数据库和发送事件
  3440. try {
  3441. DB::table($table_name)->where($id_field, $id_value)->update([
  3442. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3443. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3444. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3445. 'updated_at' => date('Y-m-d H:i:s')
  3446. ]);
  3447. // 更新缓存
  3448. Redis::setex($cacheKey, 600, $newHash);
  3449. // 发送更新事件
  3450. echo "data: " . json_encode([
  3451. 'type' => 'update',
  3452. 'data' => [
  3453. 'roles' => $roles,
  3454. 'scenes' => $scenes,
  3455. 'props' => $props,
  3456. 'elapsed_time' => time() - $startTime
  3457. ]
  3458. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3459. if (ob_get_level() > 0) {
  3460. ob_flush();
  3461. }
  3462. flush();
  3463. } catch (\Exception $e) {
  3464. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3465. }
  3466. }
  3467. }
  3468. }
  3469. // 如果所有任务都已完成,发送完成事件并退出
  3470. if (!$hasProcessing) {
  3471. // 查询数据库中的最终数据,确保返回最新的完整数据
  3472. try {
  3473. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3474. if ($finalSource) {
  3475. $finalSource = (array)$finalSource;
  3476. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3477. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3478. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3479. // 使用数据库中的最终数据
  3480. $roles = $finalRoles;
  3481. $scenes = $finalScenes;
  3482. $props = $finalProps;
  3483. }
  3484. } catch (\Exception $e) {
  3485. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3486. // 如果查询失败,继续使用内存中的数据
  3487. }
  3488. // 清理缓存
  3489. Redis::del($cacheKey);
  3490. echo "data: " . json_encode([
  3491. 'type' => 'completed',
  3492. 'data' => [
  3493. 'roles' => $roles,
  3494. 'scenes' => $scenes,
  3495. 'props' => $props,
  3496. 'total_time' => time() - $startTime
  3497. ]
  3498. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3499. if (ob_get_level() > 0) {
  3500. ob_flush();
  3501. }
  3502. flush();
  3503. break;
  3504. }
  3505. // 等待下次检查
  3506. sleep($checkInterval);
  3507. }
  3508. // 超时处理
  3509. if (time() - $startTime >= $maxDuration) {
  3510. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3511. try {
  3512. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3513. if ($finalSource) {
  3514. $finalSource = (array)$finalSource;
  3515. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3516. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3517. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3518. // 使用数据库中的最终数据
  3519. $roles = $finalRoles;
  3520. $scenes = $finalScenes;
  3521. $props = $finalProps;
  3522. }
  3523. } catch (\Exception $e) {
  3524. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3525. // 如果查询失败,继续使用内存中的数据
  3526. }
  3527. // 清理缓存
  3528. Redis::del($cacheKey);
  3529. echo "data: " . json_encode([
  3530. 'type' => 'timeout',
  3531. 'message' => '轮询超时,请刷新页面查看最新状态',
  3532. 'data' => [
  3533. 'roles' => $roles,
  3534. 'scenes' => $scenes,
  3535. 'props' => $props
  3536. ]
  3537. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3538. if (ob_get_level() > 0) {
  3539. ob_flush();
  3540. }
  3541. flush();
  3542. }
  3543. };
  3544. }
  3545. public function clipSegmentVideo($data) {
  3546. $segment_id = getProp($data, 'segment_id');
  3547. $video_time_point_start = getProp($data, 'video_time_point_start');
  3548. $video_time_point_end = getProp($data, 'video_time_point_end');
  3549. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3550. Utils::throwError('20003:参数异常');
  3551. }
  3552. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3553. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3554. }
  3555. $video_duration = $video_time_point_end - $video_time_point_start;
  3556. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3557. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3558. 'video_duration' => $video_duration,
  3559. 'video_time_point_start' => $video_time_point_start,
  3560. 'video_time_point_end' => $video_time_point_end,
  3561. 'updated_at' => date('Y-m-d H:i:s')
  3562. ]);
  3563. }
  3564. // 轮训获取图片任务结果
  3565. private function loopGetPicTaskResult($task_id) {
  3566. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3567. if (!$task) {
  3568. return '';
  3569. }
  3570. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3571. $model = getProp($task, 'model');
  3572. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3573. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3574. $isSyncModel = $isVolcModel || $isGptModel;
  3575. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3576. $start_count = 0;
  3577. $img_url = '';
  3578. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3579. sleep(3);
  3580. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3581. // 如果任务已经完成,直接返回结果
  3582. if ($task->status === 'success' && $task->result_url) {
  3583. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3584. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3585. }
  3586. // 如果任务已失败,返回空
  3587. if ($task->status === 'failed') {
  3588. return '';
  3589. }
  3590. if ($isSyncModel) continue;
  3591. // 查询任务状态
  3592. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3593. if ($statusInfo['status'] === 'success') {
  3594. $task->updateStatus('success', [
  3595. 'result_url' => $statusInfo['result_url'],
  3596. 'result_json' => $statusInfo['result_json'] ?? []
  3597. ]);
  3598. // 同步调整分镜图片状态和结果
  3599. if (getProp($task, 'alias_segment_id')) {
  3600. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3601. 'img_url' => $statusInfo['result_url'][0],
  3602. 'pic_task_status' => '已完成',
  3603. ]);
  3604. }
  3605. $img_url = $statusInfo['result_url'][0];
  3606. break;
  3607. } elseif ($statusInfo['status'] === 'failed') {
  3608. $task->updateStatus('failed', [
  3609. 'error_message' => $statusInfo['error_message'],
  3610. 'result_json' => $statusInfo['result_json'] ?? []
  3611. ]);
  3612. if (getProp($task, 'alias_segment_id')) {
  3613. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3614. 'pic_task_status' => '失败',
  3615. ]);
  3616. }
  3617. break;
  3618. }
  3619. $start_count++;
  3620. }
  3621. return $img_url;
  3622. }
  3623. /**
  3624. * 从分镜内容中提取涉及的角色
  3625. */
  3626. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3627. $found_characters = [];
  3628. foreach ($available_characters as $character) {
  3629. // 检查角色名称是否在分镜内容中出现
  3630. if (strpos($segment_content, $character) !== false) {
  3631. $found_characters[] = $character;
  3632. }
  3633. }
  3634. if (!$found_characters) {
  3635. foreach ($roles as $character) {
  3636. // 检查角色名称是否在分镜内容中出现
  3637. if (strpos($segment_content, $character) !== false) {
  3638. $found_characters[] = $character;
  3639. }
  3640. }
  3641. }
  3642. return array_unique($found_characters);
  3643. }
  3644. // 从分镜剧本中提取关键字段
  3645. private function handleSegmentContent(&$data) {
  3646. $segmentContent = getProp($data, 'segment_content');
  3647. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3648. $segmentData = [
  3649. 'description' => '',
  3650. 'composition' => '',
  3651. 'camera_movement' => '',
  3652. 'voice_actor' => '',
  3653. 'dialogue' => '',
  3654. 'frame_type' => '',
  3655. 'scene' => '', // 场景
  3656. 'characters' => '', // 出镜角色
  3657. 'tail_frame' => '', // 尾帧描述
  3658. 'emotion' => '中性', // 情感
  3659. 'gender' => '0', // 性别(0未知,1男,2女)
  3660. 'speed_ratio' => 0, // 语速
  3661. 'loudness_ratio' => 0, // 音量
  3662. 'emotion_scale' => 4, // 情感强度
  3663. 'pitch' => 0, // 音调
  3664. ];
  3665. // 用于存储需要从 segment_content 中移除的匹配项
  3666. $replaceEmptyArr = [];
  3667. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3668. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3669. $segmentData['description'] = trim($descMatch[1]);
  3670. $data['description'] = trim($descMatch[1]);
  3671. }
  3672. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3673. $segmentData['composition'] = trim($compMatch[1]);
  3674. $data['composition'] = trim($compMatch[1]);
  3675. }
  3676. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3677. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3678. $data['camera_movement'] = trim($cameraMatch[1]);
  3679. }
  3680. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3681. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3682. $data['voice_actor'] = trim($voiceMatch[1]);
  3683. }
  3684. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3685. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3686. $data['dialogue'] = trim($dialogueMatch[1]);
  3687. }
  3688. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3689. $segmentData['frame_type'] = trim($frameMatch[1]);
  3690. $data['frame_type'] = trim($frameMatch[1]);
  3691. }
  3692. // 场景字段
  3693. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3694. $segmentData['scene'] = trim($sceneMatch[1]);
  3695. $data['scene'] = trim($sceneMatch[1]);
  3696. }
  3697. // 出镜角色字段
  3698. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3699. $segmentData['characters'] = trim($charactersMatch[1]);
  3700. $data['characters'] = trim($charactersMatch[1]);
  3701. }
  3702. // 尾帧描述字段
  3703. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3704. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3705. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3706. }
  3707. // 情感字段
  3708. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3709. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3710. $segmentData['emotion'] = trim($emotionMatch[1]);
  3711. $data['emotion'] = trim($emotionMatch[1]);
  3712. }
  3713. // 性别字段
  3714. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3715. $replaceEmptyArr[] = trim($genderMatch[0]);
  3716. $genderStr = trim($genderMatch[1]);
  3717. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3718. $segmentData['gender'] = '1';
  3719. $data['gender'] = '1';
  3720. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3721. $segmentData['gender'] = '2';
  3722. $data['gender'] = '2';
  3723. } else {
  3724. $segmentData['gender'] = '0';
  3725. $data['gender'] = '0';
  3726. }
  3727. }
  3728. // 语速字段
  3729. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3730. $replaceEmptyArr[] = trim($speedMatch[0]);
  3731. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3732. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3733. }
  3734. // 音量字段
  3735. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3736. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3737. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3738. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3739. }
  3740. // 情感强度字段
  3741. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3742. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3743. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3744. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3745. }
  3746. // 音调字段
  3747. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3748. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3749. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3750. $data['pitch'] = (int)trim($pitchMatch[1]);
  3751. }
  3752. // 从 segment_content 中移除已提取的配音参数字段
  3753. if (!empty($replaceEmptyArr)) {
  3754. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3755. }
  3756. // 如果有配音角色,查询音色信息并验证情感
  3757. $voice_actor = $segmentData['voice_actor'];
  3758. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3759. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3760. $anime_id = getProp($data, 'anime_id');
  3761. $episode_id = getProp($data, 'episode_id');
  3762. // 优先从剧集的角色列表中查找
  3763. $roles = [];
  3764. if ($episode_id) {
  3765. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3766. if ($episode && getProp($episode, 'roles')) {
  3767. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3768. }
  3769. }
  3770. // 如果剧集中没有,从动漫的角色列表中查找
  3771. if (empty($roles) && $anime_id) {
  3772. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3773. if ($anime && getProp($anime, 'roles')) {
  3774. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3775. }
  3776. }
  3777. // 查找匹配的角色音色信息
  3778. $timbre_info = null;
  3779. foreach ($roles as $role) {
  3780. if (getProp($role, 'role') === $voice_actor) {
  3781. $timbre_info = $role;
  3782. break;
  3783. }
  3784. }
  3785. // 如果找到音色信息,添加到数据中
  3786. if ($timbre_info) {
  3787. $voice_type = getProp($timbre_info, 'voice_type');
  3788. $voice_name = getProp($timbre_info, 'voice_name');
  3789. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3790. if ($voice_type) {
  3791. $data['voice_type'] = $voice_type;
  3792. $segmentData['voice_type'] = $voice_type;
  3793. }
  3794. if ($voice_name) {
  3795. $data['voice_name'] = $voice_name;
  3796. $segmentData['voice_name'] = $voice_name;
  3797. }
  3798. if ($voice_audio_url) {
  3799. $data['voice_audio_url'] = $voice_audio_url;
  3800. $segmentData['voice_audio_url'] = $voice_audio_url;
  3801. }
  3802. // 验证情感是否在音色支持的情感列表中
  3803. if ($voice_type) {
  3804. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3805. if ($timbre_emotion) {
  3806. $timbre_emotion = explode(',', $timbre_emotion);
  3807. } else {
  3808. $timbre_emotion = [];
  3809. }
  3810. $emotion = getProp($segmentData, 'emotion', '中性');
  3811. if (!in_array($emotion, $timbre_emotion)) {
  3812. $emotion = '中性';
  3813. }
  3814. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3815. $emotion_list = array_flip($emotion_list);
  3816. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3817. $data['emotion_type'] = $emotion_type;
  3818. $segmentData['emotion_type'] = $emotion_type;
  3819. }
  3820. }
  3821. }
  3822. return $segmentData;
  3823. }
  3824. public function createSegmentVideoTask($data) {
  3825. $segment_id = getProp($data, 'segment_id');
  3826. $tail_frame = getProp($data, 'tail_frame');
  3827. $first_frame_url = getProp($data, 'first_frame_url');
  3828. $tail_frame_url = getProp($data, 'tail_frame_url');
  3829. $generate_audio = getProp($data, 'generate_audio', 0);
  3830. if (!$segment_id) {
  3831. Utils::throwError('1002:分镜ID不能为空');
  3832. }
  3833. // 获取分镜信息
  3834. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3835. if (!$segment) {
  3836. Utils::throwError('20003:分镜不存在');
  3837. }
  3838. $segment = (array)$segment;
  3839. $episode_id = getProp($segment, 'episode_id');
  3840. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3841. if (!$ratio) $ratio = '9:16';
  3842. // 获取分镜内容
  3843. $segmentContent = getProp($segment, 'segment_content', '');
  3844. // 检查 $segmentContent 中是否已有尾帧描述
  3845. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3846. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3847. $finalTailFrame = '';
  3848. if ($tail_frame) {
  3849. // 用户输入了尾帧描述,优先使用
  3850. $finalTailFrame = $tail_frame;
  3851. // 如果 segmentContent 中已有尾帧描述,需要替换
  3852. if ($contentHasTailFrame) {
  3853. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3854. }
  3855. } elseif ($contentHasTailFrame) {
  3856. // segmentContent 中有尾帧描述,使用它
  3857. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3858. } else {
  3859. // 两者都没有,使用分镜表中的尾帧描述
  3860. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3861. }
  3862. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3863. $hasDialogue = false;
  3864. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3865. $dialogue = trim($dialogueMatch[1]);
  3866. // 如果台词不为空且不是"无"
  3867. if (!empty($dialogue) && $dialogue !== '无') {
  3868. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3869. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3870. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3871. $hasDialogue = true;
  3872. }
  3873. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3874. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3875. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3876. if (!preg_match('/^[“]/', $dialogue)) {
  3877. $dialogue = '“' . $dialogue;
  3878. }
  3879. if (!preg_match('/[”]$/', $dialogue)) {
  3880. $dialogue .= '”';
  3881. }
  3882. // 将修改后的台词替换回 $segmentContent
  3883. $originalDialogue = $dialogueMatch[1];
  3884. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3885. }
  3886. }
  3887. // 构建完整的提示词
  3888. $fullPrompt = $segmentContent;
  3889. if ($finalTailFrame && !$contentHasTailFrame) {
  3890. // 只有当 segmentContent 中没有尾帧描述时才追加
  3891. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3892. }
  3893. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3894. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3895. $fullPrompt = trim($fullPrompt);
  3896. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3897. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3898. // 智能选择视频时长
  3899. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3900. $videoDuration = -1;
  3901. // 处理视频模型
  3902. $model = getProp($data, 'model');
  3903. if (!$model) {
  3904. // 用户没有输入,从episode表获取
  3905. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3906. $model = getProp($episode, 'video_model');
  3907. if (!$model) {
  3908. // episode表也没有,使用默认值
  3909. $model = 'doubao-seedance-1-5-pro-251215';
  3910. }
  3911. }
  3912. // 验证模型是否在可用模型表中
  3913. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3914. $model = 'doubao-seedance-1-5-pro-251215';
  3915. }
  3916. // 保存到episode表
  3917. $episode_id = getProp($segment, 'episode_id');
  3918. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3919. 'video_model' => $model,
  3920. 'updated_at' => date('Y-m-d H:i:s')
  3921. ]);
  3922. // 构建视频生成参数
  3923. $videoParams = [
  3924. 'model' => $model,
  3925. 'alias_segment_id' => $segment_id,
  3926. 'prompt' => trim($fullPrompt),
  3927. 'video_duration' => $videoDuration,
  3928. 'video_resolution' => '720P',
  3929. 'seed' => -1,
  3930. 'ratio' => $ratio,
  3931. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3932. 'draft' => false,
  3933. 'watermark' => false,
  3934. 'camera_fixed' => false,
  3935. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3936. ];
  3937. // 如果分镜有图片,作为首帧
  3938. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3939. $hasVideo = !empty(getProp($segment, 'video_url'));
  3940. if ($hasImage) {
  3941. if ($first_frame_url) {
  3942. $videoParams['first_frame_url'] = $first_frame_url;
  3943. }else {
  3944. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3945. }
  3946. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3947. }
  3948. // 构建content数组
  3949. $videoParams['content'] = [
  3950. [
  3951. 'type' => 'text',
  3952. 'text' => $videoParams['prompt'],
  3953. ]
  3954. ];
  3955. // 如果有首帧图片,添加到content中
  3956. if ($hasImage) {
  3957. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3958. $videoParams['content'][] = [
  3959. 'type' => 'image_url',
  3960. 'image_url' => [
  3961. 'url' => $videoParams['first_frame_url'],
  3962. ],
  3963. 'role' => 'reference_image',
  3964. ];
  3965. if (isset($videoParams['tail_frame_url'])) {
  3966. $videoParams['content'][] = [
  3967. 'type' => 'image_url',
  3968. 'image_url' => [
  3969. 'url' => $videoParams['tail_frame_url'],
  3970. ],
  3971. 'role' => 'reference_image',
  3972. ];
  3973. }
  3974. }else {
  3975. $videoParams['content'][] = [
  3976. 'type' => 'image_url',
  3977. 'image_url' => [
  3978. 'url' => $videoParams['first_frame_url'],
  3979. ],
  3980. 'role' => 'first_frame',
  3981. ];
  3982. if (isset($videoParams['tail_frame_url'])) {
  3983. $videoParams['content'][] = [
  3984. 'type' => 'image_url',
  3985. 'image_url' => [
  3986. 'url' => $videoParams['tail_frame_url'],
  3987. ],
  3988. 'role' => 'last_frame',
  3989. ];
  3990. }
  3991. }
  3992. }
  3993. // 获取配音音频URL
  3994. $audioUrl = getProp($segment, 'audio_url');
  3995. $audioDuration = getProp($segment, 'audio_duration');
  3996. // 音频传入的前提:必须有至少一张图片或一个视频
  3997. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  3998. // 余额预检:按预估时长计算所需积分,不足直接报错
  3999. $chargeDuration = (int)ceil((float)$audioDuration);
  4000. if ($chargeDuration <= 0) {
  4001. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4002. }
  4003. $this->pointsService->checkUserPointsEnough(
  4004. $this->pointsService->getVideoChargePoints([
  4005. 'model' => $model,
  4006. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4007. 'video_duration' => $chargeDuration,
  4008. 'ratio' => $ratio,
  4009. 'generate_audio' => $current_generate_audio,
  4010. ])
  4011. );
  4012. // dd($videoParams);
  4013. // 根据模型选择不同的视频生成方法
  4014. if (strpos($model, 'jimeng') !== false) {
  4015. // 即梦模型参数调整
  4016. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4017. unset($videoParams['content']); // 即梦不使用content格式
  4018. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4019. } elseif (strpos($model, 'kling') !== false) {
  4020. // Keling模型参数调整
  4021. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4022. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4023. unset($videoParams['ratio']);
  4024. unset($videoParams['content']); // Keling不使用content格式
  4025. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4026. } elseif (strpos($model, 'zhizhen') !== false) {
  4027. // 智帧20等新模型使用统一API
  4028. // 构建统一API参数
  4029. $unifiedParams = [
  4030. 'model_code' => $model,
  4031. 'alias_segment_id' => $segment_id,
  4032. 'prompt' => trim($fullPrompt),
  4033. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4034. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4035. 'video_ratio' => $ratio,
  4036. 'seed' => -1,
  4037. ];
  4038. // 构建parameters参数
  4039. $parameters = [
  4040. 'seconds' => $unifiedParams['video_duration'],
  4041. 'resolution' => $unifiedParams['video_resolution'],
  4042. 'ratio' => $ratio,
  4043. // 'video_mode' => 'multi_image',
  4044. // 'mode' => 'multi_image',
  4045. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4046. ];
  4047. $hasImage = false;
  4048. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4049. if ($hasImage) {
  4050. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4051. if (isset($videoParams['tail_frame_url'])) {
  4052. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4053. }
  4054. // 只有在有图片的情况下才能添加参考音频
  4055. if ($audioUrl) {
  4056. // $parameters['reference_audios'] = [$audioUrl];
  4057. }
  4058. } else {
  4059. // 没有图片时,记录错误日志
  4060. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4061. 'segment_id' => $segment_id,
  4062. 'model' => $model
  4063. ]);
  4064. }
  4065. $unifiedParams['parameters'] = $parameters;
  4066. // 调用统一API创建任务
  4067. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4068. } else {
  4069. // Seedance模型(默认)
  4070. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4071. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4072. // 添加配音音频到content中
  4073. $videoParams['content'][] = [
  4074. 'type' => 'audio_url',
  4075. 'audio_url' => [
  4076. 'url' => $audioUrl,
  4077. ],
  4078. 'role' => 'reference_audio',
  4079. ];
  4080. // 优化提示词,增加音频相关描述
  4081. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4082. $videoParams['prompt'] = $audioPrompt;
  4083. $videoParams['content'][0]['text'] = $audioPrompt;
  4084. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4085. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4086. }
  4087. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4088. }
  4089. // 更新分镜表的视频任务信息
  4090. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4091. 'video_task_id' => $task->id,
  4092. 'video_task_status' => '生成中',
  4093. 'generate_audio' => $generate_audio,
  4094. 'updated_at' => date('Y-m-d H:i:s')
  4095. ]);
  4096. return [
  4097. 'task_id' => $task->id,
  4098. 'status' => $task->status,
  4099. 'segment_id' => $segment_id,
  4100. 'video_duration' => $videoDuration
  4101. ];
  4102. }
  4103. public function createActVideoTask($data) {
  4104. $act_id = getProp($data, 'act_id');
  4105. $first_frame_url = getProp($data, 'first_frame_url');
  4106. $tail_frame_url = getProp($data, 'tail_frame_url');
  4107. $generate_audio = getProp($data, 'generate_audio', 1);
  4108. $video_duration = getProp($data, 'video_duration');
  4109. $video_resolution = getProp($data, 'video_resolution');
  4110. $ratio = getProp($data, 'ratio');
  4111. $products = getProp($data, 'products', []);
  4112. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4113. if (!is_array($reference_images) || !is_array($products)) {
  4114. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4115. }
  4116. if (!$act_id) {
  4117. Utils::throwError('1002:片段ID不能为空');
  4118. }
  4119. // 获取片段信息
  4120. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4121. if (!$act) {
  4122. Utils::throwError('20003:片段不存在');
  4123. }
  4124. $act = (array)$act;
  4125. $anime_id = getProp($act, 'anime_id');
  4126. $episode_id = getProp($act, 'episode_id');
  4127. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4128. $ace_mode = getProp($anime, 'ace_mode');
  4129. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4130. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4131. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4132. // 将资产中新出现的资产放到extra_products中
  4133. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4134. if (!empty($products) && $episode) {
  4135. // 获取剧集中的角色、场景和道具列表
  4136. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4137. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4138. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4139. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4140. // 构建角色名称列表
  4141. $role_names = array_column($roles, 'role');
  4142. // 构建场景名称列表
  4143. $scene_names = array_column($scenes, 'scene');
  4144. // 构建道具名称列表
  4145. $prop_names = array_column($props, 'prop');
  4146. // 遍历传入的products
  4147. foreach ($products as $product) {
  4148. $product_name = getProp($product, 'product_name');
  4149. // 如果product_name不在roles、scenes和props中
  4150. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4151. // 查找是否在extra_products中存在同名的
  4152. $found = false;
  4153. foreach ($extra_products as $key => $extra_product) {
  4154. if (getProp($extra_product, 'product_name') === $product_name) {
  4155. // 有同名的则覆盖
  4156. $extra_products[$key] = $product;
  4157. $found = true;
  4158. break;
  4159. }
  4160. }
  4161. // 没有则新增
  4162. if (!$found) {
  4163. $extra_products[] = $product;
  4164. }
  4165. }
  4166. }
  4167. if ($extra_products) {
  4168. // 保存到数据库
  4169. DB::table('mp_anime_episodes')
  4170. ->where('id', $episode_id)
  4171. ->update([
  4172. 'extra_products' => json_encode($extra_products, 256),
  4173. 'updated_at' => date('Y-m-d H:i:s')
  4174. ]);
  4175. }
  4176. }
  4177. // 获取分镜内容
  4178. $actContent = getProp($act, 'act_show_content', '');
  4179. // 音效同出(默认使用)
  4180. $current_generate_audio = $generate_audio ? 1 : 0;
  4181. // 构建完整的提示词
  4182. $processResult = $this->processActContentWithProducts($actContent, $products);
  4183. $fullPrompt = $processResult['content'];
  4184. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4185. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4186. // 处理视频模型
  4187. $model = getProp($data, 'model');
  4188. if (!$model) {
  4189. $model = getProp($episode, 'video_model');
  4190. if (!$model) {
  4191. // episode表也没有,使用默认值
  4192. $model = 'zhizhen-20';
  4193. }
  4194. }
  4195. // 验证模型是否在可用模型表中
  4196. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4197. $model = 'zhizhen-20';
  4198. }
  4199. // 保存到episode表
  4200. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4201. 'video_model' => $model,
  4202. 'updated_at' => date('Y-m-d H:i:s')
  4203. ]);
  4204. // 余额预检:按预估时长计算所需积分,不足直接报错
  4205. $chargeDuration = (int)$videoDuration;
  4206. if ($chargeDuration <= 0) {
  4207. $chargeDuration = 5; // 无时长时按默认5秒预估
  4208. }
  4209. $this->pointsService->checkUserPointsEnough(
  4210. $this->pointsService->getVideoChargePoints([
  4211. 'model' => $model,
  4212. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4213. 'video_duration' => $chargeDuration,
  4214. 'ratio' => $ratio,
  4215. 'generate_audio' => $current_generate_audio,
  4216. ])
  4217. );
  4218. // 构建视频生成参数
  4219. $videoParams = [
  4220. 'model' => $model,
  4221. 'alias_act_id' => $act_id,
  4222. 'prompt' => trim($fullPrompt),
  4223. 'video_duration' => $videoDuration,
  4224. 'video_resolution' => $video_resolution,
  4225. 'seed' => -1,
  4226. 'ratio' => $ratio,
  4227. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4228. 'draft' => false,
  4229. 'watermark' => false,
  4230. 'camera_fixed' => false,
  4231. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4232. ];
  4233. // 如果分镜有图片,作为首帧
  4234. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4235. $hasVideo = !empty(getProp($act, 'video_url'));
  4236. if ($hasImage) {
  4237. if ($first_frame_url) {
  4238. $videoParams['first_frame_url'] = $first_frame_url;
  4239. }else {
  4240. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4241. }
  4242. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4243. }
  4244. // 构建content数组
  4245. $videoParams['content'] = [
  4246. [
  4247. 'type' => 'text',
  4248. 'text' => $videoParams['prompt'],
  4249. ]
  4250. ];
  4251. // 如果有首帧图片,添加到content中
  4252. if ($hasImage) {
  4253. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4254. $videoParams['content'][] = [
  4255. 'type' => 'image_url',
  4256. 'image_url' => [
  4257. 'url' => $videoParams['first_frame_url'],
  4258. ],
  4259. 'role' => 'reference_image',
  4260. ];
  4261. if (isset($videoParams['tail_frame_url'])) {
  4262. $videoParams['content'][] = [
  4263. 'type' => 'image_url',
  4264. 'image_url' => [
  4265. 'url' => $videoParams['tail_frame_url'],
  4266. ],
  4267. 'role' => 'reference_image',
  4268. ];
  4269. }
  4270. }else {
  4271. $videoParams['content'][] = [
  4272. 'type' => 'image_url',
  4273. 'image_url' => [
  4274. 'url' => $videoParams['first_frame_url'],
  4275. ],
  4276. 'role' => 'first_frame',
  4277. ];
  4278. if (isset($videoParams['tail_frame_url'])) {
  4279. $videoParams['content'][] = [
  4280. 'type' => 'image_url',
  4281. 'image_url' => [
  4282. 'url' => $videoParams['tail_frame_url'],
  4283. ],
  4284. 'role' => 'last_frame',
  4285. ];
  4286. }
  4287. }
  4288. }
  4289. // dd($videoParams);
  4290. // 根据模型选择不同的视频生成方法
  4291. if (strpos($model, 'jimeng') !== false) {
  4292. // 即梦模型参数调整
  4293. unset($videoParams['content']); // 即梦不使用content格式
  4294. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4295. } elseif (strpos($model, 'kling') !== false) {
  4296. // Keling模型参数调整
  4297. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4298. unset($videoParams['ratio']);
  4299. unset($videoParams['content']); // Keling不使用content格式
  4300. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4301. } elseif (strpos($model, 'zhizhen') !== false) {
  4302. // 智帧20等新模型使用统一API
  4303. // 构建统一API参数
  4304. $unifiedParams = [
  4305. 'model_code' => $model,
  4306. 'alias_act_id' => $act_id,
  4307. 'prompt' => trim($fullPrompt),
  4308. 'video_duration' => $videoDuration,
  4309. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4310. 'video_ratio' => $ratio,
  4311. 'seed' => -1,
  4312. ];
  4313. // 构建parameters参数
  4314. $parameters = [
  4315. 'seconds' => $unifiedParams['video_duration'],
  4316. 'resolution' => $unifiedParams['video_resolution'],
  4317. 'ratio' => $ratio,
  4318. // 'video_mode' => 'multi_image',
  4319. // 'mode' => 'multi_image',
  4320. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4321. ];
  4322. $hasImage = false;
  4323. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4324. if ($hasImage) {
  4325. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4326. if (isset($videoParams['tail_frame_url'])) {
  4327. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4328. }
  4329. } else {
  4330. // 没有图片时,记录错误日志
  4331. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4332. 'act_id' => $act_id,
  4333. 'model' => $model
  4334. ]);
  4335. }
  4336. if ($reference_images) {
  4337. // 限制只传入9张参考图
  4338. $reference_images = array_slice($reference_images, 0, 9);
  4339. // 在处理之前先保存原始reference_images到任务参数中
  4340. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4341. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4342. $parameters['reference_images'] = $reference_images;
  4343. $parameters['video_mode'] = 'multi_image';
  4344. $parameters['mode'] = 'multi_image';
  4345. }
  4346. $unifiedParams['parameters'] = $parameters;
  4347. // 调用统一API创建任务
  4348. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4349. } else {
  4350. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4351. }
  4352. // 更新分镜表的视频任务信息
  4353. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4354. 'video_task_id' => $task->id,
  4355. 'video_task_status' => '生成中',
  4356. 'generate_audio' => $generate_audio,
  4357. 'updated_at' => date('Y-m-d H:i:s')
  4358. ]);
  4359. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4360. $episode_number = getProp($act, 'episode_number');
  4361. $act_number = getProp($act, 'act_number');
  4362. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4363. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4364. }
  4365. return [
  4366. 'task_id' => $task->id,
  4367. 'status' => $task->status,
  4368. 'act_id' => $act_id,
  4369. 'video_duration' => $videoDuration
  4370. ];
  4371. }
  4372. /**
  4373. * 预估视频生成所需积分(支持单一/批量)
  4374. *
  4375. * 传参与对应创建接口一致,另支持 type 参数区分场景:
  4376. * segment-单分镜转视频、act-单片段转视频、batch_segment-分镜批量、batch_act-片段批量;
  4377. * type 缺省时按 segment_id / act_id 自动推断,批量场景需显式传入。
  4378. *
  4379. * @param array $data
  4380. * @return array
  4381. */
  4382. public function previewVideoCharge(array $data): array
  4383. {
  4384. $type = (string)getProp($data, 'type', '');
  4385. if (!$type) {
  4386. if (getProp($data, 'segment_id')) {
  4387. $type = 'segment';
  4388. } elseif (getProp($data, 'act_id')) {
  4389. $type = 'act';
  4390. } else {
  4391. Utils::throwError('1003:请传入type参数(segment/act/batch_segment/batch_act)');
  4392. }
  4393. }
  4394. $mode = (string)getProp($data, 'mode', 'video_generation');
  4395. $items = [];
  4396. $model = '';
  4397. $resolution = '720p';
  4398. $buildCharge = function ($itemId, $duration, $model, $resolution, $mode) {
  4399. return $this->pointsService->getVideoChargePoints([
  4400. 'model' => $model,
  4401. 'video_resolution' => $resolution,
  4402. 'video_duration' => $duration,
  4403. 'mode' => $mode,
  4404. ]);
  4405. };
  4406. if ($type === 'segment') {
  4407. // 单分镜转视频
  4408. $segmentId = getProp($data, 'segment_id');
  4409. if (!$segmentId) {
  4410. Utils::throwError('1002:分镜ID不能为空');
  4411. }
  4412. $segment = DB::table('mp_episode_segments')->where('segment_id', $segmentId)->first();
  4413. if (!$segment) {
  4414. Utils::throwError('20003:分镜不存在');
  4415. }
  4416. $episode = DB::table('mp_anime_episodes')->where('id', $segment->episode_id)->first();
  4417. $model = getProp($data, 'model') ?: getProp($episode, 'video_model', 'doubao-seedance-1-5-pro-251215');
  4418. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4419. $model = 'doubao-seedance-1-5-pro-251215';
  4420. }
  4421. $duration = (int)ceil((float)$segment->audio_duration);
  4422. if ($duration <= 0) {
  4423. $duration = 5;
  4424. }
  4425. $items[] = [
  4426. 'id' => $segment->segment_id,
  4427. 'duration' => $duration,
  4428. 'points' => $buildCharge($segment->segment_id, $duration, $model, '720p', $mode),
  4429. ];
  4430. } elseif ($type === 'act') {
  4431. // 单片段转视频
  4432. $actId = getProp($data, 'act_id');
  4433. if (!$actId) {
  4434. Utils::throwError('1002:片段ID不能为空');
  4435. }
  4436. $act = DB::table('mp_episode_segments')->where('id', $actId)->first();
  4437. if (!$act) {
  4438. Utils::throwError('20003:片段不存在');
  4439. }
  4440. $episode = DB::table('mp_anime_episodes')->where('id', $act->episode_id)->first();
  4441. $model = getProp($data, 'model') ?: getProp($episode, 'video_model', 'zhizhen-20');
  4442. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4443. $model = 'zhizhen-20';
  4444. }
  4445. $resolution = strtolower((string)getProp($data, 'video_resolution', ''));
  4446. if (!$resolution) {
  4447. $resolution = strtolower((string)getProp($episode, 'video_resolution', '720p'));
  4448. }
  4449. $duration = (int)getProp($data, 'video_duration', 0);
  4450. if ($duration <= 0) {
  4451. $duration = (int)ceil((float)$act->act_duration);
  4452. }
  4453. if ($duration <= 0) {
  4454. $duration = 5;
  4455. }
  4456. $items[] = [
  4457. 'id' => $act->id,
  4458. 'duration' => $duration,
  4459. 'points' => $buildCharge($act->id, $duration, $model, $resolution, $mode),
  4460. ];
  4461. } elseif (in_array($type, ['batch_segment', 'batch_act'])) {
  4462. // 批量场景
  4463. $animeId = getProp($data, 'anime_id');
  4464. $episodeId = getProp($data, 'episode_id');
  4465. if (!$animeId || !$episodeId) {
  4466. Utils::throwError('1002:anime_id和episode_id不能为空');
  4467. }
  4468. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->where('anime_id', $animeId)->first();
  4469. if (!$episode) {
  4470. Utils::throwError('20003:分集不存在');
  4471. }
  4472. if ($type === 'batch_segment') {
  4473. $model = getProp($data, 'model') ?: getProp($episode, 'video_model', 'doubao-seedance-1-5-pro-251215');
  4474. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4475. $model = 'doubao-seedance-1-5-pro-251215';
  4476. }
  4477. $segments = DB::table('mp_episode_segments')
  4478. ->where('anime_id', $animeId)
  4479. ->where('episode_id', $episodeId)
  4480. ->whereNotIn('video_task_status', ['已完成', '生成中'])
  4481. ->orderBy('segment_number')
  4482. ->get();
  4483. foreach ($segments as $segment) {
  4484. if ((int)$segment->current_type === 2) {
  4485. continue;
  4486. }
  4487. $duration = (int)ceil((float)$segment->audio_duration);
  4488. if ($duration <= 0) {
  4489. $duration = 5;
  4490. }
  4491. $items[] = [
  4492. 'id' => $segment->segment_id,
  4493. 'duration' => $duration,
  4494. 'points' => $buildCharge($segment->segment_id, $duration, $model, '720p', $mode),
  4495. ];
  4496. }
  4497. } else {
  4498. // 片段批量固定智帧20
  4499. $model = 'zhizhen-20';
  4500. $acts = DB::table('mp_episode_segments')
  4501. ->where('anime_id', $animeId)
  4502. ->where('episode_id', $episodeId)
  4503. ->orderBy('act_number')
  4504. ->get();
  4505. foreach ($acts as $act) {
  4506. if ($act->video_task_status === '生成中' || (int)$act->current_type === 2) {
  4507. continue;
  4508. }
  4509. $duration = (int)ceil((float)$act->act_duration);
  4510. if ($duration <= 0) {
  4511. $duration = 5;
  4512. }
  4513. $items[] = [
  4514. 'id' => $act->id,
  4515. 'duration' => $duration,
  4516. 'points' => $buildCharge($act->id, $duration, $model, '720p', $mode),
  4517. ];
  4518. }
  4519. }
  4520. } else {
  4521. Utils::throwError('1003:type参数不正确');
  4522. }
  4523. $totalPoints = 0;
  4524. foreach ($items as $item) {
  4525. $totalPoints += $item['points'];
  4526. }
  4527. return [
  4528. 'type' => $type,
  4529. 'model' => $model,
  4530. 'video_resolution' => $resolution,
  4531. 'mode' => $mode,
  4532. 'count' => count($items),
  4533. 'total_points' => $totalPoints,
  4534. 'items' => $items,
  4535. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4536. 'remark' => '积分为预估值,按预估时长计算;实际扣费以视频生成完成后的实际时长为准',
  4537. ];
  4538. }
  4539. /**
  4540. * 根据提示词内容智能计算最优视频时长
  4541. *
  4542. * @param string $segmentContent 分镜内容
  4543. * @param string $tailFrame 尾帧描述
  4544. * @return int 视频时长(2-12秒)
  4545. */
  4546. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4547. // 合并所有文本内容
  4548. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4549. // 如果没有内容,返回默认时长
  4550. if (empty($fullText)) {
  4551. return 5;
  4552. }
  4553. // 计算文本长度(中文字符按2个字符计算)
  4554. $textLength = mb_strlen($fullText, 'UTF-8');
  4555. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4556. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4557. // 分析内容复杂度
  4558. $complexityScore = $this->analyzeContentComplexity($fullText);
  4559. // 基础时长计算(根据文本长度)
  4560. $baseDuration = 3; // 默认2秒
  4561. // if ($adjustedLength <= 20) {
  4562. // $baseDuration = 3;
  4563. // } elseif ($adjustedLength <= 40) {
  4564. // $baseDuration = 4;
  4565. // } elseif ($adjustedLength <= 60) {
  4566. // $baseDuration = 5;
  4567. // } elseif ($adjustedLength <= 80) {
  4568. // $baseDuration = 6;
  4569. // } elseif ($adjustedLength <= 100) {
  4570. // $baseDuration = 7;
  4571. // } elseif ($adjustedLength <= 120) {
  4572. // $baseDuration = 8;
  4573. // } else {
  4574. // $baseDuration = 9;
  4575. // }
  4576. // 根据内容复杂度调整时长
  4577. $finalDuration = $baseDuration + $complexityScore;
  4578. // 确保时长在2-12秒范围内
  4579. return max(4, min(12, $finalDuration));
  4580. }
  4581. /**
  4582. * 分析内容复杂度,返回时长调整值
  4583. *
  4584. * @param string $text 文本内容
  4585. * @return int 调整值(-2到+3)
  4586. */
  4587. private function analyzeContentComplexity($text) {
  4588. $score = 0;
  4589. // 动作关键词(需要更长时间展现)
  4590. $actionKeywords = [
  4591. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4592. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4593. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4594. ];
  4595. // 静态关键词(可以用较短时间)
  4596. $staticKeywords = [
  4597. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4598. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4599. ];
  4600. // 复杂场景关键词(需要更长时间)
  4601. $complexSceneKeywords = [
  4602. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4603. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4604. ];
  4605. // 情感关键词(需要适中时间表现)
  4606. $emotionKeywords = [
  4607. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4608. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4609. ];
  4610. // 检查动作关键词
  4611. foreach ($actionKeywords as $keyword) {
  4612. if (strpos($text, $keyword) !== false) {
  4613. $score += 1;
  4614. break; // 避免重复加分
  4615. }
  4616. }
  4617. // 检查静态关键词
  4618. foreach ($staticKeywords as $keyword) {
  4619. if (strpos($text, $keyword) !== false) {
  4620. $score -= 1;
  4621. break;
  4622. }
  4623. }
  4624. // 检查复杂场景关键词
  4625. foreach ($complexSceneKeywords as $keyword) {
  4626. if (strpos($text, $keyword) !== false) {
  4627. $score += 1;
  4628. break;
  4629. }
  4630. }
  4631. // 检查情感关键词
  4632. foreach ($emotionKeywords as $keyword) {
  4633. if (strpos($text, $keyword) !== false) {
  4634. $score += 1;
  4635. break;
  4636. }
  4637. }
  4638. // 检查时间相关词汇
  4639. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4640. $score += 1;
  4641. }
  4642. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4643. $score -= 1;
  4644. }
  4645. // 检查转场词汇
  4646. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4647. $score += 1;
  4648. }
  4649. // 检查环境描述(复杂环境需要更多时间)
  4650. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4651. $score += 1;
  4652. }
  4653. // 检查对话内容(对话需要更多时间)
  4654. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4655. $score += 1;
  4656. }
  4657. // 限制调整范围
  4658. return max(-1, min(4, $score));
  4659. }
  4660. /**
  4661. * 创建完整视频合成任务
  4662. *
  4663. * @param array $data
  4664. * @return array
  4665. */
  4666. public function createCompleteVideoTask($data)
  4667. {
  4668. $animeId = getProp($data, 'anime_id');
  4669. $episodeId = getProp($data, 'episode_id');
  4670. // 验证参数
  4671. if (!$animeId || !$episodeId) {
  4672. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4673. }
  4674. // 检查是否已存在处理中的任务
  4675. $existingTask = DB::table('mp_complete_video_tasks')
  4676. ->where('anime_id', $animeId)
  4677. ->where('episode_id', $episodeId)
  4678. ->whereIn('generate_status', ['执行中'])
  4679. ->first();
  4680. if ($existingTask) {
  4681. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4682. }
  4683. // 获取全能模式状态
  4684. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4685. if ((int)$ace_mode === 1) {
  4686. // 获取所有片段的配音视频,按 act_number 排序
  4687. $segments = DB::table('mp_episode_segments')
  4688. ->where('anime_id', $animeId)
  4689. ->where('episode_id', $episodeId)
  4690. ->orderBy('segment_number')
  4691. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4692. ->get();
  4693. // 检查是否所有片段都有视频
  4694. $missingVideos = $segments->filter(function($segment) {
  4695. return empty($segment->video_url);
  4696. });
  4697. if ($missingVideos->isNotEmpty()) {
  4698. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4699. }
  4700. }else {
  4701. // 获取所有分镜的配音视频,按 segment_number 排序
  4702. $segments = DB::table('mp_episode_segments')
  4703. ->where('anime_id', $animeId)
  4704. ->where('episode_id', $episodeId)
  4705. ->orderBy('segment_number')
  4706. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4707. ->get();
  4708. // 检查是否所有分镜都有配音和视频
  4709. $missingVideos = $segments->filter(function($segment) {
  4710. return empty($segment->audio_url) || empty($segment->video_url);
  4711. });
  4712. if ($missingVideos->isNotEmpty()) {
  4713. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4714. }
  4715. }
  4716. if ($segments->isEmpty()) {
  4717. Utils::throwError('20003:未找到该剧集的分镜数据');
  4718. }
  4719. // 获取当前完整视频url
  4720. $completeVideoUrl = DB::table('mp_anime_episodes')
  4721. ->where('anime_id', $animeId)
  4722. ->where('id', $episodeId)
  4723. ->value('complete_video_url');
  4724. // 构建 generate_json
  4725. $generateJson = [];
  4726. $sequence = 1;
  4727. foreach ($segments as $segment) {
  4728. if ((int)$ace_mode === 1) {
  4729. $generateJson[] = [
  4730. 'sequence' => $sequence++,
  4731. 'video_url' => $segment->video_url,
  4732. 'video_time_point_start' => $segment->video_time_point_start,
  4733. 'video_time_point_end' => $segment->video_time_point_end
  4734. ];
  4735. }else {
  4736. $generateJson[] = [
  4737. 'sequence' => $sequence++,
  4738. 'video_url' => $segment->video_url,
  4739. 'audio_url' => $segment->audio_url,
  4740. 'video_time_point_start' => $segment->video_time_point_start,
  4741. 'video_time_point_end' => $segment->video_time_point_end
  4742. ];
  4743. }
  4744. }
  4745. // 创建任务
  4746. $now = date('Y-m-d H:i:s');
  4747. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4748. 'anime_id' => $animeId,
  4749. 'episode_id' => $episodeId,
  4750. 'generate_json' => json_encode($generateJson, 256),
  4751. 'generate_status' => '执行中',
  4752. 'complete_video_url' => '',
  4753. 'created_at' => $now,
  4754. 'updated_at' => $now
  4755. ]);
  4756. if (!$taskId) {
  4757. Utils::throwError('20003:创建任务失败');
  4758. }
  4759. // 更新剧集表的任务ID和状态
  4760. $boolen = DB::table('mp_anime_episodes')
  4761. ->where('anime_id', $animeId)
  4762. ->where('id', $episodeId)
  4763. ->update([
  4764. 'complete_video_task_id' => $taskId,
  4765. 'complete_video_task_status' => '执行中',
  4766. 'updated_at' => $now
  4767. ]);
  4768. if (!$boolen) {
  4769. Utils::throwError('20003:更新剧集表失败');
  4770. }
  4771. dLog('anime')->info('创建完整视频合成任务', [
  4772. 'task_id' => $taskId,
  4773. 'anime_id' => $animeId,
  4774. 'episode_id' => $episodeId,
  4775. 'segment_count' => count($generateJson)
  4776. ]);
  4777. // 请求远程服务器执行生成
  4778. $client = new Client(['timeout' => 600, 'verify' => false]);
  4779. try {
  4780. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4781. $response = $result->getBody()->getContents();
  4782. $response_arr = json_decode($response, true);
  4783. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4784. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4785. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4786. // // 更新任务状态为失败
  4787. // DB::table('mp_complete_video_tasks')
  4788. // ->where('id', $taskId)
  4789. // ->update([
  4790. // 'generate_status' => '执行失败',
  4791. // 'error_message' => $error_msg,
  4792. // 'updated_at' => date('Y-m-d H:i:s')
  4793. // ]);
  4794. // // 同步更新剧集表状态
  4795. // DB::table('mp_anime_episodes')
  4796. // ->where('complete_video_task_id', $taskId)
  4797. // ->update([
  4798. // 'complete_video_task_status' => '执行失败',
  4799. // 'updated_at' => date('Y-m-d H:i:s')
  4800. // ]);
  4801. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4802. }
  4803. } catch (\Exception $e) {
  4804. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4805. // 更新任务状态为失败
  4806. DB::table('mp_complete_video_tasks')
  4807. ->where('id', $taskId)
  4808. ->update([
  4809. 'generate_status' => '执行失败',
  4810. 'error_message' => $e->getMessage(),
  4811. 'updated_at' => date('Y-m-d H:i:s')
  4812. ]);
  4813. // 同步更新剧集表状态
  4814. DB::table('mp_anime_episodes')
  4815. ->where('complete_video_task_id', $taskId)
  4816. ->update([
  4817. 'complete_video_task_status' => '执行失败',
  4818. 'updated_at' => date('Y-m-d H:i:s')
  4819. ]);
  4820. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4821. }
  4822. // 开始轮询任务状态
  4823. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4824. $pollInterval = 5; // 每5秒轮询一次
  4825. $attempt = 0;
  4826. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4827. while ($attempt < $maxAttempts) {
  4828. sleep($pollInterval);
  4829. $attempt++;
  4830. // 查询任务状态
  4831. $task = DB::table('mp_complete_video_tasks')
  4832. ->where('id', $taskId)
  4833. ->first();
  4834. if (!$task) {
  4835. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4836. Utils::throwError('20003:任务不存在');
  4837. }
  4838. dLog('anime')->info('轮询任务状态', [
  4839. 'task_id' => $taskId,
  4840. 'attempt' => $attempt,
  4841. 'status' => $task->generate_status
  4842. ]);
  4843. // 检查任务是否完成
  4844. if ($task->generate_status === '执行成功') {
  4845. // 同步更新剧集表状态
  4846. $boolen3 = DB::table('mp_anime_episodes')
  4847. ->where('anime_id', $animeId)
  4848. ->where('id', $episodeId)
  4849. ->update([
  4850. 'complete_video_url' => $task->complete_video_url,
  4851. 'complete_video_task_status' => '执行成功',
  4852. 'updated_at' => date('Y-m-d H:i:s')
  4853. ]);
  4854. dLog('anime')->info('视频合成任务完成', [
  4855. 'task_id' => $taskId,
  4856. 'video_url' => $task->complete_video_url,
  4857. 'attempts' => $attempt
  4858. ]);
  4859. // 如果更新成功则远程删除之前的文件
  4860. if ($boolen3 && $completeVideoUrl) {
  4861. $encode_url = urlencode($completeVideoUrl);
  4862. $client = new Client(['timeout' => 300, 'verify' => false]);
  4863. // 根据ID通过API通知合成音频
  4864. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4865. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4866. $response = $result->getBody()->getContents();
  4867. $response_arr = json_decode($response, true);
  4868. Log::info('火山删除音频返回: '.$response);
  4869. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4870. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4871. Log::info('火山删除音频失败: '.$error_msg);
  4872. // Utils::throwError('20003:火山删除音频失败');
  4873. }
  4874. }
  4875. return [
  4876. 'task_id' => $taskId,
  4877. 'anime_id' => $animeId,
  4878. 'episode_id' => $episodeId,
  4879. 'segment_count' => count($generateJson),
  4880. 'generate_status' => '执行成功',
  4881. 'complete_video_url' => $task->complete_video_url,
  4882. ];
  4883. }
  4884. // 检查任务是否失败
  4885. if ($task->generate_status === '执行失败') {
  4886. // 同步更新剧集表状态
  4887. DB::table('mp_anime_episodes')
  4888. ->where('anime_id', $animeId)
  4889. ->where('id', $episodeId)
  4890. ->update([
  4891. 'complete_video_task_status' => '执行失败',
  4892. 'updated_at' => date('Y-m-d H:i:s')
  4893. ]);
  4894. $errorMessage = $task->error_message ?? '未知错误';
  4895. dLog('anime')->error('视频合成任务失败', [
  4896. 'task_id' => $taskId,
  4897. 'error' => $errorMessage,
  4898. 'attempts' => $attempt
  4899. ]);
  4900. return [
  4901. 'task_id' => $taskId,
  4902. 'anime_id' => $animeId,
  4903. 'episode_id' => $episodeId,
  4904. 'segment_count' => count($generateJson),
  4905. 'generate_status' => '执行失败',
  4906. 'error_message' => $errorMessage
  4907. ];
  4908. }
  4909. }
  4910. // 超时处理
  4911. dLog('anime')->warning('视频合成任务超时', [
  4912. 'task_id' => $taskId,
  4913. 'max_attempts' => $maxAttempts,
  4914. 'timeout_seconds' => $maxAttempts * $pollInterval
  4915. ]);
  4916. // 更新任务状态为超时
  4917. DB::table('mp_complete_video_tasks')
  4918. ->where('id', $taskId)
  4919. ->update([
  4920. 'generate_status' => '超时',
  4921. 'error_message' => '任务执行超时(5分钟)',
  4922. 'updated_at' => date('Y-m-d H:i:s')
  4923. ]);
  4924. return [
  4925. 'task_id' => $taskId,
  4926. 'anime_id' => $animeId,
  4927. 'episode_id' => $episodeId,
  4928. 'segment_count' => count($generateJson),
  4929. 'generate_status' => '超时',
  4930. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4931. ];
  4932. }
  4933. /**
  4934. * 根据 inner_prompt_type 附加内置提示词
  4935. *
  4936. * @param string $prompt 用户提示词
  4937. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  4938. * @return string 合并后的提示词
  4939. */
  4940. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  4941. {
  4942. $innerPromptMap = [
  4943. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  4944. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  4945. ];
  4946. if (!isset($innerPromptMap[$innerPromptType])) {
  4947. return $prompt;
  4948. }
  4949. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  4950. }
  4951. /**
  4952. * 根据 inner_prompt_type 获取生成图片数量
  4953. *
  4954. * @param int $innerPromptType 内置提示词类型
  4955. * @return int 图片数量
  4956. */
  4957. public static function getInnerImageNum($innerPromptType = 0)
  4958. {
  4959. return (int)$innerPromptType === 2 ? 9 : 1;
  4960. }
  4961. /**
  4962. * 提取图片生成结果URL
  4963. *
  4964. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  4965. * @param int $innerPromptType 内置提示词类型
  4966. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  4967. */
  4968. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  4969. {
  4970. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  4971. if (is_array($resultUrls) && !empty($resultUrls)) {
  4972. $resultUrls = array_values($resultUrls);
  4973. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  4974. }
  4975. if (!empty($resultUrl)) {
  4976. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  4977. }
  4978. return (int)$innerPromptType === 2 ? [] : '';
  4979. }
  4980. public function generateImg($data) {
  4981. $prompt = getProp($data, 'prompt');
  4982. $episode_id = getProp($data, 'episode_id');
  4983. $ref_img_urls = getProp($data, 'ref_img_urls');
  4984. $ratio = getProp($data, 'ratio', '9:16');
  4985. $resolution = getProp($data, 'resolution', '2k');
  4986. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  4987. // 定义分辨率和宽高比对应的尺寸映射表
  4988. $sizeMap = [
  4989. '2k' => [
  4990. '1:1' => ['width' => 2048, 'height' => 2048],
  4991. '4:3' => ['width' => 2304, 'height' => 1728],
  4992. '3:4' => ['width' => 1728, 'height' => 2304],
  4993. '16:9' => ['width' => 2848, 'height' => 1600],
  4994. '9:16' => ['width' => 1600, 'height' => 2848],
  4995. '3:2' => ['width' => 2496, 'height' => 1664],
  4996. '2:3' => ['width' => 1664, 'height' => 2496],
  4997. '21:9' => ['width' => 3136, 'height' => 1344],
  4998. ],
  4999. '3k' => [
  5000. '1:1' => ['width' => 3072, 'height' => 3072],
  5001. '4:3' => ['width' => 3456, 'height' => 2592],
  5002. '3:4' => ['width' => 2592, 'height' => 3456],
  5003. '16:9' => ['width' => 4096, 'height' => 2304],
  5004. '9:16' => ['width' => 2304, 'height' => 4096],
  5005. '2:3' => ['width' => 2496, 'height' => 3744],
  5006. '3:2' => ['width' => 3744, 'height' => 2496],
  5007. '21:9' => ['width' => 4704, 'height' => 2016],
  5008. ],
  5009. '4k' => [
  5010. '1:1' => ['width' => 4096, 'height' => 4096],
  5011. '3:4' => ['width' => 3520, 'height' => 4704],
  5012. '4:3' => ['width' => 4704, 'height' => 3520],
  5013. '16:9' => ['width' => 5504, 'height' => 3040],
  5014. '9:16' => ['width' => 3040, 'height' => 5504],
  5015. '2:3' => ['width' => 3328, 'height' => 4992],
  5016. '3:2' => ['width' => 4992, 'height' => 3328],
  5017. '21:9' => ['width' => 6240, 'height' => 2656],
  5018. ],
  5019. ];
  5020. // 参数验证
  5021. $resolution = strtolower($resolution);
  5022. if (!isset($sizeMap[$resolution])) {
  5023. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5024. }
  5025. if (!isset($sizeMap[$resolution][$ratio])) {
  5026. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5027. }
  5028. // 根据 ratio 和 resolution 确定宽高
  5029. $width = $sizeMap[$resolution][$ratio]['width'];
  5030. $height = $sizeMap[$resolution][$ratio]['height'];
  5031. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5032. if (is_json($ref_img_urls)) {
  5033. $ref_img_urls = json_decode($ref_img_urls, true);
  5034. }else {
  5035. $ref_img_urls = explode(',', $ref_img_urls);
  5036. }
  5037. }
  5038. // 处理图片模型
  5039. $model = getProp($data, 'model');
  5040. if (!$model) {
  5041. // 用户没有输入,从episode表获取
  5042. if ($episode_id) {
  5043. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5044. $model = getProp($episode, 'image_model');
  5045. }
  5046. if (!$model) {
  5047. // episode表也没有,使用默认值
  5048. $model = 'doubao-seedream-5-0-lite-260128';
  5049. }
  5050. }
  5051. // 验证模型是否在可用模型表中
  5052. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5053. // $model = 'doubao-seedream-5-0-lite-260128';
  5054. Utils::throwError('20003:该模型已不可用,请更换!');
  5055. }
  5056. // 保存到episode表
  5057. if ($episode_id) {
  5058. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5059. 'image_model' => $model,
  5060. 'updated_at' => date('Y-m-d H:i:s')
  5061. ]);
  5062. }
  5063. // 参数验证
  5064. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5065. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5066. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5067. $imageNum = self::getInnerImageNum($inner_prompt_type);
  5068. try {
  5069. // 创建图片生成任务
  5070. $params = [
  5071. 'prompt' => $prompt,
  5072. 'model' => $model,
  5073. 'ref_img_urls' => '',
  5074. 'width' => $width,
  5075. 'height' => $height,
  5076. 'image_num' => $imageNum
  5077. ];
  5078. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5079. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5080. $task_id = $task->id;
  5081. if (!$task_id) {
  5082. Utils::throwError('20003:创建图片生成任务失败');
  5083. }
  5084. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5085. $model = getProp($task, 'model');
  5086. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5087. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5088. $isSyncModel = $isVolcModel || $isGptModel;
  5089. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5090. $start_time = time();
  5091. $timeout = 300; // 5分钟
  5092. $img_url = '';
  5093. while (time() - $start_time < $timeout) {
  5094. sleep(3);
  5095. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5096. if ($isSyncModel) {
  5097. // 刷新任务状态
  5098. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5099. if ($task->status === 'success' && $task->result_url) {
  5100. $img_url = self::extractResultUrls($task->result_url, $inner_prompt_type);
  5101. break;
  5102. } elseif ($task->status === 'failed') {
  5103. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5104. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5105. }
  5106. // // 如果还在处理中,提示用户稍后查看
  5107. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5108. }else {
  5109. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5110. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5111. if ($statusInfo['status'] === 'success') {
  5112. $task->updateStatus('success', [
  5113. 'result_url' => $statusInfo['result_url'],
  5114. 'result_json' => $statusInfo['result_json'] ?? []
  5115. ]);
  5116. $img_url = self::extractResultUrls($statusInfo['result_url'], $inner_prompt_type);
  5117. break;
  5118. } elseif ($statusInfo['status'] === 'failed') {
  5119. $task->updateStatus('failed', [
  5120. 'error_message' => $statusInfo['error_message'],
  5121. 'result_json' => $statusInfo['result_json'] ?? []
  5122. ]);
  5123. dLog('anime')->error('图片生成失败,', [
  5124. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5125. ]);
  5126. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5127. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5128. }
  5129. }
  5130. }
  5131. if (empty($img_url)) {
  5132. Utils::throwError('20003:图片生成超时,请稍后重试');
  5133. }
  5134. return $img_url;
  5135. } catch (\Exception $e) {
  5136. dLog('anime')->error('更新角色或场景失败', [
  5137. 'error' => $e->getMessage()
  5138. ]);
  5139. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5140. Utils::throwError('20003:' . $e->getMessage());
  5141. }
  5142. }
  5143. /**
  5144. * 使用文生文模型解析分镜内容
  5145. */
  5146. private function parseSegmentContentWithAI($segment_content) {
  5147. try {
  5148. // 使用DeepSeek服务的公开方法解析分镜内容
  5149. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5150. } catch (\Exception $e) {
  5151. // 如果AI解析失败,记录日志并返回原内容
  5152. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5153. return $segment_content;
  5154. }
  5155. }
  5156. /**
  5157. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5158. *
  5159. * @param int $episode_id 分集ID
  5160. * @param int $anime_id 动漫ID
  5161. * @param array $roles 分集角色数组(引用传递)
  5162. * @param array $scenes 分集场景数组(引用传递)
  5163. * @param array $episode 分集数据
  5164. */
  5165. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5166. // 获取全局动漫的角色和场景数据
  5167. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5168. if (!$anime) return;
  5169. $art_style_type = getProp($anime, 'art_style_type');
  5170. $character_prefix = '';
  5171. $scene_prefix = '';
  5172. if ($art_style_type) {
  5173. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5174. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5175. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5176. }
  5177. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5178. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5179. $roles_updated = false;
  5180. $scenes_updated = false;
  5181. // 处理角色
  5182. foreach ($roles as &$role) {
  5183. $role_name = getProp($role, 'role');
  5184. $role_description = getProp($role, 'description');
  5185. $role_pic_prompt = getProp($role, 'pic_prompt');
  5186. $role_url = getProp($role, 'url');
  5187. $role_task_id = getProp($role, 'task_id');
  5188. // 如果已有URL或已有任务ID,跳过
  5189. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5190. continue;
  5191. }
  5192. $url_inherited = false;
  5193. // 尝试从全局数据中继承
  5194. foreach ($global_roles as $global_role) {
  5195. $global_role_name = getProp($global_role, 'role');
  5196. $global_role_description = getProp($global_role, 'description');
  5197. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5198. $global_role_url = getProp($global_role, 'url');
  5199. $global_role_task_id = getProp($global_role, 'task_id');
  5200. $global_role_task_status = getProp($global_role, 'task_status');
  5201. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5202. if ($role_name === $global_role_name
  5203. && $role_description === $global_role_description
  5204. && $role_pic_prompt === $global_role_pic_prompt
  5205. && !empty($global_role_url)) {
  5206. // 继承 task_id、task_status 和 url
  5207. $role['task_id'] = $global_role_task_id;
  5208. $role['task_status'] = $global_role_task_status;
  5209. $role['url'] = $global_role_url;
  5210. $roles_updated = true;
  5211. $url_inherited = true;
  5212. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5213. break;
  5214. }
  5215. }
  5216. // 如果无法继承且没有任务ID,创建新任务
  5217. if (!$url_inherited && empty($role_task_id)) {
  5218. try {
  5219. $art_style = getProp($episode, 'art_style');
  5220. // 优先使用 pic_prompt,如果没有则使用 description
  5221. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5222. // if ($art_style) {
  5223. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5224. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5225. // }
  5226. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5227. $params = [
  5228. 'prompt' => $description,
  5229. 'ref_img_urls' => []
  5230. ];
  5231. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5232. $task_id = $task->id;
  5233. if ($task_id) {
  5234. $role['task_id'] = $task_id;
  5235. $role['task_status'] = 'processing';
  5236. $roles_updated = true;
  5237. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5238. }
  5239. } catch (\Exception $e) {
  5240. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5241. }
  5242. }
  5243. }
  5244. // 处理场景
  5245. foreach ($scenes as &$scene) {
  5246. $scene_name = getProp($scene, 'scene');
  5247. $scene_description = getProp($scene, 'description');
  5248. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5249. $scene_url = getProp($scene, 'url');
  5250. $scene_task_id = getProp($scene, 'task_id');
  5251. // 如果已有URL或已有任务ID,跳过
  5252. if (!empty($scene_url) || !empty($scene_task_id)) {
  5253. continue;
  5254. }
  5255. $url_inherited = false;
  5256. // 尝试从全局数据中继承
  5257. foreach ($global_scenes as $global_scene) {
  5258. $global_scene_name = getProp($global_scene, 'scene');
  5259. $global_scene_description = getProp($global_scene, 'description');
  5260. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5261. $global_scene_url = getProp($global_scene, 'url');
  5262. $global_scene_task_id = getProp($global_scene, 'task_id');
  5263. $global_scene_task_status = getProp($global_scene, 'task_status');
  5264. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5265. if ($scene_name === $global_scene_name
  5266. && $scene_description === $global_scene_description
  5267. && $scene_pic_prompt === $global_scene_pic_prompt
  5268. && !empty($global_scene_url)) {
  5269. // 继承 task_id、task_status 和 url
  5270. $scene['task_id'] = $global_scene_task_id;
  5271. $scene['task_status'] = $global_scene_task_status;
  5272. $scene['url'] = $global_scene_url;
  5273. $scenes_updated = true;
  5274. $url_inherited = true;
  5275. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5276. break;
  5277. }
  5278. }
  5279. // 如果无法继承且没有任务ID,创建新任务
  5280. if (!$url_inherited && empty($scene_task_id)) {
  5281. try {
  5282. $art_style = getProp($episode, 'art_style');
  5283. // 优先使用 pic_prompt,如果没有则使用 description
  5284. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5285. // if ($art_style) {
  5286. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5287. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5288. // }
  5289. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5290. $params = [
  5291. 'prompt' => $description,
  5292. 'ref_img_urls' => []
  5293. ];
  5294. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5295. $task_id = $task->id;
  5296. if ($task_id) {
  5297. $scene['task_id'] = $task_id;
  5298. $scene['task_status'] = 'processing';
  5299. $scenes_updated = true;
  5300. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5301. }
  5302. } catch (\Exception $e) {
  5303. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5304. }
  5305. }
  5306. }
  5307. // 如果有更新,保存到数据库
  5308. if ($roles_updated || $scenes_updated) {
  5309. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5310. if ($roles_updated) {
  5311. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5312. }
  5313. if ($scenes_updated) {
  5314. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5315. }
  5316. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5317. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5318. }
  5319. }
  5320. /**
  5321. * 根据图片URL使用AI反推图片提示词
  5322. *
  5323. * @param string $img_url 图片URL
  5324. * @return string 反推的提示词
  5325. */
  5326. private function generateImagePromptFromUrl($img_url) {
  5327. try {
  5328. // 获取默认模型
  5329. $model = 'doubao-seed-2-0-mini-260215';
  5330. // 构建messages参数
  5331. $messages = [
  5332. [
  5333. 'role' => 'user',
  5334. 'content' => [
  5335. [
  5336. 'type' => 'text',
  5337. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5338. ],
  5339. [
  5340. 'type' => 'image_url',
  5341. 'image_url' => [
  5342. 'url' => $img_url
  5343. ]
  5344. ]
  5345. ]
  5346. ]
  5347. ];
  5348. // 构建请求参数
  5349. $params = [
  5350. 'model' => $model,
  5351. 'messages' => $messages,
  5352. 'stream' => false,
  5353. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5354. ];
  5355. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5356. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5357. // 返回生成的内容
  5358. return getProp($result, 'fullContent', '图片描述生成失败');
  5359. } catch (\Exception $e) {
  5360. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5361. 'img_url' => $img_url
  5362. ]);
  5363. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5364. 'error' => $e->getMessage(),
  5365. 'img_url' => $img_url
  5366. ]);
  5367. return '图片描述生成失败: ' . $e->getMessage();
  5368. }
  5369. }
  5370. /**
  5371. * 音频试听接口
  5372. * 创建音频任务并轮询获取结果
  5373. *
  5374. * @param array $data 参数数组
  5375. * @return array 返回音频URL或错误信息
  5376. */
  5377. public function previewAudio($data) {
  5378. $dialogue = getProp($data, 'dialogue');
  5379. // 必填参数验证
  5380. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5381. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5382. $voice_type = getProp($data, 'voice_type');
  5383. $voice_name = getProp($data, 'voice_name');
  5384. $voice_actor = getProp($data, 'voice_actor');
  5385. $emotion_type = getProp($data, 'emotion_type');
  5386. $gender = getProp($data, 'gender', 0);
  5387. $emotion = getProp($data, 'emotion');
  5388. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5389. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5390. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5391. $pitch = getProp($data, 'pitch', 0);
  5392. try {
  5393. $now = date('Y-m-d H:i:s');
  5394. // 构建生成参数
  5395. $generate_json = json_encode([
  5396. 'text' => $dialogue,
  5397. 'role' => $voice_actor,
  5398. 'voice_type' => $voice_type,
  5399. 'voice_name' => $voice_name,
  5400. 'emotion' => $emotion,
  5401. 'emotion_type' => $emotion_type,
  5402. 'gender' => $gender,
  5403. 'speed_ratio' => $speed_ratio,
  5404. 'loudness_ratio' => $loudness_ratio,
  5405. 'emotion_scale' => $emotion_scale,
  5406. 'pitch' => $pitch,
  5407. ], 256);
  5408. // 请求远程服务器执行生成
  5409. $client = new Client(['timeout' => 600, 'verify' => false]);
  5410. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5411. $response = $result->getBody()->getContents();
  5412. $response_arr = json_decode($response, true);
  5413. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5414. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5415. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5416. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5417. }
  5418. $arr = $response_arr['data'];
  5419. $subtitle_info = $arr['subtitle_info'];
  5420. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5421. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5422. return [
  5423. 'audio_url' => $arr['url'],
  5424. 'subtitle_info' => $subtitle_info,
  5425. 'audio_duration' => round($audio_duration, 2)
  5426. ];
  5427. } catch (\Exception $e) {
  5428. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5429. Utils::throwError('20003:' . $e->getMessage());
  5430. }
  5431. }
  5432. /**
  5433. * 获取角色库列表(支持文件夹递归查询)
  5434. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5435. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5436. */
  5437. public function globalProducts($data) {
  5438. $uid = Site::getUid();
  5439. $cpid = Site::getCpid();
  5440. $role = Site::getRole();
  5441. $id = getProp($data, 'id', 0);
  5442. $parent_id = getProp($data, 'parent_id', 0);
  5443. $product_name = getProp($data, 'product_name');
  5444. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5445. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5446. if (!$product) {
  5447. Utils::throwError('20003:请选择产品类型');
  5448. }
  5449. // 根据角色和is_public参数确定查询范围
  5450. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5451. // user角色:根据is_public参数筛选
  5452. $query_user_ids = [];
  5453. if ($role === 'admin') {
  5454. // admin获取所有个人库和公共库
  5455. $query_user_ids = [$uid, 0];
  5456. } else {
  5457. // user角色根据is_public参数筛选
  5458. if ($is_public == 2) {
  5459. // 个人库+公共库
  5460. $query_user_ids = [$uid, 0];
  5461. } elseif ($is_public == 0) {
  5462. // 仅个人库
  5463. $query_user_ids = [$uid];
  5464. } elseif ($is_public == 1) {
  5465. // 仅公共库
  5466. $query_user_ids = [0];
  5467. }
  5468. }
  5469. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5470. if ($id || $product_name) {
  5471. $query = DB::table('mp_products')
  5472. ->where('cpid', $cpid)
  5473. ->whereIn('user_id', $query_user_ids)
  5474. ->where('is_deleted', 0);
  5475. // 如果指定了 id,按 id 精确查询
  5476. if ($id) {
  5477. $query->where('id', $id);
  5478. }
  5479. // 如果指定了 product_name,按名称模糊查询
  5480. if ($product_name) {
  5481. $query->where('product_name', 'like', "%{$product_name}%");
  5482. }
  5483. // 如果指定了 product,添加筛选条件
  5484. if ($product) {
  5485. $query->where('product', $product);
  5486. }
  5487. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5488. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5489. ->get()
  5490. ->map(function($value) {
  5491. $value = (array)$value;
  5492. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5493. $value['type'] = (int)$value['type'];
  5494. $value['parent_id'] = (int)$value['parent_id'];
  5495. $value['level'] = (int)$value['level'];
  5496. $value['product'] = (int)($value['product'] ?? 1);
  5497. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5498. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5499. unset($value['user_id']);
  5500. return $value;
  5501. })
  5502. ->toArray();
  5503. return $result;
  5504. }
  5505. // 递归获取所有子目录和角色
  5506. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5507. }
  5508. /**
  5509. * 递归获取指定目录下的所有子目录和角色
  5510. * @param int $cpid 公司ID
  5511. * @param int $parent_id 父目录ID
  5512. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5513. * @param array $query_user_ids 用户ID数组(支持多个)
  5514. * @param int $current_uid 当前用户ID(用于排序)
  5515. * @return array
  5516. */
  5517. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5518. // 查询当前层级的所有项(文件夹和角色)
  5519. $query = DB::table('mp_products')
  5520. ->where('cpid', $cpid)
  5521. ->where('is_deleted', 0)
  5522. ->where('parent_id', $parent_id);
  5523. // 添加用户ID验证(支持多个user_id)
  5524. if (!empty($query_user_ids)) {
  5525. $query->whereIn('user_id', $query_user_ids);
  5526. }
  5527. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5528. if ($product) {
  5529. $query->where('product', $product);
  5530. }
  5531. // 排序规则:
  5532. // 1. 文件夹在前(type DESC)
  5533. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5534. // 3. 其他排序规则
  5535. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5536. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5537. ->get();
  5538. $result = [];
  5539. foreach ($items as $item) {
  5540. $itemArray = [
  5541. 'id' => $item->id,
  5542. 'type' => (int)$item->type,
  5543. 'parent_id' => (int)$item->parent_id,
  5544. 'level' => (int)$item->level,
  5545. 'product_name' => $item->product_name,
  5546. 'url' => $item->url,
  5547. 'pic_prompt' => $item->pic_prompt ?? '',
  5548. 'three_view_image_url' => $item->three_view_image_url,
  5549. 'product' => (int)($item->product ?? 1),
  5550. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5551. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5552. ];
  5553. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5554. // 如果是文件夹,递归获取其子项
  5555. if ($item->type == 2) {
  5556. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5557. if (!empty($children)) {
  5558. $itemArray['children'] = $children;
  5559. }
  5560. }
  5561. $result[] = $itemArray;
  5562. }
  5563. return $result;
  5564. }
  5565. /**
  5566. * 创建文件夹
  5567. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5568. * @return int 返回新建文件夹ID
  5569. */
  5570. public function createFolder($data) {
  5571. $uid = Site::getUid();
  5572. $cpid = Site::getCpid();
  5573. $role = Site::getRole();
  5574. $parent_id = getProp($data, 'parent_id', 0);
  5575. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5576. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5577. // 如果是公共库操作,需要admin权限
  5578. if ($is_public && $role !== 'admin') {
  5579. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5580. }
  5581. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5582. $store_uid = $is_public ? 0 : $uid;
  5583. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5584. $product = getProp($data, 'product');
  5585. if (!in_array($product, [1, 2, 3])) {
  5586. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5587. }
  5588. // 验证父文件夹
  5589. $parent_level = 0;
  5590. if ($parent_id > 0) {
  5591. $parent = DB::table('mp_products')
  5592. ->where('id', $parent_id)
  5593. ->where('cpid', $cpid)
  5594. ->where('user_id', $store_uid)
  5595. ->where('type', 2)
  5596. ->where('is_deleted', 0)
  5597. ->first();
  5598. if (!$parent) {
  5599. Utils::throwError('20003:父文件夹不存在');
  5600. }
  5601. // 检查父文件夹的 product 类型是否一致
  5602. if ($parent->product != $product) {
  5603. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5604. }
  5605. $parent_level = $parent->level;
  5606. // 检查层级限制(最多3层)
  5607. if ($parent_level >= 3) {
  5608. Utils::throwError('20003:文件夹层级不能超过3层');
  5609. }
  5610. }
  5611. // 检查当前目录下是否已存在空白文件夹
  5612. $empty_folder_exists = DB::table('mp_products')
  5613. ->where('parent_id', $parent_id)
  5614. ->where('cpid', $cpid)
  5615. ->where('user_id', $store_uid)
  5616. ->where('type', 2)
  5617. ->where('product', $product)
  5618. ->where('product_name', '新建文件夹')
  5619. ->where('is_deleted', 0)
  5620. ->exists();
  5621. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5622. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5623. }
  5624. // 创建文件夹
  5625. $folder_id = DB::table('mp_products')->insertGetId([
  5626. 'user_id' => $store_uid,
  5627. 'cpid' => $cpid,
  5628. 'type' => 2,
  5629. 'parent_id' => $parent_id,
  5630. 'level' => $parent_level + 1,
  5631. 'product_name' => $folder_name,
  5632. 'product' => $product,
  5633. 'sort_order' => time(), // 使用时间戳作为排序权重
  5634. 'is_deleted' => 0,
  5635. 'created_at' => date('Y-m-d H:i:s'),
  5636. 'updated_at' => date('Y-m-d H:i:s')
  5637. ]);
  5638. return [
  5639. 'id' => $folder_id,
  5640. 'type' => 2,
  5641. 'parent_id' => $parent_id,
  5642. 'level' => $parent_level + 1,
  5643. 'product_name' => $folder_name,
  5644. 'product' => $product,
  5645. ];
  5646. }
  5647. /**
  5648. * 重命名文件夹或角色
  5649. * @param array $data 包含 id、product_name(新名称)
  5650. * @return bool
  5651. */
  5652. public function renameFolder($data) {
  5653. $uid = Site::getUid();
  5654. $cpid = Site::getCpid();
  5655. $role = Site::getRole();
  5656. $id = getProp($data, 'id');
  5657. $new_name = getProp($data, 'product_name');
  5658. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5659. if (!$id || !$new_name) {
  5660. Utils::throwError('20003:参数不完整');
  5661. }
  5662. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5663. $query_uid = $is_public ? 0 : $uid;
  5664. // 如果是公共库操作,需要admin权限
  5665. if ($is_public && $role !== 'admin') {
  5666. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5667. }
  5668. // 检查是否存在
  5669. $item = DB::table('mp_products')
  5670. ->where('id', $id)
  5671. ->where('cpid', $cpid)
  5672. ->where('user_id', $query_uid)
  5673. ->where('is_deleted', 0)
  5674. ->first();
  5675. if (!$item) {
  5676. Utils::throwError('20003:项目不存在');
  5677. }
  5678. return DB::table('mp_products')
  5679. ->where('id', $id)
  5680. ->where('cpid', $cpid)
  5681. ->where('user_id', $query_uid)
  5682. ->update([
  5683. 'product_name' => $new_name,
  5684. 'updated_at' => date('Y-m-d H:i:s')
  5685. ]);
  5686. }
  5687. /**
  5688. * 移动角色或文件夹到指定文件夹
  5689. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5690. * @return bool
  5691. */
  5692. public function moveProductOrFolder($data) {
  5693. $uid = Site::getUid();
  5694. $cpid = Site::getCpid();
  5695. $role = Site::getRole();
  5696. $id = getProp($data, 'id');
  5697. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5698. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5699. if (!$id) {
  5700. Utils::throwError('20003:请选择要移动的项目');
  5701. }
  5702. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5703. $query_uid = $is_public ? 0 : $uid;
  5704. // 如果是公共库操作,需要admin权限
  5705. if ($is_public && $role !== 'admin') {
  5706. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5707. }
  5708. // 检查要移动的项目
  5709. $item = DB::table('mp_products')
  5710. ->where('id', $id)
  5711. ->where('cpid', $cpid)
  5712. ->where('user_id', $query_uid)
  5713. ->where('is_deleted', 0)
  5714. ->first();
  5715. if (!$item) {
  5716. Utils::throwError('20003:项目不存在');
  5717. }
  5718. // 验证目标文件夹
  5719. $target_level = 0;
  5720. $target_product = $item->product; // 默认使用当前项目的 product
  5721. if ($target_parent_id > 0) {
  5722. $target_parent = DB::table('mp_products')
  5723. ->where('id', $target_parent_id)
  5724. ->where('cpid', $cpid)
  5725. ->where('user_id', $query_uid)
  5726. ->where('type', 2)
  5727. ->where('is_deleted', 0)
  5728. ->first();
  5729. if (!$target_parent) {
  5730. Utils::throwError('20003:目标文件夹不存在');
  5731. }
  5732. // 检查 product 类型是否一致
  5733. if ($target_parent->product != $item->product) {
  5734. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5735. }
  5736. $target_level = $target_parent->level;
  5737. $target_product = $target_parent->product;
  5738. // 如果移动的是文件夹,需要检查层级
  5739. if ($item->type == 2) {
  5740. // 计算移动后的最大层级
  5741. $max_child_level = $this->getMaxChildLevel($id);
  5742. $depth = $max_child_level - $item->level;
  5743. if ($target_level + 1 + $depth > 3) {
  5744. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5745. }
  5746. // 不能移动到自己或自己的子文件夹下
  5747. if ($this->isDescendant($target_parent_id, $id)) {
  5748. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5749. }
  5750. }
  5751. }
  5752. // 更新父文件夹和层级
  5753. $new_level = $target_level + 1;
  5754. DB::table('mp_products')
  5755. ->where('id', $id)
  5756. ->update([
  5757. 'parent_id' => $target_parent_id,
  5758. 'level' => $new_level,
  5759. 'updated_at' => date('Y-m-d H:i:s')
  5760. ]);
  5761. // 如果是文件夹,需要递归更新所有子项的层级
  5762. if ($item->type == 2) {
  5763. $this->updateChildrenLevel($id, $new_level);
  5764. }
  5765. return true;
  5766. }
  5767. /**
  5768. * 获取文件夹下最大子层级
  5769. * @param int $folder_id
  5770. * @return int
  5771. */
  5772. private function getMaxChildLevel($folder_id) {
  5773. $max_level = DB::table('mp_products')
  5774. ->where('parent_id', $folder_id)
  5775. ->where('is_deleted', 0)
  5776. ->max('level');
  5777. if (!$max_level) {
  5778. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5779. }
  5780. // 递归查找子文件夹
  5781. $children = DB::table('mp_products')
  5782. ->where('parent_id', $folder_id)
  5783. ->where('type', 2)
  5784. ->where('is_deleted', 0)
  5785. ->pluck('id');
  5786. foreach ($children as $child_id) {
  5787. $child_max = $this->getMaxChildLevel($child_id);
  5788. if ($child_max > $max_level) {
  5789. $max_level = $child_max;
  5790. }
  5791. }
  5792. return $max_level;
  5793. }
  5794. /**
  5795. * 检查 target_id 是否是 folder_id 的后代
  5796. * @param int $target_id
  5797. * @param int $folder_id
  5798. * @return bool
  5799. */
  5800. private function isDescendant($target_id, $folder_id) {
  5801. if ($target_id == $folder_id) {
  5802. return true;
  5803. }
  5804. $parent = DB::table('mp_products')
  5805. ->where('id', $target_id)
  5806. ->where('is_deleted', 0)
  5807. ->first();
  5808. if (!$parent || $parent->parent_id == 0) {
  5809. return false;
  5810. }
  5811. return $this->isDescendant($parent->parent_id, $folder_id);
  5812. }
  5813. /**
  5814. * 递归更新子项层级
  5815. * @param int $parent_id
  5816. * @param int $parent_level
  5817. */
  5818. private function updateChildrenLevel($parent_id, $parent_level) {
  5819. $children = DB::table('mp_products')
  5820. ->where('parent_id', $parent_id)
  5821. ->where('is_deleted', 0)
  5822. ->get();
  5823. foreach ($children as $child) {
  5824. $new_level = $parent_level + 1;
  5825. DB::table('mp_products')
  5826. ->where('id', $child->id)
  5827. ->update([
  5828. 'level' => $new_level,
  5829. 'updated_at' => date('Y-m-d H:i:s')
  5830. ]);
  5831. // 如果是文件夹,继续递归
  5832. if ($child->type == 2) {
  5833. $this->updateChildrenLevel($child->id, $new_level);
  5834. }
  5835. }
  5836. }
  5837. /**
  5838. * 获取文件夹路径(面包屑导航)
  5839. * @param array $data 包含 folder_id
  5840. * @return array 返回路径数组
  5841. */
  5842. public function getFolderPath($data) {
  5843. $uid = Site::getUid();
  5844. $cpid = Site::getCpid();
  5845. $folder_id = getProp($data, 'id', 0);
  5846. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5847. if ($folder_id == 0) {
  5848. return [
  5849. ['id' => 0, 'name' => '根目录']
  5850. ];
  5851. }
  5852. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5853. $query_uid = $is_public ? 0 : $uid;
  5854. $path = [];
  5855. $current_id = $folder_id;
  5856. while ($current_id > 0) {
  5857. $folder = DB::table('mp_products')
  5858. ->where('id', $current_id)
  5859. ->where('cpid', $cpid)
  5860. ->where('user_id', $query_uid)
  5861. ->where('type', 2)
  5862. ->where('is_deleted', 0)
  5863. ->first();
  5864. if (!$folder) {
  5865. break;
  5866. }
  5867. array_unshift($path, [
  5868. 'id' => $folder->id,
  5869. 'name' => $folder->product_name
  5870. ]);
  5871. $current_id = $folder->parent_id;
  5872. }
  5873. // 添加根目录
  5874. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5875. return $path;
  5876. }
  5877. public function createProduct($data) {
  5878. $uid = Site::getUid();
  5879. $cpid = Site::getCpid();
  5880. $role = Site::getRole();
  5881. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5882. // 如果是公共库操作,需要admin权限
  5883. if ($is_public && $role !== 'admin') {
  5884. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5885. }
  5886. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5887. $store_uid = $is_public ? 0 : $uid;
  5888. $product_name = trim(getProp($data, 'product_name'));
  5889. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5890. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5891. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5892. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5893. $url = trim(getProp($data, 'url'));
  5894. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5895. $versions = getProp($data, 'versions');
  5896. // 检查是否是正确的图片格式
  5897. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5898. $urlPath = parse_url($url, PHP_URL_PATH);
  5899. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5900. if (!in_array($extension, $allowedExtensions)) {
  5901. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5902. }
  5903. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5904. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5905. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5906. $product = getProp($data, 'product');
  5907. if (!in_array($product, [1, 2, 3])) {
  5908. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5909. }
  5910. // 获取父文件夹ID和层级
  5911. $parent_id = getProp($data, 'parent_id', 0);
  5912. $parent_level = 0;
  5913. if ($parent_id > 0) {
  5914. $parent = DB::table('mp_products')
  5915. ->where('id', $parent_id)
  5916. ->where('cpid', $cpid)
  5917. ->where('user_id', $store_uid)
  5918. ->where('type', 2)
  5919. ->where('is_deleted', 0)
  5920. ->first();
  5921. if (!$parent) {
  5922. Utils::throwError('20003:父文件夹不存在');
  5923. }
  5924. $parent_level = $parent->level;
  5925. }
  5926. $id = DB::table('mp_products')->insertGetId([
  5927. 'user_id' => $store_uid,
  5928. 'cpid' => $cpid,
  5929. 'type' => 1, // 1=角色图片
  5930. 'parent_id' => $parent_id,
  5931. 'level' => $parent_level + 1,
  5932. 'product_name' => $product_name,
  5933. 'url' => $url,
  5934. 'pic_prompt' => $pic_prompt,
  5935. 'product' => $product,
  5936. 'versions' => json_encode($versions, 256),
  5937. 'sort_order' => time(), // 使用时间戳作为排序权重
  5938. 'created_at' => date('Y-m-d H:i:s'),
  5939. 'updated_at' => date('Y-m-d H:i:s')
  5940. ]);
  5941. if (!$id) Utils::throwError('20003:创建失败');
  5942. return [
  5943. 'id' => $id,
  5944. 'type' => 1,
  5945. 'parent_id' => $parent_id,
  5946. 'level' => $parent_level + 1,
  5947. 'product_name' => $product_name,
  5948. 'url' => $url,
  5949. 'pic_prompt' => $pic_prompt,
  5950. 'product' => $product,
  5951. 'versions' => $versions
  5952. ];
  5953. }
  5954. public function editProduct($data) {
  5955. $uid = Site::getUid();
  5956. $cpid = Site::getCpid();
  5957. $role = Site::getRole();
  5958. $id = getProp($data, 'id');
  5959. if (!$id) Utils::throwError('20003:ID不能为空');
  5960. $versions = getProp($data, 'versions');
  5961. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5962. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5963. $query_uid = $is_public ? 0 : $uid;
  5964. // 如果是公共库操作,需要admin权限
  5965. if ($is_public && $role !== 'admin') {
  5966. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5967. }
  5968. // 检查是否存在且属于当前用户或公共库
  5969. $role = DB::table('mp_products')
  5970. ->where('id', $id)
  5971. ->where('cpid', $cpid)
  5972. ->where('user_id', $query_uid)
  5973. ->where('type', 1)->first();
  5974. if (!$role) Utils::throwError('20003:记录不存在');
  5975. $updateData = [];
  5976. // $needVersionRecord = false; // 是否需要记录版本
  5977. // 名称
  5978. $product_name = trim(getProp($data, 'product_name'));
  5979. if ($product_name) {
  5980. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5981. $updateData['product_name'] = $product_name;
  5982. }
  5983. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5984. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5985. // 图片地址
  5986. $url = trim(getProp($data, 'url'));
  5987. if ($url) {
  5988. // 检查是否是正确的图片格式
  5989. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5990. $urlPath = parse_url($url, PHP_URL_PATH);
  5991. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5992. if (!in_array($extension, $allowedExtensions)) {
  5993. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5994. }
  5995. // // 如果 url 有变更,记录版本
  5996. // if ($url !== $role->url) {
  5997. // $needVersionRecord = true;
  5998. // }
  5999. $updateData['url'] = $url;
  6000. }
  6001. // 提示词
  6002. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6003. if ($pic_prompt) {
  6004. // // 如果 pic_prompt 有变更,记录版本
  6005. // if ($pic_prompt !== $role->pic_prompt) {
  6006. // $needVersionRecord = true;
  6007. // }
  6008. $updateData['pic_prompt'] = $pic_prompt;
  6009. }
  6010. if (empty($updateData)) {
  6011. Utils::throwError('20003:没有需要更新的数据');
  6012. }
  6013. // // 如果需要记录版本,将数据添加到 versions 数组
  6014. // if ($needVersionRecord) {
  6015. // // 获取现有的 versions 数据
  6016. // $versions = json_decode($role->versions, true) ?: [];
  6017. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6018. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6019. // if ($isFirstVersion) {
  6020. // $oldVersion = [
  6021. // 'url' => $role->url,
  6022. // 'description' => $role->pic_prompt,
  6023. // ];
  6024. // // 旧版本添加到数组末尾
  6025. // $versions[] = $oldVersion;
  6026. // }
  6027. // // 构建新版本(变更后)
  6028. // $newVersion = [
  6029. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6030. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6031. // ];
  6032. // // 检查新版本是否已存在于历史版本中
  6033. // $existingIndex = -1;
  6034. // foreach ($versions as $index => $version) {
  6035. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6036. // $existingIndex = $index;
  6037. // break;
  6038. // }
  6039. // }
  6040. // if ($existingIndex !== -1) {
  6041. // // 如果已存在,移除旧的位置
  6042. // array_splice($versions, $existingIndex, 1);
  6043. // }
  6044. // // 新版本添加到数组开头(最新的在前)
  6045. // array_unshift($versions, $newVersion);
  6046. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6047. // // if (count($versions) > 10) {
  6048. // // $versions = array_slice($versions, 0, 10);
  6049. // // }
  6050. // $updateData['versions'] = json_encode($versions, 256);
  6051. // }
  6052. if ($versions) {
  6053. $updateData['versions'] = json_encode($versions, 256);
  6054. }
  6055. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6056. return DB::table('mp_products')
  6057. ->where('cpid', $cpid)
  6058. ->where('id', $id)->update($updateData);
  6059. }
  6060. /**
  6061. * 获取角色版本历史
  6062. * @param array $data 包含 id(角色ID)
  6063. * @return array 返回版本历史列表
  6064. */
  6065. public function getProductVersions($data) {
  6066. $cpid = Site::getCpid();
  6067. $id = getProp($data, 'id');
  6068. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6069. $role = DB::table('mp_products')
  6070. ->where('id', $id)
  6071. ->where('cpid', $cpid)
  6072. ->where('type', 1)
  6073. ->first();
  6074. if (!$role) Utils::throwError('20003:角色不存在');
  6075. // 获取版本历史
  6076. $versions = json_decode($role->versions, true) ?: [];
  6077. // 添加当前版本作为最新版本
  6078. $currentVersion = [
  6079. 'version' => 0, // 0 表示当前版本
  6080. 'url' => $role->url,
  6081. 'pic_prompt' => $role->pic_prompt,
  6082. 'updated_at' => $role->updated_at,
  6083. 'is_current' => true
  6084. ];
  6085. array_unshift($versions, $currentVersion);
  6086. return $versions;
  6087. }
  6088. /**
  6089. * 恢复到指定版本
  6090. * @param array $data 包含 id(角色ID)、version(版本号)
  6091. * @return bool
  6092. */
  6093. public function restoreProductVersion($data) {
  6094. $uid = Site::getUid();
  6095. $cpid = Site::getCpid();
  6096. $id = getProp($data, 'id');
  6097. $version = getProp($data, 'version');
  6098. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6099. if (!$version) Utils::throwError('20003:版本号不能为空');
  6100. $role = DB::table('mp_products')
  6101. ->where('id', $id)
  6102. ->where('cpid', $cpid)
  6103. ->where('type', 1)
  6104. ->first();
  6105. if (!$role) Utils::throwError('20003:角色不存在');
  6106. // 获取版本历史
  6107. $versions = json_decode($role->versions, true) ?: [];
  6108. // 查找指定版本
  6109. $targetVersion = null;
  6110. foreach ($versions as $v) {
  6111. if ($v['version'] == $version) {
  6112. $targetVersion = $v;
  6113. break;
  6114. }
  6115. }
  6116. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6117. // 先将当前版本保存到历史
  6118. $newVersion = [
  6119. 'version' => count($versions) + 1,
  6120. 'url' => $role->url,
  6121. 'pic_prompt' => $role->pic_prompt,
  6122. 'updated_at' => date('Y-m-d H:i:s'),
  6123. 'updated_by' => $uid
  6124. ];
  6125. array_unshift($versions, $newVersion);
  6126. // 限制版本数量
  6127. if (count($versions) > 10) {
  6128. $versions = array_slice($versions, 0, 10);
  6129. }
  6130. // 恢复到指定版本
  6131. return DB::table('mp_products')
  6132. ->where('id', $id)
  6133. ->where('cpid', $cpid)
  6134. ->update([
  6135. 'url' => $targetVersion['url'],
  6136. 'pic_prompt' => $targetVersion['pic_prompt'],
  6137. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6138. 'updated_at' => date('Y-m-d H:i:s')
  6139. ]);
  6140. }
  6141. public function deleteProduct($data) {
  6142. $uid = Site::getUid();
  6143. $cpid = Site::getCpid();
  6144. $role = Site::getRole();
  6145. $id = getProp($data, 'id');
  6146. if (!$id) Utils::throwError('20003:ID不能为空');
  6147. $ids = explode(',', $id);
  6148. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6149. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6150. $query_uid = $is_public ? 0 : $uid;
  6151. // 如果是公共库操作,需要admin权限
  6152. if ($is_public && $role !== 'admin') {
  6153. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6154. }
  6155. // 检查是否存在且属于当前用户或公共库
  6156. $role = DB::table('mp_products')
  6157. ->whereIn('id', $ids)
  6158. ->where('cpid', $cpid)
  6159. ->where('user_id', $query_uid)
  6160. ->get();
  6161. if (!$role) Utils::throwError('20003:记录不存在');
  6162. return DB::table('mp_products')
  6163. ->where('cpid', $cpid)
  6164. ->where('user_id', $query_uid)
  6165. ->whereIn('id', $ids)
  6166. ->update([
  6167. 'is_deleted' => 1,
  6168. 'updated_at' => date('Y-m-d H:i:s')
  6169. ]);
  6170. }
  6171. public function generateThreeView($data) {
  6172. $uid = Site::getUid();
  6173. $cpid = Site::getCpid();
  6174. $role = Site::getRole();
  6175. $id = getProp($data, 'id');
  6176. if (!$id) Utils::throwError('20003:ID不能为空');
  6177. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6178. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6179. $query_uid = $is_public ? 0 : $uid;
  6180. // 如果是公共库操作,需要admin权限
  6181. if ($is_public && $role !== 'admin') {
  6182. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6183. }
  6184. // 检查是否存在且属于当前用户或公共库
  6185. $product = DB::table('mp_products')
  6186. ->where('id', $id)
  6187. ->where('cpid', $cpid)
  6188. ->where('user_id', $query_uid)
  6189. ->where('type', 1)->first();
  6190. if (!$product) Utils::throwError('20003:资产不存在');
  6191. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6192. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6193. if (!$ref_img_url) {
  6194. // 如果没有传入参考图,使用角色表中的图片
  6195. $ref_img_url = $product->url ?? '';
  6196. if (!$ref_img_url) {
  6197. Utils::throwError('20003:参考图不能为空');
  6198. }
  6199. }
  6200. $pic_prompt = getProp($product, 'pic_prompt');
  6201. if ($pic_prompt) {
  6202. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6203. }
  6204. // 检查参考图是否是正确的图片格式
  6205. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6206. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6207. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6208. if (!in_array($extension, $allowedExtensions)) {
  6209. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6210. }
  6211. // 处理图片模型
  6212. $model = getProp($data, 'model');
  6213. if (!$model) {
  6214. // 使用默认模型
  6215. $model = 'doubao-seedream-5-0-lite-260128';
  6216. }
  6217. // 验证模型是否在可用模型表中
  6218. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6219. Utils::throwError('20003:该模型已不可用,请更换!');
  6220. }
  6221. $ratio = getProp($data, 'ratio', '16:9');
  6222. $resolution = getProp($data, 'resolution', '2k');
  6223. // 定义分辨率和宽高比对应的尺寸映射表
  6224. $sizeMap = [
  6225. '2k' => [
  6226. '1:1' => ['width' => 2048, 'height' => 2048],
  6227. '4:3' => ['width' => 2304, 'height' => 1728],
  6228. '3:4' => ['width' => 1728, 'height' => 2304],
  6229. '16:9' => ['width' => 2848, 'height' => 1600],
  6230. '9:16' => ['width' => 1600, 'height' => 2848],
  6231. '3:2' => ['width' => 2496, 'height' => 1664],
  6232. '2:3' => ['width' => 1664, 'height' => 2496],
  6233. '21:9' => ['width' => 3136, 'height' => 1344],
  6234. ],
  6235. '3k' => [
  6236. '1:1' => ['width' => 3072, 'height' => 3072],
  6237. '4:3' => ['width' => 3456, 'height' => 2592],
  6238. '3:4' => ['width' => 2592, 'height' => 3456],
  6239. '16:9' => ['width' => 4096, 'height' => 2304],
  6240. '9:16' => ['width' => 2304, 'height' => 4096],
  6241. '2:3' => ['width' => 2496, 'height' => 3744],
  6242. '3:2' => ['width' => 3744, 'height' => 2496],
  6243. '21:9' => ['width' => 4704, 'height' => 2016],
  6244. ],
  6245. '4k' => [
  6246. '1:1' => ['width' => 4096, 'height' => 4096],
  6247. '3:4' => ['width' => 3520, 'height' => 4704],
  6248. '4:3' => ['width' => 4704, 'height' => 3520],
  6249. '16:9' => ['width' => 5504, 'height' => 3040],
  6250. '9:16' => ['width' => 3040, 'height' => 5504],
  6251. '2:3' => ['width' => 3328, 'height' => 4992],
  6252. '3:2' => ['width' => 4992, 'height' => 3328],
  6253. '21:9' => ['width' => 6240, 'height' => 2656],
  6254. ],
  6255. ];
  6256. // 参数验证
  6257. $resolution = strtolower($resolution);
  6258. if (!isset($sizeMap[$resolution])) {
  6259. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6260. }
  6261. if (!isset($sizeMap[$resolution][$ratio])) {
  6262. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6263. }
  6264. // 根据 ratio 和 resolution 确定宽高
  6265. $width = $sizeMap[$resolution][$ratio]['width'];
  6266. $height = $sizeMap[$resolution][$ratio]['height'];
  6267. try {
  6268. // 创建图片生成任务
  6269. $params = [
  6270. 'prompt' => $prompt,
  6271. 'model' => $model,
  6272. 'ref_img_urls' => [$ref_img_url],
  6273. 'width' => $width,
  6274. 'height' => $height
  6275. ];
  6276. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6277. $task_id = $task->id;
  6278. if (!$task_id) {
  6279. Utils::throwError('20003:创建图片生成任务失败');
  6280. }
  6281. // 轮询获取结果
  6282. // 只查询数据库,不调用API,不更新任务表
  6283. $start_time = time();
  6284. $timeout = 1800;
  6285. $img_url = '';
  6286. while (time() - $start_time < $timeout) {
  6287. sleep(5);
  6288. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6289. $task = DB::table('mp_generate_pic_tasks')
  6290. ->where('id', $task_id)
  6291. ->first();
  6292. if (!$task) {
  6293. Utils::throwError('20003:任务不存在');
  6294. }
  6295. if ($task->status === 'success' && $task->result_url) {
  6296. $result_urls = is_string($task->result_url)
  6297. ? json_decode($task->result_url, true)
  6298. : $task->result_url;
  6299. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6300. break;
  6301. } elseif ($task->status === 'failed') {
  6302. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6303. }
  6304. // 其他状态继续轮询
  6305. }
  6306. if (empty($img_url)) {
  6307. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6308. }
  6309. // 更新 mp_products 表(不是任务表)
  6310. DB::table('mp_products')
  6311. ->where('id', $id)
  6312. ->where('cpid', $cpid)
  6313. ->update([
  6314. 'three_view_image_url' => $img_url,
  6315. 'updated_at' => date('Y-m-d H:i:s')
  6316. ]);
  6317. return ['three_view_image_url' => $img_url];
  6318. } catch (\Exception $e) {
  6319. dLog('anime')->error('生成三视图失败', [
  6320. 'error' => $e->getMessage()
  6321. ]);
  6322. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6323. Utils::throwError('20003:' . $e->getMessage());
  6324. }
  6325. }
  6326. /**
  6327. * 推送(复制)资产或文件夹到目标位置
  6328. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6329. * @return array 返回推送结果
  6330. */
  6331. public function pushProductOrFolder($data) {
  6332. $uid = Site::getUid();
  6333. $cpid = Site::getCpid();
  6334. $role = Site::getRole();
  6335. $product_id = getProp($data, 'product_id');
  6336. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6337. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6338. if (!$product_id) {
  6339. Utils::throwError('20003:请选择要推送的项目');
  6340. }
  6341. // 查询源项目(只通过cpid查询,不限制user_id)
  6342. $sourceItem = DB::table('mp_products')
  6343. ->where('id', $product_id)
  6344. ->where('cpid', $cpid)
  6345. ->where('is_deleted', 0)
  6346. ->first();
  6347. if (!$sourceItem) {
  6348. Utils::throwError('20003:要推送的项目不存在');
  6349. }
  6350. // 通过user_id判断源是公共库还是个人库
  6351. $source_uid = $sourceItem->user_id;
  6352. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6353. // 验证目标文件夹并确定目标是公共库还是个人库
  6354. $target_level = 0;
  6355. $target_uid = $uid; // 默认推送到个人库
  6356. $target_is_public = 0;
  6357. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6358. if ($target_parent_id > 0) {
  6359. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6360. $targetParent = DB::table('mp_products')
  6361. ->where('id', $target_parent_id)
  6362. ->where('cpid', $cpid)
  6363. ->where('type', 2)
  6364. ->where('is_deleted', 0)
  6365. ->first();
  6366. if (!$targetParent) {
  6367. Utils::throwError('20003:目标文件夹不存在');
  6368. }
  6369. // 通过user_id判断目标是公共库还是个人库
  6370. $target_level = $targetParent->level;
  6371. $target_uid = $targetParent->user_id;
  6372. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6373. // 使用目标文件夹的 product 类型
  6374. $final_product_type = $targetParent->product;
  6375. }
  6376. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6377. else {
  6378. $push_to_public = getProp($data, 'push_to_public');
  6379. if ($push_to_public === '') {
  6380. Utils::throwError('20003:请选择是否推送到公共库');
  6381. }
  6382. if ($push_to_public) {
  6383. $target_uid = 0;
  6384. $target_is_public = 1;
  6385. }
  6386. // 推送到根目录时,必须指定 product 类型
  6387. if ($target_product === null || $target_product === '') {
  6388. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6389. }
  6390. $final_product_type = $target_product;
  6391. }
  6392. // 如果目标是公共库,需要admin权限
  6393. if ($target_is_public && $role !== 'admin') {
  6394. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6395. }
  6396. // 权限验证:验证是否符合允许的推送规则
  6397. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6398. try {
  6399. DB::beginTransaction();
  6400. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6401. if ($sourceItem->type == 1) {
  6402. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6403. DB::commit();
  6404. return [
  6405. 'product_id' => $newId,
  6406. ];
  6407. }
  6408. // 如果是文件夹,递归复制(支持跨类型推送)
  6409. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6410. DB::commit();
  6411. return [
  6412. 'product_id' => $newFolderId,
  6413. ];
  6414. } catch (\Exception $e) {
  6415. DB::rollBack();
  6416. dLog('anime')->error('推送失败', [
  6417. 'error' => $e->getMessage(),
  6418. 'product_id' => $product_id
  6419. ]);
  6420. Utils::throwError('20003:' . $e->getMessage());
  6421. }
  6422. }
  6423. /**
  6424. * 验证推送权限
  6425. * 允许的推送规则:
  6426. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6427. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6428. * 3. 公共库推送给公共库(公共库 → 公共库)
  6429. *
  6430. * @param int $source_uid 源的user_id
  6431. * @param int $target_uid 目标的user_id
  6432. * @param int $current_uid 当前用户ID
  6433. * @throws \Exception
  6434. */
  6435. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6436. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6437. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6438. return; // 允许
  6439. }
  6440. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6441. if ($source_uid == 0 && $target_uid == $current_uid) {
  6442. return; // 允许
  6443. }
  6444. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6445. if ($source_uid == 0 && $target_uid == 0) {
  6446. return; // 允许
  6447. }
  6448. // 其他情况都不允许
  6449. if ($source_uid != 0 && $source_uid != $current_uid) {
  6450. // 源是别人的个人库
  6451. Utils::throwError('20003:无权限访问该资产');
  6452. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6453. // 个人库推送给公共库(不允许)
  6454. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6455. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6456. // 不同用户的个人库之间推送(不允许)
  6457. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6458. } else {
  6459. // 其他未知情况
  6460. Utils::throwError('20003:不允许的推送操作');
  6461. }
  6462. }
  6463. /**
  6464. * 复制单个资产
  6465. * @param object $sourceProduct 源资产对象
  6466. * @param int $targetParentId 目标父文件夹ID
  6467. * @param int $targetLevel 目标层级
  6468. * @param int $cpid 公司ID
  6469. * @param int $targetUid 目标用户ID
  6470. * @return int 返回新资产ID
  6471. */
  6472. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6473. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6474. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6475. $newProductData = [
  6476. 'user_id' => $targetUid,
  6477. 'cpid' => $cpid,
  6478. 'type' => 1,
  6479. 'parent_id' => $targetParentId,
  6480. 'level' => $targetLevel,
  6481. 'product_name' => $sourceProduct->product_name,
  6482. 'url' => $sourceProduct->url,
  6483. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6484. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6485. 'product' => $finalProductType,
  6486. 'versions' => $sourceProduct->versions ?? '',
  6487. 'sort_order' => time(),
  6488. 'is_deleted' => 0,
  6489. 'created_at' => date('Y-m-d H:i:s'),
  6490. 'updated_at' => date('Y-m-d H:i:s')
  6491. ];
  6492. return DB::table('mp_products')->insertGetId($newProductData);
  6493. }
  6494. /**
  6495. * 递归复制文件夹及其子项
  6496. * @param object $sourceFolder 源文件夹对象
  6497. * @param int $targetParentId 目标父文件夹ID
  6498. * @param int $targetLevel 目标层级
  6499. * @param int $cpid 公司ID
  6500. * @param int $targetUid 目标用户ID
  6501. * @param int $sourceUid 源用户ID
  6502. * @return int 返回新文件夹ID
  6503. */
  6504. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6505. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6506. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6507. // 创建新文件夹
  6508. $newFolderData = [
  6509. 'user_id' => $targetUid,
  6510. 'cpid' => $cpid,
  6511. 'type' => 2,
  6512. 'parent_id' => $targetParentId,
  6513. 'level' => $targetLevel,
  6514. 'product_name' => $sourceFolder->product_name,
  6515. 'product' => $finalProductType,
  6516. 'sort_order' => time(),
  6517. 'is_deleted' => 0,
  6518. 'created_at' => date('Y-m-d H:i:s'),
  6519. 'updated_at' => date('Y-m-d H:i:s')
  6520. ];
  6521. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6522. // 获取源文件夹下的所有子项
  6523. $children = DB::table('mp_products')
  6524. ->where('parent_id', $sourceFolder->id)
  6525. ->where('cpid', $cpid)
  6526. ->where('user_id', $sourceUid)
  6527. ->where('is_deleted', 0)
  6528. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6529. ->get();
  6530. // 递归复制子项(子项继承目标文件夹的 product 类型)
  6531. foreach ($children as $child) {
  6532. if ($child->type == 1) {
  6533. // 资产
  6534. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  6535. } else {
  6536. // 文件夹
  6537. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  6538. }
  6539. }
  6540. return $newFolderId;
  6541. }
  6542. /**
  6543. * 保存剧本资产关联关系
  6544. * @param array $data 请求参数
  6545. * @return bool
  6546. */
  6547. public function saveScriptProducts($data) {
  6548. $uid = Site::getUid();
  6549. $cpid = Site::getCpid();
  6550. $script_id = getProp($data, 'script_id');
  6551. $products = getProp($data, 'products', []);
  6552. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6553. if (!$script_id) {
  6554. Utils::throwError('20003:请提供剧本ID');
  6555. }
  6556. // 验证剧本是否存在
  6557. $script = DB::table('mp_scripts')
  6558. ->where('id', $script_id)
  6559. ->where('is_deleted', 0)
  6560. ->first();
  6561. if (!$script) {
  6562. Utils::throwError('20003:剧本不存在');
  6563. }
  6564. // 处理图片模型
  6565. $model = getProp($data, 'model');
  6566. if (!$model) {
  6567. // 使用默认模型
  6568. $model = 'doubao-seedream-5-0-lite-260128';
  6569. }
  6570. // 验证模型是否在可用模型表中
  6571. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6572. Utils::throwError('20003:该模型已不可用,请更换!');
  6573. }
  6574. $ratio = getProp($data, 'ratio', '9:16');
  6575. $resolution = getProp($data, 'resolution', '2k');
  6576. // 定义分辨率和宽高比对应的尺寸映射表
  6577. $sizeMap = [
  6578. '2k' => [
  6579. '1:1' => ['width' => 2048, 'height' => 2048],
  6580. '4:3' => ['width' => 2304, 'height' => 1728],
  6581. '3:4' => ['width' => 1728, 'height' => 2304],
  6582. '16:9' => ['width' => 2848, 'height' => 1600],
  6583. '9:16' => ['width' => 1600, 'height' => 2848],
  6584. '3:2' => ['width' => 2496, 'height' => 1664],
  6585. '2:3' => ['width' => 1664, 'height' => 2496],
  6586. '21:9' => ['width' => 3136, 'height' => 1344],
  6587. ],
  6588. '3k' => [
  6589. '1:1' => ['width' => 3072, 'height' => 3072],
  6590. '4:3' => ['width' => 3456, 'height' => 2592],
  6591. '3:4' => ['width' => 2592, 'height' => 3456],
  6592. '16:9' => ['width' => 4096, 'height' => 2304],
  6593. '9:16' => ['width' => 2304, 'height' => 4096],
  6594. '2:3' => ['width' => 2496, 'height' => 3744],
  6595. '3:2' => ['width' => 3744, 'height' => 2496],
  6596. '21:9' => ['width' => 4704, 'height' => 2016],
  6597. ],
  6598. '4k' => [
  6599. '1:1' => ['width' => 4096, 'height' => 4096],
  6600. '3:4' => ['width' => 3520, 'height' => 4704],
  6601. '4:3' => ['width' => 4704, 'height' => 3520],
  6602. '16:9' => ['width' => 5504, 'height' => 3040],
  6603. '9:16' => ['width' => 3040, 'height' => 5504],
  6604. '2:3' => ['width' => 3328, 'height' => 4992],
  6605. '3:2' => ['width' => 4992, 'height' => 3328],
  6606. '21:9' => ['width' => 6240, 'height' => 2656],
  6607. ],
  6608. ];
  6609. // 参数验证
  6610. $resolution = strtolower($resolution);
  6611. if (!isset($sizeMap[$resolution])) {
  6612. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6613. }
  6614. if (!isset($sizeMap[$resolution][$ratio])) {
  6615. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6616. }
  6617. // 根据 ratio 和 resolution 确定宽高
  6618. $width = $sizeMap[$resolution][$ratio]['width'];
  6619. $height = $sizeMap[$resolution][$ratio]['height'];
  6620. $script_name = $script->script_name ?? 'script_' . $script_id;
  6621. // 检查是否已经有该剧本的资产数据
  6622. $existingMappings = DB::table('mp_script_product_mappings')
  6623. ->where('script_id', $script_id)
  6624. ->get();
  6625. if ($existingMappings->isNotEmpty()) {
  6626. // 已存在资产映射,检查是否所有资产都有图片生成任务
  6627. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  6628. // 查询这些资产的图片生成任务状态
  6629. $productsWithTasks = DB::table('mp_products')
  6630. ->whereIn('id', $productIds)
  6631. ->where('is_deleted', 0)
  6632. ->get();
  6633. $productTaskMap = [];
  6634. $typeFolderIds = [];
  6635. $hasAllTasks = true;
  6636. foreach ($productsWithTasks as $product) {
  6637. // 收集类型文件夹ID
  6638. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  6639. $parentFolder = DB::table('mp_products')
  6640. ->where('id', $product->parent_id)
  6641. ->where('type', 2)
  6642. ->first();
  6643. if ($parentFolder) {
  6644. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  6645. }
  6646. }
  6647. // 检查是否有图片生成任务
  6648. if (!empty($product->pic_task_id)) {
  6649. $productTaskMap[$product->id] = $product->pic_task_id;
  6650. } else if($product->url && $product->pic_task_status == '生成成功') {
  6651. continue;
  6652. } else {
  6653. // 有资产没有图片任务
  6654. $hasAllTasks = false;
  6655. }
  6656. }
  6657. // 如果所有资产都有任务ID,直接轮询返回结果
  6658. if ($hasAllTasks && !empty($productTaskMap)) {
  6659. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  6660. 'script_id' => $script_id,
  6661. 'script_name' => $script_name,
  6662. 'product_count' => count($productTaskMap)
  6663. ]);
  6664. // 直接返回 SSE 流轮询结果
  6665. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6666. }
  6667. // 如果部分资产没有任务ID,只为这些资产创建任务
  6668. if (!$hasAllTasks && $auto_generate_images) {
  6669. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  6670. 'script_id' => $script_id,
  6671. 'script_name' => $script_name
  6672. ]);
  6673. // 开启事务
  6674. DB::beginTransaction();
  6675. try {
  6676. foreach ($productsWithTasks as $product) {
  6677. // 跳过已有任务的资产
  6678. if (!empty($product->pic_task_id)) {
  6679. continue;
  6680. }
  6681. // 跳过没有提示词的资产
  6682. if (empty($product->pic_prompt)) {
  6683. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6684. 'product_id' => $product->id,
  6685. 'product_name' => $product->product_name
  6686. ]);
  6687. continue;
  6688. }
  6689. try {
  6690. // 创建图片生成任务
  6691. $params = [
  6692. 'prompt' => $product->pic_prompt,
  6693. 'model' => $model,
  6694. 'ref_img_urls' => [],
  6695. 'width' => $width,
  6696. 'height' => $height
  6697. ];
  6698. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6699. $task_id = $task->id;
  6700. if ($task_id) {
  6701. $productTaskMap[$product->id] = $task_id;
  6702. // 在事务中更新资产表的任务ID和状态
  6703. DB::table('mp_products')
  6704. ->where('id', $product->id)
  6705. ->update([
  6706. 'pic_task_id' => $task_id,
  6707. 'pic_task_status' => '生成中',
  6708. 'updated_at' => now()
  6709. ]);
  6710. dLog('anime')->info('为已存在资产创建图片生成任务', [
  6711. 'product_id' => $product->id,
  6712. 'task_id' => $task_id
  6713. ]);
  6714. }
  6715. } catch (\Exception $e) {
  6716. dLog('anime')->error('创建资产图片生成任务失败', [
  6717. 'product_id' => $product->id,
  6718. 'error' => $e->getMessage()
  6719. ]);
  6720. // 标记为失败(仍在事务中)
  6721. DB::table('mp_products')
  6722. ->where('id', $product->id)
  6723. ->update([
  6724. 'pic_task_status' => '生成失败',
  6725. 'updated_at' => now()
  6726. ]);
  6727. }
  6728. }
  6729. // 提交事务
  6730. DB::commit();
  6731. // 如果有新创建的任务,返回 SSE 流
  6732. if (!empty($productTaskMap)) {
  6733. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6734. }
  6735. } catch (\Exception $e) {
  6736. // 回滚事务
  6737. DB::rollback();
  6738. dLog('anime')->error('为已存在资产创建图片任务失败', [
  6739. 'script_id' => $script_id,
  6740. 'error' => $e->getMessage()
  6741. ]);
  6742. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  6743. }
  6744. }
  6745. // 如果不需要生成图片,返回已存在的信息
  6746. return [
  6747. 'success' => true,
  6748. 'message' => '剧本资产已存在',
  6749. 'script_id' => $script_id,
  6750. 'script_name' => $script_name,
  6751. 'type_folder_ids' => $typeFolderIds,
  6752. 'existing_products' => count($productIds),
  6753. 'tasks_count' => count($productTaskMap)
  6754. ];
  6755. }
  6756. // 解析 products(可能是 JSON 字符串或数组)
  6757. if (is_string($products)) {
  6758. $products = json_decode($products, true);
  6759. if (json_last_error() !== JSON_ERROR_NONE) {
  6760. Utils::throwError('20003:产品数据格式错误');
  6761. }
  6762. }
  6763. if (!is_array($products) || empty($products)) {
  6764. Utils::throwError('20003:产品数据不能为空');
  6765. }
  6766. // 以下是原有的创建逻辑...
  6767. // 开启事务
  6768. DB::beginTransaction();
  6769. try {
  6770. $now = now();
  6771. $mappingRecords = [];
  6772. $createdProductIds = []; // 记录所有创建的资产ID
  6773. // 获取剧本名称
  6774. $script_name = $script->script_name ?? 'script_' . $script_id;
  6775. // 存储每个类型的根文件夹ID
  6776. $typeFolderIds = [];
  6777. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  6778. foreach ($products as $productGroup) {
  6779. $type = getProp($productGroup, 'type');
  6780. $title = getProp($productGroup, 'title', '');
  6781. $content = getProp($productGroup, 'content', []);
  6782. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  6783. continue;
  6784. }
  6785. // 为当前类型创建根文件夹(如果还未创建)
  6786. if (!isset($typeFolderIds[$type])) {
  6787. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  6788. 'user_id' => $uid,
  6789. 'cpid' => $cpid,
  6790. 'type' => 2, // 1.资产 2文件夹
  6791. 'product' => $type, // 1.主体 2.场景 3.道具
  6792. 'parent_id' => 0, // 根文件夹,parent_id=0
  6793. 'level' => 1, // 第一层级
  6794. 'product_name' => $script_name,
  6795. 'sort_order' => time() + $type,
  6796. 'is_deleted' => 0,
  6797. 'created_at' => $now,
  6798. 'updated_at' => $now
  6799. ]);
  6800. }
  6801. $folder_id = $typeFolderIds[$type];
  6802. // 获取表头(第一行)并查找关键列的位置
  6803. $headers = $content[0];
  6804. $nameColumnIndex = -1; // 资产名称列索引
  6805. $sequenceColumnIndex = -1; // 使用范围列索引
  6806. $promptColumnIndex = -1; // 参考提示词列索引
  6807. foreach ($headers as $index => $header) {
  6808. // 查找"资产名称"列
  6809. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  6810. $nameColumnIndex = $index;
  6811. }
  6812. // 查找"使用范围"列
  6813. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  6814. $sequenceColumnIndex = $index;
  6815. }
  6816. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  6817. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  6818. $promptColumnIndex = $index;
  6819. }
  6820. }
  6821. // 验证必要的列是否都找到了
  6822. if ($nameColumnIndex === -1) {
  6823. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  6824. continue;
  6825. }
  6826. if ($sequenceColumnIndex === -1) {
  6827. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  6828. continue;
  6829. }
  6830. // 跳过表头,解析每一行数据
  6831. for ($i = 1; $i < count($content); $i++) {
  6832. $row = $content[$i];
  6833. // 确保行数据有效
  6834. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  6835. continue;
  6836. }
  6837. // 根据动态查找的列索引提取数据
  6838. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  6839. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6840. $pic_prompt = '';
  6841. // 提取参考提示词(如果找到了该列)
  6842. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6843. $pic_prompt = trim($row[$promptColumnIndex]);
  6844. }
  6845. // 解析使用范围(逗号分隔的序号)
  6846. $sequences = [];
  6847. if (!empty($sequence_str)) {
  6848. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  6849. foreach ($sequenceParts as $part) {
  6850. if (is_numeric($part)) {
  6851. $sequences[] = (int)$part;
  6852. }
  6853. }
  6854. }
  6855. if (empty($product_name)) {
  6856. continue;
  6857. }
  6858. // 处理product_name两边的符号
  6859. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6860. // 如果名称不存在则跳过
  6861. if (!$product_name) continue;
  6862. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  6863. $product_id = DB::table('mp_products')->insertGetId([
  6864. 'product_name' => $product_name,
  6865. 'type' => 1, // 1=资产 2.文件夹
  6866. 'product' => $type, // 1=角色, 2=场景, 3=道具
  6867. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  6868. 'level' => 2, // 第二层级
  6869. 'pic_prompt' => $pic_prompt,
  6870. 'user_id' => $uid,
  6871. 'cpid' => $cpid,
  6872. 'sort_order' => time(),
  6873. 'is_deleted' => 0,
  6874. 'created_at' => $now,
  6875. 'updated_at' => $now,
  6876. ]);
  6877. // 记录创建的资产ID
  6878. $createdProductIds[] = $product_id;
  6879. // 为每个序号创建映射记录
  6880. if (!empty($sequences)) {
  6881. foreach ($sequences as $sequence) {
  6882. $mappingRecords[] = [
  6883. 'script_id' => $script_id,
  6884. 'product_id' => $product_id,
  6885. 'episode_number' => $sequence,
  6886. 'created_at' => $now,
  6887. 'updated_at' => $now,
  6888. ];
  6889. }
  6890. } else {
  6891. // 如果没有指定序号,创建一个默认映射(序号为0)
  6892. $mappingRecords[] = [
  6893. 'script_id' => $script_id,
  6894. 'product_id' => $product_id,
  6895. 'episode_number' => 0,
  6896. 'created_at' => $now,
  6897. 'updated_at' => $now,
  6898. ];
  6899. }
  6900. }
  6901. }
  6902. if (empty($mappingRecords)) {
  6903. Utils::throwError('20003:没有有效的产品数据');
  6904. }
  6905. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  6906. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  6907. // 如果需要自动生成图片,在事务中创建图片生成任务
  6908. $productTaskMap = [];
  6909. if ($auto_generate_images && !empty($createdProductIds)) {
  6910. // 查询所有创建的资产
  6911. $productsToGenerate = DB::table('mp_products')
  6912. ->whereIn('id', $createdProductIds)
  6913. ->where('is_deleted', 0)
  6914. ->get();
  6915. foreach ($productsToGenerate as $product) {
  6916. if (empty($product->pic_prompt)) {
  6917. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6918. 'product_id' => $product->id,
  6919. 'product_name' => $product->product_name
  6920. ]);
  6921. continue;
  6922. }
  6923. try {
  6924. // 创建图片生成任务
  6925. $params = [
  6926. 'prompt' => $product->pic_prompt,
  6927. 'model' => $model,
  6928. 'ref_img_urls' => [],
  6929. 'width' => $width,
  6930. 'height' => $height
  6931. ];
  6932. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6933. $task_id = $task->id;
  6934. if ($task_id) {
  6935. $productTaskMap[$product->id] = $task_id;
  6936. // 在事务中更新资产表的任务ID和状态
  6937. DB::table('mp_products')
  6938. ->where('id', $product->id)
  6939. ->update([
  6940. 'pic_task_id' => $task_id,
  6941. 'pic_task_status' => '生成中',
  6942. 'updated_at' => now()
  6943. ]);
  6944. dLog('anime')->info('创建资产图片生成任务', [
  6945. 'product_id' => $product->id,
  6946. 'task_id' => $task_id
  6947. ]);
  6948. }
  6949. } catch (\Exception $e) {
  6950. dLog('anime')->error('创建资产图片生成任务失败', [
  6951. 'product_id' => $product->id,
  6952. 'error' => $e->getMessage()
  6953. ]);
  6954. // 标记为失败(仍在事务中)
  6955. DB::table('mp_products')
  6956. ->where('id', $product->id)
  6957. ->update([
  6958. 'pic_task_status' => '生成失败',
  6959. 'updated_at' => now()
  6960. ]);
  6961. }
  6962. }
  6963. }
  6964. // 提交事务
  6965. DB::commit();
  6966. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6967. if ($auto_generate_images && !empty($productTaskMap)) {
  6968. // 返回 SSE 流(事务外轮询)
  6969. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6970. }
  6971. // 如果不需要生成图片,返回普通结果
  6972. return [
  6973. 'success' => true,
  6974. 'type_folder_ids' => $typeFolderIds,
  6975. 'inserted_count' => $insertedCount,
  6976. 'total_records' => count($mappingRecords),
  6977. 'created_products' => count($createdProductIds),
  6978. 'image_tasks_created' => count($productTaskMap)
  6979. ];
  6980. } catch (\Exception $e) {
  6981. // 回滚事务
  6982. DB::rollback();
  6983. // 记录错误日志
  6984. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6985. 'script_id' => $script_id,
  6986. 'error' => $e->getMessage(),
  6987. 'trace' => $e->getTraceAsString()
  6988. ]);
  6989. // 统一使用 Utils::throwError 抛出错误
  6990. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6991. }
  6992. }
  6993. /**
  6994. * 批量为剧本资产生成图片
  6995. *
  6996. * @param array $data 请求参数
  6997. * @return \Generator 返回 SSE 流
  6998. */
  6999. public function batchGenerateProductImages($data) {
  7000. $script_id = getProp($data, 'script_id');
  7001. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  7002. if (!$script_id) {
  7003. Utils::throwError('20003:请提供剧本ID');
  7004. }
  7005. // 验证剧本是否存在
  7006. $script = DB::table('mp_scripts')
  7007. ->where('id', $script_id)
  7008. ->where('is_deleted', 0)
  7009. ->first();
  7010. if (!$script) {
  7011. Utils::throwError('20003:剧本不存在');
  7012. }
  7013. $script_name = $script->script_name ?? 'script_' . $script_id;
  7014. // 获取需要生成图片的所有资产
  7015. $products = DB::table('mp_products')
  7016. ->whereIn('parent_id', array_values($type_folder_ids))
  7017. ->where('is_deleted', 0)
  7018. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7019. ->get();
  7020. if ($products->isEmpty()) {
  7021. Utils::throwError('20003:没有找到需要生成图片的资产');
  7022. }
  7023. // 默认参数
  7024. $model = 'doubao-seedream-5-0-lite-260128';
  7025. $width = 1600;
  7026. $height = 2848;
  7027. // 开始为每个资产创建图片生成任务
  7028. $taskIds = [];
  7029. $productTaskMap = []; // 资产ID到任务ID的映射
  7030. foreach ($products as $product) {
  7031. if (empty($product->pic_prompt)) {
  7032. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7033. continue;
  7034. }
  7035. try {
  7036. // 创建图片生成任务
  7037. $params = [
  7038. 'prompt' => $product->pic_prompt,
  7039. 'model' => $model,
  7040. 'ref_img_urls' => [],
  7041. 'width' => $width,
  7042. 'height' => $height
  7043. ];
  7044. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7045. $task_id = $task->id;
  7046. if ($task_id) {
  7047. $taskIds[] = $task_id;
  7048. $productTaskMap[$product->id] = $task_id;
  7049. // 更新资产表的任务ID和状态
  7050. DB::table('mp_products')
  7051. ->where('id', $product->id)
  7052. ->update([
  7053. 'pic_task_id' => $task_id,
  7054. 'pic_task_status' => '生成中',
  7055. 'updated_at' => now()
  7056. ]);
  7057. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7058. }
  7059. } catch (\Exception $e) {
  7060. dLog('anime')->error('创建资产图片生成任务失败', [
  7061. 'product_id' => $product->id,
  7062. 'error' => $e->getMessage()
  7063. ]);
  7064. // 标记为失败
  7065. DB::table('mp_products')
  7066. ->where('id', $product->id)
  7067. ->update([
  7068. 'pic_task_status' => '生成失败',
  7069. 'updated_at' => now()
  7070. ]);
  7071. }
  7072. }
  7073. if (empty($taskIds)) {
  7074. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7075. }
  7076. // 返回 SSE 流
  7077. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7078. }
  7079. /**
  7080. * 轮询资产图片生成任务状态(SSE流式返回)
  7081. * 只通过查询数据库获取任务状态,不主动调用API
  7082. *
  7083. * @param int $script_id 剧本ID
  7084. * @param string $script_name 剧本名称
  7085. * @param array $productTaskMap 资产ID到任务ID的映射
  7086. * @param array $type_folder_ids 类型文件夹ID映射
  7087. * @return \Generator
  7088. */
  7089. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  7090. $startTime = time();
  7091. $timeout = 1800; // 30分钟超时
  7092. $pollInterval = 10; // 10秒轮询一次
  7093. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7094. // 定义类型名称映射
  7095. $typeNames = [
  7096. 1 => 'roles', // 角色
  7097. 2 => 'scenes', // 场景
  7098. 3 => 'props' // 道具
  7099. ];
  7100. while (time() - $startTime < $timeout) {
  7101. sleep($pollInterval);
  7102. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7103. $mappings = DB::table('mp_script_product_mappings')
  7104. ->where('script_id', $script_id)
  7105. ->pluck('product_id')
  7106. ->unique()
  7107. ->toArray();
  7108. if (empty($mappings)) {
  7109. dLog('anime')->warning('该剧本没有关联的资产', [
  7110. 'script_id' => $script_id,
  7111. 'script_name' => $script_name
  7112. ]);
  7113. break;
  7114. }
  7115. // 查询所有资产的当前状态
  7116. $products = DB::table('mp_products')
  7117. ->whereIn('id', $mappings)
  7118. ->where('is_deleted', 0)
  7119. ->get();
  7120. // 统计各类型的状态(使用类型名称作为键名)
  7121. $stats = [
  7122. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7123. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7124. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7125. ];
  7126. $allCompleted = true;
  7127. $hasStatusChange = false;
  7128. foreach ($products as $product) {
  7129. $type = $product->product;
  7130. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7131. // 如果类型名称不在 stats 中,初始化
  7132. if (!isset($stats[$typeName])) {
  7133. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7134. }
  7135. $stats[$typeName]['total']++;
  7136. $task_id = $product->pic_task_id;
  7137. $currentStatus = $product->pic_task_status;
  7138. // 检查状态是否有变化
  7139. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7140. $hasStatusChange = true;
  7141. $lastStatus[$product->id] = $currentStatus;
  7142. }
  7143. // 如果是生成中,查询任务表状态
  7144. if ($currentStatus === '生成中' && $task_id) {
  7145. // 只查询数据库,不调用API
  7146. $task = DB::table('mp_generate_pic_tasks')
  7147. ->where('id', $task_id)
  7148. ->first();
  7149. if ($task) {
  7150. // 检查任务状态
  7151. if ($task->status === 'success' && $task->result_url) {
  7152. // 解析图片URL
  7153. $result_urls = $task->result_url;
  7154. if (is_string($result_urls)) {
  7155. $result_urls = json_decode($result_urls, true);
  7156. }
  7157. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7158. // 更新资产表状态
  7159. DB::table('mp_products')
  7160. ->where('id', $product->id)
  7161. ->update([
  7162. 'pic_task_status' => '生成成功',
  7163. 'url' => $img_url,
  7164. 'updated_at' => now()
  7165. ]);
  7166. $stats[$typeName]['success']++;
  7167. $stats[$typeName]['completed']++;
  7168. $hasStatusChange = true;
  7169. dLog('anime')->info('资产图片生成成功', [
  7170. 'product_id' => $product->id,
  7171. 'task_id' => $task_id,
  7172. 'img_url' => $img_url
  7173. ]);
  7174. } elseif ($task->status === 'failed') {
  7175. // 更新资产表状态
  7176. DB::table('mp_products')
  7177. ->where('id', $product->id)
  7178. ->update([
  7179. 'pic_task_status' => '生成失败',
  7180. 'updated_at' => now()
  7181. ]);
  7182. $stats[$typeName]['completed']++;
  7183. $hasStatusChange = true;
  7184. dLog('anime')->warning('资产图片生成失败', [
  7185. 'product_id' => $product->id,
  7186. 'task_id' => $task_id,
  7187. 'error' => $task->error_message ?? '未知错误'
  7188. ]);
  7189. } else {
  7190. // 任务还在处理中
  7191. $allCompleted = false;
  7192. }
  7193. } else {
  7194. // 任务不存在,标记为失败
  7195. DB::table('mp_products')
  7196. ->where('id', $product->id)
  7197. ->update([
  7198. 'pic_task_status' => '生成失败',
  7199. 'updated_at' => now()
  7200. ]);
  7201. $stats[$type]['completed']++;
  7202. $hasStatusChange = true;
  7203. dLog('anime')->error('图片生成任务不存在', [
  7204. 'product_id' => $product->id,
  7205. 'task_id' => $task_id
  7206. ]);
  7207. }
  7208. } elseif ($currentStatus === '生成成功') {
  7209. $stats[$typeName]['success']++;
  7210. $stats[$typeName]['completed']++;
  7211. } elseif ($currentStatus === '生成失败') {
  7212. $stats[$typeName]['completed']++;
  7213. } else {
  7214. // 其他状态也认为未完成
  7215. $allCompleted = false;
  7216. }
  7217. }
  7218. // 移除没有数据的类型(total=0)
  7219. foreach ($stats as $typeName => $stat) {
  7220. if ($stat['total'] === 0) {
  7221. unset($stats[$typeName]);
  7222. }
  7223. }
  7224. // 如果有状态变化,发送 SSE 更新
  7225. if ($hasStatusChange) {
  7226. $eventType = $allCompleted ? 'complete' : 'update';
  7227. $response = [
  7228. 'type' => $eventType,
  7229. 'script_id' => $script_id,
  7230. 'script_name' => $script_name,
  7231. 'stats' => $stats,
  7232. 'timestamp' => date('Y-m-d H:i:s')
  7233. ];
  7234. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7235. dLog('anime')->info('SSE更新', [
  7236. 'event_type' => $eventType,
  7237. 'script_id' => $script_id,
  7238. 'script_name' => $script_name,
  7239. 'stats' => $stats
  7240. ]);
  7241. if ($allCompleted) {
  7242. dLog('anime')->info('所有资产图片生成任务已完成', [
  7243. 'script_id' => $script_id,
  7244. 'script_name' => $script_name,
  7245. 'stats' => $stats
  7246. ]);
  7247. break;
  7248. }
  7249. }
  7250. }
  7251. // 超时处理
  7252. if (time() - $startTime >= $timeout && !$allCompleted) {
  7253. $response = [
  7254. 'type' => 'timeout',
  7255. 'message' => '部分任务超时,请稍后查看结果',
  7256. 'script_id' => $script_id,
  7257. 'script_name' => $script_name,
  7258. 'timestamp' => date('Y-m-d H:i:s')
  7259. ];
  7260. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7261. dLog('anime')->warning('资产图片生成任务超时', [
  7262. 'script_id' => $script_id,
  7263. 'script_name' => $script_name,
  7264. 'timeout' => $timeout
  7265. ]);
  7266. }
  7267. }
  7268. /**
  7269. * 获取剧本关联的资产列表
  7270. * @param array $data 请求参数
  7271. * @return array
  7272. */
  7273. public function getScriptProducts($data) {
  7274. $uid = Site::getUid();
  7275. $cpid = Site::getCpid();
  7276. $script_id = getProp($data, 'script_id');
  7277. $episode_number = getProp($data, 'episode_number');
  7278. if (!$script_id) {
  7279. Utils::throwError('20003:请提供剧本ID');
  7280. }
  7281. // 验证剧本是否存在
  7282. $script = DB::table('mp_scripts')
  7283. ->where('id', $script_id)
  7284. ->where('is_deleted', 0)
  7285. ->first();
  7286. if (!$script) {
  7287. Utils::throwError('20003:剧本不存在');
  7288. }
  7289. // 联表查询资产信息
  7290. $query = DB::table('mp_script_product_mappings as mapping')
  7291. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7292. ->where('mapping.script_id', $script_id)
  7293. ->where('product.cpid', $cpid)
  7294. ->where('product.is_deleted', 0);
  7295. // 如果提供了 episode_number,则过滤指定集数
  7296. if ($episode_number !== null && $episode_number !== '') {
  7297. $query->where('mapping.episode_number', $episode_number);
  7298. }
  7299. $mappings = $query->select(
  7300. 'mapping.script_id',
  7301. 'mapping.product_id',
  7302. 'mapping.episode_number',
  7303. 'product.product_name',
  7304. 'product.type',
  7305. 'product.product',
  7306. 'product.pic_prompt',
  7307. 'product.url',
  7308. 'product.pic_task_id',
  7309. 'product.pic_task_status',
  7310. 'product.three_view_image_url',
  7311. 'mapping.created_at'
  7312. )
  7313. ->orderBy('mapping.product_id', 'asc')
  7314. ->orderBy('mapping.episode_number', 'asc')
  7315. ->get();
  7316. // 按 product_id 分组,合并 episode_number
  7317. $productMap = [];
  7318. foreach ($mappings as $item) {
  7319. $product_id = $item->product_id;
  7320. if (!isset($productMap[$product_id])) {
  7321. $productMap[$product_id] = [
  7322. 'product_id' => $product_id,
  7323. 'product_name' => $item->product_name,
  7324. 'type' => (int)$item->type,
  7325. 'product' => (int)$item->product,
  7326. 'pic_prompt' => $item->pic_prompt,
  7327. 'url' => $item->url,
  7328. 'pic_task_id' => $item->pic_task_id,
  7329. 'pic_task_status' => $item->pic_task_status,
  7330. 'episode_numbers' => [],
  7331. 'created_at' => $item->created_at,
  7332. ];
  7333. }
  7334. // 添加 episode_number(去重)
  7335. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7336. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7337. }
  7338. }
  7339. // 按类型分组
  7340. $roles = []; // type=1 角色/主体
  7341. $scenes = []; // type=2 场景
  7342. $props = []; // type=3 道具
  7343. foreach ($productMap as $product) {
  7344. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7345. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7346. // 构造返回数据
  7347. $productData = [
  7348. 'product_id' => $product['product_id'],
  7349. 'product_name' => $product['product_name'],
  7350. 'product' => $product['product'],
  7351. 'pic_prompt' => $product['pic_prompt'],
  7352. 'url' => $product['url'],
  7353. 'pic_task_id' => $product['pic_task_id'],
  7354. 'pic_task_status' => $product['pic_task_status'],
  7355. 'episode_numbers' => $episodeNumbersStr,
  7356. 'created_at' => $product['created_at'],
  7357. ];
  7358. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7359. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7360. switch ($product['product']) {
  7361. case 1:
  7362. $roles[] = $productData;
  7363. break;
  7364. case 2:
  7365. $scenes[] = $productData;
  7366. break;
  7367. case 3:
  7368. $props[] = $productData;
  7369. break;
  7370. }
  7371. }
  7372. return [
  7373. 'script_id' => $script_id,
  7374. 'script_name' => $script->script_name ?? '',
  7375. 'roles' => $roles, // 主体
  7376. 'scenes' => $scenes, // 场景
  7377. 'props' => $props, // 道具
  7378. ];
  7379. }
  7380. /**
  7381. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7382. * @param string $actContent 原始内容
  7383. * @param array $products 产品数组(包含product_name和url)
  7384. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7385. */
  7386. public function processActContentWithProducts($actContent, $products) {
  7387. if (empty($actContent) || empty($products)) {
  7388. return [
  7389. 'content' => $actContent,
  7390. 'reference_images' => []
  7391. ];
  7392. }
  7393. // 构建产品名称到产品信息的映射
  7394. $product_dict = [];
  7395. foreach ($products as $product) {
  7396. $product_name = getProp($product, 'product_name');
  7397. if ($product_name) {
  7398. $product_dict[$product_name] = [
  7399. 'url' => getProp($product, 'url'),
  7400. 'voice_prompt' => getProp($product, 'voice_prompt')
  7401. ];
  7402. }
  7403. }
  7404. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7405. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7406. $reference_images = [];
  7407. $product_index_map = []; // 产品名称 => 图片序号的映射
  7408. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7409. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7410. $current_index = 1;
  7411. if (!empty($matches[1])) {
  7412. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7413. $seen_products = []; // 用于去重
  7414. foreach ($matches[1] as $product_name) {
  7415. // 跳过已处理的产品
  7416. if (isset($seen_products[$product_name])) {
  7417. continue;
  7418. }
  7419. $seen_products[$product_name] = true;
  7420. // 检查产品是否在字典中
  7421. if (isset($product_dict[$product_name])) {
  7422. $url = $product_dict[$product_name]['url'];
  7423. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7424. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7425. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7426. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7427. }
  7428. // 只有URL非空才分配序号和添加到参考图片
  7429. if (!empty($url)) {
  7430. // 检查URL是否已经在reference_images中(去重)
  7431. if (!in_array($url, $reference_images)) {
  7432. $reference_images[] = $url;
  7433. $product_index_map[$product_name] = $current_index;
  7434. $current_index++;
  7435. } else {
  7436. // URL重复,找到已有的序号
  7437. $existing_index = array_search($url, $reference_images) + 1;
  7438. $product_index_map[$product_name] = $existing_index;
  7439. }
  7440. } else {
  7441. // URL为空,不分配序号(后续直接去掉{})
  7442. $product_index_map[$product_name] = 0;
  7443. }
  7444. } else {
  7445. // 产品不在字典中,不分配序号
  7446. $product_index_map[$product_name] = 0;
  7447. }
  7448. }
  7449. }
  7450. // 第二步:替换内容中的 {产品名称}
  7451. $processedContent = $actContent;
  7452. foreach ($product_index_map as $product_name => $index) {
  7453. $escaped_name = preg_quote($product_name, '/');
  7454. if ($index > 0) {
  7455. // 有图片,替换为:产品名称(图X)
  7456. $replacement = $product_name . '<图片' . $index . '>';
  7457. } else {
  7458. // 无图片,只保留产品名称
  7459. $replacement = $product_name;
  7460. }
  7461. // 替换所有 {产品名称} 为处理后的格式
  7462. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7463. }
  7464. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7465. foreach ($products as $product) {
  7466. $product_name = getProp($product, 'product_name');
  7467. $voice_prompt = getProp($product, 'voice_prompt');
  7468. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7469. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7470. break; // 找到旁白后退出循环
  7471. }
  7472. }
  7473. // 第四步:将voice_prompt信息添加到内容最前面
  7474. $voice_prompt_prefix = '';
  7475. if (!empty($voice_prompts)) {
  7476. $voice_prompt_prefix .= implode('', $voice_prompts);
  7477. }
  7478. // 旁白的voice_prompt放在最后
  7479. if (!empty($narrator_voice_prompt)) {
  7480. $voice_prompt_prefix .= $narrator_voice_prompt;
  7481. }
  7482. // 如果有voice_prompt信息,添加到内容开头
  7483. if (!empty($voice_prompt_prefix)) {
  7484. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7485. }
  7486. return [
  7487. 'content' => $processedContent,
  7488. 'reference_images' => $reference_images
  7489. ];
  7490. }
  7491. public function saveActVideoGenerateParams($data) {
  7492. $episode_id = getProp($data, 'episode_id');
  7493. $model = getProp($data, 'video_model');
  7494. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7495. Utils::throwError('20003:该模型不可用');
  7496. }
  7497. if (!$model) {
  7498. // 使用默认模型
  7499. $model = 'zhizhen-20';
  7500. }
  7501. // 验证模型是否在可用模型表中
  7502. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7503. Utils::throwError('20003:该模型已不可用,请更换!');
  7504. }
  7505. $video_resolution = getProp($data, 'video_resolution', '720p');
  7506. $ratio = getProp($data, 'ratio');
  7507. if (!$ratio) $ratio = '9:16';
  7508. return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7509. 'video_model' => $model,
  7510. 'video_resolution' => $video_resolution,
  7511. 'ratio' => $ratio,
  7512. 'updated_at' => date('Y-m-d H:i:s')
  7513. ]);
  7514. }
  7515. public function confirmActs($data) {
  7516. $episode_id = getProp($data, 'episode_id');
  7517. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7518. if (!$episode) {
  7519. Utils::throwError('20003:分集不存在');
  7520. }
  7521. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7522. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7523. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  7524. // 获取所有片段数据
  7525. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7526. // 收集所有资产名称(角色、场景、道具)
  7527. $product_names = [];
  7528. // 收集角色名称
  7529. foreach ($roles as $role) {
  7530. $role_name = getProp($role, 'role');
  7531. if ($role_name && $role_name != '旁白') {
  7532. $product_names[] = $role_name;
  7533. }
  7534. }
  7535. // 收集场景名称
  7536. foreach ($scenes as $scene) {
  7537. $scene_name = getProp($scene, 'scene');
  7538. if ($scene_name) {
  7539. $product_names[] = $scene_name;
  7540. }
  7541. }
  7542. // 收集道具名称
  7543. foreach ($props as $prop) {
  7544. $prop_name = getProp($prop, 'prop');
  7545. if ($prop_name) {
  7546. $product_names[] = $prop_name;
  7547. }
  7548. }
  7549. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  7550. $product_names = array_unique($product_names);
  7551. usort($product_names, function($a, $b) {
  7552. return mb_strlen($b) - mb_strlen($a);
  7553. });
  7554. try {
  7555. DB::beginTransaction();
  7556. // 处理每个片段
  7557. foreach ($acts as $act) {
  7558. $act_content = getProp($act, 'act_content');
  7559. if (!$act_content) continue;
  7560. $processed_content = $act_content;
  7561. // 统一替换所有资产名称为 {资产名} 格式
  7562. // 使用占位符避免嵌套替换问题
  7563. $placeholder_map = [];
  7564. $placeholder_index = 0;
  7565. foreach ($product_names as $product_name) {
  7566. // 转义特殊字符
  7567. $escaped_product = preg_quote($product_name, '/');
  7568. // 检查是否匹配且未被 {} 包裹
  7569. $processed_content = preg_replace_callback(
  7570. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  7571. function($matches) use (&$placeholder_map, &$placeholder_index) {
  7572. // 使用唯一占位符
  7573. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  7574. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  7575. $placeholder_index++;
  7576. return $placeholder;
  7577. },
  7578. $processed_content
  7579. );
  7580. }
  7581. // 将所有占位符替换回实际内容
  7582. foreach ($placeholder_map as $placeholder => $replacement) {
  7583. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  7584. }
  7585. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7586. $shot_counter = 0;
  7587. $processed_content = preg_replace_callback(
  7588. '/【(?:镜头|分镜)(\d+)】/u',
  7589. function($matches) use (&$shot_counter) {
  7590. $shot_counter++;
  7591. return '【镜头' . $shot_counter . '】';
  7592. },
  7593. $processed_content
  7594. );
  7595. // 更新数据库
  7596. $boolen = DB::table('mp_episode_segments')
  7597. ->where('id', $act->id)
  7598. ->update([
  7599. 'act_show_content' => $processed_content,
  7600. 'updated_at' => date('Y-m-d H:i:s')
  7601. ]);
  7602. if (!$boolen) {
  7603. Utils::throwError('20003:片段处理失败');
  7604. }
  7605. }
  7606. }catch (\Exception $e) {
  7607. DB::rollBack();
  7608. Utils::throwError('20003:'.$e->getMessage());
  7609. }
  7610. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7611. 'is_generated' => 1,
  7612. 'updated_at' => date('Y-m-d H:i:s')
  7613. ]);
  7614. if (!$boolen1) {
  7615. DB::rollBack();
  7616. Utils::throwError('20003:分集处理失败!');
  7617. }
  7618. DB::commit();
  7619. // 重新查询更新后的片段数据
  7620. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7621. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  7622. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  7623. $products = [];
  7624. // 先处理角色数组
  7625. foreach ($roles as $role) {
  7626. $product = $role;
  7627. // 将role字段重命名为product_name
  7628. if (isset($product['role'])) {
  7629. $product['product_name'] = $product['role'];
  7630. unset($product['role']);
  7631. $product['product'] = 1; // 标记类型为角色
  7632. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7633. }
  7634. }
  7635. // 处理场景数组
  7636. foreach ($scenes as $scene) {
  7637. $product = $scene;
  7638. // 将scene字段重命名为product_name
  7639. if (isset($product['scene'])) {
  7640. $product['product_name'] = $product['scene'];
  7641. unset($product['scene']);
  7642. $product['product'] = 2; // 标记类型为场景
  7643. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7644. }
  7645. }
  7646. // 处理道具数组(逻辑与场景一致)
  7647. foreach ($props as $prop) {
  7648. $product = $prop;
  7649. // 将prop字段重命名为product_name
  7650. if (isset($product['prop'])) {
  7651. $product['product_name'] = $product['prop'];
  7652. unset($product['prop']);
  7653. $product['product'] = 3; // 标记类型为道具
  7654. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7655. }
  7656. }
  7657. // extra_products优先级更高,直接覆盖同名的roles和scenes
  7658. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  7659. foreach ($extra_products as $extra_product) {
  7660. $product_name = getProp($extra_product, 'product_name');
  7661. if ($product_name) {
  7662. $products[$product_name] = $extra_product; // 覆盖同名数据
  7663. }
  7664. }
  7665. // 重新索引数组(去除key)
  7666. $products = array_values($products);
  7667. // 构建返回的acts数组
  7668. $return_acts = [];
  7669. foreach ($acts as $act) {
  7670. $return_acts[] = [
  7671. 'act_id' => getProp($act, 'id'),
  7672. 'act_number' => getProp($act, 'act_number'),
  7673. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  7674. 'act_show_content' => getProp($act, 'act_show_content'),
  7675. 'video_url' => getProp($act, 'video_url'),
  7676. 'video_duration' => getProp($act, 'video_duration'),
  7677. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  7678. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  7679. ];
  7680. }
  7681. return [
  7682. 'anime_id' => getProp($episode, 'anime_id'),
  7683. 'episode_id' => $episode_id,
  7684. 'title' => getProp($episode, 'title'),
  7685. 'episode_number' => getProp($episode, 'episode_number'),
  7686. 'is_generated' => getProp($episode, 'is_generated'),
  7687. 'products' => $products,
  7688. 'acts' => $return_acts
  7689. ];
  7690. }
  7691. }