| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882 |
- <?php
- namespace App\Services\Anime;
- use App\Consts\BaseConst;
- use App\Consts\ErrorConst;
- use App\Facade\Site;
- use App\Libs\Utils;
- use App\Models\MpGeneratePicTask;
- use App\Services\AIGeneration\AIImageGenerationService;
- use App\Services\AIGeneration\AIVideoGenerationService;
- use App\Services\DeepSeek\DeepSeekService;
- use Dflydev\DotAccessData\Util;
- use GuzzleHttp\Client;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Redis;
- use OSS\Core\OssException;
- use OSS\OssClient;
- class AnimeService
- {
- protected $aiImageGenerationService;
- protected $aiVideoGenerationService;
- protected $DeepSeekService;
- private $url;
- private $api_key;
- private $headers;
- public function __construct(
- AIImageGenerationService $aiImageGenerationService,
- AIVideoGenerationService $aiVideoGenerationService,
- DeepSeekService $DeepSeekService
- ) {
- $this->aiImageGenerationService = $aiImageGenerationService;
- $this->aiVideoGenerationService = $aiVideoGenerationService;
- $this->DeepSeekService = $DeepSeekService;
- $this->url = 'https://api.deepseek.com/chat/completions';
- $this->api_key = env('DEEPSEEK_API_KEY');
- $this->headers = [
- 'Authorization' => 'Bearer '.$this->api_key,
- 'Content-Type' => 'application/json; charset=UTF-8'
- ];
- }
- /**
- * 构建统一的分镜数据结构(episodeInfo格式)
- * @param array $segments 分镜数据数组
- * @return array 返回包含acts和total_duration的数组
- */
- public function buildEpisodeSegmentsStructure($segments) {
- $acts = [];
- $totalDuration = 0; // 初始化总时长
-
- foreach($segments as $segment) {
- // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
- $videoDuration = getProp($segment, 'video_duration');
- $audioDuration = getProp($segment, 'audio_duration');
-
- if (!empty($videoDuration) && is_numeric($videoDuration)) {
- $totalDuration += floatval($videoDuration);
- } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
- $totalDuration += floatval($audioDuration);
- } else {
- $totalDuration += 5; // 默认5秒
- }
-
- $segment_content = getProp($segment, 'segment_content');
- // 判断是否有尾帧描述,如果有则去掉这部分内容
- if (strpos($segment_content, '尾帧') !== false) {
- // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
- $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
- }
- // 构建分镜信息
- $segmentInfo = [
- 'segment_id' => getProp($segment, 'segment_id'),
- 'segment_number' => getProp($segment, 'segment_number'),
- 'segment_content' => $segment_content,
- 'description' => getProp($segment, 'description'),
- 'composition' => getProp($segment, 'composition'),
- 'camera_movement' => getProp($segment, 'camera_movement'),
- 'voice_actor' => getProp($segment, 'voice_actor'),
- 'dialogue' => getProp($segment, 'dialogue'),
- 'frame_type' => getProp($segment, 'frame_type'),
- 'scene' => getProp($segment, 'scene'),
- 'characters' => getProp($segment, 'characters'),
- 'tail_frame' => getProp($segment, 'tail_frame'),
- 'emotion' => getProp($segment, 'emotion'),
- 'emotion_type' => getProp($segment, 'emotion_type'),
- 'gender' => getProp($segment, 'gender'),
- 'speed_ratio' => getProp($segment, 'speed_ratio'),
- 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
- 'emotion_scale' => getProp($segment, 'emotion_scale'),
- 'pitch' => getProp($segment, 'pitch'),
- 'voice_name' => getProp($segment, 'voice_name'),
- 'voice_type' => getProp($segment, 'voice_type'),
- 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
- 'img_url' => getProp($segment, 'img_url'),
- 'audio_url' => getProp($segment, 'audio_url'),
- 'audio_duration' => getProp($segment, 'audio_duration', 0),
- 'video_url' => getProp($segment, 'video_url'),
- 'video_duration' => getProp($segment, 'video_duration', 0),
- 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
- 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
- 'last_frame_url' => getProp($segment, 'last_frame_url'),
- 'current_type' => getProp($segment, 'current_type'),
- ];
-
- $actNumber = getProp($segment, 'act_number');
- if (isset($acts[$actNumber])) {
- $acts[$actNumber]['segments'][] = $segmentInfo;
- } else {
- $acts[$actNumber] = [
- 'act_number' => $actNumber,
- 'act_title' => getProp($segment, 'act_title'),
- 'act_duration' => getProp($segment, 'act_duration'),
- 'segments' => [$segmentInfo]
- ];
- }
- }
-
- return [
- 'acts' => array_values($acts),
- 'total_duration' => intval(round($totalDuration))
- ];
- }
- /**
- * 构建统一的分段数据结构(episodeInfoForAce格式)
- * @param array $segments 分段数据数组
- * @return array 返回包含acts和total_duration的数组
- */
- public function buildEpisodeActsStructureForAce($segments) {
- $acts = [];
- $totalDuration = 0; // 初始化总时长
-
- foreach($segments as $segment) {
- // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
- $videoDuration = getProp($segment, 'video_duration');
- $actDuration = getProp($segment, 'act_duration');
-
- if (!empty($videoDuration) && is_numeric($videoDuration)) {
- $totalDuration += floatval($videoDuration);
- } elseif (!empty($actDuration) && is_numeric($actDuration)) {
- $totalDuration += floatval($actDuration);
- } else {
- $totalDuration += 5; // 默认5秒
- }
- // 构建分镜信息
- $segmentInfo = [
- 'act_id' => getProp($segment, 'id'),
- 'act_number' => getProp($segment, 'act_number'),
- 'act_title' => getProp($segment, 'act_title'),
- 'act_duration' => getProp($segment, 'act_duration'),
- 'act_content' => getProp($segment, 'act_content'),
- 'video_url' => getProp($segment, 'video_url'),
- 'video_duration' => getProp($segment, 'video_duration', 0),
- 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
- 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
- 'last_frame_url' => getProp($segment, 'last_frame_url'),
- 'current_type' => getProp($segment, 'current_type'),
- ];
- $acts[] = $segmentInfo;
- }
-
- return [
- 'acts' => array_values($acts),
- 'total_duration' => intval(round($totalDuration))
- ];
- }
- /**
- * 验证画面比例是否有效
- * @param string $ratio 画面比例
- * @return bool
- */
- public function validateRatio($ratio) {
- return isset(BaseConst::IMAGE_RATIOS[$ratio]);
- }
- /**
- * 获取画面比例对应的宽高
- * @param string $ratio 画面比例
- * @return array ['width' => int, 'height' => int]
- * @throws \Exception
- */
- private function getRatioDimensions($ratio) {
- if ($ratio && !$this->validateRatio($ratio)) {
- $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
- Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
- }
- return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
- }
- public function createAnime($data) {
- $uid = Site::getUid();
- $input_art_style = getProp($data, 'art_style');
- $file = getProp($data, 'file');
- $content = getProp($data, 'content', '');
- $bid = getProp($data, 'bid', 0);
- $script_id = getProp($data, 'script_id', 0);
- $ace_mode = getProp($data, 'ace_mode', 0);
- $extra_products = getProp($data, 'products', []);
- if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
- if (!is_array($extra_products)) {
- Utils::throwError('20003:传入的资产格式不正确');
- }
-
- // 替换美术风格
- $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
- // 提取文件内容
- if ($file) {
- $content = $this->DeepSeekService->extractFileContent($file);
- if (!$content) {
- Utils::throwError('20003:无法提取文件内容,请检查文件格式');
- }
- } elseif ($script_id) {
- $content = $this->DeepSeekService->getContentByScriptId($script_id);
- if (!$content) {
- Utils::throwError('20003:无法获取剧本内容,请检查剧本');
- }
- } elseif ($bid) {
- $content = $this->DeepSeekService->getContentByBid($bid);
- if (!$content) {
- Utils::throwError('20003:无法获取书籍内容,请检查书籍');
- }
- } elseif ($content) {
- $content = filterContent($content);
- }else {
- $content = '';
- }
- $anime_data = [
- 'user_id' => $uid,
- 'anime_name' => '新剧本策划',
- 'is_multi' => getProp($data, 'is_multi', 1),
- 'content' => $content,
- 'art_style_type' => $input_art_style,
- 'ace_mode' => $ace_mode,
- 'script_id' => $script_id,
- 'extra_products' => json_encode($extra_products, 256),
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- // 处理文本模型
- $model = getProp($data, 'model');
- if (!$model) {
- // 用户没有输入,使用默认值
- $model = 'doubao-seed-2-0-mini-260215';
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'doubao-seed-2-0-mini-260215';
- }
- $anime_data['model'] = $model;
- if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
- return DB::table('mp_animes')->insertGetId($anime_data);
- }
- public function chatList($data) {
- $uid = Site::getUid();
- $anime_name = getProp($data, 'anime_name');
- $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
- if ($anime_name) {
- $query->where('anime_name', 'like', "%$anime_name%");
- }
- return $query->orderBy('id', 'desc')->paginate();
- }
- public function chatHistory($data) {
- $anime_id = getProp($data, 'anime_id');
- $sequence = getProp($data, 'sequence', 0);
- if (!$anime_id) Utils::throwError('20003:请选择对话!');
- $query = DB::table('mp_anime_records as ar')->leftJoin('mp_anime_episodes as ae', 'ar.episode_id', '=', 'ae.id')->where('ar.anime_id', $anime_id)
- ->where('ar.sequence', $sequence)->where('segment_id', 0)->where('act_id', 0)->select('ar.role', 'ar.content', 'ar.created_at', 'ar.episode_id', 'ae.title as episode_title', 'ae.created_at as episode_created_at');
-
- return $query->orderBy('ar.id')->get()->map(function ($value) {
- $value = (array)$value;
- if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
- $value['created_at'] = transDate($value['created_at']);
- $value['episode_created_at'] = transDate($value['episode_created_at']);
- return $value;
- })->toArray();
- }
- public function batchSetRoleImg($data) {
- $episode_id = getProp($data, 'episode_id');
- if (!$episode_id) Utils::throwError('1002:请选择分集');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- $roles = json_decode(getProp($data, 'roles'), true) ?: [];
- $art_style = getProp($episode, 'art_style');
- $anime_id = getProp($episode, 'anime_id');
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- $art_style_type = getProp($anime, 'art_style_type');
- $character_prefix = '';
- $scene_prefix = '';
- if ($art_style_type) {
- $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
- $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
- $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
- }
-
- foreach ($roles as &$role) {
- $role_name = getProp($role, 'role');
- if ($role_name == '旁白') continue;
-
- // 优先使用 pic_prompt,如果没有则使用 description
- $pic_prompt = getProp($role, 'pic_prompt');
- $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
-
- // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
- $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
- // 参考图地址
- $ref_img_url = getProp($role, 'url');
- if ($ref_img_url) continue; // 已有图片则跳过
-
- // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
- try {
- $params = [
- 'prompt' => $description,
- 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError("20003:角色({$role_name})生成图片失败");
- }
-
- $role['task_id'] = $task_id;
- $role['task_status'] = 'processing';
- } catch (\Exception $e) {
- logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
- Utils::throwError("20003:" . $e->getMessage());
- }
- }
-
- // 保存角色信息
- $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'roles' => json_encode($roles, 256),
- 'generate_status' => '执行中',
- 'generate_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$boolen) {
- Utils::throwError('20003:保存角色信息失败');
- }
- return $boolen;
- }
- public function batchSetSceneImg($data) {
- $episode_id = getProp($data, 'episode_id');
- if (!$episode_id) Utils::throwError('1002:请选择分集');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- $scenes = json_decode(getProp($episode, 'scenes'), true);
- $art_style = getProp($episode, 'art_style');
- $target_scene = getProp($data, 'target_scene');
- $anime_id = getProp($episode, 'anime_id');
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- $art_style_type = getProp($anime, 'art_style_type');
- $character_prefix = '';
- $scene_prefix = '';
- if ($art_style_type) {
- $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
- $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
- $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
- }
-
- foreach ($scenes as &$scene) {
- $scene_name = getProp($scene, 'scene');
- if ($scene_name != $target_scene) continue;
-
- // 优先使用 pic_prompt,如果没有则使用 description
- $pic_prompt = getProp($scene, 'pic_prompt');
- $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
-
- // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
- $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
- // 参考图地址
- $ref_img_url = getProp($scene, 'url');
- if ($ref_img_url) continue; // 已有图片则跳过
-
- // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
- try {
- $params = [
- 'prompt' => $description,
- 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError("20003:场景({$scene_name})生成图片失败");
- }
-
- $scene['task_id'] = $task_id;
- $scene['task_status'] = 'processing';
- } catch (\Exception $e) {
- logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
- Utils::throwError("20003:" . $e->getMessage());
- }
- }
-
- // 保存场景信息
- $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'scenes' => json_encode($scenes, 256),
- 'generate_status' => '执行中',
- 'generate_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$boolen) {
- Utils::throwError('20003:保存角色信息失败');
- }
- return $boolen;
- }
- public function editAnime($data) {
- $anime_id = getProp($data, 'anime_id');
- $anime_name = trim(getProp($data, 'anime_name'));
- // 确认对话名称唯一性
- if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
- if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
- }
- if (!$anime_id || !$anime_name) {
- Utils::throwError('20003:参数异常');
- }
- return DB::table('mp_animes')->where('id', $anime_id)->update([
- 'anime_name' => $anime_name,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- // $script_arr =getProp($data, 'script', []);
- // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
- // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
- // $anime_id = getProp($data, 'anime_id');
- // try {
- // DB::beginTransaction();
- // $table_data = [
- // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
- // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
- // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
- // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
- // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
- // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
- // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
- // 'status' => 3,
- // 'start_episode_sequence' => $start_episode_sequence,
- // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
- // 'episode_num' => count($script_arr['episodes']),
- // 'updated_at' => date('Y-m-d H:i:s')
- // ];
- // // 保存剧本内容
- // if (!empty($anime_id)) {
- // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
- // if (!$boolen) {
- // dLog('anime')->info('对话保存失败', $table_data);
- // Utils::throwError('20003:对话保存失败');
- // }
- // }else {
- // $table['created_at'] = $table_data['updated_at'];
- // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
- // if (!$anime_id) {
- // dLog('anime')->info('对话保存失败', $table_data);
- // Utils::throwError('20003:对话保存失败');
- // }
- // }
-
-
- // // 保存分集内容
- // // 删除历史分集内容
- // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
-
- // $episodes = [];
- // $sequence = 1;
- // foreach ($script_arr['episodes'] as $episode) {
- // $segment_number = 1;
- // foreach($episode['segments'] as $segment) {
- // $episodes[] = [
- // 'anime_id' => $anime_id,
- // 'episode_number' => $episode['episode_number'],
- // 'title' => $episode['title'],
- // // 'content' => $episode['content'],
- // 'content' => '',
- // 'segment_number' => $segment_number,
- // 'segment_content' => $segment['segment_content'],
- // 'sequence' => $sequence,
- // 'created_at' => date('Y-m-d H:i:s'),
- // 'updated_at' => date('Y-m-d H:i:s')
- // ];
- // $sequence++;
- // $segment_number++;
- // }
-
- // }
- // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
- // if (!$boolen2) {
- // dLog('deepseek')->info('分集内容保存失败', $episodes);
- // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
- // Utils::throwError('20003:分集内容保存失败');
- // }
- // } catch (\Exception $e) {
- // DB::rollBack();
- // Utils::throwError('20003:'.$e->getMessage());
- // }
- // DB::commit();
- // return true;
- }
- public function delAnime($data) {
- $anime_id = getProp($data, 'anime_id');
- if (!$anime_id) {
- Utils::throwError('20003:请选择剧本');
- }
- return DB::table('mp_animes')->where('id', $anime_id)->update([
- 'is_deleted' => 1,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- public function animeDetail($data) {
- $uid = Site::getUid();
- $anime_id = getProp($data, 'anime_id');
- $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
- ->selectRaw('id as anime_id, anime_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, remark, generate_status, created_at, ace_mode')->first();
- if (!$anime) Utils::throwError('20003:权限不足');
- $anime = (array)$anime;
- $anime['roles'] = json_decode($anime['roles']);
- $anime['scenes'] = json_decode($anime['scenes']);
- // 获取分集信息
- $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
- ->select('id as episode_id', 'episode_number', 'title', 'is_generated', DB::raw("(select es.img_url from mp_episode_segments as es where es.episode_id = mp_anime_episodes.id order by es.segment_number limit 1) as first_frame_url"))
- ->orderBy('episode_number')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
- $anime['episodes'] = $episodes;
- return $anime;
- }
- public function episodeInfo($data) {
- $uid = Site::getUid();
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择剧集');
- }
- // 验证用户权限
- $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
- if (!$anime) Utils::throwError('20003:权限不足');
- $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->first();
- if (!$episode) Utils::throwError('20003:该剧集不存在!');
- $episode = (array)$episode;
- $episode['roles'] = json_decode($episode['roles'], true);
- // foreach($episode['roles'] as &$item) {
- // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
- // }
- $episode['scenes'] = json_decode($episode['scenes'], true);
- // foreach($episode['scenes'] as &$item) {
- // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
- // }
-
- // 获取分镜信息
- $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
- ->select('*')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
-
- // 使用公共方法构建分镜结构
- $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
- $episode['acts'] = $segmentsStructure['acts'];
- $episode['total_duration'] = $segmentsStructure['total_duration'];
- return $episode;
- }
- public function episodeInfoForAce($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择剧集');
- }
- $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->first();
- if (!$episode) Utils::throwError('20003:该剧集不存在!');
- $episode = (array)$episode;
- $episode['roles'] = json_decode($episode['roles'], true);
- // foreach($episode['roles'] as &$item) {
- // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
- // }
- $episode['scenes'] = json_decode($episode['scenes'], true);
- // foreach($episode['scenes'] as &$item) {
- // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
- // }
-
- // 获取分镜信息
- $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
- ->select('*')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
-
- $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
- $episode['acts'] = $segmentsStructure['acts'];
- $episode['total_duration'] = $segmentsStructure['total_duration'];
- return $episode;
- }
- public function segmentInfo($data) {
- $uid = Site::getUid();
- $segment_id = getProp($data, 'segment_id');
- if (!$segment_id) {
- Utils::throwError('1002:请选择分镜');
- }
-
- // 获取分镜信息
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
-
- // 验证用户权限
- if ($segment) {
- $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
- if (!$anime) Utils::throwError('20003:权限不足');
- }
-
- $result = [
- 'segment_id' => getProp($segment, 'segment_id'),
- 'segment_number' => getProp($segment, 'segment_number'),
- 'segment_content' => getProp($segment, 'segment_content'),
- 'description' => getProp($segment, 'description'),
- 'composition' => getProp($segment, 'composition'),
- 'camera_movement' => getProp($segment, 'camera_movement'),
- 'voice_actor' => getProp($segment, 'voice_actor'),
- 'dialogue' => getProp($segment, 'dialogue'),
- 'frame_type' => getProp($segment, 'frame_type'),
- 'scene' => getProp($segment, 'scene'),
- 'characters' => getProp($segment, 'characters'),
- 'tail_frame' => getProp($segment, 'tail_frame'),
- 'emotion' => getProp($segment, 'emotion'),
- 'emotion_type' => getProp($segment, 'emotion_type'),
- 'gender' => getProp($segment, 'gender'),
- 'speed_ratio' => getProp($segment, 'speed_ratio'),
- 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
- 'emotion_scale' => getProp($segment, 'emotion_scale'),
- 'pitch' => getProp($segment, 'pitch'),
- 'voice_name' => getProp($segment, 'voice_name'),
- 'voice_type' => getProp($segment, 'voice_type'),
- 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
- 'img_url' => getProp($segment, 'img_url'),
- 'video_url' => getProp($segment, 'video_url'),
- 'last_frame_url' => getProp($segment, 'last_frame_url'),
- ];
- return $result;
- }
- public function copyEpisodeVersion($data) {
- $episode_id = getProp($data, 'episode_id');
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$episode) Utils::throwError('20003:该剧集不存在');
- $episode = (array)$episode;
- $anime_id = $episode['anime_id'];
- $episode_number = $episode['episode_number'];
- $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
- $sequence = $count + 1;
- unset($episode['id']);
- $now = date('Y-m-d H:i:s');
- $episode['created_at'] = $now;
- $episode['updated_at'] = $now;
- $episode['is_default'] = 1;
- // 获取版本中含有"(副本"字样的个数
- $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
- $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
- $episode['sequence'] = $sequence;
- $episode['is_generated'] = 0;
- $episode['cpid'] = $cpid;
- // 获取ace_mode
- $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
- try {
- DB::beginTransaction();
- DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
- // 新增副本
- $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
- if (!$new_episode_id) {
- Utils::throwError('20003:创建副本失败!');
- }
- // 获取分镜数据并准备插入
- $segments_for_insert = DB::table('mp_episode_segments')
- ->select('anime_id', 'episode_number', 'act_number', 'act_title', 'act_duration', 'act_content', 'segment_number', 'segment_content', 'description', 'composition', 'camera_movement', 'voice_actor', 'dialogue', 'frame_type', 'scene', 'characters', 'tail_frame', 'voice_name', 'voice_type', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
- ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
- $item = (array)$item;
- $item['episode_id'] = $new_episode_id;
- if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
- $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
- return $item;
- })->toArray();
- // 写入分镜数据
- $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
- if (!$boolen2) {
- Utils::throwError('20003:写入分镜数据失败!');
- }
- // 写入对话历史
- $records = [
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'role' => 'user',
- 'content' => '创建副本',
- 'sequence' => $episode_number,
- 'episode_id' => $new_episode_id,
- 'created_at' => $now,
- 'updated_at' => $now
- ],
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'role' => 'assistant',
- 'content' => '好的,已为您创建副本',
- 'sequence' => $episode_number,
- 'episode_id' => $new_episode_id,
- 'created_at' => $now,
- 'updated_at' => $now
- ]
- ];
- $boolen3 = DB::table('mp_anime_records')->insert($records);
- if (!$boolen3) {
- Utils::throwError('20003:对话记录保存失败');
- }
-
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- // 构建与 episodeInfo 方法一致的返回数据结构
- $result = [
- 'episode_id' => $new_episode_id,
- 'anime_id' => $anime_id,
- 'episode_number' => $episode_number,
- 'title' => $episode['title'],
- 'intro' => $episode['intro'],
- 'art_style' => $episode['art_style'],
- 'roles' => json_decode($episode['roles'], true),
- 'scenes' => json_decode($episode['scenes'], true),
- 'is_generated' => (int)$episode['is_generated']
- ];
- if ((int)$ace_mode === 1) {
- // 获取分镜信息
- $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
- ->select('*')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
- $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
- }else {
- // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
- $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
- }
- $result['acts'] = $segmentsStructure['acts'];
- $result['total_duration'] = $segmentsStructure['total_duration'];
- return $result;
- }
- public function episodeVersions($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择剧集');
- }
- $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
- $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->select('id as episode_id', 'anime_id', 'episode_number', 'sequence', 'title', 'intro', 'art_style', 'roles', 'scenes', 'is_generated')->orderBy('sequence', 'desc')->get()->map(function($value) {
- return (array)$value;
- })->toArray();
- if (!$episodes) Utils::throwError('20003:该剧集不存在!');
-
- foreach($episodes as &$episode) {
- $episode['version'] = 'V'.$episode['sequence'];
- $episode['roles'] = json_decode($episode['roles'], true);
- $episode['scenes'] = json_decode($episode['scenes'], true);
-
- // 获取分镜信息
- $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
- ->select('*')->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
-
- // 使用公共方法构建分镜结构
- $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
- $episode['acts'] = $segmentsStructure['acts'];
- $episode['total_duration'] = $segmentsStructure['total_duration'];
- }
- return $episodes;
- }
- public function bindEpisodeVersion($data) {
- $episode_id = getProp($data, 'episode_id');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$episode) Utils::throwError('20003:该剧集不存在');
- $episode = (array)$episode;
- if ((int)$episode['is_default'] === 1) return true;
- try {
- DB::beginTransaction();
- // 移除is_default标志
- $boolen = DB::table('mp_anime_episodes')->where('anime_id', $episode['anime_id'])->where('episode_number', $episode['episode_number'])->update(['is_default' => 0, 'updated_at'=>date('Y-m-d H:i:s')]);
- if (!$boolen) {
- Utils::throwError('20003:更新失败!');
- }
- // 绑定副本
- $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
- if (!$boolen2) {
- Utils::throwError('20003:绑定失败!');
- }
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- return true;
- }
- public function chatChangeImg($data) {
- $segment_id = getProp($data, 'segment_id');
- $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
- $prompt = getProp($data, 'prompt');
- if (!$prompt || !$segment_id) {
- Utils::throwError('1002:请输入提示词,并且选择分镜');
- }
- $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
- if (!$segment) Utils::throwError('20003:该分镜不存在!');
- if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
- else $ref_img_url = '';
- // $ref_img_url = '';
- if (empty($prompt)) {
- if (empty($ref_img_url)) {
- $prompt = getProp($segment, 'segment_content');
- }else {
- $prompt = '请根据图片生成';
- }
- }
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- $ratio = getProp($data, 'ratio');
- if (!$ratio) {
- $ratio = getProp($episode, 'ratio');
- if (!$ratio) $ratio = '9:16';
- }
- $art_style = getProp($episode, 'art_style');
- if ($art_style) {
- $prompt = "美术风格:{$art_style}\n{$prompt}";
- }
- $dimensions = $this->getRatioDimensions($ratio);
- $width = $dimensions['width'];
- $height = $dimensions['height'];
- try {
- $params = [
- 'alias_segment_id' => $segment_id,
- 'prompt' => $prompt,
- 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
- 'width' => $width,
- 'height' => $height
- ];
- // 优化提示词(不要生成字幕)
- $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError("20003:生成图片失败");
- }
-
- // 更新任务ID
- $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update(['pic_task_id' => $task_id, 'pic_task_status' => '生成中', 'updated_at' => date('Y-m-d H:i:s')]);
- if (!$boolen) Utils::throwError('20003:更新任务ID失败');
- } catch (\Exception $e) {
- Utils::throwError("20003:" . $e->getMessage());
- }
- // 创建任务之后先暂停10s等待异步任务完成
- sleep(10);
- $img_url = $this->loopGetPicTaskResult($task_id);
- if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
- // 图片生成后新增对话记录
- try {
- $uid = Site::getUid();
- $now = date('Y-m-d H:i:s');
-
- // 使用AI反推图片提示词
- $pic_prompt = $this->generateImagePromptFromUrl($img_url);
-
- // 保存对话记录
- $records = [
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'sequence' => $episode_number,
- 'role' => 'user',
- 'content' => $prompt,
- 'segment_id' => $segment_id,
- 'image_url' => '',
- 'created_at' => $now,
- 'updated_at' => $now
- ],
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'sequence' => $episode_number,
- 'role' => 'assistant',
- 'content' => $pic_prompt,
- 'segment_id' => $segment_id,
- 'image_url' => $img_url,
- 'created_at' => $now,
- 'updated_at' => $now
- ]
- ];
-
- DB::table('mp_anime_records')->insert($records);
-
- } catch (\Exception $e) {
- // 记录日志但不影响主流程
- dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
- 'segment_id' => $segment_id,
- 'img_url' => $img_url
- ]);
- logDB('anime', 'error', '保存对话记录失败', [
- 'segment_id' => $segment_id,
- 'img_url' => $img_url,
- 'error' => $e->getMessage()
- ]);
- }
- return $img_url;
- }
- public function segmentChatHistory($data) {
- $segment_id = getProp($data, 'segment_id');
- if (!$segment_id) Utils::throwError('20003:请选择分镜!');
- $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
-
- $chat = $query->orderBy('id')->get()->map(function ($value) {
- $value = (array)$value;
- $value['created_at'] = transDate($value['created_at']);
- return $value;
- })->toArray();
- // 获取历史图片
- $url = [];
- $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($pic_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $url = array_merge($url, json_decode($result_url, true));
- }else {
- $url[] = $result_url;
- }
- }
-
- // 获取历史视频
- $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($video_history as $task) {
- $result_url = getProp($task, 'compressed_url');
- if (is_json($result_url)) {
- $url = array_merge($url, json_decode($result_url, true));
- }else {
- $url[] = $result_url;
- }
- }
- return compact('chat', 'url');
- }
- public function changeEpisodeRoles($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- $target_roles = getProp($data, 'roles');
- $is_deleted = getProp($data, 'is_deleted', 0);
- // 参数验证
- if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
- if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
- if (!$target_roles) Utils::throwError('20003:请提供角色信息');
- // 验证剧集是否存在
- $episode = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->first();
-
- if (!$episode) Utils::throwError('20003:该剧集不存在');
- $roles = json_decode(getProp($episode, 'roles'), true);
- // 获取anime信息,检查是否有关联的script_id
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- if (!$anime) Utils::throwError('20003:动漫不存在');
-
- $script_id = getProp($anime, 'script_id');
- $episode_number = getProp($episode, 'episode_number', 1);
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- try {
- $target_role_name = getProp($target_roles, 'role');
-
- // 如果是删除操作
- if ($is_deleted == 1) {
- // 从角色列表中移除该角色
- $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
- return getProp($role, 'role') !== $target_role_name;
- }));
-
- // 更新角色列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'roles' => json_encode($roles, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:删除角色失败');
- }
- } else {
- // 新增或更新操作
- $role_found = false;
- $is_new_role = false;
-
- // 查找并更新已存在的角色
- foreach($roles as &$role) {
- if (getProp($role, 'role') === $target_role_name) {
- $role = $target_roles;
- $role_found = true;
- break;
- }
- }
-
- // 如果角色不存在,则新增
- if (!$role_found) {
- $roles[] = $target_roles;
- $is_new_role = true;
- }
- // 更新角色列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'roles' => json_encode($roles, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:更新角色列表失败');
- }
-
- // 同步更新分镜表中对应主体的音色信息
- $voice_name = getProp($target_roles, 'voice_name');
- $voice_type = getProp($target_roles, 'voice_type');
- $voice_audio_url = getProp($target_roles, 'voice_audio_url');
-
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('voice_actor', $target_role_name)
- ->update([
- 'voice_name' => $voice_name,
- 'voice_type' => $voice_type,
- 'voice_audio_url' => $voice_audio_url,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- // 如果有关联的script_id,则同步到mp_products表
- if ($script_id) {
- // 查询剧本信息
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
-
- if ($script) {
- $script_name = $script->script_name ?? 'script_' . $script_id;
- $product_name = getProp($target_roles, 'role');
- $pic_prompt = getProp($target_roles, 'pic_prompt', '');
- $url = getProp($target_roles, 'url', '');
- $product_type = 1; // 1=角色
-
- // 查找或创建以script_name命名的文件夹
- $folder = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('type', 2) // 文件夹类型
- ->where('product', $product_type) // 角色类型
- ->where('product_name', $script_name)
- ->where('parent_id', 0)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$folder) {
- // 创建文件夹
- $folder_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 2, // 文件夹
- 'product' => $product_type, // 角色类型
- 'parent_id' => 0,
- 'level' => 1,
- 'product_name' => $script_name,
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- } else {
- $folder_id = $folder->id;
- }
-
- // 查找该文件夹下是否已存在同名资产
- $existing_product = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('type', 1) // 资产类型
- ->where('product', $product_type)
- ->where('parent_id', $folder_id)
- ->where('product_name', $product_name)
- ->where('is_deleted', 0)
- ->first();
-
- if ($existing_product) {
- // 更新已存在的资产
- $updateData = [
- 'pic_task_status' => '生成成功',
- ];
- if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
- if ($url) $updateData['url'] = $url;
-
- // 处理versions字段
- $versions = getProp($target_roles, 'versions', []);
- if ($versions && is_array($versions)) {
- $updateData['versions'] = json_encode($versions, 256);
- }
-
- $updateData['updated_at'] = date('Y-m-d H:i:s');
-
- DB::table('mp_products')
- ->where('id', $existing_product->id)
- ->update($updateData);
-
- $product_id = $existing_product->id;
- } else {
- // 创建新资产
- $versions = getProp($target_roles, 'versions', []);
-
- $product_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 1, // 资产
- 'product' => $product_type, // 角色
- 'parent_id' => $folder_id,
- 'level' => 2,
- 'product_name' => $product_name,
- 'url' => $url,
- 'pic_prompt' => $pic_prompt,
- 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'pic_task_status' => '生成成功',
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
-
- // 建立或更新绑定关系
- $existing_mapping = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->where('product_id', $product_id)
- ->where('episode_number', $episode_number)
- ->first();
-
- if (!$existing_mapping) {
- // 创建绑定关系
- DB::table('mp_script_product_mappings')->insert([
- 'script_id' => $script_id,
- 'product_id' => $product_id,
- 'episode_number' => $episode_number,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- }
- }
- }
- } catch (\Exception $e) {
- dLog('anime')->error('更新剧集角色失败', [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'error' => $e->getMessage()
- ]);
- Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
- }
- return true;
- }
- public function changeEpisodeScenes($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- $target_scenes = getProp($data, 'scenes');
- $is_deleted = getProp($data, 'is_deleted', 0);
- // 参数验证
- if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
- if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
- if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
- // 验证剧集是否存在
- $episode = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->first();
-
- if (!$episode) Utils::throwError('20003:该剧集不存在');
- $scenes = json_decode(getProp($episode, 'scenes'), true);
- // 获取anime信息,检查是否有关联的script_id
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- if (!$anime) Utils::throwError('20003:动漫不存在');
-
- $script_id = getProp($anime, 'script_id');
- $episode_number = getProp($episode, 'episode_number', 1);
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- try {
- $target_scene_name = getProp($target_scenes, 'scene');
-
- // 如果是删除操作
- if ($is_deleted == 1) {
- // 从场景列表中移除该场景
- $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
- return getProp($scene, 'scene') !== $target_scene_name;
- }));
-
- // 更新场景列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'scenes' => json_encode($scenes, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:删除场景失败');
- }
- } else {
- // 新增或更新操作
- $scene_found = false;
- $is_new_scene = false;
-
- // 查找并更新已存在的场景
- foreach($scenes as &$scene) {
- if (getProp($scene, 'scene') === $target_scene_name) {
- $scene = $target_scenes;
- $scene_found = true;
- break;
- }
- }
-
- // 如果场景不存在,则新增
- if (!$scene_found) {
- $scenes[] = $target_scenes;
- $is_new_scene = true;
- }
- // 更新场景列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'scenes' => json_encode($scenes, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:更新场景列表失败');
- }
- // 如果有关联的script_id,则同步到mp_products表
- if ($script_id) {
- // 查询剧本信息
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
-
- if ($script) {
- $script_name = $script->script_name ?? 'script_' . $script_id;
- $product_name = getProp($target_scenes, 'scene');
- $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
- $url = getProp($target_scenes, 'url', '');
- $product_type = 2; // 2=场景
-
- // 查找或创建以script_name命名的文件夹
- $folder = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('type', 2) // 文件夹类型
- ->where('product', $product_type) // 场景类型
- ->where('product_name', $script_name)
- ->where('parent_id', 0)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$folder) {
- // 创建文件夹
- $folder_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 2, // 文件夹
- 'product' => $product_type, // 场景类型
- 'parent_id' => 0,
- 'level' => 1,
- 'product_name' => $script_name,
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- } else {
- $folder_id = $folder->id;
- }
-
- // 查找该文件夹下是否已存在同名资产
- $existing_product = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('type', 1) // 资产类型
- ->where('product', $product_type)
- ->where('parent_id', $folder_id)
- ->where('product_name', $product_name)
- ->where('is_deleted', 0)
- ->first();
-
- if ($existing_product) {
- // 更新已存在的资产
- $updateData = [
- 'pic_task_status' => '生成成功'
- ];
- if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
- if ($url) $updateData['url'] = $url;
-
- // 处理versions字段
- $versions = getProp($target_scenes, 'versions', []);
- if ($versions && is_array($versions)) {
- $updateData['versions'] = json_encode($versions, 256);
- }
-
- $updateData['updated_at'] = date('Y-m-d H:i:s');
-
- DB::table('mp_products')
- ->where('id', $existing_product->id)
- ->update($updateData);
-
- $product_id = $existing_product->id;
- } else {
- // 创建新资产
- $versions = getProp($target_scenes, 'versions', []);
-
- $product_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 1, // 资产
- 'product' => $product_type, // 场景
- 'parent_id' => $folder_id,
- 'level' => 2,
- 'product_name' => $product_name,
- 'url' => $url,
- 'pic_prompt' => $pic_prompt,
- 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'pic_task_status' => '生成成功',
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
-
- // 建立或更新绑定关系
- $existing_mapping = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->where('product_id', $product_id)
- ->where('episode_number', $episode_number)
- ->first();
-
- if (!$existing_mapping) {
- // 创建绑定关系
- DB::table('mp_script_product_mappings')->insert([
- 'script_id' => $script_id,
- 'product_id' => $product_id,
- 'episode_number' => $episode_number,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- }
- }
- }
- } catch (\Exception $e) {
- dLog('anime')->error('更新剧集场景失败', [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'error' => $e->getMessage()
- ]);
- Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
- }
- return true;
- }
- public function editSegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $segment_content = getProp($data, 'segment_content');
- $image_url = getProp($data, 'image_url');
- $video_url = getProp($data, 'video_url');
- // 参数验证
- if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
- // 验证分镜是否存在
- $segment = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->first();
-
- if (!$segment) Utils::throwError('20003:该分镜不存在');
- $dubTaskId = 0;
- try {
- DB::beginTransaction();
- // 准备更新数据
- $update_data = [
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- if ($segment_content) {
- // 先将segment_content赋值到update_data
- $update_data['segment_content'] = $segment_content;
-
- // 使用现有方法分析segment_content,提取各个字段
- $this->handleSegmentContent($update_data);
-
- // 如果有对话内容,创建视频配音合成任务
- $dialogue = getProp($update_data, 'dialogue');
- if (!empty($dialogue)) {
- $now = date('Y-m-d H:i:s');
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($update_data, 'voice_actor'),
- 'voice_type' => getProp($update_data, 'voice_type'),
- 'voice_name' => getProp($update_data, 'voice_name'),
- 'emotion' => getProp($update_data, 'emotion'),
- 'emotion_type' => getProp($update_data, 'emotion_type'),
- 'gender' => getProp($update_data, 'gender'),
- 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
- 'pitch' => getProp($update_data, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $segment_id,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
-
- if (!$dubTaskId) {
- Utils::throwError('20003:创建配音任务失败!');
- }
- $update_data['audio_url'] = '';
- } else {
- // dialogue为空时,直接写入默认音频信息
- $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
- $update_data['audio_duration'] = 2.0;
- $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
- }
- }
- if ($image_url) {
- $update_data['img_url'] = $image_url;
- // 同时写入一个简单的图片生成任务
- $pic_task = [
- 'alias_segment_id' => $segment_id,
- 'ref_img_url' => json_encode([]),
- 'status' => 'success',
- 'result_url' => json_encode([$image_url], 256),
- 'model' => '',
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- DB::table('mp_generate_pic_tasks')->insert($pic_task);
- }
- if ($video_url) {
- $update_data['origin_video_url'] = $video_url;
- $compressed_video_url = compressVideo($video_url);
- $update_data['current_type'] = 2;
- $update_data['video_url'] = $compressed_video_url ?: $video_url;
- // 同时写入一个简单的视频生成任务
- $video_task = [
- 'alias_segment_id' => $segment_id,
- 'status' => 'success',
- 'result_url' => $update_data['origin_video_url'],
- 'compressed_url' => $update_data['video_url'],
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- DB::table('mp_generate_video_tasks')->insert($video_task);
- }
- // 更新分镜信息
- $result = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($update_data);
- if ($result === false) {
- Utils::throwError('20003:更新分镜剧本失败');
- }
- DB::commit();
- // 如果有创建音频生成任务则调用API
- if ($dubTaskId) {
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
- logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
- Utils::throwError('20003:火山生成音频失败');
- }
- }
- return true;
- } catch (\Exception $e) {
- DB::rollBack();
- dLog('anime')->error('更新分镜剧本失败', [
- 'segment_id' => $segment_id,
- 'error' => $e->getMessage()
- ]);
- Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
- }
- }
- public function batchSetSegmentPics($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- $ratio = getProp($data, 'ratio');
- $dimensions = $this->getRatioDimensions($ratio);
- $width = $dimensions['width'];
- $height = $dimensions['height'];
-
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择剧集');
- }
- // 获取剧集信息
- $episode = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->where('is_default', 1)
- ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
- ->first();
-
- if (!$episode) {
- Utils::throwError('20003:该剧集不存在');
- }
- $model = getProp($data, 'model');
- if (!$model) {
- $model = getProp($episode, 'image_model');
- if (!$model) {
- // episode表也没有,使用默认值
- $model = 'doubao-seedream-5-0-lite-260128';
- }
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'doubao-seedream-5-0-lite-260128';
- }
- $roles = json_decode(getProp($episode, 'roles'), true);
- if (!$roles) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $role_map = [];
- foreach ($roles as $role) {
- $role_name = getProp($role, 'role');
- $role_url = getProp($role, 'url');
- if (!empty($role_name) && !empty($role_url)) {
- // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
- // $base_name = preg_replace('/[--].*$/u', '', $role_name);
- // $role_map[$base_name] = $role_url;
- // 同时保存完整名称的映射
- $role_map[$role_name] = $role_url;
- }
- }
- $scenes = json_decode(getProp($episode, 'roles'), true);
- if (!$scenes) {
- Utils::throwError('20003:场景信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $scene_map = [];
- foreach ($scenes as $scene) {
- $scene_name = getProp($scene, 'scene');
- $scene_url = getProp($scene, 'url');
- if (!empty($scene_name) && !empty($scene_url)) {
- $scene_map[$scene_name] = $scene_url;
- }
- }
- // 获取所有分镜信息
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->whereNotIn('pic_task_status', ['已完成', '生成中'])
- ->orderBy('segment_number')
- ->get()
- ->toArray();
- if (empty($segments)) {
- Utils::throwError('20003:所有分镜图片已完成或正在生成中');
- }
- // 保存图片比例
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
- $updated_segments = [];
- $failed_segments = [];
- // 批量为每个分镜生成图片任务
- foreach ($segments as $segment) {
- $segment_id = $segment->segment_id;
- $segment_content = $segment->segment_content;
-
- if (empty($segment_content)) {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => '分镜内容为空'
- ];
- continue;
- }
- try {
- $dubTaskId = 0;
- // 解析分镜内容,提取画面描述作为主要提示词
- $prompt = $segment_content;
- $ref_img_urls = [];
- // 分镜场景
- $scene = getProp($segment, 'scene');
- $matched_scene = '';
- if (isset($scene_map[$scene])) {
- $img_index = count($ref_img_urls) + 1;
- $prompt = "场景:$scene(图$img_index)\n$prompt";
- $ref_img_urls[] = $scene_map[$scene];
- $matched_scene = $scene;
- }
- // 分镜角色
- $characters = getProp($segment, 'characters');
- $characters = str_replace(['、', ',', ';'], ',', $characters);
- $roles = explode(',', $characters);
-
- // 从分镜内容中提取涉及的角色
- $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
-
- // 获取匹配角色的参考图
- foreach ($segment_characters as $character) {
- if (isset($role_map[$character])) {
- // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
- $img_index = count($ref_img_urls) + 1;
- $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
- $ref_img_urls[] = $role_map[$character];
- }
- }
-
- // 如果没有找到匹配的角色参考图,不使用参考图
- if (empty($ref_img_urls)) {
- $ref_img_urls = [];
- }
- // 准备生成任务参数
- $params = [
- 'model' => $model,
- 'alias_segment_id' => $segment_id,
- 'prompt' => $prompt,
- 'ref_img_urls' => $ref_img_urls,
- 'width' => $width,
- 'height' => $height,
- ];
- // 优化提示词(不要生成字幕)
- $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
-
- // $task_id = mt_rand(100000, 999999);
- // 调用AI图片生成服务
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => '创建生成任务失败'
- ];
- continue;
- }
- $update_data = [
- 'pic_task_id' => $task_id,
- 'pic_task_status' => '生成中',
- 'audio_url' => '',
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- // 如果有对话内容,创建视频配音合成任务
- $dialogue = getProp($segment, 'dialogue');
- if (!empty($dialogue)) {
- $now = date('Y-m-d H:i:s');
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($segment, 'voice_actor'),
- 'voice_type' => getProp($segment, 'voice_type'),
- 'voice_name' => getProp($segment, 'voice_name'),
- 'emotion' => getProp($segment, 'emotion'),
- 'emotion_type' => getProp($segment, 'emotion_type'),
- 'gender' => getProp($segment, 'gender'),
- 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
- 'pitch' => getProp($segment, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $segment_id,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
-
- if (!$dubTaskId) {
- dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
- logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
- // Utils::throwError('20003:创建配音任务失败!');
- }
-
- } else {
- // dialogue为空时,直接写入默认音频信息到分镜表
- $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
- $update_data['audio_duration'] = 2.0;
- $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
- }
-
- // 更新分镜的任务信息
- $update_result = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($update_data);
- // 如果是第一集的首帧图片,则存入待更新数组
- if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
- Redis::sadd('anime_first_frame_urls', $segment_id);
- }
-
- if ($update_result) {
- $updated_segments[] = [
- 'segment_id' => $segment_id,
- 'task_id' => $task_id,
- 'status' => '生成中',
- 'matched_scenes' => $matched_scene,
- 'matched_roles' => $segment_characters,
- 'ref_urls_count' => count($ref_img_urls)
- ];
- } else {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => '更新分镜任务状态失败'
- ];
- }
- if ($dubTaskId) {
- sleep(1);
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
- logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
- }
- }
-
- } catch (\Exception $e) {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => $e->getMessage()
- ];
- }
- }
- // 更新剧集生成状态
- if (!empty($updated_segments)) {
- DB::table('mp_anime_episodes')
- ->where('id', $episode_id)
- ->update([
- 'is_generated' => 1,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- return [
- 'success_count' => count($updated_segments),
- 'failed_count' => count($failed_segments),
- 'success_segments' => $updated_segments,
- 'failed_segments' => $failed_segments,
- 'total_segments' => count($segments)
- ];
- }
- public function reGenerateSegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_content = getProp($data, 'segment_content');
- $ratio = getProp($data, 'ratio');
- if (!$ratio) {
- $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
- if (!$ratio) $ratio = '9:16';
- }
- $dimensions = $this->getRatioDimensions($ratio);
- $width = $dimensions['width'];
- $height = $dimensions['height'];
-
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择分镜');
- }
- // 使用文生文模型重新解析segment_content
- if (!empty($segment_content)) {
- $segment_content = $this->parseSegmentContentWithAI($segment_content);
- }
- // 获取动漫的角色信息(包含参考图)
- $anime = DB::table('mp_animes')
- ->where('id', $anime_id)
- ->select('roles', 'scenes')
- ->first();
-
- if (!$anime || !$anime->roles) {
- Utils::throwError('20003:未找到角色信息');
- }
- $roles = json_decode($anime->roles, true);
- if (!$roles) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $role_map = [];
- foreach ($roles as $role) {
- $role_name = getProp($role, 'role');
- $role_url = getProp($role, 'url');
- if (!empty($role_name) && !empty($role_url)) {
- $role_map[$role_name] = $role_url;
- }
- }
- $scenes = json_decode($anime->scenes, true);
- if (!$scenes) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $scene_map = [];
- foreach ($scenes as $scene) {
- $scene_name = getProp($scene, 'scene');
- $scene_url = getProp($scene, 'url');
- if (!empty($scene_name) && !empty($scene_url)) {
- $scene_map[$scene_name] = $scene_url;
- }
- }
- $segment_id = $segment->segment_id;
- $original_segment_content = $segment->segment_content;
-
- // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
- $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
-
- if (empty($final_segment_content)) {
- Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
- }
- try {
- $dubTaskId = 0;
- // 分镜剧本数组
- $update_data = [
- 'segment_content' => $final_segment_content,
- 'pic_task_status' => '生成中',
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- // 解析分镜内容,提取画面描述作为主要提示词
- $prompt = $final_segment_content;
- $ref_img_urls = [];
- // 分镜场景
- $scene = getProp($data, 'scene');
- if ($scene) {
- $matched_scene = '';
- if (isset($scene_map[$scene])) {
- $img_index = count($ref_img_urls) + 1;
- $prompt = "场景:$scene(图$img_index)\n$prompt";
- $ref_img_urls[] = $scene_map[$scene];
- $matched_scene = $scene;
- }
- $update_data['scene'] = $scene;
- }
- // 分镜角色
- $characters = getProp($data, 'characters');
- if ($characters) {
- $update_data['characters'] = $characters;
- $characters = str_replace(['、', ',', ';'], ',', $characters);
- $characters = explode(',', $characters);
-
- // 从分镜内容中提取涉及的角色
- $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
-
- // 获取匹配角色的参考图
- foreach ($segment_characters as $character) {
- if (isset($role_map[$character])) {
- // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
- $img_index = count($ref_img_urls) + 1;
- $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
- $ref_img_urls[] = $role_map[$character];
- }
- }
- }
-
-
- // 如果没有找到匹配的角色参考图,不使用参考图
- if (empty($ref_img_urls)) {
- $ref_img_urls = [];
- }
- // 准备生成任务参数
- $params = [
- 'alias_segment_id' => $segment_id,
- 'prompt' => $prompt,
- 'ref_img_urls' => $ref_img_urls,
- 'width' => $width,
- 'height' => $height,
- ];
- // 优化提示词(不要生成字幕)
- $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
-
- // 调用AI图片生成服务
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError('20003:创建生成任务失败!');
- }
- $update_data['pic_task_id'] = $task_id;
-
- // 更新分镜剧本信息
- $this->handleSegmentContent($update_data);
- // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
- if ($segment_content) {
- $dialogue = getProp($update_data, 'dialogue');
- if (!empty($dialogue)) {
- $now = date('Y-m-d H:i:s');
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($update_data, 'voice_actor'),
- 'voice_type' => getProp($update_data, 'voice_type'),
- 'voice_name' => getProp($update_data, 'voice_name'),
- 'emotion' => getProp($update_data, 'emotion'),
- 'emotion_type' => getProp($update_data, 'emotion_type'),
- 'gender' => getProp($update_data, 'gender'),
- 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
- 'pitch' => getProp($update_data, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $segment_id,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ]);
-
- if (!$dubTaskId) {
- Utils::throwError('20003:创建配音任务失败!');
- }
-
- $update_data['audio_url'] = '';
- } else {
- // dialogue为空时,直接写入默认音频信息
- $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
- $update_data['audio_duration'] = 2.0;
- $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
- }
- }
- $boolen = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($update_data);
- // 如果是第一集的首帧图片,则存入待更新数组
- if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
- Redis::sadd('anime_first_frame_urls', $segment_id);
- }
- if ($dubTaskId) {
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
- logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
- Utils::throwError('20003:火山生成音频失败');
- }
- }
-
- } catch (\Exception $e) {
- $failed_segments[] = [
- 'segment_id' => $segment_id,
- 'error' => $e->getMessage()
- ];
- }
- // 创建任务之后先暂停10s等待异步任务完成
- sleep(10);
- $img_url = $this->loopGetPicTaskResult($task_id);
- if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
-
- // 图片生成后新增对话记录
- try {
- $uid = Site::getUid();
- $now = date('Y-m-d H:i:s');
-
- // 使用AI反推图片提示词
- $pic_prompt = $this->generateImagePromptFromUrl($img_url);
-
- // 保存对话记录
- $records = [
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'sequence' => $episode_number,
- 'role' => 'user',
- 'content' => '重新生成',
- 'segment_id' => $segment_id,
- 'image_url' => '',
- 'created_at' => $now,
- 'updated_at' => $now
- ],
- [
- 'uid' => $uid,
- 'anime_id' => $anime_id,
- 'sequence' => $episode_number,
- 'role' => 'assistant',
- 'content' => $pic_prompt,
- 'segment_id' => $segment_id,
- 'image_url' => $img_url,
- 'created_at' => $now,
- 'updated_at' => $now
- ]
- ];
-
- DB::table('mp_anime_records')->insert($records);
- } catch (\Exception $e) {
- // 记录日志但不影响主流程
- dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
- 'segment_id' => $segment_id,
- 'img_url' => $img_url
- ]);
- }
-
- return $img_url;
- }
- public function addSegment($data) {
- $prev_segment_id = getProp($data, 'prev_segment_id');
- $img_url = getProp($data, 'img_url');
- $video_url = getProp($data, 'video_url');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
- if (!$segment) Utils::throwError('20003:该分镜不存在');
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_number = getProp($segment, 'segment_number');
- $new_segment_number = $segment_number + 1;
- $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
- // 分镜剧本数组
- $insert_data = [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'episode_number' => $episode_number,
- 'act_number' => getProp($segment, 'act_number'),
- 'act_title' => getProp($segment, 'act_title'),
- 'segment_id' => $segment_id,
- 'segment_number' => $new_segment_number,
- 'segment_content' => '',
- 'img_url' => '',
- 'video_url' => '',
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- if ($img_url) $insert_data['img_url'] = $img_url;
- if ($video_url) {
- $insert_data['origin_video_url'] = $video_url;
- $insert_data['current_type'] = 2;
- $compressed_video_url = compressVideo($video_url);
- $insert_data['video_url'] = $compressed_video_url ?: $video_url;
- }
- try {
- DB::beginTransaction();
- // 先更新序号
- DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
- $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
- if (!$id) {
- Utils::throwError('20003:新增分镜失败!');
- }
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
- $segment = $segment ? (array)$segment : [];
- return $segment;
- // 以下代码暂弃用
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_number = getProp($segment, 'segment_number');
- $segment_content = getProp($data, 'segment_content');
- $img_url = getProp($data, 'img_url');
- $video_url = getProp($data, 'video_url');
- $ratio = getProp($data, 'ratio');
- $dimensions = $this->getRatioDimensions($ratio);
- $width = $dimensions['width'];
- $height = $dimensions['height'];
-
- if (!$anime_id || !$episode_id) {
- Utils::throwError('1002:请选择分镜');
- }
- // 使用文生文模型重新解析segment_content
- if (!empty($segment_content)) {
- $segment_content = $this->parseSegmentContentWithAI($segment_content);
- }
- // 获取动漫的角色信息(包含参考图)
- $anime = DB::table('mp_animes')
- ->where('id', $anime_id)
- ->select('roles', 'scenes')
- ->first();
-
- if (!$anime || !$anime->roles) {
- Utils::throwError('20003:未找到角色信息');
- }
- $roles = json_decode($anime->roles, true);
- if (!$roles) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $role_map = [];
- foreach ($roles as $role) {
- $role_name = getProp($role, 'role');
- $role_url = getProp($role, 'url');
- if (!empty($role_name) && !empty($role_url)) {
- $role_map[$role_name] = $role_url;
- }
- }
- $scenes = json_decode($anime->scenes, true);
- if (!$scenes) {
- Utils::throwError('20003:角色信息格式错误');
- }
- // 构建角色名称到参考图的映射
- $scene_map = [];
- foreach ($scenes as $scene) {
- $scene_name = getProp($scene, 'scene');
- $scene_url = getProp($scene, 'url');
- if (!empty($scene_name) && !empty($scene_url)) {
- $scene_map[$scene_name] = $scene_url;
- }
- }
- $segment_id = $segment->segment_id;
- $original_segment_content = $segment->segment_content;
-
- // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
- $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
-
- if (empty($final_segment_content)) {
- Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
- }
- try {
- $dubTaskId = 0;
- DB::beginTransaction();
- $new_segment_number = $segment_number + 1;
- $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
- // 分镜剧本数组
- $insert_data = [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'episode_number' => $episode_number,
- 'act_number' => getProp($segment, 'act_number'),
- 'act_title' => getProp($segment, 'act_title'),
- 'segment_id' => $segment_id,
- 'segment_number' => $new_segment_number,
- 'segment_content' => $final_segment_content,
- 'img_url' => $img_url,
- 'video_url' => $video_url,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- // 更新分镜剧本信息
- $this->handleSegmentContent($insert_data);
- // 如果有对话内容,创建视频配音合成任务
- $dialogue = getProp($insert_data, 'dialogue');
- if (!empty($dialogue)) {
- $now = date('Y-m-d H:i:s');
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($insert_data, 'voice_actor'),
- 'voice_type' => getProp($insert_data, 'voice_type'),
- 'voice_name' => getProp($insert_data, 'voice_name'),
- 'emotion' => getProp($insert_data, 'emotion'),
- 'emotion_type' => getProp($insert_data, 'emotion_type'),
- 'gender' => getProp($insert_data, 'gender'),
- 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
- 'pitch' => getProp($insert_data, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $segment_id,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
-
- if (!$dubTaskId) {
- Utils::throwError('20003:创建配音任务失败!');
- }
- $insert_data['audio_url'] = '';
- } else {
- // dialogue为空时,直接写入默认音频信息
- $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
- $insert_data['audio_duration'] = 2.0;
- $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
- }
- // 如果没有上传图片则使用当前描述进行生成
- if (!$img_url) {
- // 解析分镜内容,提取画面描述作为主要提示词
- $prompt = $final_segment_content;
- $ref_img_urls = [];
- // 分镜场景
- $scene = getProp($insert_data, 'scene');
- if ($scene) {
- $matched_scene = '';
- if (isset($scene_map[$scene])) {
- $img_index = count($ref_img_urls) + 1;
- $prompt = "场景:$scene(图$img_index)\n$prompt";
- $ref_img_urls[] = $scene_map[$scene];
- $matched_scene = $scene;
- }
- $update_data['scene'] = $scene;
- }
- // 分镜角色
- $characters = getProp($insert_data, 'characters');
- if ($characters) {
- $update_data['characters'] = $characters;
- $characters = str_replace(['、', ',', ';'], ',', $characters);
- $characters = explode(',', $characters);
-
- // 从分镜内容中提取涉及的角色
- $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
-
- // 获取匹配角色的参考图
- foreach ($segment_characters as $character) {
- if (isset($role_map[$character])) {
- // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
- $img_index = count($ref_img_urls) + 1;
- $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
- $ref_img_urls[] = $role_map[$character];
- }
- }
- }
-
-
- // 如果没有找到匹配的角色参考图,不使用参考图
- if (empty($ref_img_urls)) {
- $ref_img_urls = [];
- }
- // 准备生成任务参数
- $params = [
- 'alias_segment_id' => $segment_id,
- 'prompt' => $prompt,
- 'ref_img_urls' => $ref_img_urls,
- 'width' => $width,
- 'height' => $height,
- ];
-
- // 调用AI图片生成服务
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
- // $task_id = 'whatever';
- if (!$task_id) {
- Utils::throwError('20003:创建生成任务失败!');
- }
- $insert_data['pic_task_status'] = '生成中';
- $insert_data['pic_task_id'] = $task_id;
- }
-
- // 先更新序号
- DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
- $boolen = DB::table('mp_episode_segments')->insert($insert_data);
- if (!$boolen) {
- Utils::throwError('20003:新增分镜失败!');
- }
- // 如果是第一集的首帧图片,则存入待更新数组
- if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
- Redis::sadd('anime_first_frame_urls', $segment_id);
- }
-
- if ($dubTaskId) {
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
- Utils::throwError('20003:火山生成音频失败');
- }
- }
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- // 创建任务之后先暂停10s等待异步任务完成
- sleep(10);
- if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
- if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- $segment = $segment ? (array)$segment : [];
- return $segment;
- }
- public function copySegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$segment) Utils::throwError('20003:请选择分镜');
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_number = getProp($segment, 'segment_number');
- $new_segment_id = 0;
- try {
- DB::beginTransaction();
- $segment = (array)$segment;
- unset($segment['id']);
- $segment['segment_number'] += 1;
- $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
- // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
- $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
- // 更新其他分镜序号
- DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
- // 复制分镜
- $id = DB::table('mp_episode_segments')->insertGetId($segment);
- if (!$id) {
- Utils::throwError('20003:复制分镜失败');
- }
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
- $segment = $segment ? (array)$segment : [];
- return $segment;
- }
- public function moveSegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $target_segment_id = getProp($data, 'target_segment_id');
-
- // 获取源分镜信息
- $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$source_segment) Utils::throwError('20003:请选择分镜');
-
- // 获取目标分镜信息
- $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
- if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
-
- $anime_id = getProp($source_segment, 'anime_id');
- $episode_id = getProp($source_segment, 'episode_id');
- $episode_number = getProp($source_segment, 'episode_number');
- $source_segment_number = getProp($source_segment, 'segment_number');
- $target_segment_number = getProp($target_segment, 'segment_number');
-
- // 验证源分镜和目标分镜必须属于同一个动漫的同一集
- $target_anime_id = getProp($target_segment, 'anime_id');
- $target_episode_number = getProp($target_segment, 'episode_number');
-
- if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
- Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
- }
-
- // 如果源分镜和目标分镜相同,无需移动
- if ($source_segment_number == $target_segment_number) {
- return true;
- }
- try {
- DB::beginTransaction();
- if ($source_segment_number < $target_segment_number) {
- // 向后移动:源分镜移动到目标分镜之后
- // 1. 将源分镜和目标分镜之间的所有分镜序号减1
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('segment_number', '>', $source_segment_number)
- ->where('segment_number', '<=', $target_segment_number)
- ->decrement('segment_number');
-
- // 2. 将源分镜移动到目标分镜之后
- $new_segment_number = $target_segment_number;
-
- } else {
- // 向前移动:源分镜移动到目标分镜之后
- // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('segment_number', '>', $target_segment_number)
- ->where('segment_number', '<', $source_segment_number)
- ->increment('segment_number');
-
- // 2. 将源分镜移动到目标分镜之后
- $new_segment_number = $target_segment_number + 1;
- }
-
- // 3. 更新源分镜的序号
- $update_result = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update([
- 'segment_number' => $new_segment_number,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- if (!$update_result) {
- Utils::throwError('20003:更新分镜序号失败');
- }
- DB::commit();
- return true;
-
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- public function delSegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$segment) Utils::throwError('20003:请选择分镜');
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $episode_number = getProp($segment, 'episode_number');
- $segment_number = getProp($segment, 'segment_number');
- try {
- DB::beginTransaction();
- // 删除分镜
- $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
- if (!$boolen) {
- Utils::throwError('20003:删除分镜失败');
- }
- // 更新其他分镜序号
- DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- return true;
- }
- public function applySegment($data) {
- $segment_id = getProp($data, 'segment_id');
- $url = getProp($data, 'url');
- if (!$segment_id) Utils::throwError('20003:请选择分镜');
- if (!$url) Utils::throwError('20003:URL不能为空');
-
- // 获取URL的文件扩展名
- $urlPath = parse_url($url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- // 定义图片和视频的扩展名
- $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
- $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
-
- // 判断是图片还是视频
- $updateData = ['updated_at' => date('Y-m-d H:i:s')];
-
- if (in_array($extension, $imageExtensions)) {
- // 图片类型
- $updateData['img_url'] = $url;
- $updateData['current_type'] = 1;
- } elseif (in_array($extension, $videoExtensions)) {
- // 视频类型
- $updateData['video_url'] = $url;
- $updateData['current_type'] = 2;
- } else {
- Utils::throwError('20003:不支持的文件类型');
- }
-
- // 更新分镜表
- $result = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($updateData);
-
- if (!$result) {
- Utils::throwError('20003:更新分镜失败');
- }
-
- return true;
- }
- public function segmentHistory($data) {
- $segment_id = getProp($data, 'segment_id');
- // 获取历史图片
- $pics = [];
- $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($pic_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $pics = array_merge($pics, json_decode($result_url, true));
- }else {
- $pics[] = $result_url;
- }
- }
-
- // 获取历史视频
- $videos = [];
- $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($video_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $videos = array_merge($videos, json_decode($result_url, true));
- }else {
- $videos[] = $result_url;
- }
- }
- return compact('pics', 'videos');
- }
- public function addAct($data) {
- $prev_act_id = getProp($data, 'prev_act_id');
- $act_title = getProp($data, 'act_title', '');
- $act_content = getProp($data, 'act_content', '');
- $act_duration = getProp($data, 'act_duration', 5);
- $video_url = getProp($data, 'video_url');
-
- // 根据prev_act_id获取记录
- $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
- if (!$prev_segment) Utils::throwError('20003:该片段不存在');
-
- $anime_id = getProp($prev_segment, 'anime_id');
- $episode_id = getProp($prev_segment, 'episode_id');
- $episode_number = getProp($prev_segment, 'episode_number');
- $prev_act_number = getProp($prev_segment, 'act_number');
-
- // 获取新的act_number
- $new_act_number = $prev_act_number + 1;
- try {
- DB::beginTransaction();
-
- // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $prev_act_number)
- ->increment('act_number');
- // 插入新片段记录
- $insert_data = [
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'episode_number' => $episode_number,
- 'act_number' => $new_act_number,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- if ($act_title) {
- $insert_data['act_title'] = $act_title;
- }
- if ($act_content) {
- $insert_data['act_content'] = $act_content;
- }
- if ($act_duration) {
- $insert_data['act_duration'] = $act_duration;
- }
- if ($video_url) {
- $insert_data['origin_video_url'] = $video_url;
- $insert_data['current_type'] = 2;
- $compressed_video_url = compressVideo($video_url);
- $insert_data['video_url'] = $compressed_video_url ?: $video_url;
- }
- $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
- if (!$id) {
- Utils::throwError('20003:新增片段失败!');
- }
-
- DB::commit();
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
-
- $segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
- $segment = $segment ? (array)$segment : [];
- return $segment;
- }
- public function editAct($data) {
- $act_id = getProp($data, 'act_id');
- $act_content = getProp($data, 'act_content');
- $act_duration = getProp($data, 'act_duration');
- $act_title = getProp($data, 'act_title');
- $image_url = getProp($data, 'image_url');
- $video_url = getProp($data, 'video_url');
- // 参数验证
- if (!$act_id) Utils::throwError('20003:请提供片段ID');
- // 验证片段是否存在(全能模式下每个act只有一条记录)
- $segment = DB::table('mp_episode_segments')
- ->where('id', $act_id)
- ->first();
-
- if (!$segment) Utils::throwError('20003:该片段不存在');
- try {
- DB::beginTransaction();
-
- // 准备更新数据
- $update_data = [
- 'updated_at' => date('Y-m-d H:i:s')
- ];
- // 更新act相关字段
- if (!empty($act_content)) {
- $update_data['act_content'] = $act_content;
- }
-
- if (!empty($act_duration)) {
- $update_data['act_duration'] = $act_duration;
- }
-
- if (!empty($act_title)) {
- $update_data['act_title'] = $act_title;
- }
- // 处理图片上传
- if ($image_url) {
- $update_data['img_url'] = $image_url;
- $update_data['current_type'] = 1;
- // 同时写入一个图片生成任务记录
- if ($act_id) {
- $pic_task = [
- 'alias_act_id' => $act_id,
- 'ref_img_url' => json_encode([]),
- 'status' => 'success',
- 'result_url' => json_encode([$image_url], 256),
- 'model' => '',
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- DB::table('mp_generate_pic_tasks')->insert($pic_task);
- }
- }
- // 处理视频上传
- if ($video_url) {
- $update_data['origin_video_url'] = $video_url;
- $compressed_video_url = compressVideo($video_url);
- $update_data['current_type'] = 2;
- $update_data['video_url'] = $compressed_video_url ?: $video_url;
- // 同时写入一个视频生成任务记录
- if ($act_id) {
- $video_task = [
- 'alias_act_id' => $act_id,
- 'status' => 'success',
- 'result_url' => $update_data['origin_video_url'],
- 'compressed_url' => $update_data['video_url'],
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ];
- DB::table('mp_generate_video_tasks')->insert($video_task);
- }
- }
- // 更新片段信息
- $result = DB::table('mp_episode_segments')
- ->where('id', $act_id)
- ->update($update_data);
- if ($result === false) {
- Utils::throwError('20003:更新片段失败');
- }
- DB::commit();
- return true;
- } catch (\Exception $e) {
- DB::rollBack();
- dLog('anime')->error('更新片段失败', [
- 'act_id' => $act_id,
- 'error' => $e->getMessage()
- ]);
- Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
- }
- }
- public function copyAct($data) {
- $act_id = getProp($data, 'act_id');
-
- // 根据act_id获取记录(全能模式下每个act只有一条记录)
- $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if (!$source_segment) Utils::throwError('20003:请选择片段');
- $video_url = getProp($source_segment, 'video_url');
- if (!$video_url) Utils::throwError('20003:该片段没有视频无法复制');
-
- $anime_id = getProp($source_segment, 'anime_id');
- $episode_id = getProp($source_segment, 'episode_id');
- $episode_number = getProp($source_segment, 'episode_number');
- $act_number = getProp($source_segment, 'act_number');
- try {
- DB::beginTransaction();
- // 新act的编号
- $new_act_number = $act_number + 1;
-
- // 更新后续所有act的act_number
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $act_number)
- ->increment('act_number');
- // 复制该片段记录
- $segment_data = (array)$source_segment;
- unset($segment_data['id']);
- $segment_data['act_number'] = $new_act_number;
- $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
- $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
- if (!$id) {
- Utils::throwError('20003:复制片段失败');
- }
-
- DB::commit();
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- // 返回新复制的记录
- $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
- $new_segment = $new_segment ? (array)$new_segment : [];
- $new_segment['act_id'] = $id;
- return $new_segment;
- }
- public function moveAct($data) {
- $act_id = getProp($data, 'act_id');
- $target_act_id = getProp($data, 'target_act_id');
-
- // 获取源片段信息
- $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if (!$source_segment) Utils::throwError('20003:请选择片段');
-
- // 获取目标片段信息
- $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
- if (!$target_segment) Utils::throwError('20003:目标片段不存在');
-
- $anime_id = getProp($source_segment, 'anime_id');
- $episode_id = getProp($source_segment, 'episode_id');
- $source_act_number = getProp($source_segment, 'act_number');
- $target_act_number = getProp($target_segment, 'act_number');
-
- // 验证源片段和目标片段必须属于同一个动漫的同一集
- $target_anime_id = getProp($target_segment, 'anime_id');
- $target_episode_id = getProp($target_segment, 'episode_id');
-
- if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
- Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
- }
-
- // 如果源片段和目标片段相同,无需移动
- if ($source_act_number == $target_act_number) {
- return true;
- }
- try {
- DB::beginTransaction();
- if ($source_act_number < $target_act_number) {
- // 向后移动:源片段移动到目标片段之后
- // 1. 将源片段和目标片段之间的所有片段编号减1
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $source_act_number)
- ->where('act_number', '<=', $target_act_number)
- ->decrement('act_number');
-
- // 2. 将源片段移动到目标片段之后
- $new_act_number = $target_act_number;
-
- } else {
- // 向前移动:源片段移动到目标片段之后
- // 1. 将目标片段之后到源片段之前的所有片段编号加1
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $target_act_number)
- ->where('act_number', '<', $source_act_number)
- ->increment('act_number');
-
- // 2. 将源片段移动到目标片段之后
- $new_act_number = $target_act_number + 1;
- }
-
- // 3. 更新源片段的编号
- $update_result = DB::table('mp_episode_segments')
- ->where('id', $act_id)
- ->update([
- 'act_number' => $new_act_number,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- if (!$update_result) {
- Utils::throwError('20003:更新片段编号失败');
- }
- DB::commit();
- return true;
-
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- public function delAct($data) {
- $act_id = getProp($data, 'act_id');
-
- // 根据act_id获取记录(全能模式下每个act只有一条记录)
- $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if (!$segment) Utils::throwError('20003:请选择片段');
-
- $anime_id = getProp($segment, 'anime_id');
- $episode_id = getProp($segment, 'episode_id');
- $act_number = getProp($segment, 'act_number');
- try {
- DB::beginTransaction();
- // 删除该片段记录
- $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
- if (!$deleted) {
- Utils::throwError('20003:删除片段失败');
- }
- // 更新后续act的编号
- DB::table('mp_episode_segments')
- ->where('anime_id', $anime_id)
- ->where('episode_id', $episode_id)
- ->where('act_number', '>', $act_number)
- ->decrement('act_number');
-
- DB::commit();
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- return true;
- }
- public function applyAct($data) {
- $act_id = getProp($data, 'act_id');
- $url = getProp($data, 'url');
-
- if (!$act_id) Utils::throwError('20003:请选择片段');
- if (!$url) Utils::throwError('20003:URL不能为空');
-
- // 获取URL的文件扩展名
- $urlPath = parse_url($url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- // 定义图片和视频的扩展名
- $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
- $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
-
- // 判断是图片还是视频
- $updateData = ['updated_at' => date('Y-m-d H:i:s')];
-
- if (in_array($extension, $imageExtensions)) {
- // 图片类型
- $updateData['img_url'] = $url;
- $updateData['current_type'] = 1;
- } elseif (in_array($extension, $videoExtensions)) {
- // 视频类型
- $updateData['video_url'] = $url;
- $updateData['current_type'] = 2;
- } else {
- Utils::throwError('20003:不支持的文件类型');
- }
-
- // 更新片段记录(全能模式下每个act只有一条记录)
- $result = DB::table('mp_episode_segments')
- ->where('id', $act_id)
- ->update($updateData);
-
- if (!$result) {
- Utils::throwError('20003:更新片段失败');
- }
-
- return true;
- }
- public function actChatHistory($data) {
- $act_id = getProp($data, 'act_id');
- if (!$act_id) Utils::throwError('20003:请选择片段!');
- $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
-
- $chat = $query->orderBy('id')->get()->map(function ($value) {
- $value = (array)$value;
- $value['created_at'] = transDate($value['created_at']);
- if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
- else $value['reference_images'] = [];
- return $value;
- })->toArray();
- // 获取历史图片
- $url = [];
- $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($pic_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $url = array_merge($url, json_decode($result_url, true));
- }else {
- $url[] = $result_url;
- }
- }
-
- // 获取历史视频
- $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
- foreach($video_history as $task) {
- $result_url = getProp($task, 'result_url');
- if (is_json($result_url)) {
- $url = array_merge($url, json_decode($result_url, true));
- }else {
- $url[] = $result_url;
- }
- }
- // 获取资产库
- $products = [];
-
- // 通过act_id查询片段信息获取episode_id
- $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if ($segment) {
- $episode_id = getProp($segment, 'episode_id');
-
- // 查询剧集信息获取roles、scenes和extra_products
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if ($episode) {
- $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
- $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
- $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
-
- // 先合并roles和scenes
- // 处理角色数组
- foreach ($roles as $role) {
- $product = $role;
- // 将role字段重命名为product_name
- if (isset($product['role'])) {
- $product['product_name'] = $product['role'];
- unset($product['role']);
- }
- $product['product'] = 1; // 标记类型为角色
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
-
- // 处理场景数组
- foreach ($scenes as $scene) {
- $product = $scene;
- // 将scene字段重命名为product_name
- if (isset($product['scene'])) {
- $product['product_name'] = $product['scene'];
- unset($product['scene']);
- }
- $product['product'] = 2; // 标记类型为场景
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
-
- // extra_products优先级更高,直接覆盖同名的roles和scenes
- foreach ($extra_products as $extra_product) {
- $product_name = getProp($extra_product, 'product_name');
- if ($product_name) {
- $products[$product_name] = $extra_product; // 覆盖同名数据
- }
- }
-
- // 重新索引数组(去除key)
- $products = array_values($products);
- }
- }
- // 获取执行中的任务
- $tasks = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->whereNotIn('status', ['success', 'failed'])->select('id as task_id', 'alias_act_id', 'prompt', 'ref_image_url', 'status')->orderBy('id')->get()->map(function($value) {
- $value = (array)$value;
- if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
- else $value['ref_image_url'] = [];
- $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
- // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
- if (!empty($value['prompt'])) {
- $prompt = $value['prompt'];
-
- // 查找第一个【镜头】的位置
- if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
- // 从【镜头】开始截取
- $prompt = substr($prompt, $matches[0][1]);
- }
-
- // 去除所有<图片X>格式的标记(X可以是任意数字)
- $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
-
- $value['prompt'] = $prompt;
- }
-
- return $value;
- })->toArray();
- return compact('chat', 'url', 'products', 'tasks');
- }
- public function applyAudioData($data) {
- $segment_id = getProp($data, 'segment_id');
- $global_data = getProp($data, 'global_data');
- $segment_data = getProp($data, 'segment_data');
- if (!$segment_id) Utils::throwError('20003:请选择分镜');
- $global_data = is_array($global_data) ? $global_data : [];
- $segment_data = is_array($segment_data) ? $segment_data : [];
-
- // dialogue只能在segment_data中,如果在global_data中则移到segment_data
- $dialogue_item = null;
- foreach ($global_data as $key => $item) {
- if (trim((string)getProp($item, 'name')) === 'dialogue') {
- $dialogue_item = $item;
- unset($global_data[$key]);
- break;
- }
- }
- if ($dialogue_item) {
- $segment_data[] = $dialogue_item;
- }
- // 特殊参数: audio_url,audio_duration,subtitle_info
- // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
- // 如果不是全部存在,则仍需创建音频任务
- $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
- $special_update_data = [];
- $has_all_special_params = false;
-
- // 从segment_data中提取特殊参数
- $filtered_segment_data = [];
- foreach ($segment_data as $item) {
- $field_name = trim((string)getProp($item, 'name'));
- if (in_array($field_name, $special_fields)) {
- $special_update_data[$field_name] = getProp($item, 'value');
- } else {
- // 非特殊参数保留,继续后续处理
- $filtered_segment_data[] = $item;
- }
- }
-
- // 检查是否三个特殊参数都存在
- if (count($special_update_data) === 3 &&
- isset($special_update_data['audio_url']) &&
- isset($special_update_data['audio_duration']) &&
- isset($special_update_data['subtitle_info'])) {
- $has_all_special_params = true;
-
- // 立即更新到当前分镜
- $special_update_data['updated_at'] = date('Y-m-d H:i:s');
- DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->update($special_update_data);
- }
-
- // 使用过滤后的segment_data继续处理其他参数
- $segment_data = $filtered_segment_data;
-
- $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
- $global_update_data = [];
- $segment_update_data = [];
- $global_voice_type = '';
- $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$target_segment) Utils::throwError('20003:分镜不存在');
- $episode_id = getProp($target_segment, 'episode_id');
- $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$episode) Utils::throwError('20003:分集不存在');
- foreach ($global_data as $item) {
- $field_name = trim((string)getProp($item, 'name'));
- if (!$field_name || !in_array($field_name, $allow_fields)) {
- continue;
- }
- $global_update_data[$field_name] = getProp($item, 'value');
- if ($field_name === 'voice_type') {
- $global_voice_type = trim((string)getProp($item, 'value'));
- }
- }
- foreach ($segment_data as $item) {
- $field_name = trim((string)getProp($item, 'name'));
- if (!$field_name || !in_array($field_name, $allow_fields)) {
- continue;
- }
- $segment_update_data[$field_name] = getProp($item, 'value');
- }
- if ($global_voice_type) {
- $timbre_info = DB::table('mp_timbres')
- ->where('timbre_type', $global_voice_type)
- ->select('audio_url', 'timbre_name')
- ->first();
- if ($timbre_info) {
- $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
- $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
- }
- }
- try {
- DB::beginTransaction();
-
- // 收集需要创建音频合成任务的segment_id和对应的分镜数据
- $segment_ids_to_create_task = [];
- $segments_data = [];
- // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
- if (!empty($global_update_data)) {
- // 如果角色不存在,则只更新当前分镜
- if (!$target_voice_actor) {
- // 只处理当前分镜
- $affected_segments = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
- ->get();
- } else {
- // 获取该角色的所有分镜
- $affected_segments = DB::table('mp_episode_segments')
- ->where('episode_id', $episode_id)
- ->where('voice_actor', $target_voice_actor)
- ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
- ->get();
- }
-
- foreach ($affected_segments as $seg) {
- $seg = (array)$seg;
- $sid = getProp($seg, 'segment_id');
-
- // 检查参数是否发生变化
- $has_changed = false;
- foreach ($global_update_data as $field => $new_value) {
- $old_value = getProp($seg, $field);
- if ($old_value != $new_value) {
- $has_changed = true;
- break;
- }
- }
-
- if ($has_changed) {
- $segment_ids_to_create_task[] = $sid;
- $segments_data[$sid] = $seg;
- }
- }
-
- // 只有在有变化的分镜时才更新
- if (!empty($segment_ids_to_create_task)) {
- $global_segment_update_data = $global_update_data;
- $global_segment_update_data['audio_url'] = ''; // 清空音频URL
- $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
- DB::table('mp_episode_segments')
- ->where('episode_id', $episode_id)
- ->where('voice_actor', $target_voice_actor)
- ->whereIn('segment_id', $segment_ids_to_create_task)
- ->update($global_segment_update_data);
- }
- if ($global_voice_type) {
- $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
- $episode_roles = is_array($episode_roles) ? $episode_roles : [];
- $roles_updated = false;
- foreach ($episode_roles as &$role) {
- // 通过 role 字段匹配角色名,而不是 voice_name
- if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
- continue;
- }
- $role['voice_type'] = $global_voice_type;
- $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
- $role['voice_name'] = getProp($global_update_data, 'voice_name');
- $roles_updated = true;
- }
- unset($role);
- if ($roles_updated) {
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'roles' => json_encode($episode_roles, 256),
- 'updated_at' => date('Y-m-d H:i:s'),
- ]);
- }
- }
- }
- // 如果有单个分镜更新,检查是否有变化
- if (!empty($segment_update_data)) {
- // 获取当前分镜数据
- $current_segment = DB::table('mp_episode_segments')
- ->where('segment_id', $segment_id)
- ->select('segment_id', 'audio_url', 'voice_actor', 'dialogue', 'voice_type', 'voice_name', 'voice_audio_url', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
- ->first();
-
- if ($current_segment) {
- $current_segment = (array)$current_segment;
-
- // 检查参数是否发生变化
- $has_changed = false;
- foreach ($segment_update_data as $field => $new_value) {
- $old_value = getProp($current_segment, $field);
- if ($old_value != $new_value) {
- $has_changed = true;
- break;
- }
- }
-
- if ($has_changed) {
- // 如果该分镜还未在列表中,添加进去
- if (!in_array($segment_id, $segment_ids_to_create_task)) {
- $segment_ids_to_create_task[] = $segment_id;
- $segments_data[$segment_id] = $current_segment;
- }
-
- // 更新分镜数据并清空音频URL
- $segment_update_data['audio_url'] = '';
- $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
- DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
- }
- }
- }
- // 为所有有变化的分镜创建音频合成任务
- // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
- if (!empty($segment_ids_to_create_task)) {
- foreach ($segment_ids_to_create_task as $sid) {
- // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
- if ($sid === $segment_id && $has_all_special_params) {
- continue;
- }
-
- // 重新获取更新后的分镜数据
- $updated_segment = DB::table('mp_episode_segments')
- ->where('segment_id', $sid)
- ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
- ->first();
-
- if (!$updated_segment) continue;
-
- $updated_segment = (array)$updated_segment;
-
- // 检查dialogue是否为空
- $dialogue = getProp($updated_segment, 'dialogue');
- if (empty($dialogue)) {
- // dialogue为空时,直接写入默认音频信息
- DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
- 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
- 'audio_duration' => 2.0,
- 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- continue;
- }
- $generate_json = [
- 'text' => $dialogue,
- 'role' => getProp($updated_segment, 'voice_actor'),
- 'voice_type' => getProp($updated_segment, 'voice_type'),
- 'voice_name' => getProp($updated_segment, 'voice_name'),
- 'emotion' => getProp($updated_segment, 'emotion'),
- 'emotion_type' => getProp($updated_segment, 'emotion_type'),
- 'gender' => getProp($updated_segment, 'gender'),
- 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
- 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
- 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
- 'pitch' => getProp($updated_segment, 'pitch', 0),
- ];
-
- // 插入视频配音合成任务
- $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
- 'alias_segment_id' => $sid,
- 'generate_status' => '执行中',
- 'audio_url' => '',
- 'generate_json' => json_encode($generate_json, 256),
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s'),
- ]);
-
- if (!$dubTaskId) {
- dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
- continue;
- }
- // 将任务ID添加到Redis列表中
- Redis::lpush('dub_video_task_queue', $dubTaskId);
-
- // 请求远程服务器执行生成
- try {
- sleep(1);
- $client = new Client(['timeout' => 300, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
-
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
- logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
- logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
- }
- }
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- return true;
- }
- public function episodePicsInfo($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- // 参数验证
- if (!$anime_id && !$episode_id) {
- Utils::throwError('20003:请提供动漫ID或分集ID');
- }
- // 根据参数获取数据源
- if ($episode_id) {
- // 从剧集表获取
- $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$source) Utils::throwError('20003:该剧集不存在');
- $table_name = 'mp_anime_episodes';
- $id_field = 'id';
- $id_value = $episode_id;
-
- // 获取剧集的anime_id用于继承全局数据
- $anime_id = getProp($source, 'anime_id');
- } else {
- // 从动漫表获取
- $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
- if (!$source) Utils::throwError('20003:该动漫不存在');
- $table_name = 'mp_animes';
- $id_field = 'id';
- $id_value = $anime_id;
- }
- $source = (array)$source;
- $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
- $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
-
- // 如果是分集数据,需要处理继承和任务创建逻辑
- if ($episode_id) {
- $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
- }
- // 返回生成器函数,用于 SSE 流式输出
- return function() use ($roles, $scenes, $table_name, $id_field, $id_value) {
- $startTime = time();
- $maxDuration = 600; // 10分钟超时
- $checkInterval = 3; // 每3秒检查一次
- // Redis 缓存键
- $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
-
- // 生成当前数据的哈希值用于比较
- $generateHash = function($roles, $scenes) {
- return md5(json_encode(['roles' => $roles, 'scenes' => $scenes], JSON_UNESCAPED_UNICODE));
- };
- // 发送初始数据
- $currentHash = $generateHash($roles, $scenes);
- Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
- echo "data: " . json_encode([
- 'type' => 'init',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'start_time' => $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- ob_flush();
- flush();
- // 持续轮询任务状态
- while (time() - $startTime < $maxDuration) {
- $hasProcessing = false;
- $updated = false;
- // 检查角色任务状态
- foreach ($roles as $index => &$role) {
- $task_id = getProp($role, 'task_id');
- $task_status = getProp($role, 'task_status');
- $existing_url = getProp($role, 'url');
- // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
- if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
- $hasProcessing = ($task_status === 'processing');
-
- // 查询任务状态
- $task = DB::table('mp_generate_pic_tasks')
- ->where('id', $task_id)
- ->select('id', 'status', 'result_url', 'error_message')
- ->first();
- if ($task) {
- $task = (array)$task;
- $status = getProp($task, 'status');
- // 如果任务完成或失败
- if (in_array($status, ['success', 'failed'])) {
- $role['task_status'] = $status;
-
- if ($status === 'success') {
- $result_url = getProp($task, 'result_url');
- if ($result_url) {
- $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
- if (is_array($result_urls) && !empty($result_urls[0])) {
- $role['url'] = $result_urls[0];
- }
- }
- }
-
- $updated = true;
- } else if ($status === 'processing') {
- $hasProcessing = true;
- }
- }
- }
- }
- // 检查场景任务状态
- foreach ($scenes as $index => &$scene) {
- $task_id = getProp($scene, 'task_id');
- $task_status = getProp($scene, 'task_status');
- $existing_url = getProp($scene, 'url');
- // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
- if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
- $hasProcessing = ($task_status === 'processing');
-
- // 查询任务状态
- $task = DB::table('mp_generate_pic_tasks')
- ->where('id', $task_id)
- ->select('id', 'status', 'result_url', 'error_message')
- ->first();
- if ($task) {
- $task = (array)$task;
- $status = getProp($task, 'status');
- // 如果任务完成或失败
- if (in_array($status, ['success', 'failed'])) {
- $scene['task_status'] = $status;
-
- if ($status === 'success') {
- $result_url = getProp($task, 'result_url');
- if ($result_url) {
- $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
- if (is_array($result_urls) && !empty($result_urls[0])) {
- $scene['url'] = $result_urls[0];
- }
- }
- }
-
- $updated = true;
- } else if ($status === 'processing') {
- $hasProcessing = true;
- }
- }
- }
- }
- // 如果有更新,检查数据是否真的变化了(通过哈希对比)
- if ($updated) {
- $newHash = $generateHash($roles, $scenes);
- $cachedHash = Redis::get($cacheKey);
- // 只有当数据真正变化时才更新数据库和发送事件
- if ($newHash !== $cachedHash) {
- try {
- // 更新数据库
- DB::table($table_name)->where($id_field, $id_value)->update([
- 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
- 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- // 更新缓存
- Redis::setex($cacheKey, 600, $newHash);
- // 发送更新事件
- echo "data: " . json_encode([
- 'type' => 'update',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'elapsed_time' => time() - $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- ob_flush();
- flush();
- } catch (\Exception $e) {
- dLog('anime')->error('更新角色/场景信息失败: ' . $e->getMessage());
- }
- } else {
- // 即使哈希相同,如果有URL更新也要发送事件
- $hasUrlUpdate = false;
- foreach ($roles as $role) {
- if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
- $hasUrlUpdate = true;
- break;
- }
- }
- if (!$hasUrlUpdate) {
- foreach ($scenes as $scene) {
- if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
- $hasUrlUpdate = true;
- break;
- }
- }
- }
-
- if ($hasUrlUpdate) {
- // 强制更新数据库和发送事件
- try {
- DB::table($table_name)->where($id_field, $id_value)->update([
- 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
- 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- // 更新缓存
- Redis::setex($cacheKey, 600, $newHash);
- // 发送更新事件
- echo "data: " . json_encode([
- 'type' => 'update',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'elapsed_time' => time() - $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- ob_flush();
- flush();
- } catch (\Exception $e) {
- dLog('anime')->error('强制更新角色/场景信息失败: ' . $e->getMessage());
- }
- }
- }
- }
- // 如果所有任务都已完成,发送完成事件并退出
- if (!$hasProcessing) {
- // 查询数据库中的最终数据,确保返回最新的完整数据
- try {
- $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
- if ($finalSource) {
- $finalSource = (array)$finalSource;
- $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
- $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
-
- // 使用数据库中的最终数据
- $roles = $finalRoles;
- $scenes = $finalScenes;
- }
- } catch (\Exception $e) {
- dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
- // 如果查询失败,继续使用内存中的数据
- }
-
- // 清理缓存
- Redis::del($cacheKey);
- echo "data: " . json_encode([
- 'type' => 'completed',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'total_time' => time() - $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- ob_flush();
- flush();
- break;
- }
- // 等待下次检查
- sleep($checkInterval);
- }
- // 超时处理
- if (time() - $startTime >= $maxDuration) {
- // 查询数据库中的最终数据,即使超时也要返回最新数据
- try {
- $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
- if ($finalSource) {
- $finalSource = (array)$finalSource;
- $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
- $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
-
- // 使用数据库中的最终数据
- $roles = $finalRoles;
- $scenes = $finalScenes;
- }
- } catch (\Exception $e) {
- dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
- // 如果查询失败,继续使用内存中的数据
- }
-
- // 清理缓存
- Redis::del($cacheKey);
- echo "data: " . json_encode([
- 'type' => 'timeout',
- 'message' => '轮询超时,请刷新页面查看最新状态',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- ob_flush();
- flush();
- }
- };
- }
- public function clipSegmentVideo($data) {
- $segment_id = getProp($data, 'segment_id');
- $video_time_point_start = getProp($data, 'video_time_point_start');
- $video_time_point_end = getProp($data, 'video_time_point_end');
- if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
- Utils::throwError('20003:参数异常');
- }
- if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
- Utils::throwError('20003:该分镜没有视频,无法裁剪');
- }
- $video_duration = $video_time_point_end - $video_time_point_start;
- if (!$video_duration < 0) Utils::throwError('20003:参数异常');
- return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
- 'video_duration' => $video_duration,
- 'video_time_point_start' => $video_time_point_start,
- 'video_time_point_end' => $video_time_point_end,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- // 轮训获取图片任务结果
- private function loopGetPicTaskResult($task_id) {
- $task = MpGeneratePicTask::where('id', $task_id)->first();
- if (!$task) {
- return '';
- }
- // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
- $model = getProp($task, 'model');
- $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
- $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
- $isSyncModel = $isVolcModel || $isGptModel;
- // 轮询查询任务状态(火山API和即梦AI都需要轮询)
- $start_count = 0;
- $img_url = '';
- while ($start_count <= 60) { // 循环20次请求,每3s一次
- sleep(3);
- $task = MpGeneratePicTask::where('id', $task_id)->first();
-
- // 如果任务已经完成,直接返回结果
- if ($task->status === 'success' && $task->result_url) {
- $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
- return is_array($result_urls) ? $result_urls[0] : $task->result_url;
- }
-
- // 如果任务已失败,返回空
- if ($task->status === 'failed') {
- return '';
- }
- if ($isSyncModel) continue;
-
- // 查询任务状态
- $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
- if ($statusInfo['status'] === 'success') {
- $task->updateStatus('success', [
- 'result_url' => $statusInfo['result_url'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
- // 同步调整分镜图片状态和结果
- if (getProp($task, 'alias_segment_id')) {
- DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
- 'img_url' => $statusInfo['result_url'][0],
- 'pic_task_status' => '已完成',
- ]);
- }
- $img_url = $statusInfo['result_url'][0];
- break;
- } elseif ($statusInfo['status'] === 'failed') {
- $task->updateStatus('failed', [
- 'error_message' => $statusInfo['error_message'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
- if (getProp($task, 'alias_segment_id')) {
- DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
- 'pic_task_status' => '失败',
- ]);
- }
- break;
- }
- $start_count++;
- }
- return $img_url;
- }
- /**
- * 从分镜内容中提取涉及的角色
- */
- private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
- $found_characters = [];
-
- foreach ($available_characters as $character) {
- // 检查角色名称是否在分镜内容中出现
- if (strpos($segment_content, $character) !== false) {
- $found_characters[] = $character;
- }
- }
- if (!$found_characters) {
- foreach ($roles as $character) {
- // 检查角色名称是否在分镜内容中出现
- if (strpos($segment_content, $character) !== false) {
- $found_characters[] = $character;
- }
- }
- }
-
- return array_unique($found_characters);
- }
- // 从分镜剧本中提取关键字段
- private function handleSegmentContent(&$data) {
- $segmentContent = getProp($data, 'segment_content');
- // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
- $segmentData = [
- 'description' => '',
- 'composition' => '',
- 'camera_movement' => '',
- 'voice_actor' => '',
- 'dialogue' => '',
- 'frame_type' => '',
- 'scene' => '', // 场景
- 'characters' => '', // 出镜角色
- 'tail_frame' => '', // 尾帧描述
- 'emotion' => '中性', // 情感
- 'gender' => '0', // 性别(0未知,1男,2女)
- 'speed_ratio' => 0, // 语速
- 'loudness_ratio' => 0, // 音量
- 'emotion_scale' => 4, // 情感强度
- 'pitch' => 0, // 音调
- ];
-
- // 用于存储需要从 segment_content 中移除的匹配项
- $replaceEmptyArr = [];
-
- // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
- if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
- $segmentData['description'] = trim($descMatch[1]);
- $data['description'] = trim($descMatch[1]);
- }
- if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
- $segmentData['composition'] = trim($compMatch[1]);
- $data['composition'] = trim($compMatch[1]);
- }
- if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
- $segmentData['camera_movement'] = trim($cameraMatch[1]);
- $data['camera_movement'] = trim($cameraMatch[1]);
- }
- if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
- $segmentData['voice_actor'] = trim($voiceMatch[1]);
- $data['voice_actor'] = trim($voiceMatch[1]);
- }
- if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
- $segmentData['dialogue'] = trim($dialogueMatch[1]);
- $data['dialogue'] = trim($dialogueMatch[1]);
- }
- if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
- $segmentData['frame_type'] = trim($frameMatch[1]);
- $data['frame_type'] = trim($frameMatch[1]);
- }
- // 场景字段
- if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
- $segmentData['scene'] = trim($sceneMatch[1]);
- $data['scene'] = trim($sceneMatch[1]);
- }
- // 出镜角色字段
- if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
- $segmentData['characters'] = trim($charactersMatch[1]);
- $data['characters'] = trim($charactersMatch[1]);
- }
- // 尾帧描述字段
- if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
- $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
- $data['tail_frame'] = trim($tailFrameMatch[1]);
- }
-
- // 情感字段
- if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
- $replaceEmptyArr[] = trim($emotionMatch[0]);
- $segmentData['emotion'] = trim($emotionMatch[1]);
- $data['emotion'] = trim($emotionMatch[1]);
- }
-
- // 性别字段
- if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
- $replaceEmptyArr[] = trim($genderMatch[0]);
- $genderStr = trim($genderMatch[1]);
- if (strpos($genderStr, '男') !== false || $genderStr === '1') {
- $segmentData['gender'] = '1';
- $data['gender'] = '1';
- } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
- $segmentData['gender'] = '2';
- $data['gender'] = '2';
- } else {
- $segmentData['gender'] = '0';
- $data['gender'] = '0';
- }
- }
-
- // 语速字段
- if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
- $replaceEmptyArr[] = trim($speedMatch[0]);
- $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
- $data['speed_ratio'] = (float)trim($speedMatch[1]);
- }
-
- // 音量字段
- if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
- $replaceEmptyArr[] = trim($loudnessMatch[0]);
- $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
- $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
- }
-
- // 情感强度字段
- if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
- $replaceEmptyArr[] = trim($scaleMatch[0]);
- $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
- $data['emotion_scale'] = (int)trim($scaleMatch[1]);
- }
-
- // 音调字段
- if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
- $replaceEmptyArr[] = trim($pitchMatch[0]);
- $segmentData['pitch'] = (int)trim($pitchMatch[1]);
- $data['pitch'] = (int)trim($pitchMatch[1]);
- }
-
- // 从 segment_content 中移除已提取的配音参数字段
- if (!empty($replaceEmptyArr)) {
- $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
- }
-
- // 如果有配音角色,查询音色信息并验证情感
- $voice_actor = $segmentData['voice_actor'];
- if (!empty($voice_actor) && $voice_actor !== '旁白') {
- // 从当前分镜所属的剧集或动漫中查找角色音色信息
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
-
- // 优先从剧集的角色列表中查找
- $roles = [];
- if ($episode_id) {
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if ($episode && getProp($episode, 'roles')) {
- $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
- }
- }
-
- // 如果剧集中没有,从动漫的角色列表中查找
- if (empty($roles) && $anime_id) {
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- if ($anime && getProp($anime, 'roles')) {
- $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
- }
- }
-
- // 查找匹配的角色音色信息
- $timbre_info = null;
- foreach ($roles as $role) {
- if (getProp($role, 'role') === $voice_actor) {
- $timbre_info = $role;
- break;
- }
- }
-
- // 如果找到音色信息,添加到数据中
- if ($timbre_info) {
- $voice_type = getProp($timbre_info, 'voice_type');
- $voice_name = getProp($timbre_info, 'voice_name');
- $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
-
- if ($voice_type) {
- $data['voice_type'] = $voice_type;
- $segmentData['voice_type'] = $voice_type;
- }
- if ($voice_name) {
- $data['voice_name'] = $voice_name;
- $segmentData['voice_name'] = $voice_name;
- }
- if ($voice_audio_url) {
- $data['voice_audio_url'] = $voice_audio_url;
- $segmentData['voice_audio_url'] = $voice_audio_url;
- }
-
- // 验证情感是否在音色支持的情感列表中
- if ($voice_type) {
- $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
- if ($timbre_emotion) {
- $timbre_emotion = explode(',', $timbre_emotion);
- } else {
- $timbre_emotion = [];
- }
- $emotion = getProp($segmentData, 'emotion', '中性');
- if (!in_array($emotion, $timbre_emotion)) {
- $emotion = '中性';
- }
- $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
- $emotion_list = array_flip($emotion_list);
- $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
- $data['emotion_type'] = $emotion_type;
- $segmentData['emotion_type'] = $emotion_type;
- }
- }
- }
- return $segmentData;
- }
- public function createSegmentVideoTask($data) {
- $segment_id = getProp($data, 'segment_id');
- $tail_frame = getProp($data, 'tail_frame');
- $first_frame_url = getProp($data, 'first_frame_url');
- $tail_frame_url = getProp($data, 'tail_frame_url');
- $generate_audio = getProp($data, 'generate_audio', 0);
-
- if (!$segment_id) {
- Utils::throwError('1002:分镜ID不能为空');
- }
-
- // 获取分镜信息
- $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
- if (!$segment) {
- Utils::throwError('20003:分镜不存在');
- }
-
- $segment = (array)$segment;
- $episode_id = getProp($segment, 'episode_id');
- $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
- if (!$ratio) $ratio = '9:16';
-
- // 获取分镜内容
- $segmentContent = getProp($segment, 'segment_content', '');
-
- // 检查 $segmentContent 中是否已有尾帧描述
- $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
-
- // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
- $finalTailFrame = '';
- if ($tail_frame) {
- // 用户输入了尾帧描述,优先使用
- $finalTailFrame = $tail_frame;
-
- // 如果 segmentContent 中已有尾帧描述,需要替换
- if ($contentHasTailFrame) {
- $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
- }
- } elseif ($contentHasTailFrame) {
- // segmentContent 中有尾帧描述,使用它
- $finalTailFrame = trim($contentTailFrameMatch[1]);
- } else {
- // 两者都没有,使用分镜表中的尾帧描述
- $finalTailFrame = getProp($segment, 'tail_frame', '');
- }
-
- // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
- $hasDialogue = false;
- if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
- $dialogue = trim($dialogueMatch[1]);
-
- // 如果台词不为空且不是"无"
- if (!empty($dialogue) && $dialogue !== '无') {
- // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
- $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
- if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
- $hasDialogue = true;
- }
- $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
- $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
- // 句首或句尾没有中文双引号,则分别添加中文左右双引号
- if (!preg_match('/^[“]/', $dialogue)) {
- $dialogue = '“' . $dialogue;
- }
- if (!preg_match('/[”]$/', $dialogue)) {
- $dialogue .= '”';
- }
-
- // 将修改后的台词替换回 $segmentContent
- $originalDialogue = $dialogueMatch[1];
- $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
- }
- }
- // 构建完整的提示词
- $fullPrompt = $segmentContent;
- if ($finalTailFrame && !$contentHasTailFrame) {
- // 只有当 segmentContent 中没有尾帧描述时才追加
- $fullPrompt .= "\n尾帧描述:$finalTailFrame";
- }
-
- // 去除多余的换行符(将连续多个换行符替换为单个换行符)
- $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
- $fullPrompt = trim($fullPrompt);
- // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
- $current_generate_audio = $hasDialogue ? $generate_audio : 0;
-
- // 智能选择视频时长
- // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
- $videoDuration = -1;
-
- // 处理视频模型
- $model = getProp($data, 'model');
- if (!$model) {
- // 用户没有输入,从episode表获取
- $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
- $model = getProp($episode, 'video_model');
- if (!$model) {
- // episode表也没有,使用默认值
- $model = 'doubao-seedance-1-5-pro-251215';
- }
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'doubao-seedance-1-5-pro-251215';
- }
- // 保存到episode表
- $episode_id = getProp($segment, 'episode_id');
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'video_model' => $model,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 构建视频生成参数
- $videoParams = [
- 'model' => $model,
- 'alias_segment_id' => $segment_id,
- 'prompt' => trim($fullPrompt),
- 'video_duration' => $videoDuration,
- 'video_resolution' => '720P',
- 'seed' => -1,
- 'ratio' => $ratio,
- 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
- 'draft' => false,
- 'watermark' => false,
- 'camera_fixed' => false,
- // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
- ];
-
- // 如果分镜有图片,作为首帧
- $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
- $hasVideo = !empty(getProp($segment, 'video_url'));
-
- if ($hasImage) {
- if ($first_frame_url) {
- $videoParams['first_frame_url'] = $first_frame_url;
- }else {
- $videoParams['first_frame_url'] = getProp($segment, 'img_url');
- }
- if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
- }
-
- // 构建content数组
- $videoParams['content'] = [
- [
- 'type' => 'text',
- 'text' => $videoParams['prompt'],
- ]
- ];
-
- // 如果有首帧图片,添加到content中
- if ($hasImage) {
- if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'reference_image',
- ];
- if (isset($videoParams['tail_frame_url'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['tail_frame_url'],
- ],
- 'role' => 'reference_image',
- ];
- }
- }else {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'first_frame',
- ];
- if (isset($videoParams['tail_frame_url'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['tail_frame_url'],
- ],
- 'role' => 'last_frame',
- ];
- }
- }
- }
-
- // 获取配音音频URL
- $audioUrl = getProp($segment, 'audio_url');
- $audioDuration = getProp($segment, 'audio_duration');
-
- // 音频传入的前提:必须有至少一张图片或一个视频
- $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
- // dd($videoParams);
-
- // 根据模型选择不同的视频生成方法
- if (strpos($model, 'jimeng') !== false) {
- // 即梦模型参数调整
- $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
- unset($videoParams['content']); // 即梦不使用content格式
- $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
- } elseif (strpos($model, 'kling') !== false) {
- // Keling模型参数调整
- $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
- $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
- unset($videoParams['ratio']);
- unset($videoParams['content']); // Keling不使用content格式
- $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
- } elseif (strpos($model, 'zhizhen') !== false) {
- // 智帧20等新模型使用统一API
- // 构建统一API参数
- $unifiedParams = [
- 'model_code' => $model,
- 'alias_segment_id' => $segment_id,
- 'prompt' => trim($fullPrompt),
- 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
- 'video_resolution' => strtolower($videoParams['video_resolution']),
- 'video_ratio' => $ratio,
- 'seed' => -1,
- ];
-
- // 构建parameters参数
- $parameters = [
- 'seconds' => $unifiedParams['video_duration'],
- 'resolution' => $unifiedParams['video_resolution'],
- 'ratio' => $ratio,
- // 'video_mode' => 'multi_image',
- // 'mode' => 'multi_image',
- 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
- ];
-
- $hasImage = false;
- // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
- if ($hasImage) {
- $parameters['first_frame_url'] = $videoParams['first_frame_url'];
- if (isset($videoParams['tail_frame_url'])) {
- $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
- }
-
- // 只有在有图片的情况下才能添加参考音频
- if ($audioUrl) {
- // $parameters['reference_audios'] = [$audioUrl];
- }
- } else {
- // 没有图片时,记录错误日志
- logDB('anime', 'error', '智帧20模型缺少首帧图片', [
- 'segment_id' => $segment_id,
- 'model' => $model
- ]);
- }
-
- $unifiedParams['parameters'] = $parameters;
-
- // 调用统一API创建任务
- $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
- } else {
- // Seedance模型(默认)
- // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
- if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
- // 添加配音音频到content中
- $videoParams['content'][] = [
- 'type' => 'audio_url',
- 'audio_url' => [
- 'url' => $audioUrl,
- ],
- 'role' => 'reference_audio',
- ];
-
- // 优化提示词,增加音频相关描述
- $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
- $videoParams['prompt'] = $audioPrompt;
- $videoParams['content'][0]['text'] = $audioPrompt;
- } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
- $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
- }
- $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
- }
-
- // 更新分镜表的视频任务信息
- DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
- 'video_task_id' => $task->id,
- 'video_task_status' => '生成中',
- 'generate_audio' => $generate_audio,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- return [
- 'task_id' => $task->id,
- 'status' => $task->status,
- 'segment_id' => $segment_id,
- 'video_duration' => $videoDuration
- ];
- }
-
- public function createActVideoTask($data) {
- $act_id = getProp($data, 'act_id');
- $first_frame_url = getProp($data, 'first_frame_url');
- $tail_frame_url = getProp($data, 'tail_frame_url');
- $generate_audio = getProp($data, 'generate_audio', 1);
- $video_duration = getProp($data, 'video_duration');
- $video_resolution = getProp($data, 'video_resolution');
- $ratio = getProp($data, 'ratio');
- $products = getProp($data, 'products', []);
- $reference_images = array_unique(getProp($data, 'reference_images', []));
- if (!is_array($reference_images) || !is_array($products)) {
- Utils::throwError('20003:传入的参考图或资产格式不正确');
- }
-
- if (!$act_id) {
- Utils::throwError('1002:片段ID不能为空');
- }
-
- // 获取片段信息
- $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
- if (!$act) {
- Utils::throwError('20003:片段不存在');
- }
-
- $act = (array)$act;
- $anime_id = getProp($act, 'anime_id');
- $episode_id = getProp($act, 'episode_id');
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- $ace_mode = getProp($anime, 'ace_mode');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
- if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
- // 将资产中新出现的资产放到extra_products中
- // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles和scenes做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
- if (!empty($products) && $episode) {
- // 获取剧集中的角色和场景列表
- $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
- $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
- $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
-
- // 构建角色名称列表
- $role_names = array_column($roles, 'role');
- // 构建场景名称列表
- $scene_names = array_column($scenes, 'scene');
-
- // 遍历传入的products
- foreach ($products as $product) {
- $product_name = getProp($product, 'product_name');
-
- // 如果product_name不在roles和scenes中
- if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names)) {
- // 查找是否在extra_products中存在同名的
- $found = false;
- foreach ($extra_products as $key => $extra_product) {
- if (getProp($extra_product, 'product_name') === $product_name) {
- // 有同名的则覆盖
- $extra_products[$key] = $product;
- $found = true;
- break;
- }
- }
-
- // 没有则新增
- if (!$found) {
- $extra_products[] = $product;
- }
- }
- }
-
- if ($extra_products) {
- // 保存到数据库
- DB::table('mp_anime_episodes')
- ->where('id', $episode_id)
- ->update([
- 'extra_products' => json_encode($extra_products, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
-
- }
-
- // 获取分镜内容
- $actContent = getProp($act, 'act_show_content', '');
- // 音效同出(默认使用)
- $current_generate_audio = $generate_audio ? 1 : 0;
- // 构建完整的提示词
- $processResult = $this->processActContentWithProducts($actContent, $products);
- $fullPrompt = $processResult['content'];
- $reference_images = array_merge($processResult['reference_images'], $reference_images);
-
- $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
-
- // 处理视频模型
- $model = getProp($data, 'model');
- if (!$model) {
- $model = getProp($episode, 'video_model');
- if (!$model) {
- // episode表也没有,使用默认值
- $model = 'zhizhen-20-mini';
- }
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'zhizhen-20-mini';
- }
- // 保存到episode表
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'video_model' => $model,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 构建视频生成参数
- $videoParams = [
- 'model' => $model,
- 'alias_act_id' => $act_id,
- 'prompt' => trim($fullPrompt),
- 'video_duration' => $videoDuration,
- 'video_resolution' => $video_resolution,
- 'seed' => -1,
- 'ratio' => $ratio,
- 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
- 'draft' => false,
- 'watermark' => false,
- 'camera_fixed' => false,
- // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
- ];
-
- // 如果分镜有图片,作为首帧
- $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
- $hasVideo = !empty(getProp($act, 'video_url'));
-
- if ($hasImage) {
- if ($first_frame_url) {
- $videoParams['first_frame_url'] = $first_frame_url;
- }else {
- $videoParams['first_frame_url'] = getProp($act, 'img_url');
- }
- if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
- }
-
- // 构建content数组
- $videoParams['content'] = [
- [
- 'type' => 'text',
- 'text' => $videoParams['prompt'],
- ]
- ];
-
- // 如果有首帧图片,添加到content中
- if ($hasImage) {
- if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'reference_image',
- ];
- if (isset($videoParams['tail_frame_url'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['tail_frame_url'],
- ],
- 'role' => 'reference_image',
- ];
- }
- }else {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['first_frame_url'],
- ],
- 'role' => 'first_frame',
- ];
- if (isset($videoParams['tail_frame_url'])) {
- $videoParams['content'][] = [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $videoParams['tail_frame_url'],
- ],
- 'role' => 'last_frame',
- ];
- }
- }
- }
- // dd($videoParams);
-
- // 根据模型选择不同的视频生成方法
- if (strpos($model, 'jimeng') !== false) {
- // 即梦模型参数调整
- unset($videoParams['content']); // 即梦不使用content格式
- $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
- } elseif (strpos($model, 'kling') !== false) {
- // Keling模型参数调整
- $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
- unset($videoParams['ratio']);
- unset($videoParams['content']); // Keling不使用content格式
- $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
- } elseif (strpos($model, 'zhizhen') !== false) {
- // 智帧20等新模型使用统一API
- // 构建统一API参数
- $unifiedParams = [
- 'model_code' => $model,
- 'alias_act_id' => $act_id,
- 'prompt' => trim($fullPrompt),
- 'video_duration' => $videoDuration,
- 'video_resolution' => strtolower($videoParams['video_resolution']),
- 'video_ratio' => $ratio,
- 'seed' => -1,
- ];
-
- // 构建parameters参数
- $parameters = [
- 'seconds' => $unifiedParams['video_duration'],
- 'resolution' => $unifiedParams['video_resolution'],
- 'ratio' => $ratio,
- // 'video_mode' => 'multi_image',
- // 'mode' => 'multi_image',
- 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
- ];
-
- $hasImage = false;
- // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
- if ($hasImage) {
- $parameters['first_frame_url'] = $videoParams['first_frame_url'];
- if (isset($videoParams['tail_frame_url'])) {
- $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
- }
- } else {
- // 没有图片时,记录错误日志
- logDB('anime', 'error', '智帧20模型缺少首帧图片', [
- 'act_id' => $act_id,
- 'model' => $model
- ]);
- }
- if ($reference_images) {
- // 限制只传入9张参考图
- $reference_images = array_slice($reference_images, 0, 9);
- // 在处理之前先保存原始reference_images到任务参数中
- $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
- $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
- $parameters['reference_images'] = $reference_images;
- $parameters['video_mode'] = 'multi_image';
- $parameters['mode'] = 'multi_image';
- }
-
- $unifiedParams['parameters'] = $parameters;
-
- // 调用统一API创建任务
- $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
- } else {
- $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
- }
-
- // 更新分镜表的视频任务信息
- DB::table('mp_episode_segments')->where('id', $act_id)->update([
- 'video_task_id' => $task->id,
- 'video_task_status' => '生成中',
- 'generate_audio' => $generate_audio,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
- $episode_number = getProp($act, 'episode_number');
- $act_number = getProp($act, 'act_number');
- if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
- Redis::sadd('anime_act_first_frame_urls', $act_id);
- }
-
- return [
- 'task_id' => $task->id,
- 'status' => $task->status,
- 'act_id' => $act_id,
- 'video_duration' => $videoDuration
- ];
- }
- /**
- * 根据提示词内容智能计算最优视频时长
- *
- * @param string $segmentContent 分镜内容
- * @param string $tailFrame 尾帧描述
- * @return int 视频时长(2-12秒)
- */
- public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
- // 合并所有文本内容
- $fullText = trim($segmentContent . ' ' . $tailFrame);
-
- // 如果没有内容,返回默认时长
- if (empty($fullText)) {
- return 5;
- }
-
- // 计算文本长度(中文字符按2个字符计算)
- $textLength = mb_strlen($fullText, 'UTF-8');
- $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
- $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
-
- // 分析内容复杂度
- $complexityScore = $this->analyzeContentComplexity($fullText);
-
- // 基础时长计算(根据文本长度)
- $baseDuration = 3; // 默认2秒
-
- // if ($adjustedLength <= 20) {
- // $baseDuration = 3;
- // } elseif ($adjustedLength <= 40) {
- // $baseDuration = 4;
- // } elseif ($adjustedLength <= 60) {
- // $baseDuration = 5;
- // } elseif ($adjustedLength <= 80) {
- // $baseDuration = 6;
- // } elseif ($adjustedLength <= 100) {
- // $baseDuration = 7;
- // } elseif ($adjustedLength <= 120) {
- // $baseDuration = 8;
- // } else {
- // $baseDuration = 9;
- // }
-
- // 根据内容复杂度调整时长
- $finalDuration = $baseDuration + $complexityScore;
-
- // 确保时长在2-12秒范围内
- return max(4, min(12, $finalDuration));
- }
- /**
- * 分析内容复杂度,返回时长调整值
- *
- * @param string $text 文本内容
- * @return int 调整值(-2到+3)
- */
- private function analyzeContentComplexity($text) {
- $score = 0;
-
- // 动作关键词(需要更长时间展现)
- $actionKeywords = [
- '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
- '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
- '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
- ];
-
- // 静态关键词(可以用较短时间)
- $staticKeywords = [
- '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
- '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
- ];
-
- // 复杂场景关键词(需要更长时间)
- $complexSceneKeywords = [
- '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
- '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
- ];
-
- // 情感关键词(需要适中时间表现)
- $emotionKeywords = [
- '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
- '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
- ];
-
- // 检查动作关键词
- foreach ($actionKeywords as $keyword) {
- if (strpos($text, $keyword) !== false) {
- $score += 1;
- break; // 避免重复加分
- }
- }
-
- // 检查静态关键词
- foreach ($staticKeywords as $keyword) {
- if (strpos($text, $keyword) !== false) {
- $score -= 1;
- break;
- }
- }
-
- // 检查复杂场景关键词
- foreach ($complexSceneKeywords as $keyword) {
- if (strpos($text, $keyword) !== false) {
- $score += 1;
- break;
- }
- }
-
- // 检查情感关键词
- foreach ($emotionKeywords as $keyword) {
- if (strpos($text, $keyword) !== false) {
- $score += 1;
- break;
- }
- }
-
- // 检查时间相关词汇
- if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
- $score += 1;
- }
-
- if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
- $score -= 1;
- }
-
- // 检查转场词汇
- if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
- $score += 1;
- }
-
- // 检查环境描述(复杂环境需要更多时间)
- if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
- $score += 1;
- }
-
- // 检查对话内容(对话需要更多时间)
- if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
- $score += 1;
- }
-
- // 限制调整范围
- return max(-1, min(4, $score));
- }
- /**
- * 创建完整视频合成任务
- *
- * @param array $data
- * @return array
- */
- public function createCompleteVideoTask($data)
- {
- $animeId = getProp($data, 'anime_id');
- $episodeId = getProp($data, 'episode_id');
- // 验证参数
- if (!$animeId || !$episodeId) {
- Utils::throwError('20003:anime_id 和 episode_id 不能为空');
- }
- // 检查是否已存在处理中的任务
- $existingTask = DB::table('mp_complete_video_tasks')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->whereIn('generate_status', ['执行中'])
- ->first();
- if ($existingTask) {
- Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
- }
- // 获取全能模式状态
- $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
- if ((int)$ace_mode === 1) {
- // 获取所有片段的配音视频,按 act_number 排序
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->orderBy('segment_number')
- ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
- ->get();
-
- // 检查是否所有片段都有视频
- $missingVideos = $segments->filter(function($segment) {
- return empty($segment->video_url);
- });
- if ($missingVideos->isNotEmpty()) {
- Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
- }
- }else {
- // 获取所有分镜的配音视频,按 segment_number 排序
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episodeId)
- ->orderBy('segment_number')
- ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
- ->get();
- // 检查是否所有分镜都有配音和视频
- $missingVideos = $segments->filter(function($segment) {
- return empty($segment->audio_url) || empty($segment->video_url);
- });
- if ($missingVideos->isNotEmpty()) {
- Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
- }
- }
- if ($segments->isEmpty()) {
- Utils::throwError('20003:未找到该剧集的分镜数据');
- }
- // 获取当前完整视频url
- $completeVideoUrl = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->value('complete_video_url');
- // 构建 generate_json
- $generateJson = [];
- $sequence = 1;
- foreach ($segments as $segment) {
- if ((int)$ace_mode === 1) {
- $generateJson[] = [
- 'sequence' => $sequence++,
- 'video_url' => $segment->video_url,
- 'video_time_point_start' => $segment->video_time_point_start,
- 'video_time_point_end' => $segment->video_time_point_end
- ];
- }else {
- $generateJson[] = [
- 'sequence' => $sequence++,
- 'video_url' => $segment->video_url,
- 'audio_url' => $segment->audio_url,
- 'video_time_point_start' => $segment->video_time_point_start,
- 'video_time_point_end' => $segment->video_time_point_end
- ];
- }
- }
- // 创建任务
- $now = date('Y-m-d H:i:s');
- $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'generate_json' => json_encode($generateJson, 256),
- 'generate_status' => '执行中',
- 'complete_video_url' => '',
- 'created_at' => $now,
- 'updated_at' => $now
- ]);
- if (!$taskId) {
- Utils::throwError('20003:创建任务失败');
- }
- // 更新剧集表的任务ID和状态
- $boolen = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->update([
- 'complete_video_task_id' => $taskId,
- 'complete_video_task_status' => '执行中',
- 'updated_at' => $now
- ]);
- if (!$boolen) {
- Utils::throwError('20003:更新剧集表失败');
- }
- dLog('anime')->info('创建完整视频合成任务', [
- 'task_id' => $taskId,
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'segment_count' => count($generateJson)
- ]);
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 600, 'verify' => false]);
- try {
- $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
-
- // // 更新任务状态为失败
- // DB::table('mp_complete_video_tasks')
- // ->where('id', $taskId)
- // ->update([
- // 'generate_status' => '执行失败',
- // 'error_message' => $error_msg,
- // 'updated_at' => date('Y-m-d H:i:s')
- // ]);
-
- // // 同步更新剧集表状态
- // DB::table('mp_anime_episodes')
- // ->where('complete_video_task_id', $taskId)
- // ->update([
- // 'complete_video_task_status' => '执行失败',
- // 'updated_at' => date('Y-m-d H:i:s')
- // ]);
-
- Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
-
- // 更新任务状态为失败
- DB::table('mp_complete_video_tasks')
- ->where('id', $taskId)
- ->update([
- 'generate_status' => '执行失败',
- 'error_message' => $e->getMessage(),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 同步更新剧集表状态
- DB::table('mp_anime_episodes')
- ->where('complete_video_task_id', $taskId)
- ->update([
- 'complete_video_task_status' => '执行失败',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
- }
- // 开始轮询任务状态
- $maxAttempts = 60; // 5分钟 = 60次 * 5秒
- $pollInterval = 5; // 每5秒轮询一次
- $attempt = 0;
- dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
- while ($attempt < $maxAttempts) {
- sleep($pollInterval);
- $attempt++;
- // 查询任务状态
- $task = DB::table('mp_complete_video_tasks')
- ->where('id', $taskId)
- ->first();
- if (!$task) {
- dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
- Utils::throwError('20003:任务不存在');
- }
- dLog('anime')->info('轮询任务状态', [
- 'task_id' => $taskId,
- 'attempt' => $attempt,
- 'status' => $task->generate_status
- ]);
- // 检查任务是否完成
- if ($task->generate_status === '执行成功') {
- // 同步更新剧集表状态
- $boolen3 = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->update([
- 'complete_video_url' => $task->complete_video_url,
- 'complete_video_task_status' => '执行成功',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- dLog('anime')->info('视频合成任务完成', [
- 'task_id' => $taskId,
- 'video_url' => $task->complete_video_url,
- 'attempts' => $attempt
- ]);
- // 如果更新成功则远程删除之前的文件
- if ($boolen3 && $completeVideoUrl) {
- $encode_url = urlencode($completeVideoUrl);
- $client = new Client(['timeout' => 300, 'verify' => false]);
- // 根据ID通过API通知合成音频
- // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
- $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
- Log::info('火山删除音频返回: '.$response);
- if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- Log::info('火山删除音频失败: '.$error_msg);
- // Utils::throwError('20003:火山删除音频失败');
- }
- }
- return [
- 'task_id' => $taskId,
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'segment_count' => count($generateJson),
- 'generate_status' => '执行成功',
- 'complete_video_url' => $task->complete_video_url,
- ];
- }
- // 检查任务是否失败
- if ($task->generate_status === '执行失败') {
- // 同步更新剧集表状态
- DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('id', $episodeId)
- ->update([
- 'complete_video_task_status' => '执行失败',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- $errorMessage = $task->error_message ?? '未知错误';
- dLog('anime')->error('视频合成任务失败', [
- 'task_id' => $taskId,
- 'error' => $errorMessage,
- 'attempts' => $attempt
- ]);
- return [
- 'task_id' => $taskId,
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'segment_count' => count($generateJson),
- 'generate_status' => '执行失败',
- 'error_message' => $errorMessage
- ];
- }
- }
- // 超时处理
- dLog('anime')->warning('视频合成任务超时', [
- 'task_id' => $taskId,
- 'max_attempts' => $maxAttempts,
- 'timeout_seconds' => $maxAttempts * $pollInterval
- ]);
- // 更新任务状态为超时
- DB::table('mp_complete_video_tasks')
- ->where('id', $taskId)
- ->update([
- 'generate_status' => '超时',
- 'error_message' => '任务执行超时(5分钟)',
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- return [
- 'task_id' => $taskId,
- 'anime_id' => $animeId,
- 'episode_id' => $episodeId,
- 'segment_count' => count($generateJson),
- 'generate_status' => '超时',
- 'error_message' => '任务执行超时,请稍后查询任务状态'
- ];
- }
- public function generateImg($data) {
- $prompt = getProp($data, 'prompt');
- $episode_id = getProp($data, 'episode_id');
- $ref_img_urls = getProp($data, 'ref_img_urls');
- $ratio = getProp($data, 'ratio', '9:16');
- $resolution = getProp($data, 'resolution', '2k');
-
- // 定义分辨率和宽高比对应的尺寸映射表
- $sizeMap = [
- '2k' => [
- '1:1' => ['width' => 2048, 'height' => 2048],
- '4:3' => ['width' => 2304, 'height' => 1728],
- '3:4' => ['width' => 1728, 'height' => 2304],
- '16:9' => ['width' => 2848, 'height' => 1600],
- '9:16' => ['width' => 1600, 'height' => 2848],
- '3:2' => ['width' => 2496, 'height' => 1664],
- '2:3' => ['width' => 1664, 'height' => 2496],
- '21:9' => ['width' => 3136, 'height' => 1344],
- ],
- '3k' => [
- '1:1' => ['width' => 3072, 'height' => 3072],
- '4:3' => ['width' => 3456, 'height' => 2592],
- '3:4' => ['width' => 2592, 'height' => 3456],
- '16:9' => ['width' => 4096, 'height' => 2304],
- '9:16' => ['width' => 2304, 'height' => 4096],
- '2:3' => ['width' => 2496, 'height' => 3744],
- '3:2' => ['width' => 3744, 'height' => 2496],
- '21:9' => ['width' => 4704, 'height' => 2016],
- ],
- '4k' => [
- '1:1' => ['width' => 4096, 'height' => 4096],
- '3:4' => ['width' => 3520, 'height' => 4704],
- '4:3' => ['width' => 4704, 'height' => 3520],
- '16:9' => ['width' => 5504, 'height' => 3040],
- '9:16' => ['width' => 3040, 'height' => 5504],
- '2:3' => ['width' => 3328, 'height' => 4992],
- '3:2' => ['width' => 4992, 'height' => 3328],
- '21:9' => ['width' => 6240, 'height' => 2656],
- ],
- ];
-
- // 参数验证
- $resolution = strtolower($resolution);
- if (!isset($sizeMap[$resolution])) {
- Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
- }
-
- if (!isset($sizeMap[$resolution][$ratio])) {
- Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
- }
-
- // 根据 ratio 和 resolution 确定宽高
- $width = $sizeMap[$resolution][$ratio]['width'];
- $height = $sizeMap[$resolution][$ratio]['height'];
-
- if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
- if (is_json($ref_img_urls)) {
- $ref_img_urls = json_decode($ref_img_urls, true);
- }else {
- $ref_img_urls = explode(',', $ref_img_urls);
- }
- }
- // 处理图片模型
- $model = getProp($data, 'model');
- if (!$model) {
- // 用户没有输入,从episode表获取
- if ($episode_id) {
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- $model = getProp($episode, 'image_model');
- }
- if (!$model) {
- // episode表也没有,使用默认值
- $model = 'doubao-seedream-5-0-lite-260128';
- }
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- // $model = 'doubao-seedream-5-0-lite-260128';
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
- // 保存到episode表
- if ($episode_id) {
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'image_model' => $model,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- // 参数验证
- if (!$prompt) Utils::throwError('20003:请提供提示词');
- try {
- // 创建图片生成任务
- $params = [
- 'prompt' => $prompt,
- 'model' => $model,
- 'ref_img_urls' => '',
- 'width' => $width,
- 'height' => $height
- ];
- if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError('20003:创建图片生成任务失败');
- }
-
- // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
- $model = getProp($task, 'model');
- $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
- $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
- $isSyncModel = $isVolcModel || $isGptModel;
- // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
- $start_time = time();
- $timeout = 300; // 5分钟
- $img_url = '';
-
- while (time() - $start_time < $timeout) {
- sleep(3);
- // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
- if ($isSyncModel) {
- // 刷新任务状态
- $task = MpGeneratePicTask::where('id', $task_id)->first();
-
- if ($task->status === 'success' && $task->result_url) {
- $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
- $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
- break;
- } elseif ($task->status === 'failed') {
- $errorMsg = mapErrorMessage($task->error_message ?? '');
- Utils::throwError('20003:图片生成失败,' . $errorMsg);
- }
-
- // // 如果还在处理中,提示用户稍后查看
- // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
- }else {
- $task = MpGeneratePicTask::where('id', $task_id)->first();
- $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
-
- if ($statusInfo['status'] === 'success') {
- $task->updateStatus('success', [
- 'result_url' => $statusInfo['result_url'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
-
- $img_url = $statusInfo['result_url'][0];
- break;
- } elseif ($statusInfo['status'] === 'failed') {
- $task->updateStatus('failed', [
- 'error_message' => $statusInfo['error_message'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
- dLog('anime')->error('图片生成失败,', [
- 'error' => $statusInfo['error_message'] ?? '未知错误'
- ]);
- $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
- Utils::throwError('20003:图片生成失败,' . $errorMsg);
- }
- }
- }
-
- if (empty($img_url)) {
- Utils::throwError('20003:图片生成超时,请稍后重试');
- }
-
- return $img_url;
-
- } catch (\Exception $e) {
- dLog('anime')->error('更新角色或场景失败', [
- 'error' => $e->getMessage()
- ]);
- logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
-
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- /**
- * 使用文生文模型解析分镜内容
- */
- private function parseSegmentContentWithAI($segment_content) {
- try {
- // 使用DeepSeek服务的公开方法解析分镜内容
- return $this->DeepSeekService->parseSegmentContent($segment_content);
- } catch (\Exception $e) {
- // 如果AI解析失败,记录日志并返回原内容
- dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
- return $segment_content;
- }
- }
- /**
- * 处理分集的角色和场景数据(继承全局数据或创建新任务)
- *
- * @param int $episode_id 分集ID
- * @param int $anime_id 动漫ID
- * @param array $roles 分集角色数组(引用传递)
- * @param array $scenes 分集场景数组(引用传递)
- * @param array $episode 分集数据
- */
- private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
- // 获取全局动漫的角色和场景数据
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
- if (!$anime) return;
- $art_style_type = getProp($anime, 'art_style_type');
- $character_prefix = '';
- $scene_prefix = '';
- if ($art_style_type) {
- $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
- $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
- $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
- }
-
- $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
- $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
-
- $roles_updated = false;
- $scenes_updated = false;
-
- // 处理角色
- foreach ($roles as &$role) {
- $role_name = getProp($role, 'role');
- $role_description = getProp($role, 'description');
- $role_pic_prompt = getProp($role, 'pic_prompt');
- $role_url = getProp($role, 'url');
- $role_task_id = getProp($role, 'task_id');
-
- // 如果已有URL或已有任务ID,跳过
- if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
- continue;
- }
-
- $url_inherited = false;
-
- // 尝试从全局数据中继承
- foreach ($global_roles as $global_role) {
- $global_role_name = getProp($global_role, 'role');
- $global_role_description = getProp($global_role, 'description');
- $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
- $global_role_url = getProp($global_role, 'url');
- $global_role_task_id = getProp($global_role, 'task_id');
- $global_role_task_status = getProp($global_role, 'task_status');
-
- // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
- if ($role_name === $global_role_name
- && $role_description === $global_role_description
- && $role_pic_prompt === $global_role_pic_prompt
- && !empty($global_role_url)) {
- // 继承 task_id、task_status 和 url
- $role['task_id'] = $global_role_task_id;
- $role['task_status'] = $global_role_task_status;
- $role['url'] = $global_role_url;
- $roles_updated = true;
- $url_inherited = true;
- dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
- break;
- }
- }
-
- // 如果无法继承且没有任务ID,创建新任务
- if (!$url_inherited && empty($role_task_id)) {
- try {
- $art_style = getProp($episode, 'art_style');
-
- // 优先使用 pic_prompt,如果没有则使用 description
- $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
-
- // if ($art_style) {
- // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
- // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
- // }
- $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
-
- $params = [
- 'prompt' => $description,
- 'ref_img_urls' => []
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if ($task_id) {
- $role['task_id'] = $task_id;
- $role['task_status'] = 'processing';
- $roles_updated = true;
- dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
- }
- } catch (\Exception $e) {
- dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
- }
- }
- }
-
- // 处理场景
- foreach ($scenes as &$scene) {
- $scene_name = getProp($scene, 'scene');
- $scene_description = getProp($scene, 'description');
- $scene_pic_prompt = getProp($scene, 'pic_prompt');
- $scene_url = getProp($scene, 'url');
- $scene_task_id = getProp($scene, 'task_id');
-
- // 如果已有URL或已有任务ID,跳过
- if (!empty($scene_url) || !empty($scene_task_id)) {
- continue;
- }
-
- $url_inherited = false;
-
- // 尝试从全局数据中继承
- foreach ($global_scenes as $global_scene) {
- $global_scene_name = getProp($global_scene, 'scene');
- $global_scene_description = getProp($global_scene, 'description');
- $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
- $global_scene_url = getProp($global_scene, 'url');
- $global_scene_task_id = getProp($global_scene, 'task_id');
- $global_scene_task_status = getProp($global_scene, 'task_status');
-
- // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
- if ($scene_name === $global_scene_name
- && $scene_description === $global_scene_description
- && $scene_pic_prompt === $global_scene_pic_prompt
- && !empty($global_scene_url)) {
- // 继承 task_id、task_status 和 url
- $scene['task_id'] = $global_scene_task_id;
- $scene['task_status'] = $global_scene_task_status;
- $scene['url'] = $global_scene_url;
- $scenes_updated = true;
- $url_inherited = true;
- dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
- break;
- }
- }
-
- // 如果无法继承且没有任务ID,创建新任务
- if (!$url_inherited && empty($scene_task_id)) {
- try {
- $art_style = getProp($episode, 'art_style');
-
- // 优先使用 pic_prompt,如果没有则使用 description
- $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
-
- // if ($art_style) {
- // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
- // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
- // }
- $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
-
- $params = [
- 'prompt' => $description,
- 'ref_img_urls' => []
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if ($task_id) {
- $scene['task_id'] = $task_id;
- $scene['task_status'] = 'processing';
- $scenes_updated = true;
- dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
- }
- } catch (\Exception $e) {
- dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
- }
- }
- }
-
- // 如果有更新,保存到数据库
- if ($roles_updated || $scenes_updated) {
- $update_data = ['updated_at' => date('Y-m-d H:i:s')];
-
- if ($roles_updated) {
- $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
- }
-
- if ($scenes_updated) {
- $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
- }
-
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
- dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
- }
- }
- /**
- * 根据图片URL使用AI反推图片提示词
- *
- * @param string $img_url 图片URL
- * @return string 反推的提示词
- */
- private function generateImagePromptFromUrl($img_url) {
- try {
- // 获取默认模型
- $model = 'doubao-seed-2-0-mini-260215';
-
- // 构建messages参数
- $messages = [
- [
- 'role' => 'user',
- 'content' => [
- [
- 'type' => 'text',
- 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
- ],
- [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $img_url
- ]
- ]
- ]
- ]
- ];
-
- // 构建请求参数
- $params = [
- 'model' => $model,
- 'messages' => $messages,
- 'stream' => false,
- 'thinking' => ['type' => 'disabled'] // 不使用思考模式
- ];
-
- // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
- $result = $this->DeepSeekService->volcEngineChatCompletion($params);
-
- // 返回生成的内容
- return getProp($result, 'fullContent', '图片描述生成失败');
-
- } catch (\Exception $e) {
- dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
- 'img_url' => $img_url
- ]);
- logDB('anime', 'error', 'AI反推图片提示词失败', [
- 'error' => $e->getMessage(),
- 'img_url' => $img_url
- ]);
- return '图片描述生成失败: ' . $e->getMessage();
- }
- }
- /**
- * 音频试听接口
- * 创建音频任务并轮询获取结果
- *
- * @param array $data 参数数组
- * @return array 返回音频URL或错误信息
- */
- public function previewAudio($data) {
- $dialogue = getProp($data, 'dialogue');
-
- // 必填参数验证
- if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
-
- // 获取参数,优先使用传入的参数,否则使用分镜中的参数
- $voice_type = getProp($data, 'voice_type');
- $voice_name = getProp($data, 'voice_name');
- $voice_actor = getProp($data, 'voice_actor');
- $emotion_type = getProp($data, 'emotion_type');
- $gender = getProp($data, 'gender', 0);
- $emotion = getProp($data, 'emotion');
- $speed_ratio = getProp($data, 'speed_ratio', 0);
- $loudness_ratio = getProp($data, 'loudness_ratio', 0);
- $emotion_scale = getProp($data, 'emotion_scale', 0);
- $pitch = getProp($data, 'pitch', 0);
-
- try {
- $now = date('Y-m-d H:i:s');
-
- // 构建生成参数
- $generate_json = json_encode([
- 'text' => $dialogue,
- 'role' => $voice_actor,
- 'voice_type' => $voice_type,
- 'voice_name' => $voice_name,
- 'emotion' => $emotion,
- 'emotion_type' => $emotion_type,
- 'gender' => $gender,
- 'speed_ratio' => $speed_ratio,
- 'loudness_ratio' => $loudness_ratio,
- 'emotion_scale' => $emotion_scale,
- 'pitch' => $pitch,
- ], 256);
-
- // 请求远程服务器执行生成
- $client = new Client(['timeout' => 600, 'verify' => false]);
- $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
- $response = $result->getBody()->getContents();
- $response_arr = json_decode($response, true);
-
- if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
- $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
- dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
- Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
- }
- $arr = $response_arr['data'];
- $subtitle_info = $arr['subtitle_info'];
- $audio_duration = json_decode($subtitle_info, true)['duration'];
- if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
- return [
- 'audio_url' => $arr['url'],
- 'subtitle_info' => $subtitle_info,
- 'audio_duration' => round($audio_duration, 2)
- ];
-
- } catch (\Exception $e) {
- dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- /**
- * 获取角色库列表(支持文件夹递归查询)
- * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)
- * @return array 返回当前目录下的所有子目录和角色列表(递归)
- */
- public function globalProducts($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $id = getProp($data, 'id', 0);
- $parent_id = getProp($data, 'parent_id', 0);
- $product_name = getProp($data, 'product_name');
- $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
- if (!$product) {
- Utils::throwError('20003:请选择产品类型');
- }
-
- // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
- if ($id || $product_name) {
- $query = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('user_id', $uid)
- ->where('is_deleted', 0);
-
- // 如果指定了 id,按 id 精确查询
- if ($id) {
- $query->where('id', $id);
- }
-
- // 如果指定了 product_name,按名称模糊查询
- if ($product_name) {
- $query->where('product_name', 'like', "%{$product_name}%");
- }
-
- // 如果指定了 product,添加筛选条件
- if ($product) {
- $query->where('product', $product);
- }
-
- $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'created_at')
- ->orderByRaw('sort_order DESC, created_at DESC')
- ->get()
- ->map(function($value) {
- $value = (array)$value;
- $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
- $value['type'] = (int)$value['type'];
- $value['parent_id'] = (int)$value['parent_id'];
- $value['level'] = (int)$value['level'];
- $value['product'] = (int)($value['product'] ?? 1);
- $value['versions'] = json_decode($value['versions'], true) ?: [];
- return $value;
- })
- ->toArray();
-
- return $result;
- }
-
- // 递归获取所有子目录和角色
- return $this->getChildrenRecursive($cpid, $parent_id, $product, $uid);
- }
-
- /**
- * 递归获取指定目录下的所有子目录和角色
- * @param int $cpid 公司ID
- * @param int $parent_id 父目录ID
- * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
- * @param int $uid 用户ID
- * @return array
- */
- private function getChildrenRecursive($cpid, $parent_id, $product = null, $uid = null) {
- // 查询当前层级的所有项(文件夹和角色)
- $query = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('is_deleted', 0)
- ->where('parent_id', $parent_id);
-
- // 添加用户ID验证
- if ($uid) {
- $query->where('user_id', $uid);
- }
-
- // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
- if ($product) {
- $query->where('product', $product);
- }
-
- $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'created_at')
- ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
- ->get();
-
- $result = [];
-
- foreach ($items as $item) {
- $itemArray = [
- 'id' => $item->id,
- 'type' => (int)$item->type,
- 'parent_id' => (int)$item->parent_id,
- 'level' => (int)$item->level,
- 'product_name' => $item->product_name,
- 'url' => $item->url,
- 'pic_prompt' => $item->pic_prompt ?? '',
- 'three_view_image_url' => $item->three_view_image_url,
- 'product' => (int)($item->product ?? 1),
- 'created_at' => transDate($item->created_at, 'Y-m-d')
- ];
- $itemArray['versions'] = json_decode($item->versions, true) ?: [];
-
- // 如果是文件夹,递归获取其子项
- if ($item->type == 2) {
- $children = $this->getChildrenRecursive($cpid, $item->id, $product, $uid);
- if (!empty($children)) {
- $itemArray['children'] = $children;
- }
- }
-
- $result[] = $itemArray;
- }
-
- return $result;
- }
-
- /**
- * 创建文件夹
- * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
- * @return int 返回新建文件夹ID
- */
- public function createFolder($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $parent_id = getProp($data, 'parent_id', 0);
- $folder_name = getProp($data, 'product_name', '新建文件夹');
-
- // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
- $product = getProp($data, 'product');
- if (!in_array($product, [1, 2, 3])) {
- // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
- }
-
- // 验证父文件夹
- $parent_level = 0;
- if ($parent_id > 0) {
- $parent = DB::table('mp_products')
- ->where('id', $parent_id)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$parent) {
- Utils::throwError('20003:父文件夹不存在');
- }
-
- // 检查父文件夹的 product 类型是否一致
- if ($parent->product != $product) {
- Utils::throwError('20003:文件夹类型必须与父文件夹一致');
- }
-
- $parent_level = $parent->level;
-
- // 检查层级限制(最多3层)
- if ($parent_level >= 3) {
- Utils::throwError('20003:文件夹层级不能超过3层');
- }
- }
-
- // 检查当前目录下是否已存在空白文件夹
- $empty_folder_exists = DB::table('mp_products')
- ->where('parent_id', $parent_id)
- ->where('type', 2)
- ->where('product', $product)
- ->where('product_name', '新建文件夹')
- ->where('is_deleted', 0)
- ->exists();
-
- if ($empty_folder_exists && $folder_name == '新建文件夹') {
- Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
- }
-
- // 创建文件夹
- $folder_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 2,
- 'parent_id' => $parent_id,
- 'level' => $parent_level + 1,
- 'product_name' => $folder_name,
- 'product' => $product,
- 'sort_order' => time(), // 使用时间戳作为排序权重
- 'is_deleted' => 0,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- return [
- 'id' => $folder_id,
- 'type' => 2,
- 'parent_id' => $parent_id,
- 'level' => $parent_level + 1,
- 'product_name' => $folder_name,
- 'product' => $product,
- ];
- }
-
- /**
- * 重命名文件夹或角色
- * @param array $data 包含 id、product_name(新名称)
- * @return bool
- */
- public function renameFolder($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- $new_name = getProp($data, 'product_name');
-
- if (!$id || !$new_name) {
- Utils::throwError('20003:参数不完整');
- }
-
- // 检查是否存在
- $item = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$item) {
- Utils::throwError('20003:项目不存在');
- }
-
- return DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->update([
- 'product_name' => $new_name,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
-
- /**
- * 移动角色或文件夹到指定文件夹
- * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
- * @return bool
- */
- public function moveProductOrFolder($data) {
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- $target_parent_id = getProp($data, 'target_parent_id', 0);
-
- if (!$id) {
- Utils::throwError('20003:请选择要移动的项目');
- }
-
- // 检查要移动的项目
- $item = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$item) {
- Utils::throwError('20003:项目不存在');
- }
-
- // 验证目标文件夹
- $target_level = 0;
- $target_product = $item->product; // 默认使用当前项目的 product
-
- if ($target_parent_id > 0) {
- $target_parent = DB::table('mp_products')
- ->where('id', $target_parent_id)
- ->where('cpid', $cpid)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$target_parent) {
- Utils::throwError('20003:目标文件夹不存在');
- }
-
- // 检查 product 类型是否一致
- if ($target_parent->product != $item->product) {
- Utils::throwError('20003:不能移动到不同类型的文件夹下');
- }
-
- $target_level = $target_parent->level;
- $target_product = $target_parent->product;
-
- // 如果移动的是文件夹,需要检查层级
- if ($item->type == 2) {
- // 计算移动后的最大层级
- $max_child_level = $this->getMaxChildLevel($id);
- $depth = $max_child_level - $item->level;
-
- if ($target_level + 1 + $depth > 3) {
- Utils::throwError('20003:移动后文件夹层级将超过3层限制');
- }
-
- // 不能移动到自己或自己的子文件夹下
- if ($this->isDescendant($target_parent_id, $id)) {
- Utils::throwError('20003:不能移动到自己或子文件夹下');
- }
- }
- }
-
- // 更新父文件夹和层级
- $new_level = $target_level + 1;
- DB::table('mp_products')
- ->where('id', $id)
- ->update([
- 'parent_id' => $target_parent_id,
- 'level' => $new_level,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 如果是文件夹,需要递归更新所有子项的层级
- if ($item->type == 2) {
- $this->updateChildrenLevel($id, $new_level);
- }
-
- return true;
- }
-
- /**
- * 获取文件夹下最大子层级
- * @param int $folder_id
- * @return int
- */
- private function getMaxChildLevel($folder_id) {
- $max_level = DB::table('mp_products')
- ->where('parent_id', $folder_id)
- ->where('is_deleted', 0)
- ->max('level');
-
- if (!$max_level) {
- return DB::table('mp_products')->where('id', $folder_id)->value('level');
- }
-
- // 递归查找子文件夹
- $children = DB::table('mp_products')
- ->where('parent_id', $folder_id)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->pluck('id');
-
- foreach ($children as $child_id) {
- $child_max = $this->getMaxChildLevel($child_id);
- if ($child_max > $max_level) {
- $max_level = $child_max;
- }
- }
-
- return $max_level;
- }
-
- /**
- * 检查 target_id 是否是 folder_id 的后代
- * @param int $target_id
- * @param int $folder_id
- * @return bool
- */
- private function isDescendant($target_id, $folder_id) {
- if ($target_id == $folder_id) {
- return true;
- }
-
- $parent = DB::table('mp_products')
- ->where('id', $target_id)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$parent || $parent->parent_id == 0) {
- return false;
- }
-
- return $this->isDescendant($parent->parent_id, $folder_id);
- }
-
- /**
- * 递归更新子项层级
- * @param int $parent_id
- * @param int $parent_level
- */
- private function updateChildrenLevel($parent_id, $parent_level) {
- $children = DB::table('mp_products')
- ->where('parent_id', $parent_id)
- ->where('is_deleted', 0)
- ->get();
-
- foreach ($children as $child) {
- $new_level = $parent_level + 1;
- DB::table('mp_products')
- ->where('id', $child->id)
- ->update([
- 'level' => $new_level,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- // 如果是文件夹,继续递归
- if ($child->type == 2) {
- $this->updateChildrenLevel($child->id, $new_level);
- }
- }
- }
-
- /**
- * 获取文件夹路径(面包屑导航)
- * @param array $data 包含 folder_id
- * @return array 返回路径数组
- */
- public function getFolderPath($data) {
- $folder_id = getProp($data, 'id', 0);
-
- if ($folder_id == 0) {
- return [
- ['id' => 0, 'name' => '根目录']
- ];
- }
-
- $path = [];
- $current_id = $folder_id;
-
- while ($current_id > 0) {
- $folder = DB::table('mp_products')
- ->where('id', $current_id)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$folder) {
- break;
- }
-
- array_unshift($path, [
- 'id' => $folder->id,
- 'name' => $folder->product_name
- ]);
-
- $current_id = $folder->parent_id;
- }
-
- // 添加根目录
- array_unshift($path, ['id' => 0, 'name' => '根目录']);
-
- return $path;
- }
- public function createProduct($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $product_name = trim(getProp($data, 'product_name'));
- if (!$product_name) Utils::throwError('20003:名称不能为空');
- // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
- // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
- $url = trim(getProp($data, 'url'));
- if (!$url) Utils::throwError('20003:图片地址不能为空');
- $versions = getProp($data, 'versions');
-
- // 检查是否是正确的图片格式
- $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
- $urlPath = parse_url($url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- if (!in_array($extension, $allowedExtensions)) {
- Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
- }
- $pic_prompt = trim(getProp($data, 'pic_prompt'));
- if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
-
- // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
- $product = getProp($data, 'product');
- if (!in_array($product, [1, 2, 3])) {
- // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
- }
-
- // 获取父文件夹ID和层级
- $parent_id = getProp($data, 'parent_id', 0);
- $parent_level = 0;
-
- if ($parent_id > 0) {
- $parent = DB::table('mp_products')
- ->where('id', $parent_id)
- ->where('cpid', $cpid)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$parent) {
- Utils::throwError('20003:父文件夹不存在');
- }
-
- $parent_level = $parent->level;
- }
- $id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 1, // 1=角色图片
- 'parent_id' => $parent_id,
- 'level' => $parent_level + 1,
- 'product_name' => $product_name,
- 'url' => $url,
- 'pic_prompt' => $pic_prompt,
- 'product' => $product,
- 'versions' => json_encode($versions, 256),
- 'sort_order' => time(), // 使用时间戳作为排序权重
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$id) Utils::throwError('20003:创建失败');
- return [
- 'id' => $id,
- 'type' => 1,
- 'parent_id' => $parent_id,
- 'level' => $parent_level + 1,
- 'product_name' => $product_name,
- 'url' => $url,
- 'pic_prompt' => $pic_prompt,
- 'product' => $product,
- 'versions' => $versions
- ];
- }
- public function editProduct($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:ID不能为空');
- $versions = getProp($data, 'versions');
-
- // 检查是否存在且属于当前用户
- $role = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('type', 1)->first();
- if (!$role) Utils::throwError('20003:记录不存在');
-
- $updateData = [];
- // $needVersionRecord = false; // 是否需要记录版本
-
- // 名称
- $product_name = trim(getProp($data, 'product_name'));
- if ($product_name) {
- $updateData['product_name'] = $product_name;
- }
- // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
- // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
-
- // 图片地址
- $url = trim(getProp($data, 'url'));
- if ($url) {
- // 检查是否是正确的图片格式
- $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
- $urlPath = parse_url($url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- if (!in_array($extension, $allowedExtensions)) {
- Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
- }
-
- // // 如果 url 有变更,记录版本
- // if ($url !== $role->url) {
- // $needVersionRecord = true;
- // }
-
- $updateData['url'] = $url;
- }
-
- // 提示词
- $pic_prompt = trim(getProp($data, 'pic_prompt'));
- if ($pic_prompt) {
- // // 如果 pic_prompt 有变更,记录版本
- // if ($pic_prompt !== $role->pic_prompt) {
- // $needVersionRecord = true;
- // }
-
- $updateData['pic_prompt'] = $pic_prompt;
- }
-
- if (empty($updateData)) {
- Utils::throwError('20003:没有需要更新的数据');
- }
-
- // // 如果需要记录版本,将数据添加到 versions 数组
- // if ($needVersionRecord) {
- // // 获取现有的 versions 数据
- // $versions = json_decode($role->versions, true) ?: [];
- // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
-
- // // 如果是第一次记录版本,先添加旧版本(变更前)
- // if ($isFirstVersion) {
- // $oldVersion = [
- // 'url' => $role->url,
- // 'description' => $role->pic_prompt,
- // ];
- // // 旧版本添加到数组末尾
- // $versions[] = $oldVersion;
- // }
-
- // // 构建新版本(变更后)
- // $newVersion = [
- // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
- // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
- // ];
-
- // // 检查新版本是否已存在于历史版本中
- // $existingIndex = -1;
- // foreach ($versions as $index => $version) {
- // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
- // $existingIndex = $index;
- // break;
- // }
- // }
-
- // if ($existingIndex !== -1) {
- // // 如果已存在,移除旧的位置
- // array_splice($versions, $existingIndex, 1);
- // }
-
- // // 新版本添加到数组开头(最新的在前)
- // array_unshift($versions, $newVersion);
-
- // // // 限制版本数量(可选,例如只保留最近10个版本)
- // // if (count($versions) > 10) {
- // // $versions = array_slice($versions, 0, 10);
- // // }
-
- // $updateData['versions'] = json_encode($versions, 256);
- // }
- if ($versions) {
- $updateData['versions'] = json_encode($versions, 256);
- }
-
- $updateData['updated_at'] = date('Y-m-d H:i:s');
-
- return DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('id', $id)->update($updateData);
- }
-
- /**
- * 获取角色版本历史
- * @param array $data 包含 id(角色ID)
- * @return array 返回版本历史列表
- */
- public function getProductVersions($data) {
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:角色ID不能为空');
-
- $role = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('type', 1)
- ->first();
-
- if (!$role) Utils::throwError('20003:角色不存在');
-
- // 获取版本历史
- $versions = json_decode($role->versions, true) ?: [];
-
- // 添加当前版本作为最新版本
- $currentVersion = [
- 'version' => 0, // 0 表示当前版本
- 'url' => $role->url,
- 'pic_prompt' => $role->pic_prompt,
- 'updated_at' => $role->updated_at,
- 'is_current' => true
- ];
-
- array_unshift($versions, $currentVersion);
-
- return $versions;
- }
-
- /**
- * 恢复到指定版本
- * @param array $data 包含 id(角色ID)、version(版本号)
- * @return bool
- */
- public function restoreProductVersion($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- $version = getProp($data, 'version');
-
- if (!$id) Utils::throwError('20003:角色ID不能为空');
- if (!$version) Utils::throwError('20003:版本号不能为空');
-
- $role = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('type', 1)
- ->first();
-
- if (!$role) Utils::throwError('20003:角色不存在');
-
- // 获取版本历史
- $versions = json_decode($role->versions, true) ?: [];
-
- // 查找指定版本
- $targetVersion = null;
- foreach ($versions as $v) {
- if ($v['version'] == $version) {
- $targetVersion = $v;
- break;
- }
- }
-
- if (!$targetVersion) Utils::throwError('20003:版本不存在');
-
- // 先将当前版本保存到历史
- $newVersion = [
- 'version' => count($versions) + 1,
- 'url' => $role->url,
- 'pic_prompt' => $role->pic_prompt,
- 'updated_at' => date('Y-m-d H:i:s'),
- 'updated_by' => $uid
- ];
-
- array_unshift($versions, $newVersion);
-
- // 限制版本数量
- if (count($versions) > 10) {
- $versions = array_slice($versions, 0, 10);
- }
-
- // 恢复到指定版本
- return DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->update([
- 'url' => $targetVersion['url'],
- 'pic_prompt' => $targetVersion['pic_prompt'],
- 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- public function deleteProduct($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:ID不能为空');
- $ids = explode(',', $id);
-
- // 检查是否存在且属于当前用户
- $role = DB::table('mp_products')
- ->whereIn('id', $ids)
- ->where('cpid', $cpid)
- ->get();
- if (!$role) Utils::throwError('20003:记录不存在');
-
- return DB::table('mp_products')
- ->where('cpid', $cpid)
- ->whereIn('id', $ids)
- ->update([
- 'is_deleted' => 1,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- public function generateThreeView($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:ID不能为空');
-
- // 检查是否存在且属于当前用户
- $role = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('type', 1)->first();
- if (!$role) Utils::throwError('20003:记录不存在');
-
- $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
- $ref_img_url = trim(getProp($data, 'ref_img_url'));
- if (!$ref_img_url) {
- // 如果没有传入参考图,使用角色表中的图片
- $ref_img_url = $role->url ?? '';
- if (!$ref_img_url) {
- Utils::throwError('20003:参考图不能为空');
- }
- }
-
- // 检查参考图是否是正确的图片格式
- $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
- $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
-
- if (!in_array($extension, $allowedExtensions)) {
- Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
- }
-
- // 处理图片模型
- $model = getProp($data, 'model');
- if (!$model) {
- // 使用默认模型
- $model = 'doubao-seedream-5-0-lite-260128';
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
-
- try {
- // 创建图片生成任务
- $params = [
- 'prompt' => $prompt,
- 'model' => $model,
- 'ref_img_urls' => [$ref_img_url],
- 'width' => 1600,
- 'height' => 2848
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError('20003:创建图片生成任务失败');
- }
-
- // 检查任务模型类型
- $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
- $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
- $isSyncModel = $isVolcModel || $isGptModel;
- // 轮询获取结果(5分钟超时,每3秒查询一次)
- $start_time = time();
- $timeout = 300; // 5分钟
- $img_url = '';
-
- while (time() - $start_time < $timeout) {
- sleep(3);
- // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
- if ($isSyncModel) {
- // 刷新任务状态
- $task = MpGeneratePicTask::where('id', $task_id)->first();
-
- if ($task->status === 'success' && $task->result_url) {
- $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
- $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
- break;
- } elseif ($task->status === 'failed') {
- Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
- }
- } else {
- $task = MpGeneratePicTask::where('id', $task_id)->first();
- $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
-
- if ($statusInfo['status'] === 'success') {
- $task->updateStatus('success', [
- 'result_url' => $statusInfo['result_url'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
-
- $img_url = $statusInfo['result_url'][0];
- break;
- } elseif ($statusInfo['status'] === 'failed') {
- $task->updateStatus('failed', [
- 'error_message' => $statusInfo['error_message'],
- 'result_json' => $statusInfo['result_json'] ?? []
- ]);
- dLog('anime')->error('三视图生成失败', [
- 'error' => $statusInfo['error_message'] ?? '未知错误'
- ]);
- Utils::throwError('20003:三视图生成失败,' . ($statusInfo['error_message'] ?? '未知错误'));
- }
- }
- }
-
- if (empty($img_url)) {
- Utils::throwError('20003:三视图生成超时,请稍后重试');
- }
-
- // 保存三视图到 mp_products 表
- DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->update([
- 'three_view_image_url' => $img_url,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- return ['three_view_image_url' => $img_url];
-
- } catch (\Exception $e) {
- dLog('anime')->error('生成三视图失败', [
- 'error' => $e->getMessage()
- ]);
- logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
-
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
- /**
- * 保存剧本资产关联关系
- * @param array $data 请求参数
- * @return bool
- */
- public function saveScriptProducts($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $script_id = getProp($data, 'script_id');
- $products = getProp($data, 'products', []);
- $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
- if (!$script_id) {
- Utils::throwError('20003:请提供剧本ID');
- }
- // 验证剧本是否存在
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$script) {
- Utils::throwError('20003:剧本不存在');
- }
-
- $script_name = $script->script_name ?? 'script_' . $script_id;
-
- // 检查是否已经有该剧本的资产数据
- $existingMappings = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->get();
-
- if ($existingMappings->isNotEmpty()) {
- // 已存在资产映射,检查是否所有资产都有图片生成任务
- $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
-
- // 查询这些资产的图片生成任务状态
- $productsWithTasks = DB::table('mp_products')
- ->whereIn('id', $productIds)
- ->where('is_deleted', 0)
- ->get();
-
- $productTaskMap = [];
- $typeFolderIds = [];
- $hasAllTasks = true;
-
- foreach ($productsWithTasks as $product) {
- // 收集类型文件夹ID
- if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
- $parentFolder = DB::table('mp_products')
- ->where('id', $product->parent_id)
- ->where('type', 2)
- ->first();
-
- if ($parentFolder) {
- $typeFolderIds[$parentFolder->product] = $parentFolder->id;
- }
- }
-
- // 检查是否有图片生成任务
- if (!empty($product->pic_task_id)) {
- $productTaskMap[$product->id] = $product->pic_task_id;
- } else if($product->url && $product->pic_task_status == '生成成功') {
- continue;
- }
- else {
- // 有资产没有图片任务
- $hasAllTasks = false;
- }
- }
-
- // 如果所有资产都有任务ID,直接轮询返回结果
- if ($hasAllTasks && !empty($productTaskMap)) {
- dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'product_count' => count($productTaskMap)
- ]);
-
- // 直接返回 SSE 流轮询结果
- return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
- }
-
- // 如果部分资产没有任务ID,只为这些资产创建任务
- if (!$hasAllTasks && $auto_generate_images) {
- dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
- 'script_id' => $script_id,
- 'script_name' => $script_name
- ]);
-
- // 开启事务
- DB::beginTransaction();
-
- try {
- // 默认图片生成参数
- $model = 'doubao-seedream-5-0-lite-260128';
- $width = 1600;
- $height = 2848;
-
- foreach ($productsWithTasks as $product) {
- // 跳过已有任务的资产
- if (!empty($product->pic_task_id)) {
- continue;
- }
-
- // 跳过没有提示词的资产
- if (empty($product->pic_prompt)) {
- dLog('anime')->warning('资产没有提示词,跳过图片生成', [
- 'product_id' => $product->id,
- 'product_name' => $product->product_name
- ]);
- continue;
- }
-
- try {
- // 创建图片生成任务
- $params = [
- 'prompt' => $product->pic_prompt,
- 'model' => $model,
- 'ref_img_urls' => [],
- 'width' => $width,
- 'height' => $height
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if ($task_id) {
- $productTaskMap[$product->id] = $task_id;
-
- // 在事务中更新资产表的任务ID和状态
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_id' => $task_id,
- 'pic_task_status' => '生成中',
- 'updated_at' => now()
- ]);
-
- dLog('anime')->info('为已存在资产创建图片生成任务', [
- 'product_id' => $product->id,
- 'task_id' => $task_id
- ]);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('创建资产图片生成任务失败', [
- 'product_id' => $product->id,
- 'error' => $e->getMessage()
- ]);
-
- // 标记为失败(仍在事务中)
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成失败',
- 'updated_at' => now()
- ]);
- }
- }
-
- // 提交事务
- DB::commit();
-
- // 如果有新创建的任务,返回 SSE 流
- if (!empty($productTaskMap)) {
- return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
- }
-
- } catch (\Exception $e) {
- // 回滚事务
- DB::rollback();
-
- dLog('anime')->error('为已存在资产创建图片任务失败', [
- 'script_id' => $script_id,
- 'error' => $e->getMessage()
- ]);
-
- Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
- }
- }
-
- // 如果不需要生成图片,返回已存在的信息
- return [
- 'success' => true,
- 'message' => '剧本资产已存在',
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'type_folder_ids' => $typeFolderIds,
- 'existing_products' => count($productIds),
- 'tasks_count' => count($productTaskMap)
- ];
- }
- // 解析 products(可能是 JSON 字符串或数组)
- if (is_string($products)) {
- $products = json_decode($products, true);
- if (json_last_error() !== JSON_ERROR_NONE) {
- Utils::throwError('20003:产品数据格式错误');
- }
- }
- if (!is_array($products) || empty($products)) {
- Utils::throwError('20003:产品数据不能为空');
- }
- // 以下是原有的创建逻辑...
- // 开启事务
- DB::beginTransaction();
-
- try {
- $now = now();
- $mappingRecords = [];
- $createdProductIds = []; // 记录所有创建的资产ID
-
- // 获取剧本名称
- $script_name = $script->script_name ?? 'script_' . $script_id;
-
- // 存储每个类型的根文件夹ID
- $typeFolderIds = [];
-
- // 默认图片生成参数
- $model = 'doubao-seedream-5-0-lite-260128';
- $width = 1600;
- $height = 2848;
-
- // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
- foreach ($products as $productGroup) {
- $type = getProp($productGroup, 'type');
- $title = getProp($productGroup, 'title', '');
- $content = getProp($productGroup, 'content', []);
-
- if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
- continue;
- }
-
- // 为当前类型创建根文件夹(如果还未创建)
- if (!isset($typeFolderIds[$type])) {
- $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 2, // 1.资产 2文件夹
- 'product' => $type, // 1.主体 2.场景 3.道具
- 'parent_id' => 0, // 根文件夹,parent_id=0
- 'level' => 1, // 第一层级
- 'product_name' => $script_name,
- 'sort_order' => time() + $type,
- 'is_deleted' => 0,
- 'created_at' => $now,
- 'updated_at' => $now
- ]);
- }
-
- $folder_id = $typeFolderIds[$type];
-
- // 获取表头(第一行)并查找关键列的位置
- $headers = $content[0];
- $nameColumnIndex = -1; // 资产名称列索引
- $sequenceColumnIndex = -1; // 使用范围列索引
- $promptColumnIndex = -1; // 参考提示词列索引
-
- foreach ($headers as $index => $header) {
- // 查找"资产名称"列
- if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
- $nameColumnIndex = $index;
- }
- // 查找"使用范围"列
- if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
- $sequenceColumnIndex = $index;
- }
- // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
- if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
- $promptColumnIndex = $index;
- }
- }
-
- // 验证必要的列是否都找到了
- if ($nameColumnIndex === -1) {
- dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
- continue;
- }
- if ($sequenceColumnIndex === -1) {
- dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
- continue;
- }
-
- // 跳过表头,解析每一行数据
- for ($i = 1; $i < count($content); $i++) {
- $row = $content[$i];
-
- // 确保行数据有效
- if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
- continue;
- }
-
- // 根据动态查找的列索引提取数据
- $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
- $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
- $pic_prompt = '';
-
- // 提取参考提示词(如果找到了该列)
- if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
- $pic_prompt = trim($row[$promptColumnIndex]);
- }
-
- // 解析使用范围(逗号分隔的序号)
- $sequences = [];
- if (!empty($sequence_str)) {
- $sequenceParts = array_map('trim', explode(',', $sequence_str));
- foreach ($sequenceParts as $part) {
- if (is_numeric($part)) {
- $sequences[] = (int)$part;
- }
- }
- }
-
- if (empty($product_name)) {
- continue;
- }
-
- // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
- $product_id = DB::table('mp_products')->insertGetId([
- 'product_name' => $product_name,
- 'type' => 1, // 1=资产 2.文件夹
- 'product' => $type, // 1=角色, 2=场景, 3=道具
- 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
- 'level' => 2, // 第二层级
- 'pic_prompt' => $pic_prompt,
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
-
- // 记录创建的资产ID
- $createdProductIds[] = $product_id;
-
- // 为每个序号创建映射记录
- if (!empty($sequences)) {
- foreach ($sequences as $sequence) {
- $mappingRecords[] = [
- 'script_id' => $script_id,
- 'product_id' => $product_id,
- 'episode_number' => $sequence,
- 'created_at' => $now,
- 'updated_at' => $now,
- ];
- }
- } else {
- // 如果没有指定序号,创建一个默认映射(序号为0)
- $mappingRecords[] = [
- 'script_id' => $script_id,
- 'product_id' => $product_id,
- 'episode_number' => 0,
- 'created_at' => $now,
- 'updated_at' => $now,
- ];
- }
- }
- }
- if (empty($mappingRecords)) {
- Utils::throwError('20003:没有有效的产品数据');
- }
- // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
- $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
-
- // 如果需要自动生成图片,在事务中创建图片生成任务
- $productTaskMap = [];
- if ($auto_generate_images && !empty($createdProductIds)) {
- // 查询所有创建的资产
- $productsToGenerate = DB::table('mp_products')
- ->whereIn('id', $createdProductIds)
- ->where('is_deleted', 0)
- ->get();
-
- foreach ($productsToGenerate as $product) {
- if (empty($product->pic_prompt)) {
- dLog('anime')->warning('资产没有提示词,跳过图片生成', [
- 'product_id' => $product->id,
- 'product_name' => $product->product_name
- ]);
- continue;
- }
-
- try {
- // 创建图片生成任务
- $params = [
- 'prompt' => $product->pic_prompt,
- 'model' => $model,
- 'ref_img_urls' => [],
- 'width' => $width,
- 'height' => $height
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if ($task_id) {
- $productTaskMap[$product->id] = $task_id;
-
- // 在事务中更新资产表的任务ID和状态
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_id' => $task_id,
- 'pic_task_status' => '生成中',
- 'updated_at' => now()
- ]);
-
- dLog('anime')->info('创建资产图片生成任务', [
- 'product_id' => $product->id,
- 'task_id' => $task_id
- ]);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('创建资产图片生成任务失败', [
- 'product_id' => $product->id,
- 'error' => $e->getMessage()
- ]);
-
- // 标记为失败(仍在事务中)
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成失败',
- 'updated_at' => now()
- ]);
- }
- }
- }
-
- // 提交事务
- DB::commit();
-
- // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
- if ($auto_generate_images && !empty($productTaskMap)) {
- // 返回 SSE 流(事务外轮询)
- return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
- }
-
- // 如果不需要生成图片,返回普通结果
- return [
- 'success' => true,
- 'type_folder_ids' => $typeFolderIds,
- 'inserted_count' => $insertedCount,
- 'total_records' => count($mappingRecords),
- 'created_products' => count($createdProductIds),
- 'image_tasks_created' => count($productTaskMap)
- ];
-
- } catch (\Exception $e) {
- // 回滚事务
- DB::rollback();
-
- // 记录错误日志
- dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
- 'script_id' => $script_id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
-
- // 统一使用 Utils::throwError 抛出错误
- Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
- }
- }
- /**
- * 批量为剧本资产生成图片
- *
- * @param array $data 请求参数
- * @return \Generator 返回 SSE 流
- */
- public function batchGenerateProductImages($data) {
- $script_id = getProp($data, 'script_id');
- $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
-
- if (!$script_id) {
- Utils::throwError('20003:请提供剧本ID');
- }
-
- // 验证剧本是否存在
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$script) {
- Utils::throwError('20003:剧本不存在');
- }
-
- $script_name = $script->script_name ?? 'script_' . $script_id;
-
- // 获取需要生成图片的所有资产
- $products = DB::table('mp_products')
- ->whereIn('parent_id', array_values($type_folder_ids))
- ->where('is_deleted', 0)
- ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
- ->get();
-
- if ($products->isEmpty()) {
- Utils::throwError('20003:没有找到需要生成图片的资产');
- }
-
- // 默认参数
- $model = 'doubao-seedream-5-0-lite-260128';
- $width = 1600;
- $height = 2848;
-
- // 开始为每个资产创建图片生成任务
- $taskIds = [];
- $productTaskMap = []; // 资产ID到任务ID的映射
-
- foreach ($products as $product) {
- if (empty($product->pic_prompt)) {
- dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
- continue;
- }
-
- try {
- // 创建图片生成任务
- $params = [
- 'prompt' => $product->pic_prompt,
- 'model' => $model,
- 'ref_img_urls' => [],
- 'width' => $width,
- 'height' => $height
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if ($task_id) {
- $taskIds[] = $task_id;
- $productTaskMap[$product->id] = $task_id;
-
- // 更新资产表的任务ID和状态
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_id' => $task_id,
- 'pic_task_status' => '生成中',
- 'updated_at' => now()
- ]);
-
- dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('创建资产图片生成任务失败', [
- 'product_id' => $product->id,
- 'error' => $e->getMessage()
- ]);
-
- // 标记为失败
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成失败',
- 'updated_at' => now()
- ]);
- }
- }
-
- if (empty($taskIds)) {
- Utils::throwError('20003:没有成功创建任何图片生成任务');
- }
-
- // 返回 SSE 流
- return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
- }
-
- /**
- * 轮询资产图片生成任务状态(SSE流式返回)
- * 只通过查询数据库获取任务状态,不主动调用API
- *
- * @param int $script_id 剧本ID
- * @param string $script_name 剧本名称
- * @param array $productTaskMap 资产ID到任务ID的映射
- * @param array $type_folder_ids 类型文件夹ID映射
- * @return \Generator
- */
- private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
- $startTime = time();
- $timeout = 1800; // 30分钟超时
- $pollInterval = 10; // 10秒轮询一次
- $lastStatus = []; // 记录上次的状态,用于判断是否有变化
-
- // 定义类型名称映射
- $typeNames = [
- 1 => 'roles', // 角色
- 2 => 'scenes', // 场景
- 3 => 'props' // 道具
- ];
-
- while (time() - $startTime < $timeout) {
- sleep($pollInterval);
-
- // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
- $mappings = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->pluck('product_id')
- ->unique()
- ->toArray();
-
- if (empty($mappings)) {
- dLog('anime')->warning('该剧本没有关联的资产', [
- 'script_id' => $script_id,
- 'script_name' => $script_name
- ]);
- break;
- }
-
- // 查询所有资产的当前状态
- $products = DB::table('mp_products')
- ->whereIn('id', $mappings)
- ->where('is_deleted', 0)
- ->get();
-
- // 统计各类型的状态(使用类型名称作为键名)
- $stats = [
- 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
- 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
- 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
- ];
-
- $allCompleted = true;
- $hasStatusChange = false;
-
- foreach ($products as $product) {
- $type = $product->product;
- $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
-
- // 如果类型名称不在 stats 中,初始化
- if (!isset($stats[$typeName])) {
- $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
- }
-
- $stats[$typeName]['total']++;
-
- $task_id = $product->pic_task_id;
- $currentStatus = $product->pic_task_status;
-
- // 检查状态是否有变化
- if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
- $hasStatusChange = true;
- $lastStatus[$product->id] = $currentStatus;
- }
-
- // 如果是生成中,查询任务表状态
- if ($currentStatus === '生成中' && $task_id) {
- // 只查询数据库,不调用API
- $task = DB::table('mp_generate_pic_tasks')
- ->where('id', $task_id)
- ->first();
-
- if ($task) {
- // 检查任务状态
- if ($task->status === 'success' && $task->result_url) {
- // 解析图片URL
- $result_urls = $task->result_url;
- if (is_string($result_urls)) {
- $result_urls = json_decode($result_urls, true);
- }
- $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
-
- // 更新资产表状态
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成成功',
- 'url' => $img_url,
- 'updated_at' => now()
- ]);
-
- $stats[$typeName]['success']++;
- $stats[$typeName]['completed']++;
- $hasStatusChange = true;
-
- dLog('anime')->info('资产图片生成成功', [
- 'product_id' => $product->id,
- 'task_id' => $task_id,
- 'img_url' => $img_url
- ]);
- } elseif ($task->status === 'failed') {
- // 更新资产表状态
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成失败',
- 'updated_at' => now()
- ]);
-
- $stats[$typeName]['completed']++;
- $hasStatusChange = true;
-
- dLog('anime')->warning('资产图片生成失败', [
- 'product_id' => $product->id,
- 'task_id' => $task_id,
- 'error' => $task->error_message ?? '未知错误'
- ]);
- } else {
- // 任务还在处理中
- $allCompleted = false;
- }
- } else {
- // 任务不存在,标记为失败
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成失败',
- 'updated_at' => now()
- ]);
-
- $stats[$type]['completed']++;
- $hasStatusChange = true;
-
- dLog('anime')->error('图片生成任务不存在', [
- 'product_id' => $product->id,
- 'task_id' => $task_id
- ]);
- }
- } elseif ($currentStatus === '生成成功') {
- $stats[$typeName]['success']++;
- $stats[$typeName]['completed']++;
- } elseif ($currentStatus === '生成失败') {
- $stats[$typeName]['completed']++;
- } else {
- // 其他状态也认为未完成
- $allCompleted = false;
- }
- }
-
- // 移除没有数据的类型(total=0)
- foreach ($stats as $typeName => $stat) {
- if ($stat['total'] === 0) {
- unset($stats[$typeName]);
- }
- }
-
- // 如果有状态变化,发送 SSE 更新
- if ($hasStatusChange) {
- $eventType = $allCompleted ? 'complete' : 'update';
-
- $response = [
- 'type' => $eventType,
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'stats' => $stats,
- 'timestamp' => date('Y-m-d H:i:s')
- ];
-
- yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
-
- dLog('anime')->info('SSE更新', [
- 'event_type' => $eventType,
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'stats' => $stats
- ]);
-
- if ($allCompleted) {
- dLog('anime')->info('所有资产图片生成任务已完成', [
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'stats' => $stats
- ]);
- break;
- }
- }
- }
-
- // 超时处理
- if (time() - $startTime >= $timeout && !$allCompleted) {
- $response = [
- 'type' => 'timeout',
- 'message' => '部分任务超时,请稍后查看结果',
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'timestamp' => date('Y-m-d H:i:s')
- ];
-
- yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
-
- dLog('anime')->warning('资产图片生成任务超时', [
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'timeout' => $timeout
- ]);
- }
- }
- /**
- * 获取剧本关联的资产列表
- * @param array $data 请求参数
- * @return array
- */
- public function getScriptProducts($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $script_id = getProp($data, 'script_id');
- $episode_number = getProp($data, 'episode_number');
- if (!$script_id) {
- Utils::throwError('20003:请提供剧本ID');
- }
- // 验证剧本是否存在
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$script) {
- Utils::throwError('20003:剧本不存在');
- }
- // 联表查询资产信息
- $query = DB::table('mp_script_product_mappings as mapping')
- ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
- ->where('mapping.script_id', $script_id)
- ->where('product.cpid', $cpid)
- ->where('product.is_deleted', 0);
- // 如果提供了 episode_number,则过滤指定集数
- if ($episode_number !== null && $episode_number !== '') {
- $query->where('mapping.episode_number', $episode_number);
- }
- $mappings = $query->select(
- 'mapping.script_id',
- 'mapping.product_id',
- 'mapping.episode_number',
- 'product.product_name',
- 'product.type',
- 'product.product',
- 'product.pic_prompt',
- 'product.url',
- 'product.pic_task_id',
- 'product.pic_task_status',
- 'product.three_view_image_url',
- 'mapping.created_at'
- )
- ->orderBy('mapping.product_id', 'asc')
- ->orderBy('mapping.episode_number', 'asc')
- ->get();
- // 按 product_id 分组,合并 episode_number
- $productMap = [];
- foreach ($mappings as $item) {
- $product_id = $item->product_id;
-
- if (!isset($productMap[$product_id])) {
- $productMap[$product_id] = [
- 'product_id' => $product_id,
- 'product_name' => $item->product_name,
- 'type' => (int)$item->type,
- 'product' => (int)$item->product,
- 'pic_prompt' => $item->pic_prompt,
- 'url' => $item->url,
- 'pic_task_id' => $item->pic_task_id,
- 'pic_task_status' => $item->pic_task_status,
- 'episode_numbers' => [],
- 'created_at' => $item->created_at,
- ];
- }
-
- // 添加 episode_number(去重)
- if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
- $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
- }
- }
-
- // 按类型分组
- $roles = []; // type=1 角色/主体
- $scenes = []; // type=2 场景
- $props = []; // type=3 道具
-
- foreach ($productMap as $product) {
- // 将 episode_numbers 数组转换为逗号分隔的字符串
- $episodeNumbersStr = implode(',', $product['episode_numbers']);
-
- // 构造返回数据
- $productData = [
- 'product_id' => $product['product_id'],
- 'product_name' => $product['product_name'],
- 'product' => $product['product'],
- 'pic_prompt' => $product['pic_prompt'],
- 'url' => $product['url'],
- 'pic_task_id' => $product['pic_task_id'],
- 'pic_task_status' => $product['pic_task_status'],
- 'episode_numbers' => $episodeNumbersStr,
- 'created_at' => $product['created_at'],
- ];
-
- // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
- // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
- switch ($product['product']) {
- case 1:
- $roles[] = $productData;
- break;
- case 2:
- $scenes[] = $productData;
- break;
- case 3:
- $props[] = $productData;
- break;
- }
- }
- return [
- 'script_id' => $script_id,
- 'script_name' => $script->script_name ?? '',
- 'roles' => $roles, // 主体
- 'scenes' => $scenes, // 场景
- 'props' => $props, // 道具
- ];
- }
- /**
- * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
- * @param string $actContent 原始内容
- * @param array $products 产品数组(包含product_name和url)
- * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
- */
- public function processActContentWithProducts($actContent, $products) {
- if (empty($actContent) || empty($products)) {
- return [
- 'content' => $actContent,
- 'reference_images' => []
- ];
- }
-
- // 构建产品名称到产品信息的映射
- $product_dict = [];
- foreach ($products as $product) {
- $product_name = getProp($product, 'product_name');
- if ($product_name) {
- $product_dict[$product_name] = [
- 'url' => getProp($product, 'url'),
- 'voice_prompt' => getProp($product, 'voice_prompt')
- ];
- }
- }
-
- // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
- preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
-
- $reference_images = [];
- $product_index_map = []; // 产品名称 => 图片序号的映射
- $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
- $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
- $current_index = 1;
-
- if (!empty($matches[1])) {
- // 按照在内容中第一次出现的顺序,为每个产品分配序号
- $seen_products = []; // 用于去重
-
- foreach ($matches[1] as $product_name) {
- // 跳过已处理的产品
- if (isset($seen_products[$product_name])) {
- continue;
- }
-
- $seen_products[$product_name] = true;
-
- // 检查产品是否在字典中
- if (isset($product_dict[$product_name])) {
- $url = $product_dict[$product_name]['url'];
- $voice_prompt = $product_dict[$product_name]['voice_prompt'];
-
- // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
- if (!empty($voice_prompt) && $product_name !== '旁白') {
- $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
- }
-
- // 只有URL非空才分配序号和添加到参考图片
- if (!empty($url)) {
- // 检查URL是否已经在reference_images中(去重)
- if (!in_array($url, $reference_images)) {
- $reference_images[] = $url;
- $product_index_map[$product_name] = $current_index;
- $current_index++;
- } else {
- // URL重复,找到已有的序号
- $existing_index = array_search($url, $reference_images) + 1;
- $product_index_map[$product_name] = $existing_index;
- }
- } else {
- // URL为空,不分配序号(后续直接去掉{})
- $product_index_map[$product_name] = 0;
- }
- } else {
- // 产品不在字典中,不分配序号
- $product_index_map[$product_name] = 0;
- }
- }
- }
-
- // 第二步:替换内容中的 {产品名称}
- $processedContent = $actContent;
- foreach ($product_index_map as $product_name => $index) {
- $escaped_name = preg_quote($product_name, '/');
-
- if ($index > 0) {
- // 有图片,替换为:产品名称(图X)
- $replacement = $product_name . '<图片' . $index . '>';
- } else {
- // 无图片,只保留产品名称
- $replacement = $product_name;
- }
-
- // 替换所有 {产品名称} 为处理后的格式
- $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
- }
-
- // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
- foreach ($products as $product) {
- $product_name = getProp($product, 'product_name');
- $voice_prompt = getProp($product, 'voice_prompt');
-
- if ($product_name === '旁白' && !empty($voice_prompt)) {
- $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
- break; // 找到旁白后退出循环
- }
- }
-
- // 第四步:将voice_prompt信息添加到内容最前面
- $voice_prompt_prefix = '';
- if (!empty($voice_prompts)) {
- $voice_prompt_prefix .= implode('', $voice_prompts);
- }
- // 旁白的voice_prompt放在最后
- if (!empty($narrator_voice_prompt)) {
- $voice_prompt_prefix .= $narrator_voice_prompt;
- }
-
- // 如果有voice_prompt信息,添加到内容开头
- if (!empty($voice_prompt_prefix)) {
- $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
- }
-
- return [
- 'content' => $processedContent,
- 'reference_images' => $reference_images
- ];
- }
- public function saveActVideoGenerateParams($data) {
- $episode_id = getProp($data, 'episode_id');
- $model = getProp($data, 'video_model');
- if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
- Utils::throwError('20003:该模型不可用');
- }
- if (!$model) {
- // 使用默认模型
- $model = 'zhizhen-20-mini';
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
- $video_resolution = getProp($data, 'video_resolution', '720p');
- $ratio = getProp($data, 'ratio');
- if (!$ratio) $ratio = '9:16';
- return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'video_model' => $model,
- 'video_resolution' => $video_resolution,
- 'ratio' => $ratio,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
-
- }
- public function confirmActs($data) {
- $episode_id = getProp($data, 'episode_id');
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
- if (!$episode) {
- Utils::throwError('20003:分集不存在');
- }
- $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
- $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
- // 获取所有片段数据
- $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
-
- // 构建角色和场景名称数组
- $role_names = [];
- $scene_names = [];
-
- foreach ($roles as $role) {
- $role_name = getProp($role, 'role');
- if ($role_name && $role_name != '旁白') {
- $role_names[] = $role_name;
- }
- }
-
- foreach ($scenes as $scene) {
- $scene_name = getProp($scene, 'scene');
- if ($scene_name) {
- $scene_names[] = $scene_name;
- }
- }
-
- // 按照字符长度降序排序,确保先匹配长的名称(避免部分匹配问题)
- usort($role_names, function($a, $b) {
- return mb_strlen($b) - mb_strlen($a);
- });
- usort($scene_names, function($a, $b) {
- return mb_strlen($b) - mb_strlen($a);
- });
- try {
- DB::beginTransaction();
- // 处理每个片段
- foreach ($acts as $act) {
- $act_content = getProp($act, 'act_content');
- if (!$act_content) continue;
-
- $processed_content = $act_content;
-
- // 标记已处理的位置,避免重复标记
- $marked_positions = [];
-
- // 先匹配场景(在"场景:"后面)
- foreach ($scene_names as $scene_name) {
- // 转义特殊字符
- $escaped_scene = preg_quote($scene_name, '/');
- // 匹配场景:后面的场景名称(可能换行,也可能不换行)
- $pattern = '/(场景:[\s\r\n]*)(' . $escaped_scene . ')/u';
-
- $processed_content = preg_replace_callback($pattern, function($matches) use (&$marked_positions) {
- $full_match = $matches[0];
- $prefix = $matches[1];
- $scene_name = $matches[2];
-
- // 检查是否已经被标记
- if (strpos($scene_name, '{') === false && strpos($scene_name, '}') === false) {
- return $prefix . '{' . $scene_name . '}';
- }
- return $full_match;
- }, $processed_content);
- }
-
- // 再匹配角色名称(只在"画面:"部分)
- foreach ($role_names as $role_name) {
- // 转义特殊字符
- $escaped_role = preg_quote($role_name, '/');
-
- // 只匹配"画面:"开始到换行之前的内容
- $pattern = '/(画面:[^\n]*)/u';
- $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
- $line = $matches[1]; // 整行"画面:xxxxx"
-
- // 在这一行中匹配所有角色名(避免重复标记)
- $new_line = preg_replace(
- '/(?<![{])(' . $escaped_role . ')(?![}])/u',
- '{$1}',
- $line
- );
-
- return $new_line;
- }, $processed_content);
- }
-
- // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
- $shot_counter = 0;
- $processed_content = preg_replace_callback(
- '/【(?:镜头|分镜)(\d+)】/u',
- function($matches) use (&$shot_counter) {
- $shot_counter++;
- return '【镜头' . $shot_counter . '】';
- },
- $processed_content
- );
-
- // 更新数据库
- $boolen = DB::table('mp_episode_segments')
- ->where('id', $act->id)
- ->update([
- 'act_show_content' => $processed_content,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$boolen) {
- Utils::throwError('20003:片段处理失败');
- }
- }
- }catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
-
- $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'is_generated' => 1,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if (!$boolen1) {
- DB::rollBack();
- Utils::throwError('20003:分集处理失败!');
- }
- DB::commit();
- // 重新查询更新后的片段数据
- $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
- // 合并角色、场景和extra_products作为products,统一字段名为product_name
- // extra_products优先级更高,会覆盖同名的roles和scenes
- $products = [];
-
- // 先处理角色数组
- foreach ($roles as $role) {
- $product = $role;
- // 将role字段重命名为product_name
- if (isset($product['role'])) {
- $product['product_name'] = $product['role'];
- unset($product['role']);
- }
- $product['product'] = 1; // 标记类型为角色
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
-
- // 处理场景数组
- foreach ($scenes as $scene) {
- $product = $scene;
- // 将scene字段重命名为product_name
- if (isset($product['scene'])) {
- $product['product_name'] = $product['scene'];
- unset($product['scene']);
- }
- $product['product'] = 2; // 标记类型为场景
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
-
- // extra_products优先级更高,直接覆盖同名的roles和scenes
- $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
- foreach ($extra_products as $extra_product) {
- $product_name = getProp($extra_product, 'product_name');
- if ($product_name) {
- $products[$product_name] = $extra_product; // 覆盖同名数据
- }
- }
-
- // 重新索引数组(去除key)
- $products = array_values($products);
-
- // 构建返回的acts数组
- $return_acts = [];
- foreach ($acts as $act) {
- $return_acts[] = [
- 'act_id' => getProp($act, 'id'),
- 'act_number' => getProp($act, 'act_number'),
- 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
- 'act_show_content' => getProp($act, 'act_show_content'),
- 'video_url' => getProp($act, 'video_url'),
- 'video_duration' => getProp($act, 'video_duration'),
- 'video_time_point_start' => getProp($act, 'video_time_point_start'),
- 'video_time_point_end' => getProp($act, 'video_time_point_end'),
- ];
- }
- return [
- 'anime_id' => getProp($episode, 'anime_id'),
- 'episode_id' => $episode_id,
- 'title' => getProp($episode, 'title'),
- 'episode_number' => getProp($episode, 'episode_number'),
- 'is_generated' => getProp($episode, 'is_generated'),
- 'products' => $products,
- 'acts' => $return_acts
- ];
- }
- }
|