AnimeService.php 325 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Services\AIGeneration\AIImageGenerationService;
  9. use App\Services\AIGeneration\AIVideoGenerationService;
  10. use App\Services\DeepSeek\DeepSeekService;
  11. use Dflydev\DotAccessData\Util;
  12. use GuzzleHttp\Client;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. use OSS\Core\OssException;
  17. use OSS\OssClient;
  18. class AnimeService
  19. {
  20. protected $aiImageGenerationService;
  21. protected $aiVideoGenerationService;
  22. protected $DeepSeekService;
  23. private $url;
  24. private $api_key;
  25. private $headers;
  26. public function __construct(
  27. AIImageGenerationService $aiImageGenerationService,
  28. AIVideoGenerationService $aiVideoGenerationService,
  29. DeepSeekService $DeepSeekService
  30. ) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->aiVideoGenerationService = $aiVideoGenerationService;
  33. $this->DeepSeekService = $DeepSeekService;
  34. $this->url = 'https://api.deepseek.com/chat/completions';
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. }
  41. /**
  42. * 构建统一的分镜数据结构(episodeInfo格式)
  43. * @param array $segments 分镜数据数组
  44. * @return array 返回包含acts和total_duration的数组
  45. */
  46. public function buildEpisodeSegmentsStructure($segments) {
  47. $acts = [];
  48. $totalDuration = 0; // 初始化总时长
  49. foreach($segments as $segment) {
  50. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  51. $videoDuration = getProp($segment, 'video_duration');
  52. $audioDuration = getProp($segment, 'audio_duration');
  53. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  54. $totalDuration += floatval($videoDuration);
  55. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  56. $totalDuration += floatval($audioDuration);
  57. } else {
  58. $totalDuration += 5; // 默认5秒
  59. }
  60. $segment_content = getProp($segment, 'segment_content');
  61. // 判断是否有尾帧描述,如果有则去掉这部分内容
  62. if (strpos($segment_content, '尾帧') !== false) {
  63. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  64. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  65. }
  66. // 构建分镜信息
  67. $segmentInfo = [
  68. 'segment_id' => getProp($segment, 'segment_id'),
  69. 'segment_number' => getProp($segment, 'segment_number'),
  70. 'segment_content' => $segment_content,
  71. 'description' => getProp($segment, 'description'),
  72. 'composition' => getProp($segment, 'composition'),
  73. 'camera_movement' => getProp($segment, 'camera_movement'),
  74. 'voice_actor' => getProp($segment, 'voice_actor'),
  75. 'dialogue' => getProp($segment, 'dialogue'),
  76. 'frame_type' => getProp($segment, 'frame_type'),
  77. 'scene' => getProp($segment, 'scene'),
  78. 'characters' => getProp($segment, 'characters'),
  79. 'tail_frame' => getProp($segment, 'tail_frame'),
  80. 'emotion' => getProp($segment, 'emotion'),
  81. 'emotion_type' => getProp($segment, 'emotion_type'),
  82. 'gender' => getProp($segment, 'gender'),
  83. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  84. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  85. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  86. 'pitch' => getProp($segment, 'pitch'),
  87. 'voice_name' => getProp($segment, 'voice_name'),
  88. 'voice_type' => getProp($segment, 'voice_type'),
  89. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  90. 'img_url' => getProp($segment, 'img_url'),
  91. 'audio_url' => getProp($segment, 'audio_url'),
  92. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  93. 'video_url' => getProp($segment, 'video_url'),
  94. 'video_duration' => getProp($segment, 'video_duration', 0),
  95. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  96. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  97. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  98. 'current_type' => getProp($segment, 'current_type'),
  99. ];
  100. $actNumber = getProp($segment, 'act_number');
  101. if (isset($acts[$actNumber])) {
  102. $acts[$actNumber]['segments'][] = $segmentInfo;
  103. } else {
  104. $acts[$actNumber] = [
  105. 'act_number' => $actNumber,
  106. 'act_title' => getProp($segment, 'act_title'),
  107. 'act_duration' => getProp($segment, 'act_duration'),
  108. 'segments' => [$segmentInfo]
  109. ];
  110. }
  111. }
  112. return [
  113. 'acts' => array_values($acts),
  114. 'total_duration' => intval(round($totalDuration))
  115. ];
  116. }
  117. /**
  118. * 构建统一的分段数据结构(episodeInfoForAce格式)
  119. * @param array $segments 分段数据数组
  120. * @return array 返回包含acts和total_duration的数组
  121. */
  122. public function buildEpisodeActsStructureForAce($segments) {
  123. $acts = [];
  124. $totalDuration = 0; // 初始化总时长
  125. foreach($segments as $segment) {
  126. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  127. $videoDuration = getProp($segment, 'video_duration');
  128. $actDuration = getProp($segment, 'act_duration');
  129. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  130. $totalDuration += floatval($videoDuration);
  131. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  132. $totalDuration += floatval($actDuration);
  133. } else {
  134. $totalDuration += 5; // 默认5秒
  135. }
  136. // 构建分镜信息
  137. $segmentInfo = [
  138. 'act_id' => getProp($segment, 'id'),
  139. 'act_number' => getProp($segment, 'act_number'),
  140. 'act_title' => getProp($segment, 'act_title'),
  141. 'act_duration' => getProp($segment, 'act_duration'),
  142. 'act_content' => getProp($segment, 'act_content'),
  143. 'video_url' => getProp($segment, 'video_url'),
  144. 'video_duration' => getProp($segment, 'video_duration', 0),
  145. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  146. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  147. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  148. 'current_type' => getProp($segment, 'current_type'),
  149. ];
  150. $acts[] = $segmentInfo;
  151. }
  152. return [
  153. 'acts' => array_values($acts),
  154. 'total_duration' => intval(round($totalDuration))
  155. ];
  156. }
  157. /**
  158. * 验证画面比例是否有效
  159. * @param string $ratio 画面比例
  160. * @return bool
  161. */
  162. public function validateRatio($ratio) {
  163. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  164. }
  165. /**
  166. * 获取画面比例对应的宽高
  167. * @param string $ratio 画面比例
  168. * @return array ['width' => int, 'height' => int]
  169. * @throws \Exception
  170. */
  171. private function getRatioDimensions($ratio) {
  172. if ($ratio && !$this->validateRatio($ratio)) {
  173. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  174. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  175. }
  176. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  177. }
  178. public function createAnime($data) {
  179. $uid = Site::getUid();
  180. $input_art_style = getProp($data, 'art_style');
  181. $file = getProp($data, 'file');
  182. $content = getProp($data, 'content', '');
  183. $bid = getProp($data, 'bid', 0);
  184. $script_id = getProp($data, 'script_id', 0);
  185. $ace_mode = getProp($data, 'ace_mode', 0);
  186. $extra_products = getProp($data, 'products', []);
  187. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  188. if (!is_array($extra_products)) {
  189. Utils::throwError('20003:传入的资产格式不正确');
  190. }
  191. // 替换美术风格
  192. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  193. // 提取文件内容
  194. if ($file) {
  195. $content = $this->DeepSeekService->extractFileContent($file);
  196. if (!$content) {
  197. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  198. }
  199. } elseif ($script_id) {
  200. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  201. if (!$content) {
  202. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  203. }
  204. } elseif ($bid) {
  205. $content = $this->DeepSeekService->getContentByBid($bid);
  206. if (!$content) {
  207. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  208. }
  209. } elseif ($content) {
  210. $content = filterContent($content);
  211. }else {
  212. $content = '';
  213. }
  214. $anime_data = [
  215. 'user_id' => $uid,
  216. 'anime_name' => '新剧本策划',
  217. 'is_multi' => getProp($data, 'is_multi', 1),
  218. 'content' => $content,
  219. 'art_style_type' => $input_art_style,
  220. 'ace_mode' => $ace_mode,
  221. 'script_id' => $script_id,
  222. 'extra_products' => json_encode($extra_products, 256),
  223. 'created_at' => date('Y-m-d H:i:s'),
  224. 'updated_at' => date('Y-m-d H:i:s'),
  225. ];
  226. // 处理文本模型
  227. $model = getProp($data, 'model');
  228. if (!$model) {
  229. // 用户没有输入,使用默认值
  230. $model = 'doubao-seed-2-0-mini-260215';
  231. }
  232. // 验证模型是否在可用模型表中
  233. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  234. $model = 'doubao-seed-2-0-mini-260215';
  235. }
  236. $anime_data['model'] = $model;
  237. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  238. return DB::table('mp_animes')->insertGetId($anime_data);
  239. }
  240. public function chatList($data) {
  241. $uid = Site::getUid();
  242. $anime_name = getProp($data, 'anime_name');
  243. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  244. if ($anime_name) {
  245. $query->where('anime_name', 'like', "%$anime_name%");
  246. }
  247. return $query->orderBy('id', 'desc')->paginate();
  248. }
  249. public function chatHistory($data) {
  250. $anime_id = getProp($data, 'anime_id');
  251. $sequence = getProp($data, 'sequence', 0);
  252. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  253. $query = DB::table('mp_anime_records as ar')->leftJoin('mp_anime_episodes as ae', 'ar.episode_id', '=', 'ae.id')->where('ar.anime_id', $anime_id)
  254. ->where('ar.sequence', $sequence)->where('segment_id', 0)->where('act_id', 0)->select('ar.role', 'ar.content', 'ar.created_at', 'ar.episode_id', 'ae.title as episode_title', 'ae.created_at as episode_created_at');
  255. return $query->orderBy('ar.id')->get()->map(function ($value) {
  256. $value = (array)$value;
  257. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  258. $value['created_at'] = transDate($value['created_at']);
  259. $value['episode_created_at'] = transDate($value['episode_created_at']);
  260. return $value;
  261. })->toArray();
  262. }
  263. public function batchSetRoleImg($data) {
  264. $episode_id = getProp($data, 'episode_id');
  265. if (!$episode_id) Utils::throwError('1002:请选择分集');
  266. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  267. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  268. $art_style = getProp($episode, 'art_style');
  269. $anime_id = getProp($episode, 'anime_id');
  270. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  271. $art_style_type = getProp($anime, 'art_style_type');
  272. $character_prefix = '';
  273. $scene_prefix = '';
  274. if ($art_style_type) {
  275. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  276. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  277. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  278. }
  279. foreach ($roles as &$role) {
  280. $role_name = getProp($role, 'role');
  281. if ($role_name == '旁白') continue;
  282. // 优先使用 pic_prompt,如果没有则使用 description
  283. $pic_prompt = getProp($role, 'pic_prompt');
  284. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  285. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  286. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  287. // 参考图地址
  288. $ref_img_url = getProp($role, 'url');
  289. if ($ref_img_url) continue; // 已有图片则跳过
  290. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  291. try {
  292. $params = [
  293. 'prompt' => $description,
  294. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  295. ];
  296. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  297. $task_id = $task->id;
  298. if (!$task_id) {
  299. Utils::throwError("20003:角色({$role_name})生成图片失败");
  300. }
  301. $role['task_id'] = $task_id;
  302. $role['task_status'] = 'processing';
  303. } catch (\Exception $e) {
  304. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  305. Utils::throwError("20003:" . $e->getMessage());
  306. }
  307. }
  308. // 保存角色信息
  309. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  310. 'roles' => json_encode($roles, 256),
  311. 'generate_status' => '执行中',
  312. 'generate_at' => date('Y-m-d H:i:s'),
  313. 'updated_at' => date('Y-m-d H:i:s')
  314. ]);
  315. if (!$boolen) {
  316. Utils::throwError('20003:保存角色信息失败');
  317. }
  318. return $boolen;
  319. }
  320. public function batchSetSceneImg($data) {
  321. $episode_id = getProp($data, 'episode_id');
  322. if (!$episode_id) Utils::throwError('1002:请选择分集');
  323. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  324. $scenes = json_decode(getProp($episode, 'scenes'), true);
  325. $art_style = getProp($episode, 'art_style');
  326. $target_scene = getProp($data, 'target_scene');
  327. $anime_id = getProp($episode, 'anime_id');
  328. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  329. $art_style_type = getProp($anime, 'art_style_type');
  330. $character_prefix = '';
  331. $scene_prefix = '';
  332. if ($art_style_type) {
  333. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  334. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  335. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  336. }
  337. foreach ($scenes as &$scene) {
  338. $scene_name = getProp($scene, 'scene');
  339. if ($scene_name != $target_scene) continue;
  340. // 优先使用 pic_prompt,如果没有则使用 description
  341. $pic_prompt = getProp($scene, 'pic_prompt');
  342. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  343. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  344. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  345. // 参考图地址
  346. $ref_img_url = getProp($scene, 'url');
  347. if ($ref_img_url) continue; // 已有图片则跳过
  348. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  349. try {
  350. $params = [
  351. 'prompt' => $description,
  352. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  353. ];
  354. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  355. $task_id = $task->id;
  356. if (!$task_id) {
  357. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  358. }
  359. $scene['task_id'] = $task_id;
  360. $scene['task_status'] = 'processing';
  361. } catch (\Exception $e) {
  362. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  363. Utils::throwError("20003:" . $e->getMessage());
  364. }
  365. }
  366. // 保存场景信息
  367. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  368. 'scenes' => json_encode($scenes, 256),
  369. 'generate_status' => '执行中',
  370. 'generate_at' => date('Y-m-d H:i:s'),
  371. 'updated_at' => date('Y-m-d H:i:s')
  372. ]);
  373. if (!$boolen) {
  374. Utils::throwError('20003:保存角色信息失败');
  375. }
  376. return $boolen;
  377. }
  378. public function editAnime($data) {
  379. $anime_id = getProp($data, 'anime_id');
  380. $anime_name = trim(getProp($data, 'anime_name'));
  381. // 确认对话名称唯一性
  382. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  383. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  384. }
  385. if (!$anime_id || !$anime_name) {
  386. Utils::throwError('20003:参数异常');
  387. }
  388. return DB::table('mp_animes')->where('id', $anime_id)->update([
  389. 'anime_name' => $anime_name,
  390. 'updated_at' => date('Y-m-d H:i:s')
  391. ]);
  392. // $script_arr =getProp($data, 'script', []);
  393. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  394. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  395. // $anime_id = getProp($data, 'anime_id');
  396. // try {
  397. // DB::beginTransaction();
  398. // $table_data = [
  399. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  400. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  401. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  402. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  403. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  404. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  405. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  406. // 'status' => 3,
  407. // 'start_episode_sequence' => $start_episode_sequence,
  408. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  409. // 'episode_num' => count($script_arr['episodes']),
  410. // 'updated_at' => date('Y-m-d H:i:s')
  411. // ];
  412. // // 保存剧本内容
  413. // if (!empty($anime_id)) {
  414. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  415. // if (!$boolen) {
  416. // dLog('anime')->info('对话保存失败', $table_data);
  417. // Utils::throwError('20003:对话保存失败');
  418. // }
  419. // }else {
  420. // $table['created_at'] = $table_data['updated_at'];
  421. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  422. // if (!$anime_id) {
  423. // dLog('anime')->info('对话保存失败', $table_data);
  424. // Utils::throwError('20003:对话保存失败');
  425. // }
  426. // }
  427. // // 保存分集内容
  428. // // 删除历史分集内容
  429. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  430. // $episodes = [];
  431. // $sequence = 1;
  432. // foreach ($script_arr['episodes'] as $episode) {
  433. // $segment_number = 1;
  434. // foreach($episode['segments'] as $segment) {
  435. // $episodes[] = [
  436. // 'anime_id' => $anime_id,
  437. // 'episode_number' => $episode['episode_number'],
  438. // 'title' => $episode['title'],
  439. // // 'content' => $episode['content'],
  440. // 'content' => '',
  441. // 'segment_number' => $segment_number,
  442. // 'segment_content' => $segment['segment_content'],
  443. // 'sequence' => $sequence,
  444. // 'created_at' => date('Y-m-d H:i:s'),
  445. // 'updated_at' => date('Y-m-d H:i:s')
  446. // ];
  447. // $sequence++;
  448. // $segment_number++;
  449. // }
  450. // }
  451. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  452. // if (!$boolen2) {
  453. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  454. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  455. // Utils::throwError('20003:分集内容保存失败');
  456. // }
  457. // } catch (\Exception $e) {
  458. // DB::rollBack();
  459. // Utils::throwError('20003:'.$e->getMessage());
  460. // }
  461. // DB::commit();
  462. // return true;
  463. }
  464. public function delAnime($data) {
  465. $anime_id = getProp($data, 'anime_id');
  466. if (!$anime_id) {
  467. Utils::throwError('20003:请选择剧本');
  468. }
  469. return DB::table('mp_animes')->where('id', $anime_id)->update([
  470. 'is_deleted' => 1,
  471. 'updated_at' => date('Y-m-d H:i:s')
  472. ]);
  473. }
  474. public function animeDetail($data) {
  475. $uid = Site::getUid();
  476. $anime_id = getProp($data, 'anime_id');
  477. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  478. ->selectRaw('id as anime_id, anime_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, remark, generate_status, created_at, ace_mode')->first();
  479. if (!$anime) Utils::throwError('20003:权限不足');
  480. $anime = (array)$anime;
  481. $anime['roles'] = json_decode($anime['roles']);
  482. $anime['scenes'] = json_decode($anime['scenes']);
  483. // 获取分集信息
  484. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  485. ->select('id as episode_id', 'episode_number', 'title', 'is_generated', DB::raw("(select es.img_url from mp_episode_segments as es where es.episode_id = mp_anime_episodes.id order by es.segment_number limit 1) as first_frame_url"))
  486. ->orderBy('episode_number')->get()->map(function ($value) {
  487. return (array)$value;
  488. })->toArray();
  489. $anime['episodes'] = $episodes;
  490. return $anime;
  491. }
  492. public function episodeInfo($data) {
  493. $uid = Site::getUid();
  494. $anime_id = getProp($data, 'anime_id');
  495. $episode_id = getProp($data, 'episode_id');
  496. if (!$anime_id || !$episode_id) {
  497. Utils::throwError('1002:请选择剧集');
  498. }
  499. // 验证用户权限
  500. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  501. if (!$anime) Utils::throwError('20003:权限不足');
  502. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->first();
  503. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  504. $episode = (array)$episode;
  505. $episode['roles'] = json_decode($episode['roles'], true);
  506. // foreach($episode['roles'] as &$item) {
  507. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  508. // }
  509. $episode['scenes'] = json_decode($episode['scenes'], true);
  510. // foreach($episode['scenes'] as &$item) {
  511. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  512. // }
  513. // 获取分镜信息
  514. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  515. ->select('*')->get()->map(function ($value) {
  516. return (array)$value;
  517. })->toArray();
  518. // 使用公共方法构建分镜结构
  519. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  520. $episode['acts'] = $segmentsStructure['acts'];
  521. $episode['total_duration'] = $segmentsStructure['total_duration'];
  522. return $episode;
  523. }
  524. public function episodeInfoForAce($data) {
  525. $anime_id = getProp($data, 'anime_id');
  526. $episode_id = getProp($data, 'episode_id');
  527. if (!$anime_id || !$episode_id) {
  528. Utils::throwError('1002:请选择剧集');
  529. }
  530. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->first();
  531. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  532. $episode = (array)$episode;
  533. $episode['roles'] = json_decode($episode['roles'], true);
  534. // foreach($episode['roles'] as &$item) {
  535. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  536. // }
  537. $episode['scenes'] = json_decode($episode['scenes'], true);
  538. // foreach($episode['scenes'] as &$item) {
  539. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  540. // }
  541. // 获取分镜信息
  542. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  543. ->select('*')->get()->map(function ($value) {
  544. return (array)$value;
  545. })->toArray();
  546. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  547. $episode['acts'] = $segmentsStructure['acts'];
  548. $episode['total_duration'] = $segmentsStructure['total_duration'];
  549. return $episode;
  550. }
  551. public function segmentInfo($data) {
  552. $uid = Site::getUid();
  553. $segment_id = getProp($data, 'segment_id');
  554. if (!$segment_id) {
  555. Utils::throwError('1002:请选择分镜');
  556. }
  557. // 获取分镜信息
  558. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  559. // 验证用户权限
  560. if ($segment) {
  561. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  562. if (!$anime) Utils::throwError('20003:权限不足');
  563. }
  564. $result = [
  565. 'segment_id' => getProp($segment, 'segment_id'),
  566. 'segment_number' => getProp($segment, 'segment_number'),
  567. 'segment_content' => getProp($segment, 'segment_content'),
  568. 'description' => getProp($segment, 'description'),
  569. 'composition' => getProp($segment, 'composition'),
  570. 'camera_movement' => getProp($segment, 'camera_movement'),
  571. 'voice_actor' => getProp($segment, 'voice_actor'),
  572. 'dialogue' => getProp($segment, 'dialogue'),
  573. 'frame_type' => getProp($segment, 'frame_type'),
  574. 'scene' => getProp($segment, 'scene'),
  575. 'characters' => getProp($segment, 'characters'),
  576. 'tail_frame' => getProp($segment, 'tail_frame'),
  577. 'emotion' => getProp($segment, 'emotion'),
  578. 'emotion_type' => getProp($segment, 'emotion_type'),
  579. 'gender' => getProp($segment, 'gender'),
  580. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  581. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  582. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  583. 'pitch' => getProp($segment, 'pitch'),
  584. 'voice_name' => getProp($segment, 'voice_name'),
  585. 'voice_type' => getProp($segment, 'voice_type'),
  586. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  587. 'img_url' => getProp($segment, 'img_url'),
  588. 'video_url' => getProp($segment, 'video_url'),
  589. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  590. ];
  591. return $result;
  592. }
  593. public function copyEpisodeVersion($data) {
  594. $episode_id = getProp($data, 'episode_id');
  595. $uid = Site::getUid();
  596. $cpid = Site::getCpid();
  597. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  598. if (!$episode) Utils::throwError('20003:该剧集不存在');
  599. $episode = (array)$episode;
  600. $anime_id = $episode['anime_id'];
  601. $episode_number = $episode['episode_number'];
  602. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  603. $sequence = $count + 1;
  604. unset($episode['id']);
  605. $now = date('Y-m-d H:i:s');
  606. $episode['created_at'] = $now;
  607. $episode['updated_at'] = $now;
  608. $episode['is_default'] = 1;
  609. // 获取版本中含有"(副本"字样的个数
  610. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  611. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  612. $episode['sequence'] = $sequence;
  613. $episode['is_generated'] = 0;
  614. $episode['cpid'] = $cpid;
  615. // 获取ace_mode
  616. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  617. try {
  618. DB::beginTransaction();
  619. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  620. // 新增副本
  621. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  622. if (!$new_episode_id) {
  623. Utils::throwError('20003:创建副本失败!');
  624. }
  625. // 获取分镜数据并准备插入
  626. $segments_for_insert = DB::table('mp_episode_segments')
  627. ->select('anime_id', 'episode_number', 'act_number', 'act_title', 'act_duration', 'act_content', 'segment_number', 'segment_content', 'description', 'composition', 'camera_movement', 'voice_actor', 'dialogue', 'frame_type', 'scene', 'characters', 'tail_frame', 'voice_name', 'voice_type', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  628. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  629. $item = (array)$item;
  630. $item['episode_id'] = $new_episode_id;
  631. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  632. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  633. return $item;
  634. })->toArray();
  635. // 写入分镜数据
  636. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  637. if (!$boolen2) {
  638. Utils::throwError('20003:写入分镜数据失败!');
  639. }
  640. // 写入对话历史
  641. $records = [
  642. [
  643. 'uid' => $uid,
  644. 'anime_id' => $anime_id,
  645. 'role' => 'user',
  646. 'content' => '创建副本',
  647. 'sequence' => $episode_number,
  648. 'episode_id' => $new_episode_id,
  649. 'created_at' => $now,
  650. 'updated_at' => $now
  651. ],
  652. [
  653. 'uid' => $uid,
  654. 'anime_id' => $anime_id,
  655. 'role' => 'assistant',
  656. 'content' => '好的,已为您创建副本',
  657. 'sequence' => $episode_number,
  658. 'episode_id' => $new_episode_id,
  659. 'created_at' => $now,
  660. 'updated_at' => $now
  661. ]
  662. ];
  663. $boolen3 = DB::table('mp_anime_records')->insert($records);
  664. if (!$boolen3) {
  665. Utils::throwError('20003:对话记录保存失败');
  666. }
  667. }catch (\Exception $e) {
  668. DB::rollBack();
  669. Utils::throwError('20003:'.$e->getMessage());
  670. }
  671. DB::commit();
  672. // 构建与 episodeInfo 方法一致的返回数据结构
  673. $result = [
  674. 'episode_id' => $new_episode_id,
  675. 'anime_id' => $anime_id,
  676. 'episode_number' => $episode_number,
  677. 'title' => $episode['title'],
  678. 'intro' => $episode['intro'],
  679. 'art_style' => $episode['art_style'],
  680. 'roles' => json_decode($episode['roles'], true),
  681. 'scenes' => json_decode($episode['scenes'], true),
  682. 'is_generated' => (int)$episode['is_generated']
  683. ];
  684. if ((int)$ace_mode === 1) {
  685. // 获取分镜信息
  686. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  687. ->select('*')->get()->map(function ($value) {
  688. return (array)$value;
  689. })->toArray();
  690. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  691. }else {
  692. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  693. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  694. }
  695. $result['acts'] = $segmentsStructure['acts'];
  696. $result['total_duration'] = $segmentsStructure['total_duration'];
  697. return $result;
  698. }
  699. public function episodeVersions($data) {
  700. $anime_id = getProp($data, 'anime_id');
  701. $episode_id = getProp($data, 'episode_id');
  702. if (!$anime_id || !$episode_id) {
  703. Utils::throwError('1002:请选择剧集');
  704. }
  705. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  706. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->select('id as episode_id', 'anime_id', 'episode_number', 'sequence', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->orderBy('sequence', 'desc')->get()->map(function($value) {
  707. return (array)$value;
  708. })->toArray();
  709. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  710. foreach($episodes as &$episode) {
  711. $episode['version'] = 'V'.$episode['sequence'];
  712. $episode['roles'] = json_decode($episode['roles'], true);
  713. $episode['scenes'] = json_decode($episode['scenes'], true);
  714. // 获取分镜信息
  715. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  716. ->select('*')->get()->map(function ($value) {
  717. return (array)$value;
  718. })->toArray();
  719. // 使用公共方法构建分镜结构
  720. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  721. $episode['acts'] = $segmentsStructure['acts'];
  722. $episode['total_duration'] = $segmentsStructure['total_duration'];
  723. }
  724. return $episodes;
  725. }
  726. public function bindEpisodeVersion($data) {
  727. $episode_id = getProp($data, 'episode_id');
  728. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  729. if (!$episode) Utils::throwError('20003:该剧集不存在');
  730. $episode = (array)$episode;
  731. if ((int)$episode['is_default'] === 1) return true;
  732. try {
  733. DB::beginTransaction();
  734. // 移除is_default标志
  735. $boolen = DB::table('mp_anime_episodes')->where('anime_id', $episode['anime_id'])->where('episode_number', $episode['episode_number'])->update(['is_default' => 0, 'updated_at'=>date('Y-m-d H:i:s')]);
  736. if (!$boolen) {
  737. Utils::throwError('20003:更新失败!');
  738. }
  739. // 绑定副本
  740. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  741. if (!$boolen2) {
  742. Utils::throwError('20003:绑定失败!');
  743. }
  744. }catch (\Exception $e) {
  745. DB::rollBack();
  746. Utils::throwError('20003:'.$e->getMessage());
  747. }
  748. DB::commit();
  749. return true;
  750. }
  751. public function chatChangeImg($data) {
  752. $segment_id = getProp($data, 'segment_id');
  753. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  754. $prompt = getProp($data, 'prompt');
  755. if (!$prompt || !$segment_id) {
  756. Utils::throwError('1002:请输入提示词,并且选择分镜');
  757. }
  758. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  759. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  760. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  761. else $ref_img_url = '';
  762. // $ref_img_url = '';
  763. if (empty($prompt)) {
  764. if (empty($ref_img_url)) {
  765. $prompt = getProp($segment, 'segment_content');
  766. }else {
  767. $prompt = '请根据图片生成';
  768. }
  769. }
  770. $anime_id = getProp($segment, 'anime_id');
  771. $episode_id = getProp($segment, 'episode_id');
  772. $episode_number = getProp($segment, 'episode_number');
  773. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  774. $ratio = getProp($data, 'ratio');
  775. if (!$ratio) {
  776. $ratio = getProp($episode, 'ratio');
  777. if (!$ratio) $ratio = '9:16';
  778. }
  779. $art_style = getProp($episode, 'art_style');
  780. if ($art_style) {
  781. $prompt = "美术风格:{$art_style}\n{$prompt}";
  782. }
  783. $dimensions = $this->getRatioDimensions($ratio);
  784. $width = $dimensions['width'];
  785. $height = $dimensions['height'];
  786. try {
  787. $params = [
  788. 'alias_segment_id' => $segment_id,
  789. 'prompt' => $prompt,
  790. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  791. 'width' => $width,
  792. 'height' => $height
  793. ];
  794. // 优化提示词(不要生成字幕)
  795. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  796. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  797. $task_id = $task->id;
  798. if (!$task_id) {
  799. Utils::throwError("20003:生成图片失败");
  800. }
  801. // 更新任务ID
  802. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update(['pic_task_id' => $task_id, 'pic_task_status' => '生成中', 'updated_at' => date('Y-m-d H:i:s')]);
  803. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  804. } catch (\Exception $e) {
  805. Utils::throwError("20003:" . $e->getMessage());
  806. }
  807. // 创建任务之后先暂停10s等待异步任务完成
  808. sleep(10);
  809. $img_url = $this->loopGetPicTaskResult($task_id);
  810. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  811. // 图片生成后新增对话记录
  812. try {
  813. $uid = Site::getUid();
  814. $now = date('Y-m-d H:i:s');
  815. // 使用AI反推图片提示词
  816. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  817. // 保存对话记录
  818. $records = [
  819. [
  820. 'uid' => $uid,
  821. 'anime_id' => $anime_id,
  822. 'sequence' => $episode_number,
  823. 'role' => 'user',
  824. 'content' => $prompt,
  825. 'segment_id' => $segment_id,
  826. 'image_url' => '',
  827. 'created_at' => $now,
  828. 'updated_at' => $now
  829. ],
  830. [
  831. 'uid' => $uid,
  832. 'anime_id' => $anime_id,
  833. 'sequence' => $episode_number,
  834. 'role' => 'assistant',
  835. 'content' => $pic_prompt,
  836. 'segment_id' => $segment_id,
  837. 'image_url' => $img_url,
  838. 'created_at' => $now,
  839. 'updated_at' => $now
  840. ]
  841. ];
  842. DB::table('mp_anime_records')->insert($records);
  843. } catch (\Exception $e) {
  844. // 记录日志但不影响主流程
  845. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  846. 'segment_id' => $segment_id,
  847. 'img_url' => $img_url
  848. ]);
  849. logDB('anime', 'error', '保存对话记录失败', [
  850. 'segment_id' => $segment_id,
  851. 'img_url' => $img_url,
  852. 'error' => $e->getMessage()
  853. ]);
  854. }
  855. return $img_url;
  856. }
  857. public function segmentChatHistory($data) {
  858. $segment_id = getProp($data, 'segment_id');
  859. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  860. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
  861. $chat = $query->orderBy('id')->get()->map(function ($value) {
  862. $value = (array)$value;
  863. $value['created_at'] = transDate($value['created_at']);
  864. return $value;
  865. })->toArray();
  866. // 获取历史图片
  867. $url = [];
  868. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  869. foreach($pic_history as $task) {
  870. $result_url = getProp($task, 'result_url');
  871. if (is_json($result_url)) {
  872. $url = array_merge($url, json_decode($result_url, true));
  873. }else {
  874. $url[] = $result_url;
  875. }
  876. }
  877. // 获取历史视频
  878. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  879. foreach($video_history as $task) {
  880. $result_url = getProp($task, 'compressed_url');
  881. if (is_json($result_url)) {
  882. $url = array_merge($url, json_decode($result_url, true));
  883. }else {
  884. $url[] = $result_url;
  885. }
  886. }
  887. return compact('chat', 'url');
  888. }
  889. public function changeEpisodeRoles($data) {
  890. $anime_id = getProp($data, 'anime_id');
  891. $episode_id = getProp($data, 'episode_id');
  892. $target_roles = getProp($data, 'roles');
  893. $is_deleted = getProp($data, 'is_deleted', 0);
  894. // 参数验证
  895. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  896. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  897. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  898. // 验证剧集是否存在
  899. $episode = DB::table('mp_anime_episodes')
  900. ->where('anime_id', $anime_id)
  901. ->where('id', $episode_id)
  902. ->first();
  903. if (!$episode) Utils::throwError('20003:该剧集不存在');
  904. $roles = json_decode(getProp($episode, 'roles'), true);
  905. try {
  906. $target_role_name = getProp($target_roles, 'role');
  907. // 如果是删除操作
  908. if ($is_deleted == 1) {
  909. // 从角色列表中移除该角色
  910. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  911. return getProp($role, 'role') !== $target_role_name;
  912. }));
  913. // 更新角色列表
  914. $result = DB::table('mp_anime_episodes')
  915. ->where('anime_id', $anime_id)
  916. ->where('id', $episode_id)
  917. ->update([
  918. 'roles' => json_encode($roles, 256),
  919. 'updated_at' => date('Y-m-d H:i:s')
  920. ]);
  921. if ($result === false) {
  922. Utils::throwError('20003:删除角色失败');
  923. }
  924. } else {
  925. // 新增或更新操作
  926. $role_found = false;
  927. // 查找并更新已存在的角色
  928. foreach($roles as &$role) {
  929. if (getProp($role, 'role') === $target_role_name) {
  930. $role = $target_roles;
  931. $role_found = true;
  932. break;
  933. }
  934. }
  935. // 如果角色不存在,则新增
  936. if (!$role_found) {
  937. $roles[] = $target_roles;
  938. }
  939. // 更新角色列表
  940. $result = DB::table('mp_anime_episodes')
  941. ->where('anime_id', $anime_id)
  942. ->where('id', $episode_id)
  943. ->update([
  944. 'roles' => json_encode($roles, 256),
  945. 'updated_at' => date('Y-m-d H:i:s')
  946. ]);
  947. if ($result === false) {
  948. Utils::throwError('20003:更新角色列表失败');
  949. }
  950. // 同步更新分镜表中对应主体的音色信息
  951. $voice_name = getProp($target_roles, 'voice_name');
  952. $voice_type = getProp($target_roles, 'voice_type');
  953. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  954. DB::table('mp_episode_segments')
  955. ->where('anime_id', $anime_id)
  956. ->where('episode_id', $episode_id)
  957. ->where('voice_actor', $target_role_name)
  958. ->update([
  959. 'voice_name' => $voice_name,
  960. 'voice_type' => $voice_type,
  961. 'voice_audio_url' => $voice_audio_url,
  962. 'updated_at' => date('Y-m-d H:i:s')
  963. ]);
  964. }
  965. } catch (\Exception $e) {
  966. dLog('anime')->error('更新剧集角色失败', [
  967. 'anime_id' => $anime_id,
  968. 'episode_id' => $episode_id,
  969. 'error' => $e->getMessage()
  970. ]);
  971. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  972. }
  973. return true;
  974. }
  975. public function changeEpisodeScenes($data) {
  976. $anime_id = getProp($data, 'anime_id');
  977. $episode_id = getProp($data, 'episode_id');
  978. $target_scenes = getProp($data, 'scenes');
  979. $is_deleted = getProp($data, 'is_deleted', 0);
  980. // 参数验证
  981. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  982. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  983. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  984. // 验证剧集是否存在
  985. $episode = DB::table('mp_anime_episodes')
  986. ->where('anime_id', $anime_id)
  987. ->where('id', $episode_id)
  988. ->first();
  989. if (!$episode) Utils::throwError('20003:该剧集不存在');
  990. $scenes = json_decode(getProp($episode, 'scenes'), true);
  991. try {
  992. $target_scene_name = getProp($target_scenes, 'scene');
  993. // 如果是删除操作
  994. if ($is_deleted == 1) {
  995. // 从场景列表中移除该场景
  996. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  997. return getProp($scene, 'scene') !== $target_scene_name;
  998. }));
  999. // 更新场景列表
  1000. $result = DB::table('mp_anime_episodes')
  1001. ->where('anime_id', $anime_id)
  1002. ->where('id', $episode_id)
  1003. ->update([
  1004. 'scenes' => json_encode($scenes, 256),
  1005. 'updated_at' => date('Y-m-d H:i:s')
  1006. ]);
  1007. if ($result === false) {
  1008. Utils::throwError('20003:删除场景失败');
  1009. }
  1010. } else {
  1011. // 新增或更新操作
  1012. $scene_found = false;
  1013. // 查找并更新已存在的场景
  1014. foreach($scenes as &$scene) {
  1015. if (getProp($scene, 'scene') === $target_scene_name) {
  1016. $scene = $target_scenes;
  1017. $scene_found = true;
  1018. break;
  1019. }
  1020. }
  1021. // 如果场景不存在,则新增
  1022. if (!$scene_found) {
  1023. $scenes[] = $target_scenes;
  1024. }
  1025. // 更新场景列表
  1026. $result = DB::table('mp_anime_episodes')
  1027. ->where('anime_id', $anime_id)
  1028. ->where('id', $episode_id)
  1029. ->update([
  1030. 'scenes' => json_encode($scenes, 256),
  1031. 'updated_at' => date('Y-m-d H:i:s')
  1032. ]);
  1033. if ($result === false) {
  1034. Utils::throwError('20003:更新场景列表失败');
  1035. }
  1036. }
  1037. } catch (\Exception $e) {
  1038. dLog('anime')->error('更新剧集场景失败', [
  1039. 'anime_id' => $anime_id,
  1040. 'episode_id' => $episode_id,
  1041. 'error' => $e->getMessage()
  1042. ]);
  1043. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1044. }
  1045. return true;
  1046. }
  1047. public function editSegment($data) {
  1048. $segment_id = getProp($data, 'segment_id');
  1049. $segment_content = getProp($data, 'segment_content');
  1050. $image_url = getProp($data, 'image_url');
  1051. $video_url = getProp($data, 'video_url');
  1052. // 参数验证
  1053. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1054. // 验证分镜是否存在
  1055. $segment = DB::table('mp_episode_segments')
  1056. ->where('segment_id', $segment_id)
  1057. ->first();
  1058. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1059. $dubTaskId = 0;
  1060. try {
  1061. DB::beginTransaction();
  1062. // 准备更新数据
  1063. $update_data = [
  1064. 'updated_at' => date('Y-m-d H:i:s')
  1065. ];
  1066. if ($segment_content) {
  1067. // 先将segment_content赋值到update_data
  1068. $update_data['segment_content'] = $segment_content;
  1069. // 使用现有方法分析segment_content,提取各个字段
  1070. $this->handleSegmentContent($update_data);
  1071. // 如果有对话内容,创建视频配音合成任务
  1072. $dialogue = getProp($update_data, 'dialogue');
  1073. if (!empty($dialogue)) {
  1074. $now = date('Y-m-d H:i:s');
  1075. $generate_json = [
  1076. 'text' => $dialogue,
  1077. 'role' => getProp($update_data, 'voice_actor'),
  1078. 'voice_type' => getProp($update_data, 'voice_type'),
  1079. 'voice_name' => getProp($update_data, 'voice_name'),
  1080. 'emotion' => getProp($update_data, 'emotion'),
  1081. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1082. 'gender' => getProp($update_data, 'gender'),
  1083. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1084. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1085. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1086. 'pitch' => getProp($update_data, 'pitch', 0),
  1087. ];
  1088. // 插入视频配音合成任务
  1089. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1090. 'alias_segment_id' => $segment_id,
  1091. 'generate_status' => '执行中',
  1092. 'audio_url' => '',
  1093. 'generate_json' => json_encode($generate_json, 256),
  1094. 'created_at' => $now,
  1095. 'updated_at' => $now,
  1096. ]);
  1097. if (!$dubTaskId) {
  1098. Utils::throwError('20003:创建配音任务失败!');
  1099. }
  1100. $update_data['audio_url'] = '';
  1101. } else {
  1102. // dialogue为空时,直接写入默认音频信息
  1103. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1104. $update_data['audio_duration'] = 2.0;
  1105. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1106. }
  1107. }
  1108. if ($image_url) {
  1109. $update_data['img_url'] = $image_url;
  1110. // 同时写入一个简单的图片生成任务
  1111. $pic_task = [
  1112. 'alias_segment_id' => $segment_id,
  1113. 'ref_img_url' => json_encode([]),
  1114. 'status' => 'success',
  1115. 'result_url' => json_encode([$image_url], 256),
  1116. 'model' => '',
  1117. 'created_at' => date('Y-m-d H:i:s'),
  1118. 'updated_at' => date('Y-m-d H:i:s'),
  1119. ];
  1120. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1121. }
  1122. if ($video_url) {
  1123. $update_data['origin_video_url'] = $video_url;
  1124. $compressed_video_url = compressVideo($video_url);
  1125. $update_data['current_type'] = 2;
  1126. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1127. // 同时写入一个简单的视频生成任务
  1128. $video_task = [
  1129. 'alias_segment_id' => $segment_id,
  1130. 'status' => 'success',
  1131. 'result_url' => $update_data['origin_video_url'],
  1132. 'compressed_url' => $update_data['video_url'],
  1133. 'created_at' => date('Y-m-d H:i:s'),
  1134. 'updated_at' => date('Y-m-d H:i:s'),
  1135. ];
  1136. DB::table('mp_generate_video_tasks')->insert($video_task);
  1137. }
  1138. // 更新分镜信息
  1139. $result = DB::table('mp_episode_segments')
  1140. ->where('segment_id', $segment_id)
  1141. ->update($update_data);
  1142. if ($result === false) {
  1143. Utils::throwError('20003:更新分镜剧本失败');
  1144. }
  1145. DB::commit();
  1146. // 如果有创建音频生成任务则调用API
  1147. if ($dubTaskId) {
  1148. // 请求远程服务器执行生成
  1149. $client = new Client(['timeout' => 300, 'verify' => false]);
  1150. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1151. $response = $result->getBody()->getContents();
  1152. $response_arr = json_decode($response, true);
  1153. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1154. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1155. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1156. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1157. Utils::throwError('20003:火山生成音频失败');
  1158. }
  1159. }
  1160. return true;
  1161. } catch (\Exception $e) {
  1162. DB::rollBack();
  1163. dLog('anime')->error('更新分镜剧本失败', [
  1164. 'segment_id' => $segment_id,
  1165. 'error' => $e->getMessage()
  1166. ]);
  1167. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1168. }
  1169. }
  1170. public function batchSetSegmentPics($data) {
  1171. $anime_id = getProp($data, 'anime_id');
  1172. $episode_id = getProp($data, 'episode_id');
  1173. $ratio = getProp($data, 'ratio');
  1174. $dimensions = $this->getRatioDimensions($ratio);
  1175. $width = $dimensions['width'];
  1176. $height = $dimensions['height'];
  1177. if (!$anime_id || !$episode_id) {
  1178. Utils::throwError('1002:请选择剧集');
  1179. }
  1180. // 获取剧集信息
  1181. $episode = DB::table('mp_anime_episodes')
  1182. ->where('anime_id', $anime_id)
  1183. ->where('id', $episode_id)
  1184. ->where('is_default', 1)
  1185. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1186. ->first();
  1187. if (!$episode) {
  1188. Utils::throwError('20003:该剧集不存在');
  1189. }
  1190. $model = getProp($data, 'model');
  1191. if (!$model) {
  1192. $model = getProp($episode, 'image_model');
  1193. if (!$model) {
  1194. // episode表也没有,使用默认值
  1195. $model = 'doubao-seedream-5-0-lite-260128';
  1196. }
  1197. }
  1198. // 验证模型是否在可用模型表中
  1199. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1200. $model = 'doubao-seedream-5-0-lite-260128';
  1201. }
  1202. $roles = json_decode(getProp($episode, 'roles'), true);
  1203. if (!$roles) {
  1204. Utils::throwError('20003:角色信息格式错误');
  1205. }
  1206. // 构建角色名称到参考图的映射
  1207. $role_map = [];
  1208. foreach ($roles as $role) {
  1209. $role_name = getProp($role, 'role');
  1210. $role_url = getProp($role, 'url');
  1211. if (!empty($role_name) && !empty($role_url)) {
  1212. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1213. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1214. // $role_map[$base_name] = $role_url;
  1215. // 同时保存完整名称的映射
  1216. $role_map[$role_name] = $role_url;
  1217. }
  1218. }
  1219. $scenes = json_decode(getProp($episode, 'roles'), true);
  1220. if (!$scenes) {
  1221. Utils::throwError('20003:场景信息格式错误');
  1222. }
  1223. // 构建角色名称到参考图的映射
  1224. $scene_map = [];
  1225. foreach ($scenes as $scene) {
  1226. $scene_name = getProp($scene, 'scene');
  1227. $scene_url = getProp($scene, 'url');
  1228. if (!empty($scene_name) && !empty($scene_url)) {
  1229. $scene_map[$scene_name] = $scene_url;
  1230. }
  1231. }
  1232. // 获取所有分镜信息
  1233. $segments = DB::table('mp_episode_segments')
  1234. ->where('anime_id', $anime_id)
  1235. ->where('episode_id', $episode_id)
  1236. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1237. ->orderBy('segment_number')
  1238. ->get()
  1239. ->toArray();
  1240. if (empty($segments)) {
  1241. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1242. }
  1243. // 保存图片比例
  1244. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1245. $updated_segments = [];
  1246. $failed_segments = [];
  1247. // 批量为每个分镜生成图片任务
  1248. foreach ($segments as $segment) {
  1249. $segment_id = $segment->segment_id;
  1250. $segment_content = $segment->segment_content;
  1251. if (empty($segment_content)) {
  1252. $failed_segments[] = [
  1253. 'segment_id' => $segment_id,
  1254. 'error' => '分镜内容为空'
  1255. ];
  1256. continue;
  1257. }
  1258. try {
  1259. $dubTaskId = 0;
  1260. // 解析分镜内容,提取画面描述作为主要提示词
  1261. $prompt = $segment_content;
  1262. $ref_img_urls = [];
  1263. // 分镜场景
  1264. $scene = getProp($segment, 'scene');
  1265. $matched_scene = '';
  1266. if (isset($scene_map[$scene])) {
  1267. $img_index = count($ref_img_urls) + 1;
  1268. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1269. $ref_img_urls[] = $scene_map[$scene];
  1270. $matched_scene = $scene;
  1271. }
  1272. // 分镜角色
  1273. $characters = getProp($segment, 'characters');
  1274. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1275. $roles = explode(',', $characters);
  1276. // 从分镜内容中提取涉及的角色
  1277. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1278. // 获取匹配角色的参考图
  1279. foreach ($segment_characters as $character) {
  1280. if (isset($role_map[$character])) {
  1281. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1282. $img_index = count($ref_img_urls) + 1;
  1283. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1284. $ref_img_urls[] = $role_map[$character];
  1285. }
  1286. }
  1287. // 如果没有找到匹配的角色参考图,不使用参考图
  1288. if (empty($ref_img_urls)) {
  1289. $ref_img_urls = [];
  1290. }
  1291. // 准备生成任务参数
  1292. $params = [
  1293. 'model' => $model,
  1294. 'alias_segment_id' => $segment_id,
  1295. 'prompt' => $prompt,
  1296. 'ref_img_urls' => $ref_img_urls,
  1297. 'width' => $width,
  1298. 'height' => $height,
  1299. ];
  1300. // 优化提示词(不要生成字幕)
  1301. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1302. // $task_id = mt_rand(100000, 999999);
  1303. // 调用AI图片生成服务
  1304. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1305. $task_id = $task->id;
  1306. if (!$task_id) {
  1307. $failed_segments[] = [
  1308. 'segment_id' => $segment_id,
  1309. 'error' => '创建生成任务失败'
  1310. ];
  1311. continue;
  1312. }
  1313. $update_data = [
  1314. 'pic_task_id' => $task_id,
  1315. 'pic_task_status' => '生成中',
  1316. 'audio_url' => '',
  1317. 'updated_at' => date('Y-m-d H:i:s')
  1318. ];
  1319. // 如果有对话内容,创建视频配音合成任务
  1320. $dialogue = getProp($segment, 'dialogue');
  1321. if (!empty($dialogue)) {
  1322. $now = date('Y-m-d H:i:s');
  1323. $generate_json = [
  1324. 'text' => $dialogue,
  1325. 'role' => getProp($segment, 'voice_actor'),
  1326. 'voice_type' => getProp($segment, 'voice_type'),
  1327. 'voice_name' => getProp($segment, 'voice_name'),
  1328. 'emotion' => getProp($segment, 'emotion'),
  1329. 'emotion_type' => getProp($segment, 'emotion_type'),
  1330. 'gender' => getProp($segment, 'gender'),
  1331. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1332. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1333. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1334. 'pitch' => getProp($segment, 'pitch', 0),
  1335. ];
  1336. // 插入视频配音合成任务
  1337. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1338. 'alias_segment_id' => $segment_id,
  1339. 'generate_status' => '执行中',
  1340. 'audio_url' => '',
  1341. 'generate_json' => json_encode($generate_json, 256),
  1342. 'created_at' => $now,
  1343. 'updated_at' => $now,
  1344. ]);
  1345. if (!$dubTaskId) {
  1346. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1347. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1348. // Utils::throwError('20003:创建配音任务失败!');
  1349. }
  1350. } else {
  1351. // dialogue为空时,直接写入默认音频信息到分镜表
  1352. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1353. $update_data['audio_duration'] = 2.0;
  1354. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1355. }
  1356. // 更新分镜的任务信息
  1357. $update_result = DB::table('mp_episode_segments')
  1358. ->where('segment_id', $segment_id)
  1359. ->update($update_data);
  1360. // 如果是第一集的首帧图片,则存入待更新数组
  1361. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1362. Redis::sadd('anime_first_frame_urls', $segment_id);
  1363. }
  1364. if ($update_result) {
  1365. $updated_segments[] = [
  1366. 'segment_id' => $segment_id,
  1367. 'task_id' => $task_id,
  1368. 'status' => '生成中',
  1369. 'matched_scenes' => $matched_scene,
  1370. 'matched_roles' => $segment_characters,
  1371. 'ref_urls_count' => count($ref_img_urls)
  1372. ];
  1373. } else {
  1374. $failed_segments[] = [
  1375. 'segment_id' => $segment_id,
  1376. 'error' => '更新分镜任务状态失败'
  1377. ];
  1378. }
  1379. if ($dubTaskId) {
  1380. sleep(1);
  1381. // 请求远程服务器执行生成
  1382. $client = new Client(['timeout' => 300, 'verify' => false]);
  1383. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1384. $response = $result->getBody()->getContents();
  1385. $response_arr = json_decode($response, true);
  1386. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1387. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1388. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1389. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1390. }
  1391. }
  1392. } catch (\Exception $e) {
  1393. $failed_segments[] = [
  1394. 'segment_id' => $segment_id,
  1395. 'error' => $e->getMessage()
  1396. ];
  1397. }
  1398. }
  1399. // 更新剧集生成状态
  1400. if (!empty($updated_segments)) {
  1401. DB::table('mp_anime_episodes')
  1402. ->where('id', $episode_id)
  1403. ->update([
  1404. 'is_generated' => 1,
  1405. 'updated_at' => date('Y-m-d H:i:s')
  1406. ]);
  1407. }
  1408. return [
  1409. 'success_count' => count($updated_segments),
  1410. 'failed_count' => count($failed_segments),
  1411. 'success_segments' => $updated_segments,
  1412. 'failed_segments' => $failed_segments,
  1413. 'total_segments' => count($segments)
  1414. ];
  1415. }
  1416. public function reGenerateSegment($data) {
  1417. $segment_id = getProp($data, 'segment_id');
  1418. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1419. $anime_id = getProp($segment, 'anime_id');
  1420. $episode_id = getProp($segment, 'episode_id');
  1421. $episode_number = getProp($segment, 'episode_number');
  1422. $segment_content = getProp($data, 'segment_content');
  1423. $ratio = getProp($data, 'ratio');
  1424. if (!$ratio) {
  1425. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1426. if (!$ratio) $ratio = '9:16';
  1427. }
  1428. $dimensions = $this->getRatioDimensions($ratio);
  1429. $width = $dimensions['width'];
  1430. $height = $dimensions['height'];
  1431. if (!$anime_id || !$episode_id) {
  1432. Utils::throwError('1002:请选择分镜');
  1433. }
  1434. // 使用文生文模型重新解析segment_content
  1435. if (!empty($segment_content)) {
  1436. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1437. }
  1438. // 获取动漫的角色信息(包含参考图)
  1439. $anime = DB::table('mp_animes')
  1440. ->where('id', $anime_id)
  1441. ->select('roles', 'scenes')
  1442. ->first();
  1443. if (!$anime || !$anime->roles) {
  1444. Utils::throwError('20003:未找到角色信息');
  1445. }
  1446. $roles = json_decode($anime->roles, true);
  1447. if (!$roles) {
  1448. Utils::throwError('20003:角色信息格式错误');
  1449. }
  1450. // 构建角色名称到参考图的映射
  1451. $role_map = [];
  1452. foreach ($roles as $role) {
  1453. $role_name = getProp($role, 'role');
  1454. $role_url = getProp($role, 'url');
  1455. if (!empty($role_name) && !empty($role_url)) {
  1456. $role_map[$role_name] = $role_url;
  1457. }
  1458. }
  1459. $scenes = json_decode($anime->scenes, true);
  1460. if (!$scenes) {
  1461. Utils::throwError('20003:角色信息格式错误');
  1462. }
  1463. // 构建角色名称到参考图的映射
  1464. $scene_map = [];
  1465. foreach ($scenes as $scene) {
  1466. $scene_name = getProp($scene, 'scene');
  1467. $scene_url = getProp($scene, 'url');
  1468. if (!empty($scene_name) && !empty($scene_url)) {
  1469. $scene_map[$scene_name] = $scene_url;
  1470. }
  1471. }
  1472. $segment_id = $segment->segment_id;
  1473. $original_segment_content = $segment->segment_content;
  1474. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1475. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1476. if (empty($final_segment_content)) {
  1477. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1478. }
  1479. try {
  1480. $dubTaskId = 0;
  1481. // 分镜剧本数组
  1482. $update_data = [
  1483. 'segment_content' => $final_segment_content,
  1484. 'pic_task_status' => '生成中',
  1485. 'updated_at' => date('Y-m-d H:i:s')
  1486. ];
  1487. // 解析分镜内容,提取画面描述作为主要提示词
  1488. $prompt = $final_segment_content;
  1489. $ref_img_urls = [];
  1490. // 分镜场景
  1491. $scene = getProp($data, 'scene');
  1492. if ($scene) {
  1493. $matched_scene = '';
  1494. if (isset($scene_map[$scene])) {
  1495. $img_index = count($ref_img_urls) + 1;
  1496. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1497. $ref_img_urls[] = $scene_map[$scene];
  1498. $matched_scene = $scene;
  1499. }
  1500. $update_data['scene'] = $scene;
  1501. }
  1502. // 分镜角色
  1503. $characters = getProp($data, 'characters');
  1504. if ($characters) {
  1505. $update_data['characters'] = $characters;
  1506. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1507. $characters = explode(',', $characters);
  1508. // 从分镜内容中提取涉及的角色
  1509. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1510. // 获取匹配角色的参考图
  1511. foreach ($segment_characters as $character) {
  1512. if (isset($role_map[$character])) {
  1513. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1514. $img_index = count($ref_img_urls) + 1;
  1515. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1516. $ref_img_urls[] = $role_map[$character];
  1517. }
  1518. }
  1519. }
  1520. // 如果没有找到匹配的角色参考图,不使用参考图
  1521. if (empty($ref_img_urls)) {
  1522. $ref_img_urls = [];
  1523. }
  1524. // 准备生成任务参数
  1525. $params = [
  1526. 'alias_segment_id' => $segment_id,
  1527. 'prompt' => $prompt,
  1528. 'ref_img_urls' => $ref_img_urls,
  1529. 'width' => $width,
  1530. 'height' => $height,
  1531. ];
  1532. // 优化提示词(不要生成字幕)
  1533. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1534. // 调用AI图片生成服务
  1535. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1536. $task_id = $task->id;
  1537. if (!$task_id) {
  1538. Utils::throwError('20003:创建生成任务失败!');
  1539. }
  1540. $update_data['pic_task_id'] = $task_id;
  1541. // 更新分镜剧本信息
  1542. $this->handleSegmentContent($update_data);
  1543. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1544. if ($segment_content) {
  1545. $dialogue = getProp($update_data, 'dialogue');
  1546. if (!empty($dialogue)) {
  1547. $now = date('Y-m-d H:i:s');
  1548. $generate_json = [
  1549. 'text' => $dialogue,
  1550. 'role' => getProp($update_data, 'voice_actor'),
  1551. 'voice_type' => getProp($update_data, 'voice_type'),
  1552. 'voice_name' => getProp($update_data, 'voice_name'),
  1553. 'emotion' => getProp($update_data, 'emotion'),
  1554. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1555. 'gender' => getProp($update_data, 'gender'),
  1556. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1557. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1558. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1559. 'pitch' => getProp($update_data, 'pitch', 0),
  1560. ];
  1561. // 插入视频配音合成任务
  1562. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1563. 'alias_segment_id' => $segment_id,
  1564. 'generate_status' => '执行中',
  1565. 'audio_url' => '',
  1566. 'generate_json' => json_encode($generate_json, 256),
  1567. 'created_at' => date('Y-m-d H:i:s'),
  1568. 'updated_at' => date('Y-m-d H:i:s'),
  1569. ]);
  1570. if (!$dubTaskId) {
  1571. Utils::throwError('20003:创建配音任务失败!');
  1572. }
  1573. $update_data['audio_url'] = '';
  1574. } else {
  1575. // dialogue为空时,直接写入默认音频信息
  1576. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1577. $update_data['audio_duration'] = 2.0;
  1578. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1579. }
  1580. }
  1581. $boolen = DB::table('mp_episode_segments')
  1582. ->where('segment_id', $segment_id)
  1583. ->update($update_data);
  1584. // 如果是第一集的首帧图片,则存入待更新数组
  1585. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1586. Redis::sadd('anime_first_frame_urls', $segment_id);
  1587. }
  1588. if ($dubTaskId) {
  1589. // 请求远程服务器执行生成
  1590. $client = new Client(['timeout' => 300, 'verify' => false]);
  1591. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1592. $response = $result->getBody()->getContents();
  1593. $response_arr = json_decode($response, true);
  1594. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1595. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1596. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  1597. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  1598. Utils::throwError('20003:火山生成音频失败');
  1599. }
  1600. }
  1601. } catch (\Exception $e) {
  1602. $failed_segments[] = [
  1603. 'segment_id' => $segment_id,
  1604. 'error' => $e->getMessage()
  1605. ];
  1606. }
  1607. // 创建任务之后先暂停10s等待异步任务完成
  1608. sleep(10);
  1609. $img_url = $this->loopGetPicTaskResult($task_id);
  1610. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  1611. // 图片生成后新增对话记录
  1612. try {
  1613. $uid = Site::getUid();
  1614. $now = date('Y-m-d H:i:s');
  1615. // 使用AI反推图片提示词
  1616. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  1617. // 保存对话记录
  1618. $records = [
  1619. [
  1620. 'uid' => $uid,
  1621. 'anime_id' => $anime_id,
  1622. 'sequence' => $episode_number,
  1623. 'role' => 'user',
  1624. 'content' => '重新生成',
  1625. 'segment_id' => $segment_id,
  1626. 'image_url' => '',
  1627. 'created_at' => $now,
  1628. 'updated_at' => $now
  1629. ],
  1630. [
  1631. 'uid' => $uid,
  1632. 'anime_id' => $anime_id,
  1633. 'sequence' => $episode_number,
  1634. 'role' => 'assistant',
  1635. 'content' => $pic_prompt,
  1636. 'segment_id' => $segment_id,
  1637. 'image_url' => $img_url,
  1638. 'created_at' => $now,
  1639. 'updated_at' => $now
  1640. ]
  1641. ];
  1642. DB::table('mp_anime_records')->insert($records);
  1643. } catch (\Exception $e) {
  1644. // 记录日志但不影响主流程
  1645. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  1646. 'segment_id' => $segment_id,
  1647. 'img_url' => $img_url
  1648. ]);
  1649. }
  1650. return $img_url;
  1651. }
  1652. public function addSegment($data) {
  1653. $prev_segment_id = getProp($data, 'prev_segment_id');
  1654. $img_url = getProp($data, 'img_url');
  1655. $video_url = getProp($data, 'video_url');
  1656. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  1657. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1658. $anime_id = getProp($segment, 'anime_id');
  1659. $episode_id = getProp($segment, 'episode_id');
  1660. $episode_number = getProp($segment, 'episode_number');
  1661. $segment_number = getProp($segment, 'segment_number');
  1662. $new_segment_number = $segment_number + 1;
  1663. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  1664. // 分镜剧本数组
  1665. $insert_data = [
  1666. 'anime_id' => $anime_id,
  1667. 'episode_id' => $episode_id,
  1668. 'episode_number' => $episode_number,
  1669. 'act_number' => getProp($segment, 'act_number'),
  1670. 'act_title' => getProp($segment, 'act_title'),
  1671. 'segment_id' => $segment_id,
  1672. 'segment_number' => $new_segment_number,
  1673. 'segment_content' => '',
  1674. 'img_url' => '',
  1675. 'video_url' => '',
  1676. 'created_at' => date('Y-m-d H:i:s'),
  1677. 'updated_at' => date('Y-m-d H:i:s')
  1678. ];
  1679. if ($img_url) $insert_data['img_url'] = $img_url;
  1680. if ($video_url) {
  1681. $insert_data['origin_video_url'] = $video_url;
  1682. $insert_data['current_type'] = 2;
  1683. $compressed_video_url = compressVideo($video_url);
  1684. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  1685. }
  1686. try {
  1687. DB::beginTransaction();
  1688. // 先更新序号
  1689. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  1690. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  1691. if (!$id) {
  1692. Utils::throwError('20003:新增分镜失败!');
  1693. }
  1694. }catch (\Exception $e) {
  1695. DB::rollBack();
  1696. Utils::throwError('20003:'.$e->getMessage());
  1697. }
  1698. DB::commit();
  1699. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  1700. $segment = $segment ? (array)$segment : [];
  1701. return $segment;
  1702. // 以下代码暂弃用
  1703. $anime_id = getProp($segment, 'anime_id');
  1704. $episode_id = getProp($segment, 'episode_id');
  1705. $episode_number = getProp($segment, 'episode_number');
  1706. $segment_number = getProp($segment, 'segment_number');
  1707. $segment_content = getProp($data, 'segment_content');
  1708. $img_url = getProp($data, 'img_url');
  1709. $video_url = getProp($data, 'video_url');
  1710. $ratio = getProp($data, 'ratio');
  1711. $dimensions = $this->getRatioDimensions($ratio);
  1712. $width = $dimensions['width'];
  1713. $height = $dimensions['height'];
  1714. if (!$anime_id || !$episode_id) {
  1715. Utils::throwError('1002:请选择分镜');
  1716. }
  1717. // 使用文生文模型重新解析segment_content
  1718. if (!empty($segment_content)) {
  1719. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1720. }
  1721. // 获取动漫的角色信息(包含参考图)
  1722. $anime = DB::table('mp_animes')
  1723. ->where('id', $anime_id)
  1724. ->select('roles', 'scenes')
  1725. ->first();
  1726. if (!$anime || !$anime->roles) {
  1727. Utils::throwError('20003:未找到角色信息');
  1728. }
  1729. $roles = json_decode($anime->roles, true);
  1730. if (!$roles) {
  1731. Utils::throwError('20003:角色信息格式错误');
  1732. }
  1733. // 构建角色名称到参考图的映射
  1734. $role_map = [];
  1735. foreach ($roles as $role) {
  1736. $role_name = getProp($role, 'role');
  1737. $role_url = getProp($role, 'url');
  1738. if (!empty($role_name) && !empty($role_url)) {
  1739. $role_map[$role_name] = $role_url;
  1740. }
  1741. }
  1742. $scenes = json_decode($anime->scenes, true);
  1743. if (!$scenes) {
  1744. Utils::throwError('20003:角色信息格式错误');
  1745. }
  1746. // 构建角色名称到参考图的映射
  1747. $scene_map = [];
  1748. foreach ($scenes as $scene) {
  1749. $scene_name = getProp($scene, 'scene');
  1750. $scene_url = getProp($scene, 'url');
  1751. if (!empty($scene_name) && !empty($scene_url)) {
  1752. $scene_map[$scene_name] = $scene_url;
  1753. }
  1754. }
  1755. $segment_id = $segment->segment_id;
  1756. $original_segment_content = $segment->segment_content;
  1757. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1758. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1759. if (empty($final_segment_content)) {
  1760. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1761. }
  1762. try {
  1763. $dubTaskId = 0;
  1764. DB::beginTransaction();
  1765. $new_segment_number = $segment_number + 1;
  1766. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  1767. // 分镜剧本数组
  1768. $insert_data = [
  1769. 'anime_id' => $anime_id,
  1770. 'episode_id' => $episode_id,
  1771. 'episode_number' => $episode_number,
  1772. 'act_number' => getProp($segment, 'act_number'),
  1773. 'act_title' => getProp($segment, 'act_title'),
  1774. 'segment_id' => $segment_id,
  1775. 'segment_number' => $new_segment_number,
  1776. 'segment_content' => $final_segment_content,
  1777. 'img_url' => $img_url,
  1778. 'video_url' => $video_url,
  1779. 'created_at' => date('Y-m-d H:i:s'),
  1780. 'updated_at' => date('Y-m-d H:i:s')
  1781. ];
  1782. // 更新分镜剧本信息
  1783. $this->handleSegmentContent($insert_data);
  1784. // 如果有对话内容,创建视频配音合成任务
  1785. $dialogue = getProp($insert_data, 'dialogue');
  1786. if (!empty($dialogue)) {
  1787. $now = date('Y-m-d H:i:s');
  1788. $generate_json = [
  1789. 'text' => $dialogue,
  1790. 'role' => getProp($insert_data, 'voice_actor'),
  1791. 'voice_type' => getProp($insert_data, 'voice_type'),
  1792. 'voice_name' => getProp($insert_data, 'voice_name'),
  1793. 'emotion' => getProp($insert_data, 'emotion'),
  1794. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  1795. 'gender' => getProp($insert_data, 'gender'),
  1796. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  1797. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  1798. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  1799. 'pitch' => getProp($insert_data, 'pitch', 0),
  1800. ];
  1801. // 插入视频配音合成任务
  1802. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1803. 'alias_segment_id' => $segment_id,
  1804. 'generate_status' => '执行中',
  1805. 'audio_url' => '',
  1806. 'generate_json' => json_encode($generate_json, 256),
  1807. 'created_at' => $now,
  1808. 'updated_at' => $now,
  1809. ]);
  1810. if (!$dubTaskId) {
  1811. Utils::throwError('20003:创建配音任务失败!');
  1812. }
  1813. $insert_data['audio_url'] = '';
  1814. } else {
  1815. // dialogue为空时,直接写入默认音频信息
  1816. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1817. $insert_data['audio_duration'] = 2.0;
  1818. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1819. }
  1820. // 如果没有上传图片则使用当前描述进行生成
  1821. if (!$img_url) {
  1822. // 解析分镜内容,提取画面描述作为主要提示词
  1823. $prompt = $final_segment_content;
  1824. $ref_img_urls = [];
  1825. // 分镜场景
  1826. $scene = getProp($insert_data, 'scene');
  1827. if ($scene) {
  1828. $matched_scene = '';
  1829. if (isset($scene_map[$scene])) {
  1830. $img_index = count($ref_img_urls) + 1;
  1831. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1832. $ref_img_urls[] = $scene_map[$scene];
  1833. $matched_scene = $scene;
  1834. }
  1835. $update_data['scene'] = $scene;
  1836. }
  1837. // 分镜角色
  1838. $characters = getProp($insert_data, 'characters');
  1839. if ($characters) {
  1840. $update_data['characters'] = $characters;
  1841. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1842. $characters = explode(',', $characters);
  1843. // 从分镜内容中提取涉及的角色
  1844. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1845. // 获取匹配角色的参考图
  1846. foreach ($segment_characters as $character) {
  1847. if (isset($role_map[$character])) {
  1848. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1849. $img_index = count($ref_img_urls) + 1;
  1850. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1851. $ref_img_urls[] = $role_map[$character];
  1852. }
  1853. }
  1854. }
  1855. // 如果没有找到匹配的角色参考图,不使用参考图
  1856. if (empty($ref_img_urls)) {
  1857. $ref_img_urls = [];
  1858. }
  1859. // 准备生成任务参数
  1860. $params = [
  1861. 'alias_segment_id' => $segment_id,
  1862. 'prompt' => $prompt,
  1863. 'ref_img_urls' => $ref_img_urls,
  1864. 'width' => $width,
  1865. 'height' => $height,
  1866. ];
  1867. // 调用AI图片生成服务
  1868. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1869. $task_id = $task->id;
  1870. // $task_id = 'whatever';
  1871. if (!$task_id) {
  1872. Utils::throwError('20003:创建生成任务失败!');
  1873. }
  1874. $insert_data['pic_task_status'] = '生成中';
  1875. $insert_data['pic_task_id'] = $task_id;
  1876. }
  1877. // 先更新序号
  1878. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  1879. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  1880. if (!$boolen) {
  1881. Utils::throwError('20003:新增分镜失败!');
  1882. }
  1883. // 如果是第一集的首帧图片,则存入待更新数组
  1884. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  1885. Redis::sadd('anime_first_frame_urls', $segment_id);
  1886. }
  1887. if ($dubTaskId) {
  1888. // 请求远程服务器执行生成
  1889. $client = new Client(['timeout' => 300, 'verify' => false]);
  1890. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1891. $response = $result->getBody()->getContents();
  1892. $response_arr = json_decode($response, true);
  1893. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1894. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1895. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  1896. Utils::throwError('20003:火山生成音频失败');
  1897. }
  1898. }
  1899. } catch (\Exception $e) {
  1900. DB::rollBack();
  1901. Utils::throwError('20003:'.$e->getMessage());
  1902. }
  1903. DB::commit();
  1904. // 创建任务之后先暂停10s等待异步任务完成
  1905. sleep(10);
  1906. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  1907. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  1908. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1909. $segment = $segment ? (array)$segment : [];
  1910. return $segment;
  1911. }
  1912. public function copySegment($data) {
  1913. $segment_id = getProp($data, 'segment_id');
  1914. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1915. if (!$segment) Utils::throwError('20003:请选择分镜');
  1916. $anime_id = getProp($segment, 'anime_id');
  1917. $episode_id = getProp($segment, 'episode_id');
  1918. $episode_number = getProp($segment, 'episode_number');
  1919. $segment_number = getProp($segment, 'segment_number');
  1920. $new_segment_id = 0;
  1921. try {
  1922. DB::beginTransaction();
  1923. $segment = (array)$segment;
  1924. unset($segment['id']);
  1925. $segment['segment_number'] += 1;
  1926. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  1927. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  1928. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  1929. // 更新其他分镜序号
  1930. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  1931. // 复制分镜
  1932. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  1933. if (!$id) {
  1934. Utils::throwError('20003:复制分镜失败');
  1935. }
  1936. }catch (\Exception $e) {
  1937. DB::rollBack();
  1938. Utils::throwError('20003:'.$e->getMessage());
  1939. }
  1940. DB::commit();
  1941. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  1942. $segment = $segment ? (array)$segment : [];
  1943. return $segment;
  1944. }
  1945. public function moveSegment($data) {
  1946. $segment_id = getProp($data, 'segment_id');
  1947. $target_segment_id = getProp($data, 'target_segment_id');
  1948. // 获取源分镜信息
  1949. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1950. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  1951. // 获取目标分镜信息
  1952. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  1953. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  1954. $anime_id = getProp($source_segment, 'anime_id');
  1955. $episode_id = getProp($source_segment, 'episode_id');
  1956. $episode_number = getProp($source_segment, 'episode_number');
  1957. $source_segment_number = getProp($source_segment, 'segment_number');
  1958. $target_segment_number = getProp($target_segment, 'segment_number');
  1959. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  1960. $target_anime_id = getProp($target_segment, 'anime_id');
  1961. $target_episode_number = getProp($target_segment, 'episode_number');
  1962. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  1963. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  1964. }
  1965. // 如果源分镜和目标分镜相同,无需移动
  1966. if ($source_segment_number == $target_segment_number) {
  1967. return true;
  1968. }
  1969. try {
  1970. DB::beginTransaction();
  1971. if ($source_segment_number < $target_segment_number) {
  1972. // 向后移动:源分镜移动到目标分镜之后
  1973. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  1974. DB::table('mp_episode_segments')
  1975. ->where('anime_id', $anime_id)
  1976. ->where('episode_id', $episode_id)
  1977. ->where('segment_number', '>', $source_segment_number)
  1978. ->where('segment_number', '<=', $target_segment_number)
  1979. ->decrement('segment_number');
  1980. // 2. 将源分镜移动到目标分镜之后
  1981. $new_segment_number = $target_segment_number;
  1982. } else {
  1983. // 向前移动:源分镜移动到目标分镜之后
  1984. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  1985. DB::table('mp_episode_segments')
  1986. ->where('anime_id', $anime_id)
  1987. ->where('episode_id', $episode_id)
  1988. ->where('segment_number', '>', $target_segment_number)
  1989. ->where('segment_number', '<', $source_segment_number)
  1990. ->increment('segment_number');
  1991. // 2. 将源分镜移动到目标分镜之后
  1992. $new_segment_number = $target_segment_number + 1;
  1993. }
  1994. // 3. 更新源分镜的序号
  1995. $update_result = DB::table('mp_episode_segments')
  1996. ->where('segment_id', $segment_id)
  1997. ->update([
  1998. 'segment_number' => $new_segment_number,
  1999. 'updated_at' => date('Y-m-d H:i:s')
  2000. ]);
  2001. if (!$update_result) {
  2002. Utils::throwError('20003:更新分镜序号失败');
  2003. }
  2004. DB::commit();
  2005. return true;
  2006. } catch (\Exception $e) {
  2007. DB::rollBack();
  2008. Utils::throwError('20003:' . $e->getMessage());
  2009. }
  2010. }
  2011. public function delSegment($data) {
  2012. $segment_id = getProp($data, 'segment_id');
  2013. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2014. if (!$segment) Utils::throwError('20003:请选择分镜');
  2015. $anime_id = getProp($segment, 'anime_id');
  2016. $episode_id = getProp($segment, 'episode_id');
  2017. $episode_number = getProp($segment, 'episode_number');
  2018. $segment_number = getProp($segment, 'segment_number');
  2019. try {
  2020. DB::beginTransaction();
  2021. // 删除分镜
  2022. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2023. if (!$boolen) {
  2024. Utils::throwError('20003:删除分镜失败');
  2025. }
  2026. // 更新其他分镜序号
  2027. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2028. }catch (\Exception $e) {
  2029. DB::rollBack();
  2030. Utils::throwError('20003:'.$e->getMessage());
  2031. }
  2032. DB::commit();
  2033. return true;
  2034. }
  2035. public function applySegment($data) {
  2036. $segment_id = getProp($data, 'segment_id');
  2037. $url = getProp($data, 'url');
  2038. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2039. if (!$url) Utils::throwError('20003:URL不能为空');
  2040. // 获取URL的文件扩展名
  2041. $urlPath = parse_url($url, PHP_URL_PATH);
  2042. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2043. // 定义图片和视频的扩展名
  2044. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2045. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2046. // 判断是图片还是视频
  2047. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2048. if (in_array($extension, $imageExtensions)) {
  2049. // 图片类型
  2050. $updateData['img_url'] = $url;
  2051. $updateData['current_type'] = 1;
  2052. } elseif (in_array($extension, $videoExtensions)) {
  2053. // 视频类型
  2054. $updateData['video_url'] = $url;
  2055. $updateData['current_type'] = 2;
  2056. } else {
  2057. Utils::throwError('20003:不支持的文件类型');
  2058. }
  2059. // 更新分镜表
  2060. $result = DB::table('mp_episode_segments')
  2061. ->where('segment_id', $segment_id)
  2062. ->update($updateData);
  2063. if (!$result) {
  2064. Utils::throwError('20003:更新分镜失败');
  2065. }
  2066. return true;
  2067. }
  2068. public function segmentHistory($data) {
  2069. $segment_id = getProp($data, 'segment_id');
  2070. // 获取历史图片
  2071. $pics = [];
  2072. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2073. foreach($pic_history as $task) {
  2074. $result_url = getProp($task, 'result_url');
  2075. if (is_json($result_url)) {
  2076. $pics = array_merge($pics, json_decode($result_url, true));
  2077. }else {
  2078. $pics[] = $result_url;
  2079. }
  2080. }
  2081. // 获取历史视频
  2082. $videos = [];
  2083. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2084. foreach($video_history as $task) {
  2085. $result_url = getProp($task, 'result_url');
  2086. if (is_json($result_url)) {
  2087. $videos = array_merge($videos, json_decode($result_url, true));
  2088. }else {
  2089. $videos[] = $result_url;
  2090. }
  2091. }
  2092. return compact('pics', 'videos');
  2093. }
  2094. public function addAct($data) {
  2095. $prev_act_id = getProp($data, 'prev_act_id');
  2096. $act_title = getProp($data, 'act_title', '');
  2097. $act_content = getProp($data, 'act_content', '');
  2098. $act_duration = getProp($data, 'act_duration', 5);
  2099. $video_url = getProp($data, 'video_url');
  2100. // 根据prev_act_id获取记录
  2101. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2102. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2103. $anime_id = getProp($prev_segment, 'anime_id');
  2104. $episode_id = getProp($prev_segment, 'episode_id');
  2105. $episode_number = getProp($prev_segment, 'episode_number');
  2106. $prev_act_number = getProp($prev_segment, 'act_number');
  2107. // 获取新的act_number
  2108. $new_act_number = $prev_act_number + 1;
  2109. try {
  2110. DB::beginTransaction();
  2111. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2112. DB::table('mp_episode_segments')
  2113. ->where('anime_id', $anime_id)
  2114. ->where('episode_id', $episode_id)
  2115. ->where('act_number', '>', $prev_act_number)
  2116. ->increment('act_number');
  2117. // 插入新片段记录
  2118. $insert_data = [
  2119. 'anime_id' => $anime_id,
  2120. 'episode_id' => $episode_id,
  2121. 'episode_number' => $episode_number,
  2122. 'act_number' => $new_act_number,
  2123. 'created_at' => date('Y-m-d H:i:s'),
  2124. 'updated_at' => date('Y-m-d H:i:s')
  2125. ];
  2126. if ($act_title) {
  2127. $insert_data['act_title'] = $act_title;
  2128. }
  2129. if ($act_content) {
  2130. $insert_data['act_content'] = $act_content;
  2131. }
  2132. if ($act_duration) {
  2133. $insert_data['act_duration'] = $act_duration;
  2134. }
  2135. if ($video_url) {
  2136. $insert_data['origin_video_url'] = $video_url;
  2137. $insert_data['current_type'] = 2;
  2138. $compressed_video_url = compressVideo($video_url);
  2139. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2140. }
  2141. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2142. if (!$id) {
  2143. Utils::throwError('20003:新增片段失败!');
  2144. }
  2145. DB::commit();
  2146. }catch (\Exception $e) {
  2147. DB::rollBack();
  2148. Utils::throwError('20003:'.$e->getMessage());
  2149. }
  2150. $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();
  2151. $segment = $segment ? (array)$segment : [];
  2152. return $segment;
  2153. }
  2154. public function editAct($data) {
  2155. $act_id = getProp($data, 'act_id');
  2156. $act_content = getProp($data, 'act_content');
  2157. $act_duration = getProp($data, 'act_duration');
  2158. $act_title = getProp($data, 'act_title');
  2159. $image_url = getProp($data, 'image_url');
  2160. $video_url = getProp($data, 'video_url');
  2161. // 参数验证
  2162. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2163. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2164. $segment = DB::table('mp_episode_segments')
  2165. ->where('id', $act_id)
  2166. ->first();
  2167. if (!$segment) Utils::throwError('20003:该片段不存在');
  2168. try {
  2169. DB::beginTransaction();
  2170. // 准备更新数据
  2171. $update_data = [
  2172. 'updated_at' => date('Y-m-d H:i:s')
  2173. ];
  2174. // 更新act相关字段
  2175. if (!empty($act_content)) {
  2176. $update_data['act_content'] = $act_content;
  2177. }
  2178. if (!empty($act_duration)) {
  2179. $update_data['act_duration'] = $act_duration;
  2180. }
  2181. if (!empty($act_title)) {
  2182. $update_data['act_title'] = $act_title;
  2183. }
  2184. // 处理图片上传
  2185. if ($image_url) {
  2186. $update_data['img_url'] = $image_url;
  2187. $update_data['current_type'] = 1;
  2188. // 同时写入一个图片生成任务记录
  2189. if ($act_id) {
  2190. $pic_task = [
  2191. 'alias_act_id' => $act_id,
  2192. 'ref_img_url' => json_encode([]),
  2193. 'status' => 'success',
  2194. 'result_url' => json_encode([$image_url], 256),
  2195. 'model' => '',
  2196. 'created_at' => date('Y-m-d H:i:s'),
  2197. 'updated_at' => date('Y-m-d H:i:s'),
  2198. ];
  2199. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2200. }
  2201. }
  2202. // 处理视频上传
  2203. if ($video_url) {
  2204. $update_data['origin_video_url'] = $video_url;
  2205. $compressed_video_url = compressVideo($video_url);
  2206. $update_data['current_type'] = 2;
  2207. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2208. // 同时写入一个视频生成任务记录
  2209. if ($act_id) {
  2210. $video_task = [
  2211. 'alias_act_id' => $act_id,
  2212. 'status' => 'success',
  2213. 'result_url' => $update_data['origin_video_url'],
  2214. 'compressed_url' => $update_data['video_url'],
  2215. 'created_at' => date('Y-m-d H:i:s'),
  2216. 'updated_at' => date('Y-m-d H:i:s'),
  2217. ];
  2218. DB::table('mp_generate_video_tasks')->insert($video_task);
  2219. }
  2220. }
  2221. // 更新片段信息
  2222. $result = DB::table('mp_episode_segments')
  2223. ->where('id', $act_id)
  2224. ->update($update_data);
  2225. if ($result === false) {
  2226. Utils::throwError('20003:更新片段失败');
  2227. }
  2228. DB::commit();
  2229. return true;
  2230. } catch (\Exception $e) {
  2231. DB::rollBack();
  2232. dLog('anime')->error('更新片段失败', [
  2233. 'act_id' => $act_id,
  2234. 'error' => $e->getMessage()
  2235. ]);
  2236. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2237. }
  2238. }
  2239. public function copyAct($data) {
  2240. $act_id = getProp($data, 'act_id');
  2241. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2242. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2243. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2244. $video_url = getProp($source_segment, 'video_url');
  2245. if (!$video_url) Utils::throwError('20003:该片段没有视频无法复制');
  2246. $anime_id = getProp($source_segment, 'anime_id');
  2247. $episode_id = getProp($source_segment, 'episode_id');
  2248. $episode_number = getProp($source_segment, 'episode_number');
  2249. $act_number = getProp($source_segment, 'act_number');
  2250. try {
  2251. DB::beginTransaction();
  2252. // 新act的编号
  2253. $new_act_number = $act_number + 1;
  2254. // 更新后续所有act的act_number
  2255. DB::table('mp_episode_segments')
  2256. ->where('anime_id', $anime_id)
  2257. ->where('episode_id', $episode_id)
  2258. ->where('act_number', '>', $act_number)
  2259. ->increment('act_number');
  2260. // 复制该片段记录
  2261. $segment_data = (array)$source_segment;
  2262. unset($segment_data['id']);
  2263. $segment_data['act_number'] = $new_act_number;
  2264. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2265. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2266. if (!$id) {
  2267. Utils::throwError('20003:复制片段失败');
  2268. }
  2269. DB::commit();
  2270. }catch (\Exception $e) {
  2271. DB::rollBack();
  2272. Utils::throwError('20003:'.$e->getMessage());
  2273. }
  2274. // 返回新复制的记录
  2275. $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,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
  2276. $new_segment = $new_segment ? (array)$new_segment : [];
  2277. $new_segment['act_id'] = $id;
  2278. return $new_segment;
  2279. }
  2280. public function moveAct($data) {
  2281. $act_id = getProp($data, 'act_id');
  2282. $target_act_id = getProp($data, 'target_act_id');
  2283. // 获取源片段信息
  2284. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2285. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2286. // 获取目标片段信息
  2287. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2288. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2289. $anime_id = getProp($source_segment, 'anime_id');
  2290. $episode_id = getProp($source_segment, 'episode_id');
  2291. $source_act_number = getProp($source_segment, 'act_number');
  2292. $target_act_number = getProp($target_segment, 'act_number');
  2293. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2294. $target_anime_id = getProp($target_segment, 'anime_id');
  2295. $target_episode_id = getProp($target_segment, 'episode_id');
  2296. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2297. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2298. }
  2299. // 如果源片段和目标片段相同,无需移动
  2300. if ($source_act_number == $target_act_number) {
  2301. return true;
  2302. }
  2303. try {
  2304. DB::beginTransaction();
  2305. if ($source_act_number < $target_act_number) {
  2306. // 向后移动:源片段移动到目标片段之后
  2307. // 1. 将源片段和目标片段之间的所有片段编号减1
  2308. DB::table('mp_episode_segments')
  2309. ->where('anime_id', $anime_id)
  2310. ->where('episode_id', $episode_id)
  2311. ->where('act_number', '>', $source_act_number)
  2312. ->where('act_number', '<=', $target_act_number)
  2313. ->decrement('act_number');
  2314. // 2. 将源片段移动到目标片段之后
  2315. $new_act_number = $target_act_number;
  2316. } else {
  2317. // 向前移动:源片段移动到目标片段之后
  2318. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2319. DB::table('mp_episode_segments')
  2320. ->where('anime_id', $anime_id)
  2321. ->where('episode_id', $episode_id)
  2322. ->where('act_number', '>', $target_act_number)
  2323. ->where('act_number', '<', $source_act_number)
  2324. ->increment('act_number');
  2325. // 2. 将源片段移动到目标片段之后
  2326. $new_act_number = $target_act_number + 1;
  2327. }
  2328. // 3. 更新源片段的编号
  2329. $update_result = DB::table('mp_episode_segments')
  2330. ->where('id', $act_id)
  2331. ->update([
  2332. 'act_number' => $new_act_number,
  2333. 'updated_at' => date('Y-m-d H:i:s')
  2334. ]);
  2335. if (!$update_result) {
  2336. Utils::throwError('20003:更新片段编号失败');
  2337. }
  2338. DB::commit();
  2339. return true;
  2340. } catch (\Exception $e) {
  2341. DB::rollBack();
  2342. Utils::throwError('20003:' . $e->getMessage());
  2343. }
  2344. }
  2345. public function delAct($data) {
  2346. $act_id = getProp($data, 'act_id');
  2347. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2348. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2349. if (!$segment) Utils::throwError('20003:请选择片段');
  2350. $anime_id = getProp($segment, 'anime_id');
  2351. $episode_id = getProp($segment, 'episode_id');
  2352. $act_number = getProp($segment, 'act_number');
  2353. try {
  2354. DB::beginTransaction();
  2355. // 删除该片段记录
  2356. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2357. if (!$deleted) {
  2358. Utils::throwError('20003:删除片段失败');
  2359. }
  2360. // 更新后续act的编号
  2361. DB::table('mp_episode_segments')
  2362. ->where('anime_id', $anime_id)
  2363. ->where('episode_id', $episode_id)
  2364. ->where('act_number', '>', $act_number)
  2365. ->decrement('act_number');
  2366. DB::commit();
  2367. }catch (\Exception $e) {
  2368. DB::rollBack();
  2369. Utils::throwError('20003:'.$e->getMessage());
  2370. }
  2371. return true;
  2372. }
  2373. public function applyAct($data) {
  2374. $act_id = getProp($data, 'act_id');
  2375. $url = getProp($data, 'url');
  2376. if (!$act_id) Utils::throwError('20003:请选择片段');
  2377. if (!$url) Utils::throwError('20003:URL不能为空');
  2378. // 获取URL的文件扩展名
  2379. $urlPath = parse_url($url, PHP_URL_PATH);
  2380. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2381. // 定义图片和视频的扩展名
  2382. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2383. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2384. // 判断是图片还是视频
  2385. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2386. if (in_array($extension, $imageExtensions)) {
  2387. // 图片类型
  2388. $updateData['img_url'] = $url;
  2389. $updateData['current_type'] = 1;
  2390. } elseif (in_array($extension, $videoExtensions)) {
  2391. // 视频类型
  2392. $updateData['video_url'] = $url;
  2393. $updateData['current_type'] = 2;
  2394. } else {
  2395. Utils::throwError('20003:不支持的文件类型');
  2396. }
  2397. // 更新片段记录(全能模式下每个act只有一条记录)
  2398. $result = DB::table('mp_episode_segments')
  2399. ->where('id', $act_id)
  2400. ->update($updateData);
  2401. if (!$result) {
  2402. Utils::throwError('20003:更新片段失败');
  2403. }
  2404. return true;
  2405. }
  2406. public function actChatHistory($data) {
  2407. $act_id = getProp($data, 'act_id');
  2408. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2409. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2410. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2411. $value = (array)$value;
  2412. $value['created_at'] = transDate($value['created_at']);
  2413. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2414. else $value['reference_images'] = [];
  2415. return $value;
  2416. })->toArray();
  2417. // 获取历史图片
  2418. $url = [];
  2419. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2420. foreach($pic_history as $task) {
  2421. $result_url = getProp($task, 'result_url');
  2422. if (is_json($result_url)) {
  2423. $url = array_merge($url, json_decode($result_url, true));
  2424. }else {
  2425. $url[] = $result_url;
  2426. }
  2427. }
  2428. // 获取历史视频
  2429. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2430. foreach($video_history as $task) {
  2431. $result_url = getProp($task, 'result_url');
  2432. if (is_json($result_url)) {
  2433. $url = array_merge($url, json_decode($result_url, true));
  2434. }else {
  2435. $url[] = $result_url;
  2436. }
  2437. }
  2438. // 获取资产库
  2439. $products = [];
  2440. // 通过act_id查询片段信息获取episode_id
  2441. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2442. if ($segment) {
  2443. $episode_id = getProp($segment, 'episode_id');
  2444. // 查询剧集信息获取roles、scenes和extra_products
  2445. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2446. if ($episode) {
  2447. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2448. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2449. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2450. // 先合并roles和scenes
  2451. // 处理角色数组
  2452. foreach ($roles as $role) {
  2453. $product = $role;
  2454. // 将role字段重命名为product_name
  2455. if (isset($product['role'])) {
  2456. $product['product_name'] = $product['role'];
  2457. unset($product['role']);
  2458. }
  2459. $product['product'] = 1; // 标记类型为角色
  2460. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2461. }
  2462. // 处理场景数组
  2463. foreach ($scenes as $scene) {
  2464. $product = $scene;
  2465. // 将scene字段重命名为product_name
  2466. if (isset($product['scene'])) {
  2467. $product['product_name'] = $product['scene'];
  2468. unset($product['scene']);
  2469. }
  2470. $product['product'] = 2; // 标记类型为场景
  2471. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2472. }
  2473. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2474. foreach ($extra_products as $extra_product) {
  2475. $product_name = getProp($extra_product, 'product_name');
  2476. if ($product_name) {
  2477. $products[$product_name] = $extra_product; // 覆盖同名数据
  2478. }
  2479. }
  2480. // 重新索引数组(去除key)
  2481. $products = array_values($products);
  2482. }
  2483. }
  2484. // 获取执行中的任务
  2485. $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) {
  2486. $value = (array)$value;
  2487. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2488. else $value['ref_image_url'] = [];
  2489. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2490. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2491. if (!empty($value['prompt'])) {
  2492. $prompt = $value['prompt'];
  2493. // 查找第一个【镜头】的位置
  2494. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2495. // 从【镜头】开始截取
  2496. $prompt = substr($prompt, $matches[0][1]);
  2497. }
  2498. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2499. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2500. $value['prompt'] = $prompt;
  2501. }
  2502. return $value;
  2503. })->toArray();
  2504. return compact('chat', 'url', 'products', 'tasks');
  2505. }
  2506. public function applyAudioData($data) {
  2507. $segment_id = getProp($data, 'segment_id');
  2508. $global_data = getProp($data, 'global_data');
  2509. $segment_data = getProp($data, 'segment_data');
  2510. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2511. $global_data = is_array($global_data) ? $global_data : [];
  2512. $segment_data = is_array($segment_data) ? $segment_data : [];
  2513. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2514. $dialogue_item = null;
  2515. foreach ($global_data as $key => $item) {
  2516. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2517. $dialogue_item = $item;
  2518. unset($global_data[$key]);
  2519. break;
  2520. }
  2521. }
  2522. if ($dialogue_item) {
  2523. $segment_data[] = $dialogue_item;
  2524. }
  2525. // 特殊参数: audio_url,audio_duration,subtitle_info
  2526. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2527. // 如果不是全部存在,则仍需创建音频任务
  2528. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2529. $special_update_data = [];
  2530. $has_all_special_params = false;
  2531. // 从segment_data中提取特殊参数
  2532. $filtered_segment_data = [];
  2533. foreach ($segment_data as $item) {
  2534. $field_name = trim((string)getProp($item, 'name'));
  2535. if (in_array($field_name, $special_fields)) {
  2536. $special_update_data[$field_name] = getProp($item, 'value');
  2537. } else {
  2538. // 非特殊参数保留,继续后续处理
  2539. $filtered_segment_data[] = $item;
  2540. }
  2541. }
  2542. // 检查是否三个特殊参数都存在
  2543. if (count($special_update_data) === 3 &&
  2544. isset($special_update_data['audio_url']) &&
  2545. isset($special_update_data['audio_duration']) &&
  2546. isset($special_update_data['subtitle_info'])) {
  2547. $has_all_special_params = true;
  2548. // 立即更新到当前分镜
  2549. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  2550. DB::table('mp_episode_segments')
  2551. ->where('segment_id', $segment_id)
  2552. ->update($special_update_data);
  2553. }
  2554. // 使用过滤后的segment_data继续处理其他参数
  2555. $segment_data = $filtered_segment_data;
  2556. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  2557. $global_update_data = [];
  2558. $segment_update_data = [];
  2559. $global_voice_type = '';
  2560. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2561. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  2562. $episode_id = getProp($target_segment, 'episode_id');
  2563. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  2564. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2565. if (!$episode) Utils::throwError('20003:分集不存在');
  2566. foreach ($global_data as $item) {
  2567. $field_name = trim((string)getProp($item, 'name'));
  2568. if (!$field_name || !in_array($field_name, $allow_fields)) {
  2569. continue;
  2570. }
  2571. $global_update_data[$field_name] = getProp($item, 'value');
  2572. if ($field_name === 'voice_type') {
  2573. $global_voice_type = trim((string)getProp($item, 'value'));
  2574. }
  2575. }
  2576. foreach ($segment_data as $item) {
  2577. $field_name = trim((string)getProp($item, 'name'));
  2578. if (!$field_name || !in_array($field_name, $allow_fields)) {
  2579. continue;
  2580. }
  2581. $segment_update_data[$field_name] = getProp($item, 'value');
  2582. }
  2583. if ($global_voice_type) {
  2584. $timbre_info = DB::table('mp_timbres')
  2585. ->where('timbre_type', $global_voice_type)
  2586. ->select('audio_url', 'timbre_name')
  2587. ->first();
  2588. if ($timbre_info) {
  2589. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  2590. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  2591. }
  2592. }
  2593. try {
  2594. DB::beginTransaction();
  2595. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  2596. $segment_ids_to_create_task = [];
  2597. $segments_data = [];
  2598. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  2599. if (!empty($global_update_data)) {
  2600. // 如果角色不存在,则只更新当前分镜
  2601. if (!$target_voice_actor) {
  2602. // 只处理当前分镜
  2603. $affected_segments = DB::table('mp_episode_segments')
  2604. ->where('segment_id', $segment_id)
  2605. ->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')
  2606. ->get();
  2607. } else {
  2608. // 获取该角色的所有分镜
  2609. $affected_segments = DB::table('mp_episode_segments')
  2610. ->where('episode_id', $episode_id)
  2611. ->where('voice_actor', $target_voice_actor)
  2612. ->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')
  2613. ->get();
  2614. }
  2615. foreach ($affected_segments as $seg) {
  2616. $seg = (array)$seg;
  2617. $sid = getProp($seg, 'segment_id');
  2618. // 检查参数是否发生变化
  2619. $has_changed = false;
  2620. foreach ($global_update_data as $field => $new_value) {
  2621. $old_value = getProp($seg, $field);
  2622. if ($old_value != $new_value) {
  2623. $has_changed = true;
  2624. break;
  2625. }
  2626. }
  2627. if ($has_changed) {
  2628. $segment_ids_to_create_task[] = $sid;
  2629. $segments_data[$sid] = $seg;
  2630. }
  2631. }
  2632. // 只有在有变化的分镜时才更新
  2633. if (!empty($segment_ids_to_create_task)) {
  2634. $global_segment_update_data = $global_update_data;
  2635. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  2636. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  2637. DB::table('mp_episode_segments')
  2638. ->where('episode_id', $episode_id)
  2639. ->where('voice_actor', $target_voice_actor)
  2640. ->whereIn('segment_id', $segment_ids_to_create_task)
  2641. ->update($global_segment_update_data);
  2642. }
  2643. if ($global_voice_type) {
  2644. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  2645. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  2646. $roles_updated = false;
  2647. foreach ($episode_roles as &$role) {
  2648. // 通过 role 字段匹配角色名,而不是 voice_name
  2649. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  2650. continue;
  2651. }
  2652. $role['voice_type'] = $global_voice_type;
  2653. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  2654. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  2655. $roles_updated = true;
  2656. }
  2657. unset($role);
  2658. if ($roles_updated) {
  2659. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  2660. 'roles' => json_encode($episode_roles, 256),
  2661. 'updated_at' => date('Y-m-d H:i:s'),
  2662. ]);
  2663. }
  2664. }
  2665. }
  2666. // 如果有单个分镜更新,检查是否有变化
  2667. if (!empty($segment_update_data)) {
  2668. // 获取当前分镜数据
  2669. $current_segment = DB::table('mp_episode_segments')
  2670. ->where('segment_id', $segment_id)
  2671. ->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')
  2672. ->first();
  2673. if ($current_segment) {
  2674. $current_segment = (array)$current_segment;
  2675. // 检查参数是否发生变化
  2676. $has_changed = false;
  2677. foreach ($segment_update_data as $field => $new_value) {
  2678. $old_value = getProp($current_segment, $field);
  2679. if ($old_value != $new_value) {
  2680. $has_changed = true;
  2681. break;
  2682. }
  2683. }
  2684. if ($has_changed) {
  2685. // 如果该分镜还未在列表中,添加进去
  2686. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  2687. $segment_ids_to_create_task[] = $segment_id;
  2688. $segments_data[$segment_id] = $current_segment;
  2689. }
  2690. // 更新分镜数据并清空音频URL
  2691. $segment_update_data['audio_url'] = '';
  2692. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  2693. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  2694. }
  2695. }
  2696. }
  2697. // 为所有有变化的分镜创建音频合成任务
  2698. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  2699. if (!empty($segment_ids_to_create_task)) {
  2700. foreach ($segment_ids_to_create_task as $sid) {
  2701. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  2702. if ($sid === $segment_id && $has_all_special_params) {
  2703. continue;
  2704. }
  2705. // 重新获取更新后的分镜数据
  2706. $updated_segment = DB::table('mp_episode_segments')
  2707. ->where('segment_id', $sid)
  2708. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  2709. ->first();
  2710. if (!$updated_segment) continue;
  2711. $updated_segment = (array)$updated_segment;
  2712. // 检查dialogue是否为空
  2713. $dialogue = getProp($updated_segment, 'dialogue');
  2714. if (empty($dialogue)) {
  2715. // dialogue为空时,直接写入默认音频信息
  2716. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  2717. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  2718. 'audio_duration' => 2.0,
  2719. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  2720. 'updated_at' => date('Y-m-d H:i:s')
  2721. ]);
  2722. continue;
  2723. }
  2724. $generate_json = [
  2725. 'text' => $dialogue,
  2726. 'role' => getProp($updated_segment, 'voice_actor'),
  2727. 'voice_type' => getProp($updated_segment, 'voice_type'),
  2728. 'voice_name' => getProp($updated_segment, 'voice_name'),
  2729. 'emotion' => getProp($updated_segment, 'emotion'),
  2730. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  2731. 'gender' => getProp($updated_segment, 'gender'),
  2732. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  2733. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  2734. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  2735. 'pitch' => getProp($updated_segment, 'pitch', 0),
  2736. ];
  2737. // 插入视频配音合成任务
  2738. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2739. 'alias_segment_id' => $sid,
  2740. 'generate_status' => '执行中',
  2741. 'audio_url' => '',
  2742. 'generate_json' => json_encode($generate_json, 256),
  2743. 'created_at' => date('Y-m-d H:i:s'),
  2744. 'updated_at' => date('Y-m-d H:i:s'),
  2745. ]);
  2746. if (!$dubTaskId) {
  2747. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  2748. continue;
  2749. }
  2750. // 将任务ID添加到Redis列表中
  2751. Redis::lpush('dub_video_task_queue', $dubTaskId);
  2752. // 请求远程服务器执行生成
  2753. try {
  2754. sleep(1);
  2755. $client = new Client(['timeout' => 300, 'verify' => false]);
  2756. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2757. $response = $result->getBody()->getContents();
  2758. $response_arr = json_decode($response, true);
  2759. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2760. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2761. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2762. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2763. }
  2764. } catch (\Exception $e) {
  2765. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2766. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2767. }
  2768. }
  2769. }
  2770. DB::commit();
  2771. } catch (\Exception $e) {
  2772. DB::rollBack();
  2773. Utils::throwError('20003:'.$e->getMessage());
  2774. }
  2775. return true;
  2776. }
  2777. public function episodePicsInfo($data) {
  2778. $anime_id = getProp($data, 'anime_id');
  2779. $episode_id = getProp($data, 'episode_id');
  2780. // 参数验证
  2781. if (!$anime_id && !$episode_id) {
  2782. Utils::throwError('20003:请提供动漫ID或分集ID');
  2783. }
  2784. // 根据参数获取数据源
  2785. if ($episode_id) {
  2786. // 从剧集表获取
  2787. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2788. if (!$source) Utils::throwError('20003:该剧集不存在');
  2789. $table_name = 'mp_anime_episodes';
  2790. $id_field = 'id';
  2791. $id_value = $episode_id;
  2792. // 获取剧集的anime_id用于继承全局数据
  2793. $anime_id = getProp($source, 'anime_id');
  2794. } else {
  2795. // 从动漫表获取
  2796. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  2797. if (!$source) Utils::throwError('20003:该动漫不存在');
  2798. $table_name = 'mp_animes';
  2799. $id_field = 'id';
  2800. $id_value = $anime_id;
  2801. }
  2802. $source = (array)$source;
  2803. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  2804. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  2805. // 如果是分集数据,需要处理继承和任务创建逻辑
  2806. if ($episode_id) {
  2807. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  2808. }
  2809. // 返回生成器函数,用于 SSE 流式输出
  2810. return function() use ($roles, $scenes, $table_name, $id_field, $id_value) {
  2811. $startTime = time();
  2812. $maxDuration = 600; // 10分钟超时
  2813. $checkInterval = 3; // 每3秒检查一次
  2814. // Redis 缓存键
  2815. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  2816. // 生成当前数据的哈希值用于比较
  2817. $generateHash = function($roles, $scenes) {
  2818. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes], JSON_UNESCAPED_UNICODE));
  2819. };
  2820. // 发送初始数据
  2821. $currentHash = $generateHash($roles, $scenes);
  2822. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  2823. echo "data: " . json_encode([
  2824. 'type' => 'init',
  2825. 'data' => [
  2826. 'roles' => $roles,
  2827. 'scenes' => $scenes,
  2828. 'start_time' => $startTime
  2829. ]
  2830. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  2831. ob_flush();
  2832. flush();
  2833. // 持续轮询任务状态
  2834. while (time() - $startTime < $maxDuration) {
  2835. $hasProcessing = false;
  2836. $updated = false;
  2837. // 检查角色任务状态
  2838. foreach ($roles as $index => &$role) {
  2839. $task_id = getProp($role, 'task_id');
  2840. $task_status = getProp($role, 'task_status');
  2841. $existing_url = getProp($role, 'url');
  2842. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  2843. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  2844. $hasProcessing = ($task_status === 'processing');
  2845. // 查询任务状态
  2846. $task = DB::table('mp_generate_pic_tasks')
  2847. ->where('id', $task_id)
  2848. ->select('id', 'status', 'result_url', 'error_message')
  2849. ->first();
  2850. if ($task) {
  2851. $task = (array)$task;
  2852. $status = getProp($task, 'status');
  2853. // 如果任务完成或失败
  2854. if (in_array($status, ['success', 'failed'])) {
  2855. $role['task_status'] = $status;
  2856. if ($status === 'success') {
  2857. $result_url = getProp($task, 'result_url');
  2858. if ($result_url) {
  2859. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  2860. if (is_array($result_urls) && !empty($result_urls[0])) {
  2861. $role['url'] = $result_urls[0];
  2862. }
  2863. }
  2864. }
  2865. $updated = true;
  2866. } else if ($status === 'processing') {
  2867. $hasProcessing = true;
  2868. }
  2869. }
  2870. }
  2871. }
  2872. // 检查场景任务状态
  2873. foreach ($scenes as $index => &$scene) {
  2874. $task_id = getProp($scene, 'task_id');
  2875. $task_status = getProp($scene, 'task_status');
  2876. $existing_url = getProp($scene, 'url');
  2877. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  2878. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  2879. $hasProcessing = ($task_status === 'processing');
  2880. // 查询任务状态
  2881. $task = DB::table('mp_generate_pic_tasks')
  2882. ->where('id', $task_id)
  2883. ->select('id', 'status', 'result_url', 'error_message')
  2884. ->first();
  2885. if ($task) {
  2886. $task = (array)$task;
  2887. $status = getProp($task, 'status');
  2888. // 如果任务完成或失败
  2889. if (in_array($status, ['success', 'failed'])) {
  2890. $scene['task_status'] = $status;
  2891. if ($status === 'success') {
  2892. $result_url = getProp($task, 'result_url');
  2893. if ($result_url) {
  2894. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  2895. if (is_array($result_urls) && !empty($result_urls[0])) {
  2896. $scene['url'] = $result_urls[0];
  2897. }
  2898. }
  2899. }
  2900. $updated = true;
  2901. } else if ($status === 'processing') {
  2902. $hasProcessing = true;
  2903. }
  2904. }
  2905. }
  2906. }
  2907. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  2908. if ($updated) {
  2909. $newHash = $generateHash($roles, $scenes);
  2910. $cachedHash = Redis::get($cacheKey);
  2911. // 只有当数据真正变化时才更新数据库和发送事件
  2912. if ($newHash !== $cachedHash) {
  2913. try {
  2914. // 更新数据库
  2915. DB::table($table_name)->where($id_field, $id_value)->update([
  2916. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  2917. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  2918. 'updated_at' => date('Y-m-d H:i:s')
  2919. ]);
  2920. // 更新缓存
  2921. Redis::setex($cacheKey, 600, $newHash);
  2922. // 发送更新事件
  2923. echo "data: " . json_encode([
  2924. 'type' => 'update',
  2925. 'data' => [
  2926. 'roles' => $roles,
  2927. 'scenes' => $scenes,
  2928. 'elapsed_time' => time() - $startTime
  2929. ]
  2930. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  2931. ob_flush();
  2932. flush();
  2933. } catch (\Exception $e) {
  2934. dLog('anime')->error('更新角色/场景信息失败: ' . $e->getMessage());
  2935. }
  2936. } else {
  2937. // 即使哈希相同,如果有URL更新也要发送事件
  2938. $hasUrlUpdate = false;
  2939. foreach ($roles as $role) {
  2940. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  2941. $hasUrlUpdate = true;
  2942. break;
  2943. }
  2944. }
  2945. if (!$hasUrlUpdate) {
  2946. foreach ($scenes as $scene) {
  2947. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  2948. $hasUrlUpdate = true;
  2949. break;
  2950. }
  2951. }
  2952. }
  2953. if ($hasUrlUpdate) {
  2954. // 强制更新数据库和发送事件
  2955. try {
  2956. DB::table($table_name)->where($id_field, $id_value)->update([
  2957. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  2958. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  2959. 'updated_at' => date('Y-m-d H:i:s')
  2960. ]);
  2961. // 更新缓存
  2962. Redis::setex($cacheKey, 600, $newHash);
  2963. // 发送更新事件
  2964. echo "data: " . json_encode([
  2965. 'type' => 'update',
  2966. 'data' => [
  2967. 'roles' => $roles,
  2968. 'scenes' => $scenes,
  2969. 'elapsed_time' => time() - $startTime
  2970. ]
  2971. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  2972. ob_flush();
  2973. flush();
  2974. } catch (\Exception $e) {
  2975. dLog('anime')->error('强制更新角色/场景信息失败: ' . $e->getMessage());
  2976. }
  2977. }
  2978. }
  2979. }
  2980. // 如果所有任务都已完成,发送完成事件并退出
  2981. if (!$hasProcessing) {
  2982. // 查询数据库中的最终数据,确保返回最新的完整数据
  2983. try {
  2984. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  2985. if ($finalSource) {
  2986. $finalSource = (array)$finalSource;
  2987. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  2988. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  2989. // 使用数据库中的最终数据
  2990. $roles = $finalRoles;
  2991. $scenes = $finalScenes;
  2992. }
  2993. } catch (\Exception $e) {
  2994. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  2995. // 如果查询失败,继续使用内存中的数据
  2996. }
  2997. // 清理缓存
  2998. Redis::del($cacheKey);
  2999. echo "data: " . json_encode([
  3000. 'type' => 'completed',
  3001. 'data' => [
  3002. 'roles' => $roles,
  3003. 'scenes' => $scenes,
  3004. 'total_time' => time() - $startTime
  3005. ]
  3006. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3007. ob_flush();
  3008. flush();
  3009. break;
  3010. }
  3011. // 等待下次检查
  3012. sleep($checkInterval);
  3013. }
  3014. // 超时处理
  3015. if (time() - $startTime >= $maxDuration) {
  3016. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3017. try {
  3018. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3019. if ($finalSource) {
  3020. $finalSource = (array)$finalSource;
  3021. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3022. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3023. // 使用数据库中的最终数据
  3024. $roles = $finalRoles;
  3025. $scenes = $finalScenes;
  3026. }
  3027. } catch (\Exception $e) {
  3028. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3029. // 如果查询失败,继续使用内存中的数据
  3030. }
  3031. // 清理缓存
  3032. Redis::del($cacheKey);
  3033. echo "data: " . json_encode([
  3034. 'type' => 'timeout',
  3035. 'message' => '轮询超时,请刷新页面查看最新状态',
  3036. 'data' => [
  3037. 'roles' => $roles,
  3038. 'scenes' => $scenes
  3039. ]
  3040. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3041. ob_flush();
  3042. flush();
  3043. }
  3044. };
  3045. }
  3046. public function clipSegmentVideo($data) {
  3047. $segment_id = getProp($data, 'segment_id');
  3048. $video_time_point_start = getProp($data, 'video_time_point_start');
  3049. $video_time_point_end = getProp($data, 'video_time_point_end');
  3050. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3051. Utils::throwError('20003:参数异常');
  3052. }
  3053. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3054. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3055. }
  3056. $video_duration = $video_time_point_end - $video_time_point_start;
  3057. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3058. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3059. 'video_duration' => $video_duration,
  3060. 'video_time_point_start' => $video_time_point_start,
  3061. 'video_time_point_end' => $video_time_point_end,
  3062. 'updated_at' => date('Y-m-d H:i:s')
  3063. ]);
  3064. }
  3065. // 轮训获取图片任务结果
  3066. private function loopGetPicTaskResult($task_id) {
  3067. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3068. if (!$task) {
  3069. return '';
  3070. }
  3071. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3072. $model = getProp($task, 'model');
  3073. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3074. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3075. $isSyncModel = $isVolcModel || $isGptModel;
  3076. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3077. $start_count = 0;
  3078. $img_url = '';
  3079. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3080. sleep(3);
  3081. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3082. // 如果任务已经完成,直接返回结果
  3083. if ($task->status === 'success' && $task->result_url) {
  3084. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3085. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3086. }
  3087. // 如果任务已失败,返回空
  3088. if ($task->status === 'failed') {
  3089. return '';
  3090. }
  3091. if ($isSyncModel) continue;
  3092. // 查询任务状态
  3093. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3094. if ($statusInfo['status'] === 'success') {
  3095. $task->updateStatus('success', [
  3096. 'result_url' => $statusInfo['result_url'],
  3097. 'result_json' => $statusInfo['result_json'] ?? []
  3098. ]);
  3099. // 同步调整分镜图片状态和结果
  3100. if (getProp($task, 'alias_segment_id')) {
  3101. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3102. 'img_url' => $statusInfo['result_url'][0],
  3103. 'pic_task_status' => '已完成',
  3104. ]);
  3105. }
  3106. $img_url = $statusInfo['result_url'][0];
  3107. break;
  3108. } elseif ($statusInfo['status'] === 'failed') {
  3109. $task->updateStatus('failed', [
  3110. 'error_message' => $statusInfo['error_message'],
  3111. 'result_json' => $statusInfo['result_json'] ?? []
  3112. ]);
  3113. if (getProp($task, 'alias_segment_id')) {
  3114. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3115. 'pic_task_status' => '失败',
  3116. ]);
  3117. }
  3118. break;
  3119. }
  3120. $start_count++;
  3121. }
  3122. return $img_url;
  3123. }
  3124. /**
  3125. * 从分镜内容中提取涉及的角色
  3126. */
  3127. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3128. $found_characters = [];
  3129. foreach ($available_characters as $character) {
  3130. // 检查角色名称是否在分镜内容中出现
  3131. if (strpos($segment_content, $character) !== false) {
  3132. $found_characters[] = $character;
  3133. }
  3134. }
  3135. if (!$found_characters) {
  3136. foreach ($roles as $character) {
  3137. // 检查角色名称是否在分镜内容中出现
  3138. if (strpos($segment_content, $character) !== false) {
  3139. $found_characters[] = $character;
  3140. }
  3141. }
  3142. }
  3143. return array_unique($found_characters);
  3144. }
  3145. // 从分镜剧本中提取关键字段
  3146. private function handleSegmentContent(&$data) {
  3147. $segmentContent = getProp($data, 'segment_content');
  3148. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3149. $segmentData = [
  3150. 'description' => '',
  3151. 'composition' => '',
  3152. 'camera_movement' => '',
  3153. 'voice_actor' => '',
  3154. 'dialogue' => '',
  3155. 'frame_type' => '',
  3156. 'scene' => '', // 场景
  3157. 'characters' => '', // 出镜角色
  3158. 'tail_frame' => '', // 尾帧描述
  3159. 'emotion' => '中性', // 情感
  3160. 'gender' => '0', // 性别(0未知,1男,2女)
  3161. 'speed_ratio' => 0, // 语速
  3162. 'loudness_ratio' => 0, // 音量
  3163. 'emotion_scale' => 4, // 情感强度
  3164. 'pitch' => 0, // 音调
  3165. ];
  3166. // 用于存储需要从 segment_content 中移除的匹配项
  3167. $replaceEmptyArr = [];
  3168. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3169. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3170. $segmentData['description'] = trim($descMatch[1]);
  3171. $data['description'] = trim($descMatch[1]);
  3172. }
  3173. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3174. $segmentData['composition'] = trim($compMatch[1]);
  3175. $data['composition'] = trim($compMatch[1]);
  3176. }
  3177. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3178. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3179. $data['camera_movement'] = trim($cameraMatch[1]);
  3180. }
  3181. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3182. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3183. $data['voice_actor'] = trim($voiceMatch[1]);
  3184. }
  3185. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3186. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3187. $data['dialogue'] = trim($dialogueMatch[1]);
  3188. }
  3189. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3190. $segmentData['frame_type'] = trim($frameMatch[1]);
  3191. $data['frame_type'] = trim($frameMatch[1]);
  3192. }
  3193. // 场景字段
  3194. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3195. $segmentData['scene'] = trim($sceneMatch[1]);
  3196. $data['scene'] = trim($sceneMatch[1]);
  3197. }
  3198. // 出镜角色字段
  3199. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3200. $segmentData['characters'] = trim($charactersMatch[1]);
  3201. $data['characters'] = trim($charactersMatch[1]);
  3202. }
  3203. // 尾帧描述字段
  3204. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3205. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3206. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3207. }
  3208. // 情感字段
  3209. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3210. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3211. $segmentData['emotion'] = trim($emotionMatch[1]);
  3212. $data['emotion'] = trim($emotionMatch[1]);
  3213. }
  3214. // 性别字段
  3215. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3216. $replaceEmptyArr[] = trim($genderMatch[0]);
  3217. $genderStr = trim($genderMatch[1]);
  3218. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3219. $segmentData['gender'] = '1';
  3220. $data['gender'] = '1';
  3221. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3222. $segmentData['gender'] = '2';
  3223. $data['gender'] = '2';
  3224. } else {
  3225. $segmentData['gender'] = '0';
  3226. $data['gender'] = '0';
  3227. }
  3228. }
  3229. // 语速字段
  3230. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3231. $replaceEmptyArr[] = trim($speedMatch[0]);
  3232. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3233. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3234. }
  3235. // 音量字段
  3236. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3237. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3238. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3239. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3240. }
  3241. // 情感强度字段
  3242. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3243. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3244. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3245. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3246. }
  3247. // 音调字段
  3248. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3249. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3250. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3251. $data['pitch'] = (int)trim($pitchMatch[1]);
  3252. }
  3253. // 从 segment_content 中移除已提取的配音参数字段
  3254. if (!empty($replaceEmptyArr)) {
  3255. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3256. }
  3257. // 如果有配音角色,查询音色信息并验证情感
  3258. $voice_actor = $segmentData['voice_actor'];
  3259. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3260. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3261. $anime_id = getProp($data, 'anime_id');
  3262. $episode_id = getProp($data, 'episode_id');
  3263. // 优先从剧集的角色列表中查找
  3264. $roles = [];
  3265. if ($episode_id) {
  3266. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3267. if ($episode && getProp($episode, 'roles')) {
  3268. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3269. }
  3270. }
  3271. // 如果剧集中没有,从动漫的角色列表中查找
  3272. if (empty($roles) && $anime_id) {
  3273. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3274. if ($anime && getProp($anime, 'roles')) {
  3275. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3276. }
  3277. }
  3278. // 查找匹配的角色音色信息
  3279. $timbre_info = null;
  3280. foreach ($roles as $role) {
  3281. if (getProp($role, 'role') === $voice_actor) {
  3282. $timbre_info = $role;
  3283. break;
  3284. }
  3285. }
  3286. // 如果找到音色信息,添加到数据中
  3287. if ($timbre_info) {
  3288. $voice_type = getProp($timbre_info, 'voice_type');
  3289. $voice_name = getProp($timbre_info, 'voice_name');
  3290. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3291. if ($voice_type) {
  3292. $data['voice_type'] = $voice_type;
  3293. $segmentData['voice_type'] = $voice_type;
  3294. }
  3295. if ($voice_name) {
  3296. $data['voice_name'] = $voice_name;
  3297. $segmentData['voice_name'] = $voice_name;
  3298. }
  3299. if ($voice_audio_url) {
  3300. $data['voice_audio_url'] = $voice_audio_url;
  3301. $segmentData['voice_audio_url'] = $voice_audio_url;
  3302. }
  3303. // 验证情感是否在音色支持的情感列表中
  3304. if ($voice_type) {
  3305. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3306. if ($timbre_emotion) {
  3307. $timbre_emotion = explode(',', $timbre_emotion);
  3308. } else {
  3309. $timbre_emotion = [];
  3310. }
  3311. $emotion = getProp($segmentData, 'emotion', '中性');
  3312. if (!in_array($emotion, $timbre_emotion)) {
  3313. $emotion = '中性';
  3314. }
  3315. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3316. $emotion_list = array_flip($emotion_list);
  3317. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3318. $data['emotion_type'] = $emotion_type;
  3319. $segmentData['emotion_type'] = $emotion_type;
  3320. }
  3321. }
  3322. }
  3323. return $segmentData;
  3324. }
  3325. public function createSegmentVideoTask($data) {
  3326. $segment_id = getProp($data, 'segment_id');
  3327. $tail_frame = getProp($data, 'tail_frame');
  3328. $first_frame_url = getProp($data, 'first_frame_url');
  3329. $tail_frame_url = getProp($data, 'tail_frame_url');
  3330. $generate_audio = getProp($data, 'generate_audio', 0);
  3331. if (!$segment_id) {
  3332. Utils::throwError('1002:分镜ID不能为空');
  3333. }
  3334. // 获取分镜信息
  3335. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3336. if (!$segment) {
  3337. Utils::throwError('20003:分镜不存在');
  3338. }
  3339. $segment = (array)$segment;
  3340. $episode_id = getProp($segment, 'episode_id');
  3341. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3342. if (!$ratio) $ratio = '9:16';
  3343. // 获取分镜内容
  3344. $segmentContent = getProp($segment, 'segment_content', '');
  3345. // 检查 $segmentContent 中是否已有尾帧描述
  3346. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3347. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3348. $finalTailFrame = '';
  3349. if ($tail_frame) {
  3350. // 用户输入了尾帧描述,优先使用
  3351. $finalTailFrame = $tail_frame;
  3352. // 如果 segmentContent 中已有尾帧描述,需要替换
  3353. if ($contentHasTailFrame) {
  3354. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3355. }
  3356. } elseif ($contentHasTailFrame) {
  3357. // segmentContent 中有尾帧描述,使用它
  3358. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3359. } else {
  3360. // 两者都没有,使用分镜表中的尾帧描述
  3361. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3362. }
  3363. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3364. $hasDialogue = false;
  3365. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3366. $dialogue = trim($dialogueMatch[1]);
  3367. // 如果台词不为空且不是"无"
  3368. if (!empty($dialogue) && $dialogue !== '无') {
  3369. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3370. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3371. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3372. $hasDialogue = true;
  3373. }
  3374. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3375. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3376. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3377. if (!preg_match('/^[“]/', $dialogue)) {
  3378. $dialogue = '“' . $dialogue;
  3379. }
  3380. if (!preg_match('/[”]$/', $dialogue)) {
  3381. $dialogue .= '”';
  3382. }
  3383. // 将修改后的台词替换回 $segmentContent
  3384. $originalDialogue = $dialogueMatch[1];
  3385. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3386. }
  3387. }
  3388. // 构建完整的提示词
  3389. $fullPrompt = $segmentContent;
  3390. if ($finalTailFrame && !$contentHasTailFrame) {
  3391. // 只有当 segmentContent 中没有尾帧描述时才追加
  3392. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3393. }
  3394. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3395. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3396. $fullPrompt = trim($fullPrompt);
  3397. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3398. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3399. // 智能选择视频时长
  3400. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3401. $videoDuration = -1;
  3402. // 处理视频模型
  3403. $model = getProp($data, 'model');
  3404. if (!$model) {
  3405. // 用户没有输入,从episode表获取
  3406. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3407. $model = getProp($episode, 'video_model');
  3408. if (!$model) {
  3409. // episode表也没有,使用默认值
  3410. $model = 'doubao-seedance-1-5-pro-251215';
  3411. }
  3412. }
  3413. // 验证模型是否在可用模型表中
  3414. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3415. $model = 'doubao-seedance-1-5-pro-251215';
  3416. }
  3417. // 保存到episode表
  3418. $episode_id = getProp($segment, 'episode_id');
  3419. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3420. 'video_model' => $model,
  3421. 'updated_at' => date('Y-m-d H:i:s')
  3422. ]);
  3423. // 构建视频生成参数
  3424. $videoParams = [
  3425. 'model' => $model,
  3426. 'alias_segment_id' => $segment_id,
  3427. 'prompt' => trim($fullPrompt),
  3428. 'video_duration' => $videoDuration,
  3429. 'video_resolution' => '720P',
  3430. 'seed' => -1,
  3431. 'ratio' => $ratio,
  3432. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3433. 'draft' => false,
  3434. 'watermark' => false,
  3435. 'camera_fixed' => false,
  3436. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3437. ];
  3438. // 如果分镜有图片,作为首帧
  3439. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3440. $hasVideo = !empty(getProp($segment, 'video_url'));
  3441. if ($hasImage) {
  3442. if ($first_frame_url) {
  3443. $videoParams['first_frame_url'] = $first_frame_url;
  3444. }else {
  3445. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3446. }
  3447. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3448. }
  3449. // 构建content数组
  3450. $videoParams['content'] = [
  3451. [
  3452. 'type' => 'text',
  3453. 'text' => $videoParams['prompt'],
  3454. ]
  3455. ];
  3456. // 如果有首帧图片,添加到content中
  3457. if ($hasImage) {
  3458. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3459. $videoParams['content'][] = [
  3460. 'type' => 'image_url',
  3461. 'image_url' => [
  3462. 'url' => $videoParams['first_frame_url'],
  3463. ],
  3464. 'role' => 'reference_image',
  3465. ];
  3466. if (isset($videoParams['tail_frame_url'])) {
  3467. $videoParams['content'][] = [
  3468. 'type' => 'image_url',
  3469. 'image_url' => [
  3470. 'url' => $videoParams['tail_frame_url'],
  3471. ],
  3472. 'role' => 'reference_image',
  3473. ];
  3474. }
  3475. }else {
  3476. $videoParams['content'][] = [
  3477. 'type' => 'image_url',
  3478. 'image_url' => [
  3479. 'url' => $videoParams['first_frame_url'],
  3480. ],
  3481. 'role' => 'first_frame',
  3482. ];
  3483. if (isset($videoParams['tail_frame_url'])) {
  3484. $videoParams['content'][] = [
  3485. 'type' => 'image_url',
  3486. 'image_url' => [
  3487. 'url' => $videoParams['tail_frame_url'],
  3488. ],
  3489. 'role' => 'last_frame',
  3490. ];
  3491. }
  3492. }
  3493. }
  3494. // 获取配音音频URL
  3495. $audioUrl = getProp($segment, 'audio_url');
  3496. $audioDuration = getProp($segment, 'audio_duration');
  3497. // 音频传入的前提:必须有至少一张图片或一个视频
  3498. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  3499. // dd($videoParams);
  3500. // 根据模型选择不同的视频生成方法
  3501. if (strpos($model, 'jimeng') !== false) {
  3502. // 即梦模型参数调整
  3503. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  3504. unset($videoParams['content']); // 即梦不使用content格式
  3505. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  3506. } elseif (strpos($model, 'kling') !== false) {
  3507. // Keling模型参数调整
  3508. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  3509. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  3510. unset($videoParams['ratio']);
  3511. unset($videoParams['content']); // Keling不使用content格式
  3512. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  3513. } elseif (strpos($model, 'zhizhen') !== false) {
  3514. // 智帧20等新模型使用统一API
  3515. // 构建统一API参数
  3516. $unifiedParams = [
  3517. 'model_code' => $model,
  3518. 'alias_segment_id' => $segment_id,
  3519. 'prompt' => trim($fullPrompt),
  3520. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  3521. 'video_resolution' => strtolower($videoParams['video_resolution']),
  3522. 'video_ratio' => $ratio,
  3523. 'seed' => -1,
  3524. ];
  3525. // 构建parameters参数
  3526. $parameters = [
  3527. 'seconds' => $unifiedParams['video_duration'],
  3528. 'resolution' => $unifiedParams['video_resolution'],
  3529. 'ratio' => $ratio,
  3530. // 'video_mode' => 'multi_image',
  3531. // 'mode' => 'multi_image',
  3532. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  3533. ];
  3534. $hasImage = false;
  3535. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  3536. if ($hasImage) {
  3537. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  3538. if (isset($videoParams['tail_frame_url'])) {
  3539. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  3540. }
  3541. // 只有在有图片的情况下才能添加参考音频
  3542. if ($audioUrl) {
  3543. // $parameters['reference_audios'] = [$audioUrl];
  3544. }
  3545. } else {
  3546. // 没有图片时,记录错误日志
  3547. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  3548. 'segment_id' => $segment_id,
  3549. 'model' => $model
  3550. ]);
  3551. }
  3552. $unifiedParams['parameters'] = $parameters;
  3553. // 调用统一API创建任务
  3554. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  3555. } else {
  3556. // Seedance模型(默认)
  3557. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  3558. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3559. // 添加配音音频到content中
  3560. $videoParams['content'][] = [
  3561. 'type' => 'audio_url',
  3562. 'audio_url' => [
  3563. 'url' => $audioUrl,
  3564. ],
  3565. 'role' => 'reference_audio',
  3566. ];
  3567. // 优化提示词,增加音频相关描述
  3568. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  3569. $videoParams['prompt'] = $audioPrompt;
  3570. $videoParams['content'][0]['text'] = $audioPrompt;
  3571. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  3572. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  3573. }
  3574. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  3575. }
  3576. // 更新分镜表的视频任务信息
  3577. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3578. 'video_task_id' => $task->id,
  3579. 'video_task_status' => '生成中',
  3580. 'generate_audio' => $generate_audio,
  3581. 'updated_at' => date('Y-m-d H:i:s')
  3582. ]);
  3583. return [
  3584. 'task_id' => $task->id,
  3585. 'status' => $task->status,
  3586. 'segment_id' => $segment_id,
  3587. 'video_duration' => $videoDuration
  3588. ];
  3589. }
  3590. public function createActVideoTask($data) {
  3591. $act_id = getProp($data, 'act_id');
  3592. $first_frame_url = getProp($data, 'first_frame_url');
  3593. $tail_frame_url = getProp($data, 'tail_frame_url');
  3594. $generate_audio = getProp($data, 'generate_audio', 1);
  3595. $video_duration = getProp($data, 'video_duration');
  3596. $video_resolution = getProp($data, 'video_resolution');
  3597. $ratio = getProp($data, 'ratio');
  3598. $products = getProp($data, 'products', []);
  3599. $reference_images = array_unique(getProp($data, 'reference_images', []));
  3600. if (!is_array($reference_images) || !is_array($products)) {
  3601. Utils::throwError('20003:传入的参考图或资产格式不正确');
  3602. }
  3603. if (!$act_id) {
  3604. Utils::throwError('1002:片段ID不能为空');
  3605. }
  3606. // 获取片段信息
  3607. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  3608. if (!$act) {
  3609. Utils::throwError('20003:片段不存在');
  3610. }
  3611. $act = (array)$act;
  3612. $anime_id = getProp($act, 'anime_id');
  3613. $episode_id = getProp($act, 'episode_id');
  3614. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3615. $ace_mode = getProp($anime, 'ace_mode');
  3616. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3617. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  3618. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  3619. // 将资产中新出现的资产放到extra_products中
  3620. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles和scenes做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  3621. if (!empty($products) && $episode) {
  3622. // 获取剧集中的角色和场景列表
  3623. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  3624. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  3625. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  3626. // 构建角色名称列表
  3627. $role_names = array_column($roles, 'role');
  3628. // 构建场景名称列表
  3629. $scene_names = array_column($scenes, 'scene');
  3630. // 遍历传入的products
  3631. foreach ($products as $product) {
  3632. $product_name = getProp($product, 'product_name');
  3633. // 如果product_name不在roles和scenes中
  3634. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names)) {
  3635. // 查找是否在extra_products中存在同名的
  3636. $found = false;
  3637. foreach ($extra_products as $key => $extra_product) {
  3638. if (getProp($extra_product, 'product_name') === $product_name) {
  3639. // 有同名的则覆盖
  3640. $extra_products[$key] = $product;
  3641. $found = true;
  3642. break;
  3643. }
  3644. }
  3645. // 没有则新增
  3646. if (!$found) {
  3647. $extra_products[] = $product;
  3648. }
  3649. }
  3650. }
  3651. if ($extra_products) {
  3652. // 保存到数据库
  3653. DB::table('mp_anime_episodes')
  3654. ->where('id', $episode_id)
  3655. ->update([
  3656. 'extra_products' => json_encode($extra_products, 256),
  3657. 'updated_at' => date('Y-m-d H:i:s')
  3658. ]);
  3659. }
  3660. }
  3661. // 获取分镜内容
  3662. $actContent = getProp($act, 'act_show_content', '');
  3663. // 音效同出(默认使用)
  3664. $current_generate_audio = $generate_audio ? 1 : 0;
  3665. // 构建完整的提示词
  3666. $processResult = $this->processActContentWithProducts($actContent, $products);
  3667. $fullPrompt = $processResult['content'];
  3668. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  3669. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  3670. // 处理视频模型
  3671. $model = getProp($data, 'model');
  3672. if (!$model) {
  3673. $model = getProp($episode, 'video_model');
  3674. if (!$model) {
  3675. // episode表也没有,使用默认值
  3676. $model = 'zhizhen-20-mini';
  3677. }
  3678. }
  3679. // 验证模型是否在可用模型表中
  3680. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3681. $model = 'zhizhen-20-mini';
  3682. }
  3683. // 保存到episode表
  3684. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3685. 'video_model' => $model,
  3686. 'updated_at' => date('Y-m-d H:i:s')
  3687. ]);
  3688. // 构建视频生成参数
  3689. $videoParams = [
  3690. 'model' => $model,
  3691. 'alias_act_id' => $act_id,
  3692. 'prompt' => trim($fullPrompt),
  3693. 'video_duration' => $videoDuration,
  3694. 'video_resolution' => $video_resolution,
  3695. 'seed' => -1,
  3696. 'ratio' => $ratio,
  3697. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3698. 'draft' => false,
  3699. 'watermark' => false,
  3700. 'camera_fixed' => false,
  3701. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3702. ];
  3703. // 如果分镜有图片,作为首帧
  3704. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  3705. $hasVideo = !empty(getProp($act, 'video_url'));
  3706. if ($hasImage) {
  3707. if ($first_frame_url) {
  3708. $videoParams['first_frame_url'] = $first_frame_url;
  3709. }else {
  3710. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  3711. }
  3712. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3713. }
  3714. // 构建content数组
  3715. $videoParams['content'] = [
  3716. [
  3717. 'type' => 'text',
  3718. 'text' => $videoParams['prompt'],
  3719. ]
  3720. ];
  3721. // 如果有首帧图片,添加到content中
  3722. if ($hasImage) {
  3723. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3724. $videoParams['content'][] = [
  3725. 'type' => 'image_url',
  3726. 'image_url' => [
  3727. 'url' => $videoParams['first_frame_url'],
  3728. ],
  3729. 'role' => 'reference_image',
  3730. ];
  3731. if (isset($videoParams['tail_frame_url'])) {
  3732. $videoParams['content'][] = [
  3733. 'type' => 'image_url',
  3734. 'image_url' => [
  3735. 'url' => $videoParams['tail_frame_url'],
  3736. ],
  3737. 'role' => 'reference_image',
  3738. ];
  3739. }
  3740. }else {
  3741. $videoParams['content'][] = [
  3742. 'type' => 'image_url',
  3743. 'image_url' => [
  3744. 'url' => $videoParams['first_frame_url'],
  3745. ],
  3746. 'role' => 'first_frame',
  3747. ];
  3748. if (isset($videoParams['tail_frame_url'])) {
  3749. $videoParams['content'][] = [
  3750. 'type' => 'image_url',
  3751. 'image_url' => [
  3752. 'url' => $videoParams['tail_frame_url'],
  3753. ],
  3754. 'role' => 'last_frame',
  3755. ];
  3756. }
  3757. }
  3758. }
  3759. // dd($videoParams);
  3760. // 根据模型选择不同的视频生成方法
  3761. if (strpos($model, 'jimeng') !== false) {
  3762. // 即梦模型参数调整
  3763. unset($videoParams['content']); // 即梦不使用content格式
  3764. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  3765. } elseif (strpos($model, 'kling') !== false) {
  3766. // Keling模型参数调整
  3767. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  3768. unset($videoParams['ratio']);
  3769. unset($videoParams['content']); // Keling不使用content格式
  3770. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  3771. } elseif (strpos($model, 'zhizhen') !== false) {
  3772. // 智帧20等新模型使用统一API
  3773. // 构建统一API参数
  3774. $unifiedParams = [
  3775. 'model_code' => $model,
  3776. 'alias_act_id' => $act_id,
  3777. 'prompt' => trim($fullPrompt),
  3778. 'video_duration' => $videoDuration,
  3779. 'video_resolution' => strtolower($videoParams['video_resolution']),
  3780. 'video_ratio' => $ratio,
  3781. 'seed' => -1,
  3782. ];
  3783. // 构建parameters参数
  3784. $parameters = [
  3785. 'seconds' => $unifiedParams['video_duration'],
  3786. 'resolution' => $unifiedParams['video_resolution'],
  3787. 'ratio' => $ratio,
  3788. // 'video_mode' => 'multi_image',
  3789. // 'mode' => 'multi_image',
  3790. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  3791. ];
  3792. $hasImage = false;
  3793. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  3794. if ($hasImage) {
  3795. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  3796. if (isset($videoParams['tail_frame_url'])) {
  3797. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  3798. }
  3799. } else {
  3800. // 没有图片时,记录错误日志
  3801. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  3802. 'act_id' => $act_id,
  3803. 'model' => $model
  3804. ]);
  3805. }
  3806. if ($reference_images) {
  3807. // 限制只传入9张参考图
  3808. $reference_images = array_slice($reference_images, 0, 9);
  3809. // 在处理之前先保存原始reference_images到任务参数中
  3810. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  3811. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  3812. $parameters['reference_images'] = $reference_images;
  3813. $parameters['video_mode'] = 'multi_image';
  3814. $parameters['mode'] = 'multi_image';
  3815. }
  3816. $unifiedParams['parameters'] = $parameters;
  3817. // 调用统一API创建任务
  3818. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  3819. } else {
  3820. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  3821. }
  3822. // 更新分镜表的视频任务信息
  3823. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  3824. 'video_task_id' => $task->id,
  3825. 'video_task_status' => '生成中',
  3826. 'generate_audio' => $generate_audio,
  3827. 'updated_at' => date('Y-m-d H:i:s')
  3828. ]);
  3829. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  3830. $episode_number = getProp($act, 'episode_number');
  3831. $act_number = getProp($act, 'act_number');
  3832. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  3833. Redis::sadd('anime_act_first_frame_urls', $act_id);
  3834. }
  3835. return [
  3836. 'task_id' => $task->id,
  3837. 'status' => $task->status,
  3838. 'act_id' => $act_id,
  3839. 'video_duration' => $videoDuration
  3840. ];
  3841. }
  3842. /**
  3843. * 根据提示词内容智能计算最优视频时长
  3844. *
  3845. * @param string $segmentContent 分镜内容
  3846. * @param string $tailFrame 尾帧描述
  3847. * @return int 视频时长(2-12秒)
  3848. */
  3849. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  3850. // 合并所有文本内容
  3851. $fullText = trim($segmentContent . ' ' . $tailFrame);
  3852. // 如果没有内容,返回默认时长
  3853. if (empty($fullText)) {
  3854. return 5;
  3855. }
  3856. // 计算文本长度(中文字符按2个字符计算)
  3857. $textLength = mb_strlen($fullText, 'UTF-8');
  3858. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  3859. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  3860. // 分析内容复杂度
  3861. $complexityScore = $this->analyzeContentComplexity($fullText);
  3862. // 基础时长计算(根据文本长度)
  3863. $baseDuration = 3; // 默认2秒
  3864. // if ($adjustedLength <= 20) {
  3865. // $baseDuration = 3;
  3866. // } elseif ($adjustedLength <= 40) {
  3867. // $baseDuration = 4;
  3868. // } elseif ($adjustedLength <= 60) {
  3869. // $baseDuration = 5;
  3870. // } elseif ($adjustedLength <= 80) {
  3871. // $baseDuration = 6;
  3872. // } elseif ($adjustedLength <= 100) {
  3873. // $baseDuration = 7;
  3874. // } elseif ($adjustedLength <= 120) {
  3875. // $baseDuration = 8;
  3876. // } else {
  3877. // $baseDuration = 9;
  3878. // }
  3879. // 根据内容复杂度调整时长
  3880. $finalDuration = $baseDuration + $complexityScore;
  3881. // 确保时长在2-12秒范围内
  3882. return max(4, min(12, $finalDuration));
  3883. }
  3884. /**
  3885. * 分析内容复杂度,返回时长调整值
  3886. *
  3887. * @param string $text 文本内容
  3888. * @return int 调整值(-2到+3)
  3889. */
  3890. private function analyzeContentComplexity($text) {
  3891. $score = 0;
  3892. // 动作关键词(需要更长时间展现)
  3893. $actionKeywords = [
  3894. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  3895. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  3896. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  3897. ];
  3898. // 静态关键词(可以用较短时间)
  3899. $staticKeywords = [
  3900. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  3901. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  3902. ];
  3903. // 复杂场景关键词(需要更长时间)
  3904. $complexSceneKeywords = [
  3905. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  3906. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  3907. ];
  3908. // 情感关键词(需要适中时间表现)
  3909. $emotionKeywords = [
  3910. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  3911. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  3912. ];
  3913. // 检查动作关键词
  3914. foreach ($actionKeywords as $keyword) {
  3915. if (strpos($text, $keyword) !== false) {
  3916. $score += 1;
  3917. break; // 避免重复加分
  3918. }
  3919. }
  3920. // 检查静态关键词
  3921. foreach ($staticKeywords as $keyword) {
  3922. if (strpos($text, $keyword) !== false) {
  3923. $score -= 1;
  3924. break;
  3925. }
  3926. }
  3927. // 检查复杂场景关键词
  3928. foreach ($complexSceneKeywords as $keyword) {
  3929. if (strpos($text, $keyword) !== false) {
  3930. $score += 1;
  3931. break;
  3932. }
  3933. }
  3934. // 检查情感关键词
  3935. foreach ($emotionKeywords as $keyword) {
  3936. if (strpos($text, $keyword) !== false) {
  3937. $score += 1;
  3938. break;
  3939. }
  3940. }
  3941. // 检查时间相关词汇
  3942. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  3943. $score += 1;
  3944. }
  3945. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  3946. $score -= 1;
  3947. }
  3948. // 检查转场词汇
  3949. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  3950. $score += 1;
  3951. }
  3952. // 检查环境描述(复杂环境需要更多时间)
  3953. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  3954. $score += 1;
  3955. }
  3956. // 检查对话内容(对话需要更多时间)
  3957. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  3958. $score += 1;
  3959. }
  3960. // 限制调整范围
  3961. return max(-1, min(4, $score));
  3962. }
  3963. /**
  3964. * 创建完整视频合成任务
  3965. *
  3966. * @param array $data
  3967. * @return array
  3968. */
  3969. public function createCompleteVideoTask($data)
  3970. {
  3971. $animeId = getProp($data, 'anime_id');
  3972. $episodeId = getProp($data, 'episode_id');
  3973. // 验证参数
  3974. if (!$animeId || !$episodeId) {
  3975. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  3976. }
  3977. // 检查是否已存在处理中的任务
  3978. $existingTask = DB::table('mp_complete_video_tasks')
  3979. ->where('anime_id', $animeId)
  3980. ->where('episode_id', $episodeId)
  3981. ->whereIn('generate_status', ['执行中'])
  3982. ->first();
  3983. if ($existingTask) {
  3984. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  3985. }
  3986. // 获取全能模式状态
  3987. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  3988. if ((int)$ace_mode === 1) {
  3989. // 获取所有片段的配音视频,按 act_number 排序
  3990. $segments = DB::table('mp_episode_segments')
  3991. ->where('anime_id', $animeId)
  3992. ->where('episode_id', $episodeId)
  3993. ->orderBy('segment_number')
  3994. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  3995. ->get();
  3996. // 检查是否所有片段都有视频
  3997. $missingVideos = $segments->filter(function($segment) {
  3998. return empty($segment->video_url);
  3999. });
  4000. if ($missingVideos->isNotEmpty()) {
  4001. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4002. }
  4003. }else {
  4004. // 获取所有分镜的配音视频,按 segment_number 排序
  4005. $segments = DB::table('mp_episode_segments')
  4006. ->where('anime_id', $animeId)
  4007. ->where('episode_id', $episodeId)
  4008. ->orderBy('segment_number')
  4009. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4010. ->get();
  4011. // 检查是否所有分镜都有配音和视频
  4012. $missingVideos = $segments->filter(function($segment) {
  4013. return empty($segment->audio_url) || empty($segment->video_url);
  4014. });
  4015. if ($missingVideos->isNotEmpty()) {
  4016. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4017. }
  4018. }
  4019. if ($segments->isEmpty()) {
  4020. Utils::throwError('20003:未找到该剧集的分镜数据');
  4021. }
  4022. // 获取当前完整视频url
  4023. $completeVideoUrl = DB::table('mp_anime_episodes')
  4024. ->where('anime_id', $animeId)
  4025. ->where('id', $episodeId)
  4026. ->value('complete_video_url');
  4027. // 构建 generate_json
  4028. $generateJson = [];
  4029. $sequence = 1;
  4030. foreach ($segments as $segment) {
  4031. if ((int)$ace_mode === 1) {
  4032. $generateJson[] = [
  4033. 'sequence' => $sequence++,
  4034. 'video_url' => $segment->video_url,
  4035. 'video_time_point_start' => $segment->video_time_point_start,
  4036. 'video_time_point_end' => $segment->video_time_point_end
  4037. ];
  4038. }else {
  4039. $generateJson[] = [
  4040. 'sequence' => $sequence++,
  4041. 'video_url' => $segment->video_url,
  4042. 'audio_url' => $segment->audio_url,
  4043. 'video_time_point_start' => $segment->video_time_point_start,
  4044. 'video_time_point_end' => $segment->video_time_point_end
  4045. ];
  4046. }
  4047. }
  4048. // 创建任务
  4049. $now = date('Y-m-d H:i:s');
  4050. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4051. 'anime_id' => $animeId,
  4052. 'episode_id' => $episodeId,
  4053. 'generate_json' => json_encode($generateJson, 256),
  4054. 'generate_status' => '执行中',
  4055. 'complete_video_url' => '',
  4056. 'created_at' => $now,
  4057. 'updated_at' => $now
  4058. ]);
  4059. if (!$taskId) {
  4060. Utils::throwError('20003:创建任务失败');
  4061. }
  4062. // 更新剧集表的任务ID和状态
  4063. $boolen = DB::table('mp_anime_episodes')
  4064. ->where('anime_id', $animeId)
  4065. ->where('id', $episodeId)
  4066. ->update([
  4067. 'complete_video_task_id' => $taskId,
  4068. 'complete_video_task_status' => '执行中',
  4069. 'updated_at' => $now
  4070. ]);
  4071. if (!$boolen) {
  4072. Utils::throwError('20003:更新剧集表失败');
  4073. }
  4074. dLog('anime')->info('创建完整视频合成任务', [
  4075. 'task_id' => $taskId,
  4076. 'anime_id' => $animeId,
  4077. 'episode_id' => $episodeId,
  4078. 'segment_count' => count($generateJson)
  4079. ]);
  4080. // 请求远程服务器执行生成
  4081. $client = new Client(['timeout' => 600, 'verify' => false]);
  4082. try {
  4083. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4084. $response = $result->getBody()->getContents();
  4085. $response_arr = json_decode($response, true);
  4086. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4087. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4088. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4089. // // 更新任务状态为失败
  4090. // DB::table('mp_complete_video_tasks')
  4091. // ->where('id', $taskId)
  4092. // ->update([
  4093. // 'generate_status' => '执行失败',
  4094. // 'error_message' => $error_msg,
  4095. // 'updated_at' => date('Y-m-d H:i:s')
  4096. // ]);
  4097. // // 同步更新剧集表状态
  4098. // DB::table('mp_anime_episodes')
  4099. // ->where('complete_video_task_id', $taskId)
  4100. // ->update([
  4101. // 'complete_video_task_status' => '执行失败',
  4102. // 'updated_at' => date('Y-m-d H:i:s')
  4103. // ]);
  4104. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4105. }
  4106. } catch (\Exception $e) {
  4107. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4108. // 更新任务状态为失败
  4109. DB::table('mp_complete_video_tasks')
  4110. ->where('id', $taskId)
  4111. ->update([
  4112. 'generate_status' => '执行失败',
  4113. 'error_message' => $e->getMessage(),
  4114. 'updated_at' => date('Y-m-d H:i:s')
  4115. ]);
  4116. // 同步更新剧集表状态
  4117. DB::table('mp_anime_episodes')
  4118. ->where('complete_video_task_id', $taskId)
  4119. ->update([
  4120. 'complete_video_task_status' => '执行失败',
  4121. 'updated_at' => date('Y-m-d H:i:s')
  4122. ]);
  4123. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4124. }
  4125. // 开始轮询任务状态
  4126. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4127. $pollInterval = 5; // 每5秒轮询一次
  4128. $attempt = 0;
  4129. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4130. while ($attempt < $maxAttempts) {
  4131. sleep($pollInterval);
  4132. $attempt++;
  4133. // 查询任务状态
  4134. $task = DB::table('mp_complete_video_tasks')
  4135. ->where('id', $taskId)
  4136. ->first();
  4137. if (!$task) {
  4138. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4139. Utils::throwError('20003:任务不存在');
  4140. }
  4141. dLog('anime')->info('轮询任务状态', [
  4142. 'task_id' => $taskId,
  4143. 'attempt' => $attempt,
  4144. 'status' => $task->generate_status
  4145. ]);
  4146. // 检查任务是否完成
  4147. if ($task->generate_status === '执行成功') {
  4148. // 同步更新剧集表状态
  4149. $boolen3 = DB::table('mp_anime_episodes')
  4150. ->where('anime_id', $animeId)
  4151. ->where('id', $episodeId)
  4152. ->update([
  4153. 'complete_video_url' => $task->complete_video_url,
  4154. 'complete_video_task_status' => '执行成功',
  4155. 'updated_at' => date('Y-m-d H:i:s')
  4156. ]);
  4157. dLog('anime')->info('视频合成任务完成', [
  4158. 'task_id' => $taskId,
  4159. 'video_url' => $task->complete_video_url,
  4160. 'attempts' => $attempt
  4161. ]);
  4162. // 如果更新成功则远程删除之前的文件
  4163. if ($boolen3 && $completeVideoUrl) {
  4164. $encode_url = urlencode($completeVideoUrl);
  4165. $client = new Client(['timeout' => 300, 'verify' => false]);
  4166. // 根据ID通过API通知合成音频
  4167. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4168. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4169. $response = $result->getBody()->getContents();
  4170. $response_arr = json_decode($response, true);
  4171. Log::info('火山删除音频返回: '.$response);
  4172. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4173. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4174. Log::info('火山删除音频失败: '.$error_msg);
  4175. // Utils::throwError('20003:火山删除音频失败');
  4176. }
  4177. }
  4178. return [
  4179. 'task_id' => $taskId,
  4180. 'anime_id' => $animeId,
  4181. 'episode_id' => $episodeId,
  4182. 'segment_count' => count($generateJson),
  4183. 'generate_status' => '执行成功',
  4184. 'complete_video_url' => $task->complete_video_url,
  4185. ];
  4186. }
  4187. // 检查任务是否失败
  4188. if ($task->generate_status === '执行失败') {
  4189. // 同步更新剧集表状态
  4190. DB::table('mp_anime_episodes')
  4191. ->where('anime_id', $animeId)
  4192. ->where('id', $episodeId)
  4193. ->update([
  4194. 'complete_video_task_status' => '执行失败',
  4195. 'updated_at' => date('Y-m-d H:i:s')
  4196. ]);
  4197. $errorMessage = $task->error_message ?? '未知错误';
  4198. dLog('anime')->error('视频合成任务失败', [
  4199. 'task_id' => $taskId,
  4200. 'error' => $errorMessage,
  4201. 'attempts' => $attempt
  4202. ]);
  4203. return [
  4204. 'task_id' => $taskId,
  4205. 'anime_id' => $animeId,
  4206. 'episode_id' => $episodeId,
  4207. 'segment_count' => count($generateJson),
  4208. 'generate_status' => '执行失败',
  4209. 'error_message' => $errorMessage
  4210. ];
  4211. }
  4212. }
  4213. // 超时处理
  4214. dLog('anime')->warning('视频合成任务超时', [
  4215. 'task_id' => $taskId,
  4216. 'max_attempts' => $maxAttempts,
  4217. 'timeout_seconds' => $maxAttempts * $pollInterval
  4218. ]);
  4219. // 更新任务状态为超时
  4220. DB::table('mp_complete_video_tasks')
  4221. ->where('id', $taskId)
  4222. ->update([
  4223. 'generate_status' => '超时',
  4224. 'error_message' => '任务执行超时(5分钟)',
  4225. 'updated_at' => date('Y-m-d H:i:s')
  4226. ]);
  4227. return [
  4228. 'task_id' => $taskId,
  4229. 'anime_id' => $animeId,
  4230. 'episode_id' => $episodeId,
  4231. 'segment_count' => count($generateJson),
  4232. 'generate_status' => '超时',
  4233. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4234. ];
  4235. }
  4236. public function generateImg($data) {
  4237. $prompt = getProp($data, 'prompt');
  4238. $episode_id = getProp($data, 'episode_id');
  4239. $ref_img_urls = getProp($data, 'ref_img_urls');
  4240. $ratio = getProp($data, 'ratio', '9:16');
  4241. $resolution = getProp($data, 'resolution', '2k');
  4242. // 定义分辨率和宽高比对应的尺寸映射表
  4243. $sizeMap = [
  4244. '2k' => [
  4245. '1:1' => ['width' => 2048, 'height' => 2048],
  4246. '4:3' => ['width' => 2304, 'height' => 1728],
  4247. '3:4' => ['width' => 1728, 'height' => 2304],
  4248. '16:9' => ['width' => 2848, 'height' => 1600],
  4249. '9:16' => ['width' => 1600, 'height' => 2848],
  4250. '3:2' => ['width' => 2496, 'height' => 1664],
  4251. '2:3' => ['width' => 1664, 'height' => 2496],
  4252. '21:9' => ['width' => 3136, 'height' => 1344],
  4253. ],
  4254. '3k' => [
  4255. '1:1' => ['width' => 3072, 'height' => 3072],
  4256. '4:3' => ['width' => 3456, 'height' => 2592],
  4257. '3:4' => ['width' => 2592, 'height' => 3456],
  4258. '16:9' => ['width' => 4096, 'height' => 2304],
  4259. '9:16' => ['width' => 2304, 'height' => 4096],
  4260. '2:3' => ['width' => 2496, 'height' => 3744],
  4261. '3:2' => ['width' => 3744, 'height' => 2496],
  4262. '21:9' => ['width' => 4704, 'height' => 2016],
  4263. ],
  4264. '4k' => [
  4265. '1:1' => ['width' => 4096, 'height' => 4096],
  4266. '3:4' => ['width' => 3520, 'height' => 4704],
  4267. '4:3' => ['width' => 4704, 'height' => 3520],
  4268. '16:9' => ['width' => 5504, 'height' => 3040],
  4269. '9:16' => ['width' => 3040, 'height' => 5504],
  4270. '2:3' => ['width' => 3328, 'height' => 4992],
  4271. '3:2' => ['width' => 4992, 'height' => 3328],
  4272. '21:9' => ['width' => 6240, 'height' => 2656],
  4273. ],
  4274. ];
  4275. // 参数验证
  4276. $resolution = strtolower($resolution);
  4277. if (!isset($sizeMap[$resolution])) {
  4278. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  4279. }
  4280. if (!isset($sizeMap[$resolution][$ratio])) {
  4281. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  4282. }
  4283. // 根据 ratio 和 resolution 确定宽高
  4284. $width = $sizeMap[$resolution][$ratio]['width'];
  4285. $height = $sizeMap[$resolution][$ratio]['height'];
  4286. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  4287. if (is_json($ref_img_urls)) {
  4288. $ref_img_urls = json_decode($ref_img_urls, true);
  4289. }else {
  4290. $ref_img_urls = explode(',', $ref_img_urls);
  4291. }
  4292. }
  4293. // 处理图片模型
  4294. $model = getProp($data, 'model');
  4295. if (!$model) {
  4296. // 用户没有输入,从episode表获取
  4297. if ($episode_id) {
  4298. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4299. $model = getProp($episode, 'image_model');
  4300. }
  4301. if (!$model) {
  4302. // episode表也没有,使用默认值
  4303. $model = 'doubao-seedream-5-0-lite-260128';
  4304. }
  4305. }
  4306. // 验证模型是否在可用模型表中
  4307. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4308. // $model = 'doubao-seedream-5-0-lite-260128';
  4309. Utils::throwError('20003:该模型已不可用,请更换!');
  4310. }
  4311. // 保存到episode表
  4312. if ($episode_id) {
  4313. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4314. 'image_model' => $model,
  4315. 'updated_at' => date('Y-m-d H:i:s')
  4316. ]);
  4317. }
  4318. // 参数验证
  4319. if (!$prompt) Utils::throwError('20003:请提供提示词');
  4320. try {
  4321. // 创建图片生成任务
  4322. $params = [
  4323. 'prompt' => $prompt,
  4324. 'model' => $model,
  4325. 'ref_img_urls' => '',
  4326. 'width' => $width,
  4327. 'height' => $height
  4328. ];
  4329. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  4330. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4331. $task_id = $task->id;
  4332. if (!$task_id) {
  4333. Utils::throwError('20003:创建图片生成任务失败');
  4334. }
  4335. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  4336. $model = getProp($task, 'model');
  4337. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  4338. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  4339. $isSyncModel = $isVolcModel || $isGptModel;
  4340. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  4341. $start_time = time();
  4342. $timeout = 300; // 5分钟
  4343. $img_url = '';
  4344. while (time() - $start_time < $timeout) {
  4345. sleep(3);
  4346. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  4347. if ($isSyncModel) {
  4348. // 刷新任务状态
  4349. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4350. if ($task->status === 'success' && $task->result_url) {
  4351. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  4352. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  4353. break;
  4354. } elseif ($task->status === 'failed') {
  4355. $errorMsg = mapErrorMessage($task->error_message ?? '');
  4356. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4357. }
  4358. // // 如果还在处理中,提示用户稍后查看
  4359. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  4360. }else {
  4361. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4362. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  4363. if ($statusInfo['status'] === 'success') {
  4364. $task->updateStatus('success', [
  4365. 'result_url' => $statusInfo['result_url'],
  4366. 'result_json' => $statusInfo['result_json'] ?? []
  4367. ]);
  4368. $img_url = $statusInfo['result_url'][0];
  4369. break;
  4370. } elseif ($statusInfo['status'] === 'failed') {
  4371. $task->updateStatus('failed', [
  4372. 'error_message' => $statusInfo['error_message'],
  4373. 'result_json' => $statusInfo['result_json'] ?? []
  4374. ]);
  4375. dLog('anime')->error('图片生成失败,', [
  4376. 'error' => $statusInfo['error_message'] ?? '未知错误'
  4377. ]);
  4378. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  4379. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4380. }
  4381. }
  4382. }
  4383. if (empty($img_url)) {
  4384. Utils::throwError('20003:图片生成超时,请稍后重试');
  4385. }
  4386. return $img_url;
  4387. } catch (\Exception $e) {
  4388. dLog('anime')->error('更新角色或场景失败', [
  4389. 'error' => $e->getMessage()
  4390. ]);
  4391. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  4392. Utils::throwError('20003:' . $e->getMessage());
  4393. }
  4394. }
  4395. /**
  4396. * 使用文生文模型解析分镜内容
  4397. */
  4398. private function parseSegmentContentWithAI($segment_content) {
  4399. try {
  4400. // 使用DeepSeek服务的公开方法解析分镜内容
  4401. return $this->DeepSeekService->parseSegmentContent($segment_content);
  4402. } catch (\Exception $e) {
  4403. // 如果AI解析失败,记录日志并返回原内容
  4404. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  4405. return $segment_content;
  4406. }
  4407. }
  4408. /**
  4409. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  4410. *
  4411. * @param int $episode_id 分集ID
  4412. * @param int $anime_id 动漫ID
  4413. * @param array $roles 分集角色数组(引用传递)
  4414. * @param array $scenes 分集场景数组(引用传递)
  4415. * @param array $episode 分集数据
  4416. */
  4417. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  4418. // 获取全局动漫的角色和场景数据
  4419. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4420. if (!$anime) return;
  4421. $art_style_type = getProp($anime, 'art_style_type');
  4422. $character_prefix = '';
  4423. $scene_prefix = '';
  4424. if ($art_style_type) {
  4425. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  4426. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  4427. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  4428. }
  4429. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  4430. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  4431. $roles_updated = false;
  4432. $scenes_updated = false;
  4433. // 处理角色
  4434. foreach ($roles as &$role) {
  4435. $role_name = getProp($role, 'role');
  4436. $role_description = getProp($role, 'description');
  4437. $role_pic_prompt = getProp($role, 'pic_prompt');
  4438. $role_url = getProp($role, 'url');
  4439. $role_task_id = getProp($role, 'task_id');
  4440. // 如果已有URL或已有任务ID,跳过
  4441. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  4442. continue;
  4443. }
  4444. $url_inherited = false;
  4445. // 尝试从全局数据中继承
  4446. foreach ($global_roles as $global_role) {
  4447. $global_role_name = getProp($global_role, 'role');
  4448. $global_role_description = getProp($global_role, 'description');
  4449. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  4450. $global_role_url = getProp($global_role, 'url');
  4451. $global_role_task_id = getProp($global_role, 'task_id');
  4452. $global_role_task_status = getProp($global_role, 'task_status');
  4453. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  4454. if ($role_name === $global_role_name
  4455. && $role_description === $global_role_description
  4456. && $role_pic_prompt === $global_role_pic_prompt
  4457. && !empty($global_role_url)) {
  4458. // 继承 task_id、task_status 和 url
  4459. $role['task_id'] = $global_role_task_id;
  4460. $role['task_status'] = $global_role_task_status;
  4461. $role['url'] = $global_role_url;
  4462. $roles_updated = true;
  4463. $url_inherited = true;
  4464. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  4465. break;
  4466. }
  4467. }
  4468. // 如果无法继承且没有任务ID,创建新任务
  4469. if (!$url_inherited && empty($role_task_id)) {
  4470. try {
  4471. $art_style = getProp($episode, 'art_style');
  4472. // 优先使用 pic_prompt,如果没有则使用 description
  4473. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  4474. // if ($art_style) {
  4475. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4476. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4477. // }
  4478. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  4479. $params = [
  4480. 'prompt' => $description,
  4481. 'ref_img_urls' => []
  4482. ];
  4483. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4484. $task_id = $task->id;
  4485. if ($task_id) {
  4486. $role['task_id'] = $task_id;
  4487. $role['task_status'] = 'processing';
  4488. $roles_updated = true;
  4489. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  4490. }
  4491. } catch (\Exception $e) {
  4492. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  4493. }
  4494. }
  4495. }
  4496. // 处理场景
  4497. foreach ($scenes as &$scene) {
  4498. $scene_name = getProp($scene, 'scene');
  4499. $scene_description = getProp($scene, 'description');
  4500. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  4501. $scene_url = getProp($scene, 'url');
  4502. $scene_task_id = getProp($scene, 'task_id');
  4503. // 如果已有URL或已有任务ID,跳过
  4504. if (!empty($scene_url) || !empty($scene_task_id)) {
  4505. continue;
  4506. }
  4507. $url_inherited = false;
  4508. // 尝试从全局数据中继承
  4509. foreach ($global_scenes as $global_scene) {
  4510. $global_scene_name = getProp($global_scene, 'scene');
  4511. $global_scene_description = getProp($global_scene, 'description');
  4512. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  4513. $global_scene_url = getProp($global_scene, 'url');
  4514. $global_scene_task_id = getProp($global_scene, 'task_id');
  4515. $global_scene_task_status = getProp($global_scene, 'task_status');
  4516. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  4517. if ($scene_name === $global_scene_name
  4518. && $scene_description === $global_scene_description
  4519. && $scene_pic_prompt === $global_scene_pic_prompt
  4520. && !empty($global_scene_url)) {
  4521. // 继承 task_id、task_status 和 url
  4522. $scene['task_id'] = $global_scene_task_id;
  4523. $scene['task_status'] = $global_scene_task_status;
  4524. $scene['url'] = $global_scene_url;
  4525. $scenes_updated = true;
  4526. $url_inherited = true;
  4527. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  4528. break;
  4529. }
  4530. }
  4531. // 如果无法继承且没有任务ID,创建新任务
  4532. if (!$url_inherited && empty($scene_task_id)) {
  4533. try {
  4534. $art_style = getProp($episode, 'art_style');
  4535. // 优先使用 pic_prompt,如果没有则使用 description
  4536. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  4537. // if ($art_style) {
  4538. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  4539. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  4540. // }
  4541. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  4542. $params = [
  4543. 'prompt' => $description,
  4544. 'ref_img_urls' => []
  4545. ];
  4546. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4547. $task_id = $task->id;
  4548. if ($task_id) {
  4549. $scene['task_id'] = $task_id;
  4550. $scene['task_status'] = 'processing';
  4551. $scenes_updated = true;
  4552. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  4553. }
  4554. } catch (\Exception $e) {
  4555. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  4556. }
  4557. }
  4558. }
  4559. // 如果有更新,保存到数据库
  4560. if ($roles_updated || $scenes_updated) {
  4561. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  4562. if ($roles_updated) {
  4563. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  4564. }
  4565. if ($scenes_updated) {
  4566. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  4567. }
  4568. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  4569. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  4570. }
  4571. }
  4572. /**
  4573. * 根据图片URL使用AI反推图片提示词
  4574. *
  4575. * @param string $img_url 图片URL
  4576. * @return string 反推的提示词
  4577. */
  4578. private function generateImagePromptFromUrl($img_url) {
  4579. try {
  4580. // 获取默认模型
  4581. $model = 'doubao-seed-2-0-mini-260215';
  4582. // 构建messages参数
  4583. $messages = [
  4584. [
  4585. 'role' => 'user',
  4586. 'content' => [
  4587. [
  4588. 'type' => 'text',
  4589. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  4590. ],
  4591. [
  4592. 'type' => 'image_url',
  4593. 'image_url' => [
  4594. 'url' => $img_url
  4595. ]
  4596. ]
  4597. ]
  4598. ]
  4599. ];
  4600. // 构建请求参数
  4601. $params = [
  4602. 'model' => $model,
  4603. 'messages' => $messages,
  4604. 'stream' => false,
  4605. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  4606. ];
  4607. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  4608. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  4609. // 返回生成的内容
  4610. return getProp($result, 'fullContent', '图片描述生成失败');
  4611. } catch (\Exception $e) {
  4612. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  4613. 'img_url' => $img_url
  4614. ]);
  4615. logDB('anime', 'error', 'AI反推图片提示词失败', [
  4616. 'error' => $e->getMessage(),
  4617. 'img_url' => $img_url
  4618. ]);
  4619. return '图片描述生成失败: ' . $e->getMessage();
  4620. }
  4621. }
  4622. /**
  4623. * 音频试听接口
  4624. * 创建音频任务并轮询获取结果
  4625. *
  4626. * @param array $data 参数数组
  4627. * @return array 返回音频URL或错误信息
  4628. */
  4629. public function previewAudio($data) {
  4630. $dialogue = getProp($data, 'dialogue');
  4631. // 必填参数验证
  4632. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  4633. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  4634. $voice_type = getProp($data, 'voice_type');
  4635. $voice_name = getProp($data, 'voice_name');
  4636. $voice_actor = getProp($data, 'voice_actor');
  4637. $emotion_type = getProp($data, 'emotion_type');
  4638. $gender = getProp($data, 'gender', 0);
  4639. $emotion = getProp($data, 'emotion');
  4640. $speed_ratio = getProp($data, 'speed_ratio', 0);
  4641. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  4642. $emotion_scale = getProp($data, 'emotion_scale', 0);
  4643. $pitch = getProp($data, 'pitch', 0);
  4644. try {
  4645. $now = date('Y-m-d H:i:s');
  4646. // 构建生成参数
  4647. $generate_json = json_encode([
  4648. 'text' => $dialogue,
  4649. 'role' => $voice_actor,
  4650. 'voice_type' => $voice_type,
  4651. 'voice_name' => $voice_name,
  4652. 'emotion' => $emotion,
  4653. 'emotion_type' => $emotion_type,
  4654. 'gender' => $gender,
  4655. 'speed_ratio' => $speed_ratio,
  4656. 'loudness_ratio' => $loudness_ratio,
  4657. 'emotion_scale' => $emotion_scale,
  4658. 'pitch' => $pitch,
  4659. ], 256);
  4660. // 请求远程服务器执行生成
  4661. $client = new Client(['timeout' => 600, 'verify' => false]);
  4662. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  4663. $response = $result->getBody()->getContents();
  4664. $response_arr = json_decode($response, true);
  4665. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4666. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4667. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  4668. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  4669. }
  4670. $arr = $response_arr['data'];
  4671. $subtitle_info = $arr['subtitle_info'];
  4672. $audio_duration = json_decode($subtitle_info, true)['duration'];
  4673. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  4674. return [
  4675. 'audio_url' => $arr['url'],
  4676. 'subtitle_info' => $subtitle_info,
  4677. 'audio_duration' => round($audio_duration, 2)
  4678. ];
  4679. } catch (\Exception $e) {
  4680. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  4681. Utils::throwError('20003:' . $e->getMessage());
  4682. }
  4683. }
  4684. /**
  4685. * 获取角色库列表(支持文件夹递归查询)
  4686. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)
  4687. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  4688. */
  4689. public function globalProducts($data) {
  4690. $uid = Site::getUid();
  4691. $cpid = Site::getCpid();
  4692. $id = getProp($data, 'id', 0);
  4693. $parent_id = getProp($data, 'parent_id', 0);
  4694. $product_name = getProp($data, 'product_name');
  4695. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  4696. if (!$product) {
  4697. Utils::throwError('20003:请选择产品类型');
  4698. }
  4699. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  4700. if ($id || $product_name) {
  4701. $query = DB::table('mp_products')
  4702. ->where('cpid', $cpid)
  4703. ->where('user_id', $uid)
  4704. ->where('is_deleted', 0);
  4705. // 如果指定了 id,按 id 精确查询
  4706. if ($id) {
  4707. $query->where('id', $id);
  4708. }
  4709. // 如果指定了 product_name,按名称模糊查询
  4710. if ($product_name) {
  4711. $query->where('product_name', 'like', "%{$product_name}%");
  4712. }
  4713. // 如果指定了 product,添加筛选条件
  4714. if ($product) {
  4715. $query->where('product', $product);
  4716. }
  4717. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'created_at')
  4718. ->orderByRaw('sort_order DESC, created_at DESC')
  4719. ->get()
  4720. ->map(function($value) {
  4721. $value = (array)$value;
  4722. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  4723. $value['type'] = (int)$value['type'];
  4724. $value['parent_id'] = (int)$value['parent_id'];
  4725. $value['level'] = (int)$value['level'];
  4726. $value['product'] = (int)($value['product'] ?? 1);
  4727. $value['versions'] = json_decode($value['versions'], true) ?: [];
  4728. return $value;
  4729. })
  4730. ->toArray();
  4731. return $result;
  4732. }
  4733. // 递归获取所有子目录和角色
  4734. return $this->getChildrenRecursive($cpid, $parent_id, $product, $uid);
  4735. }
  4736. /**
  4737. * 递归获取指定目录下的所有子目录和角色
  4738. * @param int $cpid 公司ID
  4739. * @param int $parent_id 父目录ID
  4740. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  4741. * @param int $uid 用户ID
  4742. * @return array
  4743. */
  4744. private function getChildrenRecursive($cpid, $parent_id, $product = null, $uid = null) {
  4745. // 查询当前层级的所有项(文件夹和角色)
  4746. $query = DB::table('mp_products')
  4747. ->where('cpid', $cpid)
  4748. ->where('is_deleted', 0)
  4749. ->where('parent_id', $parent_id);
  4750. // 添加用户ID验证
  4751. if ($uid) {
  4752. $query->where('user_id', $uid);
  4753. }
  4754. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  4755. if ($product) {
  4756. $query->where('product', $product);
  4757. }
  4758. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'created_at')
  4759. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  4760. ->get();
  4761. $result = [];
  4762. foreach ($items as $item) {
  4763. $itemArray = [
  4764. 'id' => $item->id,
  4765. 'type' => (int)$item->type,
  4766. 'parent_id' => (int)$item->parent_id,
  4767. 'level' => (int)$item->level,
  4768. 'product_name' => $item->product_name,
  4769. 'url' => $item->url,
  4770. 'pic_prompt' => $item->pic_prompt ?? '',
  4771. 'three_view_image_url' => $item->three_view_image_url,
  4772. 'product' => (int)($item->product ?? 1),
  4773. 'created_at' => transDate($item->created_at, 'Y-m-d')
  4774. ];
  4775. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  4776. // 如果是文件夹,递归获取其子项
  4777. if ($item->type == 2) {
  4778. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $uid);
  4779. if (!empty($children)) {
  4780. $itemArray['children'] = $children;
  4781. }
  4782. }
  4783. $result[] = $itemArray;
  4784. }
  4785. return $result;
  4786. }
  4787. /**
  4788. * 创建文件夹
  4789. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  4790. * @return int 返回新建文件夹ID
  4791. */
  4792. public function createFolder($data) {
  4793. $uid = Site::getUid();
  4794. $cpid = Site::getCpid();
  4795. $parent_id = getProp($data, 'parent_id', 0);
  4796. $folder_name = getProp($data, 'product_name', '新建文件夹');
  4797. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  4798. $product = getProp($data, 'product');
  4799. if (!in_array($product, [1, 2, 3])) {
  4800. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  4801. }
  4802. // 验证父文件夹
  4803. $parent_level = 0;
  4804. if ($parent_id > 0) {
  4805. $parent = DB::table('mp_products')
  4806. ->where('id', $parent_id)
  4807. ->where('type', 2)
  4808. ->where('is_deleted', 0)
  4809. ->first();
  4810. if (!$parent) {
  4811. Utils::throwError('20003:父文件夹不存在');
  4812. }
  4813. // 检查父文件夹的 product 类型是否一致
  4814. if ($parent->product != $product) {
  4815. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  4816. }
  4817. $parent_level = $parent->level;
  4818. // 检查层级限制(最多3层)
  4819. if ($parent_level >= 3) {
  4820. Utils::throwError('20003:文件夹层级不能超过3层');
  4821. }
  4822. }
  4823. // 检查当前目录下是否已存在空白文件夹
  4824. $empty_folder_exists = DB::table('mp_products')
  4825. ->where('parent_id', $parent_id)
  4826. ->where('type', 2)
  4827. ->where('product', $product)
  4828. ->where('product_name', '新建文件夹')
  4829. ->where('is_deleted', 0)
  4830. ->exists();
  4831. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  4832. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  4833. }
  4834. // 创建文件夹
  4835. $folder_id = DB::table('mp_products')->insertGetId([
  4836. 'user_id' => $uid,
  4837. 'cpid' => $cpid,
  4838. 'type' => 2,
  4839. 'parent_id' => $parent_id,
  4840. 'level' => $parent_level + 1,
  4841. 'product_name' => $folder_name,
  4842. 'product' => $product,
  4843. 'sort_order' => time(), // 使用时间戳作为排序权重
  4844. 'is_deleted' => 0,
  4845. 'created_at' => date('Y-m-d H:i:s'),
  4846. 'updated_at' => date('Y-m-d H:i:s')
  4847. ]);
  4848. return [
  4849. 'id' => $folder_id,
  4850. 'type' => 2,
  4851. 'parent_id' => $parent_id,
  4852. 'level' => $parent_level + 1,
  4853. 'product_name' => $folder_name,
  4854. 'product' => $product,
  4855. ];
  4856. }
  4857. /**
  4858. * 重命名文件夹或角色
  4859. * @param array $data 包含 id、product_name(新名称)
  4860. * @return bool
  4861. */
  4862. public function renameFolder($data) {
  4863. $uid = Site::getUid();
  4864. $cpid = Site::getCpid();
  4865. $id = getProp($data, 'id');
  4866. $new_name = getProp($data, 'product_name');
  4867. if (!$id || !$new_name) {
  4868. Utils::throwError('20003:参数不完整');
  4869. }
  4870. // 检查是否存在
  4871. $item = DB::table('mp_products')
  4872. ->where('id', $id)
  4873. ->where('cpid', $cpid)
  4874. ->where('is_deleted', 0)
  4875. ->first();
  4876. if (!$item) {
  4877. Utils::throwError('20003:项目不存在');
  4878. }
  4879. return DB::table('mp_products')
  4880. ->where('id', $id)
  4881. ->where('cpid', $cpid)
  4882. ->update([
  4883. 'product_name' => $new_name,
  4884. 'updated_at' => date('Y-m-d H:i:s')
  4885. ]);
  4886. }
  4887. /**
  4888. * 移动角色或文件夹到指定文件夹
  4889. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  4890. * @return bool
  4891. */
  4892. public function moveProductOrFolder($data) {
  4893. $cpid = Site::getCpid();
  4894. $id = getProp($data, 'id');
  4895. $target_parent_id = getProp($data, 'target_parent_id', 0);
  4896. if (!$id) {
  4897. Utils::throwError('20003:请选择要移动的项目');
  4898. }
  4899. // 检查要移动的项目
  4900. $item = DB::table('mp_products')
  4901. ->where('id', $id)
  4902. ->where('cpid', $cpid)
  4903. ->where('is_deleted', 0)
  4904. ->first();
  4905. if (!$item) {
  4906. Utils::throwError('20003:项目不存在');
  4907. }
  4908. // 验证目标文件夹
  4909. $target_level = 0;
  4910. $target_product = $item->product; // 默认使用当前项目的 product
  4911. if ($target_parent_id > 0) {
  4912. $target_parent = DB::table('mp_products')
  4913. ->where('id', $target_parent_id)
  4914. ->where('cpid', $cpid)
  4915. ->where('type', 2)
  4916. ->where('is_deleted', 0)
  4917. ->first();
  4918. if (!$target_parent) {
  4919. Utils::throwError('20003:目标文件夹不存在');
  4920. }
  4921. // 检查 product 类型是否一致
  4922. if ($target_parent->product != $item->product) {
  4923. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  4924. }
  4925. $target_level = $target_parent->level;
  4926. $target_product = $target_parent->product;
  4927. // 如果移动的是文件夹,需要检查层级
  4928. if ($item->type == 2) {
  4929. // 计算移动后的最大层级
  4930. $max_child_level = $this->getMaxChildLevel($id);
  4931. $depth = $max_child_level - $item->level;
  4932. if ($target_level + 1 + $depth > 3) {
  4933. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  4934. }
  4935. // 不能移动到自己或自己的子文件夹下
  4936. if ($this->isDescendant($target_parent_id, $id)) {
  4937. Utils::throwError('20003:不能移动到自己或子文件夹下');
  4938. }
  4939. }
  4940. }
  4941. // 更新父文件夹和层级
  4942. $new_level = $target_level + 1;
  4943. DB::table('mp_products')
  4944. ->where('id', $id)
  4945. ->update([
  4946. 'parent_id' => $target_parent_id,
  4947. 'level' => $new_level,
  4948. 'updated_at' => date('Y-m-d H:i:s')
  4949. ]);
  4950. // 如果是文件夹,需要递归更新所有子项的层级
  4951. if ($item->type == 2) {
  4952. $this->updateChildrenLevel($id, $new_level);
  4953. }
  4954. return true;
  4955. }
  4956. /**
  4957. * 获取文件夹下最大子层级
  4958. * @param int $folder_id
  4959. * @return int
  4960. */
  4961. private function getMaxChildLevel($folder_id) {
  4962. $max_level = DB::table('mp_products')
  4963. ->where('parent_id', $folder_id)
  4964. ->where('is_deleted', 0)
  4965. ->max('level');
  4966. if (!$max_level) {
  4967. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  4968. }
  4969. // 递归查找子文件夹
  4970. $children = DB::table('mp_products')
  4971. ->where('parent_id', $folder_id)
  4972. ->where('type', 2)
  4973. ->where('is_deleted', 0)
  4974. ->pluck('id');
  4975. foreach ($children as $child_id) {
  4976. $child_max = $this->getMaxChildLevel($child_id);
  4977. if ($child_max > $max_level) {
  4978. $max_level = $child_max;
  4979. }
  4980. }
  4981. return $max_level;
  4982. }
  4983. /**
  4984. * 检查 target_id 是否是 folder_id 的后代
  4985. * @param int $target_id
  4986. * @param int $folder_id
  4987. * @return bool
  4988. */
  4989. private function isDescendant($target_id, $folder_id) {
  4990. if ($target_id == $folder_id) {
  4991. return true;
  4992. }
  4993. $parent = DB::table('mp_products')
  4994. ->where('id', $target_id)
  4995. ->where('is_deleted', 0)
  4996. ->first();
  4997. if (!$parent || $parent->parent_id == 0) {
  4998. return false;
  4999. }
  5000. return $this->isDescendant($parent->parent_id, $folder_id);
  5001. }
  5002. /**
  5003. * 递归更新子项层级
  5004. * @param int $parent_id
  5005. * @param int $parent_level
  5006. */
  5007. private function updateChildrenLevel($parent_id, $parent_level) {
  5008. $children = DB::table('mp_products')
  5009. ->where('parent_id', $parent_id)
  5010. ->where('is_deleted', 0)
  5011. ->get();
  5012. foreach ($children as $child) {
  5013. $new_level = $parent_level + 1;
  5014. DB::table('mp_products')
  5015. ->where('id', $child->id)
  5016. ->update([
  5017. 'level' => $new_level,
  5018. 'updated_at' => date('Y-m-d H:i:s')
  5019. ]);
  5020. // 如果是文件夹,继续递归
  5021. if ($child->type == 2) {
  5022. $this->updateChildrenLevel($child->id, $new_level);
  5023. }
  5024. }
  5025. }
  5026. /**
  5027. * 获取文件夹路径(面包屑导航)
  5028. * @param array $data 包含 folder_id
  5029. * @return array 返回路径数组
  5030. */
  5031. public function getFolderPath($data) {
  5032. $folder_id = getProp($data, 'id', 0);
  5033. if ($folder_id == 0) {
  5034. return [
  5035. ['id' => 0, 'name' => '根目录']
  5036. ];
  5037. }
  5038. $path = [];
  5039. $current_id = $folder_id;
  5040. while ($current_id > 0) {
  5041. $folder = DB::table('mp_products')
  5042. ->where('id', $current_id)
  5043. ->where('type', 2)
  5044. ->where('is_deleted', 0)
  5045. ->first();
  5046. if (!$folder) {
  5047. break;
  5048. }
  5049. array_unshift($path, [
  5050. 'id' => $folder->id,
  5051. 'name' => $folder->product_name
  5052. ]);
  5053. $current_id = $folder->parent_id;
  5054. }
  5055. // 添加根目录
  5056. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5057. return $path;
  5058. }
  5059. public function createProduct($data) {
  5060. $uid = Site::getUid();
  5061. $cpid = Site::getCpid();
  5062. $product_name = trim(getProp($data, 'product_name'));
  5063. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5064. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5065. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5066. $url = trim(getProp($data, 'url'));
  5067. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5068. $versions = getProp($data, 'versions');
  5069. // 检查是否是正确的图片格式
  5070. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5071. $urlPath = parse_url($url, PHP_URL_PATH);
  5072. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5073. if (!in_array($extension, $allowedExtensions)) {
  5074. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5075. }
  5076. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5077. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5078. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5079. $product = getProp($data, 'product');
  5080. if (!in_array($product, [1, 2, 3])) {
  5081. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5082. }
  5083. // 获取父文件夹ID和层级
  5084. $parent_id = getProp($data, 'parent_id', 0);
  5085. $parent_level = 0;
  5086. if ($parent_id > 0) {
  5087. $parent = DB::table('mp_products')
  5088. ->where('id', $parent_id)
  5089. ->where('cpid', $cpid)
  5090. ->where('type', 2)
  5091. ->where('is_deleted', 0)
  5092. ->first();
  5093. if (!$parent) {
  5094. Utils::throwError('20003:父文件夹不存在');
  5095. }
  5096. $parent_level = $parent->level;
  5097. }
  5098. $id = DB::table('mp_products')->insertGetId([
  5099. 'user_id' => $uid,
  5100. 'cpid' => $cpid,
  5101. 'type' => 1, // 1=角色图片
  5102. 'parent_id' => $parent_id,
  5103. 'level' => $parent_level + 1,
  5104. 'product_name' => $product_name,
  5105. 'url' => $url,
  5106. 'pic_prompt' => $pic_prompt,
  5107. 'product' => $product,
  5108. 'versions' => json_encode($versions, 256),
  5109. 'sort_order' => time(), // 使用时间戳作为排序权重
  5110. 'created_at' => date('Y-m-d H:i:s'),
  5111. 'updated_at' => date('Y-m-d H:i:s')
  5112. ]);
  5113. if (!$id) Utils::throwError('20003:创建失败');
  5114. return [
  5115. 'id' => $id,
  5116. 'type' => 1,
  5117. 'parent_id' => $parent_id,
  5118. 'level' => $parent_level + 1,
  5119. 'product_name' => $product_name,
  5120. 'url' => $url,
  5121. 'pic_prompt' => $pic_prompt,
  5122. 'product' => $product,
  5123. 'versions' => $versions
  5124. ];
  5125. }
  5126. public function editProduct($data) {
  5127. $uid = Site::getUid();
  5128. $cpid = Site::getCpid();
  5129. $id = getProp($data, 'id');
  5130. if (!$id) Utils::throwError('20003:ID不能为空');
  5131. $versions = getProp($data, 'versions');
  5132. // 检查是否存在且属于当前用户
  5133. $role = DB::table('mp_products')
  5134. ->where('id', $id)
  5135. ->where('cpid', $cpid)
  5136. ->where('type', 1)->first();
  5137. if (!$role) Utils::throwError('20003:记录不存在');
  5138. $updateData = [];
  5139. // $needVersionRecord = false; // 是否需要记录版本
  5140. // 名称
  5141. $product_name = trim(getProp($data, 'product_name'));
  5142. if ($product_name) {
  5143. $updateData['product_name'] = $product_name;
  5144. }
  5145. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5146. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5147. // 图片地址
  5148. $url = trim(getProp($data, 'url'));
  5149. if ($url) {
  5150. // 检查是否是正确的图片格式
  5151. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5152. $urlPath = parse_url($url, PHP_URL_PATH);
  5153. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5154. if (!in_array($extension, $allowedExtensions)) {
  5155. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5156. }
  5157. // // 如果 url 有变更,记录版本
  5158. // if ($url !== $role->url) {
  5159. // $needVersionRecord = true;
  5160. // }
  5161. $updateData['url'] = $url;
  5162. }
  5163. // 提示词
  5164. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5165. if ($pic_prompt) {
  5166. // // 如果 pic_prompt 有变更,记录版本
  5167. // if ($pic_prompt !== $role->pic_prompt) {
  5168. // $needVersionRecord = true;
  5169. // }
  5170. $updateData['pic_prompt'] = $pic_prompt;
  5171. }
  5172. if (empty($updateData)) {
  5173. Utils::throwError('20003:没有需要更新的数据');
  5174. }
  5175. // // 如果需要记录版本,将数据添加到 versions 数组
  5176. // if ($needVersionRecord) {
  5177. // // 获取现有的 versions 数据
  5178. // $versions = json_decode($role->versions, true) ?: [];
  5179. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  5180. // // 如果是第一次记录版本,先添加旧版本(变更前)
  5181. // if ($isFirstVersion) {
  5182. // $oldVersion = [
  5183. // 'url' => $role->url,
  5184. // 'description' => $role->pic_prompt,
  5185. // ];
  5186. // // 旧版本添加到数组末尾
  5187. // $versions[] = $oldVersion;
  5188. // }
  5189. // // 构建新版本(变更后)
  5190. // $newVersion = [
  5191. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  5192. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  5193. // ];
  5194. // // 检查新版本是否已存在于历史版本中
  5195. // $existingIndex = -1;
  5196. // foreach ($versions as $index => $version) {
  5197. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  5198. // $existingIndex = $index;
  5199. // break;
  5200. // }
  5201. // }
  5202. // if ($existingIndex !== -1) {
  5203. // // 如果已存在,移除旧的位置
  5204. // array_splice($versions, $existingIndex, 1);
  5205. // }
  5206. // // 新版本添加到数组开头(最新的在前)
  5207. // array_unshift($versions, $newVersion);
  5208. // // // 限制版本数量(可选,例如只保留最近10个版本)
  5209. // // if (count($versions) > 10) {
  5210. // // $versions = array_slice($versions, 0, 10);
  5211. // // }
  5212. // $updateData['versions'] = json_encode($versions, 256);
  5213. // }
  5214. if ($versions) {
  5215. $updateData['versions'] = json_encode($versions, 256);
  5216. }
  5217. $updateData['updated_at'] = date('Y-m-d H:i:s');
  5218. return DB::table('mp_products')
  5219. ->where('cpid', $cpid)
  5220. ->where('id', $id)->update($updateData);
  5221. }
  5222. /**
  5223. * 获取角色版本历史
  5224. * @param array $data 包含 id(角色ID)
  5225. * @return array 返回版本历史列表
  5226. */
  5227. public function getProductVersions($data) {
  5228. $cpid = Site::getCpid();
  5229. $id = getProp($data, 'id');
  5230. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5231. $role = DB::table('mp_products')
  5232. ->where('id', $id)
  5233. ->where('cpid', $cpid)
  5234. ->where('type', 1)
  5235. ->first();
  5236. if (!$role) Utils::throwError('20003:角色不存在');
  5237. // 获取版本历史
  5238. $versions = json_decode($role->versions, true) ?: [];
  5239. // 添加当前版本作为最新版本
  5240. $currentVersion = [
  5241. 'version' => 0, // 0 表示当前版本
  5242. 'url' => $role->url,
  5243. 'pic_prompt' => $role->pic_prompt,
  5244. 'updated_at' => $role->updated_at,
  5245. 'is_current' => true
  5246. ];
  5247. array_unshift($versions, $currentVersion);
  5248. return $versions;
  5249. }
  5250. /**
  5251. * 恢复到指定版本
  5252. * @param array $data 包含 id(角色ID)、version(版本号)
  5253. * @return bool
  5254. */
  5255. public function restoreProductVersion($data) {
  5256. $uid = Site::getUid();
  5257. $cpid = Site::getCpid();
  5258. $id = getProp($data, 'id');
  5259. $version = getProp($data, 'version');
  5260. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5261. if (!$version) Utils::throwError('20003:版本号不能为空');
  5262. $role = DB::table('mp_products')
  5263. ->where('id', $id)
  5264. ->where('cpid', $cpid)
  5265. ->where('type', 1)
  5266. ->first();
  5267. if (!$role) Utils::throwError('20003:角色不存在');
  5268. // 获取版本历史
  5269. $versions = json_decode($role->versions, true) ?: [];
  5270. // 查找指定版本
  5271. $targetVersion = null;
  5272. foreach ($versions as $v) {
  5273. if ($v['version'] == $version) {
  5274. $targetVersion = $v;
  5275. break;
  5276. }
  5277. }
  5278. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  5279. // 先将当前版本保存到历史
  5280. $newVersion = [
  5281. 'version' => count($versions) + 1,
  5282. 'url' => $role->url,
  5283. 'pic_prompt' => $role->pic_prompt,
  5284. 'updated_at' => date('Y-m-d H:i:s'),
  5285. 'updated_by' => $uid
  5286. ];
  5287. array_unshift($versions, $newVersion);
  5288. // 限制版本数量
  5289. if (count($versions) > 10) {
  5290. $versions = array_slice($versions, 0, 10);
  5291. }
  5292. // 恢复到指定版本
  5293. return DB::table('mp_products')
  5294. ->where('id', $id)
  5295. ->where('cpid', $cpid)
  5296. ->update([
  5297. 'url' => $targetVersion['url'],
  5298. 'pic_prompt' => $targetVersion['pic_prompt'],
  5299. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  5300. 'updated_at' => date('Y-m-d H:i:s')
  5301. ]);
  5302. }
  5303. public function deleteProduct($data) {
  5304. $uid = Site::getUid();
  5305. $cpid = Site::getCpid();
  5306. $id = getProp($data, 'id');
  5307. if (!$id) Utils::throwError('20003:ID不能为空');
  5308. $ids = explode(',', $id);
  5309. // 检查是否存在且属于当前用户
  5310. $role = DB::table('mp_products')
  5311. ->whereIn('id', $ids)
  5312. ->where('cpid', $cpid)
  5313. ->get();
  5314. if (!$role) Utils::throwError('20003:记录不存在');
  5315. return DB::table('mp_products')
  5316. ->where('cpid', $cpid)
  5317. ->whereIn('id', $ids)
  5318. ->update([
  5319. 'is_deleted' => 1,
  5320. 'updated_at' => date('Y-m-d H:i:s')
  5321. ]);
  5322. }
  5323. public function generateThreeView($data) {
  5324. $uid = Site::getUid();
  5325. $cpid = Site::getCpid();
  5326. $id = getProp($data, 'id');
  5327. if (!$id) Utils::throwError('20003:ID不能为空');
  5328. // 检查是否存在且属于当前用户
  5329. $role = DB::table('mp_products')
  5330. ->where('id', $id)
  5331. ->where('cpid', $cpid)
  5332. ->where('type', 1)->first();
  5333. if (!$role) Utils::throwError('20003:记录不存在');
  5334. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  5335. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  5336. if (!$ref_img_url) {
  5337. // 如果没有传入参考图,使用角色表中的图片
  5338. $ref_img_url = $role->url ?? '';
  5339. if (!$ref_img_url) {
  5340. Utils::throwError('20003:参考图不能为空');
  5341. }
  5342. }
  5343. // 检查参考图是否是正确的图片格式
  5344. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5345. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  5346. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5347. if (!in_array($extension, $allowedExtensions)) {
  5348. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5349. }
  5350. // 处理图片模型
  5351. $model = getProp($data, 'model');
  5352. if (!$model) {
  5353. // 使用默认模型
  5354. $model = 'doubao-seedream-5-0-lite-260128';
  5355. }
  5356. // 验证模型是否在可用模型表中
  5357. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5358. Utils::throwError('20003:该模型已不可用,请更换!');
  5359. }
  5360. try {
  5361. // 创建图片生成任务
  5362. $params = [
  5363. 'prompt' => $prompt,
  5364. 'model' => $model,
  5365. 'ref_img_urls' => [$ref_img_url],
  5366. 'width' => 1600,
  5367. 'height' => 2848
  5368. ];
  5369. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5370. $task_id = $task->id;
  5371. if (!$task_id) {
  5372. Utils::throwError('20003:创建图片生成任务失败');
  5373. }
  5374. // 检查任务模型类型
  5375. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5376. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5377. $isSyncModel = $isVolcModel || $isGptModel;
  5378. // 轮询获取结果(5分钟超时,每3秒查询一次)
  5379. $start_time = time();
  5380. $timeout = 300; // 5分钟
  5381. $img_url = '';
  5382. while (time() - $start_time < $timeout) {
  5383. sleep(3);
  5384. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5385. if ($isSyncModel) {
  5386. // 刷新任务状态
  5387. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5388. if ($task->status === 'success' && $task->result_url) {
  5389. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  5390. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  5391. break;
  5392. } elseif ($task->status === 'failed') {
  5393. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  5394. }
  5395. } else {
  5396. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5397. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5398. if ($statusInfo['status'] === 'success') {
  5399. $task->updateStatus('success', [
  5400. 'result_url' => $statusInfo['result_url'],
  5401. 'result_json' => $statusInfo['result_json'] ?? []
  5402. ]);
  5403. $img_url = $statusInfo['result_url'][0];
  5404. break;
  5405. } elseif ($statusInfo['status'] === 'failed') {
  5406. $task->updateStatus('failed', [
  5407. 'error_message' => $statusInfo['error_message'],
  5408. 'result_json' => $statusInfo['result_json'] ?? []
  5409. ]);
  5410. dLog('anime')->error('三视图生成失败', [
  5411. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5412. ]);
  5413. Utils::throwError('20003:三视图生成失败,' . ($statusInfo['error_message'] ?? '未知错误'));
  5414. }
  5415. }
  5416. }
  5417. if (empty($img_url)) {
  5418. Utils::throwError('20003:三视图生成超时,请稍后重试');
  5419. }
  5420. // 保存三视图到 mp_products 表
  5421. DB::table('mp_products')
  5422. ->where('id', $id)
  5423. ->where('cpid', $cpid)
  5424. ->update([
  5425. 'three_view_image_url' => $img_url,
  5426. 'updated_at' => date('Y-m-d H:i:s')
  5427. ]);
  5428. return ['three_view_image_url' => $img_url];
  5429. } catch (\Exception $e) {
  5430. dLog('anime')->error('生成三视图失败', [
  5431. 'error' => $e->getMessage()
  5432. ]);
  5433. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  5434. Utils::throwError('20003:' . $e->getMessage());
  5435. }
  5436. }
  5437. /**
  5438. * 保存剧本资产关联关系
  5439. * @param array $data 请求参数
  5440. * @return bool
  5441. */
  5442. public function saveScriptProducts($data) {
  5443. $uid = Site::getUid();
  5444. $cpid = Site::getCpid();
  5445. $script_id = getProp($data, 'script_id');
  5446. $products = getProp($data, 'products', []);
  5447. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  5448. if (!$script_id) {
  5449. Utils::throwError('20003:请提供剧本ID');
  5450. }
  5451. // 验证剧本是否存在
  5452. $script = DB::table('mp_scripts')
  5453. ->where('id', $script_id)
  5454. ->where('is_deleted', 0)
  5455. ->first();
  5456. if (!$script) {
  5457. Utils::throwError('20003:剧本不存在');
  5458. }
  5459. $script_name = $script->script_name ?? 'script_' . $script_id;
  5460. // 检查是否已经有该剧本的资产数据
  5461. $existingMappings = DB::table('mp_script_product_mappings')
  5462. ->where('script_id', $script_id)
  5463. ->get();
  5464. if ($existingMappings->isNotEmpty()) {
  5465. // 已存在资产映射,检查是否所有资产都有图片生成任务
  5466. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  5467. // 查询这些资产的图片生成任务状态
  5468. $productsWithTasks = DB::table('mp_products')
  5469. ->whereIn('id', $productIds)
  5470. ->where('is_deleted', 0)
  5471. ->get();
  5472. $productTaskMap = [];
  5473. $typeFolderIds = [];
  5474. $hasAllTasks = true;
  5475. foreach ($productsWithTasks as $product) {
  5476. // 收集类型文件夹ID
  5477. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  5478. $parentFolder = DB::table('mp_products')
  5479. ->where('id', $product->parent_id)
  5480. ->where('type', 2)
  5481. ->first();
  5482. if ($parentFolder) {
  5483. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  5484. }
  5485. }
  5486. // 检查是否有图片生成任务
  5487. if (!empty($product->pic_task_id)) {
  5488. $productTaskMap[$product->id] = $product->pic_task_id;
  5489. } else {
  5490. // 有资产没有图片任务
  5491. $hasAllTasks = false;
  5492. }
  5493. }
  5494. // 如果所有资产都有任务ID,直接轮询返回结果
  5495. if ($hasAllTasks && !empty($productTaskMap)) {
  5496. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  5497. 'script_id' => $script_id,
  5498. 'script_name' => $script_name,
  5499. 'product_count' => count($productTaskMap)
  5500. ]);
  5501. // 直接返回 SSE 流轮询结果
  5502. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  5503. }
  5504. // 如果部分资产没有任务ID,只为这些资产创建任务
  5505. if (!$hasAllTasks && $auto_generate_images) {
  5506. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  5507. 'script_id' => $script_id,
  5508. 'script_name' => $script_name
  5509. ]);
  5510. // 开启事务
  5511. DB::beginTransaction();
  5512. try {
  5513. // 默认图片生成参数
  5514. $model = 'doubao-seedream-5-0-lite-260128';
  5515. $width = 1600;
  5516. $height = 2848;
  5517. foreach ($productsWithTasks as $product) {
  5518. // 跳过已有任务的资产
  5519. if (!empty($product->pic_task_id)) {
  5520. continue;
  5521. }
  5522. // 跳过没有提示词的资产
  5523. if (empty($product->pic_prompt)) {
  5524. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  5525. 'product_id' => $product->id,
  5526. 'product_name' => $product->product_name
  5527. ]);
  5528. continue;
  5529. }
  5530. try {
  5531. // 创建图片生成任务
  5532. $params = [
  5533. 'prompt' => $product->pic_prompt,
  5534. 'model' => $model,
  5535. 'ref_img_urls' => [],
  5536. 'width' => $width,
  5537. 'height' => $height
  5538. ];
  5539. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5540. $task_id = $task->id;
  5541. if ($task_id) {
  5542. $productTaskMap[$product->id] = $task_id;
  5543. // 在事务中更新资产表的任务ID和状态
  5544. DB::table('mp_products')
  5545. ->where('id', $product->id)
  5546. ->update([
  5547. 'pic_task_id' => $task_id,
  5548. 'pic_task_status' => '生成中',
  5549. 'updated_at' => now()
  5550. ]);
  5551. dLog('anime')->info('为已存在资产创建图片生成任务', [
  5552. 'product_id' => $product->id,
  5553. 'task_id' => $task_id
  5554. ]);
  5555. }
  5556. } catch (\Exception $e) {
  5557. dLog('anime')->error('创建资产图片生成任务失败', [
  5558. 'product_id' => $product->id,
  5559. 'error' => $e->getMessage()
  5560. ]);
  5561. // 标记为失败(仍在事务中)
  5562. DB::table('mp_products')
  5563. ->where('id', $product->id)
  5564. ->update([
  5565. 'pic_task_status' => '生成失败',
  5566. 'updated_at' => now()
  5567. ]);
  5568. }
  5569. }
  5570. // 提交事务
  5571. DB::commit();
  5572. // 如果有新创建的任务,返回 SSE 流
  5573. if (!empty($productTaskMap)) {
  5574. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  5575. }
  5576. } catch (\Exception $e) {
  5577. // 回滚事务
  5578. DB::rollback();
  5579. dLog('anime')->error('为已存在资产创建图片任务失败', [
  5580. 'script_id' => $script_id,
  5581. 'error' => $e->getMessage()
  5582. ]);
  5583. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  5584. }
  5585. }
  5586. // 如果不需要生成图片,返回已存在的信息
  5587. return [
  5588. 'success' => true,
  5589. 'message' => '剧本资产已存在',
  5590. 'script_id' => $script_id,
  5591. 'script_name' => $script_name,
  5592. 'type_folder_ids' => $typeFolderIds,
  5593. 'existing_products' => count($productIds),
  5594. 'tasks_count' => count($productTaskMap)
  5595. ];
  5596. }
  5597. // 解析 products(可能是 JSON 字符串或数组)
  5598. if (is_string($products)) {
  5599. $products = json_decode($products, true);
  5600. if (json_last_error() !== JSON_ERROR_NONE) {
  5601. Utils::throwError('20003:产品数据格式错误');
  5602. }
  5603. }
  5604. if (!is_array($products) || empty($products)) {
  5605. Utils::throwError('20003:产品数据不能为空');
  5606. }
  5607. // 以下是原有的创建逻辑...
  5608. // 开启事务
  5609. DB::beginTransaction();
  5610. try {
  5611. $now = now();
  5612. $mappingRecords = [];
  5613. $createdProductIds = []; // 记录所有创建的资产ID
  5614. // 获取剧本名称
  5615. $script_name = $script->script_name ?? 'script_' . $script_id;
  5616. // 存储每个类型的根文件夹ID
  5617. $typeFolderIds = [];
  5618. // 默认图片生成参数
  5619. $model = 'doubao-seedream-5-0-lite-260128';
  5620. $width = 1600;
  5621. $height = 2848;
  5622. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  5623. foreach ($products as $productGroup) {
  5624. $type = getProp($productGroup, 'type');
  5625. $title = getProp($productGroup, 'title', '');
  5626. $content = getProp($productGroup, 'content', []);
  5627. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  5628. continue;
  5629. }
  5630. // 为当前类型创建根文件夹(如果还未创建)
  5631. if (!isset($typeFolderIds[$type])) {
  5632. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  5633. 'user_id' => $uid,
  5634. 'cpid' => $cpid,
  5635. 'type' => 2, // 1.资产 2文件夹
  5636. 'product' => $type, // 1.主体 2.场景 3.道具
  5637. 'parent_id' => 0, // 根文件夹,parent_id=0
  5638. 'level' => 1, // 第一层级
  5639. 'product_name' => $script_name,
  5640. 'sort_order' => time() + $type,
  5641. 'is_deleted' => 0,
  5642. 'created_at' => $now,
  5643. 'updated_at' => $now
  5644. ]);
  5645. }
  5646. $folder_id = $typeFolderIds[$type];
  5647. // 获取表头(第一行)并查找关键列的位置
  5648. $headers = $content[0];
  5649. $nameColumnIndex = -1; // 资产名称列索引
  5650. $sequenceColumnIndex = -1; // 使用范围列索引
  5651. $promptColumnIndex = -1; // 参考提示词列索引
  5652. foreach ($headers as $index => $header) {
  5653. // 查找"资产名称"列
  5654. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  5655. $nameColumnIndex = $index;
  5656. }
  5657. // 查找"使用范围"列
  5658. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  5659. $sequenceColumnIndex = $index;
  5660. }
  5661. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  5662. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  5663. $promptColumnIndex = $index;
  5664. }
  5665. }
  5666. // 验证必要的列是否都找到了
  5667. if ($nameColumnIndex === -1) {
  5668. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  5669. continue;
  5670. }
  5671. if ($sequenceColumnIndex === -1) {
  5672. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  5673. continue;
  5674. }
  5675. // 跳过表头,解析每一行数据
  5676. for ($i = 1; $i < count($content); $i++) {
  5677. $row = $content[$i];
  5678. // 确保行数据有效
  5679. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  5680. continue;
  5681. }
  5682. // 根据动态查找的列索引提取数据
  5683. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  5684. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  5685. $pic_prompt = '';
  5686. // 提取参考提示词(如果找到了该列)
  5687. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  5688. $pic_prompt = trim($row[$promptColumnIndex]);
  5689. }
  5690. // 解析使用范围(逗号分隔的序号)
  5691. $sequences = [];
  5692. if (!empty($sequence_str)) {
  5693. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  5694. foreach ($sequenceParts as $part) {
  5695. if (is_numeric($part)) {
  5696. $sequences[] = (int)$part;
  5697. }
  5698. }
  5699. }
  5700. if (empty($product_name)) {
  5701. continue;
  5702. }
  5703. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  5704. $product_id = DB::table('mp_products')->insertGetId([
  5705. 'product_name' => $product_name,
  5706. 'type' => 1, // 1=资产 2.文件夹
  5707. 'product' => $type, // 1=角色, 2=场景, 3=道具
  5708. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  5709. 'level' => 2, // 第二层级
  5710. 'pic_prompt' => $pic_prompt,
  5711. 'user_id' => $uid,
  5712. 'cpid' => $cpid,
  5713. 'sort_order' => time(),
  5714. 'is_deleted' => 0,
  5715. 'created_at' => $now,
  5716. 'updated_at' => $now,
  5717. ]);
  5718. // 记录创建的资产ID
  5719. $createdProductIds[] = $product_id;
  5720. // 为每个序号创建映射记录
  5721. if (!empty($sequences)) {
  5722. foreach ($sequences as $sequence) {
  5723. $mappingRecords[] = [
  5724. 'script_id' => $script_id,
  5725. 'product_id' => $product_id,
  5726. 'episode_number' => $sequence,
  5727. 'created_at' => $now,
  5728. 'updated_at' => $now,
  5729. ];
  5730. }
  5731. } else {
  5732. // 如果没有指定序号,创建一个默认映射(序号为0)
  5733. $mappingRecords[] = [
  5734. 'script_id' => $script_id,
  5735. 'product_id' => $product_id,
  5736. 'episode_number' => 0,
  5737. 'created_at' => $now,
  5738. 'updated_at' => $now,
  5739. ];
  5740. }
  5741. }
  5742. }
  5743. if (empty($mappingRecords)) {
  5744. Utils::throwError('20003:没有有效的产品数据');
  5745. }
  5746. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  5747. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  5748. // 如果需要自动生成图片,在事务中创建图片生成任务
  5749. $productTaskMap = [];
  5750. if ($auto_generate_images && !empty($createdProductIds)) {
  5751. // 查询所有创建的资产
  5752. $productsToGenerate = DB::table('mp_products')
  5753. ->whereIn('id', $createdProductIds)
  5754. ->where('is_deleted', 0)
  5755. ->get();
  5756. foreach ($productsToGenerate as $product) {
  5757. if (empty($product->pic_prompt)) {
  5758. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  5759. 'product_id' => $product->id,
  5760. 'product_name' => $product->product_name
  5761. ]);
  5762. continue;
  5763. }
  5764. try {
  5765. // 创建图片生成任务
  5766. $params = [
  5767. 'prompt' => $product->pic_prompt,
  5768. 'model' => $model,
  5769. 'ref_img_urls' => [],
  5770. 'width' => $width,
  5771. 'height' => $height
  5772. ];
  5773. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5774. $task_id = $task->id;
  5775. if ($task_id) {
  5776. $productTaskMap[$product->id] = $task_id;
  5777. // 在事务中更新资产表的任务ID和状态
  5778. DB::table('mp_products')
  5779. ->where('id', $product->id)
  5780. ->update([
  5781. 'pic_task_id' => $task_id,
  5782. 'pic_task_status' => '生成中',
  5783. 'updated_at' => now()
  5784. ]);
  5785. dLog('anime')->info('创建资产图片生成任务', [
  5786. 'product_id' => $product->id,
  5787. 'task_id' => $task_id
  5788. ]);
  5789. }
  5790. } catch (\Exception $e) {
  5791. dLog('anime')->error('创建资产图片生成任务失败', [
  5792. 'product_id' => $product->id,
  5793. 'error' => $e->getMessage()
  5794. ]);
  5795. // 标记为失败(仍在事务中)
  5796. DB::table('mp_products')
  5797. ->where('id', $product->id)
  5798. ->update([
  5799. 'pic_task_status' => '生成失败',
  5800. 'updated_at' => now()
  5801. ]);
  5802. }
  5803. }
  5804. }
  5805. // 提交事务
  5806. DB::commit();
  5807. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  5808. if ($auto_generate_images && !empty($productTaskMap)) {
  5809. // 返回 SSE 流(事务外轮询)
  5810. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  5811. }
  5812. // 如果不需要生成图片,返回普通结果
  5813. return [
  5814. 'success' => true,
  5815. 'type_folder_ids' => $typeFolderIds,
  5816. 'inserted_count' => $insertedCount,
  5817. 'total_records' => count($mappingRecords),
  5818. 'created_products' => count($createdProductIds),
  5819. 'image_tasks_created' => count($productTaskMap)
  5820. ];
  5821. } catch (\Exception $e) {
  5822. // 回滚事务
  5823. DB::rollback();
  5824. // 记录错误日志
  5825. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  5826. 'script_id' => $script_id,
  5827. 'error' => $e->getMessage(),
  5828. 'trace' => $e->getTraceAsString()
  5829. ]);
  5830. // 统一使用 Utils::throwError 抛出错误
  5831. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  5832. }
  5833. }
  5834. /**
  5835. * 批量为剧本资产生成图片
  5836. *
  5837. * @param array $data 请求参数
  5838. * @return \Generator 返回 SSE 流
  5839. */
  5840. public function batchGenerateProductImages($data) {
  5841. $script_id = getProp($data, 'script_id');
  5842. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  5843. if (!$script_id) {
  5844. Utils::throwError('20003:请提供剧本ID');
  5845. }
  5846. // 验证剧本是否存在
  5847. $script = DB::table('mp_scripts')
  5848. ->where('id', $script_id)
  5849. ->where('is_deleted', 0)
  5850. ->first();
  5851. if (!$script) {
  5852. Utils::throwError('20003:剧本不存在');
  5853. }
  5854. $script_name = $script->script_name ?? 'script_' . $script_id;
  5855. // 获取需要生成图片的所有资产
  5856. $products = DB::table('mp_products')
  5857. ->whereIn('parent_id', array_values($type_folder_ids))
  5858. ->where('is_deleted', 0)
  5859. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  5860. ->get();
  5861. if ($products->isEmpty()) {
  5862. Utils::throwError('20003:没有找到需要生成图片的资产');
  5863. }
  5864. // 默认参数
  5865. $model = 'doubao-seedream-5-0-lite-260128';
  5866. $width = 1600;
  5867. $height = 2848;
  5868. // 开始为每个资产创建图片生成任务
  5869. $taskIds = [];
  5870. $productTaskMap = []; // 资产ID到任务ID的映射
  5871. foreach ($products as $product) {
  5872. if (empty($product->pic_prompt)) {
  5873. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  5874. continue;
  5875. }
  5876. try {
  5877. // 创建图片生成任务
  5878. $params = [
  5879. 'prompt' => $product->pic_prompt,
  5880. 'model' => $model,
  5881. 'ref_img_urls' => [],
  5882. 'width' => $width,
  5883. 'height' => $height
  5884. ];
  5885. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5886. $task_id = $task->id;
  5887. if ($task_id) {
  5888. $taskIds[] = $task_id;
  5889. $productTaskMap[$product->id] = $task_id;
  5890. // 更新资产表的任务ID和状态
  5891. DB::table('mp_products')
  5892. ->where('id', $product->id)
  5893. ->update([
  5894. 'pic_task_id' => $task_id,
  5895. 'pic_task_status' => '生成中',
  5896. 'updated_at' => now()
  5897. ]);
  5898. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  5899. }
  5900. } catch (\Exception $e) {
  5901. dLog('anime')->error('创建资产图片生成任务失败', [
  5902. 'product_id' => $product->id,
  5903. 'error' => $e->getMessage()
  5904. ]);
  5905. // 标记为失败
  5906. DB::table('mp_products')
  5907. ->where('id', $product->id)
  5908. ->update([
  5909. 'pic_task_status' => '生成失败',
  5910. 'updated_at' => now()
  5911. ]);
  5912. }
  5913. }
  5914. if (empty($taskIds)) {
  5915. Utils::throwError('20003:没有成功创建任何图片生成任务');
  5916. }
  5917. // 返回 SSE 流
  5918. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  5919. }
  5920. /**
  5921. * 轮询资产图片生成任务状态(SSE流式返回)
  5922. * 只通过查询数据库获取任务状态,不主动调用API
  5923. *
  5924. * @param int $script_id 剧本ID
  5925. * @param string $script_name 剧本名称
  5926. * @param array $productTaskMap 资产ID到任务ID的映射
  5927. * @param array $type_folder_ids 类型文件夹ID映射
  5928. * @return \Generator
  5929. */
  5930. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  5931. $startTime = time();
  5932. $timeout = 1800; // 30分钟超时
  5933. $pollInterval = 10; // 10秒轮询一次
  5934. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  5935. // 定义类型名称映射
  5936. $typeNames = [
  5937. 1 => 'roles', // 角色
  5938. 2 => 'scenes', // 场景
  5939. 3 => 'props' // 道具
  5940. ];
  5941. while (time() - $startTime < $timeout) {
  5942. sleep($pollInterval);
  5943. // 查询所有资产的当前状态
  5944. $products = DB::table('mp_products')
  5945. ->whereIn('id', array_keys($productTaskMap))
  5946. ->where('is_deleted', 0)
  5947. ->get();
  5948. // 统计各类型的状态(使用类型名称作为键名)
  5949. $stats = [
  5950. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  5951. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  5952. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  5953. ];
  5954. $allCompleted = true;
  5955. $hasStatusChange = false;
  5956. foreach ($products as $product) {
  5957. $type = $product->product;
  5958. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  5959. // 如果类型名称不在 stats 中,初始化
  5960. if (!isset($stats[$typeName])) {
  5961. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  5962. }
  5963. $stats[$typeName]['total']++;
  5964. $task_id = $product->pic_task_id;
  5965. $currentStatus = $product->pic_task_status;
  5966. // 检查状态是否有变化
  5967. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  5968. $hasStatusChange = true;
  5969. $lastStatus[$product->id] = $currentStatus;
  5970. }
  5971. // 如果是生成中,查询任务表状态
  5972. if ($currentStatus === '生成中' && $task_id) {
  5973. // 只查询数据库,不调用API
  5974. $task = DB::table('mp_generate_pic_tasks')
  5975. ->where('id', $task_id)
  5976. ->first();
  5977. if ($task) {
  5978. // 检查任务状态
  5979. if ($task->status === 'success' && $task->result_url) {
  5980. // 解析图片URL
  5981. $result_urls = $task->result_url;
  5982. if (is_string($result_urls)) {
  5983. $result_urls = json_decode($result_urls, true);
  5984. }
  5985. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  5986. // 更新资产表状态
  5987. DB::table('mp_products')
  5988. ->where('id', $product->id)
  5989. ->update([
  5990. 'pic_task_status' => '生成成功',
  5991. 'url' => $img_url,
  5992. 'updated_at' => now()
  5993. ]);
  5994. $stats[$typeName]['success']++;
  5995. $stats[$typeName]['completed']++;
  5996. $hasStatusChange = true;
  5997. dLog('anime')->info('资产图片生成成功', [
  5998. 'product_id' => $product->id,
  5999. 'task_id' => $task_id,
  6000. 'img_url' => $img_url
  6001. ]);
  6002. } elseif ($task->status === 'failed') {
  6003. // 更新资产表状态
  6004. DB::table('mp_products')
  6005. ->where('id', $product->id)
  6006. ->update([
  6007. 'pic_task_status' => '生成失败',
  6008. 'updated_at' => now()
  6009. ]);
  6010. $stats[$typeName]['completed']++;
  6011. $hasStatusChange = true;
  6012. dLog('anime')->warning('资产图片生成失败', [
  6013. 'product_id' => $product->id,
  6014. 'task_id' => $task_id,
  6015. 'error' => $task->error_message ?? '未知错误'
  6016. ]);
  6017. } else {
  6018. // 任务还在处理中
  6019. $allCompleted = false;
  6020. }
  6021. } else {
  6022. // 任务不存在,标记为失败
  6023. DB::table('mp_products')
  6024. ->where('id', $product->id)
  6025. ->update([
  6026. 'pic_task_status' => '生成失败',
  6027. 'updated_at' => now()
  6028. ]);
  6029. $stats[$type]['completed']++;
  6030. $hasStatusChange = true;
  6031. dLog('anime')->error('图片生成任务不存在', [
  6032. 'product_id' => $product->id,
  6033. 'task_id' => $task_id
  6034. ]);
  6035. }
  6036. } elseif ($currentStatus === '生成成功') {
  6037. $stats[$typeName]['success']++;
  6038. $stats[$typeName]['completed']++;
  6039. } elseif ($currentStatus === '生成失败') {
  6040. $stats[$typeName]['completed']++;
  6041. } else {
  6042. // 其他状态也认为未完成
  6043. $allCompleted = false;
  6044. }
  6045. }
  6046. // 移除没有数据的类型(total=0)
  6047. foreach ($stats as $typeName => $stat) {
  6048. if ($stat['total'] === 0) {
  6049. unset($stats[$typeName]);
  6050. }
  6051. }
  6052. // 如果有状态变化,发送 SSE 更新
  6053. if ($hasStatusChange) {
  6054. $eventType = $allCompleted ? 'complete' : 'update';
  6055. $response = [
  6056. 'type' => $eventType,
  6057. 'script_id' => $script_id,
  6058. 'script_name' => $script_name,
  6059. 'stats' => $stats,
  6060. 'timestamp' => date('Y-m-d H:i:s')
  6061. ];
  6062. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  6063. dLog('anime')->info('SSE更新', [
  6064. 'event_type' => $eventType,
  6065. 'script_id' => $script_id,
  6066. 'script_name' => $script_name,
  6067. 'stats' => $stats
  6068. ]);
  6069. if ($allCompleted) {
  6070. dLog('anime')->info('所有资产图片生成任务已完成', [
  6071. 'script_id' => $script_id,
  6072. 'script_name' => $script_name,
  6073. 'stats' => $stats
  6074. ]);
  6075. break;
  6076. }
  6077. }
  6078. }
  6079. // 超时处理
  6080. if (time() - $startTime >= $timeout && !$allCompleted) {
  6081. $response = [
  6082. 'type' => 'timeout',
  6083. 'message' => '部分任务超时,请稍后查看结果',
  6084. 'script_id' => $script_id,
  6085. 'script_name' => $script_name,
  6086. 'timestamp' => date('Y-m-d H:i:s')
  6087. ];
  6088. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  6089. dLog('anime')->warning('资产图片生成任务超时', [
  6090. 'script_id' => $script_id,
  6091. 'script_name' => $script_name,
  6092. 'timeout' => $timeout
  6093. ]);
  6094. }
  6095. }
  6096. /**
  6097. * 获取剧本关联的资产列表
  6098. * @param array $data 请求参数
  6099. * @return array
  6100. */
  6101. public function getScriptProducts($data) {
  6102. $uid = Site::getUid();
  6103. $cpid = Site::getCpid();
  6104. $script_id = getProp($data, 'script_id');
  6105. $episode_number = getProp($data, 'episode_number');
  6106. if (!$script_id) {
  6107. Utils::throwError('20003:请提供剧本ID');
  6108. }
  6109. // 验证剧本是否存在
  6110. $script = DB::table('mp_scripts')
  6111. ->where('id', $script_id)
  6112. ->where('is_deleted', 0)
  6113. ->first();
  6114. if (!$script) {
  6115. Utils::throwError('20003:剧本不存在');
  6116. }
  6117. // 联表查询资产信息
  6118. $query = DB::table('mp_script_product_mappings as mapping')
  6119. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6120. ->where('mapping.script_id', $script_id)
  6121. ->where('product.cpid', $cpid)
  6122. ->where('product.is_deleted', 0);
  6123. // 如果提供了 episode_number,则过滤指定集数
  6124. if ($episode_number !== null && $episode_number !== '') {
  6125. $query->where('mapping.episode_number', $episode_number);
  6126. }
  6127. $mappings = $query->select(
  6128. 'mapping.script_id',
  6129. 'mapping.product_id',
  6130. 'mapping.episode_number',
  6131. 'product.product_name',
  6132. 'product.type',
  6133. 'product.product',
  6134. 'product.pic_prompt',
  6135. 'product.url',
  6136. 'product.pic_task_id',
  6137. 'product.pic_task_status',
  6138. 'product.three_view_image_url',
  6139. 'mapping.created_at'
  6140. )
  6141. ->orderBy('mapping.product_id', 'asc')
  6142. ->orderBy('mapping.episode_number', 'asc')
  6143. ->get();
  6144. // 按 product_id 分组,合并 episode_number
  6145. $productMap = [];
  6146. foreach ($mappings as $item) {
  6147. $product_id = $item->product_id;
  6148. if (!isset($productMap[$product_id])) {
  6149. $productMap[$product_id] = [
  6150. 'product_id' => $product_id,
  6151. 'product_name' => $item->product_name,
  6152. 'type' => (int)$item->type,
  6153. 'product' => (int)$item->product,
  6154. 'pic_prompt' => $item->pic_prompt,
  6155. 'url' => $item->url,
  6156. 'pic_task_id' => $item->pic_task_id,
  6157. 'pic_task_status' => $item->pic_task_status,
  6158. 'episode_numbers' => [],
  6159. 'created_at' => $item->created_at,
  6160. ];
  6161. }
  6162. // 添加 episode_number(去重)
  6163. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6164. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6165. }
  6166. }
  6167. // 按类型分组
  6168. $roles = []; // type=1 角色/主体
  6169. $scenes = []; // type=2 场景
  6170. $props = []; // type=3 道具
  6171. foreach ($productMap as $product) {
  6172. // 将 episode_numbers 数组转换为逗号分隔的字符串
  6173. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  6174. // 构造返回数据
  6175. $productData = [
  6176. 'product_id' => $product['product_id'],
  6177. 'product_name' => $product['product_name'],
  6178. 'product' => $product['product'],
  6179. 'pic_prompt' => $product['pic_prompt'],
  6180. 'url' => $product['url'],
  6181. 'pic_task_id' => $product['pic_task_id'],
  6182. 'pic_task_status' => $product['pic_task_status'],
  6183. 'episode_numbers' => $episodeNumbersStr,
  6184. 'created_at' => $product['created_at'],
  6185. ];
  6186. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  6187. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  6188. switch ($product['product']) {
  6189. case 1:
  6190. $roles[] = $productData;
  6191. break;
  6192. case 2:
  6193. $scenes[] = $productData;
  6194. break;
  6195. case 3:
  6196. $props[] = $productData;
  6197. break;
  6198. }
  6199. }
  6200. return [
  6201. 'script_id' => $script_id,
  6202. 'script_name' => $script->script_name ?? '',
  6203. 'roles' => $roles, // 主体
  6204. 'scenes' => $scenes, // 场景
  6205. 'props' => $props, // 道具
  6206. ];
  6207. }
  6208. /**
  6209. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  6210. * @param string $actContent 原始内容
  6211. * @param array $products 产品数组(包含product_name和url)
  6212. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  6213. */
  6214. public function processActContentWithProducts($actContent, $products) {
  6215. if (empty($actContent) || empty($products)) {
  6216. return [
  6217. 'content' => $actContent,
  6218. 'reference_images' => []
  6219. ];
  6220. }
  6221. // 构建产品名称到产品信息的映射
  6222. $product_dict = [];
  6223. foreach ($products as $product) {
  6224. $product_name = getProp($product, 'product_name');
  6225. if ($product_name) {
  6226. $product_dict[$product_name] = [
  6227. 'url' => getProp($product, 'url'),
  6228. 'voice_prompt' => getProp($product, 'voice_prompt')
  6229. ];
  6230. }
  6231. }
  6232. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  6233. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  6234. $reference_images = [];
  6235. $product_index_map = []; // 产品名称 => 图片序号的映射
  6236. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  6237. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  6238. $current_index = 1;
  6239. if (!empty($matches[1])) {
  6240. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  6241. $seen_products = []; // 用于去重
  6242. foreach ($matches[1] as $product_name) {
  6243. // 跳过已处理的产品
  6244. if (isset($seen_products[$product_name])) {
  6245. continue;
  6246. }
  6247. $seen_products[$product_name] = true;
  6248. // 检查产品是否在字典中
  6249. if (isset($product_dict[$product_name])) {
  6250. $url = $product_dict[$product_name]['url'];
  6251. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  6252. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  6253. if (!empty($voice_prompt) && $product_name !== '旁白') {
  6254. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  6255. }
  6256. // 只有URL非空才分配序号和添加到参考图片
  6257. if (!empty($url)) {
  6258. // 检查URL是否已经在reference_images中(去重)
  6259. if (!in_array($url, $reference_images)) {
  6260. $reference_images[] = $url;
  6261. $product_index_map[$product_name] = $current_index;
  6262. $current_index++;
  6263. } else {
  6264. // URL重复,找到已有的序号
  6265. $existing_index = array_search($url, $reference_images) + 1;
  6266. $product_index_map[$product_name] = $existing_index;
  6267. }
  6268. } else {
  6269. // URL为空,不分配序号(后续直接去掉{})
  6270. $product_index_map[$product_name] = 0;
  6271. }
  6272. } else {
  6273. // 产品不在字典中,不分配序号
  6274. $product_index_map[$product_name] = 0;
  6275. }
  6276. }
  6277. }
  6278. // 第二步:替换内容中的 {产品名称}
  6279. $processedContent = $actContent;
  6280. foreach ($product_index_map as $product_name => $index) {
  6281. $escaped_name = preg_quote($product_name, '/');
  6282. if ($index > 0) {
  6283. // 有图片,替换为:产品名称(图X)
  6284. $replacement = $product_name . '<图片' . $index . '>';
  6285. } else {
  6286. // 无图片,只保留产品名称
  6287. $replacement = $product_name;
  6288. }
  6289. // 替换所有 {产品名称} 为处理后的格式
  6290. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  6291. }
  6292. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  6293. foreach ($products as $product) {
  6294. $product_name = getProp($product, 'product_name');
  6295. $voice_prompt = getProp($product, 'voice_prompt');
  6296. if ($product_name === '旁白' && !empty($voice_prompt)) {
  6297. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  6298. break; // 找到旁白后退出循环
  6299. }
  6300. }
  6301. // 第四步:将voice_prompt信息添加到内容最前面
  6302. $voice_prompt_prefix = '';
  6303. if (!empty($voice_prompts)) {
  6304. $voice_prompt_prefix .= implode('', $voice_prompts);
  6305. }
  6306. // 旁白的voice_prompt放在最后
  6307. if (!empty($narrator_voice_prompt)) {
  6308. $voice_prompt_prefix .= $narrator_voice_prompt;
  6309. }
  6310. // 如果有voice_prompt信息,添加到内容开头
  6311. if (!empty($voice_prompt_prefix)) {
  6312. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  6313. }
  6314. return [
  6315. 'content' => $processedContent,
  6316. 'reference_images' => $reference_images
  6317. ];
  6318. }
  6319. public function saveActVideoGenerateParams($data) {
  6320. $episode_id = getProp($data, 'episode_id');
  6321. $model = getProp($data, 'video_model');
  6322. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  6323. Utils::throwError('20003:该模型不可用');
  6324. }
  6325. if (!$model) {
  6326. // 使用默认模型
  6327. $model = 'zhizhen-20-mini';
  6328. }
  6329. // 验证模型是否在可用模型表中
  6330. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6331. Utils::throwError('20003:该模型已不可用,请更换!');
  6332. }
  6333. $video_resolution = getProp($data, 'video_resolution', '720p');
  6334. $ratio = getProp($data, 'ratio');
  6335. if (!$ratio) $ratio = '9:16';
  6336. return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  6337. 'video_model' => $model,
  6338. 'video_resolution' => $video_resolution,
  6339. 'ratio' => $ratio,
  6340. 'updated_at' => date('Y-m-d H:i:s')
  6341. ]);
  6342. }
  6343. public function confirmActs($data) {
  6344. $episode_id = getProp($data, 'episode_id');
  6345. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  6346. if (!$episode) {
  6347. Utils::throwError('20003:分集不存在');
  6348. }
  6349. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  6350. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  6351. // 获取所有片段数据
  6352. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  6353. // 构建角色和场景名称数组
  6354. $role_names = [];
  6355. $scene_names = [];
  6356. foreach ($roles as $role) {
  6357. $role_name = getProp($role, 'role');
  6358. if ($role_name && $role_name != '旁白') {
  6359. $role_names[] = $role_name;
  6360. }
  6361. }
  6362. foreach ($scenes as $scene) {
  6363. $scene_name = getProp($scene, 'scene');
  6364. if ($scene_name) {
  6365. $scene_names[] = $scene_name;
  6366. }
  6367. }
  6368. // 按照字符长度降序排序,确保先匹配长的名称(避免部分匹配问题)
  6369. usort($role_names, function($a, $b) {
  6370. return mb_strlen($b) - mb_strlen($a);
  6371. });
  6372. usort($scene_names, function($a, $b) {
  6373. return mb_strlen($b) - mb_strlen($a);
  6374. });
  6375. try {
  6376. DB::beginTransaction();
  6377. // 处理每个片段
  6378. foreach ($acts as $act) {
  6379. $act_content = getProp($act, 'act_content');
  6380. if (!$act_content) continue;
  6381. $processed_content = $act_content;
  6382. // 标记已处理的位置,避免重复标记
  6383. $marked_positions = [];
  6384. // 先匹配场景(在"场景:"后面)
  6385. foreach ($scene_names as $scene_name) {
  6386. // 转义特殊字符
  6387. $escaped_scene = preg_quote($scene_name, '/');
  6388. // 匹配场景:后面的场景名称(可能换行,也可能不换行)
  6389. $pattern = '/(场景:[\s\r\n]*)(' . $escaped_scene . ')/u';
  6390. $processed_content = preg_replace_callback($pattern, function($matches) use (&$marked_positions) {
  6391. $full_match = $matches[0];
  6392. $prefix = $matches[1];
  6393. $scene_name = $matches[2];
  6394. // 检查是否已经被标记
  6395. if (strpos($scene_name, '{') === false && strpos($scene_name, '}') === false) {
  6396. return $prefix . '{' . $scene_name . '}';
  6397. }
  6398. return $full_match;
  6399. }, $processed_content);
  6400. }
  6401. // 再匹配角色名称(只在"画面:"部分)
  6402. foreach ($role_names as $role_name) {
  6403. // 转义特殊字符
  6404. $escaped_role = preg_quote($role_name, '/');
  6405. // 只匹配"画面:"开始到换行之前的内容
  6406. $pattern = '/(画面:[^\n]*)/u';
  6407. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
  6408. $line = $matches[1]; // 整行"画面:xxxxx"
  6409. // 在这一行中匹配所有角色名(避免重复标记)
  6410. $new_line = preg_replace(
  6411. '/(?<![{])(' . $escaped_role . ')(?![}])/u',
  6412. '{$1}',
  6413. $line
  6414. );
  6415. return $new_line;
  6416. }, $processed_content);
  6417. }
  6418. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  6419. $shot_counter = 0;
  6420. $processed_content = preg_replace_callback(
  6421. '/【(?:镜头|分镜)(\d+)】/u',
  6422. function($matches) use (&$shot_counter) {
  6423. $shot_counter++;
  6424. return '【镜头' . $shot_counter . '】';
  6425. },
  6426. $processed_content
  6427. );
  6428. // 更新数据库
  6429. $boolen = DB::table('mp_episode_segments')
  6430. ->where('id', $act->id)
  6431. ->update([
  6432. 'act_show_content' => $processed_content,
  6433. 'updated_at' => date('Y-m-d H:i:s')
  6434. ]);
  6435. if (!$boolen) {
  6436. Utils::throwError('20003:片段处理失败');
  6437. }
  6438. }
  6439. }catch (\Exception $e) {
  6440. DB::rollBack();
  6441. Utils::throwError('20003:'.$e->getMessage());
  6442. }
  6443. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  6444. 'is_generated' => 1,
  6445. 'updated_at' => date('Y-m-d H:i:s')
  6446. ]);
  6447. if (!$boolen1) {
  6448. DB::rollBack();
  6449. Utils::throwError('20003:分集处理失败!');
  6450. }
  6451. DB::commit();
  6452. // 重新查询更新后的片段数据
  6453. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  6454. // 合并角色、场景和extra_products作为products,统一字段名为product_name
  6455. // extra_products优先级更高,会覆盖同名的roles和scenes
  6456. $products = [];
  6457. // 先处理角色数组
  6458. foreach ($roles as $role) {
  6459. $product = $role;
  6460. // 将role字段重命名为product_name
  6461. if (isset($product['role'])) {
  6462. $product['product_name'] = $product['role'];
  6463. unset($product['role']);
  6464. }
  6465. $product['product'] = 1; // 标记类型为角色
  6466. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  6467. }
  6468. // 处理场景数组
  6469. foreach ($scenes as $scene) {
  6470. $product = $scene;
  6471. // 将scene字段重命名为product_name
  6472. if (isset($product['scene'])) {
  6473. $product['product_name'] = $product['scene'];
  6474. unset($product['scene']);
  6475. }
  6476. $product['product'] = 2; // 标记类型为场景
  6477. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  6478. }
  6479. // extra_products优先级更高,直接覆盖同名的roles和scenes
  6480. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  6481. foreach ($extra_products as $extra_product) {
  6482. $product_name = getProp($extra_product, 'product_name');
  6483. if ($product_name) {
  6484. $products[$product_name] = $extra_product; // 覆盖同名数据
  6485. }
  6486. }
  6487. // 重新索引数组(去除key)
  6488. $products = array_values($products);
  6489. // 构建返回的acts数组
  6490. $return_acts = [];
  6491. foreach ($acts as $act) {
  6492. $return_acts[] = [
  6493. 'act_id' => getProp($act, 'id'),
  6494. 'act_number' => getProp($act, 'act_number'),
  6495. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  6496. 'act_show_content' => getProp($act, 'act_show_content'),
  6497. 'video_url' => getProp($act, 'video_url'),
  6498. 'video_duration' => getProp($act, 'video_duration'),
  6499. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  6500. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  6501. ];
  6502. }
  6503. return [
  6504. 'anime_id' => getProp($episode, 'anime_id'),
  6505. 'episode_id' => $episode_id,
  6506. 'title' => getProp($episode, 'title'),
  6507. 'episode_number' => getProp($episode, 'episode_number'),
  6508. 'is_generated' => getProp($episode, 'is_generated'),
  6509. 'products' => $products,
  6510. 'acts' => $return_acts
  6511. ];
  6512. }
  6513. }