| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332 |
- <?php
- namespace App\Services\Anime;
- use App\Consts\BaseConst;
- use App\Consts\ErrorConst;
- use App\Exceptions\ApiException;
- use App\Facade\Site;
- use App\Libs\Utils;
- use App\Models\MpGeneratePicTask;
- use App\Models\MpTaskCenter;
- use App\Services\AIGeneration\AIImageGenerationService;
- use App\Services\AIGeneration\AIVideoGenerationService;
- use App\Services\DeepSeek\DeepSeekService;
- use App\Services\PointsService;
- use App\Services\TaskCenterService;
- 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;
- use PhpOffice\PhpSpreadsheet\IOFactory;
- class AnimeService
- {
- protected $aiImageGenerationService;
- protected $aiVideoGenerationService;
- protected $DeepSeekService;
- protected $pointsService;
- protected $taskCenterService;
- private $url;
- private $api_key;
- private $headers;
- public function __construct(
- AIImageGenerationService $aiImageGenerationService,
- AIVideoGenerationService $aiVideoGenerationService,
- DeepSeekService $DeepSeekService,
- PointsService $pointsService,
- TaskCenterService $taskCenterService
- ) {
- $this->aiImageGenerationService = $aiImageGenerationService;
- $this->aiVideoGenerationService = $aiVideoGenerationService;
- $this->DeepSeekService = $DeepSeekService;
- $this->pointsService = $pointsService;
- $this->taskCenterService = $taskCenterService;
- $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();
- $cpid = Site::getCpid();
- $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,
- 'cpid' => $cpid,
- '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 = 'deepseek-v4-pro';
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'deepseek-v4-pro';
- }
- $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] : [],
- // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'episode_number' => getProp($episode, 'episode_number'),
- ];
-
- $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] : [],
- // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'episode_number' => getProp($episode, 'episode_number'),
- ];
-
- $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, end_episode_sequence')->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;
- // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
- $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
- $episodeTasks = DB::table('mp_batch_episode_generation_details')
- ->where('anime_id', $anime_id)
- ->whereIn('status', ['pending', 'processing', 'failed']) // 只获取待生成/生成中任务,已完成或失败的不显示
- ->orderBy('episode_number')
- ->get()
- ->map(function ($task) use ($episodeNumbers) {
- if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
- return null;
- }
- return [
- 'episode_number' => (int)$task->episode_number,
- 'status' => $task->status,
- 'error_message' => $task->status == 'failed' ? $task->error_message : '',
- ];
- })
- ->filter()
- ->values()
- ->toArray();
- $anime['episode_tasks'] = $episodeTasks;
- 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', 'props', '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'];
- // }
- $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
-
- // 获取分镜信息
- $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'];
- // 获取mp_animes表中的视频参数
- $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
- $episode['video_params'] = [
- 'video_model' => getProp($anime, 'video_model'),
- 'video_resolution' => getProp($anime, 'video_resolution'),
- 'ratio' => getProp($anime, 'video_ratio'),
- ];
- 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,
- 'pic_task_id' => $task_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,
- 'pic_task_id' => $task_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', 'video_task_id', 'pic_task_id', '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,兼容角色对象内部(roles.is_deleted)的传参
- $is_deleted = getProp($data, 'is_deleted', getProp($target_roles, 'is_deleted', 0));
- // 控制字段不随角色内容写入分集roles存储
- if (is_array($target_roles)) {
- unset($target_roles['is_deleted']);
- }
- // 参数验证
- 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 (empty($target_role_name)) {
- Utils::throwError('20003:角色名称不能为空');
- }
-
- // 如果是删除操作
- 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('user_id', $uid)
- ->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', '');
- $three_view_image_url = trim(getProp($target_roles, 'three_view_image_url', ''));
- // 兼容 versions 传入数组或 JSON 字符串
- $versions = getProp($target_roles, 'versions', null);
- if (is_string($versions) && $versions !== '') {
- $decoded_versions = json_decode($versions, true);
- if (is_array($decoded_versions)) {
- $versions = $decoded_versions;
- }
- }
- $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;
- // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
- if (is_array($target_roles) && array_key_exists('three_view_image_url', $target_roles)) {
- $updateData['three_view_image_url'] = trim(getProp($target_roles, 'three_view_image_url', ''));
- }
-
- // 处理versions字段,显式传入数组(含空数组)时覆盖
- if (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 {
- // 创建新资产
- $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,
- 'three_view_image_url' => $three_view_image_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,兼容场景对象内部(scenes.is_deleted)的传参
- $is_deleted = getProp($data, 'is_deleted', getProp($target_scenes, 'is_deleted', 0));
- // 控制字段不随场景内容写入分集scenes存储
- if (is_array($target_scenes)) {
- unset($target_scenes['is_deleted']);
- }
- // 参数验证
- 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 (empty($target_scene_name)) {
- Utils::throwError('20003:场景名称不能为空');
- }
-
- // 如果是删除操作
- 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('user_id', $uid)
- ->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', '');
- $three_view_image_url = trim(getProp($target_scenes, 'three_view_image_url', ''));
- // 兼容 versions 传入数组或 JSON 字符串
- $versions = getProp($target_scenes, 'versions', null);
- if (is_string($versions) && $versions !== '') {
- $decoded_versions = json_decode($versions, true);
- if (is_array($decoded_versions)) {
- $versions = $decoded_versions;
- }
- }
- $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;
- // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
- if (is_array($target_scenes) && array_key_exists('three_view_image_url', $target_scenes)) {
- $updateData['three_view_image_url'] = trim(getProp($target_scenes, 'three_view_image_url', ''));
- }
-
- // 处理versions字段,显式传入数组(含空数组)时覆盖
- if (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 {
- // 创建新资产
- $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,
- 'three_view_image_url' => $three_view_image_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 changeEpisodeProps($data) {
- $anime_id = getProp($data, 'anime_id');
- $episode_id = getProp($data, 'episode_id');
- $target_props = getProp($data, 'props');
- // 删除标志优先取最外层入参 is_deleted,兼容道具对象内部(props.is_deleted)的传参
- $is_deleted = getProp($data, 'is_deleted', getProp($target_props, 'is_deleted', 0));
- // 控制字段不随道具内容写入分集props存储
- if (is_array($target_props)) {
- unset($target_props['is_deleted']);
- }
- // 参数验证
- if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
- if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
- if (!$target_props) Utils::throwError('20003:请提供道具信息');
- // 验证剧集是否存在
- $episode = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->first();
-
- if (!$episode) Utils::throwError('20003:该剧集不存在');
- $props = json_decode(getProp($episode, 'props'), 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_prop_name = getProp($target_props, 'prop');
- if (empty($target_prop_name)) {
- Utils::throwError('20003:道具名称不能为空');
- }
-
- // 如果是删除操作
- if ($is_deleted == 1) {
- // 从道具列表中移除该道具
- $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
- return getProp($prop, 'prop') !== $target_prop_name;
- }));
-
- // 更新道具列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'props' => json_encode($props, 256),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($result === false) {
- Utils::throwError('20003:删除道具失败');
- }
- } else {
- // 新增或更新操作
- $prop_found = false;
- $is_new_prop = false;
-
- // 查找并更新已存在的道具
- foreach($props as &$prop) {
- if (getProp($prop, 'prop') === $target_prop_name) {
- $prop = $target_props;
- $prop_found = true;
- break;
- }
- }
-
- // 如果道具不存在,则新增
- if (!$prop_found) {
- $props[] = $target_props;
- $is_new_prop = true;
- }
- // 更新道具列表
- $result = DB::table('mp_anime_episodes')
- ->where('anime_id', $anime_id)
- ->where('id', $episode_id)
- ->update([
- 'props' => json_encode($props, 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('user_id', $uid)
- ->where('is_deleted', 0)
- ->first();
-
- if ($script) {
- $script_name = $script->script_name ?? 'script_' . $script_id;
- $product_name = getProp($target_props, 'prop');
- $pic_prompt = getProp($target_props, 'pic_prompt', '');
- $url = getProp($target_props, 'url', '');
- $three_view_image_url = trim(getProp($target_props, 'three_view_image_url', ''));
- // 兼容 versions 传入数组或 JSON 字符串
- $versions = getProp($target_props, 'versions', null);
- if (is_string($versions) && $versions !== '') {
- $decoded_versions = json_decode($versions, true);
- if (is_array($decoded_versions)) {
- $versions = $decoded_versions;
- }
- }
- $product_type = 3; // 3=道具
-
- // 查找或创建以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;
- // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
- if (is_array($target_props) && array_key_exists('three_view_image_url', $target_props)) {
- $updateData['three_view_image_url'] = trim(getProp($target_props, 'three_view_image_url', ''));
- }
-
- // 处理versions字段,显式传入数组(含空数组)时覆盖
- if (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 {
- // 创建新资产
- $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,
- 'three_view_image_url' => $three_view_image_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 = 'gpt-image-2';
- }
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- $model = 'gpt-image-2';
- }
- $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,
- 'pic_task_id' => $task_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,
- 'pic_task_id' => $task_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_show_content'] = $act_content;
- $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
- // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
- $shot_counter = 0;
- $update_data['act_show_content'] = preg_replace_callback(
- '/【(?:镜头|分镜)(\d+)】/u',
- function($matches) use (&$shot_counter) {
- $shot_counter++;
- return '【镜头' . $shot_counter . '】';
- },
- $update_data['act_show_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();
- // 返回新复制的记录
- $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,act_show_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $act_id)->first();
- $new_segment = (array)$new_segment;
- return $new_segment;
- } 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:请选择片段');
-
- $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['video_url'] = '';
- $segment_data['video_task_id'] = '';
- $segment_data['video_task_status'] = '';
- $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,act_show_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', 'video_task_id', 'pic_task_id', '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) ?: [];
- $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
- $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
-
- // 先合并roles、scenes和props
- // 处理角色数组
- foreach ($roles as $role) {
- $product = $role;
- // 将role字段重命名为product_name
- if (is_array($product) && !empty($product['role'] ?? null)) {
- $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 (is_array($product) && !empty($product['scene'] ?? null)) {
- $product['product_name'] = $product['scene'];
- unset($product['scene']);
- $product['product'] = 2; // 标记类型为场景
- $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
- }
- }
- // 处理道具数组
- foreach ($props as $prop) {
- $product = $prop;
- // 将prop字段重命名为product_name
- if (is_array($product) && !empty($product['prop'] ?? null)) {
- $product['product_name'] = $product['prop'];
- unset($product['prop']);
- $product['product'] = 3; // 标记类型为道具
- $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) ?: [];
- $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
-
- // 如果是分集数据,需要处理继承和任务创建逻辑
- if ($episode_id) {
- $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
- }
- // 返回生成器函数,用于 SSE 流式输出
- return function() use ($roles, $scenes, $props, $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, $props) {
- return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
- };
- // 发送初始数据
- $currentHash = $generateHash($roles, $scenes, $props);
- Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
- echo "data: " . json_encode([
- 'type' => 'init',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'props' => $props,
- 'start_time' => $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- if (ob_get_level() > 0) {
- 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;
- }
- }
- }
- }
- // 检查道具任务状态
- foreach ($props as $index => &$prop) {
- $task_id = getProp($prop, 'task_id');
- $task_status = getProp($prop, 'task_status');
- $existing_url = getProp($prop, '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'])) {
- $prop['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])) {
- $prop['url'] = $result_urls[0];
- }
- }
- }
-
- $updated = true;
- } else if ($status === 'processing') {
- $hasProcessing = true;
- }
- }
- }
- }
- // 如果有更新,检查数据是否真的变化了(通过哈希对比)
- if ($updated) {
- $newHash = $generateHash($roles, $scenes, $props);
- $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),
- 'props' => json_encode($props, 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,
- 'props' => $props,
- 'elapsed_time' => time() - $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- if (ob_get_level() > 0) {
- 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) {
- foreach ($props as $prop) {
- if (!empty(getProp($prop, 'url')) && getProp($prop, '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),
- 'props' => json_encode($props, 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,
- 'props' => $props,
- 'elapsed_time' => time() - $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- if (ob_get_level() > 0) {
- 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) ?: [];
- $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
-
- // 使用数据库中的最终数据
- $roles = $finalRoles;
- $scenes = $finalScenes;
- $props = $finalProps;
- }
- } catch (\Exception $e) {
- dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
- // 如果查询失败,继续使用内存中的数据
- }
-
- // 清理缓存
- Redis::del($cacheKey);
- echo "data: " . json_encode([
- 'type' => 'completed',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'props' => $props,
- 'total_time' => time() - $startTime
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- if (ob_get_level() > 0) {
- 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) ?: [];
- $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
-
- // 使用数据库中的最终数据
- $roles = $finalRoles;
- $scenes = $finalScenes;
- $props = $finalProps;
- }
- } catch (\Exception $e) {
- dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
- // 如果查询失败,继续使用内存中的数据
- }
-
- // 清理缓存
- Redis::del($cacheKey);
- echo "data: " . json_encode([
- 'type' => 'timeout',
- 'message' => '轮询超时,请刷新页面查看最新状态',
- 'data' => [
- 'roles' => $roles,
- 'scenes' => $scenes,
- 'props' => $props
- ]
- ], JSON_UNESCAPED_UNICODE) . "\n\n";
- if (ob_get_level() > 0) {
- 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', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
- $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);
- // 余额预检:按预估时长计算所需积分,不足直接报错
- $chargeDuration = (int)ceil((float)$audioDuration);
- if ($chargeDuration <= 0) {
- $chargeDuration = 5; // 无音频时长时按默认5秒预估
- }
- $this->pointsService->checkUserPointsEnough(
- $this->pointsService->getVideoChargePoints([
- 'model' => $model,
- 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
- 'video_duration' => $chargeDuration,
- 'ratio' => $ratio,
- 'generate_audio' => $current_generate_audio,
- ])
- );
- // 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模型(默认)
- // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
- if ($this->isKuaikuaiSeedanceModel($model)) {
- $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
- if ($canUseAudio && $audioUrl) {
- // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
- $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
- $videoParams['reference_audio_assets'] = $reference_audio_assets;
- // 优化提示词,增加音频相关描述
- $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
- $videoParams['prompt'] = $audioPrompt;
- } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
- $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
- }
- $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
- } elseif ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
- // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
- // 添加配音音频到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
- ];
- }
-
- /**
- * 是否为快快AI Seedance 2.0/2.5 系列模型
- * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
- *
- * @param string $model
- * @return bool
- */
- public function isKuaikuaiSeedanceModel(string $model): bool
- {
- return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
- }
- /**
- * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
- *
- * @param string $model
- * @return bool
- */
- public function isBaiduSeedanceModel(string $model): bool
- {
- return in_array($model, [
- 'baidu-doubao-seedance-2-0-260128',
- 'baidu-doubao-seedance-2-0-fast-260128',
- 'baidu-doubao-seedance-2-0-mini-260615',
- 'baidu-doubao-seedance-2-5-260628',
- ], true);
- }
- /**
- * 是否为海外百度Seedance(dreamina真人素材空间)模型
- * 系统内使用 baidu-dreamina- 前缀名,请求网关时映射为 dreamina-* 原名
- *
- * @param string $model
- * @return bool
- */
- public function isOverseasBaiduSeedanceModel(string $model): bool
- {
- return in_array($model, [
- 'baidu-dreamina-seedance-2-0-260128',
- 'baidu-dreamina-seedance-2-0-fast-260128',
- 'baidu-dreamina-seedance-2-0-mini-260615',
- 'baidu-dreamina-seedance-2-5-260628',
- ], true);
- }
- /**
- * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-doubao-* / baidu-dreamina-* / 快快AI seed-2 系列)
- * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
- *
- * @param string $model
- * @return bool
- */
- public function isSeedance20SeriesModel(string $model): bool
- {
- return strpos($model, 'doubao-seedance-2.0') !== false
- || $this->isKuaikuaiSeedanceModel($model)
- || $this->isBaiduSeedanceModel($model)
- || $this->isOverseasBaiduSeedanceModel($model);
- }
- 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');
- $art_style_type = getProp($anime, 'art_style_type');
- $art_style = getProp($anime, 'art_style');
- $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和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
- if (!empty($products) && $episode) {
- // 获取剧集中的角色、场景和道具列表
- $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
- $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
- $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
- $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
-
- // 构建角色名称列表
- $role_names = array_column($roles, 'role');
- // 构建场景名称列表
- $scene_names = array_column($scenes, 'scene');
- // 构建道具名称列表
- $prop_names = array_column($props, 'prop');
-
- // 遍历传入的products
- foreach ($products as $product) {
- $product_name = getProp($product, 'product_name');
-
- // 如果product_name不在roles、scenes和props中
- if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_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'];
- // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
- $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 = 'seed-2';
- }
- }
- // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
- $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
- if (!in_array($model, $valid_models)) {
- $model = 'seed-2';
- }
- // 保存到episode表(仅在专用方法中更新模型)
- // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- // 'video_model' => $model,
- // 'updated_at' => date('Y-m-d H:i:s')
- // ]);
- // 余额预检:按预估时长计算所需积分,不足直接报错
- $chargeDuration = (int)$videoDuration;
- if ($chargeDuration <= 0) {
- $chargeDuration = 5; // 无时长时按默认5秒预估
- }
- $this->pointsService->checkUserPointsEnough(
- $this->pointsService->getVideoChargePoints([
- 'model' => $model,
- 'video_resolution' => strtolower($video_resolution ?? '720p'),
- 'video_duration' => $chargeDuration,
- 'ratio' => $ratio,
- 'generate_audio' => $current_generate_audio,
- ])
- );
-
- // 构建视频生成参数
- $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', 'doubao-seedance-2.0', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-0-260128', 'baidu-dreamina-seedance-2-0-fast-260128', 'baidu-dreamina-seedance-2-0-mini-260615', 'baidu-dreamina-seedance-2-5-260628'])) {
- $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);
-
- // 根据模型选择不同的视频生成方法
- try {
- 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);
- } elseif ($this->isSeedance20SeriesModel($model)) {
- // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
- $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
- $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
- // 保存原始参考图用于任务记录
- $videoParams['reference_images'] = $reference_images;
- if ($reference_images) {
- // 限制只传入9张参考图
- $reference_images = array_slice($reference_images, 0, 9);
- // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
- $videoParams['ref_image_url'] = json_encode($reference_images, 256);
- // 参考图上传为素材(国内百度/海外百度dreamina/快快AI),上传失败时同步清理提示词中的<图片N>标记
- $reference_image_assets = $isKuaikuai
- ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
- : ($isDreamina
- ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $fullPrompt)
- : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt));
- // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
- $videoParams['prompt'] = trim($fullPrompt);
- $videoParams['content'][0]['text'] = trim($fullPrompt);
- $videoParams['reference_image_assets'] = $reference_image_assets;
- }
- // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
- if ($isKuaikuai) {
- $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
- $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
- } else {
- $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
- }
- } else {
- $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
- }
- } catch (ApiException $e) {
- // 上游调用抛出的网关异常统一做友好化处理;本地业务错误(非1001)保持原提示不变
- if ($e->getCode() === 1001) {
- Utils::throwError('1001:' . mapErrorMessage($e->getMessage()));
- }
- throw $e;
- } catch (\Exception $e) {
- // 其他未包装的异常,同样只对报错信息做格式化,便于前端展示友好提示
- Utils::throwError('20003:' . mapErrorMessage($e->getMessage()));
- }
-
- // 更新分镜表的视频任务信息
- 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);
- }
-
- $result = [
- 'task_id' => $task->id,
- 'status' => $task->status,
- 'act_id' => $act_id,
- 'video_duration' => $videoDuration
- ];
- // 仅当任务提交阶段就已失败时,附带格式化后的错误信息;正常返回结构不受影响
- if ($task->status === 'failed' && !empty($task->error_message)) {
- $result['error_message'] = mapErrorMessage($task->error_message);
- }
- return $result;
- }
- /**
- * 文生视频通用方法
- * 支持传入视频参数、提示词、参考图等信息,不支持products入参
- * 用户提示词不做任何处理,直接组装参数后根据模型调用
- *
- * @param array $data 请求参数
- * @return array
- */
- public function generateVideo($data) {
- $prompt = getProp($data, 'prompt');
- if (empty($prompt)) {
- Utils::throwError('20003:提示词不能为空');
- }
- $model = getProp($data, 'model');
- if (!$model) {
- $model = 'seed-2';
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
- $video_duration = getProp($data, 'video_duration', 5);
- // 默认超分720p档(按480p生成后本地超分到720p);480p为原始档需前端显式指定
- $video_resolution = getProp($data, 'video_resolution', 'sr_720p');
- $ratio = getProp($data, 'ratio', '9:16');
- $generate_audio = getProp($data, 'generate_audio', 1);
- $seed = getProp($data, 'seed', -1);
- $first_frame_url = getProp($data, 'first_frame_url');
- $tail_frame_url = getProp($data, 'tail_frame_url');
- // 参考图(支持数组或JSON字符串,最多9张)
- $reference_images = getProp($data, 'reference_images', []);
- if (is_string($reference_images)) {
- $reference_images = json_decode($reference_images, true) ?: [];
- }
- if (!is_array($reference_images)) {
- Utils::throwError('20003:参考图格式不正确');
- }
- $reference_images = array_values(array_unique(array_filter($reference_images)));
- $reference_images = array_slice($reference_images, 0, 9);
- // 参考视频(支持数组或JSON字符串,最多3个)
- $reference_videos = getProp($data, 'reference_videos', []);
- if (is_string($reference_videos)) {
- $reference_videos = json_decode($reference_videos, true) ?: [];
- }
- if (!is_array($reference_videos)) {
- Utils::throwError('20003:参考视频格式不正确');
- }
- $reference_videos = array_values(array_unique(array_filter($reference_videos)));
- if (count($reference_videos) > 3) {
- Utils::throwError('20003:参考视频最多选择3个');
- }
- $reference_videos = array_slice($reference_videos, 0, 3);
- // 参考音频(支持数组或JSON字符串,最多3个)
- $reference_audios = getProp($data, 'reference_audios', []);
- if (is_string($reference_audios)) {
- $reference_audios = json_decode($reference_audios, true) ?: [];
- }
- if (!is_array($reference_audios)) {
- Utils::throwError('20003:参考音频格式不正确');
- }
- $reference_audios = array_values(array_unique(array_filter($reference_audios)));
- if (count($reference_audios) > 3) {
- Utils::throwError('20003:参考音频最多选择3个');
- }
- $reference_audios = array_slice($reference_audios, 0, 3);
- // 余额预检:按预估时长计算所需积分,不足直接报错
- $chargeDuration = (int)ceil((float)$video_duration);
- if ($chargeDuration <= 0) {
- $chargeDuration = 5; // 无时长时按默认5秒预估
- }
- $this->pointsService->checkUserPointsEnough(
- $this->pointsService->getVideoChargePoints([
- 'model' => $model,
- 'video_resolution' => strtolower($video_resolution ?? '720p'),
- 'video_duration' => $chargeDuration,
- 'ratio' => $ratio,
- 'generate_audio' => (int)$generate_audio,
- ])
- );
- // 构建视频生成参数(用户参数直接透传,提示词不做处理)
- $videoParams = [
- 'model' => $model,
- 'prompt' => $prompt,
- 'video_duration' => $video_duration,
- 'video_resolution' => $video_resolution,
- 'seed' => $seed,
- 'ratio' => $ratio,
- 'generate_audio' => (int)$generate_audio === 1 ? true : false,
- 'draft' => getProp($data, 'draft', false),
- 'watermark' => getProp($data, 'watermark', false),
- 'camera_fixed' => getProp($data, 'camera_fixed', false),
- ];
- if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
- if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
- // 构建content数组
- $videoParams['content'] = [
- [
- 'type' => 'text',
- 'text' => $prompt,
- ]
- ];
- // 根据模型选择不同的视频生成方法
- if (strpos($model, 'jimeng') !== false) {
- // 即梦模型参数调整
- unset($videoParams['content']); // 即梦不使用content格式
- $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
- } elseif (strpos($model, 'kling') !== false) {
- // 可灵模型参数调整
- $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
- unset($videoParams['ratio']);
- unset($videoParams['content']); // 可灵不使用content格式
- $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
- } elseif (strpos($model, 'zhizhen') !== false) {
- // 智帧等新模型使用统一API
- $unifiedParams = [
- 'model_code' => $model,
- 'prompt' => $prompt,
- 'video_duration' => $video_duration,
- 'video_resolution' => strtolower($video_resolution),
- 'video_ratio' => $ratio,
- 'seed' => $seed,
- ];
- // 构建parameters参数
- $parameters = [
- 'seconds' => $unifiedParams['video_duration'],
- 'resolution' => $unifiedParams['video_resolution'],
- 'ratio' => $ratio,
- 'generate_audio' => (int)$generate_audio === 1 ? true : false,
- ];
- // 首帧和尾帧
- if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
- if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
- // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
- $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
- if ($refImageUrls) {
- $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
- }
- // 参考图处理
- if ($reference_images) {
- $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
- $parameters['reference_images'] = $reference_images;
- $parameters['video_mode'] = 'multi_image';
- $parameters['mode'] = 'multi_image';
- }
- // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
- if ($reference_videos) {
- $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
- $parameters['reference_videos'] = $reference_videos;
- }
- if ($reference_audios) {
- $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
- $parameters['reference_audios'] = $reference_audios;
- }
- $unifiedParams['parameters'] = $parameters;
- // 调用统一API创建任务
- $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
- } elseif ($this->isSeedance20SeriesModel($model)) {
- // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
- $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
- $isDreamina = $this->isOverseasBaiduSeedanceModel($model);
- $videoParams['reference_images'] = $reference_images;
- // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
- $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
- if ($refImageUrls) {
- $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
- }
- if ($reference_images) {
- // 参考图上传为素材(国内百度/海外百度dreamina/快快AI)
- $reference_image_assets = $isKuaikuai
- ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
- : ($isDreamina
- ? $this->aiVideoGenerationService->processReferenceImagesToBaiduDreaminaAssets($reference_images, $videoParams['prompt'])
- : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']));
- $videoParams['reference_image_assets'] = $reference_image_assets;
- }
- // 参考视频上传为素材(国内百度/海外百度dreamina/快快AI)
- if ($reference_videos) {
- $reference_video_assets = $isKuaikuai
- ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
- : ($isDreamina
- ? $this->aiVideoGenerationService->processReferenceVideosToBaiduDreaminaAssets($reference_videos, $videoParams['prompt'])
- : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']));
- $videoParams['reference_video_assets'] = $reference_video_assets;
- }
- // 参考音频上传为素材(国内百度/海外百度dreamina/快快AI)
- if ($reference_audios) {
- $reference_audio_assets = $isKuaikuai
- ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
- : ($isDreamina
- ? $this->aiVideoGenerationService->processReferenceAudiosToBaiduDreaminaAssets($reference_audios, $videoParams['prompt'])
- : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']));
- $videoParams['reference_audio_assets'] = $reference_audio_assets;
- }
- // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
- if ($reference_images || $reference_videos || $reference_audios) {
- $videoParams['content'][0]['text'] = $videoParams['prompt'];
- }
- // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
- if ($isKuaikuai) {
- $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
- $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
- } else {
- $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
- }
- } else {
- // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
- // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
- $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
- if ($refImageUrls) {
- $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
- }
- if ($reference_videos) {
- foreach ($reference_videos as $videoUrl) {
- $videoParams['content'][] = [
- 'type' => 'video_url',
- 'video_url' => [
- 'url' => $videoUrl,
- ],
- 'role' => 'reference_video',
- ];
- }
- }
- if ($reference_audios) {
- foreach ($reference_audios as $audioUrl) {
- $videoParams['content'][] = [
- 'type' => 'audio_url',
- 'audio_url' => [
- 'url' => $audioUrl,
- ],
- 'role' => 'reference_audio',
- ];
- }
- }
- $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
- }
- return [
- 'task_id' => $task->id,
- 'status' => $task->status,
- 'model' => $model,
- 'video_duration' => $video_duration,
- 'video_resolution' => $video_resolution,
- 'ratio' => $ratio
- ];
- }
- /**
- * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
- *
- * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
- * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
- * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
- *
- * @param array $data
- * @return array
- */
- public function previewCharge(array $data): array
- {
- $mode = (string)getProp($data, 'mode', '');
- if (!in_array($mode, ['chat', 'image', 'video'])) {
- Utils::throwError('1003:请传入mode参数(chat/image/video)');
- }
- // 视频计费场景(video_generation/video_to_video),默认视频生成
- $scene = (string)getProp($data, 'scene', 'video_generation');
- // 未显式传scene且带参考视频时,自动按video_to_video定价
- if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
- $scene = 'video_to_video';
- }
- $items = [];
- $model = '';
- $resolution = '';
- if ($mode === 'video') {
- // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
- $model = (string)getProp($data, 'model', '');
- if (!$model) {
- Utils::throwError('1002:model参数不能为空');
- }
- $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
- $duration = (int)getProp($data, 'video_duration', 5);
- if ($duration <= 0) {
- $duration = 5;
- }
- $count = max(1, (int)getProp($data, 'count', 1));
- $pointsPerVideo = $this->pointsService->getVideoChargePoints([
- 'model' => $model,
- 'video_resolution' => $resolution,
- 'video_duration' => $duration,
- 'mode' => $scene,
- ]);
- $points = $pointsPerVideo * $count;
- $items[] = [
- 'type' => 'video',
- 'model' => $model,
- 'video_resolution' => $resolution,
- 'video_duration' => $duration,
- 'count' => $count,
- 'points' => $points,
- ];
- } elseif ($mode === 'image') {
- // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
- $model = (string)getProp($data, 'model', '');
- if (!$model) {
- Utils::throwError('1002:model参数不能为空');
- }
- $resolution = strtolower((string)getProp($data, 'resolution', ''));
- if (!$resolution) {
- $width = (int)getProp($data, 'width', 0);
- $height = (int)getProp($data, 'height', 0);
- if ($width <= 0 || $height <= 0) {
- $width = 1600;
- $height = 2848;
- }
- $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
- }
- $imageNum = max(1, (int)getProp($data, 'image_num', 1));
- $points = $this->pointsService->getImageChargePoints([
- 'model' => $model,
- 'resolution' => $resolution,
- ]) * $imageNum;
- $items[] = [
- 'type' => 'image',
- 'model' => $model,
- 'resolution' => $resolution,
- 'image_num' => $imageNum,
- 'points' => $points,
- ];
- } else {
- // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
- // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
- $priceType = (string)getProp($data, 'price_type', 'special');
- if (!in_array($priceType, ['special', 'normal'], true)) {
- Utils::throwError('1003:price_type参数仅支持special或normal');
- }
- $count = max(1, (int)getProp($data, 'count', 1));
- $animeId = getProp($data, 'anime_id');
- $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
- if ($animeId && $generateEpisodes > 0) {
- // 批量生成分集按 special 档预估,与实际扣费口径一致
- $priceType = 'special';
- $currentMaxEpisode = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('is_default', 1)
- ->max('episode_number');
- $currentMaxEpisode = $currentMaxEpisode ?: 0;
- $startEpisodeNumber = $currentMaxEpisode + 1;
- $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
- $existingSkipped = DB::table('mp_batch_episode_generation_details')
- ->where('anime_id', $animeId)
- ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
- ->whereIn('status', ['pending', 'processing', 'completed'])
- ->count();
- $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
- if ($count < 0) {
- $count = 0;
- }
- }
- $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
- $items[] = [
- 'type' => 'chat',
- 'count' => $count,
- 'price_type' => $priceType,
- 'points' => $points,
- ];
- }
- $totalPoints = 0;
- foreach ($items as $item) {
- $totalPoints += $item['points'];
- }
- return [
- 'mode' => $mode,
- 'total_points' => $totalPoints,
- 'items' => $items,
- 'points_balance' => $this->pointsService->getUserPointsBalance(),
- 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
- ];
- }
- /**
- * 根据提示词内容智能计算最优视频时长
- *
- * @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' => '任务执行超时,请稍后查询任务状态'
- ];
- }
- /**
- * 根据 inner_prompt_type 附加内置提示词
- *
- * @param string $prompt 用户提示词
- * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
- * @return string 合并后的提示词
- */
- public static function appendInnerPrompt($prompt, $innerPromptType = 0)
- {
- $innerPromptMap = [
- 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。',
- 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
- ];
- if (!isset($innerPromptMap[$innerPromptType])) {
- return $prompt;
- }
- return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
- }
- /**
- * 根据 inner_prompt_type 获取生成图片数量
- *
- * @param int $innerPromptType 内置提示词类型
- * @param int $imageNum 传入的图片张数
- * @return int 图片数量
- */
- public static function getInnerImageNum($innerPromptType = 0, $imageNum)
- {
- return (int)$innerPromptType === 2 ? 9 : $imageNum;
- }
- /**
- * 提取图片生成结果URL
- *
- * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
- * @param int $innerPromptType 内置提示词类型
- * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
- */
- public static function extractResultUrls($resultUrl, $innerPromptType = 0)
- {
- $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
- if (is_array($resultUrls) && !empty($resultUrls)) {
- $resultUrls = array_values($resultUrls);
- return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
- }
- if (!empty($resultUrl)) {
- return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
- }
- return (int)$innerPromptType === 2 ? [] : '';
- }
- public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
- $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');
- $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
- $imageNum = (int)getProp($data, 'image_num', 1);
-
- // 分辨率档位与尺寸映射统一从 BaseConst 获取
- $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
-
- // 参数验证
- $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 = 'gpt-image-2';
- }
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- // $model = 'gpt-image-2';
- 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:请提供提示词');
- // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
- $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
- $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
- try {
- // 创建图片生成任务
- $params = [
- 'prompt' => $prompt,
- 'model' => $model,
- 'ref_img_urls' => '',
- 'width' => $width,
- 'height' => $height,
- 'image_num' => $imageNum,
- // 计费锚点(动漫/剧集/剧本),上下文没有时不记录
- 'anime_id' => getProp($data, 'anime_id'),
- 'episode_id' => $episode_id,
- ];
- 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:创建图片生成任务失败');
- }
- // 创建任务中心记录并关联图片任务ID
- $taskCenter = $this->taskCenterService->createTask('image', [
- 'title' => '文生图',
- 'ref_task_id' => $task_id,
- // 'prompt' => $prompt,
- // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
- ]);
- $taskCenterId = $taskCenter->id;
- // 组装本次任务信息(用于init消息,类似generateVideo)
- $taskInfo = [
- 'task_id' => $task_id,
- 'status' => getProp($task, 'status', 'processing'),
- 'model' => $model,
- 'ratio' => $ratio,
- 'resolution' => $resolution,
- 'image_num' => $imageNum,
- ];
- // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
- if (is_callable($onTaskCreated)) {
- $onTaskCreated($taskCenterId, $taskInfo);
- }
- // 检查任务模型类型(火山模型和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;
- // 任务需要轮询获取结果(15分钟超时,每3秒查询一次)
- $start_time = time();
- $timeout = 900; // 15分钟
- $img_url = '';
- $img_urls = [];
- $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
- $queueMessageInterval = 60; // 队列消息发送间隔(秒)
-
- while (time() - $start_time < $timeout) {
- sleep(3);
- // 每分钟发送一次队列状态消息(仅流式模式)
- if (is_callable($onPoll)) {
- $currentTime = time();
- if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
- $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
- $lastQueueMessageTime = $currentTime;
- }
- }
- // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
- if ($isSyncModel) {
- // 刷新任务状态
- $task = MpGeneratePicTask::where('id', $task_id)->first();
-
- if ($task->status === 'success' && $task->result_url) {
- $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
- $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
- if (!empty($resultUrls)) {
- $img_urls = $resultUrls;
- $img_url = $resultUrls[0];
- } else {
- $img_url = (string)$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'] ?? []
- ]);
-
- $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
- $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
- if (!empty($resultUrls)) {
- $img_urls = $resultUrls;
- $img_url = $resultUrls[0];
- } else {
- $img_url = (string)$statusInfo['result_url'];
- }
- 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:图片生成超时,请稍后重试');
- }
-
- // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
- if (count($img_urls) > 1) {
- return [
- 'img_url' => $img_url,
- 'image_urls' => $img_urls,
- 'task_id' => $taskCenterId,
- ];
- }
-
- return [
- 'img_url' => $img_url,
- 'task_id' => $taskCenterId,
- ];
-
- } 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' => [],
- // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'episode_number' => getProp($episode, 'episode_number'),
- ];
-
- $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' => [],
- // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
- 'anime_id' => $anime_id,
- 'episode_id' => $episode_id,
- 'episode_number' => getProp($episode, 'episode_number'),
- ];
-
- $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);
-
- // 仅记录 token 使用明细(不扣积分)
- $uid = 0;
- try {
- $uid = (int)Site::getUid();
- } catch (\Throwable $e) {
- // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
- }
- $this->pointsService->recordTokenOnlyDetail(
- $uid,
- $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
- [
- 'model' => $model,
- 'img_url' => $img_url,
- 'source' => 'generateImagePromptFromUrl',
- ],
- 'chat',
- $model,
- ''
- );
- // 返回生成的内容
- 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(搜索关键词)、is_public(筛选类型)
- * @return array 返回当前目录下的所有子目录和角色列表(递归)
- */
- public function globalProducts($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $role = Site::getRole();
- $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.道具
- $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
-
- if (!$product) {
- Utils::throwError('20003:请选择产品类型');
- }
-
- // 根据角色和is_public参数确定查询范围
- // admin角色:获取所有个人库+公共库(忽略is_public参数)
- // user角色:根据is_public参数筛选
- $query_user_ids = [];
- if ($role === 'admin') {
- // admin获取所有个人库和公共库
- $query_user_ids = [$uid, 0];
- } else {
- // user角色根据is_public参数筛选
- if ($is_public == 2) {
- // 个人库+公共库
- $query_user_ids = [$uid, 0];
- } elseif ($is_public == 0) {
- // 仅个人库
- $query_user_ids = [$uid];
- } elseif ($is_public == 1) {
- // 仅公共库
- $query_user_ids = [0];
- }
- }
-
- // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
- if ($id || $product_name) {
- $query = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->whereIn('user_id', $query_user_ids)
- ->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', 'timbre_url', 'versions', 'product', 'user_id', 'created_at')
- ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, 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['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
- $value['timbre_url'] = $value['timbre_url'] ?? '';
- $value['versions'] = json_decode($value['versions'], true) ?: [];
- unset($value['user_id']);
- return $value;
- })
- ->toArray();
-
- return $result;
- }
-
- // 递归获取所有子目录和角色
- return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
- }
-
- /**
- * 递归获取指定目录下的所有子目录和角色
- * @param int $cpid 公司ID
- * @param int $parent_id 父目录ID
- * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
- * @param array $query_user_ids 用户ID数组(支持多个)
- * @param int $current_uid 当前用户ID(用于排序)
- * @return array
- */
- private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
- // 查询当前层级的所有项(文件夹和角色)
- $query = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('is_deleted', 0)
- ->where('parent_id', $parent_id);
-
- // 添加用户ID验证(支持多个user_id)
- if (!empty($query_user_ids)) {
- $query->whereIn('user_id', $query_user_ids);
- }
-
- // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
- if ($product) {
- $query->where('product', $product);
- }
-
- // 排序规则:
- // 1. 文件夹在前(type DESC)
- // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
- // 3. 其他排序规则
- $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'timbre_url', 'versions', 'product', 'user_id', 'created_at')
- ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, 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,
- 'timbre_url' => $item->timbre_url ?? '',
- 'product' => (int)($item->product ?? 1),
- 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
- '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, $query_user_ids, $current_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();
- $role = Site::getRole();
- $parent_id = getProp($data, 'parent_id', 0);
- $folder_name = getProp($data, 'product_name', '新建文件夹');
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- // 如果是公共库操作,需要admin权限
- if ($is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能操作公共资产库');
- }
-
- // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
- $store_uid = $is_public ? 0 : $uid;
-
- // 获取 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('cpid', $cpid)
- ->where('user_id', $store_uid)
- ->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('cpid', $cpid)
- ->where('user_id', $store_uid)
- ->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' => $store_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();
- $role = Site::getRole();
- $id = getProp($data, 'id');
- $new_name = getProp($data, 'product_name');
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- if (!$id || !$new_name) {
- Utils::throwError('20003:参数不完整');
- }
-
- // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
- $query_uid = $is_public ? 0 : $uid;
-
- // 如果是公共库操作,需要admin权限
- if ($is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能操作公共资产库');
- }
-
- // 检查是否存在
- $item = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$item) {
- Utils::throwError('20003:项目不存在');
- }
-
- return DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->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) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $role = Site::getRole();
- $id = getProp($data, 'id');
- $target_parent_id = getProp($data, 'target_parent_id', 0);
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- if (!$id) {
- Utils::throwError('20003:请选择要移动的项目');
- }
-
- // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
- $query_uid = $is_public ? 0 : $uid;
-
- // 如果是公共库操作,需要admin权限
- if ($is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能操作公共资产库');
- }
-
- // 检查要移动的项目
- $item = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->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('user_id', $query_uid)
- ->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) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $folder_id = getProp($data, 'id', 0);
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- if ($folder_id == 0) {
- return [
- ['id' => 0, 'name' => '根目录']
- ];
- }
-
- // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
- $query_uid = $is_public ? 0 : $uid;
-
- $path = [];
- $current_id = $folder_id;
-
- while ($current_id > 0) {
- $folder = DB::table('mp_products')
- ->where('id', $current_id)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->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();
- $role = Site::getRole();
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- // 如果是公共库操作,需要admin权限
- if ($is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能操作公共资产库');
- }
-
- // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
- $store_uid = $is_public ? 0 : $uid;
-
- // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
- $script_id = (int)getProp($data, 'script_id', 0);
- $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
- if ($script_id && empty($episode_numbers)) {
- Utils::throwError('20003:剧集序号不能为空');
- }
- if (!$script_id && !empty($episode_numbers)) {
- Utils::throwError('20003:请提供剧本ID');
- }
-
- $product_name = trim(getProp($data, 'product_name'));
- if (!$product_name) Utils::throwError('20003:名称不能为空');
- $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $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) 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 格式');
- }
- // 选填三视图图片地址,格式校验与 url 一致
- $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
- if ($three_view_image_url) {
- $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
- $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
- if (!in_array($threeViewExtension, $allowedExtensions)) {
- Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
- }
- }
- // 选填音色音频地址(兼容 timbre_url/audio_url/timbre 传参)
- $timbre_url = $this->getProductTimbreUrl($data);
- if ($timbre_url) {
- $this->validateProductAudioUrl($timbre_url);
- }
- $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('user_id', $store_uid)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$parent) {
- Utils::throwError('20003:父文件夹不存在');
- }
-
- $parent_level = $parent->level;
- }
- // 创建资产并保存剧本资产关联关系(同一事务)
- DB::beginTransaction();
- try {
- $id = DB::table('mp_products')->insertGetId([
- 'user_id' => $store_uid,
- 'cpid' => $cpid,
- 'type' => 1, // 1=角色图片
- 'parent_id' => $parent_id,
- 'level' => $parent_level + 1,
- 'product_name' => $product_name,
- 'url' => $url,
- 'three_view_image_url' => $three_view_image_url,
- 'timbre_url' => $timbre_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:创建失败');
-
- // 保存剧本资产关联关系
- if ($script_id) {
- $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
- }
-
- DB::commit();
- } catch (\Exception $e) {
- DB::rollback();
- throw $e;
- }
-
- return [
- 'id' => $id,
- 'type' => 1,
- 'parent_id' => $parent_id,
- 'level' => $parent_level + 1,
- 'product_name' => $product_name,
- 'url' => $url,
- 'three_view_image_url' => $three_view_image_url,
- 'timbre_url' => $timbre_url,
- 'pic_prompt' => $pic_prompt,
- 'product' => $product,
- 'versions' => $versions
- ];
- }
- public function editProduct($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $role = Site::getRole();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:ID不能为空');
- $versions = getProp($data, 'versions');
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
- $script_id = (int)getProp($data, 'script_id', 0);
- $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
- if ($script_id && empty($episode_numbers)) {
- Utils::throwError('20003:剧集序号不能为空');
- }
- if (!$script_id && !empty($episode_numbers)) {
- Utils::throwError('20003:请提供剧本ID');
- }
-
- // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
- $query_uid = $is_public ? 0 : $uid;
-
- // 如果是公共库操作,需要admin权限
- if ($is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能操作公共资产库');
- }
-
- // 检查是否存在且属于当前用户或公共库
- $role = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->where('type', 1)->first();
- if (!$role) Utils::throwError('20003:记录不存在');
-
- $updateData = [];
- // $needVersionRecord = false; // 是否需要记录版本
-
- // 名称
- $product_name = trim(getProp($data, 'product_name'));
- if ($product_name) {
- $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $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:名称不能重复,请修改');
-
- // 图片地址
- $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
- $url = trim(getProp($data, 'url'));
- if ($url) {
- // 检查是否是正确的图片格式
- $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;
- }
- // 三视图图片地址(选填),格式校验与 url 一致;显式传空表示当前版本没有三视图
- $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
- if ($three_view_image_url) {
- $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
- $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
- if (!in_array($threeViewExtension, $allowedExtensions)) {
- Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
- }
- }
- // 显式传入三视图(含空值)时同步写入,空值表示当前版本没有三视图
- if (array_key_exists('three_view_image_url', $data)) {
- $updateData['three_view_image_url'] = $three_view_image_url;
- }
- // 音色音频地址(选填,显式传空字符串可清除已有音色)
- if (array_key_exists('timbre_url', $data) || array_key_exists('audio_url', $data) || array_key_exists('timbre', $data)) {
- $timbre_url = $this->getProductTimbreUrl($data);
- if ($timbre_url) {
- $this->validateProductAudioUrl($timbre_url);
- }
- $updateData['timbre_url'] = $timbre_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;
- }else {
- Utils::throwError('20003:请输入提示词');
- }
-
- if (empty($updateData) && !$script_id) {
- 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);
- }
-
- if (!empty($updateData)) {
- $updateData['updated_at'] = date('Y-m-d H:i:s');
- }
-
- // 更新资产并保存剧本资产关联关系(同一事务)
- DB::beginTransaction();
- try {
- $updated = true;
- if (!empty($updateData)) {
- $updated = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('id', $id)
- ->update($updateData);
- }
-
- // 保存剧本资产关联关系
- if ($script_id) {
- $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
- }
-
- DB::commit();
- } catch (\Exception $e) {
- DB::rollback();
- throw $e;
- }
-
- return $updated;
- }
- /**
- * 获取资产音色音频地址
- * 兼容 timbre_url/audio_url/timbre 三种传参,timbre 支持字符串或 {"url":"..."} 结构
- *
- * @param array $data
- * @return string
- */
- private function getProductTimbreUrl($data) {
- foreach (['timbre_url', 'audio_url', 'timbre'] as $key) {
- if (!array_key_exists($key, $data)) {
- continue;
- }
- $value = $data[$key];
- if (is_array($value)) {
- $value = getProp($value, 'url', $value[0] ?? '');
- }
- if (!is_string($value)) {
- continue;
- }
- return trim($value);
- }
- return '';
- }
- /**
- * 校验资产音色音频地址格式
- *
- * @param string $url 音频地址
- * @return void
- */
- private function validateProductAudioUrl($url) {
- $allowedExtensions = ['mp3', 'wav', 'm4a', 'aac', 'ogg', 'oga', 'flac', 'amr', 'wma', 'weba'];
- $urlPath = parse_url($url, PHP_URL_PATH);
- $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
- if (!in_array($extension, $allowedExtensions)) {
- Utils::throwError('20003:音色音频格式不正确,仅支持 mp3、wav、m4a、aac、ogg、flac、amr、wma 格式');
- }
- }
-
- /**
- * 保存单一资产与剧本剧集的关联关系
- *
- * @param int $product_id 资产ID
- * @param int $script_id 剧本ID
- * @param array $episode_numbers 剧集序号数组(序号从1开始)
- * @return int 新增关联数量
- */
- private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
- $uid = Site::getUid();
-
- // 验证剧本是否存在
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$script) {
- Utils::throwError('20003:剧本不存在');
- }
-
- // 验证剧本归属:只能关联自己的剧本
- if ((int)$script->user_id !== (int)$uid) {
- Utils::throwError('20003:只能添加到自己的剧本');
- }
-
- // 使用 splitContent 拆分剧本内容获取总集数
- $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
-
- // 解析剧集序号(数组)
- $episodes = [];
- foreach ($episode_numbers as $item) {
- if (is_array($item)) {
- continue;
- }
- $item = trim((string)$item);
- if ($item === '' || !is_numeric($item)) {
- Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
- }
- $episodes[] = (int)$item;
- }
-
- // 去重并校验序号范围(序号从1开始)
- $episodes = array_values(array_unique($episodes));
- if (empty($episodes)) {
- Utils::throwError('20003:剧集序号不能为空');
- }
-
- foreach ($episodes as $episode) {
- if ($episode < 1 || $episode > $totalEpisodes) {
- Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
- }
- }
-
- $now = now();
-
- // 过滤已存在的关联,避免重复
- $existingEpisodes = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->where('product_id', $product_id)
- ->whereIn('episode_number', $episodes)
- ->pluck('episode_number')
- ->all();
-
- $mappingRecords = [];
- foreach ($episodes as $episode) {
- if (in_array($episode, $existingEpisodes)) {
- continue;
- }
- $mappingRecords[] = [
- 'script_id' => $script_id,
- 'product_id' => $product_id,
- 'episode_number' => $episode,
- 'created_at' => $now,
- 'updated_at' => $now,
- ];
- }
-
- $insertedCount = 0;
- if (!empty($mappingRecords)) {
- $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
- }
-
- return $insertedCount;
- }
-
- /**
- * 规范化剧集序号参数,统一为数组
- * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
- *
- * @param mixed $episode_number 剧集序号参数
- * @return array
- */
- private function normalizeEpisodeNumbers($episode_number) {
- if (!is_array($episode_number)) {
- $episode_number = explode(',', (string)$episode_number);
- }
-
- $items = [];
- foreach ($episode_number as $item) {
- if (is_array($item)) {
- continue;
- }
- foreach (explode(',', (string)$item) as $part) {
- $part = trim($part);
- if ($part !== '') {
- $items[] = $part;
- }
- }
- }
-
- return $items;
- }
-
- /**
- * 获取剧本总集数(通过 splitContent 拆分剧本内容)
- *
- * @param object $script 剧本记录
- * @return int 总集数
- */
- private function getScriptTotalEpisodeCount($script) {
- if (empty($script->content)) {
- Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
- }
-
- $totalEpisodes = count(splitContent($script->content));
- if ($totalEpisodes < 1) {
- Utils::throwError('20003:剧本内容无法拆分出剧集');
- }
-
- return $totalEpisodes;
- }
-
- /**
- * 获取剧本总集数
- *
- * @param array $data 包含 script_id(剧本ID)
- * @return array
- */
- public function getScriptTotalEpisodes($data) {
- $script_id = (int)getProp($data, 'script_id', 0);
- 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:剧本不存在');
- }
-
- return [
- 'script_id' => $script_id,
- 'script_name' => $script->script_name ?? 'script_' . $script_id,
- 'episode_num' => $this->getScriptTotalEpisodeCount($script),
- ];
- }
-
- /**
- * 获取角色版本历史
- * @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();
- $role = Site::getRole();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:ID不能为空');
- $ids = explode(',', $id);
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
- $query_uid = $is_public ? 0 : $uid;
-
- // 如果是公共库操作,需要admin权限
- if ($is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能操作公共资产库');
- }
-
- // 检查是否存在且属于当前用户或公共库
- $role = DB::table('mp_products')
- ->whereIn('id', $ids)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->get();
- if (!$role) Utils::throwError('20003:记录不存在');
-
- return DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->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();
- $role = Site::getRole();
- $id = getProp($data, 'id');
- if (!$id) Utils::throwError('20003:ID不能为空');
- $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
-
- // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
- $query_uid = $is_public ? 0 : $uid;
-
- // 如果是公共库操作,需要admin权限
- if ($is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能操作公共资产库');
- }
-
- // 检查是否存在且属于当前用户或公共库
- $product = DB::table('mp_products')
- ->where('id', $id)
- ->where('cpid', $cpid)
- ->where('user_id', $query_uid)
- ->where('type', 1)->first();
- if (!$product) Utils::throwError('20003:资产不存在');
-
- $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,特写大小为标准一寸照,人物不要带表情。右侧是全身的三视图,其中正面、侧面的三视图给人脸打白色码、不显示五官。主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字。'));
- $ref_img_url = trim(getProp($data, 'ref_img_url'));
- if (!$ref_img_url) {
- // 如果没有传入参考图,使用角色表中的图片
- $ref_img_url = $product->url ?? '';
- if (!$ref_img_url) {
- Utils::throwError('20003:参考图不能为空');
- }
- }
- $pic_prompt = getProp($product, 'pic_prompt');
- if ($pic_prompt) {
- $prompt .= '\n参考图原始提示词: '.$pic_prompt;
- }
-
- // 检查参考图是否是正确的图片格式
- $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 = 'gpt-image-2';
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
- $ratio = getProp($data, 'ratio', '16:9');
- $resolution = getProp($data, 'resolution', '2k');
- // 分辨率档位与尺寸映射统一从 BaseConst 获取
- $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
-
- // 参数验证
- $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'];
-
- try {
- // 创建图片生成任务
- $params = [
- 'prompt' => $prompt,
- 'model' => $model,
- 'ref_img_urls' => [$ref_img_url],
- 'width' => $width,
- 'height' => $height
- ];
-
- $task = $this->aiImageGenerationService->createImageGenerationTask($params);
- $task_id = $task->id;
-
- if (!$task_id) {
- Utils::throwError('20003:创建图片生成任务失败');
- }
- // 轮询获取结果
- // 只查询数据库,不调用API,不更新任务表
- $start_time = time();
- $timeout = 1800;
- $img_url = '';
-
- while (time() - $start_time < $timeout) {
- sleep(5);
- // 只查询数据库中的任务状态,不调用API,不更新任务表
- $task = DB::table('mp_generate_pic_tasks')
- ->where('id', $task_id)
- ->first();
-
- if (!$task) {
- Utils::throwError('20003:任务不存在');
- }
-
- if ($task->status === 'success' && $task->result_url) {
- $result_urls = is_string($task->result_url)
- ? json_decode($task->result_url, true)
- : $task->result_url;
- $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
- break;
- } elseif ($task->status === 'failed') {
- Utils::throwError('20003:三视图生成失败,' . ($task->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 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
- * @return array 返回推送结果
- */
- public function pushProductOrFolder($data) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $role = Site::getRole();
- $product_id = getProp($data, 'product_id');
- $target_parent_id = getProp($data, 'target_parent_id', 0);
- $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
-
- if (!$product_id) {
- Utils::throwError('20003:请选择要推送的项目');
- }
-
- // 查询源项目(只通过cpid查询,不限制user_id)
- $sourceItem = DB::table('mp_products')
- ->where('id', $product_id)
- ->where('cpid', $cpid)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$sourceItem) {
- Utils::throwError('20003:要推送的项目不存在');
- }
-
- // 通过user_id判断源是公共库还是个人库
- $source_uid = $sourceItem->user_id;
- $source_is_public = ($source_uid == 0) ? 1 : 0;
-
- // 验证目标文件夹并确定目标是公共库还是个人库
- $target_level = 0;
- $target_uid = $uid; // 默认推送到个人库
- $target_is_public = 0;
- $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
-
- if ($target_parent_id > 0) {
- // 查询目标文件夹(只通过cpid查询,不限制user_id)
- $targetParent = DB::table('mp_products')
- ->where('id', $target_parent_id)
- ->where('cpid', $cpid)
- ->where('type', 2)
- ->where('is_deleted', 0)
- ->first();
-
- if (!$targetParent) {
- Utils::throwError('20003:目标文件夹不存在');
- }
-
- // 通过user_id判断目标是公共库还是个人库
- $target_level = $targetParent->level;
- $target_uid = $targetParent->user_id;
- $target_is_public = ($target_uid == 0) ? 1 : 0;
-
- // 使用目标文件夹的 product 类型
- $final_product_type = $targetParent->product;
- }
- // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
- else {
- $push_to_public = getProp($data, 'push_to_public');
- if ($push_to_public === '') {
- Utils::throwError('20003:请选择是否推送到公共库');
- }
- if ($push_to_public) {
- $target_uid = 0;
- $target_is_public = 1;
- }
-
- // 推送到根目录时,必须指定 product 类型
- if ($target_product === null || $target_product === '') {
- Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
- }
- $final_product_type = $target_product;
- }
-
- // 如果目标是公共库,需要admin权限
- if ($target_is_public && $role !== 'admin') {
- Utils::throwError('20003:只有管理员才能推送到公共资产库');
- }
-
- // 权限验证:验证是否符合允许的推送规则
- $this->validatePushPermission($source_uid, $target_uid, $uid);
-
- try {
- DB::beginTransaction();
-
- // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
- if ($sourceItem->type == 1) {
- $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
- DB::commit();
- return [
- 'product_id' => $newId,
- ];
- }
-
- // 如果是文件夹,递归复制(支持跨类型推送)
- $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
-
- DB::commit();
- return [
- 'product_id' => $newFolderId,
- ];
-
- } catch (\Exception $e) {
- DB::rollBack();
- dLog('anime')->error('推送失败', [
- 'error' => $e->getMessage(),
- 'product_id' => $product_id
- ]);
- Utils::throwError('20003:' . $e->getMessage());
- }
- }
-
- /**
- * 验证推送权限
- * 允许的推送规则:
- * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
- * 2. 公共库推送给自己的个人库(公共库 → 个人库)
- * 3. 公共库推送给公共库(公共库 → 公共库)
- *
- * @param int $source_uid 源的user_id
- * @param int $target_uid 目标的user_id
- * @param int $current_uid 当前用户ID
- * @throws \Exception
- */
- private function validatePushPermission($source_uid, $target_uid, $current_uid) {
- // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
- if ($source_uid == $current_uid && $target_uid == $current_uid) {
- return; // 允许
- }
-
- // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
- if ($source_uid == 0 && $target_uid == $current_uid) {
- return; // 允许
- }
-
- // 规则3:公共库推送给公共库(公共库 → 公共库)
- if ($source_uid == 0 && $target_uid == 0) {
- return; // 允许
- }
-
- // 其他情况都不允许
- if ($source_uid != 0 && $source_uid != $current_uid) {
- // 源是别人的个人库
- Utils::throwError('20003:无权限访问该资产');
- } elseif ($source_uid == $current_uid && $target_uid == 0) {
- // 个人库推送给公共库(不允许)
- Utils::throwError('20003:不允许将个人资产推送到公共库');
- } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
- // 不同用户的个人库之间推送(不允许)
- Utils::throwError('20003:不允许推送到其他用户的个人库');
- } else {
- // 其他未知情况
- Utils::throwError('20003:不允许的推送操作');
- }
- }
-
- /**
- * 复制单个资产
- * @param object $sourceProduct 源资产对象
- * @param int $targetParentId 目标父文件夹ID
- * @param int $targetLevel 目标层级
- * @param int $cpid 公司ID
- * @param int $targetUid 目标用户ID
- * @return int 返回新资产ID
- */
- private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
- // 如果指定了 productType,使用指定的;否则使用源的 product 类型
- $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
-
- $newProductData = [
- 'user_id' => $targetUid,
- 'cpid' => $cpid,
- 'type' => 1,
- 'parent_id' => $targetParentId,
- 'level' => $targetLevel,
- 'product_name' => $sourceProduct->product_name,
- 'url' => $sourceProduct->url,
- 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
- 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
- 'product' => $finalProductType,
- 'versions' => $sourceProduct->versions ?? '',
- '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 DB::table('mp_products')->insertGetId($newProductData);
- }
-
- /**
- * 递归复制文件夹及其子项
- * @param object $sourceFolder 源文件夹对象
- * @param int $targetParentId 目标父文件夹ID
- * @param int $targetLevel 目标层级
- * @param int $cpid 公司ID
- * @param int $targetUid 目标用户ID
- * @param int $sourceUid 源用户ID
- * @return int 返回新文件夹ID
- */
- private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
- // 如果指定了 productType,使用指定的;否则使用源的 product 类型
- $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
-
- // 创建新文件夹
- $newFolderData = [
- 'user_id' => $targetUid,
- 'cpid' => $cpid,
- 'type' => 2,
- 'parent_id' => $targetParentId,
- 'level' => $targetLevel,
- 'product_name' => $sourceFolder->product_name,
- 'product' => $finalProductType,
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'created_at' => date('Y-m-d H:i:s'),
- 'updated_at' => date('Y-m-d H:i:s')
- ];
-
- $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
-
- // 获取源文件夹下的所有子项
- $children = DB::table('mp_products')
- ->where('parent_id', $sourceFolder->id)
- ->where('cpid', $cpid)
- ->where('user_id', $sourceUid)
- ->where('is_deleted', 0)
- ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
- ->get();
-
- // 递归复制子项(子项继承目标文件夹的 product 类型)
- foreach ($children as $child) {
- if ($child->type == 1) {
- // 资产
- $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
- } else {
- // 文件夹
- $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
- }
- }
-
- return $newFolderId;
- }
- /**
- * 转让剧本归属(剧本及其关联资产)
- *
- * 仅调整 mp_scripts.user_id 与 mp_products.user_id,其他表保持不变。
- * 权限:仅 admin / superadmin 可操作;目标用户必须是同组(cpid 相同)且角色为 user(组员)的用户,禁止跨组转让。
- * 多个剧本逐个独立事务处理,单个剧本失败不影响其他剧本;
- * 单个剧本内的剧本记录与关联资产必须全部更新成功,否则整体回滚。
- *
- * @param array $data 请求参数:script_ids(数组或英文逗号分隔,兼容单个 script_id)、target_user_id
- * @return array
- */
- public function transferScriptOwner($data) {
- $operatorRole = Site::getRole();
- $operatorCpid = Site::getCpid();
- // 1.权限校验:仅管理员和超管可操作
- if (!in_array($operatorRole, ['admin', 'superadmin'], true)) {
- Utils::throwError(ErrorConst::NOT_ACCESS);
- }
- // 2.目标用户校验:必须存在且角色为 user(组员)
- $targetUserId = (int)getProp($data, 'target_user_id', 0);
- if ($targetUserId < 1) {
- Utils::throwError('1002:请选择转让的目标用户');
- }
- $targetUser = DB::table('mp_manage_users')
- ->where('id', $targetUserId)
- ->where('is_deleted', 0)
- ->first();
- if (!$targetUser) {
- Utils::throwError('20003:目标用户不存在');
- }
- if ((string)getProp($targetUser, 'role') !== 'user') {
- Utils::throwError('20003:只能转让给角色为组员(user)的用户');
- }
- $targetCpid = (int)getProp($targetUser, 'cpid');
- // 3.规范化剧本ID列表(兼容数组、逗号分隔字符串、script_id 单值)
- $rawScriptIds = getProp($data, 'script_ids');
- if (empty($rawScriptIds)) {
- $rawScriptIds = getProp($data, 'script_id');
- }
- $scriptIds = $this->normalizeIdList($rawScriptIds);
- if (empty($scriptIds)) {
- Utils::throwError('20003:请提供剧本ID');
- }
- // 预取剧本名称,便于失败结果中回显
- $scriptNameMap = DB::table('mp_scripts')
- ->whereIn('id', $scriptIds)
- ->pluck('script_name', 'id')
- ->all();
- $successList = [];
- $failedList = [];
- // 4.逐个剧本独立事务处理,单个失败不影响其他剧本
- foreach ($scriptIds as $scriptId) {
- DB::beginTransaction();
- try {
- $successList[] = $this->transferSingleScriptOwner(
- $scriptId,
- $targetUserId,
- $targetCpid,
- $operatorRole,
- $operatorCpid,
- Site::getUid()
- );
- DB::commit();
- } catch (\Throwable $e) {
- DB::rollBack();
- $failedList[] = [
- 'script_id' => (int)$scriptId,
- 'script_name' => (string)($scriptNameMap[$scriptId] ?? ''),
- 'reason' => $e->getMessage() !== '' ? $e->getMessage() : '转让失败',
- ];
- dLog('anime')->error('剧本归属转让失败', [
- 'script_id' => $scriptId,
- 'target_user_id' => $targetUserId,
- 'operator_uid' => Site::getUid(),
- 'error' => $e->getMessage(),
- ]);
- }
- }
- return [
- 'target_user_id' => $targetUserId,
- 'success_count' => count($successList),
- 'failed_count' => count($failedList),
- 'success_list' => $successList,
- 'failed_list' => $failedList,
- ];
- }
- /**
- * 单个剧本的归属转让(需在事务中调用)
- *
- * @param int $scriptId 剧本ID
- * @param int $targetUserId 目标用户ID
- * @param int $targetCpid 目标用户所属公司ID
- * @param string $operatorRole 操作人角色
- * @param int $operatorCpid 操作人所属公司ID
- * @param int $operatorUid 操作人用户ID
- * @return array
- */
- private function transferSingleScriptOwner($scriptId, $targetUserId, $targetCpid, $operatorRole, $operatorCpid, $operatorUid) {
- $script = DB::table('mp_scripts')
- ->where('id', $scriptId)
- ->where('is_deleted', 0)
- ->first();
- if (!$script) {
- Utils::throwError('20003:剧本不存在');
- }
- $scriptCpid = (int)getProp($script, 'cpid');
- $fromUserId = (int)getProp($script, 'user_id');
- // 管理员仅可操作本组剧本
- if ($operatorRole !== 'superadmin' && $scriptCpid !== $operatorCpid) {
- Utils::throwError(ErrorConst::NOT_ACCESS);
- }
- // 管理员仅可转让自己创建的剧本(超管不做此验证)
- if ($operatorRole !== 'superadmin' && $fromUserId !== (int)$operatorUid) {
- Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
- }
- // 禁止跨组转让:目标用户必须与剧本同组
- if ($targetCpid !== $scriptCpid) {
- Utils::throwError('20003:不能跨组转让,目标用户与剧本不在同一组');
- }
- // 关联资产ID(同一资产可能关联多个剧集序号,需去重)
- $productIds = $this->normalizeIdList(
- DB::table('mp_script_product_mappings')
- ->where('script_id', $scriptId)
- ->pluck('product_id')
- ->all()
- );
- $folderIds = [];
- if (!empty($productIds)) {
- $products = DB::table('mp_products')
- ->whereIn('id', $productIds)
- ->select('id', 'cpid', 'parent_id', 'user_id')
- ->get();
- // 关联资产必须全部存在,否则视为数据异常,不提交
- if ($products->count() !== count($productIds)) {
- Utils::throwError('20003:剧本存在已丢失的关联资产,无法完成转让');
- }
- foreach ($products as $product) {
- // 关联资产必须与剧本同组,避免误转让跨组资产
- if ((int)getProp($product, 'cpid') !== $scriptCpid) {
- Utils::throwError('20003:剧本存在跨组关联资产,无法完成转让');
- }
- $parentId = (int)getProp($product, 'parent_id', 0);
- if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
- $folderIds[] = $parentId;
- }
- }
- // 仅转让归属于原剧本所有者的资产
- $folderIds = DB::table('mp_products')
- ->whereIn('id', $folderIds)
- ->where('type', 2)
- ->where('cpid', $scriptCpid)
- ->where('user_id', $fromUserId)
- ->pluck('id')
- ->map('intval')
- ->all();
- // 管理员仅可转让自己创建的资产及其所属文件夹(超管不做此验证)
- if ($operatorRole !== 'superadmin') {
- foreach ($products as $product) {
- if ((int)getProp($product, 'user_id') !== (int)$operatorUid) {
- Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
- }
- }
- foreach ($products as $product) {
- $parentId = (int)getProp($product, 'parent_id', 0);
- if ($parentId > 0 && !in_array($parentId, $folderIds, true)) {
- Utils::throwError('20003:管理员仅能转让自己创建的剧本和资产');
- }
- }
- }
- }
- $now = now();
- // 5.更新剧本归属
- DB::table('mp_scripts')
- ->where('id', $scriptId)
- ->update([
- 'user_id' => $targetUserId,
- 'updated_at' => $now,
- ]);
- // 6.更新关联资产归属
- if (!empty($productIds)) {
- DB::table('mp_products')
- ->whereIn('id', $productIds)
- ->update([
- 'user_id' => $targetUserId,
- 'updated_at' => $now,
- ]);
- }
- // 7.更新资产所属的类型根文件夹归属(文件夹属于 mp_products,随资产一并转让)
- if (!empty($folderIds)) {
- DB::table('mp_products')
- ->whereIn('id', $folderIds)
- ->update([
- 'user_id' => $targetUserId,
- 'updated_at' => $now,
- ]);
- }
- // 8.校验剧本与资产是否全部更新成功,任一未成功则回滚
- $scriptOwner = (int)DB::table('mp_scripts')->where('id', $scriptId)->value('user_id');
- if ($scriptOwner !== $targetUserId) {
- Utils::throwError('20003:剧本归属更新失败');
- }
- if (!empty($productIds)) {
- $updatedProductCount = DB::table('mp_products')
- ->whereIn('id', $productIds)
- ->where('user_id', $targetUserId)
- ->count();
- if ($updatedProductCount !== count($productIds)) {
- Utils::throwError('20003:部分剧本资产转让失败,已回滚');
- }
- }
- if (!empty($folderIds)) {
- $updatedFolderCount = DB::table('mp_products')
- ->whereIn('id', $folderIds)
- ->where('user_id', $targetUserId)
- ->count();
- if ($updatedFolderCount !== count($folderIds)) {
- Utils::throwError('20003:部分资产文件夹转让失败,已回滚');
- }
- }
- return [
- 'script_id' => (int)$scriptId,
- 'script_name' => (string)getProp($script, 'script_name', ''),
- 'from_user_id' => $fromUserId,
- 'to_user_id' => $targetUserId,
- 'product_count' => count($productIds),
- 'folder_count' => count($folderIds),
- ];
- }
- /**
- * 规范化ID列表,兼容数组、逗号分隔字符串以及字符串数组
- *
- * @param mixed $ids 待处理的ID集合
- * @return array 去重后的正整数ID数组
- */
- private function normalizeIdList($ids) {
- if (!is_array($ids)) {
- $ids = explode(',', (string)$ids);
- }
- $result = [];
- foreach ($ids as $item) {
- if (is_array($item)) {
- continue;
- }
- foreach (explode(',', (string)$item) as $part) {
- $part = trim($part);
- if ($part !== '' && is_numeric($part) && (int)$part > 0) {
- $result[] = (int)$part;
- }
- }
- }
- return array_values(array_unique($result));
- }
- /**
- * 通过 Excel 批量导入剧本资产(独立实现,不依赖 saveScriptProducts)
- *
- * 流程:
- * 1. 校验剧本存在且属于当前用户
- * 2. 解析 Excel 并校验强制列与数据完整性(资产类型/资产名称/使用范围/参考提示词)
- * 3. 名称去重(与 Excel 内及该剧本已有关联资产比对)
- * 4. 事务内创建类型文件夹、资产与剧本映射
- * 5. 为没有图片的资产创建图片生成任务,生成中返回 SSE 轮询
- *
- * @param array $data 请求参数
- * @param \Illuminate\Http\UploadedFile $file 上传的 Excel 文件
- * @return array|\Generator
- */
- public function importScriptProductsByExcel($data, $file) {
- $uid = Site::getUid();
- $cpid = Site::getCpid();
- $script_id = (int)getProp($data, 'script_id', 0);
- if (!$script_id) {
- Utils::throwError('20003:请提供剧本ID');
- }
- // 验证剧本是否存在,且只能导入自己创建的剧本
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->where('user_id', $uid)
- ->first();
- if (!$script) {
- Utils::throwError('20003:剧本不存在或无权限操作');
- }
- $script_name = $script->script_name ?? 'script_' . $script_id;
- // 校验上传文件
- if (!$file) {
- Utils::throwError('20003:请上传Excel文件');
- }
- $extension = strtolower($file->getClientOriginalExtension());
- if (!in_array($extension, ['xlsx', 'xls'])) {
- Utils::throwError('20003:文件格式错误,仅支持 xlsx、xls 格式');
- }
- if ($file->getSize() > 10 * 1024 * 1024) {
- Utils::throwError('20003:文件大小不能超过10M');
- }
- // 解析 Excel(第一行为表头)
- $rows = $this->readImportExcelRows($file);
- if (empty($rows)) {
- Utils::throwError('20003:Excel内容为空');
- }
- $headers = array_shift($rows);
- // 定位强制列
- $typeColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产类型'], ['资产类型', '类型']);
- $nameColumnIndex = $this->findImportExcelColumnIndex($headers, ['资产名称'], ['资产名称', '名称']);
- $rangeColumnIndex = $this->findImportExcelColumnIndex($headers, ['使用范围'], ['使用范围', '范围']);
- $promptColumnIndex = $this->findImportExcelColumnIndex($headers, ['参考提示词', '提示词'], ['提示词']);
- $missingColumns = [];
- if ($typeColumnIndex < 0) {
- $missingColumns[] = '资产类型';
- }
- if ($nameColumnIndex < 0) {
- $missingColumns[] = '资产名称';
- }
- if ($rangeColumnIndex < 0) {
- $missingColumns[] = '使用范围';
- }
- if ($promptColumnIndex < 0) {
- $missingColumns[] = '参考提示词';
- }
- if (!empty($missingColumns)) {
- Utils::throwError('20003:Excel缺少必填列:' . implode('、', $missingColumns));
- }
- // 先整体校验 Excel 数据,所有异常行一次性返回
- $validation = $this->validateImportExcelRows(
- $rows,
- $typeColumnIndex,
- $nameColumnIndex,
- $rangeColumnIndex,
- $promptColumnIndex
- );
- $errors = $validation['errors'];
- $checkedRows = $validation['checked_rows'];
- if (empty($checkedRows)) {
- $errors[] = 'Excel中没有有效的数据行';
- }
- if (!empty($errors)) {
- Utils::throwError('20003:Excel数据校验失败:' . implode(';', $errors));
- }
- // 名称去重:Excel 内部 + 该剧本已关联资产(按 createProduct 的名称判断逻辑)
- $existingNames = $this->getScriptProductNames($script_id, $cpid);
- $dedupResult = $this->deduplicateImportRows($checkedRows, $existingNames);
- $validRows = $dedupResult['valid_rows'];
- $skipped = $dedupResult['skipped'];
- // 图片生成参数(与 saveScriptProducts 保持一致的校验规则)
- $model = getProp($data, 'model');
- if (!$model) {
- $model = 'gpt-image-2';
- }
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
- $ratio = getProp($data, 'ratio', '9:16');
- $resolution = strtolower(getProp($data, 'resolution', '2k'));
- $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
- if (!isset($sizeMap[$resolution])) {
- Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
- }
- if (!isset($sizeMap[$resolution][$ratio])) {
- Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
- }
- $width = $sizeMap[$resolution][$ratio]['width'];
- $height = $sizeMap[$resolution][$ratio]['height'];
- $autoRaw = getProp($data, 'auto_generate_images', true);
- $auto_generate_images = !in_array($autoRaw, [false, 0, '0', 'false', 'False'], true);
- // 创建/复用任务中心记录(md5 验重,避免重复任务)
- $taskCenterId = $this->createScriptProductTaskCenter(
- $uid,
- $cpid,
- $script_id,
- $validRows,
- $model,
- $ratio,
- $resolution,
- $auto_generate_images
- );
- // 全部为重复项:参照 saveScriptProducts,检查已存在资产的图片状态,缺图的补建任务
- if (empty($validRows)) {
- $existingTaskInfo = $this->prepareExistingScriptProductTasks(
- $script_id,
- $model,
- $width,
- $height,
- $auto_generate_images
- );
- $productTaskMap = $existingTaskInfo['product_task_map'];
- $typeFolderIds = $existingTaskInfo['type_folder_ids'];
- if (!empty($productTaskMap)) {
- $message = 'Excel中的资产均已存在,正在为缺少图片的资产生成图片';
- } elseif (!$existingTaskInfo['has_all_tasks']) {
- $message = 'Excel中的资产均已存在,部分资产没有参考提示词,无法生成图片';
- } else {
- $message = 'Excel中的资产均已存在,且图片已全部生成完成';
- }
- $resultData = [
- 'success' => true,
- 'message' => $message,
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'imported_count' => 0,
- 'existing_products' => $existingTaskInfo['product_count'],
- 'skipped_count' => count($skipped),
- 'skipped' => $skipped,
- 'created_products' => [],
- 'type_folder_ids' => $typeFolderIds,
- 'pending_tasks_count' => count($productTaskMap),
- 'image_tasks_created' => $existingTaskInfo['created_count'],
- 'task_center_id' => $taskCenterId,
- ];
- // 有需要轮询的任务(已有任务或本次补建):走 SSE 轮询
- if (!empty($productTaskMap)) {
- return $this->pollProductImageTasks(
- $script_id,
- $script_name,
- $productTaskMap,
- $typeFolderIds,
- $taskCenterId,
- ['import_result' => $resultData],
- ['import_result' => $resultData]
- );
- }
- // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
- return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
- }
- // 事务内创建资产、类型文件夹与剧本映射
- $typeFolderIds = [];
- $createdProducts = [];
- $mappingRecords = [];
- $now = now();
- DB::beginTransaction();
- try {
- foreach ($validRows as $row) {
- $type = $row['type'];
- if (!isset($typeFolderIds[$type])) {
- // 与 createProduct 一致:先查找该剧本已存在的类型文件夹,没有则创建
- $folder = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('type', 2)
- ->where('product', $type)
- ->where('product_name', $script_name)
- ->where('parent_id', 0)
- ->where('is_deleted', 0)
- ->first();
- if ($folder) {
- $typeFolderIds[$type] = $folder->id;
- } else {
- $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 2, // 文件夹
- 'product' => $type, // 1=角色 2=场景 3=道具
- '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];
- $product_id = DB::table('mp_products')->insertGetId([
- 'user_id' => $uid,
- 'cpid' => $cpid,
- 'type' => 1, // 资产
- 'product' => $type,
- 'parent_id' => $folder_id,
- 'level' => 2,
- 'product_name' => $row['product_name'],
- 'pic_prompt' => $row['pic_prompt'],
- 'sort_order' => time(),
- 'is_deleted' => 0,
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
- $createdProducts[] = [
- 'id' => $product_id,
- 'type' => $type,
- 'product_name' => $row['product_name'],
- 'pic_prompt' => $row['pic_prompt'],
- ];
- // 为每个使用范围(集数)创建映射记录
- foreach ($row['episode_numbers'] as $episodeNumber) {
- $mappingRecords[] = [
- 'script_id' => $script_id,
- 'product_id' => $product_id,
- 'episode_number' => $episodeNumber,
- 'created_at' => $now,
- 'updated_at' => $now,
- ];
- }
- }
- // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
- DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
- // 剧本已有资产,同步更新is_products标记
- DB::table('mp_scripts')->where('id', $script_id)->update([
- 'is_products' => 1,
- 'updated_at' => $now,
- ]);
- DB::commit();
- } catch (\Exception $e) {
- DB::rollback();
- if ($taskCenterId) {
- $this->taskCenterService->updateTask($taskCenterId, [
- 'status' => MpTaskCenter::STATUS_FAILED,
- 'error_message' => $e->getMessage(),
- ]);
- }
- dLog('anime')->error('Excel导入剧本资产失败: ' . $e->getMessage(), [
- 'script_id' => $script_id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
- Utils::throwError('20003:Excel导入剧本资产失败:' . $e->getMessage());
- }
- // 参照 saveScriptProducts:为新建资产以及已存在但缺图的资产统一补建图片生成任务
- $existingTaskInfo = $this->prepareExistingScriptProductTasks(
- $script_id,
- $model,
- $width,
- $height,
- $auto_generate_images
- );
- $productTaskMap = $existingTaskInfo['product_task_map'];
- $resultData = [
- 'success' => true,
- 'message' => '导入完成',
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'imported_count' => count($createdProducts),
- 'skipped_count' => count($skipped),
- 'skipped' => $skipped,
- 'created_products' => array_map(function ($item) {
- return [
- 'id' => $item['id'],
- 'type' => $item['type'],
- 'product_name' => $item['product_name'],
- ];
- }, $createdProducts),
- 'type_folder_ids' => $typeFolderIds,
- 'pending_tasks_count' => count($productTaskMap),
- 'image_tasks_created' => $existingTaskInfo['created_count'],
- 'task_center_id' => $taskCenterId,
- ];
- // 有待生成的图片任务:返回 SSE 轮询结果(导入统计在 init 与 complete 事件中)
- if (!empty($productTaskMap)) {
- return $this->pollProductImageTasks(
- $script_id,
- $script_name,
- $productTaskMap,
- $typeFolderIds,
- $taskCenterId,
- ['import_result' => $resultData],
- ['import_result' => $resultData]
- );
- }
- // 没有需要轮询的任务:直接通过 complete 事件返回导入结果
- return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
- }
- /**
- * 校验 Excel 数据行(先校验完毕,再进行后续逻辑)
- *
- * @param array $rows
- * @param int $typeColumnIndex
- * @param int $nameColumnIndex
- * @param int $rangeColumnIndex
- * @param int $promptColumnIndex
- * @return array ['errors' => [], 'checked_rows' => []]
- */
- private function validateImportExcelRows(array $rows, $typeColumnIndex, $nameColumnIndex, $rangeColumnIndex, $promptColumnIndex) {
- $errors = [];
- $checkedRows = [];
- foreach ($rows as $rowIndex => $row) {
- // 数据从第2行开始(表头占第1行)
- $excelRowNo = $rowIndex + 2;
- if (!is_array($row) || $this->isImportExcelRowEmpty($row)) {
- continue;
- }
- $typeRaw = trim((string)($row[$typeColumnIndex] ?? ''));
- $nameRaw = trim((string)($row[$nameColumnIndex] ?? ''));
- $rangeRaw = trim((string)($row[$rangeColumnIndex] ?? ''));
- $promptRaw = trim((string)($row[$promptColumnIndex] ?? ''));
- $missingFields = [];
- if ($typeRaw === '') {
- $missingFields[] = '资产类型';
- }
- if ($nameRaw === '') {
- $missingFields[] = '资产名称';
- }
- if ($rangeRaw === '') {
- $missingFields[] = '使用范围';
- }
- if ($promptRaw === '') {
- $missingFields[] = '参考提示词';
- }
- if (!empty($missingFields)) {
- $errors[] = "第{$excelRowNo}行:" . implode('、', $missingFields) . '不能为空';
- continue;
- }
- // 资产类型校验
- $productType = $this->resolveImportProductType($typeRaw);
- if (!$productType) {
- $errors[] = "第{$excelRowNo}行:资产类型「{$typeRaw}」不正确,仅支持 角色/场景/道具";
- continue;
- }
- // 资产名称去除两边特殊符号
- $productName = $this->normalizeImportProductName($nameRaw);
- if ($productName === '') {
- $errors[] = "第{$excelRowNo}行:资产名称「{$nameRaw}」去除特殊符号后为空";
- continue;
- }
- if (mb_strlen($productName, 'UTF-8') > 64) {
- $errors[] = "第{$excelRowNo}行:资产名称「{$productName}」超过64个字符";
- continue;
- }
- // 解析使用范围(逗号分隔的集数)
- $episodeNumbers = $this->parseImportEpisodeNumbers($rangeRaw);
- if (empty($episodeNumbers)) {
- $errors[] = "第{$excelRowNo}行:使用范围「{$rangeRaw}」格式错误,仅支持数字或逗号分隔的数字";
- continue;
- }
- $checkedRows[] = [
- 'row' => $excelRowNo,
- 'type' => $productType,
- 'product_name' => $productName,
- 'episode_numbers' => $episodeNumbers,
- 'pic_prompt' => $promptRaw,
- ];
- }
- return [
- 'errors' => $errors,
- 'checked_rows' => $checkedRows,
- ];
- }
- /**
- * Excel 资产名称去重:Excel 内部 + 剧本已有关联资产
- *
- * @param array $checkedRows
- * @param array $existingNames 剧本已有关联资产名称集合(name => true)
- * @return array ['valid_rows' => [], 'skipped' => []]
- */
- private function deduplicateImportRows(array $checkedRows, array $existingNames) {
- $seenNames = [];
- $validRows = [];
- $skipped = [];
- foreach ($checkedRows as $row) {
- $nameKey = $row['product_name'];
- $typeText = $this->getImportProductTypeText($row['type']);
- if (isset($seenNames[$nameKey])) {
- $skipped[] = [
- 'row' => $row['row'],
- 'type' => $typeText,
- 'product_name' => $row['product_name'],
- 'reason' => 'Excel中资产名称重复',
- ];
- continue;
- }
- if (isset($existingNames[$nameKey])) {
- $skipped[] = [
- 'row' => $row['row'],
- 'type' => $typeText,
- 'product_name' => $row['product_name'],
- 'reason' => '剧本中已存在同名资产',
- ];
- continue;
- }
- $seenNames[$nameKey] = true;
- $validRows[] = $row;
- }
- return [
- 'valid_rows' => $validRows,
- 'skipped' => $skipped,
- ];
- }
- /**
- * 读取 Excel 文件为二维数组(第一行为表头)
- *
- * @param \Illuminate\Http\UploadedFile $file
- * @return array
- */
- private function readImportExcelRows($file) {
- try {
- $reader = IOFactory::createReaderForFile($file->getRealPath());
- $reader->setReadDataOnly(true);
- $spreadsheet = $reader->load($file->getRealPath());
- $sheet = $spreadsheet->getSheet(0);
- $rows = $sheet->toArray(null, true, true, false);
- $spreadsheet->disconnectWorksheets();
- unset($spreadsheet);
- return $rows;
- } catch (\Exception $e) {
- dLog('anime')->error('Excel文件解析失败', [
- 'error' => $e->getMessage(),
- ]);
- Utils::throwError('20003:Excel文件解析失败,请确认文件格式正确');
- }
- }
- /**
- * 查找 Excel 表头列索引(先精确匹配,再模糊匹配)
- *
- * @param array $headers
- * @param array $exactKeywords
- * @param array $fuzzyKeywords
- * @return int
- */
- private function findImportExcelColumnIndex(array $headers, array $exactKeywords, array $fuzzyKeywords) {
- foreach ($headers as $index => $header) {
- $header = trim((string)$header);
- if ($header === '') {
- continue;
- }
- foreach ($exactKeywords as $keyword) {
- if ($header === $keyword) {
- return $index;
- }
- }
- }
- foreach ($headers as $index => $header) {
- $header = trim((string)$header);
- if ($header === '') {
- continue;
- }
- foreach ($fuzzyKeywords as $keyword) {
- if (mb_strpos($header, $keyword) !== false) {
- return $index;
- }
- }
- }
- return -1;
- }
- /**
- * 判断 Excel 行是否为空行
- *
- * @param array $row
- * @return bool
- */
- private function isImportExcelRowEmpty(array $row) {
- foreach ($row as $cell) {
- if (trim((string)$cell) !== '') {
- return false;
- }
- }
- return true;
- }
- /**
- * 资产名称去除两边特殊符号(与 createProduct 保持一致)
- *
- * @param string $name
- * @return string
- */
- private function normalizeImportProductName($name) {
- $name = trim((string)$name);
- $name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $name);
- if (!$name || preg_match('/^[-—_]+$/u', $name)) {
- return '';
- }
- return $name;
- }
- /**
- * 解析 Excel 中的资产类型
- *
- * @param string $value
- * @return int|null 1=角色 2=场景 3=道具
- */
- private function resolveImportProductType($value) {
- $value = trim((string)$value);
- $map = [
- '角色' => 1,
- '主体' => 1,
- '人物' => 1,
- '1' => 1,
- '场景' => 2,
- '2' => 2,
- '道具' => 3,
- '3' => 3,
- ];
- return isset($map[$value]) ? $map[$value] : null;
- }
- /**
- * 资产类型文案
- *
- * @param int $type
- * @return string
- */
- private function getImportProductTypeText($type) {
- $map = [1 => '角色', 2 => '场景', 3 => '道具'];
- return isset($map[$type]) ? $map[$type] : (string)$type;
- }
- /**
- * 解析使用范围(逗号分隔的集数)
- *
- * @param string $value
- * @return array
- */
- private function parseImportEpisodeNumbers($value) {
- $parts = preg_split('/[,,、\s]+/u', trim((string)$value));
- $episodeNumbers = [];
- foreach ($parts as $part) {
- if ($part === '') {
- continue;
- }
- if (!is_numeric($part)) {
- return [];
- }
- $episodeNumbers[] = (int)$part;
- }
- $episodeNumbers = array_values(array_unique($episodeNumbers));
- sort($episodeNumbers);
- return $episodeNumbers;
- }
- /**
- * 获取剧本已关联资产名称集合(按 createProduct 的名称判断逻辑)
- *
- * @param int $script_id
- * @param int $cpid
- * @return array
- */
- private function getScriptProductNames($script_id, $cpid) {
- $products = DB::table('mp_script_product_mappings as m')
- ->join('mp_products as p', 'm.product_id', '=', 'p.id')
- ->where('m.script_id', $script_id)
- ->where('p.cpid', $cpid)
- ->where('p.type', 1)
- ->where('p.is_deleted', 0)
- ->get(['p.product_name']);
- $names = [];
- foreach ($products as $product) {
- $name = $this->normalizeImportProductName($product->product_name);
- if ($name !== '') {
- $names[$name] = true;
- }
- }
- return $names;
- }
- /**
- * 获取剧本已关联的资产名称(仅按剧本判重,不区分资产类型)
- *
- * @param int $script_id
- * @return array ['资产名称' => true]
- */
- private function getScriptAssetNames($script_id) {
- $products = DB::table('mp_script_product_mappings as m')
- ->join('mp_products as p', 'm.product_id', '=', 'p.id')
- ->where('m.script_id', $script_id)
- ->where('p.type', 1)
- ->where('p.is_deleted', 0)
- ->get(['p.product_name']);
- $names = [];
- foreach ($products as $product) {
- $name = $this->normalizeImportProductName($product->product_name);
- if ($name !== '') {
- $names[$name] = true;
- }
- }
- return $names;
- }
- /**
- * 校验并提取本次入参中的新增资产行
- *
- * 规则:
- * - 资产名称为空(或仅剩占位符):跳过
- * - 同一份入参内重名(跨类型):保留最后一条
- * - 与剧本已关联资产同名(跨类型判重,仅限当前剧本):不算新增
- * - 新增行的参考提示词为空:直接报错,不进行任何后续处理
- *
- * @param int $script_id
- * @param mixed $products 入参(数组或 JSON 字符串)
- * @return array [['type' => int, 'product_name' => string, 'pic_prompt' => string, 'episode_numbers' => []]]
- */
- private function extractNewScriptProductRows($script_id, $products) {
- // 兼容 JSON 字符串;无法解析时按"没有新增行"处理,由后续创建逻辑给出原有报错
- if (is_string($products)) {
- $decoded = json_decode($products, true);
- $products = (json_last_error() === JSON_ERROR_NONE) ? $decoded : [];
- }
- if (!is_array($products) || empty($products)) {
- return [];
- }
- $rowMap = [];
- foreach ($products as $productGroup) {
- $type = getProp($productGroup, 'type');
- $content = getProp($productGroup, 'content', []);
- if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
- continue;
- }
- // 获取表头(第一行)并查找关键列的位置
- $headers = $content[0];
- $nameColumnIndex = -1;
- $sequenceColumnIndex = -1;
- $promptColumnIndex = -1;
- $fallbackPromptColumnIndex = -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;
- } elseif (strpos($header, '提示词') !== false && $fallbackPromptColumnIndex === -1) {
- // 与 Excel 导入保持一致:优先"参考提示词",否则兼容"提示词"列
- $fallbackPromptColumnIndex = $index;
- }
- }
- if ($promptColumnIndex === -1) {
- $promptColumnIndex = $fallbackPromptColumnIndex;
- }
- if ($nameColumnIndex === -1) {
- continue;
- }
- for ($i = 1; $i < count($content); $i++) {
- $row = $content[$i];
- if (empty($row) || !isset($row[$nameColumnIndex])) {
- continue;
- }
- // 处理product_name两边的符号;名称为空或仅剩占位符号则跳过
- $product_name = $this->normalizeImportProductName($row[$nameColumnIndex]);
- if ($product_name === '') {
- continue;
- }
- $pic_prompt = '';
- if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
- $pic_prompt = trim((string)$row[$promptColumnIndex]);
- }
- // 解析使用范围(逗号分隔的序号),为空时由创建逻辑写入默认映射(序号0)
- $sequences = [];
- $sequence_str = ($sequenceColumnIndex >= 0 && isset($row[$sequenceColumnIndex]))
- ? trim((string)$row[$sequenceColumnIndex])
- : '';
- if ($sequence_str !== '') {
- foreach (array_map('trim', explode(',', $sequence_str)) as $part) {
- if (is_numeric($part)) {
- $sequences[] = (int)$part;
- }
- }
- }
- // 跨类型判重,同一份入参内重名保留最后一条
- $rowMap[$product_name] = [
- 'type' => (int)$type,
- 'product_name' => $product_name,
- 'pic_prompt' => $pic_prompt,
- 'episode_numbers' => $sequences,
- ];
- }
- }
- // 与剧本已关联资产判重(仅限当前剧本,跨类型)
- $existingNames = $this->getScriptAssetNames($script_id);
- $newRows = [];
- $emptyPromptNames = [];
- foreach ($rowMap as $name => $row) {
- if (isset($existingNames[$name])) {
- continue;
- }
- if ($row['pic_prompt'] === '') {
- $emptyPromptNames[] = $name;
- continue;
- }
- $newRows[] = $row;
- }
- // 新增行的参考提示词为空:直接报错,不进行任何后续处理
- if (!empty($emptyPromptNames)) {
- Utils::throwError('20003:以下新增资产的参考提示词不能为空:' . implode('、', $emptyPromptNames));
- }
- return $newRows;
- }
- /**
- * 已有关联资产的图片任务处理(参照 saveScriptProducts 的处理方式)
- *
- * - 已有图片任务的资产:收集任务ID,交给轮询
- * - 已有图片且生成成功的资产:跳过
- * - 没有图片的资产:允许自动生成时补建图片任务(需要提示词)
- *
- * @param int $script_id
- * @param string $model
- * @param int $width
- * @param int $height
- * @param bool $auto_generate_images
- * @return array ['product_task_map' => [], 'type_folder_ids' => [], 'has_all_tasks' => bool, 'product_count' => int, 'created_count' => int]
- */
- private function prepareExistingScriptProductTasks($script_id, $model, $width, $height, $auto_generate_images) {
- $productTaskMap = [];
- $typeFolderIds = [];
- $hasAllTasks = true;
- $createdCount = 0;
- $existingMappings = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->get();
- $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
- $productsWithTasks = DB::table('mp_products')
- ->whereIn('id', $productIds)
- ->where('is_deleted', 0)
- ->get();
- 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;
- } elseif ($product->url && $product->pic_task_status == '生成成功') {
- continue;
- } else {
- // 有资产没有图片
- $hasAllTasks = false;
- }
- }
- // 为没有图片的资产补建图片生成任务
- if (!$hasAllTasks && $auto_generate_images && $productsWithTasks->isNotEmpty()) {
- DB::beginTransaction();
- try {
- 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 {
- $task = $this->aiImageGenerationService->createImageGenerationTask([
- 'prompt' => $product->pic_prompt,
- 'model' => $model,
- 'ref_img_urls' => [],
- 'width' => $width,
- 'height' => $height,
- // 计费锚点(剧本),用于积分明细归属统计
- 'script_id' => $script_id,
- ]);
- $task_id = $task->id;
- if ($task_id) {
- $productTaskMap[$product->id] = $task_id;
- $createdCount++;
- 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();
- } catch (\Exception $e) {
- DB::rollback();
- dLog('anime')->error('为已存在资产创建图片任务失败', [
- 'script_id' => $script_id,
- 'error' => $e->getMessage(),
- ]);
- Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
- }
- }
- return [
- 'product_task_map' => $productTaskMap,
- 'type_folder_ids' => $typeFolderIds,
- 'has_all_tasks' => $hasAllTasks,
- 'product_count' => count($productIds),
- 'created_count' => $createdCount,
- ];
- }
- /**
- * 保存剧本资产关联关系
- * @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:剧本不存在');
- }
- // 处理图片模型
- $model = getProp($data, 'model');
- if (!$model) {
- // 使用默认模型
- $model = 'gpt-image-2';
- }
- // 验证模型是否在可用模型表中
- if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
- Utils::throwError('20003:该模型已不可用,请更换!');
- }
- $ratio = getProp($data, 'ratio', '9:16');
- $resolution = getProp($data, 'resolution', '2k');
- // 分辨率档位与尺寸映射统一从 BaseConst 获取
- $sizeMap = BaseConst::IMAGE_RESOLUTION_SIZE_MAP;
-
- // 参数验证
- $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'];
-
- $script_name = $script->script_name ?? 'script_' . $script_id;
-
- // 先校验并提取本次入参中的新增资产行:
- // 新增行的参考提示词为空时直接报错,不写任何数据、不创建任务中心记录
- $newRows = $this->extractNewScriptProductRows($script_id, $products);
- // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
- $taskCenterId = $this->createScriptProductTaskCenter(
- $uid,
- $cpid,
- $script_id,
- $products,
- $model,
- $ratio,
- $resolution,
- $auto_generate_images
- );
- // 检查是否已经有该剧本的资产数据
- $existingMappings = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->get();
-
- // 已有资产且本次没有新增行时,走原有的"已存在"处理;否则走下方创建逻辑
- if ($existingMappings->isNotEmpty() && empty($newRows)) {
- // 已存在资产映射,检查是否所有资产都有图片生成任务
- $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, $taskCenterId);
- }
-
- // 如果部分资产没有任务ID,只为这些资产创建任务
- if (!$hasAllTasks && $auto_generate_images) {
- dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
- 'script_id' => $script_id,
- 'script_name' => $script_name
- ]);
- // 开启事务
- DB::beginTransaction();
-
- try {
-
- 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,
- // 计费锚点(剧本),用于积分明细归属统计
- 'script_id' => $script_id,
- ];
-
- $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, $taskCenterId);
- }
-
- } catch (\Exception $e) {
- // 回滚事务
- DB::rollback();
-
- dLog('anime')->error('为已存在资产创建图片任务失败', [
- 'script_id' => $script_id,
- 'error' => $e->getMessage()
- ]);
-
- Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
- }
- }
-
- // 如果不需要生成图片,返回已存在的信息
- $resultData = [
- 'success' => true,
- 'message' => '剧本资产已存在',
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'type_folder_ids' => $typeFolderIds,
- 'existing_products' => count($productIds),
- 'tasks_count' => count($productTaskMap),
- 'task_center_id' => $taskCenterId
- ];
- // 接口已正常完成,更新任务中心状态和结果
- if ($taskCenterId) {
- $this->taskCenterService->updateTask($taskCenterId, [
- 'status' => MpTaskCenter::STATUS_SUCCESS,
- 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
- 'error_message' => null
- ]);
- }
- return $resultData;
- }
- // 走到这里说明有新行需要创建(或剧本还没有任何资产),保留原有的入参校验报错
- if (empty($newRows)) {
- $decodedProducts = $products;
- if (is_string($decodedProducts)) {
- $decodedProducts = json_decode($decodedProducts, true);
- if (json_last_error() !== JSON_ERROR_NONE) {
- Utils::throwError('20003:产品数据格式错误');
- }
- }
- if (!is_array($decodedProducts) || empty($decodedProducts)) {
- Utils::throwError('20003:产品数据不能为空');
- }
- Utils::throwError('20003:没有有效的产品数据');
- }
- // 仅保留本次新增的资产行,复用下方原有的创建逻辑
- $products = [];
- foreach ($newRows as $newRow) {
- if (!isset($products[$newRow['type']])) {
- $products[$newRow['type']] = [
- 'type' => $newRow['type'],
- 'content' => [['资产名称', '使用范围', '参考提示词']],
- ];
- }
- $products[$newRow['type']]['content'][] = [
- $newRow['product_name'],
- implode(',', $newRow['episode_numbers']),
- $newRow['pic_prompt'],
- ];
- }
- $products = array_values($products);
- // 以下是原有的创建逻辑...
- // 开启事务
- DB::beginTransaction();
-
- try {
- $now = now();
- $mappingRecords = [];
- $createdProductIds = []; // 记录所有创建的资产ID
-
- // 获取剧本名称
- $script_name = $script->script_name ?? 'script_' . $script_id;
-
- // 存储每个类型的根文件夹ID
- $typeFolderIds = [];
-
- // 遍历每个产品类型(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])) {
- $folder = DB::table('mp_products')
- ->where('cpid', $cpid)
- ->where('type', 2)
- ->where('product', $type)
- ->where('product_name', $script_name)
- ->where('parent_id', 0)
- ->where('is_deleted', 0)
- ->first();
- if ($folder) {
- $typeFolderIds[$type] = $folder->id;
- } else {
- $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((string)$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;
- }
- // 处理product_name两边的符号
- $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
- // 如果名称不存在或仅剩占位符号,则跳过
- if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
- dLog('anime')->warning('资产名称无效,跳过保存', [
- 'script_id' => $script_id,
- 'type' => $type,
- 'product_name' => $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);
- // 剧本已有资产,同步更新is_products标记
- DB::table('mp_scripts')->where('id', $script_id)->update([
- 'is_products' => 1,
- 'updated_at' => $now
- ]);
-
- // 如果需要自动生成图片,在事务中创建图片生成任务
- $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,
- // 计费锚点(剧本),用于积分明细归属统计
- 'script_id' => $script_id,
- ];
-
- $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();
-
- // 本次新增资产创建的图片任务
- $createdTaskMap = $productTaskMap;
-
- } catch (\Exception $e) {
- // 回滚事务
- DB::rollback();
-
- // 更新任务中心状态为失败
- if (!empty($taskCenterId)) {
- $this->taskCenterService->updateTask($taskCenterId, [
- 'status' => MpTaskCenter::STATUS_FAILED,
- 'error_message' => $e->getMessage()
- ]);
- }
- // 记录错误日志
- dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
- 'script_id' => $script_id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
-
- // 统一使用 Utils::throwError 抛出错误
- Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
- }
- // 落库成功后统一处理图片任务:
- // 1) 本次新增资产的图片任务已在上方事务中创建
- // 2) 剧本内已存在但缺图的资产在此补建,并与新增资产的任务一并收集为待轮询任务
- $existingTaskInfo = $this->prepareExistingScriptProductTasks(
- $script_id,
- $model,
- $width,
- $height,
- $auto_generate_images
- );
- $productTaskMap = $existingTaskInfo['product_task_map'];
- // 创建阶段解析到的类型根文件夹优先
- $typeFolderIds = $typeFolderIds + $existingTaskInfo['type_folder_ids'];
- // 保存结果(SSE 的 init / complete 事件会携带该结构)
- $resultData = [
- 'success' => true,
- 'message' => '保存完成',
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'type_folder_ids' => $typeFolderIds,
- 'inserted_count' => $insertedCount,
- 'total_records' => count($mappingRecords),
- 'created_products' => count($createdProductIds),
- 'pending_tasks_count' => count($productTaskMap),
- 'image_tasks_created' => count($createdTaskMap) + $existingTaskInfo['created_count'],
- 'task_center_id' => $taskCenterId,
- ];
- // 有待完成的图片任务:返回 SSE 轮询流(事务外轮询)
- if ($auto_generate_images && !empty($productTaskMap)) {
- return $this->pollProductImageTasks(
- $script_id,
- $script_name,
- $productTaskMap,
- $typeFolderIds,
- $taskCenterId,
- ['import_result' => $resultData],
- ['import_result' => $resultData]
- );
- }
- // 没有需要轮询的任务:通过 SSE complete 事件返回保存结果
- return $this->streamImportComplete($script_id, $script_name, $resultData, $typeFolderIds, $taskCenterId);
- }
- /**
- * 根据入参创建或复用任务中心记录
- *
- * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
- * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
- * 避免生成重复任务。
- *
- * @param int|string $uid
- * @param int|string $cpid
- * @param int|string $script_id
- * @param mixed $products
- * @param string $model
- * @param string $ratio
- * @param string $resolution
- * @param mixed $auto_generate_images
- * @return int 任务中心ID
- */
- private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
- // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
- if (is_string($products)) {
- $decoded = json_decode($products, true);
- if (json_last_error() === JSON_ERROR_NONE) {
- $products = $decoded;
- }
- }
- $params = [
- 'script_id' => (int)$script_id,
- 'products' => $products,
- 'model' => $model,
- 'ratio' => $ratio,
- 'resolution' => $resolution,
- 'auto_generate_images' => (bool)$auto_generate_images,
- ];
- $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
- // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
- $existing = DB::table('mp_task_center')
- ->where('uid', (int)$uid)
- ->where('cpid', (int)$cpid)
- ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
- ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
- ->where('params_md5', $paramsMd5)
- ->orderBy('id', 'desc')
- ->first();
- if ($existing) {
- dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
- 'script_id' => $script_id,
- 'task_center_id' => $existing->id,
- 'params_md5' => $paramsMd5,
- ]);
- return (int)$existing->id;
- }
- // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
- $now = date('Y-m-d H:i:s');
- DB::table('mp_task_center')->insertOrIgnore([
- 'uid' => (int)$uid,
- 'cpid' => (int)$cpid,
- 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
- 'title' => '剧本资产图片生成',
- 'ref_task_id' => 0,
- 'status' => MpTaskCenter::STATUS_PROCESSING,
- 'result' => null,
- 'error_message' => null,
- 'prompt' => null,
- 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
- 'params_md5' => $paramsMd5,
- 'created_at' => $now,
- 'updated_at' => $now,
- ]);
- // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
- $taskId = (int)DB::table('mp_task_center')
- ->where('uid', (int)$uid)
- ->where('cpid', (int)$cpid)
- ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
- ->where('params_md5', $paramsMd5)
- ->orderBy('id', 'desc')
- ->value('id');
- dLog('anime')->info('创建任务中心记录', [
- 'script_id' => $script_id,
- 'task_center_id' => $taskId,
- 'params_md5' => $paramsMd5,
- ]);
- return $taskId;
- }
- /**
- * 任务结束时更新任务中心记录的状态和结果
- *
- * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
- * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
- *
- * @param int|null $taskCenterId
- * @param array $resultData 接口返回结果数组
- * @param bool $timeout 是否超时未完成
- */
- private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
- if (!$taskCenterId) {
- return;
- }
- $stats = $resultData['stats'] ?? [];
- $successCount = (int)array_sum(array_column((array)$stats, 'success'));
- $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
- $failedCount = $completedCount - $successCount;
- // 与接口返回给客户端的结果保持一致
- $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
- if ($timeout) {
- $this->taskCenterService->updateTask((int)$taskCenterId, [
- 'status' => MpTaskCenter::STATUS_FAILED,
- 'result' => $result,
- 'error_message' => '部分任务超时,请稍后查看结果',
- ]);
- return;
- }
- $this->taskCenterService->updateTask((int)$taskCenterId, [
- 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
- 'result' => $result,
- 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
- ]);
- }
- /**
- * 批量为剧本资产生成图片
- *
- * @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 = 'gpt-image-2';
- $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,
- // 计费锚点(剧本),用于积分明细归属统计
- 'script_id' => $script_id,
- ];
-
- $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 返回:直接通过 complete 事件返回导入结果
- *
- * @param int $script_id
- * @param string $script_name
- * @param array $resultData 导入结果(原普通 JSON 的 data 内容)
- * @param array $type_folder_ids
- * @param int|null $taskCenterId
- * @return \Generator
- */
- private function streamImportComplete($script_id, $script_name, array $resultData, $type_folder_ids, $taskCenterId = null) {
- if ($taskCenterId) {
- $initResponse = [
- 'type' => 'init',
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'timestamp' => date('Y-m-d H:i:s'),
- 'task_center_id' => (int)$taskCenterId,
- 'import_result' => $resultData,
- ];
- yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
- }
- $stats = $this->collectScriptProductStats($script_id);
- $response = [
- 'type' => 'complete',
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'stats' => $stats,
- 'timestamp' => date('Y-m-d H:i:s'),
- 'import_result' => $resultData,
- ];
- if ($taskCenterId) {
- $response['task_center_id'] = (int)$taskCenterId;
- }
- yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
- // 更新任务中心状态和结果
- $this->finishScriptProductTask($taskCenterId, $response);
- }
- /**
- * 统计剧本资产的图片生成状态(仅按 mp_products 当前状态统计,不驱动任务)
- *
- * @param int $script_id
- * @return array
- */
- private function collectScriptProductStats($script_id) {
- $stats = [
- 'character' => ['total' => 0, 'success' => 0, 'completed' => 0],
- 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0],
- 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0],
- ];
- $typeNames = [1 => 'roles', 2 => 'scenes', 3 => 'props'];
- $productIds = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->pluck('product_id')
- ->unique()
- ->toArray();
- if (empty($productIds)) {
- return [];
- }
- $products = DB::table('mp_products')
- ->whereIn('id', $productIds)
- ->where('is_deleted', 0)
- ->get();
- foreach ($products as $product) {
- $typeName = $typeNames[$product->product] ?? 'unknown';
- if (!isset($stats[$typeName])) {
- $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
- }
- $stats[$typeName]['total']++;
- if ($product->pic_task_status === '生成成功') {
- $stats[$typeName]['success']++;
- $stats[$typeName]['completed']++;
- } elseif ($product->pic_task_status === '生成失败') {
- $stats[$typeName]['completed']++;
- }
- }
- foreach ($stats as $typeName => $stat) {
- if ($stat['total'] === 0) {
- unset($stats[$typeName]);
- }
- }
- return $stats;
- }
- /**
- * 轮询资产图片生成任务状态(SSE流式返回)
- * 只通过查询数据库获取任务状态,不主动调用API
- *
- * @param int $script_id 剧本ID
- * @param string $script_name 剧本名称
- * @param array $productTaskMap 资产ID到任务ID的映射
- * @param array $type_folder_ids 类型文件夹ID映射
- * @param int|null $taskCenterId 任务中心ID
- * @param array $initExtra 追加到 init 事件中的额外数据
- * @param array $completeExtra 追加到 complete、timeout 事件中的额外数据
- * @return \Generator
- */
- private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null, array $initExtra = [], array $completeExtra = []) {
- $startTime = time();
- $timeout = 1800; // 30分钟超时
- $pollInterval = 10; // 10秒轮询一次
- $lastStatus = []; // 记录上次的状态,用于判断是否有变化
- // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
- if ($taskCenterId) {
- $initResponse = array_merge([
- 'type' => 'init',
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'timestamp' => date('Y-m-d H:i:s'),
- 'task_center_id' => (int)$taskCenterId,
- ], $initExtra);
- yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
- }
-
- // 定义类型名称映射
- $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[$typeName]['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')
- ];
- if ($taskCenterId) {
- $response['task_center_id'] = $taskCenterId;
- }
- if ($eventType === 'complete') {
- $response = array_merge($response, $completeExtra);
- }
-
- 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
- ]);
-
- // 全部任务完成,更新任务中心状态和结果
- $this->finishScriptProductTask($taskCenterId, $response);
- 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')
- ];
- if ($taskCenterId) {
- $response['task_center_id'] = $taskCenterId;
- }
- $response = array_merge($response, $completeExtra);
-
- yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
-
- dLog('anime')->warning('资产图片生成任务超时', [
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'timeout' => $timeout
- ]);
- // 超时未完成,更新任务中心状态和结果
- $this->finishScriptProductTask($taskCenterId, $response, true);
- }
- }
- /**
- * 定时任务:检查产品图片生成任务状态并更新产品记录
- * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
- * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
- *
- * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
- */
- public function checkProductPicTasks() {
- // 查询所有生成中的产品图片任务
- $products = DB::table('mp_products')
- ->whereNotNull('pic_task_id')
- ->where('pic_task_status', '生成中')
- ->where('is_deleted', 0)
- ->get();
- $stats = [
- 'total' => $products->count(),
- 'success' => 0,
- 'failed' => 0,
- 'pending' => 0,
- ];
- foreach ($products as $product) {
- try {
- $task_id = $product->pic_task_id;
- // 通过 pic_task_id 查询图片生成任务结果
- $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) : $task->result_url;
- // 更新资产表状态
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成成功',
- 'url' => $img_url,
- 'updated_at' => now()
- ]);
- $stats['success']++;
- 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['failed']++;
- dLog('anime')->warning('资产图片生成失败', [
- 'product_id' => $product->id,
- 'task_id' => $task_id,
- 'error' => $task->error_message ?? '未知错误'
- ]);
- } else {
- // 任务还在处理中
- $stats['pending']++;
- }
- } else {
- // 任务不存在,标记为失败
- DB::table('mp_products')
- ->where('id', $product->id)
- ->update([
- 'pic_task_status' => '生成失败',
- 'updated_at' => now()
- ]);
- $stats['failed']++;
- dLog('anime')->error('图片生成任务不存在', [
- 'product_id' => $product->id,
- 'task_id' => $task_id
- ]);
- }
- } catch (\Exception $e) {
- dLog('anime')->error('检查产品图片生成任务异常', [
- 'product_id' => $product->id,
- 'task_id' => $product->pic_task_id ?? null,
- 'error' => $e->getMessage()
- ]);
- }
- }
- return $stats;
- }
- /**
- * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
- *
- * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
- * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
- * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
- *
- * @return int 更新的任务中心记录数
- */
- public function checkSaveScriptProductTaskCenters() {
- $updated = 0;
- // 只扫描尚未结束的 saveScriptProducts 任务
- $tasks = DB::table('mp_task_center')
- ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
- ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
- ->orderBy('id', 'desc')
- ->limit(500)
- ->get();
- // 与 pollProductImageTasks 保持一致的类型名称映射
- $typeNames = [
- 1 => 'roles', // 角色
- 2 => 'scenes', // 场景
- 3 => 'props', // 道具
- ];
- foreach ($tasks as $task) {
- try {
- $taskParams = json_decode((string)$task->params, true);
- $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
- if (!$script_id) {
- dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
- 'task_center_id' => $task->id,
- ]);
- continue;
- }
- // 获取该剧本关联的全部资产ID
- $productIds = DB::table('mp_script_product_mappings')
- ->where('script_id', $script_id)
- ->pluck('product_id')
- ->unique()
- ->toArray();
- if (empty($productIds)) {
- // 剧本没有关联资产,不视为完成,等待下一次检查
- continue;
- }
- $products = DB::table('mp_products')
- ->whereIn('id', $productIds)
- ->where('is_deleted', 0)
- ->get();
- $stats = [];
- $allCompleted = true;
- foreach ($products as $product) {
- $typeName = $typeNames[$product->product] ?? 'unknown';
- if (!isset($stats[$typeName])) {
- $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
- }
- $stats[$typeName]['total']++;
- if ($product->pic_task_status === '生成成功') {
- $stats[$typeName]['success']++;
- $stats[$typeName]['completed']++;
- } elseif ($product->pic_task_status === '生成失败') {
- $stats[$typeName]['completed']++;
- } else {
- // 仍有资产在生成中或未生成,任务未完成
- $allCompleted = false;
- }
- }
- if (!$allCompleted) {
- continue;
- }
- // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
- $script = DB::table('mp_scripts')
- ->where('id', $script_id)
- ->where('is_deleted', 0)
- ->first();
- $script_name = $script->script_name ?? 'script_' . $script_id;
- $this->finishScriptProductTask($task->id, [
- 'type' => 'complete',
- 'script_id' => $script_id,
- 'script_name' => $script_name,
- 'stats' => $stats,
- 'timestamp' => date('Y-m-d H:i:s'),
- 'task_center_id' => (int)$task->id,
- ]);
- $updated++;
- dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
- 'task_center_id' => $task->id,
- 'script_id' => $script_id,
- 'stats' => $stats,
- ]);
- } catch (\Exception $e) {
- dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
- 'task_center_id' => $task->id,
- 'error' => $e->getMessage(),
- ]);
- }
- }
- return $updated;
- }
- /**
- * 获取剧本关联的资产列表
- * @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',
- 'product.timbre_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,
- 'timbre_url' => $item->timbre_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'],
- 'timbre_url' => $product['timbre_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
- 'url' => getProp($product, 'three_view_image_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');
- $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
- if (!in_array($model, $valid_models)) {
- Utils::throwError('20003:该模型不可用');
- }
- // 验证模型是否在可用模型表中
- 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';
- $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
- if (!$episode) {
- Utils::throwError('20003:分集不存在');
- }
- dLog('anime')->info('保存分集视频参数', $data);
- try {
- DB::beginTransaction();
- $result = 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')
- ]);
- if ($result === false) {
- Utils::throwError('20003:分集视频参数保存失败');
- }
- // 同步更新mp_animes表
- $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
- 'video_model' => $model,
- 'video_resolution' => $video_resolution,
- 'video_ratio' => $ratio,
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- if ($anime_result === false) {
- Utils::throwError('20003:动漫视频参数保存失败');
- }
- } catch (\Exception $e) {
- DB::rollBack();
- Utils::throwError('20003:'.$e->getMessage());
- }
- DB::commit();
- return $result;
-
- }
- 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) ?: [];
- $props = json_decode(getProp($episode, 'props'), true) ?: [];
- // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
- $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
- // 获取所有片段数据
- $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
-
- // 先构建完整的 products(角色、场景、道具、extra_products,并用资产库映射覆盖),
- // 再处理每个片段的 act_content,避免 extra_products 等资产名未被格式化为 {资产名}
- // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
- // extra_products优先级更高,会覆盖同名的roles、scenes和props
- $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便于后续覆盖
- }
-
- }
-
- // 处理道具数组(逻辑与场景一致)
- foreach ($props as $prop) {
- $product = $prop;
- // 将prop字段重命名为product_name
- if (isset($product['prop'])) {
- $product['product_name'] = $product['prop'];
- unset($product['prop']);
- $product['product'] = 3; // 标记类型为道具
- $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; // 覆盖同名数据
- }
- }
- // mp_script_product_mappings 信息优先级更高:
- // 获取当前剧集所属动漫剧本下、与本集资产同名的资产库最新数据(url/三视图/提示词等),
- // 覆盖分集 JSON 中保存的同名旧快照;分集内独有的 description、voice_prompt 等字段保留
- $anime = DB::table('mp_animes')->where('id', getProp($episode, 'anime_id'))->first();
- $script_id = $anime ? (int)getProp($anime, 'script_id', 0) : 0;
- if ($script_id && !empty($products)) {
- $currentProductNames = array_keys($products);
- $normalizeName = function($name) {
- return trim(preg_replace(
- '/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u',
- '',
- trim((string)$name)
- ));
- };
- $mappingItems = 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.is_deleted', 0)
- ->whereIn('product.product_name', $currentProductNames)
- ->select(
- 'mapping.product_id',
- 'product.product_name',
- 'product.product',
- 'product.pic_prompt',
- 'product.url',
- 'product.three_view_image_url',
- )
- ->get();
- $mappingByName = [];
- foreach ($mappingItems as $mappingItem) {
- $normalizedName = $normalizeName($mappingItem->product_name);
- if (!$normalizedName) continue;
- $mappingByName[$normalizedName] = [
- 'product_id' => (int)$mappingItem->product_id,
- 'product_name' => $mappingItem->product_name,
- 'product' => (int)$mappingItem->product,
- 'pic_prompt' => $mappingItem->pic_prompt ?? '',
- 'url' => $mappingItem->url ?? '',
- 'three_view_image_url' => $mappingItem->three_view_image_url ?? '',
- ];
- }
- foreach ($products as $key => &$product) {
- $normalizedKey = $normalizeName($key);
- if ($normalizedKey && isset($mappingByName[$normalizedKey])) {
- $product = array_merge($product, $mappingByName[$normalizedKey]);
- }
- }
- unset($product);
- }
- // 兼容返回 three_view_image_url 字段(旧数据可能没有该键,统一补空值)
- foreach ($products as &$product) {
- if (!isset($product['three_view_image_url'])) {
- $product['three_view_image_url'] = '';
- }
- }
- unset($product);
-
- // 重新索引数组(去除key)
- $products = array_values($products);
-
- // 基于构建完成的 products 收集所有资产名称(含 extra_products 中的资产)
- $product_names = [];
- foreach ($products as $product) {
- $product_name = getProp($product, 'product_name');
- if ($product_name && $product_name !== '旁白') {
- $product_names[] = $product_name;
- }
- }
-
- // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
- $product_names = array_unique($product_names);
- usort($product_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;
-
- // 统一替换所有资产名称为 {资产名} 格式
- // 使用占位符避免嵌套替换问题
- $placeholder_map = [];
- $placeholder_index = 0;
-
- foreach ($product_names as $product_name) {
- // 转义特殊字符
- $escaped_product = preg_quote($product_name, '/');
-
- // 检查是否匹配且未被 {} 包裹
- $processed_content = preg_replace_callback(
- '/(?<![{])(' . $escaped_product . ')(?![}])/u',
- function($matches) use (&$placeholder_map, &$placeholder_index) {
- // 使用唯一占位符
- $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
- $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
- $placeholder_index++;
- return $placeholder;
- },
- $processed_content
- );
- }
-
- // 将所有占位符替换回实际内容
- foreach ($placeholder_map as $placeholder => $replacement) {
- $processed_content = str_replace($placeholder, $replacement, $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();
- // 构建返回的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'),
- 'video_params' => [
- 'video_model' => getProp($episode, 'video_model'),
- 'video_resolution' => getProp($episode, 'video_resolution'),
- 'ratio' => getProp($episode, 'ratio'),
- ],
- 'products' => $products,
- 'acts' => $return_acts
- ];
- }
- /**
- * 参照 episodePicsInfo 的更新与监控逻辑:
- * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
- * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
- */
- private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
- $pollInterval = 5; // 每5秒查询一次
- $maxWaitSeconds = 60; // 最多持续1分钟
- $startTime = time();
- while (true) {
- // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
- $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) ?: [];
- $props = json_decode(getProp($episode, 'props'), true) ?: [];
- $updated = false;
- $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
- $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
- $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
- $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
- $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
- // 有图片任务结果更新时写回分集表
- if ($updated) {
- DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
- 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
- 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
- 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
- 'updated_at' => date('Y-m-d H:i:s')
- ]);
- }
- // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
- if (empty($waitingAssets) && empty($missingAssets)) {
- return;
- }
- // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
- if (empty($waitingAssets)) {
- Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
- }
- // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
- if (time() - $startTime >= $maxWaitSeconds) {
- Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
- }
- sleep($pollInterval);
- }
- }
- /**
- * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
- * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
- * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
- */
- private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
- foreach ($assets as &$asset) {
- $assetName = getProp($asset, $nameKey);
- if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
- continue;
- }
- // 已有图片URL的资产视为已生成
- if (getProp($asset, 'url')) {
- continue;
- }
- $task_id = getProp($asset, 'task_id');
- // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
- if (!$task_id) {
- $missingAssets[] = $assetName;
- continue;
- }
- $task = DB::table('mp_generate_pic_tasks')
- ->where('id', $task_id)
- ->select('status', 'result_url')
- ->first();
- // 任务不存在:同样记录为缺失项,不在此处直接报错
- if (!$task) {
- $missingAssets[] = $assetName;
- continue;
- }
- if ($task->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])) {
- $asset['url'] = $result_urls[0];
- $asset['task_status'] = 'success';
- $updated = true;
- continue;
- }
- }
- // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
- $waitingAssets[] = $assetName;
- } elseif ($task->status === 'failed') {
- // 生成失败:记录为缺失项,待其他任务处理完后统一报错
- $missingAssets[] = $assetName;
- } else {
- // 任务仍在生成中,等待下一次轮询
- $waitingAssets[] = $assetName;
- }
- }
- unset($asset);
- }
- /**
- * 导出动漫剧本为PDF(参照示例PDF版式)
- * @param int $animeId 动漫ID
- * @param int $episodeCount 导出集数,默认8,传-1表示全部
- * @param string|null $savePath 指定保存路径(为空则直接下载输出)
- * @return string|null
- */
- public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
- // 图片下载与转换可能占用较多内存
- ini_set('memory_limit', '512M');
- $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
- if (!$anime) Utils::throwError('20003:该动漫不存在!');
- $anime = (array)$anime;
- // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
- $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
- // 获取分集(默认展示版本,按集数升序)
- $episodeQuery = DB::table('mp_anime_episodes')
- ->where('anime_id', $animeId)
- ->where('is_default', 1)
- ->orderBy('episode_number')
- ->orderBy('id');
- if ($episodeCount > 0) {
- $episodeQuery->limit($episodeCount);
- }
- $episodes = $episodeQuery->get()->map(function ($value) {
- return (array)$value;
- })->toArray();
- if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
- // 聚合主体/场景/道具列表(前N集内容,按名称去重)
- $roles = $this->mergeEpisodeItems($episodes, 'role');
- $scenes = $this->mergeEpisodeItems($episodes, 'scene');
- $props = $this->mergeEpisodeItems($episodes, 'prop');
- // 组装分集剧本数据
- $episodeScripts = [];
- foreach ($episodes as $episode) {
- $segments = DB::table('mp_episode_segments')
- ->where('anime_id', $animeId)
- ->where('episode_id', $episode['id'])
- ->get();
- // 按act_number分组,同一片段多版本时取最新一条(id最大)
- $acts = [];
- foreach ($segments as $segment) {
- $segment = (array)$segment;
- $actNumber = (int)getProp($segment, 'act_number', 0);
- if ($actNumber <= 0) continue;
- if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
- $acts[$actNumber] = [
- 'id' => (int)$segment['id'],
- 'act_number' => $actNumber,
- 'duration' => getProp($segment, 'act_duration', ''),
- 'content' => getProp($segment, 'act_content', ''),
- ];
- }
- }
- ksort($acts);
- // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
- $segmentCounter = 0;
- foreach ($acts as &$act) {
- $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
- }
- unset($act);
- // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
- $narratorVoice = '';
- $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
- foreach ($episodeRoles as $role) {
- if (getProp($role, 'role') === '旁白') {
- $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
- break;
- }
- }
- if ($narratorVoice === '') {
- foreach ($acts as $act) {
- if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
- $narratorVoice = trim($match[1]);
- break;
- }
- }
- }
- $episodeScripts[] = [
- 'episode_number' => getProp($episode, 'episode_number'),
- 'title' => getProp($episode, 'title', ''),
- 'act_count' => count($acts),
- 'narrator_voice' => $narratorVoice,
- 'acts' => array_values($acts),
- ];
- }
- // 并发下载列表图片(主体/场景/道具),url => 临时文件
- $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
- // 构建PDF
- $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
- // 图片已嵌入PDF,清理临时文件
- foreach ($imageCache as $imgFile) {
- @unlink($imgFile);
- }
- $filename = $anime['anime_name'] . '_' . date('YmdHis');
- if ($savePath) {
- $pdf->Output($savePath, 'F');
- return $savePath;
- }
- // 直接下载输出
- header('Content-Type: application/pdf');
- header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
- $pdf->Output($filename . '.pdf', 'D');
- exit();
- }
- /**
- * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
- * @param array $episodes 分集数据
- * @param string $nameKey role|scene|prop
- * @return array
- */
- private function mergeEpisodeItems(array $episodes, $nameKey) {
- $fieldMap = [
- 'role' => 'roles',
- 'scene' => 'scenes',
- 'prop' => 'props',
- ];
- $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
- $items = [];
- foreach ($episodes as $episode) {
- $list = json_decode(getProp($episode, $field, ''), true) ?: [];
- foreach ($list as $item) {
- if (!is_array($item)) continue;
- $name = trim((string)getProp($item, $nameKey, ''));
- if ($name === '') continue;
- // 旁白不进入主体列表(仅作为旁白音色来源)
- if ($nameKey === 'role' && $name === '旁白') continue;
- if (!isset($items[$name])) {
- $items[$name] = $item;
- }
- }
- }
- return array_values($items);
- }
- /**
- * 构建动漫剧本PDF
- * @param array $anime 动漫信息
- * @param array $roles 主体列表
- * @param array $scenes 场景列表
- * @param array $props 道具列表
- * @param array $episodeScripts 分集剧本数据
- * @param array $imageCache 图片缓存(url => 临时文件路径)
- * @return \TCPDF
- */
- private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
- $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
- $pdf->SetCreator('动漫剧本导出系统');
- $pdf->SetAuthor('系统');
- $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
- $pdf->SetSubject('动漫剧本导出');
- $pdf->SetMargins(15, 15, 15);
- $pdf->SetAutoPageBreak(true, 15);
- // 剧本名
- $pdf->AddPage();
- $pdf->SetFont('simsun', 'B', 20);
- $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
- $pdf->Ln(5);
- // 故事梗概
- $intro = trim((string)getProp($anime, 'intro', ''));
- if ($intro !== '') {
- $this->pdfSectionTitle($pdf, '故事梗概');
- $this->pdfBody($pdf, $intro);
- }
- // 美术风格
- $artStyle = trim((string)getProp($anime, 'art_style', ''));
- if ($artStyle !== '') {
- $this->pdfSectionTitle($pdf, '美术风格');
- $this->pdfBody($pdf, $artStyle);
- }
- // 主体列表(文字+图片)
- $this->pdfSectionTitle($pdf, '主体列表');
- foreach ($roles as $index => $role) {
- $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
- }
- $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
- // 场景列表(文字+图片)
- $this->pdfSectionTitle($pdf, '场景列表');
- foreach ($scenes as $index => $scene) {
- $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
- }
- $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
- // 道具列表(文字+图片)
- $this->pdfSectionTitle($pdf, '道具列表');
- foreach ($props as $index => $prop) {
- $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
- }
- $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
- // 分镜剧本
- $this->pdfSectionTitle($pdf, '分镜剧本');
- foreach ($episodeScripts as $episodeScript) {
- $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
- $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
- if ($episodeTitleRaw !== '') {
- // title 字段可能已带"第N集"前缀,避免重复
- if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
- $episodeTitle = $episodeTitleRaw;
- } else {
- $episodeTitle .= ':' . $episodeTitleRaw;
- }
- }
- $this->pdfSubTitle($pdf, $episodeTitle, 13);
- $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
- if (getProp($episodeScript, 'narrator_voice') !== '') {
- $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
- }
- foreach (getProp($episodeScript, 'acts', []) as $act) {
- $actTitle = '片段' . getProp($act, 'act_number');
- if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
- $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
- }
- $this->pdfSubTitle($pdf, $actTitle, 12);
- if (getProp($act, 'content') !== '') {
- $this->pdfBody($pdf, getProp($act, 'content'));
- }
- }
- }
- return $pdf;
- }
- /**
- * PDF章节标题(带分隔线)
- */
- private function pdfSectionTitle($pdf, $title) {
- if ($pdf->GetY() > 230) {
- $pdf->AddPage();
- }
- $pdf->SetFont('simsun', 'B', 15);
- $pdf->Cell(0, 10, $title, 0, 1, 'L');
- $y = $pdf->GetY();
- $pdf->SetLineWidth(0.4);
- $pdf->Line(15, $y, 195, $y);
- $pdf->Ln(4);
- }
- /**
- * PDF子标题(集数/片段标题)
- */
- private function pdfSubTitle($pdf, $title, $size = 13) {
- if ($pdf->GetY() > 240) {
- $pdf->AddPage();
- }
- $pdf->SetFont('simsun', 'B', $size);
- $pdf->Cell(0, 8, $title, 0, 1, 'L');
- $pdf->Ln(1);
- }
- /**
- * PDF正文段落
- */
- private function pdfBody($pdf, $text) {
- $pdf->SetFont('simsun', '', 11);
- $pdf->MultiCell(0, 6, $text, 0, 'L');
- $pdf->Ln(2);
- }
- /**
- * 输出列表项图片(每张图单独一页,图下标注名称)
- * @param \TCPDF $pdf
- * @param array $items 列表项
- * @param string $nameKey role|scene|prop
- * @param array $imageCache 图片缓存(url => 临时文件路径)
- */
- private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
- foreach ($items as $item) {
- $url = trim((string)getProp($item, 'url', ''));
- $name = trim((string)getProp($item, $nameKey, ''));
- if ($url === '' || !isset($imageCache[$url])) continue;
- $imgPath = $imageCache[$url];
- $size = @getimagesize($imgPath);
- if (!$size || $size[0] <= 0 || $size[1] <= 0) {
- continue;
- }
- $pdf->AddPage();
- // 图片按比例缩放,居中偏上,为底部名称标注预留空间
- $maxW = 160;
- $maxH = 170;
- $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
- $drawW = $size[0] * $ratio;
- $drawH = $size[1] * $ratio;
- $x = (210 - $drawW) / 2;
- $y = max(15, (297 - $drawH) / 2 - 10);
- $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
- // 图下标注名称
- $pdf->SetFont('simsun', 'B', 13);
- $pdf->SetY(297 - 28);
- $pdf->Cell(0, 8, $name, 0, 1, 'C');
- }
- }
- /**
- * 并发下载远程图片到临时文件,并统一缩放转为JPEG
- * @param array $items 包含url字段的列表项
- * @return array url => 临时文件路径
- */
- private function downloadImagesConcurrently(array $items) {
- // 收集唯一的图片URL
- $urls = [];
- foreach ($items as $item) {
- $url = trim((string)getProp($item, 'url', ''));
- if ($url !== '') $urls[$url] = true;
- }
- if (!$urls) return [];
- $urls = array_keys($urls);
- $tmpDir = sys_get_temp_dir();
- $rawFiles = [];
- foreach ($urls as $url) {
- $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
- $rawFiles[$url] = $rawFile;
- }
- $client = new Client(['timeout' => 180, 'verify' => false]);
- // 低并发下载,sink写入文件避免大图占用内存
- $generator = (function () use ($urls, $client, $rawFiles) {
- foreach ($urls as $url) {
- yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
- }
- })();
- $errors = [];
- $each = new \GuzzleHttp\Promise\EachPromise($generator, [
- 'concurrency' => 4,
- 'rejected' => function ($reason, $url) use (&$errors) {
- $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
- },
- ]);
- $each->promise()->wait();
- // 失败的图片串行重试一次(独占带宽,提高成功率)
- foreach ($urls as $url) {
- if (!isset($errors[$url])) continue;
- try {
- $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
- unset($errors[$url]);
- } catch (\Throwable $e) {
- // 重试仍失败
- }
- }
- $cache = [];
- foreach ($urls as $url) {
- $rawFile = $rawFiles[$url];
- if (isset($errors[$url])) {
- dLog('anime')->error('导出PDF图片下载失败', [
- 'url' => $url,
- 'error' => $errors[$url],
- ]);
- @unlink($rawFile);
- continue;
- }
- $converted = $this->convertImageFile($rawFile, $url);
- if ($converted !== null) {
- $cache[$url] = $converted;
- } else {
- @unlink($rawFile);
- }
- }
- return $cache;
- }
- /**
- * 将已下载的图片文件缩放并转为JPEG
- * @param string $rawFile 原始图片临时文件
- * @param string $url 图片地址(用于命名)
- * @return string|null 转换后的文件路径,转换失败返回null
- */
- private function convertImageFile($rawFile, $url) {
- $content = @file_get_contents($rawFile);
- if ($content === false || $content === '') return null;
- if (!function_exists('imagecreatefromstring')) return null;
- $image = @imagecreatefromstring($content);
- if ($image === false) return null;
- $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
- imagedestroy($image);
- if ($jpeg !== null) {
- @unlink($rawFile);
- }
- return $jpeg;
- }
- /**
- * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
- * @param resource $srcImage GD图片资源
- * @param string $rawFile 原始图片临时文件
- * @param string $url 图片地址(用于命名)
- * @return string|null 压缩后的JPEG文件路径
- */
- private function compressImageForPdf($srcImage, $rawFile, $url) {
- $maxBytes = 2 * 1024 * 1024; // 2MB
- $sizes = [2048, 1600, 1280, 1024, 800];
- $qualities = [85, 70, 55, 40];
- $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
- foreach ($sizes as $size) {
- $resized = $this->copyAndResize($srcImage, $size);
- $flat = $this->flattenToWhite($resized);
- imagedestroy($resized);
- foreach ($qualities as $quality) {
- ob_start();
- $saved = imagejpeg($flat, null, $quality);
- $data = ob_get_clean();
- if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
- file_put_contents($jpeg, $data);
- imagedestroy($flat);
- dLog('anime')->info('导出PDF图片压缩完成', [
- 'url' => $url,
- 'size' => filesize($jpeg),
- 'edge' => $size,
- 'quality' => $quality,
- ]);
- return $jpeg;
- }
- }
- imagedestroy($flat);
- }
- // 兜底:最小尺寸、最低质量强制输出
- $resized = $this->copyAndResize($srcImage, 800);
- $flat = $this->flattenToWhite($resized);
- imagedestroy($resized);
- $saved = imagejpeg($flat, $jpeg, 30);
- imagedestroy($flat);
- if (!$saved) return null;
- dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
- 'url' => $url,
- 'size' => filesize($jpeg),
- ]);
- return $jpeg;
- }
- /**
- * 等比缩放图片副本(不销毁原图)
- * @param resource $srcImage GD图片资源
- * @param int $maxEdge 最大边长
- * @return resource
- */
- private function copyAndResize($srcImage, $maxEdge) {
- $width = imagesx($srcImage);
- $height = imagesy($srcImage);
- $max = max($width, $height);
- if ($max <= $maxEdge) {
- $copy = imagecreatetruecolor($width, $height);
- imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
- return $copy;
- }
- $ratio = $maxEdge / $max;
- $newWidth = max(1, (int)round($width * $ratio));
- $newHeight = max(1, (int)round($height * $ratio));
- $resized = imagecreatetruecolor($newWidth, $newHeight);
- imagealphablending($resized, false);
- imagesavealpha($resized, true);
- imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
- return $resized;
- }
- /**
- * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
- * @param resource $image GD图片资源
- * @return resource
- */
- private function flattenToWhite($image) {
- $width = imagesx($image);
- $height = imagesy($image);
- $flat = imagecreatetruecolor($width, $height);
- $white = imagecolorallocate($flat, 255, 255, 255);
- imagefill($flat, 0, 0, $white);
- imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
- return $flat;
- }
- /**
- * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
- * @param string $content 片段内容
- * @param int $counter 当前已编号数量(引用传递,整集累计)
- * @return string
- */
- private function renumberSegmentBlocks($content, &$counter) {
- return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
- $counter++;
- return '【' . $match[1] . $counter . '】';
- }, $content);
- }
- }
|